Pic Final Book
-
Upload
santhosh-kumar -
Category
Documents
-
view
182 -
download
0
description
Transcript of Pic Final Book
PIC MICROCONTROLLER
Pic 16f877a micro controller
Chapter no
Description Page no
1 Micro controller1.1 micro controller introduction1.2 difference between micro controller and micro processor
2 Pic micro controller2.1 features2.2 pic family2.3 how to select a pic micro controller2.4 pin diagram2.5 architecture2.6 memory oraganisation
3 i/o ports3.1 programming with i/o ports3.2 sample programs
4 Interfacing 7 segment display with pic4.1 fundamentals4.2 pin configurations4.3 interfacing with mcu4.4 sample programs
5 Interfacing lcd with pic5.1 operation5.2 functions of the control lines5.3 schematic for interfacing lcd module5.4 initialization for the lcd module5.5 sample programs
6 Timers6.1 timer06.2 timer0 calculation6.3 timer16.4 timer1 calculation6.5 timer26.6 timer2 calculation6.7 sample programs
1
PIC MICROCONTROLLER
7 Ccp7.1 capture mode7.2 compare mode7.3 pwm mode7.4 model calculation7.5 sample programs
8 Analog to digital converter(ADC)8.1 operation8.2 adcon0 register8.3 adcon1 register8.4 a/d result registers8.5 adc with lcd8.6 adc with 7-seg08.7 adc with usart
9 communications9.1 introduction9.2 enabling serial communication9.3 usart transmit block diagram9.4 usart transmit and control register9.5usart receive block diagram9.6 usart receive and control register9.7 sample programs
10 interrupts10.1 intcon register10.2 pie register10.3 pir register
11 Mater synchronous serial port(MSSP)11.1 serial peripheral interface(spi)11.2 inter integrated circouis(i2c)
12 Additional topics12.1 Watch dog timers(WDT)12.2 Power up reset(POR)12.3 brown out reset(BOR)12.4 RS-232 serial communication
13 Interfacing external peripherals
2
PIC MICROCONTROLLER
13.1 using 4*4 keypad13.2 using lm35 sensor13.3 interfacing dc motor(or) stepper motor13.4 interfacing gsm modem
1. MICROCONTROLLER
HISTORY: The PIC microcontroller was developed by General Instruments in 1975. PIC was developed when Microelectronics Division of General Instruments was testing its 16-bit CPU CP1600. Although the CP1600 was a good CPU but it had low I/O performance. The PIC controller was used to offload the I/O the tasks from CPU to improve the overall performance of the system. In 1985, General Instruments converted their Microelectronics Division to Microchip Technology. PIC stands for Peripheral Interface Controller. The General Instruments used the acronyms Programmable Interface Controller and Programmable Intelligent Computer for the initial PICs (PIC1640 and PIC1650). In 1993, Microchip Technology launched the 8-bit PIC16C84 with EEPROM which could be programmed using serial programming method. The improved version of PIC16C84 with flash memory (PIC18F84 and PIC18F84A) hit the market in 1998.
1.2 DIFFERENCE BETWEEN MICROCONTROLLER AND MICROPROCESSOR
MICROPROCESSOR MICROCONTROLLERMicroprocessor contains ALU,control unit, Microcontroller contains microprocessor,different register and interrupt circuit. memory(RAM,ROM),I/O interfacing circuit
and peripheral devices such as A/Dconverter, serial I/O, timer etc.
It has many instructions to move data It has one or two instructions to move databetween memory and CPU between memory and CPU.It has one or two bit handling instructions It has many bit handling instructions
3
PIC MICROCONTROLLER
Access times for memory and I/O devices Less access times for built in memory andare more. I/O devices.Microprocessor based system requires more Microcontroller based system requires lesshardware. hardware reducing PCB size and increasing
the flexibilityIt has single memory map for data and code. It has separate memory map for data and
code.Less number of pins are multifunctioned More number of pins are multifunctioned
4
PIC MICROCONTROLLER
2. PIC MICROCONTROLLER
PIC is abbreviated as Peripheral Interface Controller. Microcontroller PIC16F877A is one of the PIC Micro Family microcontroller which is popular at this moment, start from beginner until all professionals. Because very easy using PIC16F877A and use FLASH memory technology so that can be write-erase until thousand times. The superiority this Risc Microcontroller compared to with other microcontroller 8-bit especially at a speed of and his code compression. PIC16F877A have 40 pin by 33 path of I/O. PIC16F877A perfectly fits many uses, from automotive industries and controlling home appliances to industrial instruments, remote sensors, electrical door locks and safety devices. It is also ideal for smart cards as well as for battery supplied devices because of its low consumption.EEPROM memory makes it easier to apply microcontrollers to devices where permanent storage of various parameters is needed (codes for transmitters, motor speed, receiver frequencies, etc.). Low cost, low consumption, easy handling and flexibility make PIC16F877A applicable even in areas where microcontrollers had not previously been considered (example: timer functions, interface replacement in larger systems, coprocessor applications, etc.).In System Programmability of this chip (along with using only two pins in data transfer) makes possible the flexibility of a product, after assembling and testing have been completed. This capability can be used to create assembly-line production, to store calibration data available only after final testing, or it can be used to improve programs on finished products.
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 other 28-pin or 40/44-pin PIC16CXXX and
5
PIC MICROCONTROLLER
PIC16FXXX microcontrollers.
PERIPHERAL FEATURES:
Timer0: 8-bit timer/counter with 8-bit prescalar
Timer1: 16-bit timer/counter with prescalar,can be incremented during Sleep via external crystal/clock
Timer2: 8-bit timer/counter with 8-bit period register, prescalar and post scaler
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
Synchronous Serial Port (SSP) with SPI(Master mode) and I2C (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).
ANALOG FEATURES:
10-bit, up to 8-channel Analog-to-Digital
Converter (A/D)
Brown-out Reset (BOR)
Analog Comparator module with:
6
PIC MICROCONTROLLER
Two analog comparators
Programmable on-chip voltage reference
(VREF) module
Programmable input multiplexing from device
inputs and internal voltage reference
Comparator outputs are externally accessible
CHARACTERISTICS OF THE RISC (REDUCED INSTRUCTION SET CONTROL) SYSTEM:
Instruction set of 35 commands Instructions are carried out in 2 clock cycles
You can calculate the execution time of the command in accordance with the frequency clock (if the frequency clock is 20Mhz, execution time of a command is 200ns)
The ports of 28/40/44 pins microcontrollers are the same
PIC FAMILY:
PIC Microcontrollers MCU from Microchip Company divided into 4 large families. Each family has a variety of components that provide built-in special features
7
PIC MICROCONTROLLER
The first family, PIC10 (10FXXX) - is called Low End.
The PIC10FXXX devices from Microchip Technology are low-cost, high-performance, 8-bit, fully static, Flash-based CMOS microcontrollers. They employ RISC architecture with only 33 single-word/ single-cycle instructions. The 12-bit wide instructions are highly symmetrical. The easy-to-use and easy to remember instruction set reduces development time significantly. The PIC10FXXX devices contain an 8-bit ALU and working register.
The second family, PIC12 (PIC12FXXX) – is called Mid-Range.
The PIC12FXXX most popular among this starter their way in this field. Mid-Range devices feature 14-bit program word architecture and are available in 8 to 64-pin packages that offer an operating voltage range of 1.8-5.5V, small package footprints, interrupt handling, an 8-level hardware stack, multiple A/D channels and EEPROM data memory. Mid-range devices offer a wide range of package options and a wide range of peripheral integration. These devices feature various serial analog and digital peripherals, such as: SPI, I2C™, USART, LCD and A/D converters.
The third family is PIC16 (16FXXX).
With six variants ranging from 3.5K-14 Kbytes of Flash memory, up to 256 bytes of RAM and a mix of peripherals including EUSART, CCP and onboard and comparators. These devices are well suited for designers with applications that need more code space or I/O than 14-pin variants supply, and are looking to increase system performance and code efficiency by employing hardware motor control and communications capability.
The fourth family is PIC 17/18(18FXXX).
The PIC18 family utilizes 16-bit program word architecture and incorporates an advanced RISC architecture with 32 level-deep stack, 8x8 hardware multiplier, and multiple internal and external interrupts. With the highest performance in Microchip‟s 8-bit portfolio, the PIC18 family provides up to 16 MIPS and linear memory. PIC18 is the most popular architecture for new 8-bit designs where customers want to program in C language.
8
PIC MICROCONTROLLER
PIN DIAGRAM FOR PIC MICRCONTROLLER:
9
PIC MICROCONTROLLER
10
PIC MICROCONTROLLER
MEMORY ORGANIZATION
Memory of the PIC16F877 divided into 3 types of memories:
Program Memory - A memory that contains the program (which we had written), after we've burned it. As a reminder, Program Counter executes commands stored in the program memory, one after the other.
Data Memory – This is RAM memory type, which contains a special registers like SFR (Special Faction Register) and GPR (General Purpose Register). The variables that we store in the Data Memory during the program are deleted after we turn off the micro.
These two memories have separated data buses, which makes the access to each one of them very easy.
Data EEPROM (Electrically Erasable Programmable Read-Only Memory) - A memory that allows storing the variables as a result of burning the written program.
Each one of them has a different role. Program Memory and Data Memory two memories that are needed to build a program, and Data EEPROM is used to save data after the microcontroller is turn off.
Program Memory and Data EEPROM they are non-volatile memories, which store the information even after the power is turn off. These memories called flash or EEPROM. In contrast, Data Memory does not save the information because it needs power in order to maintain the information stored in the chip. PIC16F87XA Program Memory
2.6.1 PIC16F87XA PROGRAM MEMORY
The PIC16F87XA devices have a 13-bit program counter capable of addressing an 8K word x 14 bit program memory space. This memory is used to store the program after we burn it to the microcontroller. The PIC16F876A/877A devices have 8K words x 14 bits of Flash program memory that can be electrically erased and reprogrammed. Each time we burn program into the micro, we erase an old program and write a new one.
Program Counter (PC) keeps track of the program execution by holding the address of the current instruction. It is automatically incremented to the next
11
PIC MICROCONTROLLER
instruction during the current instruction execution.
The PIC16F87XA family has an 8-level deep x 13-bit wide hardware stack. The stack space is not part of either program or data space and the stack pointer are not readable or writable. In the PIC microcontrollers, this is a special block of RAM memory used only for this purpose.The CALL instruction is used to jump to a subroutine, which must be terminated with the RETURN instruction. CALL has the address of the first instruction in the subroutine as its operand. When the CALL instruction is executed, the destination address is copied to the PC. The PC is PUSHed onto the stack when a CALL instruction is executed, or an interrupt causes a branch. The stack is POPed in the event of a RETURN, RETLW or a
RETFIE instruction execution.
The stack operates as a circular buffer. This means that after the stack has been PUSH‟ed eight times, the ninth push overwrites the value that was stored from the first push. The tenth push overwrites the second push (and so on).
2.6.2 PIC16F877A DATA MEMORY
The data memory is partitioned into multiple banks which contain the General purpose registers and special function registers. Number of banks may vary depending on the microcontroller; for example, micro PIC16F84 has only two banks.
Each bank extends up to 7Fh (128 bytes). The lower locations of each bank are reserved for the Special Function Registers. Above the Special Function Registers are General Purpose Registers, implemented as static RAM. While program is being executed, it is working with the particular bank. The default bank is BANK0.
To access a register that is located in another bank, one should access it inside the program. There are special registers which can be accessed from any bank, such as STATUS register.
12
PIC MICROCONTROLLER
13
PIC MICROCONTROLLER
14
PIC MICROCONTROLLER
3. I/O PORTS
In pic microcontroller totally contains 40 pins among that only 33 pins are used for used for I/O purpose and remaining pins are used for the special purpose.These 33 pins are divided into 5 different PORTS as follows.
PORTA – 6 pins.
PORTB – 8 pins.
PORTC – 8 pins.
PORTD – 8 pins.
PORTE – 3 pins.
These pins are bidirectional (i.e. Input and Output).User have to decide the particular purpose of the pins.
Configuring PORTS:For port configuration two registers are used. They are listed below.
TRIS Register.
PORT Register.
Each PORT is having their individual TRIS &PORT registers. For example configuring the PORTA is given below.
PORTA AND THE TRISA REGISTER:
PORTA is a 6-bit wide, bidirectional port. The corresponding data direction register is TRISA. Setting a TRISA bit (= 1) will make the corresponding PORTA pin an input (i.e.,
15
PIC MICROCONTROLLER
put the corresponding output driver in a High-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).
Similarly all ports are configured.
PROGRAMS FOR CONFIGURING THE PORTS
#PROGRAM 1:-LED GLOW #include<pic.h> void main()
{ TRISB=0X00; PORTB=0XFF;
}
#PROGRAM 2:-BLINKING LED #include<pic.h> delay(){ for(int i=0;i<255;i++) for(int j=0;j<355;j++);
}void main()
{ TRISB=0X00; PORTB=0X00;
while(1)
{ PORTB=0XFF; delay(); PORTB=0X00; delay();
} }
#PROGRAM 3:-RUNNING LED#include<pic.h>
16
PIC MICROCONTROLLER
delay()
{ int m,n; for(m=0;m<50;m++){for(n=0;n<200;n++);
} }void main()
{ TRISB=0x00; PORTB=0x00; int k=0x01; while(1)
{ PORTB=k; k=(k<<1); delay();
if(k>0x80){k=0x01;} } }
#PROGRAM 4:-LED USING SWITCH#include<pic.h>void main()
{ TRISD=0xFF; PORTD=0x00; TRISB=0x00; PORTB=0xFF; if(RD0==1)
RB0=0;else
RB0=1; if(RD1==1)
RB1=0;else
RB1=1; if(RD2==1)
RB2=0;
17
PIC MICROCONTROLLER
else
RB2=1; if(RD3==1)
RB3=0;else
RB3=1;}#PROGRAM:5-ODD LED#include<pic.h>delay(){
for(int i=0;i<30000;i++);}void main(){
TRISB=0X00;PORTB=0X00;while(1){
PORTB=0X01;delay();PORTB=0X04;delay();PORTB=0X10;delay();PORTB=0X40;delay();}}
18
PIC MICROCONTROLLER
3.7-SEGMENT DISPLAYSeven segment displays are very common for electronic product to display numerical output. Many common devices like calculators, watches, electronic weighing scales,ovens etc use them. You must have also seen lifts display the current floor numbers in seven segment displays. So in this article will show you how to use 7-Segment displays in your own projects. Fundamentals A seven-segment display is so named because it is divided into seven different segments that can be switched on or off. The different combination of these segments switched on produces different English numbers. The display also has a decimal point.
The figure shows a seven segment display and the names of the various segments. For example if you want to display number 4 then segments that will be „on‟ are {f,g,b,c} while rest are „off‟.Basically the seven segments are just LEDs. The one common end of all the leds are connected while the rest are available. Depending on whether anode or cathode of all the leds are common they are of two types. Common anode Common cathode
value h g f e d c b a Hex value0 0 0 1 1 1 1 1 1 0x3f1 0 0 0 0 0 1 1 0 0x062 0 1 0 1 1 0 1 1 0x5b3 0 1 0 0 1 1 1 1 0x4f4 0 1 1 0 0 1 1 0 0x665 0 1 1 0 1 1 0 1 0x6d6 0 1 1 1 1 1 0 1 0x7d7 0 0 0 0 0 1 1 1 0x078 0 1 1 1 1 1 1 1 0x7f9 0 1 1 0 1 1 1 1 0x6f
19
PIC MICROCONTROLLER
PROGRAM:1
7-SEGMENT DISPLAY
#include<pic.h>
delay()
{
for(int i=0;i<3;i++)
for(int j=0;j<30;j++);
}
void main()
{
TRISC=0x00;
TRISB=0x00;
PORTC=0x00;
PORTB=0x00;
while(1)
{
PORTC=0x01;
PORTB=0x66;
delay();
PORTC=0x02;
PORTB=0x7d;
delay();
PORTC=0x04;
PORTB=0x6d;
delay();
PORTC=0x08;
PORTB=0x66;
delay();
}}
20
PIC MICROCONTROLLER
PROGRAM:2
COUNTER DOWN
#include<pic.h>
delay()
{
int i,j;
for(i=0;i<10;i++)
for(j=0;j<10;j++);
}
main()
{
int D,D1,D2,D3,D4;
TRISB=0x00;
TRISC=0x00;
PORTB=0;
PORTC=0;
char arr[10]={0x3F,0x06,0x5B,0x4F,0x66,0x6D,0x7D,0x07,0x7F,0x67};
while(1)
{
for(int i=9999;i>=0;i--)
{
D1=i/1000;
D=i%1000;
D2=D/100;
D=D%100;
D3=D/10;
D4=D%10;
for(int f=0;f<=5000;f++);
PORTC=0x01;
21
PIC MICROCONTROLLER
PORTB=arr[D1];
delay();
PORTC=0x02;
PORTB=arr[D2];
delay();
PORTC=0x04;
PORTB=arr[D3];
delay();
PORTC=0x08;
PORTB=arr[D4];
delay();
}
}
}
PROGRAM:3
COUNTER UP
#include<pic.h>
delay()
{
int i,j;
for(i=0;i<10;i++)
for(j=0;j<10;j++);
}
main()
{
int D,D1,D2,D3,D4,e;
TRISB=0x00;
TRISC=0x00;
PORTB=0;
22
PIC MICROCONTROLLER
PORTC=0;
char arr[10]={0x3F,0x06,0x5B,0x4F,0x66,0x6D,0x7D,0x07,0x7F,0x67};
while(1)
{
for(int i=0;i<10000;i++)
{
D1=i/1000;
D=i%1000;
D2=D/100;
D=D%100;
D3=D/10;
D4=D%10;
for(e=0;e<50;e++){
PORTC=0x08;
PORTB=arr[D1];
delay();
PORTC=0x04;
PORTB=arr[D2];
delay();
PORTC=0x02;
PORTB=arr[D3];
delay();
PORTC=0x01;
PORTB=arr[D4];
delay();
}
}
}
23
PIC MICROCONTROLLER
}
PROGRAM:4
CHANGING THE SEGMENT POSITION
#include<pic.h>void main(){
TRISC=0x00;PORTC=0x00;TRISB=0x00;PORTB=0x00;
char a,b,c,d,temp;a=0x06;b=0x5B;c=0x4F;d=0x66;while(1){
PORTC=0x01;PORTB=a;
delay();PORTC=0X02;PORTB=b;delay();PORTC=0x04;PORTB=c;delay();PORTC=0x08;PORTB=d;delay();temp=d;d=c;c=b;b=a;a=temp;delay();}}delay(){for(int i=1;i<30000;i++);}
24
PIC MICROCONTROLLER
INTERFACING LCD WITH PIC
OPERATION:
Here the Lcd used is HD44780 type LCD.In general the HD44780 type LCD module can operates in 2 modes which are the 4-bit data interface mode and 8-bit data interface mode. When operating in 4-bit mode, 2 transfers per character per command are required whereas is it easier to implement in 8-bit mode which requires less program memory but as tradeoff it requires 4 more additional I/O ports. Most common data interface from microcontroller are:
1. Full 8-bit interface
2. 4-bit interface using high nibble of the port
3. 4-bit interface using low nibble of the port.
In this application note, only the 8-bit interface mode will be described which means that 8-bit data bus will be used to connect the microcontroller to the LCD module. Apart from the 8-bit data bus, the LCD also requires 3 more pins of control lines which are the EN (enable) pin, RS (register select) pin and the R/W (read/write mode) pin to interface with the microcontroller (in this application note, the Microchip PIC16F877A will be used).
25
PIC MICROCONTROLLER
FUNCTIONS OF THE CONTROL LINES
The 8 data bus or data lines are referred as DB0 to DB7. As stated earlier the 3 control lines are referred as EN, RS and R/W.
EN is the enable line. It used to send pulses to the LCD module which indicates the start of a transmission data or byte to the LCD module. To indicate the start of transmission, this EN bit is set high and when the transmission is done, this EN bit is set back to low.
RS is the register select line which determines whether the data byte sent to the LCD controller is a command or text data to be display on the LCD screen. When sending command, this RS bit is set low whereas when text data are to be sent, this RS bit is set to high.
Finally the third control line is the R/W line which is the read or write control line. When this line is low, the data on the data bus is written to the LCD module while when this line is high, the LCD can read to check its own status.
26
PIC MICROCONTROLLER
Control line FunctionEN 1-enable 0-disableRS 0-command mode 1-data modeR/W 0-read data 1-write data
Flow Chart for Initialization of LCD Module:
27
PIC MICROCONTROLLER
INSTRUCTION CODE DESCRIPTIONClear display 0000 0001 Clear display and reset addressHome cursor 0000 001x Reset display location addressEntry mode 0000 01MS Set cursor move and display shiftDisplay control 0000 1DCB Display&cursor enableShift control 0001 PRxx Moves cursor and shifts displayFunction control 001L NFxx Data mode,line number,fontCGRAM address 01gg ggggg Send character generator ram addressDDRAM address 1ddd dddd Send display data ram address
x-don’t careM-cursor move direction 1=right 0=leftS=enable whole display shift =1D=whole display on =1C=cursor on=1 B=blinking cursor on=1P=display shift =1,cursor move=0R=shift right =1,shift left=0L=8 bits=1,4-bits=0N=2 lines=1,1 line=0 F=5*10 character=1,5*8=0 g=character generator RAM address bit d=data ram address bit
0x80 81 82 83 84 85 86 87 88 89 8a 8b 8c 8d 8e 0x8f
0xc0 c1 c2 c3 c4 c5 c6 c7 c8 c9 ca cb cc cd ce 0xcf
28
PIC MICROCONTROLLER
#PROGRAM FOR INTERFACING LCD WITH PIC:
#include<pic.h>char cmd[6]={0x01,0x0D,0x07,0x38,0x8f}; char cmd1[6]={0x01,0x0D,0x07,0x38,0xcf}; char data[8]={"ADVETECH"};char data1in[10]={"COIMBATORE"};
void main(){
portconfig(); while(1){
command(); datain(); command1(); data1();}}
delay(){
int a,b; for(a=0;a<200;a++) for(b=0;b<100;b++);}
portconfig(){
TRISB=0;TRISE=0;PORTB=0;PORTE=0;
}
command(){
for (int i=0;i<6;i++){
PORTE=0x04;PORTB=cmd[i]; delay();RE2=0;
}}
datain(){
for(int i=0;i<8;i++){
PORTE=0x05;PORTB=data[i]; delay();RE2=0;
29
PIC MICROCONTROLLER
}}
command1(){for(int m=0;m<6;m++){PORTE=0X04; PORTB=cmd1[m]; delay();RE2=0;}}
data1(){for(int n=0;n<10;n++){PORTE=0X05; PORTB=data1in[n]; delay();RE2=0;}
PROGRAM:2#include<pic.h>char command[6]={0x01,0x0d,0x07,0x38,0x80};char data[10]={"ADVETECH"};void main(){
TRISE=0X00;PORTE=0X00;TRISB=0X00;PORTB=0X00;while(1){
cmd();dat();}}cmd(){
for(int i=0;i<6;i++){
PORTE=0X04;PORTB=command[i];delay();RE2=0;}}
dat(){
for(int i=0;i<10;i++){
PORTE=0X05;PORTB=data[i];delay();PORTE=0X00;}}
delay()30
PIC MICROCONTROLLER
{for(int i=0;i<30000;i++);
}
TIMERS
Timers are used to count internal data, where counters are used to count external data.
Timers
TIMER0 TIMER 1 TIMER2
TIMER0:
Timer0 is an 8-bit timer/counter with the following features:
8-bit timer/counter;
8-bit prescaler (shared with Watchdog timer);
Programmable internal or external clock source;
Interrupt on overflow; and
Programmable external clock edge selection.
In order to use Timer0 properly, it is necessary:
Step 1: To select mode:
Timer mode is selected by the T0CS bit of the OPTION_REG register, (T0CS:
0=timer, 1=counter).
When used, the prescaler should be assigned to the timer/counter by clearing the
PSA bit of the OPTION_REG register. The prescaler rate is set by using the PS2-
PS0 bits of the same register.
When an interrupt is used, the GIE and TMR0IE bits of the INTCON register
should be set.
Step 2: To measure and count
Time measurement:
Reset the TMR0 register or write some known value to it.
Elapsed time (in microseconds if 4MHz quartz crystal is used) is measured by
reading the TMR0 register.
31
PIC MICROCONTROLLER
The flag bit TMR0IF of the INTCON register is automatically set every time the
TMR0 register overflows. If enabled, an interrupt occurs.
Counting:
The polarity of pulses to be counted on the RA4 pin is selected by the TOSE bit
of the OPTION_REG register (T0SE: 0=positive, 1=negative pulses).
Number of pulses may be read from the TMR0 register. The prescaler and
interrupt are used in the same manner as in the timer mode.
Block diagram of TIMER0
32
PIC MICROCONTROLLER
This entire operation of the TIMER0 is controlled by the register called OPTION register. The structure of the register is given below.OPTION REGISTER:
RBPU - PORTB Pull-up enable bito 0 - PORTB pull-up resistors disabled.o 1 - PORTB pins can be connected to pull-up resistors.
INTEDG - Interrupt Edge Select bito 0 - Interrupt on rising edge of the INT pin (0-1).o 1 - Interrupt on falling edge of the INT pin (1-0).
T0CS - TMR0 Clock Select bito 0 - Pulses are brought to the Timer0/counter input through the RA4 pin.o 1 - Timer0 uses internal cycle clock (Fosc/4).
T0SE - TMR0 Source Edge Select bito 0 - Increment on high-to-low transition on the TMR0 pin.o 1 - Increment on low-to-high transition on the TMR0 pin.
PSA - Prescaler Assignment bito 0 - Prescaler is assigned to the WDT.o 1 - Prescaler is assigned to the Timer0/counter.
PS2, PS1, PS0 - Prescaler Rate Select bit Prescaler rate is set by combining these bits. As seen in the table, the same
combination of bits gives different prescaler rate for the Timer0/counter and watch-dog timer, respectively.
PS2 PS1 PS0 TIMER0 WDT
0 0 0 1:2 1:1
0 0 1 1:4 1:2
0 1 0 1:8 1:4
0 1 1 1:16 1:8
1 0 0 1:32 1:16
1 0 1 1:64 1:32
1 1 0 1:128 1:64
1 1 1 1:256 1:128
33
PIC MICROCONTROLLER
This OPTION register is for configuring the timer. The time needed for the particular application should be defined by the user for defining the time the following formula is used.
Fout= fclk ------------------------------------------------------ (4*prescalar*(256-TMR0)*count)
Where Tout=1/fout
MODEL CALCULATION:
If we want 0.5 sec delay in our program the following calculation is to be performed to attain the desired 0.5 secs.Solution:Tout=1/fout=1/0.5=2Hz(needed frequency)Fclk=4MHzCount=4MHz/(4*256*(256-0)*2)=7.629=8Count=8
TIMER1
Timer1 module is a 16-bit timer/counter, which means that it consists of two registers
(TMR1L and TMR1H). It is capable of counting up to 65.535 pulses in a single cycle, i.e.
before the counting starts from zero.
Similar to Timer0, these registers can be read or written to at any point. In case an
overflow occurs, an interrupt is automatically generated, provided it is enabled.
The Timer1 may be set to operate in one of two modes, either as a timer or a counter.
Unlike the Timer0, both of these modes give additional possibilitis.
The Timer1 has the following features:
16-bit timer/counter register pair;
Programmable internal or external clock source;
34
PIC MICROCONTROLLER
3-bit prescaler;
Optional Low Power (LP) oscillator;
Synchronous or asynchronous operation;
Timer1 gate control (count enabled) via comparator or the T1G pin;
Interrupt on overflow;
Wake-up on overflow (external clock); and
Clock source for Capture/Compare module.
T1CON Register
Bits of the T1CON register are in control of the Timer1 operation.
T1GINV - Timer1 Gate Invert bit acts as a logic state inverter on the T1G pin gate or the
comparator C2 output (C2OUT) gate. It enables the timer to count pulses while the gate
is high or low.
1 - Timer 1 counts when the T1G pin or bit C2OUT gate is high (1).
35
PIC MICROCONTROLLER
0 - Timer 1 counts when the T1G pin or bit C2OUT gate is low (0).
TMR1GE - Timer1 Gate Enable bit determines whether the T1G pin or the com parator
C2 output (C2OUT) gate will be active or not. This bit is enabled only when the Timer1
is on (bit TMR1ON = 1). Otherwise, it is ignored.
1 - Timer1 is enabled only when the Timer1 gate is not active.
0 - Gate doesn’t affect the operation of Timer1.
T1CKPS1, T1CKPS0 - determine the rate of the prescaler assigned to the Timer1.
T1CKPS1 T1CKPS0 PRESCALAR RATE
0 0 1:1
0 1 1:2
1 0 1:4
1 1 1:8
T1OSCEN - LP Oscillator Enable Control bit
1 - LP oscillator is enabled for the Timer1 clock (a low-power oscillator with a
frequency of 32.768 kHz).
0 - LP oscillator is disabled.
T1SYNC - Timer1 External Clock Input Synchronization Control bit enables the LP
oscillator input or the T1CKI pin input to be synchronized with the micro controller
internal clock. The bit is ignored as long as pulses supplied from the microcontroller
clock source are counted (bit TMR1CS = 0).
1 - External clock input will not be synchronized..
0 - External clock input will be synchronized..
TMR1CS - Timer TMR1 Clock Source Select bit
1 - Count pulses on the T1CKI pin (on the rising edge 0-1).
0 - Count pulses generated by the microcontroller clock.
TMR1ON - Timer1 On bit
1 - Timer1 enabled.
0 - Timer1 disabled.
In Short
In order to use the Timer1 properly, it is necessary to do the following:
36
PIC MICROCONTROLLER
Since it is not possible to turn off the prescaler, its rate should be adjusted by
using bits T1CKPS1 and T1CKPS0 of the register T1CON (Refer to the previous
table).
Select the appropriate mode using the TMR1CS bit of the register T1CON.
(TMR1CS: 0=the clock source is internal quartz oscillator, 1= the clock is
supplied externally).
By setting the T1OSCEN bit of the same register, the oscillator is enabled and the
TMR1H and TMR1L registers are incremented on every clock pulse. Counting
stops by clearing this bit.
The prescaler is cleared by clearing or writing to the counter registers.
When both timer registers are filled with ones, an overflow occures, the TMR1IF
flag is set and counting starts from zero.
Fout = fclk ------------------------------------------------------ (4*prescalar*(65536-TMR1)*count)
Where Tout=1/fout
MODEL CALCULATION:
If we want 1 sec delay in our program the following calculation is to be performed to attain the desired 1 secs.Solution:
Tout=1/fout=1/1=1Hz(needed frequency)Fclk=4MHzCount=4MHz/(4*8*(65536-0)*1)=1.98Count=2
37
PIC MICROCONTROLLER
TIMER2
When using the Timer2, keep in mind the following details related to its registers:
At the moment of power on, the PR2 register contains the value FFh.
Both prescaler and postscaler are cleared by writing to the TMR2 register.
Both prescaler and postscaler are cleared by writing to the T2CON register.
On any reset - you guess, both prescaler and postscaler are cleared.
Pulses generated by the quartz oscillator first pass through the prescaler the rate of which
may be changed using the T2CKPS1 and T2CKPS0 bits. The output of the prescaler is
then used to increment the TMR2 register starting at 00h. The values of TMR2 and PR2
registers are compared all the time and the TMR2 is constantly incremented until it
matches the value stored in PR2. When the match occurs, the TMR2 register is
automatically cleared. The Timer2 postscaler is incremented on every match and its
output is used to generate an interrupt if enabled.
The TMR2 and PR2 registers are both readable and writable. Counting may be stopped
by clearing the TMR2ON bit, thus reducing power consumption.
The moment of the Timer2 reset may also be used as a serial communication clock
signal.
38
PIC MICROCONTROLLER
The operation of the Timer2 is under control of several bits of the T2CON register.
TOUTPS3 - TOUTPS0 - Timer2 Output Postcaler Select bits are used to determine the
postscaler rate according to the following table:
TOUTPS3 TOUTPS2 TOUTPS1 TOUTPS0 POSTSCALAR
0 0 0 0 1:1
0 0 0 0 1:2
0 0 0 1 1:3
0 0 1 0 1:4
0 0 1 1 1:5
0 1 0 0 1:6
0 1 0 1 1:7
0 1 1 0 1:8
0 1 1 1 1:9
1 0 0 0 1:10
1 0 0 1 1:11
1 0 1 0 1:12
1 0 1 1 1:13
1 1 0 0 1:14
1 1 0 1 1:15
1 1 1 1 1:16
TMR2ON - Timer2 On bit turns the Timer2 on. 1 - Timer2 is on. 0 - Timer2 is off.
T2CKPS1, T2CKPS0 - Timer2 Clock Prescale bits determine the prescaler rate:
39
PIC MICROCONTROLLER
T2CKPS1 T2CKPS0 PRESCALAR
0 0 1:1
0 1 1:4
1 0 1:16
1 1 1:16
40
PIC MICROCONTROLLER
PROGRAM:1
#include<pic.h> int count=0; void main(){TRISB=0X00;PORTB=0X00; PR2=128; TMR2=0; T2CON=0x7f; while(1){
while(!TMR2IF); TMR2IF=0; count++; if(count==30){
PORTB=~PORTB; count=0;
}}
}
#PROGRAM FOR TIMER 3:
#include<pic.h> int count=0; void main(){TRISB=0X00;PORTB=0X00; PR2=128; TMR2=0; T2CON=0x7f; while(1){
while(!TMR2IF); TMR2IF=0; count++; if(count==30){
PORTB=~PORTB;
41
PIC MICROCONTROLLER
count=0;}
}}
PROGRAM:4#include<pic.h>void main()
{TRISB=0X00; PORTB=0X01;OPTION=0x07;TMR0=0;while(1){
forward();}
}forward()
{int z=0;int count=0;while(z<8){
while(!T0IF);T0IF=0;count++;if(count==1){
PORTB=PORTB<<1;count=0;z++;if(z==7){
reverse();}
} }
}reverse()
{int z=0;int count=0;while(z<8){
while(!T0IF);T0IF=0;count++;
42
PIC MICROCONTROLLER
if(count==1){
PORTB=PORTB>>1;count=0;z++;if(z==7){
forward();}
} }
}
CCP MODULE
The CCP module (Capture/Compare/PWM) is a peripheral which allows the user to time
and control different events. As its name suggests, it can be set to operate in three
different modes:
Capture Mode provides an access to the current state of a register which constantly
changes its value. In this case, it is the timer register TMR1.
Compare Mode constantly compares values of two registers. One of them is the timer
register TMR1.
PWM (Pulse Width Modulation) can generate signals of varying frequency and duty
cycle on one or more output pins.
There are two CCP modules integrated into the PIC16F887 microcontroller - CCP1 and
CCP2. They are almost identical in operation with difference in enhanced PWM features
available on the CCP1 module only
CCP1 MODULE
The heart of the CCP1 module is a 16-bit register CCPR1 which consists of two registers
CCPR1L and CCPR1H. It is used for capturing binary numbers from the timer register
TMR1 (TMR1H and TMR1L) or comparing binary numbers stored in registers CCPR1
and TMR1.
43
PIC MICROCONTROLLER
If enabled by software, the timer register TMR1 reset may occur on any match in the
compare mode. Besides, the CCP1 module is capable of generating PWM signals of
varying frequency and duty cycle.
Bits of the CCP1CON register are in control of the CCP1 module.
CCP1 IN CAPTURE MODE
In this mode, the CCP1 register (consisting of the CCPR1H and CCPR1L register pair)
captures a 16-bit value from the timer register TMR1 (consisting of the TMR1H and
TMR1L register pair) when one of the following events occurs on the RC2/CCP1 pin:
Every falling edge (1 -> 0);
Every rising edge (0 -> 1);
Every 4th rising edge (0 -> 1); and
Every 16th rising edge (0 -> 1).
Which of these events will cause a 16-bit data to be captured depends on the combination
of four bits (CCP1M3, CCP1M2, CCP1M1 and CCP1M0) of the control register. In
addition, the following conditions must be met:
The RC2/CCP1 pin must be configured as an input; and
The Timer1 module must operate as a timer or a synchronous counter.
The CCP1IF flag bit is set when capture is made. If the CCP1IE bit of the PIE1 register is
set when it happens, an interrupt occurs.
44
PIC MICROCONTROLLER
When the CCP1 module exits the capture mode, an unwanted capture interrupt may be
generated. In order to prevent this, both the bit enabling the CCP1IE interrupt and the
CCP1IF flag bit should be cleared prior to making any change in the CCP1CON control
register.
CCP1 IN COMPARE MODE
In this mode, the value stored in the CCP1 register is constantly compared to the value
stored in the TMR1 timer register. When a match occurs, the logic state of the RC2/CCP1
output pin may be changed, which depends on the state of bits in the control register
(CCP1M3 - CCP1M0). The CCP1IF flag bit will be simultaneously set.
To set the CCP1 module to operate in the compare mode, two conditions must be met:
The RC2/CCP1 pin must be configured as an output; and
Timer1 must be synchronized with internal clock.
CCP1 IN PWM MODE
Pulse sequences with varying pulse frequency and duty cycle have a wide range of
application in automation. A typical example is a power control unit. Refer to figure
below. If a logic zero (0) indicates a switch-off state and a logic one (1) indicates a
switchon state, electrical power to feed a consumer with will be directly proportional to
the pulse duration. This ratio is called Duty Cycle.
45
PIC MICROCONTROLLER
Another example, also common in practice, is the use of PWM signals in signal
generating units to produce signals of arbitrary waveforms such as sinusoidal waveform.
See figure below:
Devices which operate using PWM signals are commonly used in practice as adjustable
frequency drivers controlling the operation of electric motors (speed, acceleration,
deceleration etc.).
46
PIC MICROCONTROLLER
Figure above shows a block diagram of the CCP1 module set to PWM mode. In order to
generate a pulse of arbitrary duty cycle on its output pin, it is necessary to set pulse
period (frequency) and pulse duration first.
PWM PERIOD
The PWM output pulse period (T) depends on the value stored in the PR2 register of the
Timer2. It is calculated by means of the following equation:
PWM Period = (PR2 +1) * 4Tosc * TMR2 Prescale Value
If the PWM period (T) is known, it is easy to calculate signal frequency (F) because these
two values are related by equation F=1/T.
47
PIC MICROCONTROLLER
PWM PULSE WIDTH
The PWM pulse width is determined by means of 10 bits in total: all bits (eight in total)
of the CCPR1L register as MSbs and two bits of the CCP1CON register as LSbs (DC1B1
and DC1B0). The result is a 10-bit number contained in the formula:
Pulse Width = (CCPR1L,DC1B1,DC1B0) * Tosc * TMR2 Prescale Value
The output pin will be constantly set if the pulse width is by negligence set to be
larger than PWM period.
In this case, the Timer2 postscaler cannot be used for generating long PWM
periods.
PWM SIGNAL RESOLUTION
A PWM signal is nothing more than a pulse sequence with varying duty cycle. For one
specific frequency (number of pulses per second), there is a limited number of duty cycle
combinations. Resolution is a maximum number of duty cycle combinations measured in
bits. For example, a 10-bit resolution will result in 1024 discrete duty cycles, whereas an
8-bit resolution will result in 256 discrete duty cycles etc. As for this microcontroller, the
resolution depends on the contents of the PR2 register. The maximum resolution is
obtained by writing number FFh to this register.
. ANALOG TO DIGITAL CONVERTER
The ANALOG-TO-DIGITAL CONVERTER converts analog voltage to binary numbers. These binary numbers can be in different length - 2, 4, 8, 10-bit. The more bits the binary number has, the higher the resolution of the - A/D.
For example: Suppose that the voltage that supplied to the A/D converter varies from 0 to 5 volt, and the A/D converter converts the input voltage to a binary number of two-bits.
With two bits, we can only display 4 different options
00,01,10,11
That is, we can show the changes from 0 to 5 volt with 4 numbers, or more precisely four levels. You can see the 4 levels in the following illustration:
48
PIC MICROCONTROLLER
We can see that the red signal far from being ideal, i.e. not close enough to the original analog input voltage values. Thus, we can say that A/D with the binary number of two-bits has a low resolution and there is a large gap between the real value of the analog input voltage and the values represented by the A/D.Now, suppose that the voltage that supplied to the A/D converter is still varies from 0 to 5 volt, however, the A/D converter converts the input voltage to a binary number of three-bits. With three bits, we can get 8 different options
000 001 010 011 100 101 110 111
That is, we can show the changes from 0 to 5 volt with 8 numbers, or more precisely 8 levels. You can see the eight levels in the following illustration:
Now we can see that the RED line represents the original signal “better” than the previous RED line. The gap between the analog signal and the digital signal smaller compared to the previous graph. Based on the "good" results that we received, we can say that current A/D converter has high resolution compare to previous case.
Therefore we can say that the ANALOG TO DIGITAL CONVERTER (A/D) of the microcontroller with a larger amount of bits has a higher resolution and better accuracy when converting from analog signal to digital signal.
There is another fact to mention about the resolution of the A/D converter. Since the converter converts the signals, it takes a certain time. The conversion time of the low resolution A/D take less time then the conversion time of the high resolution A/D.
When you are planning special systems, you have to take into account this fact. If you are planning to build accurate and fast systems, you have to consider carefully which convert to choose: if you select an analog to digital converter (A/D) with high resolution – system will not be as “fast; but if you select an analog to digital converter (A/D) with high-speed response – you will loose the resolution of the system.
6.1 How to convert analog values to digital values:
If we decide to work with an analog to digital converter (A/D) with three-bit length, we obtain eight different binary numbers which represent different voltage levels. For example:
Voltage levels [V] Binary representation
0-0.62 0000.621-1.25 0011.251-1.87 0101.871-2.5 0112.51-3.12 100
49
PIC MICROCONTROLLER
3.121-3.75 1013.751-4.37 1104.371-5.00 111In this example, the analog voltage values from 0v to 0.62v have a binary
representation of 000; the analog voltage values from 0.621v to 1.25v have a binary representation of 001 so on.
The Analog to Digital Converter (ADC) module located within the PIC microcontroller has a resolution of ten-bit length. Therefore, the converter can divide the analog input voltage between 0v and 5v to 2^ 10 levels, which are 1024 levels. We can say that the resolution of this component is very high. How do we know what is the binary value/representation of the analog input voltage?
We can use the triangle method to calculate/find the binary representation of an analog input voltage. For example, lets calculate/find the binary value representation on the analog input voltage of 3.65 volt:
5v-------->10243.65v------xX=(1024*3.65)/5=747.52=748
The analog input voltage of 3.65v will be represented by decimal number 748 or by binary number 1011101100.Using similar way we can find a binary representation for any desired level of the analog input voltage.
The A/D module has four 8 bit registers. These registers are:
ADCON0 - A/D Control Register 0; determines the behavior of the A/D
ADCON1 - A/D Control Register 1; determines the configuration of the PORTA and PORTE and how the result of conversion of A/D will be store
ADRESH - A/D Result High Register
ADRESL - A/D Result Low Register
The size of this register is one byte (8 bits). Each bit has an important role in the definition of the component. Here's a breakdown of the bits role:
50
PIC MICROCONTROLLER
After we define the appropriate pins in the specific PORT to be analog inputs, we can sample the analog input voltage using one of the following channels:
You can sample from PORTA each of the pins RA0 and RA5 except pin RA4 (used for other purposes) as well as of PORTE.
GO/DONE: A/D Conversion Status bitIf 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)
ADON: A/D On bit1 = A/D converter module is operating0 = A/D converter module is shut-off and consumes no operating current
The size of this register is one byte (8 bits). Each bit has an important role in the definition of the component. Here's a breakdown of the bits role:
51
PIC MICROCONTROLLER
ADFM: A/D Result Format Select bit1 = 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’.
As we said, the A/D converter has a resolution of ten bits, i.e., the result of the conversion can not be stored in one register of eight bits. Therefore, the result is stored in two registers: ADRESL and ADRESH. The size of each register is 8 bits long, so that we have 16 (2*8) bits all together. We can store the result of the conversion which is 10 bits long using the two registers ADRESL and ADRESH in the following 2 ways:
alignment to the left
alignment to the right
Allignment to the left -the eight MSB bits are stored in the ADRESH, and the two LSB bits are stored in ADRESL. In this case, the remaining six bits appear as - "0".
Left justified
X X X X X X X X X X 0 0 0 0 0 0ADRESH ADRESL
Right justified
0 0 0 0 0 0 X X X X X X X X X XADRESH ADRESL
Alignment to the right- the eight LSB bits are stored in ADRESL, and two MSB bits are stored in the ADRESH. In this case six highest bits appear as - "0".
PCFG3:PCFG0: A/D Port Configuration Control bits:With these bits we can control the pins of PORTA or PORTE. We can decide an analog (A) or digital (D) mode.
pcfg3:0 an7/re2 an6/re1 an5/re0 an4/ra5 an3/ra3 an2/ra2 an1/ra1 an0/ra0 vref+ vref- chan/refs
0000 A A A A A A A A VDD
VSS 8/0
0001 A A A A Vref+ A A A VDD
VSS 7/1
0010 D D D A A A A A VD VSS 5/052
PIC MICROCONTROLLER
D0011 D D D A VREF+ A A A VD
DVSS 4/1
0100 D D D D A D A A VDD
VSS 3/0
0101 D D D D VREF+ D A A VDD
VSS 2/1
0110 D D D D D D d d VDD
VSS 0/0
0111 D D D D D D d d VDD
VSS 0/0
1000 A A A A Vref+ Vref- A A VDD
VSS 6/2
1001 D D A A A A A A VDD
VSS 6/0
1010 D D A A Vref+ A A A VDD
VSS 5/1
1011 D D A A Vref+ Vref- A A VDD
VSS 4/2
1100 D D D A Vref+ Vref- A A VDD
VSS 3/2
1101 D D D D Vref+ Vref- A A VDD
VSS 2/2
1110 D D D D D D d A VDD
VSS 1/0
1111 D D D D Vref+ Vref- d A VDD
VSS 1/2
If we want to work with the PORTA and PORTE as analog ports, then we select the option PCFG3: PCFG0 = 0000; If we want to work with ports as digital, then we select the option PCFG3: PCFG0 = 011x.
In general, after the specified desired behavior of the A/D converter unit and before we start the conversion operation, we have to set up channel through which the analog information will be received using TRIS command. To begin making the conversion, we have to set the GO/DONE =1. This is done by using the command ADGO = 1. When the conversion ends, the result will be loaded into 2 registers ADRESH: ADRESL. Status bit GO/DONE (the register ADCON0) will be set to zero and the ADIF flag is set.
53
PIC MICROCONTROLLER
One of the most important analog modules within the microcontroller is an A/D converter
which has the following features:
Conversion is performed by applying the method of successive approximation;
There are 14 separate analog inputs connected to the microcontroller port pins;
The A/D converter converts an analog input signal into a 10-bit binary number;
The resolution, i.e. the quality of conversion may be adjusted to various needs by
selecting voltage references Vref- and Vref+.
A/D CONVERTER
Even though the use of A/D converter seems to be very complicated, it is basically very
simple, simpler than the use of timers and serial communication modules, anyway.
The operation of A/D converter is in control of the bits of four registers:
ADRESH Contains high byte of conversion result;
ADRESL Contains low byte of conversion result;
ADCON0 Control register 0; and
ADCON1 Control register 1.
ADRESH and ADRESL Registers
The process of converting an analog value into digital has as a result a 10-bit number to
be stored in the ADRESH and ADRESL registers. There are two ways of handling this
number - left and right justification which simplifies its use to a great extent. The format
54
PIC MICROCONTROLLER
of conversion result depends on the ADFM bit of the ADCON1 register. In case the A/D
converter is not used, ADRESH and ADRESL registers may be used as general-purpose
registers.
PROGRAM:1
#include<pic.h>
void main()
{
55
PIC MICROCONTROLLER
TRISA=0XFF;
TRISB=0X00;
PORTB=0X00;
ADCON0=0XC5;
ADCON1=0X8E;
while(1)
{
while(ADGO==1);
PORTB=ADRESL;
delay();
PORTB=ADRESH;
delay();
ADGO=1;
}
}
delay()
{
for(int i=0;i<30000;i++);
}
56
PIC MICROCONTROLLER
PROGRAM:2
#include<pic.h>
void delay()
{
for(int i=0;i<100;i++)
for(int j=0;j<100;j++);
}
void send_data(char data1) //data mode for lcd
{
while(!TRMT);
TXREG=data1;
delay();
}
void main()
{
int a,b,c,d=0,d0,d1,d2,d3;
TRISA0=1; // adc i/p
TRISC6=0;
TRISC7=1;
TXSTA=0x26;
57
PIC MICROCONTROLLER
RCSTA=0x90;
SPBRG=25;
delay();
ADCON0=0xC5;
ADCON1=0x8E;
while(1) {
ADGO=1;
while(ADGO==1);
a=ADRESL;
b=ADRESH;
b=b*256;
c=b+a;
d0=c/1000;
d=c%1000;
d1=d/100;
d=d%100;
d2=d/10;
d3=d%10;
d0=d0+0x30;
d1=d1+0x30;
58
PIC MICROCONTROLLER
d2=d2+0x30;
d3=d3+0x30;
send_data(d0); //data mode for lcd
send_data(d1);
send_data(d2);
send_data(d3);
send_data(0x01);
}
}
PROGRAM:3
#include<pic.h>
config(unsigned char data);
data(unsigned char data1);
delay()
{
for(int 1-0;a<10000;a++);
}
void main()
{
int a,b,c,d=0,d0,d1,d2,d3;
TRISA0=1;
59
PIC MICROCONTROLLER
TRISB=0x00;
TRISE=0x00;
PORTA=0x00;
PORTB=0x00;
PORTE=0x00;
config(0x01);
delay();
config(0x06);
delay();
config(0x0E);
delay();
config(0x38);
delay();
config(0x80);
delay();
ADC)N0=0xC5;
ADCON1=0x8E;
while(1)
{
ADGO=1;
while(ADGO==1);
60
PIC MICROCONTROLLER
a=ADRESL;
b=ADRESH;
b=b*256;
c=a+b;
d3=c/1000;
d=c%1000;
d2=d/100;
d=d%100;
d1=d/10;
d0=d%10;
d3=d3+0x30;
d2=d2+0x30;
d1=d1+0x30;
d0=d0+0x30;
data(d3);
data(d2);
data(d1);
data(d0);
config(0x02);
}
config(char data)
61
PIC MICROCONTROLLER
{
PORTE=0x04;
delay();
PORTB=data;
delay();
}
PIC SERIAL COMMUNICATIONS
INTRODUCTION TO SERIAL COMMUNICATION WITH PIC16F877 MICROCONTROLLER:
In this tutorial we will study the communication component – USART (Universal Synchronous Asynchronous Receiver Transmitter) located within the PIC. It is a universal communication component (Synchronous/Asynchronous), which can be used as transmitter or as receiver. USART in order to allow communication between PIC to PIC or between PIC to a personal computer. We will start with the definition of media concepts. There are two options to differentiate when speaking about transmission of information on the transmission lines:
Serial communication –transfer data bit by bit
Parallel communication –transfer data byte by byte
In addition to the serial and parallel communications, there are 2 types of communication we will explore:
Synchronous communication
Asynchronous communication 62
PIC MICROCONTROLLER
SYNCHRONOUS COMMUNICATION
When using the synchronous communication – the information is transmitted from the transmitter to the receiver:
In sequence
Bit after bit
With fixed baud rate
The clock frequency is transmitted along with the bits
That means that the transmitter and the receiver are synchronized between them by the same clock frequency. The clock frequency can be transmitted along with the information, while it is encoded in the information itself, or in many cases there is an additional wire for the clock.This type of communication is faster compare to the asynchronous communication since it is "constantly transmitting” the information, with no stops.
ASYNCHRONOUS COMMUNICATION
When using the asynchronous communication - the transmitter and the receiver refraining to transmit long sequences of bits because there isn't a full synchronization between the transmitter, that sends the data, and the receiver, that receives the dataIn this case, the information is divided into frames, in the size of byte. Each one of the frame has:
“Start” bit marks the beginning of a new frame. “Stop” bit marks the end of the frame.
Frames of information must not necessarily be transmitted at equal time space, since they are independent of the clock.
ENABLING SERIAL COMMUNICATION
To communicate with external components such as computers or microcontrollers, the PIC micro uses a component called USART - Universal Synchronous Asynchronous Receiver Transmitter. This component can be configured as:
Full-Duplex asynchronous system that can communicate with peripheral devices, such as CRT terminals and personal computers
Half-Duplex synchronous system that can communicate with peripheral devices, such as A/D or D/A integrated circuits, serial EEPROMs, etc.
63
PIC MICROCONTROLLER
The USART system integrated into the PIC16F887 microcontroller has the following
features:
Full-duplex asynchronous transmit and receive;
Programmable 8- or 9-bit wide characters;
Address detection in 9-bit mode;
Input buffer overrun error detection
Half-duplex communication in synchronous mod
64
PIC MICROCONTROLLER
ASYNCHRONOUS USART TRANSMITTER
TXSTA Register
CSRC - Clock Source Select bit - is used to for the clock source selection. It is used only in
synchronous mode.
1 - Master mode. Clock is generated internally from Baud Rate Generator.
0 - Slave mode. Clock is generated from external source.
TX9 - 9-bit Transmit Enable bit
1 - 9-bit data transmission via the EUSART system.
0 - 8-bit data transmission via the EUSART system.
TXEN - Transmit Enable bit
1 - Transmission enabled.
0 - Transmission disabled.
SYNC - USART Mode Select bit
1 - USART operates in synchronous mode.
0 - USART operates in asynchronous mode.
65
PIC MICROCONTROLLER
SENDB - Send Break Character bit is only used in asynchronous mode and when required to
observe the LIN bus standard.
1 - Break character transmission is enabled.
0 - Break character transmission is completed.
BRGH - High Baud Rate Select bit determines baud rate in asynchronous mode. It does not
affect EUSART in synchronous mode.
1 - EUSART operates at high speed.
0 - EUSART operates at low speed.
TRMT - Transmit Shift Register Status bit
1 - TSR register is empty.
0 - TSR register is full.
TX9D - Ninth bit of Transmit Data can be used as address or parity bit.
In order to enable data transmission via the USART module, it is necessary to configure this
module to operate as a transmitter. In other words, it is necessary to define the state of the
following bits:
TXEN = 1 - USART transmitter is enabled by setting the TXEN bit of the TXSTA
register.
SYNC = 0 - USART is configured to operate in asynchronous mode by clearing the
SYNC bit of the TXSTA register.
SPEN = 1 - By setting the SPEN bit of the RCSTA register, USART is enabled and the
TX/CK pin is automatically configured as an output.
USART ASYNCHRONOUS RECEIVER
66
PIC MICROCONTROLLER
RCSTA Register
SPEN - Serial Port Enable bit
1 - Serial port enabled. RX/DT and TX/CK pins are automatically configured as input
and output, respectively.
0 - Serial port disabled.
RX9 - 9-bit Receive Enable bit
1 - Reception of 9-bit data via the EUSART system.
0 - Reception of 8-bit data via the EUSART system.
SREN - Single ReceiveEnable bit is used only in synchronous mode when the microcontroller
operates as a master.
1 - Single receive enabled.
0 - Single receive disabled.
CREN - Continuous Receive Enable bit acts differently depending on the EUSART mode.
Asynchronous mode:
1 - Receiver enabled.
0 - Receiver disabled.
Synchronous mode:
67
PIC MICROCONTROLLER
1 - Enables continuous receive until the CREN bit is cleared.
0 - Disables continuous receive.
ADDEN - Address Detect Enable bit is only used in address detect mode.
1 - Enables address detection on 9-bit data receive.
0 - Disables address detection. The ninth bit can be used as a parity bit.
FERR - Framing Error bit
1 - Framing Error is detected on receive.
0 - No framing error.
OERR - Overrun Error bit.
1 - On receive, Overrun Error is detected.
0 - No overrun error.
RX9D - Ninth bit of Received Data can be used as address or parity bit.
The following diagram shows three words appearing on the RX input. The receiving buffer is
read after the third word, causing the OEER bit (overrun error bit) to be set.
PROGRAM:1
#include<pic.h>
void delay()
{
for(int i=0;i<100;i++)
for(int j=0;j<100;j++);
}
void send_data(char data1) //data mode for lcd
{
while(!TRMT);
TXREG=data1;
68
PIC MICROCONTROLLER
delay();
}
void main()
{
int a,b,c,d=0,d0,d1,d2,d3;
TRISA0=1; // adc i/p
TRISC6=0;
TRISC7=1;
TXSTA=0x26;
RCSTA=0x90;
SPBRG=25;
delay();
ADCON0=0xC5;
ADCON1=0x8E;
while(1) {
ADGO=1;
while(ADGO==1);
a=ADRESL;
b=ADRESH;
b=b*256;
69
PIC MICROCONTROLLER
c=b+a;
d0=c/1000;
d=c%1000;
d1=d/100;
d=d%100;
d2=d/10;
d3=d%10;
d0=d0+0x30;
d1=d1+0x30;
d2=d2+0x30;
d3=d3+0x30;
send_data(d0); //data mode for lcd
send_data(d1);
send_data(d2);
send_data(d3);
send_data(0x01);
}
}
PROGRAM:2
#include<pic.h>
70
PIC MICROCONTROLLER
void main()
{
TRISD=0xff;
TRISB=0x00;
TRISC6=0;
TRISC7=1;
TXSTA=0x26;
RCSTA=0x90;
SPBRG=25;
int reg=1;
while(1)
{
if(RD0==1)
{
if(reg==1)
{
reg=0;
while(!TRMT);
TXREG='1';
PORTB=0x0f;
}
71
PIC MICROCONTROLLER
}
else if(RD1==1)
{
if(reg==1)
{
reg=0;
while(!TRMT);
TXREG='2';
PORTB=0xf0;
}
}
else if(RD2==1)
{
if(reg==1)
{
reg=0;
while(!TRMT);
TXREG='3';
PORTB=0xf0;
}
}
72
PIC MICROCONTROLLER
else if(RD2==1)
{
if(reg==1)
{
reg=0;
while(!TRMT);
TXREG='4';
PORTB=0xf0;
}
}
else
{
TXREG=0x0a;
PORTB=0x00;
reg=1;
}
}
}
PROGRAM:3
#include<pic.h>
void main()
73
PIC MICROCONTROLLER
{
TRISB=0x00;
TRISC6=0;
TRISC7=1;
PORTB=0x00;
TXSTA=0x26;
RCSTA=0x90;
SPBRG=25;
GIE=1;
PEIE=1;
RCIE=1;
int a;
while(1);
{
if(RCIF==1)
{
a=RCREG;
switch(a)
{
case '1':
74
PIC MICROCONTROLLER
PORTB=0x10;
break;
case '2':
PORTB=0x20;
break;
case '3':
PORTB=0x40;
break;
case '4':
PORTB=0x80;
break;
}
}
}
}
INTERRUPT
INTERRUPT SYSTEM REGISTERS
A reception of an interrupt request doesn’t mean that it will automatically occur, because it must also be
enabled by the user (from within the program). For this reason, there are special bits used to enable or
disable interrupts. It is easy to recognize them by letters IE (stands for Interrupt Enable) contained in their
names. Besides, each interrupt is associated with another bit called a flag which indicates that an
75
PIC MICROCONTROLLER
interrupt request has arrived regardless of whether it is enabled or not. Likewise, their names are followed
by IF (Interrupt Flag).
As you can see, everything is based on a simple and efficient principle. When an interrupt request arrives,
the flag bit will be set first. If the appropriate IE bit is not set (0), the interrupt condition will be completely
ignored. Otherwise, an interrupt occurs. If several interrupt sources are enabled, it is necessary to detect
the active one before an interrupt routine starts execution. Source detection is performed by checking flag
bits.
It is important to know that flag bits are not automatically cleared, but by software while the interrupt
routine execution is under way. If we neglect this detail, another interrupt will occur immediately after
returning to the main program, even though there are no more requests for its execution. Simply put, the
flag, as well as the IE bit, remain set.
All interrupt sources typical of the PIC16F887 microcontroller are shown on the next page. Note several
things:
The GIE bit enables all unmasked interrupts and disables all interrupts simultaneously.
The PEIE bit enables all unmasked peripheral interrupts and disables all peripheral interrupts. This
doesn’t refer to Timer0 and PORTB interrupt sources.
To enable an interrupt to occur by changing the PORTB logic state, it is necessary to enable it for each bit
separately. In this case, bits of the IOCB register act as control IE bits.
76
PIC MICROCONTROLLER
INTCON Register
The INTCON register includes various enable and flag bits for TMR0 register overflow, PORTB change
and external INT pin interrupts.
Legend: R/W - Readable/Writable Bit, (0) After reset, bit is cleared, (X) After reset, bit is unknown
GIE - Global Interrupt Enable bit - controls all possible interrupt sources
simultaneously.
o 1 - All unmasked interrupts enabled.
o 0 - All interrupts disabled.
77
PIC MICROCONTROLLER
PEIE - Peripheral Interrupt Enable bit acts similar to the GIE bit, but controls interrupts
enabled by peripheral modules. Hence, it has no impact on interrupts triggered by
Timer0 or by changing the state of port PORTB or pin RB0/INT.
o 1 - All unmasked peripheral interrupts enabled.
o 0 - All peripheral interrupts disabled.
T0IE - TMR0 Overflow Interrupt Enable bit controls interrupts triggered by the TMR0
overflow.
o 1 - TMR0 overflow interrupt enabled.
o 0 - TMR0 overflow interrupt disabled.
INTE - RB0/INT External Interrupt Enable bit controls interrupt caused by changing
the logic state of the RB0/INT input pin (external interrupt).
o 1 - INT external interrupt enabled.
o 0 - INT external interrupt disabled.
RBIE - RB Port Change Interrupt Enable bit. When configured as inputs, PORTB pins
may cause an interrupt by changing their logic state (no matter whether it is high-to-low
transition or vice versa, the fact that their logic state is changed only matters). The RBIE
bit determines whether an interrupt is to occur or not.
o 1 - PORTB change interrupt enabled.
o 0 - PORTB change interrupt disabled.
T0IF - TMR0 Overflow Interrupt Flag bit registers the Timer0 register overflow, when
counting starts at zero.
o 1 - TMR0 register has overflowed (bit must be cleared from within the software).
o 0 - TMR0 register has not overflowed.
INTF - RB0/INT External Interrupt Flag bit registers the change of the RB0/INT pin
logic state.
o 1 - INT external interrupt has occurred (must be cleared from within the software).
o 0 - INT external interrupt has not occurred.
RBIF - RB Port Change Interrupt Flag bit registers any change of the logic state of
some PORTB input pins.
78
PIC MICROCONTROLLER
o 1 - At least one of the PORTB general purpose I/O pins has changed its logic state. After port
PORTB read is complete, the RBIF bit must be cleared from within the software.
o 0 - None of the PORTB general purpose I/O pins has changed its logic state.
PIE1 Register
The PIE1 register contains peripheral interrupt enable bits.
Legend: (-) Unimplemented bit, (R/W) - Readable/Writable Bit, (0) After reset, bit is cleared
ADIE - A/D Converter Interrupt Enable bit.
o 1 - ADC interrupt enabled.
o 0 - ADC interrupt disabled.
RCIE - EUSART Receive Interrupt Enable bit.
o 1 - Enables the EUSART receive interrupt.
o 0 - Disables the EUSART receive interrupt.
TXIE - EUSART Transmit Interrupt Enable bit.
o 1 - EUSART receive interrupt enabled.
o 0 - EUSART receive interrupt disabled.
SSPIE - Master Synchronous Serial Port (MSSP) Interrupt Enable bit - enables an
interrupt request to be generated every time a data transfer via synchronous serial
communication module (SPI or I2C mode) is complete.
o 1 - MSSP interrupt enabled.
o 0 - MSSP interrupt disabled.
CCP1IE - CCP1 Interrupt Enable bit enables an interrupt request to be generated in
CCP1 module used for PWM signal processing.
o 1 - CCP1 interrupt enabled.
o 0 - CCP1 interrupt disabled.
TMR2IE - TMR2 to PR2 Match Interrupt Enable bit
o 1 - TMR2 to PR2 match interrupt enabled.
79
PIC MICROCONTROLLER
o 0 - TMR2 to PR2 match interrupt disabled.
TMR1IE - TMR1 Overflow Interrupt Enable bit enables an interrupt request to be
generated upon each TMR1 timer register overflow, i.e. when the counting starts from
zero.
o 1 - TMR1 overflow interrupt enabled.
o 0 - TMR1 overflow interrupt disabled.
PIE2 Register
The PIE2 register also contains various interrupt enable bits.
Legend: (-) Unimplemented bit, (R/W) - Readable/Writable Bit, (0) After reset, bit is cleared
OSFIE - Oscillator Fail Interrupt Enable bit.
o 1 - Oscillator fail interrupt enabled.
o 0 - Oscillator fail interrupt disabled.
C2IE - Comparator C2 Interrupt Enable bit.
o 1 - Comparator C2 interrupt enabled.
o 0 - Comparator C2 interrupt disabled.
C1IE - Comparator C1 Interrupt Enable bit.
o 1 - Comparator C1 interrupt enabled.
o 0 - Comparator C1 interrupt disabled.
EEIE - EEPROM Write Operation Interrupt Enable bit.
o 1 - EEPROM write operation interrupt enabled.
o 0 - EEPROM write operation interrupt disabled.
BCLIE - Bus Collision Interrupt Enable bit.
o 1 - Bus collision interrupt enabled.
o 0 - Bus collision interrupt disabled.
ULPWUIE - Ultra Low-Power Wake-up Interrupt Enable bit.
o 1 - Ultra low-power wake-up interrupt enabled.
80
PIC MICROCONTROLLER
o 0 - Ultra low-power wake-up interrupt disabled.
CCP2IE - CCP2 Interrupt Enable bit.
o 1 - CCP2 interrupt enabled.
o 0 - CCP2 interrupt disabled.
PIR1 Register
The PIR1 register contains the interrupt flag bits.
Legend: (-) Unimplemented bit, (R/W) - Readable/Writable Bit, (R) - Readable Bit, (0) After reset, bit
is cleared
ADIF - A/D Converter Interrupt Flag bit.
o 1 - A/D conversion is completed (the bit must be cleared from within the software).
o 0 - A/D conversion is not completed or has not started.
RCIF - EUSART Receive Interrupt Flag bit.
o 1 - EUSART receive buffer is full. The bit is cleared by reading the RCREG register.
o 0 - EUSART receive buffer is not full.
TXIF - EUSART Transmit Interrupt Flag bit.
o 1 - EUSART transmit buffer is empty. The bit is cleared on any write to the TXREG register.
o 0 - EUSART transmit buffer is full.
SSPIF - Master Synchronous Serial Port (MSSP) Interrupt Flag bit.
o 1 - All MSSP interrupt conditions during data transmit/receive are met. They differ depending on
MSSP operating mode (SPI or I2C). This bit must be cleared from within the software before exiting
the interrupt service routine.
o 0 - No MSSP interrupt condition met.
CCP1IF - CCP1 Interrupt Flag bit.
o 1 - CCP1 interrupt condition is met (CCP1 is a unit for capturing, comparing and generating PWM
signal). Operating mode indicates whether capture or compare match has occurred. In both cases,
the bit must be cleared from within the software. This bit is not used in PWM mode.
81
PIC MICROCONTROLLER
o 0 - No CCP1 interrupt condition met.
TMR2IF - Timer2 to PR2 Interrupt Flag bit
o 1 - TMR2 (8-bit register) to PR2 match has occurred. This bit must be cleared from within the
software before exiting the interrupt service routine.
o 0 - No TMR2 to PR2 match has occurred.
TMR1IF - Timer1 Overflow Interrupt Flag bit
o 1 - TMR1 register has overflowed. The bit must be cleared from within the software.
o 0 - TMR1 register has not overflowed.
PIR2 Register
The PIR2 register contains interrupt flag bits.
Legend: (-) Unimplemented bit, (R/W) - Readable/Writable Bit, (0) After reset, bit is cleared
OSFIF - Oscillator Fail Interrupt Flag bit.
o 1 - Quartz oscillator failed and clock input has turned into internal oscillator INTOSC. This bit must
be cleared from within the software.
o 0 - Quartz oscillator operates normally.
C2IF - Comparator C2 Interrupt Flag bit.
o 1 - Comparator C2 output has changed (bit C2OUT). This bit must be cleared from within the
software.
o 0 - Comparator C2 output has not changed.
C1IF - Comparator C1 Interrupt Flag bit.
o 1 - Comparator C1 output has changed (bit C1OUT). This bit must be cleared from within the
software.
o 0 - Comparator C1 output has not changed.
EEIF - EE Write Operation Interrupt Flag bit.
o 1 - EEPROM write complete. This bit must be cleared from within the software.
o 0 - EEPROM write is not complete or has not started yet.
82
PIC MICROCONTROLLER
BCLIF - Bus Collision Interrupt Flag bit.
o 1 - A bus collision has occurred in the MSSP when set to operate in I2C master mode. This bit must
be cleared from within the software.
o 0 - No bus collision has occurred.
ULPWUIF - Ultra Low-power Wake-up Interrupt Flag bit.
o 1 - Wake-up condition has occurred. This bit must be cleared from within the software.
o 0 - No wake-up condition has occurred.
CCP2IF - CCP2 Interrupt Flag bit.
o 1 - CCP2 interrupt condition is met (unit for capturing, comparing and generating PWM signal).
Operating mode indicates whether capture or compare match has occurred. In both cases, the bit
must be cleared from within the software. This bit is not used in PWM mode.
o 0 - No CCP2 interrupt condition met.
MASTER SYNCHRONOUS SERIAL PORT MODULE
The MSSP module (Master Synchronous Serial Port) is a very useful, but at the same time one of
the most complex circuits within the microcontroller. It enables high speed communication
between the microcontroller and other peripherals or other microcontrollers by using few
input/output lines (three or maximum four). Therefore, it is commonly used to connect the
microcontroller to LCD displays, A/D converters, serial EEPROMs, shift registers etc. The main
feature of this type of communication is that it is synchronous and suitable for use in systems
with a single master and one or more slaves. The master device contains a baud rate generator
and supplies all devices in the system with the clock. Slave devices may in this way eliminate the
internal clock generation circuit. The MSSP module can operate in one out of two modes:
SPI mode (Serial Peripheral Interface); and
I2C mode (Inter-Integrated Circuit).
As can be seen in figure below, one MSSP module represents only a half of the hardware needed
to establish serial communication, while the other half is stored in the device it exchanges data
with. Even though the modules on both ends of the line are the same, their modes are essentially
different depending on whether they operate as a Master or a Slave:
83
PIC MICROCONTROLLER
If the microcontroller to be programmed controls another device or circuit (peripherals), it should
be set to operate as a master. It will generate clock when needed, i.e. only when data reception
and transmission are required by the software. Obviously, it is solely up to the master device to
establish connection or not.
Otherwise, if the microcontroller to be programmed is a peripheral of some more complex device
(for example, a PC) then it should operate as a slave. As such, it always has to wait for data
transmission request to be sent by the master device.
SPI MODE
The SPI mode allows 8 bits of data to be transmitted and received simultaneously using 3
input/output lines:
SDO - Serial Data Out - transmit line;
SDI - Serial Data In - receive line; and
SCK - Serial Clock - synchronization line.
Apart from these three lines, there is the forth line (SS) as well which may be used if the
microcontroller exchanges data with several peripheral devices. Refer to figure below.
SS - Slave Select - is an additional line used for specific device selection. It is active only when
the microcontroller is in slave mode, i.e. when the external - master device requires data
exchange.
The MSSP module uses in total of 4 register when set to SPI mode:
SSPSTAT - status register
84
PIC MICROCONTROLLER
SSPCON - control register
SSPBUF - buffer register
SSPSR - shift register (not directly available)
The first three registers are writable/readable and can be changed at any moment, while the forth
register, since not available, is used for converting data into ‘serial’ format.
As can be seen in figure below, the central part of the SPI module consists of two registers
connected to pins for reception, transmission and synchronization.
The Shift register (SSPRS) is directly connected to the microcontroller pins and used for serial
data transmission. The SSPRS register has its input and output so as the data can be shifted in
and out. In other words, each bit appearing on the input (receive line) simultaneously shifts
another bit toward the output (transmit line).
The SSPBUF register (Buffer) is part of memory used to temporarily hold the data prior to being
sent or immediately after being received. After all 8 bits of data have been received, the byte is
moved from the SSPRS to the SSPBUF register. Such operation allows the next byte to be
received before reading the data that has just been received. Any write to the SSPBUF register
during data transmission/reception will be ignored. From the programmers’ point of view, this
register is considered the most important as being most frequently accessed.
85
PIC MICROCONTROLLER
Receiving/Transmitting data using the SPI mode
Prior to starting the SPI initialization, it is necessary to specify several options:
Master mode TRISC.3=0 (the SCK pin is the clock output);
Slave mode TRISC.3=1 (the SCK pin is the clock input);
Data input phase- middle or end of data output time (the SMP bit of the SSPSTAT
register);
Clock edge (the CKE bit of the SSPSTAT register);
Baud Rate, bits SSPM3-SSPM0 of the SSPCON register (only in Master mode);
Slave select mode, bits SSPM3-SSPM0 of the SSPCON register (Slave mode only).
The SPI module starts to operate by setting the SSPEN bit:
Step 1.
Data to be transferred should be written to the buffer register SSPBUF. If the SPI module
operates in master mode, the microcontroller will automatically perform the following steps 2, 3
and 4. If the SPI module operates as Slave, the microcontroller will not perform these steps until
the SCK pin detects clock signal.
Step 2.
The data is now moved to the SSPSR register and the SSPBUF register is not cleared.
Step 3.
This data is then shifted to the output pin (MSB bit first) while the register is simultaneously
86
PIC MICROCONTROLLER
being filled with bits through the input pin. In Master mode, the microcontroller itself generates
clock, while the Slave mode uses an external clock (the SCK pin).
Step 4.
The SSPSR register is full once 8 bits of data have been received. It is indicated by setting the
BF bit of the SSPSTAT register and the SSPIF bit of the PIR1 register. The received data (one
byte) is automatically moved from the SSPSR register to the SSPBUF register. Since serial data
transmission is performed automatically, the rest of the program is normally executed while the
data transmission is in progress. In this case, the function of the SSPIF bit is to generate an
interrupt when one byte transmission is completed.
Step 5.
Finally, the data stored in the SSPBUF register is ready to use and should be moved to a desired
register.
I2C MODE
I2C mode (Inter IC Bus) The I2C mode (Inter IC Bus) is especially suitable when the
microcontroller and an integrated circuit, which the microcontroller should exchange data with,
are within the same device. It is usually another microcontroller or a specialized, cheap
integrated circuit belonging to the new generation of the so called ‘smart peripheral components’
(memory modules, temperature sensors, real-time clocks etc.)
Similar to serial communication in SPI mode, data transfer in I2C mode is synchronous and
bidirectional. This time only two pins are used for data transmission. These are the SDA (Serial
Data) and SCL (Serial Clock) pins. The user must configure these pins as inputs or outputs by
means of the TRISC bits.
By observing particular rules (protocols), this mode enables up to 122 different components to be
simultaneously connected in a simple way by using only two valuable I/O pins. Let’s take a look
at how it works:
87
PIC MICROCONTROLLER
Clock, necessary to synchronize the operation of both devices, is always generated by the master
device (a microcontroller) and its frequency directly affects the baud rate. Even though there is a
protocol allowing maximum 3,4 MHz clock frequency (so called highspeed I2C bus), this book
covers only the most frequently used protocol the clock frequency of which is limited to 100
KHz. There is no limitations for minimum frequency.
When master and slave components are synchronized by the clock, every data exchange is
always initiated by the master. Once the MSSP module has been enabled, it waits for a Start
condition to occur. The master device first sends the START bit (a logic zero) through the SDA
pin, then a 7-bit address of the selected slave device, and finally, the bit which requires data write
(0) or read (1) to the device. In other words, eight bits are shifted to the SSPSR register following
the start condition. All slave devices sharing the same transmission line will simultaneously
receive the first byte, but only one of them has the address to match and receives the whole data.
Once the first byte has been sent (only 8-bit data are transmitted), the master goes into receive
mode and waits for acknowledgment from the slave device that address match has occurred. If
the slave device sends acknowledge data bit (1), data transfer will be continued until the master
device (microcontroller) sends the Stop bit.
88
PIC MICROCONTROLLER
This is the simplest explanation of how two components communicate. Such a microcontroller is
also capable of controlling more complicated situations when 1024 different components (10-bit
address), shared by several different master devices, are connected. Such devices are rarely used
in practice and there is no need to discuss them at greater length.
Figure below shows the block diagram of the MSSP module in I2C mode.
The MSSP module uses six registers for I2C operation. Some of them are shown in figure above:
89
PIC MICROCONTROLLER
SSPCON
SSPCON2
SSPSTAT
SSPBUF
SSPSR
SSPADD
SSPSTAT Register
SMP Sample bit
SPI master mode - This bit determines input data phase.
1 - Logic state is read at the end of data output time.
0 - Logic state is read in the middle of data output time.
SPI slave mode - This bit must be cleared when SPI is used in Slave mode.
I²C mode (master or slave)
1 - Slew rate control disabled for standard speed mode (100kHz).
0 - Slew rate control enabled for high speed mode (400k Hz).
CKE - Clock Edge Select bit selects synchronization mode.
CKP = 0:
1 - Data is transferred on rising edge of clock pulse (0 - 1).
0 - Data is transferred on falling edge of clock pulse (1 - 0).
CKP = 1:
1 - Data is transferred on falling edge of clock pulse (1 - 0).
0 - Data is transferred on rising edge of clock pulse (0 - 1).
D/A - Data/Address bit is used in I2C mode only.
1 - Indicates that the last byte received or transmitted was data.
0 - Indicates that the last byte received or transmitted was address.
P - Stop bit is used in I²C mode only.
90
PIC MICROCONTROLLER
1 - Last detected bit is the STOP bit.
0 - Last detected bit is not the STOP bit.
S - Start bit is used in I²C mode only.
1 - Last detected bit is the START bit.
0 - Last detected bit is not the START bit.
R/W - Read Write bit is used in I2C mode only. This bit contains the R/W bit information
following the last address match. This bit is only valid from the address match to the next Start
bit, Stop bit or not ACK bit.
In I²C slave mode
1 - Data read.
0 - Data write.
In I²C master mode
1 - Transmit is in progress.
0 - Transmit is not in progress.
UA - Update Address bit is used in 10-bit I2C mode only.
1 - The SSPADD register must be updated.
0 - Address in the SSPADD register is correct and doesn’t need to be updated.
BF Buffer Full Status bit
During data receive (in SPI and I²C modes)
1 - Receive complete. The SSPBUF register is full.
0 - Receive not complete. The SSPBUF register is empty.
During data transmit (in I²C mode only)
1 - Data transmit in progress (doesn’t include the ACK and STOP bits).
0 - Data transmit complete (doesn’t include the ACK and STOP bits).
SSPCON Register
WCOL Write Collision Detect bit
91
PIC MICROCONTROLLER
1 - Collision detected. Write to the SSPBUF register was attempted while the I2C
conditions were not valid for transmission to start.
0 - No collision.
SSPOV Receive Overflow Indicator bit
1 - A new byte is received before reading the previously received data. Since there is no
space for new data receive, one of these two bytes must be cleared. In this case, data
stored in the SSPSR register is irretrievably lost.
0 - Serial data is received correctly.
SSPEN - Synchronous Serial Port Enable bit determines the microcontroller pins function and
initializes MSSP module:
In SPI mode
1 - Enables MSSP module and configures pins SCK, SDO, SDI and SS as serial port
pins.
0 - Disables MSSP module and configures these pins as I/O port pins.
In I²C mode
1 - Enables MSSP module and configures pins SDA and SCL as serial port pins.
0 - Disables MSSP module and configures these pins as I/O port pins.
CKP - Clock Polarity Select bit is not used in I²C master mode.
In SPI mode
1 - Idle state for clock is a high level.
0 - Idle state for clock is a low level.
In I²C slave mode
1 - Enables clock.
0 - Keeps clock low. Used to provide more time for data stabilization.
SSPM3-SSPM0 - Synchronous Serial Port Mode Select bits. SSP mode is determined by
combining these bits:
TOUTPS3 TOUTPS2 TOUTPS1 TOUTPS0 POSTSCALAR
0 0 0 0 SPI master mode, clock = Fosc/4
0 0 0 0 SPI master mode, clock = Fosc/16
92
PIC MICROCONTROLLER
0 0 0 1 SPI master mode, clock = Fosc/64
0 0 1 0SPI master mode, clock =
(outputTMR)/2
0 0 1 1SPI slave mode, SS pin control
enabled
0 1 0 0SPI slave mode, SS pin control
disabled, SS can be used as I/O pin
0 1 0 1 I²C slave mode, 7-bit address used
0 1 1 0 I²C slave mode, 10-bit address used
0 1 1 1I²C master mode, clock = Fosc /
[4(SSPAD+1)]
1 0 0 0 Mask used in I²C slave mode
1 0 0 1 Not used
1 0 1 0 I²C controlled master mode
1 0 1 1 Not used
1 1 0 0 Not used
1 1 0 1 I²C slave mode, 7-bit address used,START and STOP bits enable
interrupt
1 1 1 1 I²C slave mode, 10-bit address used,START and STOP bits enable
interrupt
SSPCON2 Register
GCEN - General Call Enable bit
In I²C slave mode only
1 - Enables interrupt when a general call address (0000h) is received in the SSPSR.
0 - General call address disabled.
ACKSTAT - Acknowledge Status bit
In I²C Master Transmit mode only
1 - Acknowledge was not received from slave.
0 - Acknowledge was received from slave.
93
PIC MICROCONTROLLER
ACKDT - Acknowledge data bit
In I²C Master Receive mode only
1 - Not Acknowledge.
0 - Acknowledge.
ACKEN - Acknowledge Sequence Enable bit
In I²C Master Receive mode
1 - Initiate acknowledge condition on the SDA and SCL pins and transmit the ACKDT
data bit. It is automatically cleared by hardware.
0 - Acknowledge condition is not initiated.
RCEN - Receive Enable bit
In I²C Master mode only
1 - Enables data receive in I2C mode.
0 - Receive disabled.
PEN - STOP condition Enable bit
In I²C Master mode only
1 - Initiates STOP condition on the SDA and SCL pins. This bit is automatically cleared
by hardware.
0 - STOP condition is not initiated.
RSEN - Repeated START Condition Enabled bit
In I²C master mode only
1 - Repeted START condition initiated on the SDA and SCL pins. This bit is
automatically cleared by hardware.
0 - Repeated START condition is not initiated.
SEN - START Condition Enabled/Stretch Enabled bit
In I²C Master mode only
1 - Initiates START condition on the SDA and SCL pins. This bit is automatically cleared
by hardware.
0 - START condition is not initiated.
94
PIC MICROCONTROLLER
I2C in Master Mode
The most common case is that the microcontroller operates as a master and a peripheral
component as a slave. This is why this book covers just this mode. It is also considered that the
address consists of 7 bits and a target device contains only one microcontroller (single-master
device).
In order to enable MSSP module in this mode, it is necessary to do the following:
Set baud rate (SSPADD register), turn off slew rate control (by setting the SMP bit of the
SSPSTAT register) and select master mode (SSPCON register). After all these preparations have
been finished and the module has been enabled (SSPCON register:SSPEN bit), it is necessary to
wait for internal electronics to signal that everything is ready for data transmission, i.e. the SSPIF
bit of the PIR1 register is set.
This bit should be cleared by software and after that the microcontroller is ready to exchange
data with peripherals.
DATA TRANSMISSION IN I2C MASTER MODE
95
PIC MICROCONTROLLER
Data transmission on the SDA pin starts with a logic zero (0) which appears upon setting the
SEN bit of the SSPCON2 register. Even enabled, the microcontroller has to wait a certain time
before it starts communication. It is the so called ‘Start condition’ during which internal
preparations and checks are performed. If all conditions are met, the SSPIF bit of the PIR1 is set
and data transmission starts as soon as the SSPBUF register is loaded.
Maximum 112 integrated circuits (slave devices) may simultaneously share the same
transmission line. The first data byte sent by the master device contains the address to match
only one slave device. All addresses are listed in respective data sheets. The eighth bit of the first
data byte specifies direction of data transmission, i.e. whether the microcontroller is to send or
receive data. In this case, the eighth bit is cleared to logic zero (0), which means that it is about
data transmission.
96
PIC MICROCONTROLLER
When address match occurs, the microcontroller has to wait for the acknowledge data bit. The
slave device acknowledges address match by clearing the ASKSTAT bit of the SSPCON2
register. If the match has properly occurred, all data bytes are transmitted in the same way.
Data transmission ends by setting the SEN bit of the SSPCON2 register. The STOP condition
occurs, which enables the SDA pin to receive pulses:
Start - Address - Acknowledge - Data - Acknowledge....Data - Acknowledge - Stop!
Data Reception in I2C Master Mode
Preparations for data reception are similar to those for data transmission, with exception that the
last bit of the first sent byte (containing address) is set to logic one (1). It specifies that master
expects to receive data from the addressed slave device. Let’s see what happens within the
microcontroller:
After internal preparations are finished and the START bit is set, the slave device starts sending
one byte at a time. These bytes are stored in the serial register SSPSR. Each data is, after
receiving the last eighth bit, loaded to the SSPBUF register from where it can be read. Reading
this register causes the acknowledge bit to be automatically sent, which means that the master
device is ready to receive new data.
Likewise, data reception ends by setting the STOP bit:
97
PIC MICROCONTROLLER
Start - Address - Acknowledge - Data - Acknowledge... Data - Acknowledge - Stop!
In this pulse sequence, the acknowledge bit is sent to the slave device.
BAUD RATE GENERATOR
In order to synchronize data transmission, all events taking place on the SDA pin must be
synchronized with a clock generated in the master device by a simple oscillator the frequency of
which depends on the microcontroller’s main oscillator frequency, the value written to the
SSPADD register and the current SPI mode as well.
The clock frequency of the mode described in this book depends on selected quartz crystal and
the SPADD register. Figure below shows the formula used to calculate it.
98
PIC MICROCONTROLLER
USEFUL NOTES ...
When the microcontroller communicates with peripheral components, it may happen that data
transmission fails for some reason. In this case, it is recommended to check the state of some of
the bits which can clarify the issue. In practice, the status of these bits is checked by executing a
short subroutine after each byte transmission and reception (just in case).
WCOL (SPCON,7) - If you try to write a new data to the SSPBUF register while another data
transmission/reception is in progress, the WCOL bit will be set and the contents of the SSPBUF
register remains unchanged. Write does not occur. After this, the WCOL bit must be cleared in
software.
BF (SSPSTAT,0) - In transmission mode, this bit is set when the CPU writes data to the
SSPBUF register and remains set until the byte in serial format is shifted from the SSPSR
register. In reception mode, this bit is set when data or address is loaded to the SSPBUF register.
It is cleared after reading the SSPBUF register.
99
PIC MICROCONTROLLER
SSPOV (SSPCON,6) - In reception mode, this bit is set when a new byte is received by the
SSPSR register via serial communication, whereas the previously received data has not been read
from the SSPBUF register yet.
SDA and SCL Pins - When the SPP module is enabled, these pins turn into Open Drain outputs.
It means that they must be connected to the resistors which are, on the other end, connected to
the positive power supply.
In short
Receiving/Transmitting data in the I2C mode
In order to establish serial communication in I2C mode, the following should be done:
Setting Module and Sending Address:
Value to determine baud rate should be written to the SSPADD register.
SlewRate control should be turned off by setting the SMP bit of the SSPSTAT register.
In order to select Master mode, binary value 1000 should be written to the SSPM3-
SSPM0 bits of the SSPCON1 register.
The SEN bit of the SSPCON2 register (START sequence) should be set.
The SSPIF bit is automatically set at the end of the START sequence when the module is
ready to operate. It should be cleared.
Slave address should be written to the SSPBUF register.
When the byte is sent, the SSPIF bit (interrupt) is automatically set after receiving the
acknowledge bit from the Slave device.
Data Transmit:
Data to be send should be written to the SSPBUF register.
100
PIC MICROCONTROLLER
When the byte is sent, the SSPIF bit (interrupt) is automatically set after receiving the
acknowledge bit from the Slave device.
In order to inform the Slave device that data transmission is complete, STOP condition
should be initiated by setting the PEN bit of the SSPCON register.
Data Receive:
In order to enable reception, the RSEN bit of the SSPCON2 register should be set.
The SSPIF bit indicates data reception. When data is read from the SSPBUF register, the
ACKEN bit of the SSPCON2 register should be set in order to enable acknowledge bit to
be sent.
In order to inform the Slave device that data transmission is complete, the STOP
condition should be initiated by setting the PEN bit of the SSPCON register.
WATCH DOG TIMER
A watchdog timer is a timer connected to a stand-alone RC oscillator within the microcontroller.
If the watchdog timer is enabled, every time it counts up to the maximum value, the microcontroller reset
occurs and the program execution starts from the first instruction. The point is to prevent this from
happening by using a specific command.
Anyway, the whole idea is based on the fact that every program is executed in several longer or shorter
loops. If instructions for the watchdog timer reset are set at the appropriate program locations, in addition
to commands being regularly executed, then the operation of the watchdog timer will not affect the
program execution. If for any reason, usually due to manufacturing noise, the program counter ‘gets
stuck’ at some memory location from which there is no return, the watchdog timer will not be cleared, so
the register’s value being constantly incremented will reach the maximum et voila! Reset occurs and the
program will be executed from the beginning.
101
PIC MICROCONTROLLER
POWER SUPPLY CIRCUIT
There are two things worth attention when speaking of the microcontroller power supply circuit:
Brown out is a potentially dangerous condition which occurs at the moment the
microcontroller is turned off or when the power supply voltage drops to its minimum
value due to noise. As the microcontroller consists of several circuits with different
operating voltage levels, such condition can cause its out-of-control performance. In
order to prevent it, the microcontroller usually has a built-in reset circuit which causes
the reset condition to occur as soon as the microcontroller goes into a brown out state of
emergency.
Reset pin is usually referred to as MCLR (Master Clear Reset). It is used for causing an
external reset of the microcontroller by applying a logic zero (0) or a logic one (1) to it,
which depends on the type of the microcontroller. In case the brown out circuit is not
built into the microcontroller, a simple external circuit for brown out reset can be
connected to the MCLR pin.
102
PIC MICROCONTROLLER
RS-232
INTERFACING USING KEYPAD:
103
PIC MICROCONTROLLER
TEMPERATURE MONITORING USING LM35 SENSOR:
PIC MUSICAL DOORBELL:
104