Upload
sarvanme
View
222
Download
0
Embed Size (px)
Citation preview
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 1/149
UNIT-II
Microcontrollers
INTRODUCTION TO PIC.
Microcontroller is a single chip micro computer made through VLSI fabrication. A
microcontroller also called an embedded controller because the microcontroller and its support
circuits are often built into, or embedded in, the devices they control. A microcontroller isavailable in different word lengths like microprocessors (4bit,8bit,16bit,32bit,64bit and 128 bit
microcontrollers are available today).
Microcontroller Chip
You can find microcontrollers in all kinds of electronic devices these days. Any device thatmeasures, stores, controls, calculates, or displays information must have a microcontroller chipinside. The largest single use for microcontrollers is in automobile industry (microcontrollers
widely used for controlling engines and power controls in automobiles). You can also find
microcontrollers inside keyboards, mouse, modems, printers, and other peripherals. In test
equipments, microcontrollers make it easy to add features such as the ability to storemeasurements, to create and store user routines, and to display messages and waveforms.
Consumer products that use microcontrollers include digital camcorders, optical players,
LCD/LED display units, etc. And these are just a few examples.
1) A microcontroller basically contains one or more following components:
Central processing unit(CPU)
Random Access Memory)(RAM)
Read Only Memory(ROM)
Input/output ports
Timers and Counters
Interrupt Controls
Analog to digital converters
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 2/149
Digital analog converters
Serial interfacing ports
Oscillatory circuits
2) A microcontroller internally consists of all features required for a computing system and
functions as a computer without adding any external digital parts in it.
3) Most of the pins in the microcontroller chip can be made programmable by the user.
4) A microcontroller has many bit handling instructions that can be easily understood by theprogrammer.
5) A microcontroller is capable of handling Boolean functions.
6) Higher speed and performance.
7) On-chip ROM structure in a microcontroller provides better firmware security.
8 ) Easy to design with low cost and small size.
Microcontroller structure
The basic structure and block diagram of a microcontroller is shown in the fig (1.1).
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 3/149
Microcontroller Structure
Image Taken From
CPU
CPU is the brain of a microcontroller .CPU is responsible for fetching the instruction, decodes it,
then finally executed. CPU connects every part of a microcontroller into a single system. Theprimary function of CPU is fetching and decoding instructions. Instruction fetched from programmemory must be decoded by the CPU.
Memory
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 4/149
The function of memory in a microcontroller is same as microprocessor. It is used to store data
and program. A microcontroller usually has a certain amount of RAM and ROM (EEPROM,EPROM, etc) or flash memories for storing program source codes.
Parallel input/output ports
Parallel input/output ports are mainly used to drive/interface various devices such as LCD‘S,
LED‘S, printers, memories, etc to a microcontroller.
Serial ports
Serial ports provide various serial interfaces between microcontroller and other peripherals like
parallel ports.
Timers/counters
This is the one of the useful function of a microcontroller. A microcontroller may have morethan one timer and counters. The timers and counters provide all timing and counting functions
inside the microcontroller. The major operations of this section are perform clock functions,modulations, pulse generations, frequency measuring, making oscillations, etc. This also can be
used for counting external pulses.
Analog to Digital Converter (ADC)
ADC converters are used for converting the analog signal to digital form. The input signal in this
converter should be in analog form (e.g. sensor output) and the output from this unit is in digital
form. The digital output can be use for various digital applications (e.g. measurement devices).
Digital to Analog Converter (DAC)
DAC perform reversal operation of ADC conversion.DAC convert the digital signal into analog
format. It usually used for controlling analog devices like DC motors, various drives, etc.
Interrupt control
The interrupt control used for providing interrupt (delay) for a working program .The interrupt
may be external (activated by using interrupt pin) or internal (by using interrupt instruction
during programming).
Special functioning block
Some microcontrollers used only for some special applications (e.g. space systems and robotics)
these controllers containing additional ports to perform such special operations. This considered
as special functioning block.
Comparison between Microprocessor and Microcontroller
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 5/149
The main comparison between microprocessor and microcontroller shown in fig (1.2)
Comparison of Micrprocessor and Microcontroller
Source Of Image
Microprocessors Microcontrollers
1 It is only a general purpose computerCPU
It is a micro computer itself
2 Memory, I/O ports, timers, interrupts
are not available inside the chip
All are integrated inside the microcontroller chip
3 This must have many additional digital
components to perform its operation
Can function as a micro computer without any
additional components.
4 Systems become bulkier and Make the system simple, economic and compact
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 6/149
expensive.
5 Not capable for handling Booleanfunctions
Handling Boolean functions
6 Higher accessing time required Low accessing time
7 Very few pins are programmable Most of the pins are programmable
8 Very few number of bit handlinginstructions
Many bit handling instructions
9 Widely Used in modern PC and
laptops
widely in small control systems
E.g. INTEL 8086,INTEL Pentium series INTEL8051,89960,PIC16F877
Advantages of Microcontrollers
The main advantages of microcontrollers are given.
a) Microcontrollers act as a microcomputer without any digital parts.
b) As the higher integration inside microcontroller reduce cost and size of the system.
c) Usage of microcontroller is simple, easy for troubleshoot and system maintaining.
d) Most of the pins are programmable by the user for performing different functions.
e) Easily interface additional RAM, ROM,I/O ports.
f) Low time required for performing operations.
Disadvantages of Microcontrollers
a) Microcontrollers have got more complex architecture than that of microprocessors.
b) Only perform limited number of executions simultaneously.
c) Mostly used in micro-equipments.
d) Cannot interface high power devices directly.
Applications
Microcontrollers are widely used in modern electronics equipments. Some basic applications of
microcontroller is given below.
a) Used in biomedical instruments.
b) Widely used in communication systems.
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 7/149
c) Used as peripheral controller in PC.
d) Used in robotics.
e) Used in automobile fields.
Introduction to Peripheral Interface Controllers (PIC)
Peripheral Interface Controllers (PIC) is one of the advanced microcontrollers developed by
microchip technologies. These microcontrollers are widely used in modern electronics
applications. A PIC controller integrates all type of advanced interfacing ports and memorymodules. These controllers are more advanced than normal microcontroller like INTEL 8051.
The first PIC chip was announced in 1975 (PIC1650). As like normal microcontroller, the PIC
chip also combines a microprocessor unit called CPU and is integrated with various types of
memory modules (RAM, ROM, EEPROM ,etc), I/O ports, timers/counters, communicationports, etc.
PIC Chip
Image From All PIC microcontroller family uses Harvard architecture. This architecture has the program and
data accessed from separate memories so the device has a program memory bus and a datamemory bus (more than 8 lines in a normal bus). This improves the bandwidth (data throughput)
over traditional von Neumann architecture where program and data are fetched from the same
memory (accesses over the same bus). Separating program and data memory further allowsinstructions to be sized differently than the 8-bit wide data word.
Basic structure of a modern Peripheral interface controller chip is show in the picture below.
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 8/149
PIC Structure
CPU
The function of CPU in PIC is same as a normal microcontroller CPU. A PIC CPU consists of
several sub units such as instruction decoder, ALU, accumulator, control unit, etc. The CPU inPIC normally supports Reduced Instruction Set Computer (RISC) architecture (Reduced
Instruction Set Computer (RISC), a type of microprocessor that focuses on rapid and efficient
processing of a relatively small set of instructions. RISC design is based on the premise that most
of the instructions a computer decodes and executes are simple. As a result, RISC architecturelimits the number of instructions that are built into the microcontroller but optimizes each so it
can be carried out very rapidly (usually within a single clock cycle.) . These RISC structure gives
the following advantages.
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 9/149
• The RISC structure only has 35 simple instructions as compared to others
• The execution time is same for most of the instructions (except very few numbers).
• The execution time required is very less (5 million instructions/second (approximately).
Memory
The memory in a PIC chip used to store the data and programs temporary or permanently. As
like normal microcontrollers, the PIC chip also has certain amount of RAM, ROM, EEPROM,other flash memory, etc.
ROM memory is used for permanent storage. The ROM memory also called as n program
memory. A PI chip has certain amount of ROM memory.
EEPROM memory is another category of ROM memory. The contents in the EEPROM changesduring run time and at that time it acts like a RAM memory. But the difference is after the
power goes off , the data remains in this ROM chip. This is the one of the special advantages of
EEPROM. In the PIC chip the function of EPROM is to store the values created during the
runtime.
RAM memory is the one of the complex memory module in a PIC chip. This memory associatedwith various type of registers (special function registers and general purpose registers) and
memory BANK modules (BANK 0, BANK 1, etc.). Once the power goes off, the contents in theRAM will be cleared. As like normal microcontrollers, the RAM memory is used to store
temporary data and provide immediate results.
Flash memory
This is a special type of memory where READ, WRITE, and ERASE operations can be done
many times. This type of memory was invented by INTEL corporation in 1980. A PIC Chipnormally contains a certain amount of flash memory.
Registers
Information is stored in a CPU memory location called a register. Registers can be thought of as
the CPU‘s tiny scratchpad, temporarily storing instructions or data. Registers basically classifiedinto the following.
1) General Purpose Register (GPR) A general purpose register (or processor register) is a small storage area available on a CPU
whose contents can be accessed more quickly than other storage that available on PIC. A generalpurpose register can store both data addresses simultaneously.
2) Special Function registers (SFR) These are also a part of RAM memory locations. As compared to GPR, their purpose is
predetermined during the manufacturing time and cannot be changed by the user. It is only forspecial dedicated functions.
Interrupts
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 10/149
Interrupt is the temporary delay in a running program. These delays stop the current execution
for a particular interval. This interval/delay is usually called as interrupt. When an interruptrequest arrives into a current execution program, then it stops its regular execution. Interrupt can
be performed by externally (hardware interrupt) or internally (by using software).
Bus
BUS is the communication or data transmission/reception path in a microcontroller unit. In anormal microcontroller chip, two types of buses are normally available.
1) Data bus
Data bus is used for memory addressing. The function of data bus is interfacing all the circuitry
components inside the PIC chip.
2) Address bus
Address bus mostly used for memory addressing. The function of address bus is to transmit theaddress from the CPU to memory locations.
USART or UART
These ports are used for the transmission (TX) and reception (RX) of data. These transmissions
possible with help of various digital data transceiver modules like RF, IR, Bluetooth, etc. This is
the one of the simplest way to communicate the PIC chip with other devices.
Oscillators
Oscillator unit basically an oscillation/clock generating circuit which is used for providing properclock pulses to the PIC chip. This clock pulses also helps the timing and counting applications .
A PIC chip normally use various types of clock generators. According to the application and the
type of PIC used, the oscillators and its frequencies may vary. RC (Resistor-Capacitor), LC(Inductor-Capacitor), RLC (Resistor-Inductor-capacitor), crystal oscillators, etc are the normal
oscillators used with A PIC chip.
STACK
The entire PIC chip has an area for storing the return addresses. This area or unit called Stack is
used in some Peripheral interface controllers. The hardware stack is not accessible by software.
But for most of the controllers, it can be easily accessible.
Input/output ports
These ports are used for the interfacing various input/output devices and memories. According to
the type of PIC, the number of ports may change.
Advanced functioning blocks
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 11/149
These sections include various advanced features of a PIC chip. According to the type of PIC,
these features may change. Various advanced features in a peripheral interface controller arepower up timer, oscillator start up timer, power on reset, watch dog timer, brown out reset, in
circuit debugger, low voltage programming, voltage comparator, CCP modules etc.
Limitations of PIC Architecture
• Peripheral Interface Controller has only one accumulator.
• Small instruction set.
• Register banking switch required to access RAM of other devices.
• Operations and registers are not orthogonal.
• Program memory is not accessible.
Advantages of PIC Controlled System
• Reliability
The PIC controlled system often resides machines that are expected to run continuously for manyyears without any error and in some cases recover by themselves if an error occurs(with help of
supporting firmware).
• Performance Many of the PIC based embedded system use a simple pipelined RISC processor for computationand most of them provide on-chip SRAM for data storage to improve the performance.
• Power consumption A PIC controlled system operates with minimal power consumption without sacrificing
performance. Power consumption can be reduced by independently and dynamically controlling
multiple power platforms.
• Memory Most of the PIC based systems are memory expandable and will help in easily adding more andmore memory according to the usage and type of application. In small applications the inbuilt
memory can be used
Architecture and Memory Organization of PIC 16F877
The basic building block of PIC 16F877 is based on Harvard architecture. This microcontrolleralso has many advanced features as mentioned in the previous post. Here you can see the basic
internal architecture and memory organisation of PIC16F877.
Architecture of PIC16F877
The figure below shows the internal architecture of a PIC16F877A chip.
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 12/149
Internal Architecture of PIC16F877A Chip
The use of each functional block inside this controller has already been explained in the previous
post. Now let us look in to the detailed explanation about each sections inside the PIC 16F877.
Memory Organization of PIC16F877
The memory of a PIC 16F877 chip is divided into 3 sections. They are
1. Program memory
2. Data memory and
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 13/149
3. Data EEPROM
1. Program memory
Program memory contains the programs that are written by the user. The program counter (PC)
executes these stored commands one by one. Usually PIC16F877 devices have a 13 bit wideprogram counter that is capable of addressing 8K×14 bit program memory space. This memory
is primarily used for storing the programs that are written (burned) to be used by the PIC. Thesedevices also have 8K*14 bits of flash memory that can be electrically erasable /reprogrammed.
Each time we write a new program to the controller, we must delete the old one at that time. The
figure below shows the program memory map and stack.
PIC16f877 Program Memory
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 14/149
Program counters (PC) is used to keep the track of the program execution by holding the address
of the current instruction. The counter is automatically incremented to the next instruction duringthe current instruction execution.
The PIC16F87XA family has an 8-level deep x 13-bit wide hardware stack. The stack space is
not a part of either program or data space and the stack pointers are not readable or writable. Inthe PIC microcontrollers, this is a special block of RAM memory used only for this purpose.
Each time the main program execution starts at address 0000 – Reset Vector. The address 0004
is ―reserved‖ for the ―interrupt service routine‖ (ISR).
2. PIC16F87XA Data Memory Organization
The data memory of PIC16F877 is separated into multiple banks which contain the general
purpose registers (GPR) and special function registers (SPR). According to the type of the
microcontroller, these banks may vary. The PIC16F877 chip only has four banks (BANK 0,
BANK 1, BANK 2, and BANK4). Each bank holds 128 bytes of addressable memory.
Data Memory Organization
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 15/149
IMAGE TAKEN FROM
The banked arrangement is necessary because there are only 7 bits are available in the instruction
word for the addressing of a register, which gives only 128 addresses. The selection of the banks
are determined by control bits RP1, RP0 in the STATUS registers Together the RP1, RP0 and
the specified 7 bits effectively form a 9 bit address. The first 32 locations of Banks 1 and 2, andthe first 16 locations of Banks2 and 3 are reserved for the mapping of the Special Function
Registers (SFR‘s).
BANK RP0 RP1
0 0 0
1 1 0
2 0 1
3 1 1
A bit of RP1 & RP0 of the STATUS register selects the bank access.
3. Data EEPROM and FLASH
The data EEPROM and Flash program memory is readable and writable during normal operation
(over the full VDD range). This memory is not directly mapped in the register file space. Instead,it is indirectly addressed through the Special Function Registers. There are six SFRs used to read
and write this memory:
• EECON1
• EECON2
• EEDATA
• EEDATH
• EEADR
• EEADRH
The EEPROM data memory allows single-byte read and writes. The Flash program memoryallows single-word reads and four-word block writes. Program memory write operations
automatically perform an erase-before write on blocks of four words. A byte write in dataEEPROM memory automatically erases the location and writes the new data (erase-before-write). The write time is controlled by an on-chip timer. The write/erase voltages are generated
by an on-chip charge pump, rated to operate over the voltage range of the device for byte or
word operations.
Register Memory Organization in PIC 16F877
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 16/149
A register is a place inside the PIC which used to read or write the data/program. The memory of
the PIC is divided into a series of registers. Each of the registers has its own address and memorylocations. These addresses are normally denoted by using hexadecimal numbers. According to
the type of working and usage, the registers in PIC are classified into two categories.
General Purpose Registers (GPR)
GPR is a small amount of storage that can be accessible more quickly than any other memory.These register files can be accessed either directly, or indirectly, through the File Select Register
(FSR). The General Purpose Register (GPR) memory map (PIC16F877A) is shown in the figure
below.
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 17/149
General Purpose Register - PIC 16F877
Special Function Registers (SFR)
The special function registers are also memory registers which is used for special dedicated
functions. These registers perform various dedicated functions inside the PIC chip. Each special
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 18/149
function inside this PIC chip is controlled by using these registers. These registers are used by
the CPU and peripheral modules for controlling the desired operation of the device. Theseregisters are normally implemented as in the form of static RAM memory. A list of these
registers is given in the tables below. The Special Function Registers can be classified into two
sets: core (CPU) and peripheral. Those registers associated with the core functions are described
in detail in this section. The figures below shows SFR memory map of PIC16F877.
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 19/149
Special Function Registers (SFR) - PIC 16F877
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 20/149
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 21/149
Special Function Registers (SFR) - PIC 16F877
Status Register
Status register is an eight bit register that contains the arithmetic status of the arithmetic logicunit (ALU), the reset status and the bank select bits for the data memory. The detailed
explanation of status register is given below.
Status registers (address 03h, 83h, 103h, and 183h)
R/W*-0 R/W-0 R/W-0 R-1 R-1 R/W-x** R/W-x R/W-x
IRP RP1 RP0 TO PD Z DC C
Bit7
Bit 0
(*R/W-readable/writable, **x-unknown bit)
Bit 7 – (IRP): this is a Register Bank Select Bit usually used for indirect addressing
mode.
Bit 6-5 (RP1:RP0): these bits are Register Bank Select bits commonly used for direct
addressing mode (each banks in this mode carry 128 byes)
(11 = Bank 3 (180h-1FFh)
10 = Bank 2 (100h-17Fh)
01 = Bank 1 (80h-FFh)
00 = Bank 0 (00h-7Fh))
Bit 4, (TO): this is a time-out bit used for timing and counting, sleep and reset functions.
(1 = after power-up, CLRWDT instruction or SLEEP instruction
0 = A WDT time-out occurred)
Bit 3, (PD): Power-down bit
(1 = after power-up or by the CLRWDT instruction
0 = by execution of the SLEEP instruction)
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 22/149
Bit 2, (Z): Zero bit
(1 = the result of an arithmetic or logic operation is zero
0 = the result of an arithmetic or logic operation is not zero.)
Bit 1 DC: Digit carry/borrow bit (ADDWF, ADDLW, SUBLW, SUBWF instructions)
(For borrow, the polarity is reversed)
(1 = A carry-out from the 4th low order bit of the result occurred
0 = No carry-out from the 4th low order bit of the result.)
Bit 0 (C): Carry/borrow bit (ADDWF, ADDLW, SUBLW, SUBWF instructions)
(1 = A carry-out from the Most Significant bit of the result occurred
0 = No carry-out from the Most Significant bit of the result occurred.)
Option Register
The option Register is a readable and writable register, which contains various control bits to
configure the TMR0 prescaler/WDT postscaler (single assignable register known also as the pre-
scaler), the external INT interrupt andTMR0 and the weak pull-ups on PORTB. Structure of
option register is shown below.
R/W-1 R/W-1 R/W-1 R/W-1 R/W-1 /W-1 R/W-1 R/W-1RBPU(inverting) INTEDG T0CS T0SE PSA S2 PS1 PS0
7
0
Bit 7 (RBPU): This is a PORTB Pull-up Enable bit. If this bit is ‗1‘ then PORTB pull-
up function disabled. If this bit is ‗0‘, it enabled the pull-up function by individual port-
latch values.
(1 = PORTB pull-ups are disabled.
0 = PORTB pull-ups are enabled by individual port latch values.)
Bit 6 (INTEDG): This is an Interrupt Edge Select bit. This bit decided if the interrupt is
on either raisin edge or falling edge. The function of this bit is given below.
(1 = Interrupt on rising edge of RB0/INT pin.
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 23/149
0 = Interrupt on falling edge of RB0/INT pin.)
Bit 5 (T0CS): this is a timer-0(TMR0) Clock Source Select bit and its function is given
below.
(1 = Transition on RA4/T0CKI pin.
0 = Internal instruction cycle clock (CLKO).)
Bit 4 (T0SE): TMR0 Source Edge Select bit which select the timer 0 source edge.
(1 = Increment on high-to-low transition on RA4/T0CKI pin.
0 = Increment on low-to-high transition on RA4/T0CKI pin.)
Bit 3 (PSA): Prescaler Assignment bit.
(1 = Prescaler is assigned to the Watch Dog Timer (WDT).
0 = Prescaler is assigned to the Timer0 module.)
Bit 2-0 (PS2:PS0): Prescaler Rate Select bits.
INTCON Register
The INTCON register is a readable and writable register, which contains various enable and flag
bits for the
TMR0 register overflow, RB port change and external RB0/INT pin interrupts. The architecture
of this register is given below.
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-x
GIE PEIE TMR0IE INTE RBIE TMR0IF INTF RBIF
Bit 7 GIE: Global Interrupt Enable bit. If this bit is enable (‗1‘), which also enable allunmasked interrupts and if it is zero (‗0‘), which disable all interrupts.
(1 = Enables all unmasked interrupts.
0 = Disables all interrupts.)
Bit 6 (PEIE): this is a Peripheral Interrupt Enable bit which used for controlling
peripheral interrupts. If this bit is enable(‗1‘), also enable all unmasked peripheral
interrupts and if it is disable(‗0‘), also disable all active peripheral interrupt actions.
(1 = Enables all unmasked peripheral interrupts
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 24/149
0 = Disables all peripheral interrupts)
Bit 5 (TMR0IE): This is timer 0(TMR0) Overflow Interrupt Enable bit which control the
overflow interrupt in timer 0.
(1 = Enables the TMR0 interrupt
0 = Disables the TMR0 interrupt)
Bit 4 (INTE): This is an RB0/INT External Interrupt Enable bit which used for
enable/disable external interrupts.
(1 = Enables the RB0/INT external interrupt
0 = Disables the RB0/INT external interrupt)
Bit 3 (RBIE): RB Port Change Interrupt Enable bit which control PORTB changeinterrupt.
(1 = Enables the RB port change interrupt.
0 = Disables the RB port change interrupt.)
Bit 2 (TMR0IF): TMR0 Overflow Interrupt Flag bit which controls the overflow of timer
0.
(1 = TMR0 register has overflowed [must be cleared in software]
0 = TMR0 register did not overflow)
Bit 1 (INTF): RB0/INT External Interrupt Flag control bit.
(1 = The RB0/INT external interrupt occurred (must be cleared in software)
0 = The RB0/INT external interrupt did not occur).
Bit 0 (RBIF): RB Port Change Interrupt Flag bit.
(1 = At least one of the RB7:RB4 pins changed state; a mismatch condition will continue to setthat bit. Reading PORTB will end the mismatch condition and allow the bit to be cleared
[Must be cleared in software] ).
PIE1 Register
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 25/149
The PIE1 register contains the individual enable bits for the peripheral interrupts. The structure
of this register is shown below.
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
PSPIE ADIE RCIE TXIE SSPIE CCP1IE TMR2IE TMR1IE
Bit 7 (PSPIE): this bit is the Parallel Slave Port Read/Write Interrupt Enable bit
(1 = Enables the PSP read/write interrupt
0 = Disables the PSP read/write interrupt)
Bit 6 (ADIE): A/D Converter Interrupt Enable bit which control the analog to digital
converter interrupt.
(1 = Enables the A/D converter interrupt
0 = Disables the A/D converter interrupt)
Bit 5 (RCIE): USART Receive Interrupt Enable bit which control the USART datareception interrupt.
(1 = Enables the USART receive interrupt
0 = Disables the USART receive interrupt)
Bit 4 (TXIE): USART Transmit Interrupt Enable bit that control USART data
transmission.
(1 = Enables the USART transmit interrupt
0 = Disables the USART transmit interrupt)
Bit 3 (SSPIE): Synchronous Serial Port Interrupt Enable bit that control SSP data
interrupt.
(1 = Enables the SSP interrupt
0 = Disables the SSP interrupt)
Bit 2 (CCP1IE): CCP1 Interrupt Enable bit which control the capture-compare-pulsewidth modulation interrupt.
(1 = Enables the CCP1 interrupt
0 = Disables the CCP1 interrupt)
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 26/149
Bit 1 (TMR2IE): TMR2 to PR2 Match Interrupt Enable bit.
(1 = Enables the TMR2 to PR2 match interrupt
0 = Disables the TMR2 to PR2 match interrupt)
Bit 0 (TMR1IE): TMR1 Overflow Interrupt Enable bit that control the overflow interruptof timer 1 module.
(1 = Enables the TMR1 overflow interrupt
0 = Disables the TMR1 overflow interrupt)
PIR1 Register
The PIR1 register contains the individual flag bits for the peripheral interrupt. The structure of
PIR1 register is given below.
R/W-0 R/W-0 R-0 R-0 R/W-0 R/W-0 R/W-0 R/W-0
PSPIF ADIF RCIF TXIF SSPIF CCP1IF TMR2IF TMR1IF
Bit 7 (PSPIF): Parallel Slave Port Read/Write Interrupt Flag bit.
(1 = A read or a write operation has taken place (must be cleared in software)
0 = No read or write has occurred)
Bit 6 (ADIF): A/D Converter Interrupt Flag bit that control the interrupt flag for thatanalog to digital converter.
(1 = An A/D conversion completed
0 = The A/D conversion is not complete)
Bit 5 (RCIF): USART Receive Interrupt Flag bit.
(1 = The USART receive buffer is full
0 = The USART receive buffer is empty)
Bit 4 (TXIF): USART Transmit Interrupt Flag bit.
(1 = The USART transmit buffer is empty
0 = The USART transmit buffer is full)
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 27/149
Bit 3 (SSPIF): Synchronous Serial Port (SSP) Interrupt Flag bit that control the SSP
interrupt flag in a PIC.
(1 = The SSP interrupt condition has occurred and must be cleared in software before returning
from the Interrupt Service Routine. The conditions that will set this bit are:
• SPI – A transmission/reception has taken place.
• I2C Slave – A transmission/reception has taken place.
• I2C Master
- A transmission/reception has taken place.
- The initiated Start condition was completed by the SSP module.
- The initiated Stop condition was completed by the SSP module.
- The initiated Restart condition was completed by the SSP module.
- The initiated Acknowledge condition was completed by the SSP module.
- A Start condition occurred while the SSP module was Idle (multi-master system).
- A Stop condition occurred while the SSP module was Idle (multi-master system).
0 = No SSP interrupt condition has occurred)
Bit 2 (CCP1IF): CCP1 Interrupt Flag bit that control capture-compare-pulse width
modulation interrupt flag. It works in three modes. They are given below.
1. Capture mode:
1 = A TMR1 register capture occurred (must be cleared in software)
0 = No TMR1 register capture occurred
2. Compare mode:
1 = A TMR1 register compare match occurred (must be cleared in software)
0 = No TMR1 register compare match occurred
3. PWM mode:
Bit 1 (TMR2IF): TMR2 to PR2 Match Interrupt Flag bit
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 28/149
(1 = TMR2 to PR2 match occurred (must be cleared in software)
0 = No TMR2 to PR2 match occurred)
Bit 0 (TMR1IF): TMR1 Overflow Interrupt Flag bit.
(1 = TMR1 register overflowed (must be cleared in software)
0 = TMR1 register did not overflow)
PIE2 Register
The PIE2 register contains the individual enable bits for the CCP2 peripheral interrupt, the SSP
bus collision
Interrupt, EEPROM write operation interrupt and the comparator interrupt. The structure of this
register is given below.
U-0 R/W-0 U-0 R/W-0 R/W-0 U-0 U-0 R/W-0
————— CMIE ————— EEIE BCLIE ————
— -
————— CCP2IE
Bit 7 Unimplemented: Read as ‗0‘
Bit 6 (CMIE): Comparator Interrupt Enable bit
(1 = Enables the comparator interrupt
0 = Disable the comparator interrupt)
Bit 5 Unimplemented: Read as ‗0‘
Bit 4 (EEIE): EEPROM Write Operation Interrupt Enable bit
(1 = Enable EEPROM write interrupt
0 = Disable EEPROM write interrupt)
Bit 3 (BCLIE): Bus Collision Interrupt Enable bit.
(1 = Enable bus collision interrupt
0 = Disable bus collision interrupt)
Bit 2-1 Unimplemented: Read as ‗0‘
Bit 0 (CCP2IE): CCP2 Interrupt Enable bit.
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 29/149
(1 = Enables the CCP2 interrupt
0 = Disables the CCP2 interrupt)
PIR2 Register
The PIR2 register contains the flag bits for the CCP2 interrupt, the SSP bus collision interrupt,EEPROM write operation interrupt and the comparator interrupt. The structure of this register is
given below.
U-0 R/W-0 U-0 R/W-0 R/W-0 U-0 U-0 R/W-0
————— CMIF ————— EEIF BCLIF ————
-
————— CCP2IF
Bit 7 Unimplemented: Read as ‗0‘
Bit 6 (CMIF): Comparator Interrupt Flag bit
(1 = the comparator input has changed (must be cleared in software)
0 = the comparator input has not changed)
Bit 5 Unimplemented: Read as ‗0‘
Bit 4 (EEIF): EEPROM Write Operation Interrupt Flag bit.
(1 = the write operation completed (must be cleared in software)
0 = the write operation is not complete or has not been started)
Bit 3 (BCLIF): Bus Collision Interrupt Flag bit.
(1 = A bus collision has occurred in the SSP when configured for I2C Master Mode
0 = No bus collision has occurred)
Bit 2-1 Unimplemented: Read as ‗0‘
Bit 0 (CCP2IF): CCP2 Interrupt Flag bit. This also works in three modes. They ere
1. Capture mode:
1 = A TMR1 register capture occurred (must be cleared in software)
0 = No TMR1 register capture occurred
Compare mode:
1 = A TMR1 register compare match occurred (must be cleared in software)
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 30/149
0 = No TMR1 register compare match occurred
2. PWM mode:
This mode is not used.
PCON Register
The Power Control (PCON) register contains flag bits to allow differentiation between a Power-on Reset
(POR), a Brown-out Reset (BOR), a Watchdog Reset (WDT) and an external MCLR Reset. Thestructure of this register is given below.
U-0 U-0 U-0 U-0 U-0 U-0 R/W-0 R/W-1
—— —— - —— - —— - —— - ——— POR(inverting) BOR(inverting)
Bit 7-2 Unimplemented: Read as ‗0‘
Bit 1 (POR): Power-on Reset Status bit
(1 = No Power-on Reset occurred
0 = A Power-on Reset occurred (must be set in software after a Power-on Reset occurs)
Bit 0(BOR): Brown-out Reset Status bit
(1 = No Brown-out Reset occurred
0 = A Brown-out Reset occurred (must be set in software after a Brown-out Reset occurs).
ADDRESSING MODES:
• There are 3 types of addressing modes in PIC
Immediate Addressing
Movlw H‘0F‘
Direct Addressing
• Uses 7 bits of 14 bit instruction to identify a register file address
• 8th
and 9th
bit comes from RP0 and RP1 bits of STATUS register.
• Exp:
Z equ D‘2‘
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 31/149
btfss STATUS, Z
Indirect Addressing
• Full 8 bit register address is written the special function register FSR
• INDF is used to get the content of the address pointed by FSR• Exp : A sample program to clear RAM locations H‘20‘ – H‘2F‘ .
Instruction Sets in PIC
Instruction sets are the source codes that are written by the programmer for performing the
desired operations in a PIC chip. These codes can be usually written in any of the programminglanguages such as C, C++, assembly languages, and so on. The instruction set commands are
pre-determined for each and every function with its own command syntaxes and are executed by
the PIC chip. PIC chips are normally use Reduced Instruction Set Programming that only
contain 35 simple instruction sets that are much easier to learn by the programmer as comparedto CISC instruction set. According to the type of instruction, the instruction sets can be
classified into 5 groups. Here in this first section you can get the basics of computerprogramming by using various instruction sets
The instruction sets in PIC is developed by the basis of RISC structure. The instruction sets can
be classified into 5 separate categories (depends on the basis of type of operation). They are
1) DATA TRANSFER GROUP
2) ARITHMETIC AND LOGIC OPERATIONS GROUP
3) BIT OPERATION GROUP INSTRUCTIONS
4) PROGRAM FLOW CONTROL
Data Transfer Group Instructions in PIC
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 32/149
Data transfer group instructions are one of the major instructions widely used in PIC
programming for data transfer purposes. By using these types of instructions, we can move orchange the value (bits) from one location to another.
Data Transfer Instructions with Syntaxes
1. MOVLW
“MOVLW” instruction is used to write constant in W register (move the value from literal to W
register).
Syntax:
Label MOVLW k
Description:
8 bit constant is written in W reg.
Operation:
k to (W)
Operand:
0 < k < 255
No. of words: 1 No. cycles: 1
Flags: Nil
2. MOVWF
MOVWF instruction is used to move the data (bits) from W register to flag register F
(copy/move the value from W register to F register).
Syntax:
Label MOVWF f
Description:
Content of W is copied into f register (flag register).
Operation:
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 33/149
W to (f) (W register to Flag register)
Operand:
0 < f < 127
No. of words: 1
No. cycles: 1
Flags: Nil
3. MOVF
MOVF command is used for copy/move the contents (bits) in the flag register to D register
(Copy f to d register).
D register (destination register) is a special register which can be switchable in its destination
according to its status. If the status of D register is ‗0‘, the destination is W register and if thestatus is ‗1‘, the destination of D register became F register (flag)
Syntax:
Label MOVF f, d
Description:
Content of f is copied into destination.
If d = 0, the destination is W register
If d = 1, the destination is f register
Operation:
F to (D)
Operand:
0 < k < 127
No. of words: 1
No. cycles: 1
Flags: Z
4. CLRW
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 34/149
CLRW is a clearing instruction that helps to reset the values of W register to ‗0‘ (write ‗0‘ in W
register).
Syntax:
Label CLRW
Description:
Zero is copied into W register
Z flag in status register is set to one
Operation:
0 to (W)
Operand: nil
No. of words: 1
No. cycles: 1
Flags: Z
5. CLRF f
CLRF f Write ‗0‘ in F register that helps to reset the current status to ‗0‘
Syntax:
Label CLRF f
Description:
Zero is copied into f register
Z flag in status register is set to one
Operation:
0 to (f)
Operand: nil
No. of words: 1
No. cycles: 1
Flags: Z
6. SWAPF
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 35/149
SWAPF used for swap (interchanging functions) functions which Swap the nibbles (4bits).The
destination of this function depends on the destination register status.
Syntax:
Label SWAPF f, d
Description:
Upper, Lower nibbles are exchanged
If d = 0, the destination is W register
If d = 1, the destination is f register
Operation:
f (0:3) to d(4:7) and f(4:7) to d(0:3)
Operand:
0 < f < 127
No. of words: 1
No. cycles: 1
Flags: –
ARITHMETICAL AND LOGICAL OPERATIONSGROUP
In this article, the basic arithmetic and loguc operations that are carried out by a PIC is
explained in detail.
Arithmetic and logic operation group instructions are used for performing all arithmetic
operations and logic operations. By using these types of instructions, the PIC chip can easily
perform all arithmetic and logic operations inside the micro controller (PIC). The arithmetic
operations are addition (ADD), subtraction (SUB), multiplication (MUL), division (DIV) and
logical operations are AND, OR, NOT, XOR, and so on. The basic Arithmetical and Logicaloperations that are performed by a PIC is given below.
1) ADDLW
―ADDLW‖ instruction is used for performing addition operation (adding a constant with Wregister). By using this instruction, we can add two bits easily and the result value can be stored
in another register or memory location.
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 36/149
Syntax: Label ADDLW k
Description: Given constant is added with W reg.
Operation: (w) + k to w
Operand: 0 < k < 255
No. of words: 1
No. cycles: 1
Flags: C, DC, Z
2) ADDWF
―ADDWF‖ is also used for performing the addition operation. This ADDWF instruction adds theconstant with W register.
Syntax: Label ADDWF f, d
Description: Add W reg. content with f register
Operation: (w) + (f) to w if d = 0 and (w) + (f) to f if d = 1
Operand: 0 < f < 127
No. of words: 1
No. cycles: 1
Flags: C, DC, Z
3) SUBLW
―SUBLW‖ used for performing subtraction function which can be subtracting two values andcan be stored to another memory location. This instruction helps to Subtract W content from
given constant.
Syntax: Label SUBLW k
Description: W reg. content is subtracted from k
Operation: k – (w) to w
Operand: 0 < k < 255
No. of words: 1
No. cycles: 1
Flags: C, DC, Z
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 37/149
4) SUBWF
SUBWF is used for performing subtraction operation. In SUBLW, this instruction Subtracts Wcontent from f register.
Syntax: Label SUBWF f
Description: W reg. content is subtracted from f
Operation: f – (w) to w if d = 0 and f – (w) to f if d = 1
Operand: 0 < f < 127
No. of words: 1
No. cycles: 1
Flags: C, DC, Z
5) ANDLW
ANDLW is a logical instruction which used for performing Logic AND. By using thisinstruction helps AND the constant with W.
Syntax: Label ANDLW k
Description: Given constant is .and. with W reg.
Operation: (w) .and. k to w
Operand: 0 < k < 255
No. of words: 1
No. cycles: 1
Flags: Z
6) IORLW
This command is used for performing logical OR operation. By using this instruction, it willperform Logical OR operation with W register.
Syntax: Label IORLW k
Description: Given constant is .or. with W reg.
Operation: (w) .or. k to w
Operand: 0 < k < 255
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 38/149
No. of words: 1
No. cycles: 1
Flags: Z
7) IORWF
Logic OR the W reg. with f
Syntax: Label IORWF f, d
Description: W reg. is .or. with f reg.
Operation: (w) .and. f to w, if d = 0 and (w) .and. f to f, if d = 1
Operand: 0 < f < 127
No. of words: 1 No. cycles: 1
Flags: Z
8 ) XORLW
This command is used for performing logical XOR operation. By using this command, it will
perform logical XOR with Logic constant and W register.
Syntax: Label XORLW k
Description: Given constant is .XOR. with W reg.
Operation: (w) .xor. k to w
Operand: 0 < k < 255
No. of words: 1
No. cycles: 1
Flags: Z
9) XORWF
This command used to perform Logic XOR the W reg. with f
Syntax: Label XORWF f, d
Description: W reg. is .xor. with f reg.
Operation: (w) .and. f to w, if d = 0 and (w) .and. f to f, if d = 1
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 39/149
Operand: 0 < f < 127
No. of words: 1
No. cycles: 1
Flags: Z
10) INCF
INCF command used for performing increment operations.(Increment f registers content)
Syntax: Label INCF f, d
Description: Increment the content of f register
Operation: (f) + 1 to w, if d = 0 and (f) + 1 to f, if d = 1
Operand: 0 < f < 127
No. of words: 1
No. cycles: 1
Flags: Z
11) DECF
DECF command used for performing Decrement f register content
Syntax: Label DECF f, d
Description: Decrement the content of f register
Operation: (f) – 1 to w, if d = 0 and (f) – 1 to f, if d = 1
Operand: 0 < f < 127
No. of words: 1
No. cycles: 1
Flags: Z
12) RLF
RLF command is used for performing rotate register content left through Carry
Syntax: Label RLF f, d
Description: Rotate f content left through Carry
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 40/149
Operation: Result to w, if d = 0 and Result to f, if d = 1
Operand: 0 < f < 127
No. of words: 1
No. cycles: 1 Flags: C
13) RRF
RRF command used for perform Rotate register content right through Carry
Syntax: Label RRF f, d
Description: Rotate f content right through Carry
Operation: Result to w, if d = 0 and Result to f, if d = 1
Operand: 0 < f < 127
No. of words: 1
No. cycles: 1
Flags: C
14) COMF
COMF command for perform Complement f registers content
Syntax: Label COMF f, d
Description: Complement the register content
Operation: Result to w, if d = 0 and Result to f, if d = 1
Operand: 0 < f < 127
No. of words: 1
No. cycles: 1
Flags: Z
Bit Operation Group
1) BCF
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 41/149
BCF is a resetting command instruction used for performing reset operations for a specified bit
or specified register (simply called bit clearing flag or bit clearing command). Normally BCFresets the specified bit in f registers content.
Syntax: Label BCF f, b
Description: Reset the specified bit of register f Operation: Result to f
Operand: 0 < f < 127 and 0 < b < 7
No. of words: 1
No. cycles: 1
Flags: nil
2 ) BSF
BSF is the inversing operation of BCF. This is also a bitwise operation. The BSF instruction willset the specified bit in the f register (simply called Bit Set Flag or Bit Set command).
Syntax: Label BSF f, b
Description: Set the specified bit of register f
Operation: Result to f
Operand: 0 < f < 127 and 0 < b < 7
No. of words: 1
No. cycles: 1
Flags: nil
PROGRAM FLOW CONTROL
1) BTFSC
BTFSC is a special type program flow instruction which control the current program flow.
Normally BTFSC Test the bit in f, skip if it is zero.
Syntax: Label BTFSC f, b
Description: Test the specified bit of register f, skip the next instruction if it is zero
Operation: Skip the next instruction if f (b) = 0
Operand: 0 < f < 127 and 0 < b < 7
No. of words: 1 No. cycles: 1 or 2 depends on bit value
Flags: NIL
2) BTFSS
BTFSS also program flow control instruction. This instruction Test the bit in f, skip if it is one
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 42/149
Syntax: Label BTFSS f, b
Description: Test the specified bit of register f, skip the next instruction if it is one
Operation: Skip the next instruction if f (b) = 1
Operand: 0 < f < 127 and 0 < b < 7
No. of words: 1
No. cycles: 1 or 2 depends on bit value Flags: nil
3) INCFSZ
INCFSZ is a content increment command which Increment f content, skip if it is zero
Syntax: Label INCFSZ f, d
Description: Increment the f content, skip the next instruction if f is zero
Operation: Skip the next instruction if f = zero
Operand: (f) + 1 = w if d = 0 and (f) + 1 = f if d = 1 No. of words: 1
No. cycles: 1 or 2 depends on bit value
Flags: nil
4) DECFSZ
DECFSZ command Decrement f content, skip if it is zero
Syntax: Label DECFSZ f, d
Description: Decrement the f content, skip the next instruction if f is zero
Operation: Skip the next instruction if f = zero Operand: (f) – 1 = w if d = 0 and (f) – 1 = f if d = 1
No. of words: 1
No. cycles: 1 or 2 depends on bit value
Flags: nil
5) GOTO
GOTO instruction is used for Jump to specified address locations.
Syntax: Label GOTO Label
Description: Unconditional jump to specified label Operation: k to PC(10:0), PCLATH(4:3) to PC(12:11)
Operand: 0 < k < 2048
No. of words: 1
No. cycles: 2
Flags: nil
6) CALL
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 43/149
CALL command is used for Call the required sub-program or other values.
Syntax: Label CALL Label
Description: Unconditional call the label
Operation: (PC) + 1 to Top of stack, k to PC(10:0), PCLATH(4:3) to PC(12:11)
Operand: 0 < k < 2048 No. of words: 1
No. cycles: 2
Flags: nil
7) RETURN
RETURN command is used for Return to main program from any other sub programs
Syntax: Label RETURN
Description: Unconditional return from subroutine
Operation: Top of stack to (PC) Operand: nil
No. of words: 1
No. cycles: 2
Flags: nil
8 )RETLW
RETLW is also a return command. By using this command, Return to main program with k in w
reg .
Syntax: Label RETLW k Description: Unconditional return from subroutine
Operation: Top of stack to (PC) and k loaded in w register
Operand: 0 < k < 255
No. of words: 1
No. cycles: 2
Flags: nil
9) RETFIE
RETFIE used to return from interrupt routine
Syntax: Label RETFIE
Description: Unconditional return from subroutine
Operation: Top of stack to (PC) and Global Interrupt bit is enabled
Operand: nil
No. of words: 1
No. cycles: 2
Flags: nil
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 44/149
Other Instructions in PIC
1) NOP
NOP command used for denoting No Operation
Syntax: Label NOP
Description: No operation
Operation: nil
Operand: nil
No. of words: 1
No. cycles: 1
Flags: nil
2) CLRWDT
CLRWDT command used for Initialize watchdog time feature .
Syntax: Label CLRWDT
Description: Watchdog timer and pre-scalar is reset and TO and PD are set
Operation: 0 to WDT, 0 to pre-scalar and Status bits TO and PD are set
Operand: TO and PD
No. of words: 1
No. cycles: 1
Flags: nil
3) SLEEP
SLEEP command used for initialize Standby mode.
Syntax: Label SLEEP
Description: Goes into low consumption, OSC is stopped, Watchdog timer and pre-scalar is reset and TO and PD bits are set
Operation: 0 to WDT, 0 to pre-scalar and Status bits, TO is set and PD is reset
Operand: TO and PD
No. of words: 1
No. cycles: 1
Flags: nil
PROGRANMMING IN PIC
1.To write a C program to perform the arithmetic operations addition, subtraction, multiplication,
division in 8051.
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 45/149
ALGORITHM:
Step 1: Start the program.
Step 2: Declare the header file.
Step 3: Initializing port0 for addition and the output is stored in P0.
Step 4: Initializing port1 for subtraction and the output is stored in P1.
Step 5: Initializing port2 for multiplication and the output is stored in P2.
Step 6: Initializing port3 for division and the output is stored in P3.
Step 7: Stop the program.
PROGRAM:
#include <reg51.h>
void main(void)
P0=0x35 + 0x0F;
P1=0x04 - 0x68;
P2=0x54 / 0x78;
P3=0x55*0x10;
2.To write a C program to convert hexadecimal number into a decimal number in 8051.
ALGORITHM:
Step 1: Start the program.
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 46/149
Step 2: Declare the header file.
Step 3: Declare the variables.
Step 4: perform division & modulus operations.
Step 5: store the values in ports P0, P1, P2.
Step 6: Stop the program.
PROGRAM:
#include <reg51.h>
Unsigned char w, x, y, z;
Unsigned char HD=0x96;
void main()
w=HD/10;
x=HD%10;
y=w%10;
z=w/10;
P0=x;
P1=y;
P2=z
3.To write a C program to perform the logical operations AND, OR, EX-OR and SHIFT operations in 8051.
ALGORITHM:
Step 1: Start the program.
Step 2: Declare the header file.
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 47/149
Step 3: Initializing port0 for AND operation and the output is stored in P0.
Step 4: Initializing port1 for OR operation and the output is stored in P1.
Step 5: Initializing port2 for EX-OR operation and the output is stored in P2.
Step 6: Giving an input in port0 and inverting it and storing the output in P0.
Step 7: Giving an input in port1 and shifting it right three times and storing the output in P1.
Step 8: Giving an input in port2 and shifting it right four times and storing the output in P2.
Step 9: Giving an input in port0 and shifting it left four times and storing the output in P0.
Step 10: Stop the program.
PROGRAM:
#include <reg51.h>
void main(void)
P0=0x35 & 0x0F;
P1=0x04 | 0x68;
P2=0x54 ^ 0x78;
P0=~0x55;
P1=0x9A >> 3;
P2=0x77 >> 4;
P0=0x6 << 4;
4. To write a C program to perform the 2’s complement operation in 8051.
ALGORITHM:
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 48/149
Step 1: Start the program.
Step 2: Declare the header file.
Step 3: declare the variable x.
Step 4: perform one’s complement and add one and store the result in P0.
Step 5: Stop the program
PROGRAM:
#include <reg51.h>
Unsigned char x=oxFE
void main()
x=~x;
x=x+1;
P0=x;
RAM AND ROM ALLOCATION
MEMORY
The PIC16F887 has three types of memory ROM, RAM and EEPROM. All of them will be separately discussed since
each has specific functions, features and organization.
ROM MEMORY
ROM memory is used to permanently save the program being executed. This is why it is often called ‘program
memory’. The PIC16F887 has 8Kb of ROM (in total of 8192 locations). Since the ROM memory is made with FLASH
technology, its contents can be changed by providing a special programming voltage (13V).
However, it is not necessary to explain it in detail as being automatically performed by means of a special program on
the PC and a simple electronic device called the programmer.
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 49/149
EEPROM MEMORY
Similar to program memory, the contents of EEPROM is permanently saved, even when the power goes off.
However, unlike ROM, the contents of EEPROM can be changed during the operation of the microcontroller. This is
why this memory (256 locations) is perfect for permanently saving some of the results created and used during the
operation.
RAM MEMORY
This is the third and the most complex part of microcontroller memory. In this case, it consists of two parts: general-
purpose registers and special-function registers (SFR). All these registers are divided in four memory banks to be
explained later in the chapter.
Even though both groups of registers are cleared when power goes off and even though they are manufactured in the
same manner and act in a similar way, their functions do not have many things in common.
Timer
Many times, we plan and build systems that perform various processes that depend on time.
Simple example of this process is the digital wristwatch. The role of this electronic system is to
display time in a very precise manner and change the display every second (for seconds), every
minute (for minutes) and so on.
To perform the steps we've listed, the system must use a timer, which needs to be very accuratein order to take necessary actions.The clock is actually a core of any electronic system.
In this PIC timer module tutorial we will study the existing PIC timer modules. Themicrocontroller PIC16F877 has 3 different timers:
PIC Timer0
PIC Timer1
PIC Timer2
We can use these timers for various important purposes. So far we used ―delay procedure‖ toimplement some delay in the program, that was counting up to a specific value, before the
program could be continued. "Delay procedure" had two disadvantages:
we could not say exactly how long the Delay procedure was in progress
we could not perform any further steps while the program executes the "delay procedure"
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 50/149
Now, using Timers we can build a very precise time delays which will be based on the system
clock and allow us to achieve our desired time delay well-known in advance.In order for us to know how to work with these timers, we need to learn some things about each
one of them. We will study each one separately.
PIC Timer0
The Timer0 module timer/counter has the following features:
8-bit timer/counter
Readable and writable
8-bit software programmable prescaler
Internal (4 Mhz) or external clock select
Interrupt on overflow from FFh to 00h
Edge select (rising or falling) for external clock
Let‘s explain the features of PIC Timer0 we have listed above:
Timer0 has a register called TMR0 Register, which is 8 bits of size.
We can write the desired value into the register which will be increment as the program
progresses. Frequency varies depending on the Prescaler. Maximum value that can be assignedto this register is 255.
TMR0IF - TMR0 Overflow Interrupt Flag bit. The TMR0 interrupt is generated when the TMR0 register overflows from FFh to 00h. This
overflow sets bit TMR0IF (INTCON<2>). You can initialize the value of this register to what
ever you want (not necessarily "0").
We can read the value of the register TMR0 and write into. We can reset its value at any givenmoment (write) or we can check if there is a certain numeric value that we need (read).
Prescaler - Frequency divider.
We can use Prescaler for further division of the system clock. The options are:
1:2
1:4
1:8
1:16
1:32 1:64
1:128
1:256
The structure of the OPTION_REG register
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 51/149
We perform all the necessary settings with OPTION_REG Register. The size of the
register is 8 bits. Click the link to explore the relevant bits of OPTION_REG Register
Initializing the OPTION_REG register
The following is an example how we can initialize the OPTION_REG:
1. PSA=0; // Prescaler is assigned to the Timer0 module
2. PS0=1; // Prescaler rate bits
3. PS1=1; // are set to “111” 4. PS2=1; // which means divide by 256
5. TOSE=0; // rising edge6. TOCS=0; // Internal instruction cycle clock
Block diagram of the PIC Timer0 / WDT prescaler
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 52/149
PIC TIMER0 block diagram
Calculating Count, Fout, and TMR0 values
If using INTERNAL crystal as clock, the division is performed as follow:
PIC TIMER0 formula for internal clock
Fout – The output frequency after the division.
Tout – The Cycle Time after the division.
4 - The division of the original clock (4 MHz) by 4, when using internal crystal as
clock (and not external oscillator).
Count - A numeric value to be placed to obtain the desired output frequency - Fout.
(256 - TMR0) - The number of times in the timer will count based on the registerTMR0.
An example of INTERNAL crystal as clock
Suppose we want to create a delay of 0.5 second in the our program using Timer0.
What is the value of Count?
Calculation:
First, let’s assume that the frequency division by the Prescaler will be 1:256. Second,let’s set TMR0=0. Thus:
Formula to calculate Cout using Timer0
If using EXTERNAL clock source (oscillator), the division is performed as follow:
PIC TIMER0 formula for external clock
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 53/149
In this case there is no division by 4 of the original clock. We use the external
frequency as it is.
An example of EXTERNAL clock source (oscillator):
What is the output frequency - Fout, when the external oscillator is 100kHz andCount=8?
Calculation:
First, let’s assume that the frequency division by the Prescaler will be 1:256. Second,
let’s set TMR0=0. Thus:
Formula to calculate Fout for Timer0
Delay of 1 sec using Timer0
The following simple program creates a delay of 1 sec using Timer0:
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 54/149
PIC Timer1 tutorial
The Timer1 module, timer/counter, has the following features:
16-bit timer/counter consisting of two 8-bit registers (TMR1H and TMR1L)
readable and writable 8-bit software programmable prescaler
Internal (4 Mhz) or external clock select
Interrupt on overflow from FFFFh to 0000h
Let‘s explain the features of PIC Timer1 we have listed above:
Timer1 has a register called TMR1 register, which is 16 bits of size.
Actually, the TMR1 consists of two 8-bits registers:
TMR1H
TMR1L
It increments from 0000h to the maximum value of 0xFFFFh (or 0 b1111 1111 1111 1111 or
65,535 decimal). The TMR1 interrupt, if enabled, is generated on overflow which is latched ininterrupt flag bit, TMR1IF (PIR1<0>). This interrupt can be enabled/disabled by setting/clearing
TMR1 interrupt enable bit, TMR1IE (PIE1<0>). You can initialize the value of this register to
what ever you want (not necessarily "0").
TMR1IF – TMR1 overflow Interrupt Flag bit.
This flag marks the end of ONE cycle count. The flag need to be reset in the software if youwant to do another cycle count. We can read the value of the register TMR1 and write into. We
can reset its value at any given moment (write) or we can check if there is a certain numericvalue that we need (read).
Prescaler – Frequency divider.
We can use Prescaler for further division of the system clock. The size of the register is 2-bit
only, so you can make four different division. The options are:
1:1
1:2
1:4
1:8
You can choose whether to use an internal system clock (crystal) or external oscillator that canbe connected to a pin RC0.
The structure of the T1CON register
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 55/149
We perform all the necessary settings with T1CON register. As we can see, the size of the
register is 8 bits. Let‘s explore the relevant bits:
Initializing the T1CON register
The following is an example how we can initialize the T1CON register:
1. TMR1ON=1; // the timer is enable
2. TMR1CS=0; // internal clock source
3. T1CKPS0=0; // Prescaler value set to ―00‖
4. T1CKPS1=0; // which means 1:1 (no division)
Or you can set all the T1CON register at once as follows:T1CON=0b00000001;
CLICK here for more information about PIC TIMER 1 Module
Block diagram of the PIC Timer1
PIC TIMER1 block diagram
Calculating Count, Fout, and Timer1 values
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 56/149
If using INTERNAL crystal as clock, the division is performed as follow:
PIC TIMER1 formula for internal clock
Fout – The output frequency after the division.
Tout – The Cycle Time after the division.
4 - The division of the original clock (4 MHz) by 4, when using internal crystal as clock (and notexternal oscillator).
Count - A numeric value to be placed to obtain the desired output frequency - Fout.
(256 - TMR1) - The number of times in the timer will count based on the register TMR0.
If using EXTERNAL clock source (oscillator), the division is performed as follow:
PIC TIMER1 formula for external clock
Simple example and calculation of how to use TIMER1:
Suppose we want to create a delay of 2 second in the our program using Timer1. What is the
value of Count?
Calculation:
First, let‘s assume that the frequency division by the Prescaler will be 1:1. Second, let‘s setTMR1=0, which means the TMR1 will count 65,536 times. Thus:
Formula to calculate Cout for Timer1
Delay of 1 sec using Timer1
The following simple program creates a delay of 1 sec using TIMER1:
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 57/149
#include<pic.h>
int Count = 0;void main (void)T1CON = 0b00000001;while (1)while (! TMR1IF);TMR1IF = 0;Count ++;if (Count == 15)Count = 0;
PIC Timer2 tutorial
The Timer2 module, timer/counter, has the following features:
two 8-bit registers (TMR2 and PR2)
readable and writable
a prescaler and a postscaler
connected only to an internal clock - 4 MHz crystal
Interrupt on overflow
Let‘s explain the features of PIC Timer2 we have listed above:
• Timer2 has 2 count registers: TMR2 and PR2. The size of each registers is 8-bit in which we
can write numbers from 0 to 255. The TMR2 register is readable and writable and is cleared onany device Reset. PR2 is a readable and writable register and initialized to FFh upon Reset.
Register TMR2 is used to store the "initial" count value (the value from which it begins to
count). Register PR2 is used to store the "ending" count value (the maximum value we
need/want to reach). ie: using Timer2 we can determine the started count value, the final countvalue, and the count will be between these two values. The Timer2 increments from 00h until it
matches PR2 and then resets to 00h on the next increment cycle.
• Prescaler and Postscaler - Timer2 is an 8-bit timer with a prescaler and a postscaler. Eachallows to make additional division of the frequency clock source.
Prescaler divides the frequency clock source BEFORE the counting take place at the registerTMR2, thus the counting inside the TMR2 register is performed based on the divided frequency
clock source by the Prescaler
The match output of TMR2 goes through a 4-bit postscaler (which gives a 1:1 to 1:16 scaling
inclusive) to generate a TMR2 interrupt (latched in flag bit, TMR2IF (PIR1<1>)).Postscaler divides the frequency that comes out of the Comparator again for the last time.
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 58/149
TIMER2 Prescaler and Postscaler
• TMR2IF - TMR2 to PR2 Match Interrupt Flag bit.
• Comparator – Compares the value of the register TMR2 and the maximum value of the registerPR2.
• TMR2 – The register in which the "initial" count value is written.
• PR2 – The register in which the final or the maximum count value is written.
We perform all the necessary settings with T2CON Register The structure of the T2CON
register:
As we can see, the size of the register is 8 bits. Let's explore the relevant bits:
T2CKPS1:T2CKPS0: Timer2 Clock Prescale Select bits
The input clock (FOSC/4) has a prescale option of 1:1, 1:4 or 1:16, selected by control bits
T2CKPS1:T2CKPS0 (T2CON<1:0>).
00 = Prescaler is 1
01 = Prescaler is 4
1x = Prescaler is 16
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 59/149
TMR2ON: Timer2 On bit
Timer2 can be shut-off by clearing control bit, TMR2ON (T2CON<2>), to minimize powerconsumption.
1 = Timer2 is on
0 = Timer2 is off
TOUTPS3:TOUTPS0: Timer2 Output Postscale Select bits The match output of TMR2 goes through a 4-bit postscaler (which gives a 1:1 to 1:16 scaling
inclusive selected by control bits TOUTPS3:TOUTPS0 (T2CON<6:3>).
0000 = 1:1 postscale
0001 = 1:2 postscale
0010 = 1:3 postscale
•
•
• 1111 = 1:16 postscale
The following is an example how we can initialize the T2CON register:
1. TMR2ON=1; // the timer is enable
2. T2CKPS0=0; // Prescaler – 1:13. T2CKPS1=0;
4. TOUTPS0=1; // Postscaler – 1:165. TOUTPS0=1;
6. TOUTPS0=1;7. TOUTPS0=1;
Or you can set all the T2CON register at once as follows:
T2CON=0b01111100;
CLICK here for more information about PIC TIMER 2 Module
TIMER2 BLOCK DIAGRAM
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 60/149
How to calculate the required values of the TIMER2:
Fout – The output frequency after the division.Tout – The Cycle Time after the division.
4 - The division of the original clock (4 MHz) by 4, when using internal crystal as clock (and not
external oscillator).Count - A numeric value to be placed to obtain the desired output frequency - fout.
(PR2 – TMR2) - The number of times the counter will count.
Simple example and calculation of how to use TIMER2:
Suppose we want to create a delay of 1 second in the our program using Timer2. What is the
value of Count?
Calculation:
First, let's assume that the frequency division by the Prescaler will be 1:1 and Postscaler will be
1:16. Second, let's set TMR1=0 and PR2=255. Thus:
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 61/149
The following simple C language program creates a delay of 1 sec using TIMER2:
MP LAB
MPLAB Integrated Development Environment (IDE) is a free, integrated toolset for the
development of embedded applications on Microchip's PIC and dsPIC microcontrollers.
VersionsMPLAB IDE v8
The current version of MPLAB IDE is version 8.63. It is a 32-bit application on MicrosoftWindows and includes several free software components for application development, hardware
emulation and debugging. MPLAB IDE also serves as a single, unified graphical user interfacefor additional Microchip and third-party software and hardware development tools.
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 62/149
Both Assembly and C programming languages can be used with MPLAB IDE v8. Others may be
supported through the use of third-party programs.
Support for MPLAB IDE, along with sample code, tutorials, and drivers can be found on
Microchip's website. MPLAB IDE v8 does not support Linux, Unix or Macintosh operating
systems.
MPLAB X IDE
MPLAB X is not a new version of the current MPLAB IDE v8 framework but is instead based
on Oracle's open-source NetBeans platform. In addition to its predecessor's functionalities and
compatibility with Microchip's existing development tools, the new IDE utilises many NetBeans
features allowing for user-interface improvements and performance upgrades. This also includeshighly-anticipated cross-platform support in MPLAB IDE, allowing development for PIC
microcontrollers on Mac OS X and Linux operating systems, in addition to Windows. This IDEalso support the SDCC open source compiler on the three major OS: Mac, Linux and Windows.By using the MPLABX with SDCC one may be able to set up a complete free suite for
programming Microchip PIC's in C language.
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 63/149
UNIT –III Peripheral Of PIC Microcontroller
TIMER
Overview of Timer Modules :
PIC 16C74A has three modules, viz., Timer-0, Timer-1 and Timer-2. Timer-0 and Timer-2 are 8-bit timeTimer-1 is a 16-bit timer. Each timer module can generate an interrupt on timer overflow.
Timer-0 Overview:
The timer-0 module is a simple 8-bit UP counter. The clock source can be either the internal clock (f osc /4an external clock. When the clock source is external, the Timer-0 module can be programmed to increme
on either the rising or falling clock edge. Timer-0 module has a programmable pre-scaler option. This pr
scaler can be assigned either to Timer-0 or the Watch dog timer, but not to both.
The Timer-0 Counter sets a flag T0IF (Timer-0 Interrupt Flag) when it overflows and can cause an interr
at that time if that interrupt source has been enabled, (T0IE = 1), i.e., timer-0 interrupt enable bit = 1.
OPTION Register Configuration :
Option Register (Addr: 81H) Controls the prescaler and Timer -0 clock source. The following OPTION
register configuration is for clock source = f osc /4 and no Watchdog timer.
Timer-0 use without pre-scalar
Internal clock source of f osc /4. (External clock source, if selected, can be applied at RA4/TOCKI inputPORTA).
The following diagram shows the timer use without the prescaler.
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 64/149
Fig 20.1 Timer - 0 operation without prescalerTimer-0 use with pre-scalar:
The pre-scalar can be used either with the Timer-0 module or with the Watchdog timer. The pre-scalar is
available for Timer-0 if the pre-scalar assignment bit PSA in the OPTION register is 0. Pre-scalar is a
programmable divide by n counter that divides the available clock by a pre-specified number before applto the Timer-0 counter.
Fig 20.2 Timer - 0 with prescaler
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 65/149
Timer - 1 Module
Timer 1 module is a 16-bit timer/counter consisting of two 8-bit registers (TMR1H and TMR1L) which a
readable and writable. The TMR1 register pair (TMR1H:TMR1L) increments from 0000H to FFFFH androlls over to 0000H. The TMR1 interrupt, if enabled, is generated on overflow, which sets the interrupt fbit TMR1IF (bit-0 of PIR1 register). This interrupt can be enabled/disabled by setting/clearing TMR1interrupt enable bit TMR1IE (bit-0 of the PIE1 register).
The operating and control modes of Timer1 are determined by the special purpose register T1CON.Various bits of T1CON register are given as follows:-
Fig 21.1 T1CON Register
TMR1 ON : Timer1 ON bit
0 = stops Timer 1; 1 = Enables Timer 1TMR1CS : Timer 1 Clock source Select Bit
1 = External Clock (RCO/T1OSO/T1CKI)
0 = Internal Clock ( )
: Timer 1 External Clock Input Synchronization Bit
(Valid if TMR1CS = 1)
1 - Do not synchronize0 - Synchronize
T1OSCEN: Oscillator enable control bit
1 = Oscillator is enabled
0 = Oscillator is shut off
Timer 1 Input Clock Prescaler
Select bits Prescaler Value
T1CKPS1 T1CKPS0
1 1 1:8
1 0 1:4
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 66/149
0 1 1:2
0 0 1:1
Fig 21.2 Operation of Timer 1
Timer 1 can operate in one of the two modes
As a timer (TMR1CS = 0). In the timer mode, Timer 1 increments in every instruction cycle. The
timer 1 clock source is . Since the internal clock is selected, the timer is always synchronizand there is no further need of synchronization.
As a counter (TMR1CS = 1). In the counter mode, external clock input from the pin RCO/T1CKI
selected.
Reading and writing Timer 1
Reading TMR1H and TMR1L from Timer 1, when it is running from an external clock source, have to b
done with care. Reading TMR1H or TMR1L for independent 8 - bit values does not pose any problem. W
the 16-bit value of the Timer is required, the high byte (TMR1H) is read first followed by the low byte(THR1lL). It should be ensured that TMR1L does not overflow (that is goes from FFH to 00H) since TH
was read. This condition is verified by reading TMR1H once again and comparing with previous value o
TMR1H.Example Program
Reading 16bit of free running Timer 1
movf TMR1H ; read high byte
movwf TMPH ; store in TMPHmovf TMR1L ; read low byte
movwf TMPL ; store in TMPL
movf TMR1H, W ; read high byte in W
subwf TMPH, W ; subtract 1 st read with 2 nd readbtfsc STATUS, Z ; and check for equality
goto next ;
; if the high bytes differ, then there is an overflow
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 67/149
; read the high byte again followed by the low byte
movf TMR1H, W ; read high bytemovwf TMPH
movf TMR1L, W ; read low byte
movwf TMPL
next : nopTimer 2 Overview
Fig 21.3 Schematic diagram showing operation of Timer 2
Timer 2 is an 8 - bit timer with a pre-scaler and a post-scaler. It can be used as the PWM time base for PW
mode of capture compare PWM (CCP) modules. The TMR2 register is readable and writable and is clear
on device reset.
The input clock ( ) has a pre-scaler option of 1:1, 1:4 or 1:16 which is selected by bit 0 and bit 1 oT2CON register respectively.
The Timer 2 module has an 8bit period register (PR2). Timer-2 increments from 00H until it is equal to Pand then resets to 00H on the next clock cycle. PR2 is a readable and writable register. PR2 is initailised
FFH on reset.
The output of TMR2 goes through a 4bit post-scaler (1:1, 1:2, to 1:16) to generate a TMR2 interrupt bysetting TMR2IF.
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 68/149
Fig 21.4 The T2CON Register
Interrupt Logic in PIC 16C74A
PIC 16C74A microcontroller has one vectored interrupt location (i.e., 0004H) but has 12 interrupt sourceThere is no interrupt priority. Only one interrupt is served at a time. However interrupts can be masked. T
interrupt logic is shown below :
Fig 21.5 Schematic diagram showing the interrupt logic for PIC
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 69/149
Capture / Compare /PWM (CCP) :
PIC16C74A has two CCP Modules. Each CCP module contains a 16 bit register (two 8-bit registers) andoperate in one of the three modes, viz., 16-bit capture, 16-bit compare, or up to 10-bit Pulse Width
Modulation (PWM). The details of the two modules (CCP1 and CCp2) are given as follows.
CCP1 Module:
CCP1 Module consists of two 8-bit registers, viz., CCPR1L (low byte) and CCPR1H (high byte). The
CCP1CON register controls the operation of CCP1 Module.
CCP2 Module:
CCP2 Module consists of two 8 bit registers, viz., CCPR2L (Low byte) and CCPR2H (high byte). TheCCP1CON register controls the operation of CCP2 Module.
Both CCP1 and CCP2 modules are identical in operation with the exception of the operation of special evtrigger.
The following table shows the timer resources for the CCP Mode.
CCP Mode Timer Used
Capture
Compare
PWM
Timer 1
Timer 1
Timer 2
CCP1CON Register (Address 17H )
CCP2CON Register is exactly similar to CCP1CON register. CCP2CON Register address is 1DH.
CCP1CON controls CCP module1 where as CCP2CON controls CCP Module2.
Bit 5-4:CCP1X CCP1Y: PWM least significant bits. These bits are of no use in Capture mode. In PWM Mode, t
bits are the two Lsbs of the PWM duty cycle. The eight Msbs are found in CCPR1L. Thus the PWM mod
operates in 10-bit mode.
Bit 3-0:CCP1M3:CCP1MO (CCP1 Mode select bits)
0000=Capture/Compare/PWM Mode off 0100=Capture mode, every falling edge0101=Capture mode, every rising edge
0110=Capture mode, every 4 th rising edge
0111=Capture mode, every 16 th rising edge
1000=Compare mode, set output on match (CCP1IF bit is set)1001=Compare mode, clear output on match (CCP1IF bit is set)
1010=Compare mode, generate software interrupt on match (CCP1IF bit is set, CCP1 pin unaffected)
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 70/149
1011=Compare mode, trigger special event (CCP1IF bit is set;CCP1 resets Tmr1; CCP2 resets TMR1 an
starts A/D conversion if A/D module is Enabled)11XX=PWM mode.
Capture Mode (CCP1):
Capture Mode captures the 16-bit value of TMR1 into CCPR1H:CCPR1L register pair in response to an
event occurring on RC2/CCP1 pin. Capture Mode for CCP2 is exactly similar to that of CCP1.An event on RC2/CCP1 pin is defined as follows:
Every falling edge
Every rising edge.
Every 4 th rising edge.
Every 16 th rising edge.
As mentioned earlier, this event is decided by bit 3-0 of CCP1CON register.
Schematic diagram for capture mode of operation
Fig 22.1 Capture operation
Required condition for capture mode:
1. RC2/CCP1 pin should be configured as an input by setting TRISC (bit 2).
2. Timer 1 should be operated from the internal clock (fosc/4), i.e., timer mode or in synchronized
counter mode.
Compare Mode (CCP1)
Compare mode for CCP2 is similar to that of CCP1, except that in special event trigger mode, CCP1 rese
TMR1 only, whereas CCP2 resets TMR1 and starts A/D conversion if A/D module is enabled.
In compare mode, the 16-bit CCPR1 register value is compared against TMR1 register pair (TMR1H and
TMR1L) value. When a match occurs, the RC2/CCP1 pin is driven high or driven low or remains unchanas decided by CCP1CON<3:0> bits.
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 71/149
Fig 22.2 Compare Operation
Required conditions for compare mode
1. RC2/CCP1 pin must be configured as an output by clearing TRISC<2> bit.
2. Timer-1 should be operated in timer mode (i.e., internal clock source of f osc /4) or in synchronizecounter mode.
In software interrupt mode, CCP1IF bit is set but CCP1 pin in unaffected.
As shown in the figure, in special event trigger mode, both CCP1 and CCP2 intiates an A/D conversion.
PWM mode (CCP1)
Both CCP1 and CCP2 have similar operation in PWM mode. Here we will discuss PWM with respect to
CCP1.
In PWM mode, the CCP1 pin produces upto a 10-bit resolution Pulse Width Modulation (PWM) outputRC2/CCP1 pin should be configured in the uotput mode by clearing TRISC<2> bit.
The schematic block diagram of CCP1 module in PWM mode is shown in the figure.
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 72/149
Fig 22.3 PWM Operation
It can be noted that PR2 (Period Register, 8 bit) decides the PWM period where CCPR1L (8-bits) and
CCP1CON <5:4> (2-bits) decide the PWM duty cycle. When TMR2 equals PR2, the SR latch is set andRC2/CCP1 pin is pulled high. In the same time, TMR2 is cleared and the duty cycle value available in
CCPR1L is latched to CCPR1H. CCPR1H, CCP1CON <5:4> decide the duty cycle and when this 10-bi
ewquals the TMR2+2 prescaler or Q-bits, the SR latch is set and RC2/CCP1 pin is driven low.
A PWM output as shown has a time period. The time for which the output stays high is called duty cycle
PWM Period
The PWM period is specified by writing to PR2 register. The PWM period can be calculated using thefollowing formula:PWM period = [( PR 2) + 1] × 4 × T osc × (TMR2 prescale value)
PWM frequency = 1/ PWM period
When TMR2 is equal to PR2, the following events occur on the next increment cycle.
TMR2 is cleared
the CCP1 pin is set (if PWM duty cycle is 0 The PWM duty cycle is latched from CCPR1L into CCPR1H
PWM duty cycle
The PWM duty cycle is specified by writing to the CCPR1L register and to CCP1CON < 5 : 4 >
bits. Up to 10-bit resolution is available where CCPR1L contains the eight MSBs and CCP1CON < 5 : 4 contains the two LSB's. The 10-bit value is represented by CCPR1L : CCP1CON < 5 : 4 >.
The PWM duty cycle is given by
PWM duty cycle = (CCPR1L : CCP1CON < 5 : 4 > ). T osc . (TMR2 prescale value)
To understand the 10-bit counter configuration from Timer-2, let us first see the counting mechanism of Timer-2, as shown in Fig 22.4.
Fig 22.4 Counting mechanism in Timer - 2
If the prescaler is 1, the 10-bit counter is configured as follows
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 73/149
Fig 22.5 Prescaler set to divide by oneIf the prescaler is 4, the 10-bit counter is configured as follows.
Fig 22.6 Prescaler programed to divide by four
If the prescaler is 16, the 10-bit counter is realized as follows.
Fig 22.7 Prescaler programed to divide by 16
Although CCPR1L and CCP1CON < 5 : 4 > can be written to at anytime, the duty cycle value is not latc
into CCPR1H until a match between PR2 and TMR2 occurs. In PWM mode, CCPR1H is a read-onlyregister.
The CCPR1H register and a 2-bit internal latch are used to double buffer the PWM duty cycle. This doubbuffering is essential for glitchless PWM operation. When the CCPR1H and 2-bit latch match TMR2
concatenated with an internal 2-bit Q clock or 2-bits of prescaler, the CCP1 pin is cleared. Maximum PWresolution (bits) for a given PWM frequency can be calculated as
If the PWM duty cycle is longer than the PWM period, then the CCP1 pin will not be cleared.
PWM Period and duty cycle calculation
Example:
Desired PWM frequency = 78.125 kHzosc = 20MHz
TMR2 Prescalar = 1
Find the maximum resolution of duty cycle that can be used with a 78.124 kHz frequency and 20 MHz
oscillator.
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 74/149
256 = 2PWM
ResolutionAt most, an 8-bit resolution duty cycle can be obtained from a 78.125 kHz frequency and 20 MHz oscilla
ie, 0 CCPR1L : CCP1CON <5 : 4> ≤ 255 .
Any value greater than 255 will result in a 100 % duty cycle. The following table gives the PWM freque
f PWM if f osc = 20MHz
Duty cycle resolution 10-Bit counter scale PR2 value Prescaler 1 Prescaler 4 Prescaler 16
10 bit 1024 255 19.53 KHz 4.88 kHz 1.22 kHz
≈ 10 bit 1000 249 20kHz 5kHz 1.25kHz
8 bit 256 63 78.125kHz 19.53kHz 4.88kHz
6 bit 64 15 312.5kHz 78.125kHz 19.53kHz
ADCAn analog-to-digital converter (ADC) converts an analog signal into an equivalent digital number. PIC
16C74A has an inbuilt ADC with the following features -
8-bit conversion
8 analog input channels
An analog multiplexer
A sample and hold circuit for signal on the selected input channel
Alternative clock sources for carrying out conversion Adjustable sampling rate
Choice of an internal or external reference voltage
Interrupt to microcontroller on end of conversion
Port A and Port E pins are used for analog inputs/reference voltage for ADC. In A/D conversion, the inpuanalog voltage is digitized and an equivalent digital output is generated as shown in the figure.
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 75/149
Fig 23.1 Digital output versus analog input
Port-A pins (Alternate functions)
RA0/AN0 - can be used as analog input-0RA1/AN1 - can be used as analog input-1RA2/AN2 - can be used as analog input-2
RA3/AN3/Vref - can be used as analog input-3 or analog reference voltage
RA4/TOCKI - clock input to Timer-0
RA5/ /AN4 - can be used for analog input 4 or slave select for the synchronized serial port.Port-E pins (Alternate functions)
RE0/ /AN5 - can be used as analog input-5
RE1/ /AN6 - can be used as analog input-6RE2/ /AN7 - can be used as analog input-7
PIC microcontroller has internal sample and hold circuit. The input signal should be stable across the
capacitor before the conversion is initiated.
Fig 23.2 Sample and Hold Circuit
After waiting for the sampling time, a conversion can be initiated. The ADC Circuit will open the sampliswitch and carry out the conversion of the input voltage as it was at the moment of opening of the switch
Upon completion of the conversion, the sampling switch is again closed and VHold once again tracks VSou
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 76/149
Using the A/D Converter
Registers ADCON1, TRISA, and TRISE must be initialized to select the reference voltage and input
channels. The first step selects the ADC clock from among the four choices (f osc /2, f osc /8, f osc /32, and RCThe constraint for selcting clock frequency is that the ADC clock period must be 1.6micro seconds or
greater.
The A/D module has 3registers. These registers are:-
A/D result register (ADRES)
A/D control register 0 (ADCON 0)
A/D control register 1 (ADCON 1)
The ADCON0 register, which is shown below, controls the operation of A/D module.
Fig 23.3 ADCON0 register
Bit 7-6 - A/D Clock select bits
ADCS1:ADCS000 = f osc /201 = f osc /8
10 = f osc /32
11 = f RC- clock derived from an internal RC oscillatorBit 5-3 - A/D Channel Select
CHS2:CHS0
000 - Channel 0 - AN0
001 - Channel 1 - AN1010 - Channel 2 - AN2011 - Channel 3 - AN3
100 - Channel 4 - AN4101 - Channel 5 - AN5110 - Channel 6 - AN6
111 - Channel 7 - AN7
Bit 2 - A/D conversion status bit
GO /
if A/D Converter is enabled (ie. ADON = 1) then
If GO / = 1, A/D conversion is in progress(setting this bit starts A/D conversion)
If GO / = 0, A/D conversion is not in progress
(This bit is automatically cleared by hardware when A/D conversion is complete)Bit1 - Unimplemented
Bit 0 - ADON: A/D On bit
1. A/D Converter module is ON
2. A/D Converter module is OFF
ADCON1 Register
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 77/149
This register specifies the analog inputs
Fig 23.4 ADCON1 register
PCFG2:PCFG0 RA0 RA1 RA2 RA5 RA3 RE0 RE1 RE2 VR
000 A A A A A A A A VD
001 A A A A VREF A A A RA
010 A A A A A D D D VD
011 A A A A VREF D D D RA
100 A A D D A D D D VD
101 A A D D VREF D D D RA
11X D D D D D D D D -
Fig 23.5 PCFG2:PCFG0 = A/D Port configuration control bitsA = Analog inputD = Digital I/O
Fig 23.6 Schematic diagram of A/D convertor analog inputs and reference voltage
Steps for A/D conversion
1. Configure A/D module
Configure analog inputs/voltage reference and digital I/O (ADCON1)
Select A/D Channel (ADCON0)
Select A/D Conversion Clock (ADCON0)
Turn on A/D Module (ADCON0)
2. Configure A/D Interrupt (Optional)
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 78/149
Clear ADIF bit in PIR1 register
Set ADIE bit in PIE1 register
Set GIE bit
3. Wait for required acquisition time
4. Start Conversion - set GO/ bit (ADCON0)
5. Wait for A/D conversion to complete, by either polling GO/ bit or by waiting for the A/Dinterrupt
6. Read A/D result registers (ADRES). Clear ADIF if required.
Example Program
A/D conversion with interrupt
org 000H
goto Mainlineorg 020H
bsf STATUS, RP0 ; Select Bank 1
clrf ADCON 1 ; Configure A/D inputs
bsf PIE1, ADIE ; Enable A/D interruptbcf STATUS, RP0 ; Select Bank 0
movlw 081H ; Select fosc/32, channel 0, A/D onmovwf ADCON0
bcf PIR1, ADIF
bsf INTCON, PEIE ; Enable peripheral and global interrupt bits
bsf INTCON, GIE ; interrupt bits; Ensure that the required sampling time of the selected input channel has been elapsed.
; Then conversion may be started.
; bsf ADCON0, GO ; Start A/D conversion.
; ADIF bit will be set and GO/ ; bit is cleared upon completion of A/D conversion.
Interrupt Service Routine
Org 004H
Movf ADRES, W ; Result of A/D conversion in W
Consideration of Sampling Time
When a channel is selected (writing to ADCON0), the switch 'SW' in Fig 23.8 is closed, changing C HOLD
VSource . When A/D conversion is started (setting Go bit in ADCON0), SW is opened. The time from the
closure of 'SW' till the voltage across CHOLD (Vo) reaches VSource is the minimum sampling time Ts . Th
actual sampling time can be higher than Ts .The graph between Ts and source resistance RSource is shown in Fig 23.7.+
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 79/149
Fig 23.7 Relation between sampling time and source resistance
Fig 23.8 Sampling circuit in the PIC µC
Rss is the resistance of the sampling switch 'SW' and CHold is the charge holding capacitance. CHold is nea
50pF. RSource is the impedance of the external analog source Vsource. Once the switch 'SW' is closed, the
capacitor Chold takes some time to charge up. This time it is called the sampling time (T s). This time varlinearly with RSource as shown. The recommended value of impedance of the external analog source, Vsou
is less than 10kΩ.
The circuit in Fig 23.8 is a first order RC circuit. When SW is closed, V o varies as shown in Fig 23.9.
Fig 23.9
From Fig 23.9,
Ts = 5 = 5 ( Rsource + Rss) CHOLD = 5 Rss CHOLD + 5 Rsource CHOLD
Hence sampling time Ts varies linearly with RSource as shown
Most of mid range PIC microcontrollers include a Synchronous Serial Port (SSP) Module. The discussiothis section is relevant to PIC16C74A only. SSP Module section can be configured in either of the follow
two modes.
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 80/149
Serial Peripheral Interface (SPI)
Inter Integrated Circuit (I2C)
Either of these modes can be used to interconnect two or more PIC chips to each other using a minimal
number of wires for communication. Alternatively, either can be used to connect a PIC microcontroller to
peripheral chip. When I
2
C mode is selected, the peripheral chip must also have an I
2
C interface. On theother hand, the SPI mode provides the clock and serial data lines for direct connection to shift registers. T
leads to increased I/O interface capability and an arbitrary number of I/O devices can be connected to a Pmicrocontroller. SPI can also achieve data rate significantly higher than I2C. Both the communication
methods are synchronous, i.e., the data transfer is synchronized with an explicit clock signal.
Two special purpose registers control the synchronous serial port (SSP) operations. These registers are:
SSPCON (Synchronous Serial Port Control Register), Address: 14H
SSPSTAT(Synchronous Serial Port status Register), Address: 94H
Serial Peripheral Interface (SPI)
Port-C three pins, viz., RC5/SDO, RC4/SDI and RC3/SCK/SCL are mainly used for SPI mode. In additioone Port-A pin, viz., RA5/ /AN4 is used for slave select. The schematic block diagram of SPI is show
the figure
Fig 24.1 Schematic diagram under SPI Mode
The SPI port requires RC3/SCK pin to be an output that generates the clock signal used by the external s
registers. When SPI is configured in the slave mode, RC3/SCK pin works as the input for the clock.
When a byte is written to SSPBUF register, it is shifted out of RC5/SDO pin in synchronous with the emclock pulses on RC3/SCK pin. The MSB of SSPBUF is the first bit to appear on RC5/SDO pin.
Simultaneously, the same write to SSPBUF also initiates the 8 bit data reception into SSPBUF of whatev
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 81/149
appears on RC4/SDI pin at the time of rising edges of the clock on SCK pin. Hence shifting-in and shiftin
out of data occur simultaneously.
Fig 24.2 SPI Master / Slave Connection
The schematic diagram of SPI Master/Slave connection is shown in the figure.
Timing diagram for data transfer in 'Master mode' :
SSPIF interrupt flag is cleared by the user software if already in the set mode. The interrupt is enabled. A
write to SSPBUF initiates the data transfer, i.e., transmission and reception. The clock pulses (8 clock pu
are output through SCK pin. The data is received through SDI. When CKP=1 (SSPCON<4>), data chang
at SDO at negative clock transition and is read through SDI at positive clock transition. The idle state of clock is high. If CKP=0, data appears at SDO at positive clock transition and is read through SDI at nega
clock transition. The idle state of the clock is low. These are shown in the following diagrams.
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 82/149
(i) Timing diagram for CKP=1
(ii) Timing diagram for CKP=0
Fig 24.3 Timing Diagram under SPI mode
hough SPI is a serial communication interface, it can be used to realize multiple output parallel ports and
multiple input parallel ports. We will consider this realization of an output parallel port and an input portseparately.
Parallel Output Port Realization
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 83/149
A parallel 8-bit output port can be realized through SPI with the help of a shift register chip (74HC595) a
shown in Fig 25.1. RC5/SD0 pin outputs serial data while RC3/SCK oin outputs the serial clock. Since indata transfer is not required, port pin RC4/SDI is used to latch the shift register data to the output pins of
shift register. Hence RC4 is configured as an output pin.
Fig 25.1 PIC connection (in SPI mode) with a shift register
When an 8-bit data is written to SSPBUF, the data is shifted out of RC5/SD0 pin. With CKP = 1, the datastable at the positive transition but changes at the negative transition. The shift shifts the data at the posit
clock transition. After 8 clock pulses, all 8-bits are shifted in the shift register. The completion of data tra
is indicated by SSPIF interrupt flag becoming ' 1' . The interrupt service routine make RC4 ' 1' , thus latchthe 8-bit data to the output of the shift register. The configuration of various registers are shown in Fig 25
Port configurations
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 84/149
Fig 25.2 Various Register Configurations
Parallel Input Port Realization
A shift register (74HC165) is connected to the PIC microcontroller as shown in Fig 25.3. Pin RD7 is conas an output and is used to load 8-bit data to the shift register. A dummy write to SSPBUF initiates datatransfer. Data bit is read into RC4/SDI at the negative clock transition (CKP = 0) where the data bit is sta
Data is shifted in the shift register at the position clock transition as shown in the timing diagram. After th
completion of data transfer, SSPIF interrupt flag goes high. Therafter the 8-bit data can be read by readinSSPBUF.
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 85/149
Fig 25.3 Realization of an 8-bit parallel input port with PIC in SPI mode.
Port configurationsFig 25.4 gives the configurations various registers for inputs parallel port realization.
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 86/149
Fig 25.4 Configurations of various registers for parallel input port
I2C Communication in PIC Microcontroller
I C stands for Inter-Integrated circuit. I C communication is a two wire bi-directional interface for
connecting one or more master processors with one or more slave devices, such as an EEPROM, ADC,
RAM, LCD display, DAC, etc. I2C interface requires two open drain I/O pins, viz. SDA (Serial Data) an
SCL (Serial Clock).
The reason for open drain connection is that the data transfer is bi-directional and any of the devicesconnected to the I
2C bus can drive the data line (SDA). The serial clock line (SCL) is usually driven by t
master. Since SDA and SCL pins are open drain pins, external pull-up resistances are required for operatiof I 2C bus.
A typical I C bus showing the connection of multi-master and multi-slave configuration is shown in the
following figure.
Fig 26.1 Multimaster Multislave Connection
Some conventions are followed in I C communication. Let us assume that there is one master and one sl
and 8-data bits are sent. We will initially assume that the master is the transmitter and the slave is thereceiver. The clock is driven by the master. On receiving 8-bits, an acknowledgement bit is driven by the
receiver on SDA line. The acknowledgement bit is usually Low (0). The following diagram shows the da
communication pattern having 8 data bits and one acknowledgement bit.
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 87/149
Fig 26.2 Timing diagram for data transfer
The following features are to be noted -
1. SDA line transmits/ receives data bits. MSB is sent first.
2. Data in SDA line is stable during clock (SCL) high. A new bit is initiated at the negative clock
transition after a specified hold time.
3. Serial clock (SCL) is driven by the master.4. An acknowledgement bit (0) is driven by the receiver after the end of reception. If the receiver do
not acknowledge, SDA line remains high (1).
I C bus transfer consists of a number of byte transfers within a START condition and either another STAcondition or a STOP condition. During the idle state when no data transfer is taking place, both SDA and
SCL lines are released by all the devices and remains high. When a master wants to initiate a data transfepulls SDA low followed by SCL being pulled low. This is called START condition. Similarly, when the
processor wants to terminate the data transfer it first releases SCL (SCL becomes high) and then SDA. T
is called a STOP condition. START and STOP conditions are shown in the diagram as follows.
Fig 26.3 Timing diagram for START and STOP Conditions
START and STOP conditions are unique and they never happen within a data transfer.
Data Communication Protocol:
In I C communication both 7-bit and 10-bit slave addressing are possible. In 7-bit addressing mode 128slaves can be interfaced with a single master. Similarly, in 10-bit addressing mode, 1024 slaves can be
interfaced with the master. We will discuss here 7-bit addressing mode only. 10-bit addressing mode is
similar to 7-bit addressing except from the fact that the number of address bits is more.
Following a 'start' condition, the master sends a 7-bit address of the slave on SDA line. The MSB is sent
After sending 7-bit address of the slave peripheral, a R/ (8th bit) bit is sent by the master. If R/ bit is the following byte (after the acknowledgement bit) is written by the master to the addressed slave periphe
If R/ =1, the following byte (after the acknowledgement bit) has to be read from the slave by the masteAfter sending the 7-bit address of the slave, the master sends the address (usually 8 bit) of the internal
register of the slave wherefrom the data has to be read or written to. The subsequent access is automatica
directed to the next address of the internal register.
The following diagrams give the general format to write and read from several peripheral internal registe
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 88/149
Fig 26.4 Data transfer protocol for writing to a slave device
R/ (Read / Write) bit indicates whether the data is to be written by the master or read by the master. If is 1, the subsequent data are to be read by the master. If R/ = 0, the subsequent data are to be written b
master to the addressed slave. It has to be noted that the slave address is sent first, following a 'start'
condition. The addressed slave responds by acknowledging and gets ready for data transfer.If data has to be read from a specific address of the slave device, the master sends the 7-bit address of the
slave first following a 'start' condition. R/ bit is sent as 'low'. The addressed slave acknowledges by pu
the ACK line low. The master then sends the 8-bit internal address of the slave from which data has to be
read. The slave acknowledges. Since R/ bit was initially 0, the master is in the write mode. To change to read mode, the 'start' condition is again generated followed by 7-bit address of the slave with R/ = 1
slave acknowledges. The slave then sends data from previously specified internal address to the master. T
master acknowledges by pulling ACK bit low. The data transfer stops when the master does not acknowlthe data reception and a 'stop' condition is generated.
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 89/149
UNIT IV
LCD INTERFACING
Liquid Crystal Display (LCD-Displaytech 162A )
LCD Displaytech 162A consists of a LCD panel, a controller IC (KS0070B) and a back light LED. The L
module consists of total 16 pins in which, 2 are for power supply, 2 pins for Backlight LED, one pin for
contrast adjustment, 3 pins are for control signals and 8 pins are data pins. In order to display any data, wneed to do certain initiations. The following are the main three steps in displaying any data in the LCD
display.
1. Initializing LCD by sequence of instructions
2. Executing commands depending on our settings in the LCD3. Writing data into the DRAM locations of LCD in the Standard Character Pattern of LCD
For doing above steps, refer the manual for LCD and follow the instructions and timing diagrams strictlyMPLABIDE
MPLABIDE is a free software which can be downloaded from the website www.microchip.com
Working with MPLABIDE :
MPLABIDE is a simulator for PIC microcontrollers to write and edit the code in assembly language, com
it and also to run the code. Output can be verified using simulator.
Steps to Use MPLABIDE
After Installing the software MPLABIDEv7.2,open MPLABIDE.
To built a new project, open
Project Project WizardProject wizard New
Device 16F877
Location (Ex:C:\ProgramFiles\Microchip\MPASM Suite\MPASMWIN.EXE) Next
<Project name>&<Project Directory> Next
(Add file "f877tmpo.asm" which was located in programfiles microchip MPASMSuiteTemplate Object)
(Add file "16f877.lkr" which was located in programfiles microchip MPASMSuite LKR
Next FinishTo have more clear refer to MPLABIDE help files.
After building the project open the editor f877tmpo.asm and write the assembly code
After writing the assembly code in the editor, build the project by clicking on the following optionProject Build all
Check for the errors in the output window
View Output
Once the error free code was made, simulate the code by following option
Debugger Select Tool MPLAB SIM
Simulator options are
1. Step into - Each time only one instruction will be executed (Single stepping mode)
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 90/149
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 91/149
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 92/149
Circuit Diagram
Fig 43.2 Circuit Diagram
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 93/149
Fig 43.3 Circuit assembly on breadboard
KEYPAD INTERFACE
Keypad is an array of 4x4 keys with each key being a switch. The four rows are connected to pins 0-3 of
Port1 and the four columns to pins 4-7 of Port1 as shown in the figure below. Each column is also conne
to supply voltage through a pull up resistor (around 1k Ohms). To read a particular key, the correspondinrow is driven to '0'. In a key is pressed and the corresponding row is driven '0' then current flows through
corresponding pull up resistor and the corresponding column reads '0'. Otherwise the corresponding colu
reads '1' (open circuit). For example if Key 5 is pressed -
R1 = 0, C1:C4 = 1111
R2 = 0, C1:C4 = 1011
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 94/149
Fig 42.1 Keypad schematic
Procedure
1. Write the assembly code in Win8051. Compile and simulate it.2. Once the code is error free, run it and check output with the Simulator
3. After checking the code in the simulator, the code (file with .HEX extension) is loaded into Atme
89C51 microcontroller using Universal SP3 Programmer.4. Now connections are made as shown in the circuit diagram.
5. Switch on the supply and push Reset button
6. Observe the results7. Switch off the supply
Assembly Code
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 95/149
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 96/149
Observation
Microcontroller takes few microseconds to scan all 16 keys on the keypad whereas human response is of
order of milliseconds. Hence contact time of a key is long enough for it to be scanned by the microcontro
Circuit Diagram
Fig 42.2 Circuit diagram for keypad interfacing
MEASUREMENT OF FREQUENCY
Introduction:
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 97/149
A frequency counter is an electronic instrument, or component of one, that is used formeasuring frequency. Frequency is defined as the number of events of a particular sort occurring
in a set period of time. Frequency counters usually measure the number of oscillations or pulses
per second in a repetitive electronic signal.
The Schematic Diagram:
Most frequency counters work by using a counter which accumulates the number of events
occurring within a specific period of time (In this project, I used the counter of Timer1) . After a
preset period (1 second, for example), the value in the counter is transferred to a display and the
counter is reset to zero.
Fig.(2): Freq. Count. Circuit Diagram
If the event being measured repeats itself with sufficient stability and the frequency isconsiderably lower than that of the clock oscillator being used, the resolution of the measurement
can be greatly improved by measuring the time required for an entire number of cycles, ratherthan counting the number of entire cycles observed for a pre-set duration (you can use
CCP1/Cature to do that).
Source Code:
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 98/149
C Source Code
/*************************************/
/* Project: Frequency Counter */ /* Copyright@ Abdullah M. Abdul-Hadi */
/* Date: 12-May-2011 */
/* www.pic-tronics.com */ /*********************************/
#include <16f877a.h>
#use delay(clock=20M)#include <lcd420.c>
#include <LCD_D.h>
#fuses hs,nowdt,nocpd,nolvp,noprotect
#byte portc=0x07
#bit led=portc.4
void LCD_D();
unsigned int16 value;
void main()
set_tris_c(0x00);led=1;
delay_ms(500);LCD_D();
delay_ms(50);while(1)
set_timer1(0);setup_timer_1(t1_external | T1_DIV_BY_1);
delay_ms(1000); // in protues, should be 1000/3
setup_timer_1(T1_DISABLED);value=get_timer1();
lcd_gotoxy(11,4);printf(lcd_putc,"%LU HZ ",value);
led=!led;
*****************************************************************
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 99/149
DATA ACQUICATION SYSTEM
Introduction
Measurement of the three basic quantities: voltage, temperature, and current can provideenough information to allow for debugging of almost any electrical circuit. During the development of aswitch-mode power supply it was determined that some sort of data logging was necessary to protect thesupply and determine if the supply was operating properly. Out of this need a data acquisition systemwas developed. The data acquisition system measures one channel of voltage from 0 to 20 volts, onechannel of current from –50 to +50 amps, and two channels of temperature (one ambient and one load).This amount of data is enough to determine supply efficiency and temperature rise. With additionalchannels or faster sampling rates it would be possible to measure and calculate inrush current, supplystability, and transient response.
Implementation options
Two options were initially considered to implement the data logger. First, adding an outboardanalog to digital converter (ADC) to the 8052 board used for development in class was considered. This
approach had the advantage of allowing me to use a known good development system, software toolset,
and the ability to get support from teachers and other students. Unfortunately, I had a difficult time
finding multi-channel ADC converters featuring parallel interfaces to 8-bit busses that could resolve more
than 8 bits. Most modern ADCs found used a serial interface. This was a problem on the 8052 board as
the serial port was tied up for communication to the PC. Also fully developing a software-based serial
protocol on a relatively slow processor like the 8052 could be difficult. Figure 1 shows the proposed block
diagram for the 8052 based data acquisition system.
Figure 1, data acquisition system using 8052 board
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 100/149
The second option considered the use of an altogether different processor, the Microchip PICcontroller. PICs are self-contained microcontrollers often including clock, I/O, and a host of peripheralson-chip. The great advantage seen by adopting the PIC was a chip with onboard analog to digitalconverters was available in a small 14-pin DIP package. In addition a serial port, and multipletimer/counters were available. A low-cost ($35) development kit is available from Microchip to try out anyof the 14-pin series of micrcontrollers. Additionally, for the intended application a low-power small form
factor device was a plus. Essentially all the PIC needs to create the system is the analog interface and avoltage regulator. Just the 8052 board requires 2 to 3 times the space of the board designed for the PICcontroller and analog board. The downside of this approach hinged around learning a new assemblylanguage for the PIC microcontroller and learning a new development environment and device
programmer. Figure 2 shows the block diagram for the PIC data acquisition system.
Figure 2, PIC processor based data acquisition system
PIC selection and setup
There are literally hundreds of PIC microcontrollers to pick from. The programmer I had alreadypurchased narrowed this selection down to 8 or 14 pin devices. At minimum 4 ADC channels, a UART,
and one counter timer were needed. The first device found to meet these specifications was the
PIC16F688. The ‘688 contains 8 channels of 10-bit AD converters, an enhanced UART, two timer
counters, analog input comparison modules, an internal 32kHz to 8MHz clock, and flash program
memory.
In order to use the PIC, settings for all the internal registers needed to be determined or
calculated via the datasheet. The internal oscillator was used and set to 4MHz. Next, the serial port was
configured. The enhanced UART (EUSART) has an internal baud rate generator (no external timer is
needed). The EUSART was setup to communicate at 9600 bps, 1 stop bit, 8 data bits, and no parity. This
seemed to be a common serial data rate that was easily achieved with little error in bit-rate on the PIC
(about 0.16%). The commonly used baud rates were all available in tables in the ‘688 datasheet. After
the serial port was configured the analog to digital converter was set-up. A conversion time of 4.0us as
dictated by the datasheet was selected. Then, registers were set up to use the positive supply as the ADC
reference voltage along with selecting the location of the most significant bit of the result. Finally, a timer
was set up to control the rate of data sampling. The timer values were set to allow for maximum delay
that turned out to be around ¾ of a second. The timer overflow bit was checked via polling. This
approach was used because exact time intervals were not needed and quick response was not necessary.
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 101/149
Microchip provides an integrated development environment (IDE) called MPLAB for coding,
compiling, setting up, and controlling programmers for the PIC series of microcontrollers. Included in the
IDE is a debugger and compiler. The debugger worked well until additional peripherals were initialized
and used which then caused the debugger to crash the IDE. Thus, all further testing needed to be
conducted on actual hardware. A simple USB powered programmer interfaced to the IDE and
reprogrammed the flash program memory in PIC controllers.
Microcontroller Firmware
After configuration of peripherals the microcontroller firmware consisted of a simple loop that
acquired samples, converted them to a format acceptable to HyperTerminal, and echoed them to the
serial port. Code is attached to the end of this document in listing 1. Peripherals were first initialized as
described in the previous section. Following this a timer set to approximately one second would overflow
triggering a capture event. The capture event consists of setting ADC registers, then waiting for the
conversion to be completed. These events are repeated four times to cover all the input channels. The
results are then converted to a three digit octal number via shifts and bit masks. Only 8 bits of the 10-bit
result are converted to octal, as it appeared the lower value bits only added noise to the acquired signal.
Finally, the converted values were output on the serial port to HyperTerminal in ASCII format delimited
with commas. Figure 3 shows the block diagram for the microcontroller firmware.
Figure 3, A block diagram of the PIC’s firmware
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 102/149
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 103/149
Figure 5, analog interface section of the data acquisition
system
The physical hardware is shown in photo 1. Two LM35 temperature sensors are attached via
twisted cable, enabling them to be clamped onto heatsinks to measure power supply temperatures. A set
of binding posts is provided for voltage measurement and current measurement input. The 9 pin serial
port hangs off the left side of the development board (black PCB on top). Unregulated (9 to 37 VDC) DC
input is supplied via two wires exiting the back of the board.
Photo 1, physical realization of the data acquisition system
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 104/149
Results
To test the data acquisition system an unregulated power supply was used. Real power supplies
have internal resistance that can be demonstrated if the load of the supply is varied. The circuit in figure
6 was built to show the effect of loading the supply under various conditions.
Figure 6, an unregulated power supply loaded with various
power resistors
The output voltage, current, ambient temperature, and temperature of the load resistor were all
monitored via the data acquisition system. After logging the octal numbers to a text file viaHyperTerminal, the data was scaled and plotted in MS Excel.
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 105/149
Plot 1, result of power supply testing, showing voltage, current, and two temperatures
Plot 1 shows the results of loading the supply with three different values of load resistors. As expected
the supply voltage sags with decreasing resistance. The output current changes from 400mA to about 1A
over the three different resistors. Finally, the temperature of the load resistor peaks at about 55 degrees
Celsius. This simple application example shows the utility and some of the capabilities of the data
acquisition system.
Conclusions and Future Work
The data acquisition system proved to be a successful, yet challenging final project. Choosing adifferent microcontroller platform on which to base the project made hardware design much simpler.However, using the PIC controller greatly increased the difficulty of software design. A new assemblylanguage was learned to take advantage of the PIC. Additionally, it was necessary to learn the
development environment, compiler, and device programmer. Hardware design went relatively smoothly.Highly integrated sensors made the analog interface a snap. For some sensors such as the current sensorand to a lesser degree the temperature sensors the data acquired was of low resolution. Ideally, a higherresolution ADC converter would be needed to take better data, or a variable gain amplifier could be used.
The primary problem with the current sensor was because it was intended for a 0 to 50 A range. In theoriginal application this high current sensor was fine. Under testing, low-current supplies were used thatshowed the low resolution of the ADC. This combined with using a very small region of the currentsensors range resulted in noisy captured data.
This data acquisition system, while functional, could be improved. Primarily, the improvements
are centered on the lack of resolution of the ADC in the PIC controller and the need for better PC
interface software. Other microcontrollers such as the MSC series from Texas Instruments have on-board
ADC converters with up to 24 bits of resolution. These microcontrollers also feature programmable gain
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 106/149
amplifiers, which effectively increase the dynamic range of the ADC and thus further increase resolution.
An improved voltage measurement input is also desired. Currently, the system can only measure positive
ground referenced voltages. With a true differential amplifier input, positive and negative voltages could
be read without the fear of shorting a measurement channel to ground. On the software side two major
improvements are warranted. First, the capability to display real-time values of the captured data would
greatly increase the utility of the data acquisition system. Next, an integrated capture and displayprogram would greatly simplify data capture. The current system requires capturing data via
HyperTerminal to a text file. This text file then is updated in an excel spreadsheet. Excel’s update feature
works most of the time, however, trouble was occasionally experienced resulting in Excel crashing. The
current solution is far from a one-click data capture. With dedicated software it is possible that a single
click would enable a user to view live data and concurrently save the trend data to a file.
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 107/149
Listing 1, PIC16F688 assembly code for the data acquisition system
list p=16f688 ; list directive to define processor
#include <P16F688.inc> ; processor specific variable definitions
__CONFIG _CP_OFF & _CPD_OFF & _BOD_OFF & _PWRTE_ON & _WDT_OFF & _INTRC_OSC_NOCLKOUT &_MCLRE_OFF & _FCMEN_OFF & _IESO_OFF
; '__CONFIG' directive is used to embed configuration data within .asm file.
; The labels following the directive are located in the respective .inc file.
; See respective data sheet for additional information on configuration word.
;***** VARIABLE DEFINITIONS
w_temp EQU 0x71 ; variable used for context saving
status_temp EQU 0x72 ; variable used for context saving
pclath_temp EQU 0x73 ; variable used for context saving
ADCH0 EQU B'00000001' ;setup ch 0, Vdd for Vref, and left justified result
ADCH1 EQU B'00000101' ;set to Ch1 same settings as above
ADCH2 EQU B'00001001' ;set to Ch2 same settings as above
ADCH3 EQU B'00001101' ;set to Ch3 same settings as above
COUNTER EQU 0x60 ;counter variable
TXPREBUF EQU 0x61 ;A buffer for the serial transmit buffer (a prebuf)
OCTTOVERT EQU 0x20 ;stores the a/d value when it's being converted to octal
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 108/149
;**********************************************************************
ORG 0x0 ; processor reset vector
goto main ; go to beginning of program
main
;***********************************************************
;Setup For 9600 bps tx serial interface
;***********************************************************
bsf STATUS, RP0 ;bank 1
movlw B'00111111' ;setup RC0-5 as inputs for serial i/o and A/D
movwf TRISC
bcf STATUS, RP0 ;bank 0
bsf RCSTA, SPEN ;serial port enable
bsf BAUDCTL, BRG16 ;use 16 bit baudrate generator
bcf TXSTA, BRGH ;use low baudrate speed
movlw d'25'
movwf SPBRG ;setup baudrate generator
bcf TXSTA, SYNC ;asynchronous serial i/o
bsf TXSTA, TXEN ;enable transmission
;***********************************************************
;Setup A/D converter
;***********************************************************
bsf STATUS, RP0 ;bank 1
movlw B'00011111' ;Setup all of port A as inputs for A/D
movwf TRISA
movlw 0xFF
movwf ANSEL ;Enable all available Analog channels
movlw B'01010000'
movwf ADCON1 ;Set 4uS conversion time w/ 4MHz internal clk
bcf STATUS, RP0 ;bank 0
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 109/149
movlw ADCH0
movwf ADCON0 ;AD: right justified result, ch 0, VDD ref. voltage
call WaitForAD
;***********************************************************
;Setup Timer1 for 1/10 second wait period
;***********************************************************
movlw B'00110001'
movwf T1CON ;load timer1 config register
GoAgain:
movlw 0x01 ;set to max for approx 1 sec delay
movwf TMR1L
movlw 0x00
movwf TMR1H
;bsf T1CON, TMR1ON ;start timer
bcf PIR1, TMR1IF ;clear overflow flag
;This is the delay between sample periods from the analog inputs
Wait:
btfss PIR1, TMR1IF ;check if timer has overflowed
goto Wait
call GetADValues
; loop through 4 values here and print them out
movlw 0x4 ;loop 4 times
movwf COUNTER
movlw 0x21 ;point to first a/d value
movwf FSR ;data pointer
OutLoop:
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 110/149
movf INDF, W ;getting indirect data
movwf OCTTOVERT ;store a/d value we need to convert
call TO_OCTAL ;convert currently selected A/D Channel to octal
movf 0x30, W ;output all bytes
movwf TXPREBUF
call SENDBYTE
movf 0x31, W
movwf TXPREBUF
call SENDBYTE
movf 0x32, W
movwf TXPREBUF
call SENDBYTE
movlw ',' ;do checking on this one to see if we're at the last byte
movwf TXPREBUF
call SENDBYTE
incf FSR ;goto next a/d value
decfsz COUNTER ;is counter zero yet? if so skip goto
goto OutLoop
; end of above loop
movlw 0x0A ;Line Feed (newline, hopefully)
movwf TXPREBUF
call SENDBYTE
;movlw 0x0D ;carridge return
;movwf TXPREBUF
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 111/149
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 112/149
call WaitForAD
movlw ADCH1 ;goto channel 1
movwf ADCON0
bsf ADCON0, GO ;start conversion
btfsc ADCON0, GO ;conversion done?
goto $-1 ;keep looping
movf ADRESH, W ;get high byte into acc W
movwf INDF ;store adresh to 22h
incf FSR ;move ptr to 23h
call WaitForAD
movlw ADCH2 ;goto channel 2
movwf ADCON0
bsf ADCON0, GO ;start conversion
btfsc ADCON0, GO ;conversion done?
goto $-1 ;keep looping
movf ADRESH, W ;get high byte into acc W
movwf INDF ;store adresh to 23h
incf FSR ;move ptr to 24h
call WaitForAD
movlw ADCH3 ;goto channel 3
movwf ADCON0
bsf ADCON0, GO ;start conversion
btfsc ADCON0, GO ;conversion done?
goto $-1 ;keep looping
movf ADRESH, W ;get high byte into acc W
movwf INDF ;store adresh to 24h
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 113/149
return
;convert to 3 octal bytes in ASCII
;stores bytes in 0x30 to 0x32, w/ lsb in 0x32 msb in 0x30
;input value stored in 0x20, ie OCTTOVERT
TO_OCTAL:
clrc ;clear carry
movlw B'00000111' ;bit mask field
andwf OCTTOVERT, W ;and with ADRESH
addlw 0x30 ;make this into an ASCII number
movwf 0x32 ;store result away
;octal byte 2
movlw B'00111000' ;bit mask field
andwf OCTTOVERT, W ;get 2nd set of 3 bits
movwf 0x31 ;place back into file
rrf 0x31 ;rotate to LSB, need 3x
rrf 0x31
rrf 0x31
movf 0x31, W ;now get it back
addlw 0x30 ;and add 30h to make a ascii number
movwf 0x31 ;store again
;octal byte 3
clrc ;clear carry
movlw B'11000000' ;bit mask field
andwf OCTTOVERT, W ;get last 2 bits
movwf 0x30
rrf 0x30
rrf 0x30
rrf 0x30
rrf 0x30
rrf 0x30
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 114/149
rrf 0x30
;btfsc 0x21, 0 ;check the LSB value from the last byte
;bsf 0x31, 2
movf 0x30, W ;get value back
addlw 0x30 ;convert to ASCII
movwf 0x30 ;store it
return
;transmit data on serial port
SENDBYTE:
btfss TXSTA, TRMT ;check tx buffer ready bit
goto SENDBYTE ;try again, keep polling
movf TXPREBUF, W ;get data from pre-buffer
movwf TXREG ;move data to tx register and start transmission
return
ORG 0x2100 ; data EEPROM location
DE 1,2,3,4 ; define first four EEPROM locations as 1, 2, 3, and 4
END ; directive 'end of program'
MOTOR CONTROL
Controlling Stepper Motors with a PIC Microcontroller
For applications where precise measuring of a motors' rotor position is critical, a Stepper Motoris the best choice. Stepper motors operate differently from other motors; rather than voltage
being applied and the rotor spinning smoothly, stepper motors turn on a series of electrical pulses
to the motor's windings. Each pulse rotates the rotor by an exact degree. These pulses are called"steps", hence the name "stepper motor".
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 115/149
The degrees per pulse is set in the motor's manufacturing, and is provided in the spec sheets for
that motor. They can range from ultra-fine movements of a fraction of a degree (i.e., 0.10degrees), to larger steps (i.e. 62.5 degrees).
This article will explain the operating principals of stepper motors, and will give instructions on
how to control them via a PIC16F84 microcontroller to perform many functions.
How Stepper Motors Work
Stepper motors consist of a permanent magnet rotating shaft, called the rotor, and electromagnets
on the stationary portion that surrounds the motor, called the stator. Figure 1 illustrates one
complete rotation of a stepper motor. At position 1, we can see that the rotor is beginning at theupper electromagnet, which is currently active (has voltage applied to it). To move the rotor
clockwise (CW), the upper electromagnet is deactivated and the right electromagnet is activated,
causing the rotor to move 90 degrees CW, aligning itself with the active magnet. This process is
repeated in the same manner at the south and west electromagnets until we once again reach the
starting position.
Figure 1
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 116/149
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 117/149
Figure 3
The specific stepper motor we are using for our experiments (ST-02: 5VDC, 5 degrees per step)has 6 wires coming out of the casing. If we follow Figure 5, the electrical equivalent of the
stepper motor, we can see that 3 wires go to each half of the coils, and that the coil windings are
connected in pairs. This is true for all four-phase stepper motors.
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 118/149
Figure 5
However, if you do not have an equivalent diagram for the motor you want to use, you can make
a resistance chart to decipher the mystery connections. There is a 13 ohm resistance between thecenter-tap wire and each end lead, and 26 ohms between the two end leads. Wires originating
from separate coils are not connected, and therefore would not read on the ohm meter.
First Stepper Circuit
Figure 4 is the schematic of our first test circuit. The PIC's output lines are first buffered by a4050 hex buffer chip, and are then connected to an NPN transistor. The transistor used, TIP120,
is actually a NPN Darlington (it is shown as a standard NPN). The TIP120's act like switches,
activating one stepper motor coil at a time.
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 119/149
Figure 4
Due to a inductive surge created when a coil is toggled, a standard 1N4001 diode is usually
placed across each transistor as shown in the figure, providing a safe way of dispersing thereverse current without damaging the transistor. Sometimes called a snubbing diode. The
TIP120 transistors do not need an external snubbing diode because they have a built in
diode. So the diodes shown in the drawing are the internal diodes in the TIP120 transistors.
The simplest way to operate a stepper motor with a PIC is with the full step pattern shown inTable 1. Each part of the sequence turns on only one transistor at a time, one after the other.After the sequence is completed, it repeats infinitely until power is removed.
Q1 Q2 Q3 Q4
+ - - -
- + - -
- - + -
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 120/149
- - - +
Table 1
I purposely made this first program as small as possible, simply to demonstrate how easy it is tocontrol a stepper motor. Also note the use of high and low commands to control the output lines,rather than peek and poke routines. For our purposes, high and low are sufficient.
Listing 1
' First stepper motor controller program
' Rotates motor at set speed forever
Symbol delay = B0
delay = 25
loop:
high 0pause delay
low 0
high 1pause delay
low 1
high 2
pause delay
low 2high 3
pause delaylow 3
goto loop
' use b0 as the delay variable
' set the delay to 25 ms
' turn on Q1
' wait 25 ms' turn off Q1' turn on Q2
' wait 25 ms
' turn off Q2' turn on Q3
' wait 25 ms
' turn off Q3
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 121/149
' turn on Q4
' wait 25 ms' turn off Q4
' forever
Second Basic Program
The first program was fine for demonstrating how to control a stepper motor with a PIC Micro,
but was severely limited to the one mode of operation preprogrammed into it. In this nextprogram, we will make the program controllable by external user input in the form of four
switches: SW1 will incrementally increase the delay variable, thereby slowing the rotation of the
motor. SW2 does the opposite. SW3 halts all operation while the switch is pressed. SW4 reverses
direction of the motor (CW to CCW or vice-versa) while it is closed (pressed).
listing 2
' Second stepper motor controller program' Responds to user input by changing speed or direction
Symbol delay = B0
delay = 100
forward:
high 0
pause delaylow 0
high 1
pause delaylow 1
high 2
pause delaylow 2
high 3
pause delay
low 3goto check
reverse:
high 3pause delay
low 3
high 2pause delay
low 2
high 1pause delay
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 122/149
low 1
high 0pause delay
low 0
goto check
check:
if pin4 = 0 then timeup
if pin5 = 0 then timednif pin6 = 0 then halt
if pin7 = 0 then reverse
goto forward
timeup:
delay = delay + 5
pause 50
if delay > 250 then maxif pin4 = 0 then timeup
goto check
timedn:
delay = delay - 5
pause 50if delay <20 then min
if pin5 = 0 then timedn
goto check
halt:
if pin6 = 0 then halt
goto check
max:
delay = 245goto check
min: delay = 25
goto check
' use b0 as the delay variable' delay will begin at 100 ms
' turn on Q1
' wait for delay ms
' turn off Q1
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 123/149
' turn on Q2
' wait for delay ms' turn off Q2
' turn on Q3
' wait for delay ms
' turn off Q3' turn on Q4
' wait for delay ms
' turn off Q4' check the status of switches
' turn on Q4
' wait for delay ms
' turn off Q4
' turn on Q3
' wait for delay ms' turn off Q3
' turn on Q2' wait for delay ms
' turn off Q2
' turn on Q1
' wait for delay ms' turn off Q1
' check the status of switches
' if nothing pressed, continue
' increase delay by 5 ms
' pause for 50 ms
' check switches again
' decrease delay by 5 ms
' pause for 50 ms
' check switches again
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 124/149
'check switches again
' cap the delay at 245 ms
' check switches again
' limit the delay to 25 ms
' go back and check switches
End Listing 2
As you can see by looking at the schematic (Figure 7), the "switches" used in this circuit are
pieces of jumper wire on a breadboard. The inputs (B0-B3) are kept high via Vcc through a 10Kresistor. Theses switches are activated by grounding them via another piece of jumper wire.
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 125/149
Figure 7
A note on the previous two listings: the minimum delay used in the programs was 25 ms.Depending on the clock speed of your crystal, 25 ms may be either too fast or too slow for the
rotor to move. If you are having problems getting these programs to work, this is a likely culprit
(further troubleshooting information).
Half Stepping
As previously stated, half-stepping doubles the resolution of the motor. In our case, we are usinga motor with a 5 degree / per step resolution, requiring 72 steps to complete one rotation. By half
stepping, we could double this to 2.5 degrees / pulse, requiring 144 steps to complete one
rotation. Table 2 shows the step pattern.
Step Q1 Q2 Q3 Q4
1 + - - -
2 + + - -
3 - + - -
4 - + + -
5 - - + -
6 - - + +
7 - - - +
8 + - - +
Table 2
There are two ways in which you could implement half-stepping in a PIC. One way would be todrive it directly, using the two previous listings, but replacing the high/low commands with the
pins that correspond to each step. The other (and easier) way would be to use a UCN 5804Stepper Motor IC in conjunction with the PIC.
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 126/149
The UCN 5804 Stepper Motor IC
By using an external stepper motor controller, such as the UCN 5804, you can simplify yourprograms and control as many motors as you have outputs via an array of UCN 5804's. Not only
does it allow for the control of more motors, but more importantly, it simplifies the process. You
now only have to output the pulse of your desired speed. Additionally, you can switch betweenfull and half stepping in real time via a switch on the UCN 5804 (or you may have the PICcontrol it), as well as reverse direction. A pinout for the UCN804 is shown in Figure 8.
Figure 8
The schematic we will build to use this chip is shown in Figure 9. Since we are using a 5Vstepper motor, we will be powering the UCN 5804 with a 9V wall transformer. You cannot use6V, due to the draw of the motor. The UCN 5804 can support voltages up to 35V.
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 127/149
Figure 9
Notice in the schematic that two resistors, rx and ry, do not have an assigned value. This isbecause our motor draws only 100 mA, well under the chip's supported 1,250 mA. However, if
you were to use a motor that draws the maximum or above, then you would need to use rx and ryto get the amperage under 1,250 mA. For example, a 24V motor with a phase resistance of 15
ohms would draw 1,600 mA (24/15 = 1.6). In this case, you should use _at least_ a 5 ohm
resistor for both rx and ry, which would bring the current down to 1.2 A.
Since the input of the UCN 5804 is CMOS and TTL compatible, we can connect the outputs
from the PIC directly into the UCN 5804. Two outputs are needed; one to control the step input(pin 11), and one to control the output enable (pin 15) which enables the stepper motor while
high and disables the stepper motor while low.
Pins 9 and 10 control the stepping method (half or full steps). Pin 14 controls the step direction.
Both of these controls can be manipulated by the PIC, but it is easier to control them directly
through the use of jumpers acting as switches.
All the program has to do, is output a pulse and set the output enable low. This can be
accomplished with a very simple program such as the following:
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 128/149
Listing 3
' Stepper motor control with a UCN 5804
Symbol delay = B0
low 1delay = 10
delay = delay * 1000
loop: pulsout 0,delay
goto loop
' make a delay variable
' set the output enable low' set a pulsewidth of 10 ms
' turn delay into microseconds
' send pulsewidth of delay to UCN5804
' repeat forever
End Listing 3
Notice that I added an extra step; taking the defined "delay" value and multiplying it by 1,000.
This is necessary because the pulsout command requires a pulsewidth in micro-seconds, not
milli-seconds. You can make the code even smaller by removing lines 1, 3, and 4 and replacing"delay" in line 5 with a set number in microseconds. However, I prefer to the method shown inthe listing, because it makes it easier to change the delay parameter in the more familiar
milliseconds without having to convert it to microseconds.
Speed Control via Potentiometers
The PIC Basic language has a command that allows you to read the value of potentiometers on agiven scale. This is the "pot" command, and is used in thefollowing manner:
pot pin,scale,var
Where pin is the pin the potentiometer is connected to (pins B0-7), scale is the maximum value
the command will return (in this case 245, being the maximum amount of ms we want inbetween pulses), and var is the variable the value will be placed in.
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 129/149
Using this command, we can determine the value of a potentiometer (we will be using a 50K
ohm pot) and then use it to control the pulsewidth outputted to the UCN 5804. A schematic isshown in Figure 10.
Figure 10
The program is shown in listing 4. First, it reads the value of pin B2 (the potentiometer), thenplaces it on a scale of 245. That value is then multiplied by 1,000 (converting it intomicroseconds) and set to the UCN 5804.
Listing 4
' Controlling a stepper motor with the UCN 5804 and a potentiometer
Symbol delay = B0
low 1
start:
pot 2,245,delay
if delay < 25 min
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 130/149
goto turn
turn:
delay = delay * 1000
pulsout 0,delay
goto start
min:
delay = 25goto turn
' make a delay variable
' set the output enable low
' read pot at pin B2
' set min delay to 25' if delay is over 25, start moving
' turn delay into microseconds
' send to UCN 5804' go back to start
' bottom out the delay at 25' start the motor
End Listing 4
Not quite as complicated as you may have expected (thanks to the use of the UCN 5804). Notice
again, the minimum delay set at 25 ms. If you would like to make it a lower number (thereby
making the motor turn faster), simply change all occurrences of "25" to the number desired.
Controlling Stepper Motors with a PIC Microcontroller
If your motor does not move at all when the program is active, then the most likely problem is
that the diodes are facing the wrong direction. Check the schematic for proper wiring.
If the motor is moving, but does so only sporadically or jiggles back and forth, then there can be
a number of possible causes:
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 131/149
1. There is not enough power going to the motor. This is often the case when using batteries
which cannot support the drain of the motor. It is recommended that you use a wall transformerto power the motor in combination with a 7805 voltage regulator to power the circuitry.
2. You are not using TIP 120 transistors, or a variation that is not able to support the load of the
stepper motor.
3. The stepper motor is not wired to the correct transistor. Check the coil resistance with an ohmmeter and rewire properly. For motors purchased from us, the pinouts are available here.
4. The pulse frequency is higher than that which the motor can react to, causing a malfunction.
The programs in this article use the delay variable to control pulse frequency. Try increasing the
value to decrease pulse frequency.
GENERATION OF GATE SIGNAL FOR CONVERTER AND INVERTER
Output 120V
AC/ Variable
Load
Solar Panel Charging
Circuit
Battery Inverter
Circuit
Hand CrankStation
User
Interface
Microcontroller
Variable
Light Source
Phil (Power)
Sierra (Station)
Luis (Interface)
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 132/149
Figure 1: Project Block Diagram
2 Design
2.1 Component Descriptions
2.1.1 Variable Light Source
The Variable Light Source is used to simulate different levels of solar radiation. It will be a small
desk lamp, about two feet high with an adjustable neck and a 40 W soft white light bulb. This lamp will
be attached to a dimmer that will slide to allow various amount of light output. Users of the circuit will
be able to change the amount of light the panel receives and therefore see what effects that has on
solar panel voltage and efficiency.
2.1.2 Solar Panel
The Solar Panel is the backbone for the power system and therefore was mandatory to size first.
Originally a Universal Power Group (18V, .56A 10W) solar panel was going to be used however, a six cell
white Sun Power promotional panel was available on loan from the Power Group and was selected for
this reason. Since the panel was promotional it was necessary to map out its IV-characteristics. The
technique used to do this is outlined in section 3.2.1. The results were an open circuit voltage around 4V
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 133/149
and a short circuit current around 4A with a maximum power achieved of 9.68W. This fits our
requirements of the panel being able to provide 8W which is described in section 2.2.1.
2.1.3 Charging Circuit
The charging circuit is used to provide a constant float voltage to the Lead-Acid Battery. It willtake the solar panels 3-6V as input and boost it to 13.7V +/- 0.1V in order to match the batteries
charging requirements. The converter will be built with discrete parts and the schematic is given in
Error! Reference source not found. below. A MTP50N06 MOSFET (50V/60A) was used since its voltage
and current ratings are well above the required 11V/5A limit. A 1N5822 Schottky Rectifier was selected
due to its low 0.525V on-state voltage drop. To drive the MOSFET an IR2112 low-side gate driver will be
used. The output capacitors are two 100µF electrolytic capacitors. The choice for two capacitors rather
than one comes from a desire to reduce the overall effective series resistance (ESR). By placing two
similar capacitors in parallel the ESR will drop to half its original value simply based on basic resistor
physics. The input inductor is a 325µH inductor sized in order to reduce the current ripple of the circuit.
It was wound using a powdered iron core of material type #26 and 28 gauge wire. The circuit will utilize
the microcontroller as a feedback loop to insure it meets the batteries charging specifications.
Figure 2: Charging Circuit Design
2.1.4 Battery
The battery was selected to handle a load up to 100W for at least a 50 minute class period. The
Universal Power Group 12V 7Ah battery was borrowed from the Power Lab. It will take a charge input
from the charging circuit and output power to the inverter. The voltage of the battery will be monitored
by the PIC through a simple resistor divider network. Current will also be monitored by the PIC through a
5V 5A Current Sensor. This information will then be displayed to the user.
2.1.5 Inverter Circuit
The inverter is the final stage in the conversion process. It will take the output from the battery
and convert it to 120VAC to drive the variable load station. Originally the goal was to have 60Hz sine
wave at the output but due to the unavailability of a 100W transformer it was decided to keep the 100
kHz switching and provide a 100 kHz square wave at the output. It will be built discretely and the
schematic is given in Error! Reference source not found. below. The MOSFETs used will be MTP50N06
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 134/149
(50V/60A) which was selected because they had suitable voltage and current ratings. Two IRS2003 Dual
High/Low side gate drivers will be used to drive the FETs. These drivers were selected due to the fact
that they came with a built in dead time between high and low driving. This dead time is necessary to
prevent creating a short across the battery terminals which is known as “shoot-through current”. The
circuit will take a PWM signal generated from the PIC. A transformer will be the final stage in the
conversion and is used to boost the inverters output from the 12V to 120V value needed for 120Vrms.
The inverter should be able to handle 100W at the output in order to drive the entire range of the
Variable Load Station. Finally, it will be monitored by the microcontroller to provide information on the
power delivered to the load.
Figure 3: Inverter Circuit Design
2.1.6 Variable Load Station
The Variable Load Station provides the educator the ability to demonstrate the effect of
different loading conditions on the overall efficiency and operation of the power circuitry. To mimic real
world applications a load that varies from 0 – 100W was desired. This is handled by implementing the
circuitry depicted in figure 4 below. Each resistor is a PF1260 High Power Silicon Resistor (20W, 1kΩ).
Each resistor being 1kΩ means that each one will consume 14.4W when switched into the circuit. The
switches are Single Pull Double Throw (SPDT) Switches that were provided by the parts shop. The station
has its own printed circuit board (PCB) in order to allow the switches to be mounted to the external of
the display case.
Figure 4: Variable Load Station Schematic
2.1.7 Microcontroller
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 135/149
As seen below in Error! Reference source not found., the microcontroller circuit consists of a
PIC18LF2610, 12V to 5V voltage regulator IC, a 0.1µF capacitor connected at VDD in order to clean up
the power signal, and both VSS connected to ground. The PIC has a TX and RX outputs and inputs that
will be used to connect to the Sparkfun BlueSMiRF Bluetooth module RX and TX pins respectively, which
will facilitate the Bluetooth connection between the PIC and the Android phone. The PIC’s output pins
24 and 13 are CCP2 and CCP1 respectively and are the PWM outputs that are connected to the charging
circuit and the inverter circuit. Pins 2-5, 7, and 21 are configured as inputs with an analog to digital
converter. These inputs will be used to measure in voltage and current at the specific probe points in
order to calculate power, and to monitor and maintain the optimal charging circuit voltage.
Figure 5: Microcontroller Schematic
2.1.8 User Interface Application
The user interface block will be design using Eclipse IDE, Java Development Tool, and XML based
layout files. The end product will be an Android app that the user can download to their Android phone
and follow the different components of the project on their own while learning about the process and
looking at real time data values such as power, voltage, current, duty cycle, and frequency. The app will
look similar to the layouts shown in Figures 6.
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 136/149
Figure 6: Android App Home Screen
2.1.9 Hand Crank Station
The Hand Crank Station is meant as a fun way for the user to compare the power produced by
the solar panel to that produced by a more conventional mechanical method. The station consists of a
12V DC motor connected to an 8.5cm shaft through a gearbox. The gearbox was necessary based on our
testing which showed a human can spin the shaft at a slower 40-60RPM than is need for the 1800RPM
motor. The 65.5:1 gear ratio was selected due to availability in the machine shop and worked well.
2.2 Design Calculations
2.2.1 Solar Panel
The panel should be able to charge the 80Wh battery 10% in a one hour class period. This meansthat the panel should be able to provide 8W at any given time. This is given by equation 1 below.
P = (1)
The 10W promotional panel obtained from the power lab will provide enough power.
2.2.2 Charging Circuit
Input: 3-6Vdc from Solar Panel
Output: 13.7V +/- 0.1Vdc to the Battery
PIC to deliver Switching Signal
The characteristic equation for a Boost topology converter is given in equation 2 below. This
assumes ideal parts (i.e. no voltage drop across the diode) and was used when making the design
calculation.
(2)
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 137/149
As a quick check to see whether one or two boosts would be needed the Duty values were calculated in
the extreme cases. These values should be between 10-90% and as can be seen below they came out
within this range.
(3)
(4)
One issue is how close the duty cycle gets to 90% even when using a simplified model. This implies a
need to check a more realistic model by including a voltage drop across the diode of 0.5V (the value for
the 1N5822). The new equation for duty cycle is worked out below.
(5)
Solving for D yields:
(6)
D = 77%
This is still below the 90% mark so the design can be continued.
With the duty signal verified the parts now need to be selected. First is the capacitor sizing
which determines the ripple on the output of the converter. This is done by using the characteristicequation for a capacitor given below.
(7)
(8)
For a Boost converter the current is simply the output current when the MOSFET is on. The current
relationship is simply the inverse of the voltage relationship. Therefore, for our circuit, the output
current will be either 1.45A or 2.2A in the worst case scenario when the solar panel is supplying its full
5A. Using the values above the Capacitance should be 66µF. The selection of two 100µF came from adesire to reduce ESR.
Now the diode and MOSFET must be sized for voltage and current ratings. Both the diode and
MOSFET must be able to block:
(9)
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 138/149
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 139/149
(13
)
2.2.5 Inductor Design
Because inductors are such specialty items it was necessary to wind our own inductors. A
powdered iron core was selected to act as the magnetic medium due to the wide range of core types
and their availability in the parts shop. The characteristic equation for these inductors is given below
where N is the number of windings and AL is given in .
(14)
Since the required inductance value was calculated above in the charging circuit section it is desired to
find a material with an AL value that will give a reasonable amount of number of turns. Solving for AL inthe equation above and taking N to be 100 yields:
(15)
(16)
The material T-80-26 was found in the parts shop with an AL value of 450. Using this material with 80
turns would yield a value of 288µH according to the inductance equation above. This is what was
selected and after winding was measured using the LRC Bridge 2400 to be 325µH. This discrepancy is
acceptable and most likely occurred due to incorrect counting when winding the inductor.
2.2.6 Variable Load Station
The load station has to be able to handle a maximum of 100W and be incremental in nature.
Ideally each resistor will consume 10W which leads to a total of 10 incremental steps that can be
demonstrated. To find the resistance needed for each step the equation below can be solved using V as
120VAC.
P = (17)
R = (18)
This yields R = 1.44 kΩ. 1kΩ resistors were selected due to availability which led to 14.4W dissipated in
each resistor. This meant a total of 7 resistors are needed to reach the 100W maximum.
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 140/149
2.2.7 Microcontroller
Equation 19 below will be used to initialize the charging circuits PWM signal duty cycle, where
Vin is the monitored voltage, Vout is to be maintained at 13.7V, and D is the duty cycle of the PWM
signal.
(19)
When using the calculation above the duty cycle should stay between 10%-90% range so as to not
damage the circuit. After initializing the duty cycle value for the PWM signal the charging circuit voltage
is monitored in order to change the D to maintain a 13.7V at Vout.
The voltage and current values measured at the probe points will be used to measure the power at
specific points in the process through the use of equation 20.
(20)
(21)
(22)
3. Design Requirements and Verification
3.1 Requirements
Status Performance Requirement Testing and Verification Procedure
Complete 1) The solar panel will provide 8 W
a) The open circuit voltage will
be approximately 4 V
outside on a day when the
sun is unobstructed for at
least 70% of the time
b) The short circuit current of
the solar panel will be 5-6 A
outside on a day when the
sun is unobstructed for atleast 70% of the time
c) Plot of the solar panel’s I-V
curve will be fitted to the
curve of Figure 1 within 10%
1) Measure the output power
when the lamp is on at full
power and is shone directly
onto the solar panel
a) Obtain the open circuit
voltage with the solar panel
outside at noon on a day
with >70% sun by
measuring voltage with a
known resistanceb) Obtain short circuit current
of the solar panel by
dividing the obtained
voltage by the known
resistance
c) Once the current and
resistances are known, the
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 141/149
results will be plotted on a
graph and the output will be
analyzed and included in
documentation
Complete 2) The charging circuit will provide
13.7V +/- 0.1V for charging of
the battery over entire solar
panel range.
a) Can handle the 2-5V input
variation with external
Switching Signal.
b) Gate of the MOSFET is
receiving a 100kHz Switching
signal.
2) Monitor the converter recording
Pin
,Pout
, Vout
, Vin
to see proper
operation and record efficiency.
a) Connect input to variable
power supply. Measure
output voltage on
oscilloscope to verify proper
13.7 +/- 0.1V output. Ensure
duty cycle is within 10-90%.
b) Check to see a 0-5V square
wave at Pin 24 of the PIC.
Check to see a 0-12V square
wave at Pin 7 of the Gate
Driver. Both signals shouldbe 100 kHz.
Transformer Needed 3) The inverter should convert the
output from the battery into
120VAC to either of the loads
c) Can handle 12Vdc to 120Vac
conversion over entire
output range with 100 kHz
switching signal.
d) Can accept PWM signal from
PIC
3) Test the converter over the
entire load range. Record
efficiency data as well as display
output waveform on
oscilloscope.
a) Vary load over 0-100W
range. View the output
voltage waveform and
compare to a 120V square
wave. Its frequency shouldbe 100 kHz.
b) Using the oscilloscope, view
the PIC PWM signal from
Pin 13. It should be a 0-5V
square wave with a duty
cycle of 50%. With the
oscilloscope view both the
outputs of the gate driver.
They should be 0-12V
square waves. One will be
inverted while the other is
not.
Complete 4) The microcontroller will make
accurate measurements of the
inputs including the power
measurements from the solar
panel and hand crank, the
charging of the batter, and the
efficiency of the circuitry to
4) Because the output of the solar
panel and the hand crank can be
found from aforementioned
processes, lab equipment will
be used to test values from the
microcontroller and a chart will
be created to ensure
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 142/149
within 5% of the actually value
A. Charging Circuit PWM
Output will be 100KHz with
feedback controlled duty
cycle value
B. Inverter Circuit PWM Output
will be 100KHz with a 50%
duty cycle
C. Analog to Digital Converter
will measure accurate
voltage and current
measurements
D. PIC will send and receive
data via Bluetooth
accurately
a) 5V voltage regulation at VDD
on the PIC
functionality within 5% of the
actual value.
a) View oscilloscope to ensure
the microcontroller is
producing accurate values.
b) The Bluetooth connectivity
will be tested by using test
text to check connectivity.
c) An oscilloscope will be used
to compare the actual duty
cycle.
d) Use a multimeter to ensure
the LM7805 IC is regulating
voltage properly from 12V.
Complete 5) Hand Crank Station shouldoutput 12V+/-2V
a) The hand crank startup
torque should be no greater
than 6.87 Nm
5) Hook output to voltmeter andverify 12V +/-1V at the output
under moderate human strain
a) Measure torque by finding
the product of the length of
the arm, the magnitude of
the force and the sine of the
angle between the force
vector and arm vector
Complete 6) The Android App will present
the project data point values,
update its values real-time viaBluetooth, and provide
summary information on the
different processes in the
project.
A. Bluetooth connectivity
through the app
B. Provide voltage, current,
power, and duty cycle,
values
C. Provide summary
information on the Charging
Circuit, Inverter Circuit,
120VAC Variable Load
Station, Hand Crank Station,
and Battery.
6) The Android App functionality
can be observed by running the
app on an Android phone.A. Confirm pairing and
connection between the PIC
and app through real-time
updates of the data points.
Figure 7: Verification Table
3.2 Verification Testing
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 143/149
3.2.1 Solar Panel
The solar panel was tested outside on three separate occasions. Since the panel was a
promotional item no datasheet exists for the unit. Because of this the data was compared to a typical IV-
Curve of a solar panel given in figure 8 below.
Figure 8: Typical IV-Curve of Solar Panel
To get different points on the panels IV-Curve a system of parallel resistors like that of figure 9was used. As more resistors are switched in the overall resistance is decreased and the curve is traced
from the open circuit voltage (Voc) towards the short circuit current (Isc). Data for our three tests are
given below in figure 10, 11, and 12. Figure 13 is a graph of test 3 which yielded the best results. Test 3
yielded the best results because the values of the resistors (10Ω) were low enough to begin the change
from the constant voltage region near the open circuit voltage to the constant current region. The other
tests used resistors that were too large (3kΩ, 39Ω) and therefore the data obtained only covered a small
portion of the graph close to Voc. Figure 13 shows that the panel fits a typical curve although the slope
from Voc to the knee of the curve is much flatter. Also, still more resistors would have been needed in
order to trace the curve even closer to the sort circuit current.
Figure 9: Schematic for Solar Panel Testing
Test 1 on February 22nd
Ohms
Open
Circuit 3000 2000 1000 666.67 560 280 186 112
Voltage 3.33 3.24 3.3 3.26 3.26 3.19 3.19 3.18 2.96
Current 0 0.00108 0.00165 0.00326 0.00489 0.005696 0.011393 0.017097 0.026429
Power 0 0.003499 0.005445 0.010628 0.015941 0.018172 0.036343 0.054368 0.078229
Figure 10: Test 1 Data
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 144/149
Test 2 on February 29th
Ohms
Open
Circuit 39 19.5 13 9.75 7.8 6.5
Voltage 3.88 3.76 3.75 3.6 3.6 3.7 3.66
Current 0 0.09641 0.192308 0.276923 0.369231 0.474359 0.563077
Power 0 0.362503 0.721154 0.996923 1.329231 1.755128 2.060862Figure 11: Test 2 Data
Test 3 on March 9th
Ohms Open Circuit 10 5 3.33 1.666667 1.111111 0.833333 0.714286
Voltage 3.81 3.7 3.62 3.5 3.28 3.04 2.85 2.63
Current 0 0.37 0.724 1.051051 1.968 2.736 3.42 3.682
Power 0 1.369 2.62088 3.678679 6.45504 8.31744 9.747 9.68366
Figure 12: Test 3 Data
Figure 13: IV-Curve for Test 3
3.2.2 Charging Circuit
The charging circuit has been tested using an external switching signal and Power Supplies. The
12V and 5V logic level supplies were provided by the HP E3631A Triple Outlet Power Supply. The solar
panel input voltage was provided by the Kenwood Variable DC Supply and was varied over the entire 3-
6V range. Finally, the switching signal was provided by the 8011A Pulse Generator which allowed for
control over the switching frequency and pulse width. The frequency was set to 100kHz in order to test
the circuit as designed.
It was desirable to see the efficiency of the converter over the range of desired inputs as well as
over a range of Load levels. Two separate tests were performed.
First, the Load was set at a constant 1.25 W by putting a 150 Ω load across the output. The
voltage was then varied from 3V to 6V in increments of 1V to see the effects of varying solar panel inputvoltage on converter efficiency. Data was also collected using the Oscilloscope to see the ripple on the
output voltage. The results are given in Figure 14 and Figure 15 below:
Vin Vout Delta V Efficiency
2.94 13.71 0.1 0.71
3.95 13.68 0.15 0.8
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 145/149
4.98 13.76 0.14 0.85
5.97 13.72 0.11 0.87
Figure 14: Data for Constant Power Varying Input Voltage
Figure 15: Graph of Efficiency vs. Input Voltage Next, the input voltage was held at 5V and the input power was varied from 1W to 5W. This is a
good estimate of what we believe our panel will be able to provide and was made based on the solartesting that Sierra did. Again data was collected in order to obtain efficiency of the converter. The
results are given in Figure 16 and Figure 17 below:
Vin Vout Pin Pout Efficiency
4.98 13.71 0.87 0.74 0.85
4.98 13.76 1.48 1.26 0.85
4.95 13.72 2.32 1.91 0.82
4.89 13.73 5.2 3.9 0.75
Figure 16: Data for Constant Voltage Varying Power
Figure 17: Efficiency vs. Input Power
These tests verify that the converter can function over the expected input voltage range and
provide adequate output voltage. The ripple on the output is slightly higher than desired however this
shouldn’t cause any problems with the functioning of the overall circuit. If it becomes an issue more
capacitance can be used on the output or a smaller switching frequency can be used for the switching
signal both of which should reduce voltage ripple.
3.2.3 Inverter Circuit
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 146/149
To test the functioning of the inverter circuit a simple constant load was attached to the output
of the converter. Data was then recorded through the oscilloscope to demonstrate the delay time
between the high and low gate drivers which are demonstrated in Figure 18.
Figure 18: Gate Delay for the IRS2003
Data was also taken to see the output voltage and frequency. This data is shown in Figure 19
with CH1= Reference Signal from PIC, CH2 = High Side Gate Drive Signal, CH3= Low Side Gate Drive
Signal, and CH4 being the Output Voltage of the inverter. It is significant to notice that the output signal
is a 100 kHz square wave due to the inability to find a suitable 100 W 60 Hz transformer. Also, it is
significant to notice 12 VAC rather than the 120 VAC desired. This was due to a failure in the design of
the transformer which we believe to be inadequate to handle the 100 kHz signal. A new magnetic core
would need to be selected to avoid transformer saturation.
Figure 19: Testing and Verification of Inverter Circuit
3.2.4 Microcontroller
As seen in Figure 20, the 12V to 5V regulator is working as it should maintain a 5V supply to the
PIC. In Figure 21, it can be seen that the output of the PIC charging circuit PWM produces the desired
100 kHz signal with a feedback controlled variable duty cycle that changes per the monitoring code to
keep the charging circuit Vout at 13.7V. Figure 22 shows that the inverter circuit PWM is at 100kHz and
a constant 50% duty cycle. As seen in Figure 23, the Analog to Digital converter works as expected.
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 147/149
Figure 20: 12V to 5V Voltage Regulator
Figure 21: PIC Charging Circuit PWM Output
Figure 22: PIC Inverter Circuit PWM Output
Actual Voltage ADC Voltage Percent Error
1 1 0.00%
2 2 0.00%
3 3 0.00%
4 4 0.00%
5 5 0.00%
6 6 0.00%
7 8 14.29%
8 9 12.50%10 11 10.00%
14 16 14.29%
Figure 23: Analog to Digital Converter Testing Results
3.2.5 Current Sensors
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 148/149
To measure current and report it to the PIC 5V 5A Hall Effect current sensors were used.
According to the manufacturers datasheet the relationship between input current to the output voltage
is given by the equation below.
(23)
To verify this relationship a simple test circuit was hooked up following the schematic given on the
datasheet in Figure 24.
Figure 24: Current Sensor Testing Setup The pins 1 and 2 were connected to a constant DC voltage source provided by the Kenwood Supply in
the Power Lab. Pins 3 and 4 went out to the load while Pin 7 was monitored by the bench multimeter.
We then swept the input voltage over a range while keeping the output load constant. We measured
the current through Pins 1 and 3 and the voltage out at Pin 7. This allowed for the creation of a V vs. I
graph that is given in Figure 25. The data for our tests is given in Figure 26.
Figure 25: V vs. I Curve Generated For Current Sensors
As can be seen the measured values yielded a relationship given by the equation below.
(24)
This is slightly different than the value given on the manufacturers datasheet and was used when
programming the PIC.
Current sensor testing March 29
Voltage ResistanceMeasured Vout
Vout % Error
7/30/2019 ACA STUDY Material
http://slidepdf.com/reader/full/aca-study-material 149/149