DsPIC30F Family Reference Manual
DsPIC30F Family Reference Manual
• Microchip believes that its family of products is one of the most secure families of its kind on the market today, when used in the
intended manner and under normal conditions.
• There are dishonest and possibly illegal methods used to breach the code protection feature. All of these methods, to our
knowledge, require using the Microchip products in a manner outside the operating specifications contained in Microchip’s Data
Sheets. Most likely, the person doing so is engaged in theft of intellectual property.
• Microchip is willing to work with the customer who is concerned about the integrity of their code.
• Neither Microchip nor any other semiconductor manufacturer can guarantee the security of their code. Code protection does not
mean that we are guaranteeing the product as “unbreakable.”
Code protection is constantly evolving. We at Microchip are committed to continuously improving the code protection features of our
products. Attempts to break Microchip’s code protection feature may be a violation of the Digital Millennium Copyright Act. If such acts
allow unauthorized access to your software or other copyrighted work, you may have a right to sue for relief under that Act.
Introduction
Section 1. Introduction
HIGHLIGHTS
This section of the manual contains the following topics:
1.1 Introduction
Microchip is a leading provider of microcontrollers and analog semiconductors. The company’s
focus is on products that meet the needs of the embedded control market. We are a leading
supplier of:
• 8-bit general purpose microcontrollers (PICmicro® MCUs)
• dsPIC30F 16-bit microcontrollers
• Speciality and standard non-volatile memory devices
• Security devices (KEELOQ®)
• Application specific standard products
Please request a Microchip Product Line Card for a listing of all the interesting products that we
have to offer. This literature can be obtained from your local sales office, or downloaded from the
Microchip web site (www.microchip.com).
1.2 Manual Objective
PICmicro and dsPIC30F devices are grouped by the size of their Instruction Word and Data Path.
The current device families are:
1. Base-Line: 12-bit Instruction Word length, 8-bit Data Path
2. Mid-Range: 14-bit Instruction Word length, 8-bit Data Path
3. High-End: 16-bit Instruction Word length, 8-bit Data Path
4. Enhanced: 16-bit Instruction Word length, 8-bit Data Path
5. dsPIC30F: 24-bit Instruction Word length, 16-bit Data Path
This manual describes the dsPIC30F 16-bit MCU family of devices.
This manual explains the operation of the dsPIC30F MCU family architecture and peripheral
modules, but does not cover the specifics of each device. The user should refer to the data sheet
for device specific information. The information that can be found in the data sheet includes:
• Device memory map
• Device pinout and packaging details
• Device electrical specifications
• List of peripherals included on the device
Code examples are given throughout this manual. These examples sometimes need to be
written as device specific as opposed to family generic, though they are valid for most other
devices. Some modifications may be required for devices with variations in register file
mappings.
Introduction
Each part of the dsPIC30F device can be placed into one of three groups:
1. CPU Core
2. System Integration
3. Peripherals
1.3.3 Peripherals
The dsPIC30F has many peripherals that allow the device to be interfaced to the external world.
The peripherals discussed in this manual include:
1. I/O Ports
2. Timers
3. Input Capture Module
4. Output Compare Module
5. Quadrature Encoder Interface (QEI)
6. 10-bit A/D Converter
7. 12-bit A/D Converter
8. UART Module
9. SPITM Module
10. I2CTM Module
11. Data Converter Interface (DCI) Module
12. CAN Module
Introduction
Table 1-1 defines some of the symbols and terms used throughout this manual.
Introduction
Revision A
This is the initial released revision of this document.
Revision B
There were no technical content or editorial revisions to this section of the manual, however, this
section was updated to reflect Revision B throughout the manual.
Revision C
There were no technical content revisions to this section of the manual, however, this section was
updated to reflect Revision C throughout the manual.
NOTES:
CPU
Section 2. CPU
HIGHLIGHTS
This section of the manual contains the following topics:
2.1 Introduction
The dsPIC30F CPU module has a 16-bit (data) modified Harvard architecture with an enhanced
instruction set, including significant support for DSP. The CPU has a 24-bit instruction word, with
a variable length opcode field. The program counter (PC) is 24-bits wide and addresses up to
4M x 24 bits of user program memory space. A single cycle instruction pre-fetch mechanism is
used to help maintain throughput and provides predictable execution. All instructions execute in
a single cycle, with the exception of instructions that change the program flow, the double-word
move (MOV.D) instruction and the table instructions. Overhead free program loop constructs are
supported using the DO and REPEAT instructions, both of which are interruptible at any point.
The dsPIC30F devices have sixteen 16-bit working registers in the programmer’s model. Each
of the working registers can act as a data, address, or address offset register. The 16th working
register (W15) operates as a software stack pointer for interrupts and calls.
The dsPIC30F instruction set has two classes of instructions: the MCU class of instructions and
the DSP class of instructions. These two instruction classes are seamlessly integrated into the
architecture and execute from a single execution unit. The instruction set includes many
Addressing modes and was designed for optimum C compiler efficiency.
The data space can be addressed as 32K words or 64 Kbytes and is split into two blocks,
referred to as X and Y data memory. Each memory block has its own independent Address
Generation Unit (AGU). The MCU class of instructions operate solely through the X memory
AGU, which accesses the entire memory map as one linear data space. Certain DSP instruc-
tions operate through the X and Y AGUs to support dual operand reads, which splits the data
address space into two parts. The X and Y data space boundary is device specific.
The upper 32 Kbytes of the data space memory map can optionally be mapped into program
space at any 16K program word boundary defined by the 8-bit Program Space Visibility Page
(PSVPAG) register. The program to data space mapping feature lets any instruction access
program space as if it were data space. Furthermore, RAM may be connected to the program
memory bus on devices with an external bus and used to extend the internal data RAM.
Overhead free circular buffers (modulo addressing) are supported in both X and Y address
spaces. The modulo addressing removes the software boundary checking overhead for DSP
algorithms. Furthermore, the X AGU circular addressing can be used with any of the MCU class
of instructions. The X AGU also supports bit-reverse addressing to greatly simplify input or
output data reordering for radix-2 FFT algorithms.
The CPU supports Inherent (no operand), Relative, Literal, Memory Direct, Register Direct
and Register Indirect Addressing modes. Each instruction is associated with a predefined
Addressing mode group depending upon its functional requirements. As many as 6 Addressing
modes are supported for each instruction.
For most instructions, the dsPIC30F is capable of executing a data (or program data) memory
read, a working register (data) read, a data memory write and a program (instruction) memory
read per instruction cycle. As a result, 3 operand instructions can be supported, allowing
A+B=C operations to be executed in a single cycle.
The DSP engine features a high speed, 17-bit by 17-bit multiplier, a 40-bit ALU, two 40-bit
saturating accumulators and a 40-bit bi-directional barrel shifter. The barrel shifter is capable of
shifting a 40-bit value up to 15 bits right, or up to 16 bits left, in a single cycle. The DSP instruc-
tions operate seamlessly with all other instructions and have been designed for optimal
real-time performance. The MAC instruction and other associated instructions can concurrently
fetch two data operands from memory while multiplying two W registers. This requires that the
data space be split for these instructions and linear for all others. This is achieved in a
transparent and flexible manner through dedicating certain working registers to each address
space.
The dsPIC30F has a vectored exception scheme with up to 8 sources of non-maskable traps
and 54 interrupt sources. Each interrupt source can be assigned to one of seven priority levels.
A block diagram of the CPU is shown in Figure 2-1.
X Address Bus
CPU
Y Data Bus
X Data Bus
16 16 16
16
Interrupt Data Latch Data Latch
Controller PSV & Table
Data Access Y Data X Data
24 Control Block 8 16 RAM RAM
(4 Kbytes) (4 Kbytes)
16 16
Address Address
24 Latch Latch
16 16
Y Address Bus
24 PCU PCH PCL X RAGU
Program Counter 16 X WAGU
Stack Loop
Control Control
Address Latch Logic Logic
Program Memory
(144 Kbytes) Y AGU
Data EEPROM
(4 Kbytes) EA MUX
16
Data Latch 16
ROM Latch
16 16
IR
24
Literal Data
16
16 x 16
W Reg Array 16
Instruction
16 16
Decode &
Control
Divide
Control Signals DSP Support
to Various Blocks Power-up Engine
Timer
I/O Ports
SPI1, UART1,
Timers DCI UART2
SPI2
CPU
W1
W2
W3
W4
DSP Operand W5
Registers
W6
W7 Working/Address
Registers
W8
W9
DSP Address
Registers W10
W11
W12
PUSH.S and POP.S Shadows
W13
Frame Pointer/W14
Stack Ptr/W15 0
39 31 15 0
DSP ACCA ACCAU ACCAH ACCAL
Accumulators ACCB ACCBU ACCBH ACCBL
22 0
0 Program Counter
7 0
TBLPAG Data Table Page Address
7 0
PSVPAG Program Space Visibility
Page Address
15 0
RCOUNT REPEAT Loop Counter
15 0
DCOUNT DO Loop Counter
22 0
DOSTART 0 DO Loop Start Address
22 0
DOEND 0 DO Loop End Address
SRH SRL
OA OB SA SB OAB SAB DA DC IPL<2:0> RA N OV SZ C Status Register
15 0
CORCON Core Control Register
Note: DCOUNT, DOSTART and DOEND have one level of shadow registers (not shown) for nested DO loops.
W0 is a special working register because it is the only working register that can be used in file
register instructions. File register instructions operate on a specific memory address contained
in the instruction opcode and W0. W1-W15 cannot be specified as a target register in file register
instructions.
The file register instructions provide backward compatibility with existing PICmicro® devices
which have only one W register. The label ‘WREG’ is used in the assembler syntax to denote W0
in a file register instruction. For example:
MOV WREG,0x0100 ; move contents of W0 to address 0x0100
ADD 0x0100,WREG ; add W0 to address 0x0100, store in W0
Note: For a complete description of Addressing modes and instruction syntax, please
refer to the dsPIC30F Programmer’s Reference Manual (DS70032).
Since the W registers are memory mapped, it is possible to access a W register in a file register
instruction as shown below:
MOV 0x0004, W10 ; equivalent to MOV W2, W10
where 0x0004 is the address in memory of W2.
Further, it is also possible to execute an instruction that will attempt to use a W register as both
an address pointer and operand destination. For example:
MOV W1,[W2++]
where:
W1 = 0x1234
W2 = 0x0004 ;[W2] addresses W2
In the example above, the contents of W2 are 0x0004. Since W2 is used as an address pointer,
it points to location 0x0004 in memory. W2 is also mapped to this address in memory. Even
though this is an unlikely event, it is impossible to detect until run-time. The dsPIC30F ensures
that the data write will dominate, resulting in W2 = 0x1234 in the example above.
Byte instructions which target the W register array only affect the Least Significant Byte of the
target register. Since the working registers are memory mapped, the Least and Most Significant
Bytes can be manipulated through byte wide data memory space accesses.
The PUSH.S and POP.S instructions are useful for fast context save/restore during a function call
or Interrupt Service Routine (ISR). The PUSH.S instruction will transfer the following register
CPU
values into their respective shadow registers:
• W0...W3
• SR (N, OV, Z , C, DC bits only)
The POP.S instruction will restore the values from the shadow registers into these register
locations. A code example using the PUSH.S and POP.S instructions is shown below:
MyFunction:
PUSH.S ; Save W registers, MCU status
MOV #0x03,W0 ; load a literal value into W0
ADD RAM100 ; add W0 to contents of RAM100
BTSC SR,#Z ; is the result 0?
BSET Flags,#IsZero ; Yes, set a flag
POP.S ; Restore W regs, MCU status
RETURN
The PUSH.S instruction will overwrite the contents previously saved in the shadow registers. The
shadow registers are only one level in depth, so care must be taken if the shadow registers are
to be used for multiple software tasks.
The user must ensure that any task using the shadow registers will not be interrupted by a higher
priority task that also uses the shadow registers. If the higher priority task is allowed to interrupt
the lower priority task, the contents of the shadow registers saved in the lower priority task will
be overwritten by the higher priority task.
The following registers are automatically saved in shadow registers when a DO instruction is
executed:
• DOSTART
• DOEND
• DCOUNT
The DO shadow registers are one level in depth, permitting two loops to be automatically nested.
Refer to Section 2.9.2.2 “DO Loop Nesting” for further details.
W15 is initialized to 0x0800 during all Resets. This address ensures that the stack pointer (SP)
will point to valid RAM in all dsPIC30F devices and permits stack availability for non-maskable
trap exceptions, which may occur before the SP is initialized by the user software. The user may
reprogram the SP during initialization to any location within data space.
The stack pointer always points to the first available free word and fills the software stack working
from lower towards higher addresses. It pre-decrements for a stack pop (read) and
post-increments for a stack push (writes), as shown in Figure 2-3.
When the PC is pushed onto the stack, PC<15:0> is pushed onto the first available stack word,
then PC<22:16> is pushed into the second available stack location. For a PC push during any
CALL instruction, the MSByte of the PC is zero-extended before the push as shown in Figure 2-3.
During exception processing, the MSByte of the PC is concatenated with the lower 8 bits of the
CPU status register, SR. This allows the contents of SRL to be preserved automatically during
interrupt processing.
15 0
CALL SUBR
Stack Grows Towards
Higher Address
CPU
example, the contents of W0 can be pushed onto the stack by:
PUSH W0
This syntax is equivalent to:
MOV W0,[W15++]
The contents of the top-of-stack can be returned to W0 by:
POP W0
This syntax is equivalent to:
MOV [--W15],W0
Figure 2-4 through Figure 2-7 show examples of how the software stack is used. Figure 2-4
shows the software stack at device initialization. W15 has been initialized to 0x0800. Further-
more, this example assumes the values 0x5A5A and 0x3636 have been written to W0 and W1,
respectively. The stack is pushed for the first time in Figure 2-5 and the value contained in W0 is
copied to the stack. W15 is automatically updated to point to the next available stack location
(0x0802). In Figure 2-6, the contents of W1 are pushed onto the stack. In Figure 2-7, the stack
is popped and the top-of-stack value (previously pushed from W1) is written to W3.
0x0000
W15 0x0800
0xFFFE
W15 = 0x0800
W0 = 0x5A5A
W1 = 0x3636
0x0000
0x5A5A 0x0800 PUSH W0
W15 0x0802
0xFFFE
W15 = 0x0802
W0 = 0x5A5A
W1 = 0x3636
0x0000
PUSH W1
0x5A5A 0x0800
0x3636 0x0802
W15 0x0804
0xFFFE
W15 = 0x0804
W0 = 0x5A5A
W1 = 0x3636
0x0000
POP W3
0x05A5A 0x0800
W15 0x03636 0x0802
0xFFFE
W15 = 0x0802
0x3636 → W3
Note: A Stack Error Trap may be caused by any instruction that uses the contents of the
W15 register to generate an effective address (EA). Thus, if the contents of W15 are
greater than the contents of the SPLIM register by 2, and a CALL instruction is
executed, or if an interrupt occurs, a Stack Error Trap will be generated.
If stack overflow checking has been enabled, a stack error trap will also occur if the W15 effective
address calculation wraps over the end of data space (0xFFFF).
Note: A write to the Stack Pointer Limit register, SPLIM, should not be followed by an
indirect read operation using W15.
Refer to Section 6. “Reset Interrupts” for more information on the stack error trap.
CPU
The dsPIC30F CPU has a 16-bit status register (SR), the LSByte of which is referred to as the
lower status register (SRL). The upper byte of SR is referred to as SRH. A detailed description
of SR is shown in Register 2-1.
SRL contains all the MCU ALU operation status flags, plus the CPU interrupt priority status bits,
IPL<2:0> and the REPEAT loop active status bit, RA (SR<4>). During exception processing, SRL
is concatenated with the MSByte of the PC to form a complete word value, which is then stacked.
SRH contains the DSP Adder/Subtractor status bits, the DO loop active bit, DA (SR<9>) and the
Digit Carry bit, DC (SR<8>).
The SR bits are readable/writable with the following exceptions:
1. The DA bit (SR<8>): DA is a read only bit.
2. The RA bit (SR<4>): RA is a read only bit.
3. The OA, OB (SR<15:14>) and OAB (SR<11>) bits: These bits are read only and can only
be modified by the DSP engine hardware.
4. The SA, SB (SR<13:12>) and SAB (SR<10>) bits: These are read and clear only and can
only be set by the DSP engine hardware. Once set, they remain set until cleared by the
user, irrespective of the results from any subsequent DSP operations.
Note: Clearing the SAB bit will also clear both the SA and SB bits.
Note: A description of the SR bits affected by each instruction is provided in the dsPIC30F
Programmer’s Reference Manual (DS70030).
CPU
111 = CPU Interrupt Priority Level is 7 (15). User interrupts disabled.
110 = CPU Interrupt Priority Level is 6 (14)
101 = CPU Interrupt Priority Level is 5 (13)
100 = CPU Interrupt Priority Level is 4 (12)
011 = CPU Interrupt Priority Level is 3 (11)
010 = CPU Interrupt Priority Level is 2 (10)
001 = CPU Interrupt Priority Level is 1 (9)
000 = CPU Interrupt Priority Level is 0 (8)
Note 1: The IPL<2:0> bits are concatenated with the IPL<3> bit (CORCON<3>) to form the CPU
Interrupt Priority Level. The value in parentheses indicates the IPL if IPL<3> = 1. User interrupts
are disabled when IPL<3> = 1.
2: The IPL<2:0> status bits are read only when NSTDIS = 1 (INTCON1<15>).
bit 4 RA: REPEAT Loop Active bit
1 = REPEAT loop in progress
0 = REPEAT loop not in progress
bit 3 N: MCU ALU Negative bit
1 = Result was negative
0 = Result was non-negative (zero or positive)
bit 2 OV: MCU ALU Overflow bit
This bit is used for signed arithmetic (2’s complement). It indicates an overflow of the magnitude which
causes the sign bit to change state.
1 = Overflow occurred for signed arithmetic (in this arithmetic operation)
0 = No overflow occurred
bit 1 Z: MCU ALU Zero bit
1 = An operation which effects the Z bit has set it at some time in the past
0 = The most recent operation which effects the Z bit has cleared it (i.e., a non-zero result)
bit 0 C: MCU ALU Carry/Borrow bit
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
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
C = Clear only bit S = Set only bit -n = Value at POR
‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
R/W-0 R/W-0 R/W-1 R/W-0 R/C-0 R/W-0 R/W-0 R/W-0
SATA SATB SATDW ACCSAT IPL3 PSV RND IF
bit 7 bit 0
CPU
1 = Program space visible in data space
0 = Program space not visible in data space
bit 1 RND: Rounding Mode Select bit
1 = Biased (conventional) rounding enabled
0 = Unbiased (convergent) rounding enabled
bit 0 IF: Integer or Fractional Multiplier Mode Select bit
1 = Integer mode enabled for DSP multiply ops
0 = Fractional mode enabled for DSP multiply ops
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’ C = Bit can be cleared
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
The TBLPAG register is used to hold the upper 8 bits of a program memory address during table
read and write operations. Table instructions are used to transfer data between program memory
space and data memory space. Refer to Section 4. “Program Memory” for further details.
Program space visibility allows the user to map a 32-Kbyte section of the program memory space
into the upper 32 Kbytes of data address space. This feature allows transparent access of
constant data through dsPIC30F instructions that operate on data memory. The PSVPAG
register selects the 32 Kbyte region of program memory space that is mapped to the data
address space. Refer to Section 4. “Program Memory” for more information on the PSVPAG
register.
The MODCON register is used to enable and configure modulo addressing (circular buffers).
Refer to Section 3. “Data Memory” for further details on modulo addressing.
The XMODSRT and XMODEND registers hold the start and end addresses for modulo (circular)
buffers implemented in the X data memory address space. Refer to Section 3. “Data Memory”
for further details on modulo addressing.
The YMODSRT and YMODEND registers hold the start and end addresses for modulo (circular)
buffers implemented in the Y data memory address space. Refer to Section 3. “Data Memory”
for further details on modulo addressing.
The XBREV register is used to set the buffer size used for bit-reversed addressing. Refer to
Section 3. “Data Memory” for further details on bit-reversed addressing.
The DISICNT register is used by the DISI instruction to disable interrupts of priority 1-6 for a
specified number of cycles. See Section 6. “Reset Interrupts” for further information.
CPU
nature. Depending on the operation, the ALU may affect the values of the Carry (C), Zero (Z),
Negative (N), Overflow (OV) and Digit Carry (DC) status bits in the SR register. The C and DC
status bits operate as a Borrow and Digit Borrow bits, respectively, for subtraction operations.
The ALU can perform 8-bit or 16-bit operations, depending on the mode of the instruction that is
used. Data for the ALU operation can come from the W register array or data memory depending
on the Addressing mode of the instruction. Likewise, output data from the ALU can be written to
the W register array or a data memory location.
Refer to the dsPIC30F Programmer’s Reference Manual (DS70030) for information on the SR
bits affected by each instruction, Addressing modes and 8-bit/16-bit Instruction modes.
Note 1: Byte operations use the 16-bit ALU and can produce results in excess of 8 bits.
However, to maintain backward compatibility with PICmicro devices, the ALU result
from all byte operations is written back as a byte (i.e., MSByte not modified), and
the SR register is updated based only upon the state of the LSByte of the result.
2: All register instructions performed in Byte mode only affect the LSByte of the W
registers. The MSByte of any W register can be modified by using file register
instructions that access the memory mapped contents of the W registers.
Data input to the DSP engine is derived from one of the following sources:
1. Directly from the W array (registers W4, W5, W6 or W7) for dual source operand DSP
instructions. Data values for the W4, W5, W6 and W7 registers are pre-fetched via the X
and Y memory data buses.
2. From the X memory data bus for all other DSP instructions.
Data output from the DSP engine is written to one of the following destinations:
1. The target accumulator, as defined by the DSP instruction being executed.
2. The X memory data bus to any location in the data memory address space.
The DSP engine has the capability to perform inherent accumulator to accumulator operations
which require no additional data.
The MCU shift and multiply instructions use the DSP engine hardware to obtain their results. The
X memory data bus is used for data reads and writes in these operations.
A block diagram of the DSP engine is shown in Figure 2-8.
Note: For detailed code examples and instruction syntax related to this section, refer to
the dsPIC30F Programmer’s Reference Manual (DS70030).
CPU
Saturation Logic
Round Logic
40 40-bit Accumulator A 40 16
40-bit Accumulator B
Saturate
Adder
Negate
40
40 40
Barrel
16
Shifter
40
X Data Bus
Sign-Extend
Y Data Bus
32 16
Zero Backfill
32
32
17-bit x 17-bit
Multiplier/Scaler
16-bit to 17-bit
Conversion
16 16
To/From W Array
2.6.2 Multiplier
The dsPIC30F features a 17-bit x 17-bit multiplier which is shared by both the MCU ALU and the
DSP engine. The multiplier is capable of signed or unsigned operation and can support either
1.31 fractional (Q.31) or 32-bit integer results.
The multiplier takes in 16-bit input data and converts the data to 17-bits. Signed operands to the
multiplier are sign-extended. Unsigned input operands are zero-extended. The 17-bit conversion
logic is transparent to the user and allows the multiplier to support mixed sign and
unsigned/unsigned multiplication.
The IF control bit (CORCON<0>) determines integer/fractional operation for the instructions
listed in Table 2-3. The IF bit does not affect MCU multiply instructions listed in Table 2-4, which
are always integer operations. The multiplier scales the result one bit to the left for fractional
operation. The LSbit of the result is always cleared. The multiplier defaults to Fractional mode for
DSP operations at a device Reset.
The representation of data in hardware for each of these modes is as follows:
• Integer data is inherently represented as a signed two’s complement value, where the
MSbit is defined as a sign bit. Generally speaking, the range of an N-bit two’s
complement integer is -2N-1 to 2N-1 – 1.
• Fractional data is represented as a two’s complement fraction where the MSbit is
defined as a sign bit and the radix point is implied to lie just after the sign bit (Q.X
format). The range of an N-bit two’s complement fraction with this implied radix point is
-1.0 to (1 – 21-N).
Figure 2-9 and Figure 2-10 illustrate how the multiplier hardware interprets data in Integer and
Fractional modes. The range of data in both Integer and Fractional modes is listed in Table 2-2.
CPU
Integer:
0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1
1.15 Fractional:
0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1
-2 0 . 2 -1
2 -2
2 -3
... 2-15
1 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0
-2 15
2 14
2 13
2 12
.... 20
1.15 Fractional:
1 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0
-20 . 2 -1
2 -2
2 -3
... 2-15
The DSP instructions that utilize the multiplier are summarized in Table 2-3.
The US control bit (CORCON<12>) determines whether DSP multiply instructions are signed
(default) or unsigned. The US bit does not influence the MCU multiply instructions which have
specific instructions for signed or unsigned operation. If the US bit is set, the input operands for
instructions shown in Table 2-3 are considered as unsigned values which are always
zero-extended into the 17th bit of the multiplier value.
The same multiplier is used to support the MCU multiply instructions, which include integer 16-bit
signed, unsigned and mixed sign multiplies as shown in Table 2-4. All multiplications performed
by the MUL instruction produce integer results. The MUL instruction may be directed to use byte
or word sized operands. Byte input operands will produce a 16-bit result and word input operands
will produce a 32-bit result to the specified register(s) in the W array.
CPU
source and post-accumulation destination. For the ADD (accumulator) and LAC instructions, the
data to be accumulated or loaded can optionally be scaled via the barrel shifter prior to
accumulation.
The 40-bit adder/subtractor may optionally negate one of its operand inputs to change the sign
of the result (without changing the operands). The negate is used during multiply and subtract
(MSC), or multiply and negate (MPY.N) operations.
The 40-bit adder/subtractor has an additional saturation block which controls accumulator data
saturation, if enabled.
Six Status register bits have been provided to support saturation and overflow. They are located
in the CPU Status register, SR, and are listed below:
The OA and OB bits are read only and are modified each time data passes through the accumu-
lator add/subtract logic. When set, they indicate that the most recent operation has overflowed
into the accumulator guard bits (bits 32 through 39). This type of overflow is not catastrophic; the
guard bits preserve the accumulator data. The OAB status bit is the logically ORed value of OA
and OB.
The OA and OB bits, when set, can optionally generate an arithmetic error trap. The trap is
enabled by setting the corresponding overflow trap flag enable bit OVATE:OVBTE
(INTCON1<10:9>). The trap event allows the user to take immediate corrective action, if desired.
The SA and SB bits can be set each time data passes through the accumulator saturation logic.
Once set, these bits remain set until cleared by the user. The SAB status bit indicates the logically
ORed value of SA and SB. The SA and SB bits will be cleared when SAB is cleared. When set,
these bits indicate that the accumulator has overflowed its maximum range (bit 31 for 32-bit
saturation or bit 39 for 40-bit saturation) and will be saturated (if saturation is enabled).
When saturation is not enabled, the SA and SB bits indicate that a catastrophic overflow has
occurred (the sign of the accumulator has been destroyed). If the COVTE (INTCON1<8>) bit is
set, SA and SB bits will generate an arithmetic error trap when saturation is disabled.
Note: See Section 6. “Reset Interrupts” for further information on arithmetic warning
traps.
Note: The user must remember that SA, SB and SAB status bits can have different
meanings depending on whether accumulator saturation is enabled. The
Accumulator Saturation mode is controlled via the CORCON register.
Note: See Section 6. “Reset Interrupts” for further information on arithmetic error traps.
In addition to adder/subtractor saturation, writes to data space can be saturated without affecting
the contents of the source accumulator. This feature allows data to be limited while not sacrificing
the dynamic range of the accumulator during intermediate calculation stages. Data space write
saturation is enabled by setting the SATDW control bit (CORCON<5>). Data space write
saturation is enabled by default at a device Reset.
The data space write saturation feature works with the SAC and SAC.R instructions. The value
held in the accumulator is never modified when these instructions are executed. The hardware
takes the following steps to obtain the saturated write result:
1. The read data is scaled based upon the arithmetic shift value specified in the instruction.
2. The scaled data is rounded (SAC.R only).
3. The scaled/rounded value is saturated to a 16-bit result based on the value of the guard
bits. For data values greater than 0x007FFF, the data written to memory is saturated to
the maximum positive 1.15 value, 0x7FFF. For input data less than 0xFF8000, data
written to memory is saturated to the maximum negative 1.15 value, 0x8000.
The MAC and MSC instructions can optionally write a rounded version of the accumulator that is
not the target of the current operation into data space memory. The write is performed across the
CPU
X-bus into combined X and Y address space. This accumulator write back feature is beneficial
in certain FFT and LMS algorithms.
The following Addressing modes are supported by the accumulator write back hardware:
1. W13, register direct:
The rounded contents of the non-target accumulator are written into W13 as a 1.15
fractional result.
2. [W13]+=2, register indirect with post-increment:
The rounded contents of the non-target accumulator are written into the address pointed
to by W13 as a 1.15 fraction. W13 is then incremented by 2.
16 15 0 16 15 0
MSWord 1XXX XXXX XXXX XXXX MSWord 1 1000 0000 0000 0000
16 15 0 16 15 0
MSWord 0XXX XXXX XXXX XXXX MSWord 0 1000 0000 0000 0000
Round Down (add nothing) when: Round Down (add nothing) when:
LSWord < 0x8000 1. LSWord = 0x8000 and bit 16 = 0
2. LSWord < 0x8000
Table 2-6: Instructions that Utilize the DSP Engine Barrel Shifter
Instruction Description
ASR Arithmetic multi-bit right shift of data memory location
LSR Logical multi-bit right shift of data memory location
SL Multi-bit shift left of data memory location
SAC Store DSP accumulator with optional shift
SFTAC Shift DSP accumulator
CPU
• DIV.SD: 32/16 signed divide
• DIV.UD: 32/16 unsigned divide
• DIV.SW: 16/16 signed divide
• DIV.UW: 16/16 unsigned divide
The quotient for all divide instructions is placed in W0, and the remainder in W1. The 16-bit
divisor can be located in any W register. A 16-bit dividend can be located in any W register and
a 32-bit dividend must be located in an adjacent pair of W registers.
All divide instructions are iterative operations and must be executed 18 times within a REPEAT
loop. The user is responsible for programming the REPEAT instruction. A complete divide
operation takes 19 instruction cycles to execute.
The divide flow is interruptible, just like any other REPEAT loop. All data is restored into the
respective data registers after each iteration of the loop, so the user will be responsible for
saving the appropriate W registers in the ISR. Although they are important to the divide
hardware, the intermediate values in the W registers have no meaning to the user. The divide
instructions must be executed 18 times in a REPEAT loop to produce a meaningful result.
Refer to the “dsPIC30F Programmer’s Reference Manual” (DS70030) for more information and
programming examples for the divide instructions.
Three cycles will be taken when a two-word instruction is skipped. In this case, the program
memory pre-fetch data is discarded and the second word of the two-word instruction is
fetched. The second word of the instruction will be executed as a NOP, as shown in
Figure 2-15.
CPU
executed in the cycle immediately after the table operation as shown in Figure 2-17.
Figure 2-19: Instruction Pipeline Flow – 1-Word, 1-Cycle (With Instruction Stall)
The loop count for Repeat operations is held in the 14-bit RCOUNT register, which is memory
mapped. RCOUNT is initialized by the REPEAT instruction. The REPEAT instruction sets the
Repeat Active, or RA (SR<4>) status bit to ‘1’, if the RCOUNT is a non-zero value.
RA is a read only bit and cannot be modified through software. For repeat loop count values
greater than ‘0’, the PC is not incremented. Further PC increments are inhibited until
RCOUNT = 0. See Figure 2-20 for an instruction flow example of a Repeat loop.
For a loop count value equal to ‘0’, REPEAT has the effect of a NOP and the RA (SR<4>) bit is not
set. The Repeat loop is essentially disabled before it begins, allowing the target instruction to
execute only once while pre-fetching the subsequent instruction (i.e., normal execution flow).
Note: The instruction immediately following the REPEAT instruction (i.e., the target
instruction) is always executed at least one time. It is always executed one time
more than the value specified in the 14-bit literal or the W register operand.
CPU
further REPEAT loops from within (any number) of nested interrupts. After SRL is stacked, the
RA status bit is cleared to restore normal execution flow within the ISR.
Note: If a Repeat loop has been interrupted and an ISR is being processed, the user must
stack the RCOUNT (Repeat Count register) prior to executing another REPEAT
instruction within an ISR.
Note: If Repeat was used within an ISR, the user must unstack RCOUNT prior to executing
RETFIE.
Returning into a Repeat loop from an ISR using RETFIE requires no special handling. Interrupts
will pre-fetch the repeated instruction during the third cycle of the RETFIE. The stacked RA bit
will be restored when the SRL register is popped and, if set, the interrupted Repeat loop will be
resumed.
Note: Should the repeated instruction (target instruction in the Repeat loop) be accessing
data from PS using PSV, the first time it is executed after a return from an exception
will require 2 instruction cycles. Similar to the first iteration of a loop, timing limita-
tions will not allow the first instruction to access data residing in PS in a single
instruction cycle.
An interrupted Repeat loop can be terminated earlier than normal in the ISR by clearing the
RCOUNT register in software.
Any instruction can immediately follow a REPEAT except for the following:
1. Program Flow Control instructions (any branch, compare and skip, subroutine calls,
returns, etc.).
2. Another REPEAT or DO instruction.
3. DISI, ULNK, LNK, PWRSAV, RESET.
4. MOV.D instruction.
Note: There are some instructions and/or Instruction Addressing modes that can be
executed within a Repeat loop, but make little sense when repeated.
The number of iterations executed by a DO loop will be the (14-bit literal value +1) or the (Wn
value + 1). If a W register is used to specify the number of iterations, the two MSbits of the W
register are not used to specify the loop count. The operation of a DO loop is similar to the
‘do-while’ construct in the C programming language because the instructions in the loop will
always be executed at least once.
The dsPIC30F has three registers associated with DO loops: DOSTART, DOEND and DCOUNT.
These registers are memory mapped and automatically loaded by the hardware when the DO
instruction is executed. DOSTART holds the starting address of the DO loop while DOEND holds
the end address of the DO loop. The DCOUNT register holds the number of iterations to be
executed by the loop. DOSTART and DOEND are 22-bit registers that hold the PC value. The
MSbits and LSbits of these registers is fixed to ‘0’. Refer to Figure 2-2 for further details. The
LSbit is not stored in these registers because PC<0> is always forced to ‘0’.
The DA status bit (SR<9>) indicates that a single DO loop (or nested DO loops) is active. The
DA bit is set when a DO instruction is executed and enables a PC address comparison with the
DOEND register on each subsequent instruction cycle. When PC matches the value in DOEND,
DCOUNT is decremented. If the DCOUNT register is not zero, the PC is loaded with the address
contained in the DOSTART register to start another iteration of the DO loop.
The DO loop will terminate when DCOUNT = 0. If there are no other nested DO loops in progress,
then the DA bit will also be cleared.
Note: The group of instructions in a DO loop construct is always executed at least one
time. The DO loop is always executed one time more than the value specified in the
literal or W register operand.
The DOSTART, DOEND and DCOUNT registers each have a shadow register associated with
them, such that the DO loop hardware supports one level of automatic nesting. The DOSTART,
CPU
DOEND and DCOUNT registers are user accessible and they may be manually saved to permit
additional nesting, where required.
The DO Level bits, DL<2:0> (CORCON<10:8>) indicate the nesting level of the DO loop currently
being executed. When the first DO instruction is executed, DL<2:0> is set to B‘001’ to indicate
that one level of DO loop is underway. The DA (SR<9>) is also set. When another DO instruction
is executed within the first DO loop, the DOSTART, DOEND and DCOUNT registers are
transferred into the shadow registers, prior to being updated with the new loop values. The
DL<2:0> bits are set to B‘010’ indicating that a second, nested DO loop is in progress. The DA
(SR<9>) bit also remains set.
If no more than one level of DO loop nesting is required in the application, no special attention is
required. Should the user require more than one level of DO loop nesting, this may be achieved
through manually saving the DOSTART, DOEND and DCOUNT registers prior to executing the
next DO instruction. These registers should be saved whenever DL<2:0> is B’010’ or greater.
The DOSTART, DOEND and DCOUNT registers will automatically be restored from their shadow
registers when a DO loop terminates and DL<2:0> = B’010’.
Note: The DL<2:0> (CORCON<10:8>) bits are combined (logically OR-ed) to form the DA
(SR<9>) bit. If nested DO loops are being executed, the DA bit is cleared only when
the loop count associated with the outer most loop expires.
DO loops may be interrupted at any time. If another DO loop is to be executed during the ISR,
the user must check the DL<2:0> status bits and save the DOSTART, DOEND and DCOUNT
registers as required.
No special handling is required if the user can ensure that only one level of DO loop will ever be
executed in:
• both background and any one ISR handler (if interrupt nesting is enabled) or
• both background and any ISR (if interrupt nesting is disabled)
Alternatively, up to two (nested) DO loops may be executed in either background or within any
• one ISR handler (if interrupt nesting is enabled) or
• in any ISR (if interrupt nesting is disabled)
It is assumed that no DO loops are used within any trap handlers.
Returning to a DO loop from an ISR, using the RETFIE instruction, requires no special handling.
Note: Exiting a DO loop without using EDT is not recommended because the hardware
will continue to check for DOEND addresses.
There are restrictions on the last instruction executed in a DO loop. The last instruction in a DO
loop should not be:
1. Flow control instruction (for e.g., any branch, compare and skip, GOTO, CALL, RCALL,
TRAP).
2. RETURN, RETFIE and RETLW will work correctly as the last instruction of a DO loop, but
the user must be responsible for returning into the loop to complete it.
3. Another REPEAT or DO instruction.
4. Target instruction within a REPEAT loop. This restriction implies that the penultimate
instruction also cannot be a REPEAT.
5. Any instruction that occupies two words in program space.
6. DISI instruction
Loop length is defined as the signed offset of the last instruction from the first instruction in the DO
loop. The loop length when added to the address of the first instruction in the loop forms the
address of the last instruction of the loop.There are some loop length values that should be
avoided.
1. Loop Length = -2
Execution will start at the first instruction in the loop (i.e., at [PC]) and will continue until the
loop end address (in this case [PC – 4]) is pre-fetched. As this is the first word of the DO
instruction, it will execute the DO instruction again, re-initializing the DCOUNT and
pre-fetching [PC]. This will continue forever as long as the loop end address [PC – 4] is
pre-fetched. This value of n has the potential of creating an infinite loop (subject to a
Watchdog Timer Reset).
end_loop: DO #33, end_loop ;DO is a two-word instruction
NOP ;2nd word of DO executes as a NOP
ADD W2,W3,W4 ;First instruction in DO loop([PC])
CPU
execute again. This will continue as long as the loop end address [PC – 2] is pre-fetched
and the loop does not terminate. Should the value in the DCOUNT register reach zero and
on a subsequent decrement generate a borrow, the loop will terminate. However, in such a
case the initial instruction outside the loop will once again be the first loop instruction.
DO #33, end_loop ;DO is a two-word instruction
end_loop: NOP ;2nd word of DO executes as a NOP
ADD W2,W3,W4 ;First instruction in DO loop([PC])
3. Loop Length = 0
Execution will start at the first instruction in the loop (i.e., at [PC]) and will continue until the
loop end address ([PC]) is pre-fetched. If the loop is to continue, this pre-fetch will cause
the DO loop hardware to load the DOEND address ([PC]) into the PC for the next fetch
(which will be [PC] again). After the first true iteration of the loop, the first instruction in the
loop will be executed repeatedly until the loop count underflows and the loop terminates.
When this occurs, the initial instruction outside the loop will be the instruction after [PC].
DO #33, end_loop ;DO is a two-word instruction
NOP ;2nd word of DO executes as a NOP
end_loop: ADD W2,W3,W4 ;First instruction in DO loop([PC])
Instruction Register
ADD MOV
Contents
CPU
2. Data space is not addressed until after the instruction stall.
3. PC increment is inhibited until after the instruction stall.
4. Further instruction fetches are inhibited until after the instruction stall.
When an interrupt event coincides with two adjacent instructions that will cause an instruction
stall, one of two possible outcomes could occur:
1. The interrupt could be coincident with the first instruction. In this situation, the first instruc-
tion will be allowed to complete and the second instruction will be executed after the ISR
completes. In this case, the stall cycle is eliminated from the second instruction because
the exception process provides time for the first instruction to complete the write phase.
2. The interrupt could be coincident with the second instruction. In this situation, the second
instruction and the appended stall cycle will be allowed to execute prior to the ISR. In this
case, the stall cycle associated with the second instruction executes normally. However,
the stall cycle will be effectively absorbed into the exception process timing. The exception
process proceeds as if an ordinary two-cycle instruction was interrupted.
The CALL and RCALL instructions write to the stack using W15 and may, therefore, force an
instruction stall prior to the next instruction, if the source read of the next instruction uses W15.
The RETFIE and RETURN instructions can never force an instruction stall prior to the next
instruction because they only perform read operations. However, the user should note that the
RETLW instruction could force a stall, because it writes to a W register during the last cycle.
The GOTO and branch instructions can never force an instruction stall because they do not
perform write operations.
Other than the addition of instruction stall cycles, RAW data dependencies will not affect the
operation of either DO or REPEAT loops.
The pre-fetched instruction within a REPEAT loop does not change until the loop is complete or
an exception occurs. Although register dependency checks occur across instruction boundaries,
the dsPIC30F effectively compares the source and destination of the same instruction during a
REPEAT loop.
The last instruction of a DO loop either pre-fetches the instruction at the loop start address or the
next instruction (outside the loop). The instruction stall decision will be based on the last
instruction in the loop and the contents of the pre-fetched instruction.
When program space (PS) is mapped to data space by enabling the PSV (CORCON<2>) bit, and
the X space EA falls within the visible program space window, the read or write cycle is redirected
to the address in program space. Accessing data from program space takes up to 3 instruction
cycles.
Instructions operating in PSV address space are subject to RAW data dependencies and
consequent instruction stalls, just like any other instruction.
Consider the following code segment:
ADD W0,[W1],[W2++] ; PSV = 1, W1=0x8000, PSVPAG=0xAA
MOV [W2],[W3]
This sequence of instructions would take 5 instruction cycles to execute. 2 instruction cycles are
added to perform the PSV access via W1. Furthermore, an instruction stall cycle is inserted to
resolve the RAW data dependency caused by W2.
DS70049C-page 2-38
W1 0002 W1 0000 0000 0000 0000
W2 0004 W2 0000 0000 0000 0000
W3 0006 W3 0000 0000 0000 0000
W4 0008 W4 0000 0000 0000 0000
W5 000A W5 0000 0000 0000 0000
W6 000C W6 0000 0000 0000 0000
W7 000E W7 0000 0000 0000 0000
W8 0010 W8 0000 0000 0000 0000
W9 0012 W9 0000 0000 0000 0000
W10 0014 W10 0000 0000 0000 0000
W11 0016 W11 0000 0000 0000 0000
W12 0018 W12 0000 0000 0000 0000
W13 001A W13 0000 0000 0000 0000
W14 001C W14 0000 0000 0000 0000
W15 001E W15 0000 0000 0000 0000
SPLIM 0020 SPLIM 0000 0000 0000 0000
dsPIC30F Family Reference Manual
DS70049C-page 2-39
Section 2. CPU
2
CPU
dsPIC30F Family Reference Manual
Note: Please visit the Microchip web site (www.microchip.com) for additional Application
Notes and code examples for the dsPIC30F Family of devices.
CPU
Revision B
This revision incorporates additional technical content for the dsPIC30F CPU module.
Revision C
This revision incorporates all known errata at the time of this document update.
NOTES:
HIGHLIGHTS
This section of the manual contains the following topics:
Data Memory
3.1 Introduction
The dsPIC30F data width is 16-bits. All internal registers and data space memory are organized
as 16-bits wide. The dsPIC30F features two data spaces. The data spaces can be accessed
separately (for some DSP instructions) or together as one 64-Kbyte linear address range (for
MCU instructions). The data spaces are accessed using two Address Generation Units (AGUs)
and separate data paths.
An example data space memory map is shown in Figure 3-1.
Data memory addresses between 0x0000 and 0x07FF are reserved for the device special
function registers (SFRs). The SFRs include control and status bits for the CPU and peripherals
on the device.
The RAM begins at address 0x0800 and is split into two blocks, X and Y data space. For data
writes, the X and Y data spaces are always accessed as a single, linear data space. For data
reads, the X and Y memory spaces can be accessed independently or as a single, linear space.
Data reads for MCU class instructions always access the the X and Y data spaces as a single
combined data space. Dual source operand DSP instructions, such as the MAC instruction,
access the X and Y data spaces separately to support simultaneous reads for the two source
operands.
MCU instructions can use any W register as an address pointer for a data read or write operation.
During data reads, the DSP class of instructions isolates the Y address space from the total data
space. W10 and W11 are used as address pointers for reads from the Y data space. The remain-
ing data space is referred to as X space, but could more accurately be described as “X minus Y”
space. W8 and W9 are used as address pointers for data reads from the X data space in DSP
class instructions.
Figure 3-2 shows how the data memory map functions for both MCU class and DSP class
instructions. Note that it is the W register number and type of instruction that determines how
address space is accessed for data reads. In particular, MCU instructions treat the X and Y
memory as a single combined data space. The MCU instructions can use any W register as an
address pointer for reads and writes. The DSP instructions that can simultaneously pre-fetch two
data operands, split the data memory into two spaces. Specific W registers must be used for read
address pointers in this case.
Some DSP instructions have the ability to store the accumulator that is not targeted by the
instruction to data memory. This function is called “accumulator write back”. W13 must be used
as an address pointer to the combined data memory space for accumulator write back
operations.
For DSP class instructions, W8 and W9 should point to implemented X memory space for all
memory reads. If W8 or W9 points to Y memory space, zeros will be returned. If W8 or W9 points
to an unimplemented memory address, an address error trap will be generated.
For DSP class instructions, W10 and W11 should point to implemented Y memory space for all
memory reads. If W10 or W11 points to implemented X memory space, all zeros will be returned.
If W10 or W11 points to an unimplemented memory address, an address error trap will be
generated. For additional information on address error traps, refer to Section 6. “Reset Inter-
rupts”.
Note: The data memory map and the partition between the X and Y data spaces is device
specific. Refer to the specific dsPIC30F device data sheet for further details.
MSByte LSByte
16-bits Address
Address
MSByte LSByte
0x0001 0x0000
SFR Space
0x07FF 0x07FE
0x0801 0x0800
0x17FF 0x17FE
0x1801 0x1800
0x27FF 0x27FE
0x2801 0x2800
3
0x8001 0x8000
Data Memory
X Data RAM
Unimplemented
Provides Program
Space Visibility
0xFFFF
Note 1: The partition between the X and Y data spaces is device specific. Refer to the appropriate device
data sheet for further details. The data space boundaries indicated here are used for example
purposes only.
2: Near data memory can be accessed directly via file register instructions that encode a 13-bit
address into the opcode. At a minimum, the near data memory region overlaps all of the SFR
space and a portion of X memory space. All of X memory space and some or all of Y memory
space may be included in the near data memory region, depending on the device variant.
3: All data memory can be accessed indirectly via W registers or directly using the MOV instruction.
4: Upper half of data memory map can be mapped into a segment of program memory space for
program space visibility.
X SPACE
UNUSED
X SPACE
X SPACE
UNUSED
MCU Class Instructions (Read/Write) Dual Source Operand DSP Instructions (Read)
DSP Instructions (Write)
Note: Data writes for DSP instructions consider the entire data memory as one
combined space. DSP instructions that perform an accumulator write back
use W13 as an address pointer for writes to the combined data spaces.
Note: The entire 64K data space can be addressed directly using the MOV instruction.
Refer to the dsPIC30F Programmer’s Reference Manual (DS70030) for further
details.
Data Memory
The Y memory bus is never used for data writes. The function of the Y AGU and Y memory bus
is to support concurrent data reads for DSP class instructions.
The Y AGU timing is identical to that of the X RAGU, in that its effective address calculation starts
prior to the instruction cycle, using information derived from the pre-fetched instruction. The EA
is presented to the address bus at the beginning of the instruction cycle.
The Y AGU supports Modulo Addressing and Post-modification Addressing modes for the DSP
class of instructions that use it.
Note: The Y AGU does not support data writes. All data writes occur via the X WAGU to
the combined X and Y data spaces. The Y AGU is only used during data reads for
dual source operand DSP instructions.
ALU OP
X RAGU [W7] [W8]+=2 [--W9]
Stall Check Stall Check
X WAGU [W10] [W9++] [W13] [W6++]
Stall Check
ALU OP
During
Y AGU [W10]+=2
Q3
X Address [W7] W10 W9 W8 W13 W9-2 W6
Y Address W10
Note: All word accesses must be aligned to an even address (LSB = 0). Misaligned word
data fetches are not supported, so care must be taken when mixing byte and word
operations or translating from existing PICmicro code. Should a misaligned word
read or write be attempted, an address error trap will occur. A misaligned read
operation will complete, but a misaligned write will not take place. The trap will then
be taken, allowing the system to examine the machine state prior to execution of the
address Fault.
MSByte LSByte
15 8 7 0
0001 Byte 1 Byte 0 0000 3
0003 Byte 3 Byte 2 0002
Data Memory
0005 Byte 5 Byte 4 0004
Word 0 0006
Word 1 0008
Long Word<15:0> 000A
Long Word<31:16> 000C
Note: The user must decide whether an incrementing or decrementing modulo buffer is
required for the application. There are certain address restrictions that depend on
whether an incrementing or decrementing modulo buffer is to be implemented.
The data buffer start address is arbitrary, but must be at a ‘zero’ power of two boundary for
incrementing modulo buffers. The modulo start address can be any value for decrementing
modulo buffers and is calculated using the chosen buffer end address and buffer length.
For example, if the buffer length for an incrementing buffer is chosen to be 50 words (100 bytes),
then the buffer start byte address must contain 7 Least Significant zeros. Valid start addresses
may, therefore, be 0xNN00 and 0xNN80, where ‘N’ is any hexadecimal value.
The data buffer end address is arbitrary but must be at a ‘ones’ boundary for decrementing
buffers. The modulo end address can be any value for an incrementing buffer and is calculated
using the chosen buffer start address and buffer length.
For example, if the buffer size (modulus value) is chosen to be 50 words (100 bytes), then the
buffer end byte address for decrementing modulo buffer must contain 7 Least Significant ones.
Valid end addresses may, therefore, be 0xNNFF and 0xNN7F, where ‘x’ is any hexadecimal
value.
Note: If the required modulo buffer length is an even power of 2, modulo start and end
addresses can be chosen that satisfy the requirements for incrementing and
decrementing buffers.
The end address for an incrementing modulo buffer must be calculated from the chosen start
address and the chosen buffer length in bytes. Equation 3-1 may be used to calculate the end
address.
Equation 3-1: Modulo End Address for Incrementing Buffer
The start address for a decrementing modulo buffer is calculated from the chosen end address
and the buffer length, as shown in Equation 3-2.
Equation 3-2: Modulo Start Address for Decrementing Buffer
A write operation to the Modulo Addressing Control register, MODCON, should not be
immediately followed by an indirect read operation using any W register. The code segment
shown in Example 3-1 will thus lead to unexpected results.
Note 1: Using a POP instruction to pop the contents of the top-of-stack (TOS) location into
MODCON, also constitutes a write to MODCON. The instruction immediately
following a write to MODCON cannot be any instruction performing an indirect read
operation.
3
2: The user should note that some instructions perform an indirect read operation,
Data Memory
implicitly. These are: POP, RETURN, RETFIE, RETLW and ULNK.
To work around this problem of initialization, use any Addressing mode other than indirect reads
in the instruction that immediately follows the initialization of MODCON. A simple work around to
the problem is achieved by adding a NOP after initializing MODCON, as shown in Example 3-2.
An additional condition exists for indirect read operations performed immediately after writing to
the modulo address SFRs:
• XMODSRT
• XMODEND
• YMODSRT
• YMODEND
If modulo addressing has already been enabled in MODCON, then a write to the X (or Y) modulo
address SFRs should not be immediately followed by an indirect read, using the W register
designated for modulo buffer access from X-data space (or Y-data space). The code segment in
Example 3-3 shows how initializing the modulo SFRs associated with the X-data space, could
lead to unexpected results. A similar example can be made for initialization in Y-data space.
To work around this issue, insert a NOP, or perform any operation other than an indirect read that
uses the W register designated for modulo buffer access, after initializing the modulo address
SFRs. This is demonstrated in Example 3-4. Another alternative would be to enable modulo
addressing in MODCON after initializing the modulo start and end address SFRs.
Note: Alternatively, execute other instructions that do not perform indirect read operations,
using the W register designated for modulo buffer access.
Data Memory
-boundary requirements for both incrementing and decrementing modulo buffers.
A new EA can exceed the modulo buffer boundary by up to the length of the buffer and still be
successfully corrected. This is important to remember when the Register Indexed ([Wb + Wn])
and Literal Offset ([Wn + lit10]) Addressing modes are used. The user should remember that
the Register Indexed and Literal Offset Addressing modes do not change the value held in the
W register. Only the indirect with Pre- and Post-modification Addressing modes ([Wn++],
[Wn--], [++Wn], [--Wn]) will modify the W register address value.
0x1163
Byte
3
Address
Data Memory
MOV #0x11E0,W0
MOV W0,XMODSRT ;set modulo start address
MOV #0x11FF,W0
0x11E0
MOV W0,XMODEND ;set modulo end address
MOV #0x8001,W0
MOV W0,MODCON ;enable W1, X AGU for modulo
MOV #0x000F,W0 ;W0 holds buffer fill value
MOV #0x11FE,W1 ;point W1 to buffer
DO #15,FILL ;fill the 16 buffer locations
MOV W0,[W1--] ;fill the next location
FILL:
DEC W0,W0 ;decrement the fill value
b3 b2 b1 b0
b0 b1 b2 b3
Bit-Reversed Result
Modulo addressing and bit-reversed addressing can be enabled simultaneously using the same
W register, but bit-reversed addressing operation will always take precedence for data writes
when enabled. As an example, the following setup conditions would assign the same W register
to modulo and bit-reversed addressing:
• X modulo addressing is enabled (XMODEN = 1)
3
• Bit-reverse addressing is enabled (BREN = 1)
Data Memory
• W1 assigned to modulo addressing (XWM<3:0> = 0001)
• W1 assigned to bit-reversed addressing (BWM<3:0> = 0001)
For data reads that use W1 as the pointer, modulo address boundary checking will occur. For
data writes using W1 as the destination pointer, the bit-reverse hardware will correct W1 for data
re-ordering.
If bit-reversed addressing has already been enabled by setting the BREN (XBREV<15>) bit, then
a write to the XBREV register should not be followed by an indirect read operation using the W
register, designated as the bit reversed address pointer.
3
When XB<14:0> = 0x0008, the bit-reversed buffer size will be 16 words. Bits 1-4 of the W
register will be subject to bit-reversed address correction, but bits 5-15 (outside the pivot point)
Data Memory
will not be modified by the bit-reverse hardware. Bit 0 is not modified because the bit-reverse
hardware only operates on word addresses.
The XB modifier controls the ‘pivot point’ for the bit-reverse address modification. Bits outside of
the pivot point will not be subject to bit-reversed address corrections.
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
XB<14:0> = 0x0008
Bits 1-4 of address
are modified.
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
Bit-Reversed Result
Pivot Point
Lower Byte:
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
YWM<3:0> XWM<3:0>
bit 7 bit 0
Data Memory
bit 7-4 YWM<3:0>: Y AGU W Register Select for Modulo Addressing bits
1111 = Modulo addressing disabled
1010 = W10 selected for modulo addressing
1011 = W11 selected for modulo addressing
Note: All other settings of the YWM<3:0> control bits are reserved and should not be used.
bit 3-0 XWM<3:0>: X RAGU and X WAGU W Register Select for Modulo Addressing bits
1111 = Modulo addressing disabled
1110 = W14 selected for modulo addressing
•
•
0000 = W0 selected for modulo addressing
Note: A write to the MODCON register should not be followed by an instruction that performs an
indirect read operation using a W register. Unexpected results may occur. Some instructions
perform an implicit indirect read. These are: POP, RETURN, RETFIE, RETLW and ULNK.
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R-0
XS<7:1> 0
bit 7 bit 0
bit 15-1 XS<15:1>: X RAGU and X WAGU Modulo Addressing Start Address bits
bit 0 Unimplemented: Read as ‘0’
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R-1
XE<7:1> 1
bit 7 bit 0
bit 15-1 XE<15:1>: X RAGU and X WAGU Modulo Addressing End Address bits
bit 0 Unimplemented: Read as ‘1’
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R-0
YS<7:1> 0
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Data Memory
YE<15:8>
bit 15 bit 8
Lower Byte:
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R-1
YE<7:1> 1
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
XB<7:0>
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Note: Please visit the Microchip web site (www.microchip.com) for additional Application
Notes and code examples for the dsPIC30F Family of devices.
Data Memory
HIGHLIGHTS
This section of the manual contains the following topics:
Program
Memory
Interrupt 52 Vector
Interrupt 53 Vector 00007E
Reserved 000080
User Memory
000082
Space
Interrupt 52 Vector
Interrupt 53 Vector 0000FE
000100
User Flash
Program Memory
(48K Instructions)
017FFE
018000
Reserved
(Read 0’s)
7FEFFE
800000
4
Space
Reserved
Program
8005BE
Memory
8005C0
UNITID
8005FE
800600
Reserved
F7FFFE
Device Configuration F80000
Registers F8000E
F80010
Reserved
FEFFFE
DEVID (2) FF0000
FFFFFE
Note: The address boundaries for user Flash program memory and data EEPROM memory will depend on the dsPIC30F device variant
that is selected. Refer to the appropriate device data sheet for further details.
24-bits
0x000000
User 24
Instruction
23
+1(1) Space
Latch
23
Instruction
Program Counter 0
22 0
0x7FFFFE
Figure 4-3: High and Low Address Regions for Table Operations
PC Address 23 16 8 0
0x000100 00000000
0x000102 00000000
0x000104 00000000
0x000106 00000000
Program
Memory
7 0 15 0
TBLPAG EA
24-bit EA
PC Address 23 16 8 0
0x000100 00000000
0x000102 00000000
0x000104 00000000
0x000106 00000000
TBLRDL.B (Wn<0> = 0)
TBLRDL.W
Program Memory
‘Phantom’ Byte
TBLRDL.B (Wn<0> = 1)
(Read as ‘0’)
TBLRDH.W
PC Address 23 16 8 0
0x000100 00000000
0x000102 00000000
0x000104 00000000
0x000106 00000000
TBLRDH.B (Wn<0> = 0)
Program Memory
‘Phantom’ Byte
(Read as ‘0’) TBLRDH.B (Wn<0> = 1)
Program
Memory
Program Space
0x000100
Data Space
0x0000
PSVPAG
0x01
0x8000 8 23 15 0
EA<15> = 1 0x008000
15 23
0xFFFF
0x017FFF
Upper 8 bits of Program
Memory Data cannot be
read using Program Space
Visibility. Data Read
4
23 bits
Program
Memory
Select
1 Wn
PSVPAG Reg
8 bits 15 bits
23-bit EA
Instructions that use PSV within a REPEAT loop eliminate the extra instruction cycle(s) required
for the data access from program memory, hence incurring no overhead in execution time.
However, the following iterations of the REPEAT loop will incur an overhead of two instruction
cycles to complete execution:
- The first iteration
- The last iteration
- Instruction execution prior to exiting the loop due to an interrupt
- Instruction execution upon re-entering the loop after an interrupt is serviced
Refer to Section 2. “CPU” for more information about instruction stalls using PSV.
4.5 Program Memory Writes
The dsPIC30F family of devices contains internal program Flash memory for executing user
code. There are two methods by which the user can program this memory:
1. Run-Time Self Programming (RTSP)
2. In-Circuit Serial Programming™ (ICSP™)
RTSP is accomplished using TBLWT instructions. ICSP is accomplished using the SPI interface
and integral bootloader software. Refer to Section 5. “Flash and EEPROM Programming” for
further details about RTSP. ICSP specifications can be downloaded from the Microchip
Technology web site (www.microchip.com).
int main(void)
{
// Initialize the UART1
U1MODE = 0x8000;
U1STA = 0x0000;
U1BRG = ((FCY/16)/BAUD) - 1; // set baud rate = BAUD
TXPtr = &hello[0]; // point to first char in string
U1STAbits.UTXEN = 1; // Initiate transmission
while (1)
{
while (*TXPtr) // while valid char in string ...
if (!U1STAbits.UTXBF) // and buffer not full ...
U1TXREG = *TXPtr++; // transmit string via UART
} // end main
__reset:
4
clr U1STA
mov #0x8000,W0 ; enable UART module
Program
Memory
mov W0,U1MODE
mov #BR,W0 ; set baudrate using formula value
mov W0, U1BRG ; /
bset U1STA,#UTXEN ; initiate transmission
Again:
rcall Delay500mSec ; delay for 500 mS
mov #psvpage(hello),w0
mov w0, PSVPAG
bset.b CORCONL,#PSV
mov #psvoffset(hello),w0
TxSend:
mov.b [w0++], w1 ; get char in string
cp w1,#0 ; if Null
bra Z,Again ; then re-initialize
BufferTest:
btsc U1STA,#UTXBF ; see if buffer full
bra BufferTest ; wait till empty
mov w1,U1TXREG ; load value in TX buffer
bra TxSend ; repeat for next char.
Note: Please visit the Microchip web site (www.microchip.com) for additional Application
Notes and code examples for the dsPIC30F Family of devices.
Program
Memory
NOTES:
HIGHLIGHTS
This section of the manual contains the following topics:
5
Flash and EEPROM
Programming
5.1 Introduction
This section describes programming techniques for Flash program memory and data EEPROM
memory. The dsPIC30F family of devices contains internal program Flash memory for executing
user code. There are two methods by which the user can program this memory:
1. Run-Time Self Programming (RTSP)
2. In-Circuit Serial Programming™ (ICSP™)
RTSP is performed by the user’s software. ICSP is performed using a serial data connection to
the device and allows much faster programming times than RTSP. RTSP techniques are
described in this chapter. The ICSP protocol is described in the dsPIC30F Programming
Specification document, which may be downloaded from the Microchip web site.
The data EEPROM is mapped into the program memory space. The EEPROM is organized as
16-bit wide memory and the memory size can be up to 2K words (4 Kbytes). The amount of
EEPROM is device dependent. Refer to the device data sheet for further information.
The programming techniques used for the data EEPROM are similar to those used for Flash
program memory RTSP. The key difference between Flash and data EEPROM programming
operations is the amount of data that can be programmed or erased during each program/erase
cycle.
5.2 Table Instruction Operation
The table instructions provide one method of transferring data between the program memory
space and the data memory space of dsPIC30F devices. A summary of the table instructions is
provided here since they are used during programming of the Flash program memory and data
EEPROM. There are four basic table instructions:
• TBLRDL: Table Read Low
• TBLRDH: Table Read High
• TBLWTL: Table Write Low
• TBLWTH: Table Write High
The TBLRDL and the TBLWTL instructions are used to read and write to bits <15:0> of program
memory space. TBLRDL and TBLWTL can access program memory in Word or Byte mode.
The TBLRDH and TBLWTH instructions are used to read or write to bits <23:16> of program
memory space. TBLRDH and TBLWTH can access program memory in Word or Byte mode. Since
the program memory is only 24-bits wide, the TBLRDH and TBLWTH instructions have the ability
to address an upper byte of program memory that does not exist. This byte is called the ‘phantom
byte’. Any read of the phantom byte will return 0x00 and a write to the phantom byte has no
effect.
Always remember that the 24-bit program memory can be regarded as two side-by-side 16-bit
spaces, with each space sharing the same address range. Therefore, the TBLRDL and TBLWTL
instructions access the ‘low’ program memory space (PM<15:0>). The TBLRDH and TBLWTH
instructions access the ‘high’ program memory space (PM<31:16>). Any reads or writes to
PM<31:24> will access the phantom (unimplemented) byte. When any of the table instructions
are used in Byte mode, the LSb of the table address will be used as the byte select bit. The LSb
determines which byte in the high or low program memory space is accessed.
Figure 5-1 shows how the program memory is addressed using the table instructions. A 24-bit
program memory address is formed using bits <7:0> of the TBLPAG register and the effective
address (EA) from a W register, specified in the table instruction. The 24-bit program counter is
shown in Figure 5-1 for reference. The upper 23 bits of the EA are used to select the program
memory location. For the Byte mode table instructions, the LSb of the W register EA is used to
pick which byte of the 16-bit program memory word is addressed. A ‘1’ selects bits <15:8>, a ‘0’
selects bits <7:0>. The LSb of the W register EA is ignored for a table instruction in Word mode.
In addition to the program memory address, the table instruction also specifies a W register (or
a W register pointer to a memory location) that is the source of the program memory data to be
written, or the destination for a program memory read. For a table write operation in Byte mode,
bits <15:8> of the source working register are ignored.
7 0 15 0
TBLPAG EA
24-bit EA
The following code example shows how to read a word of program memory using the table
instructions in Word mode:
; Setup the address pointer to program space
MOV #tblpage(PROG_ADDR),W0 ; get table page value
MOV W0,TBLPAG ; load TBLPAG register
MOV #tbloffset(PROG_ADDR),W0 ; load address LS word
; Read the program memory location
TBLRDH [W0],W3 ; Read high byte to W3
TBLRDL [W0],W4 ; Read low word to W4
In the code example above, the post-increment operator on the read of the low byte causes the
address in the working register to increment by one. This sets EA<0> to a ‘1’ for access to the
middle byte in the third write instruction. The last post-increment sets W0 back to an even
address, pointing to the next program memory location.
Note: The tblpage() and tbloffset() directives are provided by the Microchip
assembler for the dsPIC30F. These directives select the appropriate TBLPAG and
W register values for the table instruction from a program memory address value.
Refer to the MPLAB ASM 30, MPLAB LINK30 and Utilities User’s Guide (DS51317) 5
for further details.
Flash and EEPROM
Programming
Table write instructions do not write directly to the non-volatile program and data memory.
Instead, the table write instructions load holding latches that store the write data. The holding
latches are not memory mapped and can only be accessed using table write instructions. When
all of the holding latches have been loaded, the actual memory programming operation is started
by executing a special sequence of instructions.
The number of holding latches will determine the maximum memory block size that can be
programmed and may vary depending on the type of non-volatile memory and the device variant.
For example, the number of holding latches could be different for program memory, data
EEPROM memory and Device Configuration registers for a given device.
In general, the program memory is segmented into rows and panels. Each panel will have its own
set of table write holding latches. This allows multiple memory panels to be programmed at once,
reducing the overall programming time for the device. For each memory panel, there are
generally enough holding latches to program one row of memory at a time. The memory logic
automatically decides which set of write latches to load based on the address value used in the
table write instruction.
Please refer to the specific device data sheet for further details.
The following sequence can be used to write a single program memory latch location in Word
mode:
; Setup the address pointer to program space
MOV #tblpage(PROG_ADDR),W0 ; get table page value
MOV W0,TBLPAG ; load TBLPAG register
MOV #tbloffset(PROG_ADDR),W0 ; load address LS word
; Load write data into W registers
MOV #PROG_LOW_WORD,W2
MOV #PROG_HI_BYTE,W3
; Perform the table writes to load the latch
TBLWTL W2,[W0]
TBLWTH W3,[W0++]
In this example, the contents of the upper byte of W3 does not matter because this data will be
written to the phantom byte location. W0 is post-incremented by 2, after the second TBLWTH
instruction, to prepare for the write to the next program memory location.
To write a single program memory latch location in Byte mode, the following code sequence can
be used:
; Setup the address pointer to program space
MOV #tblpage(PROG_ADDR),W0 ; get table page value
MOV W0,TBLPAG ; load TBLPAG register
MOV #tbloffset(PROG_ADDR),W0 ; load address LS word
; Load data into working registers
MOV #LOW_BYTE,W2
MOV #MID_BYTE,W3
MOV #HIGH_BYTE,W4
; Write data to the latch
TBLWTH.B W4,[W0] ; write high byte
TBLWTL.B W2,[W0++] ; write low byte
TBLWTL.B W3,[W0++] ; write middle byte
In the code example above, the post-increment operator on the write to the low byte causes the
address in W0 to increment by one. This sets EA<0> = 1 for access to the middle byte in the third
write instruction. The last post-increment sets W0 back to an even address pointing to the next
program memory location.
5.3 Control Registers
Flash and data EEPROM programming operations are controlled using the following
Non-Volatile Memory (NVM) control registers:
• NVMCON: Non-Volatile Memory Control Register
• NVMKEY: Non-Volatile Memory Key Register
• NVMADR: Non-Volatile Memory Address Register
Figure 5-2: NVM Addressing with TBLPAG and NVM Address Registers
24-bit PM address
EA<0> is
Byte Select
TBLPAG Reg W Register EA
MOV #0x55,W0
MOV #0xAA,W0
MOV W0,NVMKEY
MOV W0,NVMKEY ; NOP not required
BSET NVMCON,#WR ; Start the program/erase cycle
NOP
NOP
POP SR ; Re-enable interrupts
Refer to Section 5.4.2 “Flash Programming Operations” for further programming examples.
Lower Byte:
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
PROGOP<7:0>
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
S = Settable bit -n = Value at POR ‘1’ = Bit is set
‘0’ = Bit is cleared x = Bit is unknown
5
Flash and EEPROM
Programming
Lower Byte:
R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x
NVMADR<7:0>
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x
NVMADRU<7:0>
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
W-0 W-0 W-0 W-0 W-0 W-0 W-0 W-0
NVMKEY<7:0>
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
5
Flash and EEPROM
Programming
The user can erase and program Flash Program Memory by rows (32 instruction words). The
general process is as follows:
1. Read one row of program Flash (32 instruction words) and store into data RAM as a data
“image”. The RAM image must be read from an even 32-word program memory address
boundary.
2. Update the RAM data image with the new program memory data.
3. Erase program Flash row.
• Setup NVMCON register to erase 1 row of Flash program memory.
• Write address of row to be erased into NVMADRU and NVMADR registers.
• Disable interrupts.
• Write the key sequence to NVMKEY to enable the erase.
• Set the WR bit. This will begin erase cycle.
• CPU will stall for the duration of the erase cycle.
• The WR bit is cleared when erase cycle ends.
• Re-enable interrupts.
4. Write 32 instruction words of data from RAM into the Flash program memory write latches.
5. Program 32 instruction words into program Flash.
• Setup NVMCON to program one row of Flash program memory.
• Disable interrupts.
• Write the key sequence to NVMKEY to enable the program cycle.
• Set the WR bit. This will begin the program cycle.
• CPU will stall for duration of the program cycle.
• The WR bit is cleared by the hardware when program cycle ends.
• Re-enable interrupts.
6. Repeat steps 1 through 6, as needed, to program the desired amount of Flash program
memory
Note: The user should remember that the minimum amount of program memory that can
be modified using RTSP is 32 instruction word locations. Therefore, it is important
that an image of these locations be stored in general purpose RAM before an erase
cycle is initiated. An erase cycle must be performed on any previously written
locations before any programming is done.
5
Flash and EEPROM
Programming
The following is a code sequence that can be used to erase a row (32 instructions) of program
memory. The NVMCON register is configured to erase one row of program memory. The
NVMADRU and NVMADR registers are loaded with the address of the row to be erased. The
program memory must be erased at ‘even’ row boundaries. Therefore, the 6 LSbits of the value
written to the NVMADR register have no effect when a row is erased.
The erase operation is initiated by writing a special unlock, or key sequence to the NVMKEY
register before setting the WR control bit (NVMCON<15>). The unlock sequence needs to be
executed in the exact order shown without interruption. Therefore, interrupts should be disabled
prior to writing the sequence.
Two NOP instructions should be inserted in the code at the point where the CPU will resume
operation. Finally, interrupts can be enabled (if required).
; Setup NVMCON to erase one row of Flash program memory
MOV #0x4041,W0
MOV W0,NVMCON
; Setup address pointer to row to be ERASED
MOV #tblpage(PROG_ADDR),W0
MOV W0,NVMADRU
MOV #tbloffset(PROG_ADDR),W0
MOV W0,NVMADR
; Disable interrupts, if enabled
PUSH SR
MOV #0x00E0,W0
IOR SR
; Write the KEY sequence
MOV #0x55,W0
MOV W0, NVMKEY
MOV #0xAA, W0
MOV W0, NVMKEY
; Start the erase operation
BSET NVMCON,#WR
; Insert two NOPs after the erase cycle (required)
NOP
NOP
; Re-enable interrupts, if needed
POP SR
Note: When erasing a row of program memory, the user writes the upper 8 bits of the
erase address directly to the NVMADRU and NVMADR registers. Together, the
contents of the NVMADRU and NVMADR registers form the complete address of
the program memory row to be erased.
The NVMADRU and NVMADR registers specify the address for all Flash erase and
program operations. However, these two registers do not have to be directly written
by the user for Flash program operations. This is because the table write instruc-
tions used to write the program memory data automatically transfers the TBLPAG
register contents and the table write address into the NVMADRU and NVMADR
registers.
The above code example could be modified to perform a ‘dummy’ table write
operation to capture the program memory erase address.
The following is a sequence of instructions that can be used to load the 768-bits of write latches
(32 instruction words). 32 TBLWTL and 32 TBLWTH instructions are needed to load the write
latches selected by the table pointer.
The TBLPAG register is loaded with the 8 MSbits of the program memory address. The user
does not need to write the NVMADRU:NVMADR register-pair for a Flash programming opera-
tion. The 24-bits of the program memory address are automatically captured into the
NVMADRU:NVMADR register-pair when each table write instruction is executed. The program
memory must be programmed at an ‘even’ 32 instruction word address boundary. In effect, the
6 LSbits of the value captured in the NVMADR register are not used during the programming
operation.
The row of 32 instruction words do not necessarily have to be written in sequential order. The
6 LSbits of the table write address determine which of the latches will be written. However, all 32
instruction words should be written for each programming cycle to overwrite old data.
MOV #LOW_WORD_0,W2
MOV #HIGH_BYTE_0,W3
TBLWTL W2,[W0]
TBLWTH W3,[W0++] ; 1st_program_word
MOV #LOW_WORD_1,W2
MOV #HIGH_BYTE_1,W3
TBLWTL W2,[W0]
TBLWTH W3,[W0++] ; 2nd_program_word
MOV #LOW_WORD_2,W2
MOV #HIGH_BYTE_2,W3
TBLWTL W2, [W0]
TBLWTH W3, [W0++] ; 3rd_program_word
MOV #LOW_WORD_3,W2
MOV #HIGH_BYTE_3,W3
TBLWTL W2,[W0]
TBLWTH W3,[W0++] ; 4th_program_word
........
........
MOV #LOW_WORD_31,W2
MOV #HIGH_BYTE_31,W3
TBLWTL W2,[W0]
TBLWTH W3,[W0++] ; 32nd_program_word
5
Flash and EEPROM
Programming
1. Write the new configuration value to the table write latch using a TBLWTL instruction.
2. Configure NVMCON for a Configuration register write (NVMCON = 0x4008).
3. Disable interrupts, if enabled.
4. Write the key sequence to NVMKEY.
5. Start the write sequence by setting WR (NVMCON<15>).
6. CPU execution will resume when the write is finished.
7. Re-enable interrupts, if needed.
The following code sequence can be used to modify a Device Configuration register:
; Set up a pointer to the location to be written.
MOV #tblpage(CONFIG_ADDR),W0
MOV W0,TBLPAG
MOV #tbloffset(CONFIG_ADDR),W0
; Get the new data to write to the configuration register
MOV #ConfigValue,W1
; Perform the table write to load the write latch
TBLWTL W1,[W0]
; Configure NVMCON for a configuration register write
MOV #0x4008,W0
MOV W0,NVMCON
; Disable interrupts, if enabled
PUSH SR
MOV #0x00E0,W0
IOR SR
; Write the KEY sequence
MOV #0x55,W0
MOV W0,NVMKEY
MOV #0xAA,W0
MOV W0,NVMKEY
; Start the programming sequence
BSET NVMCON,#WR
; Insert two NOPs after programming
NOP
NOP
; Re-enable interrupts, if required
POP SR
complete.
Programming
• Enable NVM interrupts. The CPU will be interrupted when the operation is complete.
Further programming operations can be handled in the ISR.
Note: Unexpected results will be obtained should the user attempt to read the EEPROM
while a programming or erase operation is underway.
5
Flash and EEPROM
Programming
5
Flash and EEPROM
Programming
Note: Sixteen table write instructions have been used in this code segment to provide
clarity in the example. The code segment could be simplified by using a single table
write instruction in a REPEAT loop.
Note: Program Space Visibility (PSV) can also be used to read locations in the program
memory address space. See Section 4. “Program Memory” for further information
about PSV.
Question 1: I cannot get the device to program or erase properly. My code appears to
be correct. What could be the cause?
Answer: Interrupts should be disabled when a program or erase cycle is initiated to ensure that
the key sequence executes without interruption. Interrupts can be disabled by raising the current
CPU priority to level 7. The code examples in this chapter disable interrupts by saving the current
SR register value on the stack, then ORing the value 0x00E0 with SR to force IPL<2:0> = 111.
If no priority level 7 interrupts are enabled, then the DISI instruction provides another method to
temporarily disable interrupts, while the key sequence is executed.
Question 2: What is an easy way to read data EEPROM without using table
instructions?
Answer: The data EEPROM is mapped into the program memory space. PSV can be used to
map the EEPROM region into data memory space. See Section 4. “Program Memory” for
further information about PSV.
5
Flash and EEPROM
Programming
5
Flash and EEPROM
Programming
NOTES:
Interrupts
Section 6. Reset Interrupts
HIGHLIGHTS
This section of the manual contains the following topics:
6.1 Introduction
The dsPIC30F interrupt controller module reduces the numerous peripheral interrupt request
signals to a single interrupt request signal to the dsPIC30F CPU and has the following features:
• Up to 8 processor exceptions and software traps
• 7 user selectable priority levels
• Interrupt Vector Table (IVT) with up to 62 vectors
• A unique vector for each interrupt or exception source
• Fixed priority within a specified user priority level
• Alternate Interrupt Vector Table (AIVT) for debug support
• Fixed interrupt entry and return latencies
Note: Any unimplemented or unused vector locations in the IVT and AIVT should be
programmed with the address of a default interrupt handler routine that contains a
RESET instruction.
Interrupts
Reset – GOTO Instruction 0x000000
Reset – GOTO Address 0x000002
Reserved 0x000004
Oscillator Fail Trap Vector
Address Error Trap Vector
Decreasing Natural
Stack Error Trap Vector
Order Priority
Arithmetic Error Trap Vector
IVT Reserved
Reserved
Reserved
Interrupt Vector 0 0x000014
Interrupt Vector 1
~
~
~
Interrupt Vector 52
Interrupt Vector 53 0x00007E
Reserved 0x000080
See Table 6-2
Reserved 0x000082
for Interrupt
Reserved 0x000084
Vector details.
Oscillator Fail Trap Vector
Address Error Trap Vector
Stack Error Trap Vector
Arithmetic Error Trap Vector
AIVT Reserved
Reserved
Reserved
Interrupt Vector 0 0x000094
Interrupt Vector 1
~
~
~
Interrupt Vector 52
Interrupt Vector 53 0x0000FE
Interrupts
The CPU can operate at one of sixteen priority levels, 0-15. An interrupt or trap source must have
a priority level greater than the current CPU priority in order to initiate an exception process.
Peripheral and external interrupt sources can be programmed for level 0-7, while CPU priority
levels 8-15 are reserved for trap sources. A trap is a non-maskable interrupt source intended to
detect hardware and software problems (see Section 6.2 ”Non-Maskable Traps”). The priority
level for each trap source is fixed and only one trap is assigned to a priority level. Note that an
interrupt source programmed to priority level 0 is effectively disabled, since it can never be
greater than the CPU priority.
The current CPU priority level is indicated by the following four status bits:
• IPL<2:0> status bits located in SR<7:5>
• IPL3 status bit located in CORCON<3>
The IPL<2:0> status bits are readable and writable, so the user may modify these bits to disable
all sources of interrupts below a given priority level. If IPL<2:0> = 3, for example, the CPU would
not be interrupted by any source with a programmed priority level of 0, 1, 2 or 3.
Trap events have higher priority than any user interrupt source. When the IPL3 bit is set, a trap
event is in progress. The IPL3 bit can be cleared, but not set by the user. In some applications,
it may be desirable to clear the IPL3 bit when a trap has occurred and branch to an instruction
other than the instruction after the one that originally caused the trap to occur.
All user interrupt sources can be disabled by setting IPL<2:0> = 111.
Note: The IPL<2:0> bits become read only bits when interrupt nesting is disabled. See
Section 6.2.4.2 ”Interrupt Nesting” for more information.
Note: The peripherals and sources of interrupt available in the IVT will vary depending on
the specific dsPIC30F device. The sources of interrupt shown in this document
represent a comprehensive listing of all interrupt sources found on dsPIC30F
devices. Refer to the specific device data sheet for further details.
The stack is initialized to 0x0800 during Reset. A stack error trap will be generated should the
stack pointer address ever be less than 0x0800.
There is a Stack Limit register (SPLIM) associated with the stack pointer that is uninitialized at
Reset. The stack overflow check is not enabled until a word write to SPLIM occurs.
All Effective Addresses (EA) generated using W15 as a source or destination pointer are
compared against the value in SPLIM. Should the EA be greater than the contents of the SPLIM
register, then a stack error trap is generated. In addition, a stack error trap will be generated
should the EA calculation wrap over the end of data space (0xFFFF).
A stack error can be detected in software by polling the STKERR status bit (INTCON1<2>). To
avoid re-entering the Trap Service Routine, the STKERR status flag must be cleared in software
prior to returning from the trap with a RETFIE instruction.
Interrupts
Any of the following events will cause an arithmetic error trap to be generated:
• Accumulator A Overflow
• Accumulator B Overflow
• Catastrophic Accumulator Overflow
• Divide by Zero
• Shift Accumulator (SFTAC) operation exceeding +/-16 bits
There are three enable bits in the INTCON1 register that enable the three types of accumulator
overflow traps. The OVATE control bit (INTCON1<10>) is used to enable traps for an Accumula-
tor A overflow event. The OVBTE control bit (INTCON1<9>) is used to enable traps for an
Accumulator B overflow event. The COVTE control bit (INTCON1<8>) is used to enable traps for
a catastrophic overflow of either accumulator.
An Accumulator A or Accumulator B overflow event is defined as a carry-out from bit 31. Note
that no accumulator overflow can occur if the 31-bit Saturation mode is enabled for the accumu-
lator. A catastrophic accumulator overflow is defined as a carry-out from bit 39 of either
accumulator. No catastrophic overflow can occur if accumulator saturation (31-bit or 39-bit) is
enabled.
Divide-by-zero traps cannot be disabled. The divide-by-zero check is performed during the first
iteration of the REPEAT loop that executes the divide instruction.
Accumulator shift traps cannot be disabled. The SFTAC instruction can be used to shift the
accumulator by a literal value or a value in one of the W registers. If the shift value exceeds
+/-16 bits, an arithmetic trap will be generated. The SFTAC instruction will execute, but the results
of the shift will not be written to the target accumulator.
An arithmetic error trap can be detected in software by polling the MATHERR status bit
(INTCON1<4>). To avoid re-entering the Trap Service Routine, the MATHERR status flag must
be cleared in software prior to returning from the trap with a RETFIE instruction. Before the
MATHERR status bit can be cleared, all conditions that caused the trap to occur must also be
cleared. If the trap was due to an accumulator overflow, the OA and OB status bits (SR<15:14>)
must be cleared. The OA and OB status bits are read only, so the user software must perform a
dummy operation on the overflowed accumulator (such as adding ‘0’) that will cause the
hardware to clear the OA or OB status bit.
If a higher priority trap occurs while any lower priority trap is in progress, processing of the lower
priority trap will be suspended and the higher priority trap will be Acknowledged and processed.
The lower priority trap will remain pending until processing of the higher priority trap completes.
Each hard trap that occurs must be Acknowledged before code execution of any type may
continue. If a lower priority hard trap occurs while a higher priority trap is pending, Acknowledged,
or is being processed, a hard trap conflict will occur. The conflict occurs because the lower
priority trap cannot be Acknowledged until processing for the higher priority trap completes.
The device is automatically reset in a hard trap conflict condition. The TRAPR status bit
(RCON<15> ) is set when the Reset occurs, so that the condition may be detected in software.
An oscillator failure trap event will be generated for any of the following reasons:
• The Fail-Safe Clock Monitor (FSCM) is enabled and has detected a loss of the system
clock source.
• A loss of PLL lock has been detected during normal operation using the PLL.
• The FSCM is enabled and the PLL fails to achieve lock at a Power-On Reset (POR).
An oscillator failure trap event can be detected in software by polling the OSCFAIL status bit
(INTCON1<1>), or the CF status bit (OSCCON<3>). To avoid re-entering the Trap Service
Routine, the OSCFAIL status flag must be cleared in software prior to returning from the trap with
a RETFIE instruction.
Refer to Section 7. “Oscillator” and Section 24. “Device Configuration” for more information
about the FSCM.
The following paragraphs describe operating scenarios that would cause an address error trap
to be generated:
1. A misaligned data word fetch is attempted. This condition occurs when an instruction
performs a word access with the LSb of the effective address set to ‘1’. The dsPIC30F
CPU requires all word accesses to be aligned to an even address boundary.
2. A bit manipulation instruction using the Indirect Addressing mode with the LSb of the
effective address set to ‘1’.
3. A data fetch from unimplemented data address space is attempted.
4. Execution of a “BRA #literal” instruction or a “GOTO #literal” instruction, where
literal is an unimplemented program memory address.
5. Executing instructions after modifying the PC to point to unimplemented program memory
addresses. The PC may be modified by loading a value into the stack and executing a
RETURN instruction.
Data space writes will be inhibited whenever an address error trap occurs, so that data is not
destroyed.
An address error can be detected in software by polling the ADDRERR status bit (INTCON1<3>).
To avoid re-entering the Trap Service Routine, the ADDRERR status flag must be cleared in
software prior to returning from the trap with a RETFIE instruction.
Note: In the MAC class of instructions, the data space is split into X and Y spaces. In these
instructions, unimplemented X space includes all of Y space, and unimplemented Y
space includes all of X space.
Interrupts
Once the DISI instruction has executed and DISICNT holds a non-zero value, the interrupt
disable time can be extended by modifying the contents of DISICNT.
Note: Software modification of the DISICNT register is not recommended.
The DISI status bit (INTCON2<14>) is set whenever interrupts are disabled as a result of the
DISI instruction.
Note: The DISI instruction can be used to quickly disable all user interrupt sources if no
source is assigned to CPU priority level 7.
15 0
This stack location used
to store the IPL3 status
Stack Grows Towards
bit (CORCON<3>).
Higher Address
The RETFIE (Return from Interrupt) instruction will unstack the PC return address, IPL3 status
bit, and SRL register to return the processor to the state and priority level prior to the interrupt
sequence.
Interrupts, by default, are nestable. Any ISR that is in progress may be interrupted by another
source of interrupt with a higher user assigned priority level. Interrupt nesting may be optionally
disabled by setting the NSTDIS control bit (INTCON1<15>). When the NSTDIS control bit is set,
all interrupts in progress will force the CPU priority to level 7 by setting IPL<2:0> = 111. This
action will effectively mask all other sources of interrupt until a RETFIE instruction is executed.
When interrupt nesting is disabled, the user assigned interrupt priority levels will have no effect,
except to resolve conflicts between simultaneous pending interrupts.
The IPL<2:0> bits become read only when interrupt nesting is disabled. This prevents the user
software from setting IPL<2:0> to a lower value, which would effectively re-enable interrupt
nesting.
Note: User interrupt sources that are assigned to CPU priority level 0 cannot wake the
CPU from Sleep or Idle mode, because the interrupt source is effectively disabled.
To use an interrupt as a wake-up source, the CPU priority level for the interrupt must
be assigned to CPU priority level 1 or greater.
Interrupts
6.3.1 Interrupt Latency for One-Cycle Instructions
Figure 6-3 shows the sequence of events when a peripheral interrupt is asserted during a
one-cycle instruction. The interrupt process takes four instruction cycles. Each cycle is numbered
in the Figure for reference.
The interrupt flag status bit is set during the instruction cycle after the peripheral interrupt occurs.
The current instruction completes during this instruction cycle. In the second instruction
cycle after the interrupt event, the contents of the PC and SRL registers are saved into a
temporary buffer register. The second cycle of the interrupt process is executed as a NOP to
maintain consistency with the sequence taken during a two-cycle instruction (see Section 6.3.2
”Interrupt Latency for Two-Cycle Instructions”). In the third cycle, the PC is loaded with the
vector table address for the interrupt source and the starting address of the ISR is fetched. In the
fourth cycle, the PC is loaded with the ISR address. The fourth cycle is executed as a NOP while
the first instruction in the ISR is fetched.
TCY 1 2 3 4
INST Fetch
Executed INST(PC-2) INST(PC) FNOP Vector FNOP ISR ISR + 2 ISR + 4
Interrupt Flag
Status bit
CPU Priority 4 4 4 4 6 6 6 6
TCY 1 2 3 4
INST
Executed INST(PC-2) INST(PC) INST(PC) Fetch FNOP ISR ISR + 2 ISR + 4
1st cycle 2nd cycle Vector
Interrupt Flag
Status bit
CPU Priority 4 4 4 4 6 6 6 6
Figure 6-5: Interrupt Timing, Interrupt Occurs During 1st Cycle of a 2-Cycle Instruction
TCY 1 2 3 4
Interrupt Flag
Status bit
CPU Priority 4 4 4 4 6 6 6 6
Interrupts
The “Return from Interrupt” instruction, RETFIE, exits an interrupt or trap routine.
During the first cycle of a RETFIE instruction, the upper bits of the PC and the SRL register are
popped from the stack. The lower 16 bits of the stacked PC value are popped from the stack
during the second cycle. The third instruction cycle is used to fetch the instruction addressed by
the updated program counter. This cycle executes as a NOP.
TCY
PC ISR ISR + 2 PC PC + 2 PC + 4 PC + 6
CPU
Priority 6 6 6 4 4 4 4
Note: The total number and type of interrupt sources will depend on the device variant.
Refer to the specific device data sheet for further details.
Interrupts
R-0 R-0 R/C-0 R/C-0 R-0 R/C-0 R-0 R-0
OA OB SA SB OAB SAB DA DC
bit 15 bit 8
Lower Byte:
R/W-0 R/W-0 R/W-0 R-0 R/W-0 R/W-0 R/W-0 R/W-0
IPL<2:0> RA N OV Z C
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’ C = Bit can be cleared
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
R/W-0 R/W-0 R/W-1 R/W-0 R/C-0 R/W-0 R/W-0 R/W-0
SATA SATB SATDW ACCSAT IPL3 PSV RND IF
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’ C = Bit can be cleared
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
U-0 U-0 U-0 R/W-0 R/W-0 R/W-0 R/W-0 U-0
— — — MATHERR ADDRERR STKERR OSCFAIL —
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Interrupts
R/W-0 R-0 U-0 U-0 U-0 U-0 U-0 U-0
ALTIVT DISI — — — — — —
bit 15 bit 8
Lower Byte:
U-0 U-0 U-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
— — — INT4EP INT3EP INT2EP INT1EP INT0EP
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
T3IF T2IF OC2IF IC2IF T1IF OC1IF IC1IF INT0IF
bit 7 bit 0
Interrupts
bit 1 IC1IF: Input Capture Channel 1 Interrupt Flag Status bit
1 = Interrupt request has occurred
0 = Interrupt request has not occurred
bit 0 INT0IF: External Interrupt 0 Flag Status bit
1 = Interrupt request has occurred
0 = Interrupt request has not occurred
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
INT2IF T5IF T4IF OC4IF OC3IF IC8IF IC7IF INT1IF
bit 7 bit 0
Interrupts
bit 1 IC7IF: Input Capture Channel 7 Interrupt Flag Status bit
1 = Interrupt request has occurred
0 = Interrupt request has not occurred
bit 0 INT1IF: External Interrupt 1 Flag Status bit
1 = Interrupt request has occurred
0 = Interrupt request has not occurred
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
PWMIF C2IF INT4IF INT3IF OC8IF OC7IF OC6IF OC5IF
bit 7 bit 0
Interrupts
bit 1 OC6IF: Output Compare Channel 6 Interrupt Flag Status bit
1 = Interrupt request has occurred
0 = Interrupt request has not occurred
bit 0 OC5IF: Output Compare Channel 5 Interrupt Flag Status bit
1 = Interrupt request has occurred
0 = Interrupt request has not occurred
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
T3IE T2IE OC2IE IC2IE T1IE OC1IE IC1IE INT0IE
bit 7 bit 0
Interrupts
bit 1 IC1IE: Input Capture Channel 1 Interrupt Enable bit
1 = Interrupt request enabled
0 = Interrupt request not enabled
bit 0 INT0IE: External Interrupt 0 Enable bit
1 = Interrupt request enabled
0 = Interrupt request not enabled
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
INT2IE T5IE T4IE OC4IE OC3IE IC8IE IC7IE INT1IE
bit 7 bit 0
Interrupts
bit 1 IC7IE: Input Capture Channel 7 Interrupt Enable bit
1 = Interrupt request enabled
0 = Interrupt request not enabled
bit 0 INT1IE: External Interrupt 1 Enable bit
1 = Interrupt request enabled
0 = Interrupt request not enabled
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
PWMIE C2IE INT4IE INT3IE OC8IE OC7IE OC6IE OC5IE
bit 7 bit 0
Interrupts
bit 1 OC6IE: Output Compare Channel 6 Interrupt Enable bit
1 = Interrupt request enabled
0 = Interrupt request not enabled
bit 0 OC5IE: Output Compare Channel 5 Interrupt Enable bit
1 = Interrupt request enabled
0 = Interrupt request not enabled
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
U-0 R/W-1 R/W-0 R/W-0 U-0 R/W-1 R/W-0 R/W-0
— IC1IP<2:0> — INT0IP<2:0>
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Interrupts
U-0 R/W-1 R/W-0 R/W-0 U-0 R/W-1 R/W-0 R/W-0
— T3IP<2:0> — T2IP<2:0>
bit 15 bit 8
Lower Byte:
U-0 R/W-1 R/W-0 R/W-0 U-0 R/W-1 R/W-0 R/W-0
— OC2IP<2:0> — IC2IP<2:0>
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
U-0 R/W-1 R/W-0 R/W-0 U-0 R/W-1 R/W-0 R/W-0
— U1RXIP<2:0> — SPI1IP<2:0>
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Interrupts
U-0 R/W-1 R/W-0 R/W-0 U-0 R/W-1 R/W-0 R/W-0
— CNIP<2:0> — MI2CIP<2:0>
bit 15 bit 8
Lower Byte:
U-0 R/W-1 R/W-0 R/W-0 U-0 R/W-1 R/W-0 R/W-0
— SI2CIP<2:0> — NVMIP<2:0>
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
U-0 R/W-1 R/W-0 R/W-0 U-0 R/W-1 R/W-0 R/W-0
— IC7IP<2:0> — INT1IP<2:0>
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Interrupts
U-0 R/W-1 R/W-0 R/W-0 U-0 R/W-1 R/W-0 R/W-0
— INT2IP<2:0> — T5IP<2:0>
bit 15 bit 8
Lower Byte:
U-0 R/W-1 R/W-0 R/W-0 U-0 R/W-1 R/W-0 R/W-0
— T4IP<2:0> — OC4IP<2:0>
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
U-0 R/W-1 R/W-0 R/W-0 U-0 R/W-1 R/W-0 R/W-0
— U2TXIP<2:0> — U2RXIP<2:0>
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Interrupts
U-0 R/W-1 R/W-0 R/W-0 U-0 R/W-1 R/W-0 R/W-0
— IC6IP<2:0> — IC5IP<2:0>
bit 15 bit 8
Lower Byte:
U-0 R/W-1 R/W-0 R/W-0 U-0 R/W-1 R/W-0 R/W-0
— IC4IP<2:0> — IC3IP<2:0>
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
U-0 R/W-1 R/W-0 R/W-0 U-0 R/W-1 R/W-0 R/W-0
— OC6IP<2:0> — OC5IP<2:0>
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Interrupts
U-0 R/W-1 R/W-0 R/W-0 U-0 R/W-1 R/W-0 R/W-0
— PWMIP<2:0> — C2IP<2:0>
bit 15 bit 8
Lower Byte:
U-0 R/W-1 R/W-0 R/W-0 U-0 R/W-1 R/W-0 R/W-0
— INT4IP<2:0> — INT3IP<2:0>
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
U-0 R/W-1 R/W-0 R/W-0 U-0 R/W-1 R/W-0 R/W-0
— DCIIP<2:0> — QEIIP<2:0>
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Interrupts
U-0 U-0 U-0 U-0 U-0 U-0 U-0 U-0
— — — — — — — —
bit 15 bit 8
Lower Byte:
U-0 U-0 U-0 U-0 U-0 R/W-1 R/W-0 R/W-0
— — — — — FLTBIP<2:0>
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
6.5.1 Initialization
The following steps describe how to configure a source of interrupt:
1. Set the NSTDIS Control bit (INTCON1<15>) if nested interrupts are not desired.
2. Select the user assigned priority level for the interrupt source by writing the control bits in
the appropriate IPCx Control register. The priority level will depend on the specific
application and type of interrupt source. If multiple priority levels are not desired, the IPCx
register control bits for all enabled interrupt sources may be programmed to the same
non-zero value.
Note: At a device Reset, the IPC registers are initialized, such that all user interrupt
sources are assigned to priority level 4.
3. Clear the interrupt flag status bit associated with the peripheral in the associated IFSx
Status register.
4. Enable the interrupt source by setting the interrupt enable control bit associated with the
source in the appropriate IECx Control register.
INTCON1 0080 NSTDIS — — — — OVATE OVBTE COVTE — — — MATHERR ADDRERR STKERR OSCFAIL — 0000 0000 0000 0000
INTCON2 0082 ALTIVT — — — — — — — — — — INT4EP INT3EP INT2EP INT1EP INT0EP 0000 0000 0000 0000
IFT0IF 0084 CNIF MI2CIF SI2CIF NVMIF ADIF U1TXIF U1RXIF SPI1IF T3IF T2IF OC2IF IC2IF T1IF OC1IF IC1IF INT0 0000 0000 0000 0000
IFS1 0086 IC6IF IC5IF IC4IF IC3IF C1IF SPI2IF U2TXIF U2RXIF INT2IF T5IF T4IF OC4IF OC3IF IC8IF IC7IF INT1IF 0000 0000 0000 0000
IFS2 0088 — — — FLTBIF FLTAIF LVDIF DCIIF QEIIF PWMIF C2IF INT4IF INT3IF OC8IF OC7IF OC6IF OC5IF 0000 0000 0000 0000
IEC0 008C CNIE MI2CIE SI2CIE NVMIE ADIE U1TXIE U1RXIE SPI1IE T3IE T2IE OC2IE IC2IE T1IE OC1IE IC1IE INT0IE 0000 0000 0000 0000
DS70053C-page 6-43
Section 6. Interrupts
6
Interrupts
dsPIC30F Family Reference Manual
Question 1: What happens when two sources of interrupt become pending at the same
time and have the same user assigned priority level?
Answer: The interrupt source with the highest natural order priority will take precedence. The
natural order priority is determined by the Interrupt Vector Table (IVT) address for that source.
Interrupt sources with a smaller IVT address have a higher natural order priority.
Question 2: Can the DISI instruction be used to disable all sources of interrupt and
traps?
Answer: The DISI instruction does not disable traps or priority level 7 interrupt sources.
However, the DISI instruction can be used as a convenient way to disable all interrupt sources
if no priority level 7 interrupt sources are enabled in the user’s application.
Interrupts
application notes may not be written specifically for the dsPIC30F Product Family, but the
concepts are pertinent and could be used with modification and possible limitations. The current
application notes related to the Interrupts module are:
Note: Please visit the Microchip web site (www.microchip.com) for additional Application
Notes and code examples for the dsPIC30F Family of devices.
HIGHLIGHTS
This section of the manual contains the following topics:
7
7.1 Introduction .................................................................................................................... 7-2
Oscillator
7.2 Device Clocking and MIPS ............................................................................................ 7-5
7.3 Oscillator Configuration.................................................................................................. 7-6
7.4 Oscillator Control Registers – OSCCON and OSCTUN .............................................. 7-13
7.5 Primary Oscillator......................................................................................................... 7-20
7.6 Crystal Oscillators/Ceramic Resonators ...................................................................... 7-22
7.7 Determining Best Values for Crystals, Clock Mode, C1, C2 and Rs ............................ 7-24
7.8 External Clock Input..................................................................................................... 7-25
7.9 External RC Oscillator.................................................................................................. 7-26
7.10 Phase Locked Loop (PLL) ........................................................................................... 7-30
7.11 Low-Power 32 kHz Crystal Oscillator........................................................................... 7-31
7.12 Oscillator Start-up Timer (OST).................................................................................... 7-31
7.13 Internal Fast RC Oscillator (FRC) ................................................................................ 7-31
7.14 Internal Low-Power RC (LPRC) Oscillator................................................................... 7-32
7.15 Fail-Safe Clock Monitor (FSCM) .................................................................................. 7-32
7.16 Programmable Oscillator Postscaler............................................................................ 7-33
7.17 Clock Switching Operation........................................................................................... 7-34
7.18 Design Tips .................................................................................................................. 7-38
7.19 Related Application Notes............................................................................................ 7-39
7.20 Revision History ........................................................................................................... 7-40
7.1 Introduction
This section describes the operation of the oscillator system for dsPIC30F devices in the General
Purpose, Sensor and Motor Control families. The oscillator system has the following modules
and features:
• Various external and internal oscillator options as clock sources
• An on-chip PLL to boost internal operating frequency
• Clock switching between various clock sources
• Programmable clock postscaler for system power savings
• A Fail-Safe Clock Monitor (FSCM) that detects clock failure and takes fail-safe measures
• Device clocking controlled by Special Function Registers as well as nonvolatile Configura-
tion bits
A simplified diagram of the oscillator system is shown in Figure 7-1.
VERSION 2 30F2010, Oscillator System VERSION 2 adds the following capabilities to VERSION 1:
30F4011, • Internal FRC oscillator may also be provided as an input to the PLL to allow fast
30F4012, execution while eliminating the need for an external clock source (This feature is
30F5011, applicable to all devices other than the 30F2010)
30F5013 • User tuning capability added for the Internal FRC oscillator
Oscillator
30F6011A,
30F6012A,
30F6013A,
30F6014A,
30F6015
OSC1
Primary PLL PLL
Oscillator x4, x8, x16
OSC2
Primary Osc
(2)
Primary
Oscillator
Stability Detector
Oscillator
POR Start-up
Timer Clock
Switching Programmable
Secondary Osc and Control Clock Divider
FOSC(1)
Block
SOSCO Secondary
Secondary
Oscillator Oscillator
SOSCI 32 kHz Stability Detector
to Timer1
Note 1: The system clock output, FOSC, is divided by 4 to get the instruction cycle clock.
2: Devices that feature VERSION 2 or VERSION 3 of the Oscillator System allow the internal FRC oscillator to be
connected to the PLL.
Oscillator
TCY
FOSC
FCY
PC PC PC + 2 PC + 4
Register 7-1: FOSC: Oscillator Configuration Register for Oscillator System VERSION 1
Upper Byte:
U U U U U U U U
— — — — — — — —
bit 23 bit 16
Middle Byte:
R/P R/P U U U U R/P R/P
FCKSM<1:0> — — — — FOS<1:0>
bit 15 bit 8 7
Lower Byte:
Oscillator
U U U U R/P R/P R/P R/P
— — — — FPR<3:0>
bit 7 bit 0
Legend:
R = Readable bit P = Programmable bit U = Unimplemented bit
Table 7-2: Oscillator System VERSION 1: Configuration Bit Values for Clock Selection
Oscillator OSC2 Pin
Oscillator Mode FOS<1:0> FPR<3:0>
Source Function
EC w/ PLL 16x Primary 1 1 1 1 1 1 I/O (Note 4)
EC w/ PLL 8x Primary 1 1 1 1 1 0 I/O
EC w/ PLL 4x Primary 1 1 1 1 0 1 I/O
ECIO Primary 1 1 1 1 0 0 I/O
EC Primary 1 1 1 0 1 1 FOSC/4
Reserved Primary 1 1 1 0 1 0 n/a
ERC Primary 1 1 1 0 0 1 FOSC/4
ERCIO Primary 1 1 1 0 0 0 I/O
XT w/ PLL 16x Primary 1 1 0 1 1 1 (Note 3)
XT w/ PLL 8x Primary 1 1 0 1 1 0 (Note 3)
XT w/ PLL 4x Primary 1 1 0 1 0 1 (Note 3)
XT Primary 1 1 0 1 0 0 (Note 3)
HS Primary 1 1 0 0 1 x (Note 3)
XTL Primary 1 1 0 0 0 x (Note 3)
LP Secondary 0 0 — — — — (Notes 1, 2)
FRC Internal 0 1 — — — — (Notes 1, 2)
LPRC Internal 1 0 — — — — (Notes 1, 2)
Note 1: OSC2 pin function is determined by the Primary Oscillator mode selection (FPR<3:0> Configuration bits).
2: Note that OSC1 pin cannot be used as an I/O pin, even if the Secondary oscillator or an internal clock
source is selected at all times.
3: In these Oscillator modes, a crystal is connected between the OSC1 and OSC2 pins.
4: This is the default Oscillator mode for an unprogrammed (erased) device. An unprogrammed Configuration
bit has a value of ‘1’.
5: XTL – XTL Crystal Oscillator mode (200 kHz-4 MHz crystal)
6: XT – XT Crystal Oscillator mode (4 MHz-10 MHz crystal)
7: HS – HS Crystal Oscillator mode (10 MHz-25 MHz crystal)
Register 7-2: FOSC: Oscillator Configuration Register for Oscillator System VERSION 2
Upper Byte:
U U U U U U U U
— — — — — — — —
bit 23 bit 16
Middle Byte:
R/P R/P U U U U R/P R/P
FCKSM<1:0> — — — — FOS<1:0>
bit 15 bit 8 7
Lower Byte:
Oscillator
U U U U R/P R/P R/P R/P
— — — — FPR<3:0>
bit 7 bit 0
Legend:
R = Readable bit P = Programmable bit U = Unimplemented bit
Table 7-3: Oscillator System VERSION 2: Configuration Bit Values for Clock Selection:
Oscillator OSC2 Pin
Oscillator Mode FOS<1:0> FPR<3:0>
Source Function
EC Primary 1 1 1 0 1 1 CLKO
ECIO Primary 1 1 1 1 0 0 I/O
EC w/PLL 4x Primary 1 1 1 1 0 1 I/O
EC w/PLL 8x Primary 1 1 1 1 1 0 I/O
EC w/PLL 16x Primary 1 1 1 1 1 1 I/O (Note 4)
ERC Primary 1 1 1 0 0 1 CLKO
ERCIO Primary 1 1 1 0 0 0 I/O
XT Primary 1 1 0 1 0 0 (Note 3)
XT w/PLL 4x Primary 1 1 0 1 0 1 (Note 3)
XT w/PLL 8x Primary 1 1 0 1 1 0 (Note 3)
XT w/PLL 16x Primary 1 1 0 1 1 1 (Note 3)
XTL Primary 1 1 0 0 0 0 (Note 3)
HS Primary 1 1 0 0 1 0 (Note 3)
FRC w/PLL 4x Primary 1 1 0 0 0 1 I/O
FRC w/PLL 8x Primary 1 1 1 0 1 0 I/O
FRC w/PLL 16x Primary 1 1 0 0 1 1 I/O
LP Secondary 0 0 — — — — (Notes 1, 2)
FRC Internal FRC 0 1 — — — — (Notes 1, 2)
LPRC Internal LPRC 1 0 — — — — (Notes 1, 2)
Note 1: OSC2 pin function is determined by the Primary Oscillator mode selection (FPR<3:0>).
2: Note that OSC1 pin cannot be used as an I/O pin, even if the secondary oscillator or an internal clock
source is selected at all times.
3: In these Oscillator modes, a crystal is connected between the OSC1 and OSC2 pins.
4: This is the default Oscillator mode for an unprogrammed (erased) device. An unprogrammed Configuration
bit has a value of ‘1’.
5: XTL – XTL Crystal Oscillator mode (200 kHz-4 MHz crystal)
6: XT – XT Crystal Oscillator mode (4 MHz-10 MHz crystal)
7: HS – HS Crystal Oscillator mode (10 MHz-25 MHz crystal)
Register 7-3: FOSC: Oscillator Configuration Register for Oscillator System VERSION 3
Upper Byte:
U U U U U U U U
— — — — — — — —
bit 23 bit 16
Middle Byte:
R/P R/P U U U R/P R/P R/P
FCKSM<1:0> — — — FOS<2:0>
bit 15 bit 8 7
Lower Byte:
Oscillator
U U U R/P R/P R/P R/P R/P
— — — FPR<4:0>
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
Table 7-4: Oscillator System VERSION 3: Configuration Bit Values for Clock Selection
Oscillator OSC2 Pin
Oscillator Mode FOS<2:0> FPR<4:0>
Source Function
ECIO w/ PLL 4x PLL 1 1 1 0 1 1 0 1 I/O
ECIO w/ PLL 8x PLL 1 1 1 0 1 1 1 0 I/O
ECIO w/ PLL 16x PLL 1 1 1 0 1 1 1 1 I/O
FRC w/ PLL 4x PLL 1 1 1 0 0 0 0 1 I/O
FRC w/ PLL 8x PLL 1 1 1 0 1 0 1 0 I/O
FRC w/ PLL 16x PLL 1 1 1 0 0 0 1 1 I/O
XT w/ PLL 4x PLL 1 1 1 0 0 1 0 1 (Note 3)
XT w/ PLL 8x PLL 1 1 1 0 0 1 1 0 (Note 3)
XT w/ PLL 16x PLL 1 1 1 0 0 1 1 1 (Note 3)
HS2 w/ PLL 4x PLL 1 1 1 1 0 0 0 1 (Note 3)
HS2 w/ PLL 8x PLL 1 1 1 1 0 0 1 0 (Note 3)
HS2 w/ PLL 16x PLL 1 1 1 1 0 0 1 1 (Note 3)
HS3 w/ PLL 4x PLL 1 1 1 1 0 1 0 1 (Note 3)
HS3 w/ PLL 8x PLL 1 1 1 1 0 1 1 0 (Note 3)
HS3 w/ PLL 16x PLL 1 1 1 1 0 1 1 1 (Note 3)
ECIO External 0 1 1 0 1 1 0 0 I/O
XT External 0 1 1 0 0 1 0 0 (Note 3)
HS External 0 1 1 0 0 0 1 0 (Note 3)
EC External 0 1 1 0 1 0 1 1 CLKOUT
ERC External 0 1 1 0 1 0 0 1 CLKOUT
ERCIO External 0 1 1 0 1 0 0 0 I/O
XTL External 0 1 1 0 0 0 0 0 (Note 3)
LP Secondary 0 0 0 x x x x x (Note 1, 2)
FRC Internal FRC 0 0 1 x x x x x (Note 1, 2)
LPRC Internal LPRC 0 1 0 x x x x x (Note 1, 2)
Note 1: OSC2 pin function is determined by (FPR<4:0>).
2: OSC1 pin cannot be used as an I/O pin even if the secondary oscillator or an internal clock source is
selected at all times.
3: In these Oscillator modes, a crystal is connected between the OSC1 and OSC2 pins.
4: XTL – XTL Crystal Oscillator mode (200 kHz-4 MHz crystal)
5: XT – XT Crystal Oscillator mode (4 MHz-10 MHz crystal)
6: HS – HS Crystal Oscillator mode (10 MHz-25 MHz crystal)
Oscillator
The OSCCON Control register provides control of clock switching and clock source status
information.
The COSC Status bits in OSCCON are read-only bits that indicate the oscillator source that the
device is operating from. The COSC bits are set to the FOS Configuration bit values at a
Power-on Reset and will change to indicate the new oscillator source at the end of a clock switch
operation.
The NOSC Status bits in OSCCON are control bits that select the new clock source for a clock
switch operation. The NOSC bits are set to the FOS Configuration bit values at a Power-on Reset
or Brown-out Reset and are modified by the user software during a clock switch operation.
The POST<1:0> control bits (OSCCON<8:7>) control the system clock divide ratio.
The LOCK Status bit (OSCCON<5>) is read-only and indicates the status of the PLL circuit.
The CF Status bit (OSCCON<3>) is a readable/writable Status bit that indicates a clock failure.
The LPOSCEN control bit (OSCCON<1>) is used to enable or disable the 32 kHz Low-Power
Crystal oscillator.
The OSWEN control bit (OSCCON<0>) is used to initiate a clock switch operation. The OSWEN
bit is cleared automatically after a successful clock switch.
The TUN<3:0> bits allow the user to tune the internal FRC oscillator to frequencies higher and
lower than the nominal value of 7.37 MHz.
Note: The OSCCON register is write-protected because it controls the device clock
switching mechanism. See Section 7.4.1 “Protection Against Accidental Writes
to OSCCON” for instructions on writing to OSCCON.
Lower Byte:
R/W-0 R/W-0 R-0 U-0 R/W-0 U-0 R/W-0 R/W-0
POST<1:0> LOCK — CF — LPOSCEN OSWEN
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
y = Value set from Configuration bits on POR or BOR
Lower Byte:
R/W-0 R/W-0 R-0 U-0 R/W-0 U-0 R/W-0 R/W-0
POST<1:0> LOCK — CF — LPOSCEN OSWEN
bit 7 bit 0
7
bit 15-14 TUN<3:2>: Upper 2 bits of the TUN bit-field. Refer to the description of TUN<1:0> (OSCCON<11:10>)
bits for details.
Oscillator
bit 13-12 COSC<1:0>: Current Oscillator Source Status bits
11 = Primary oscillator
10 = Internal LPRC oscillator
01 = Internal FRC oscillator
00 = Low-Power 32 kHz Crystal oscillator (Timer1)
bit 11-10 TUN<1:0>: Lower 2 bits of the TUN bit-field.
The four bit field specified by TUN<3:0> allows the user to tune the Internal Fast RC oscillator which has
a nominal frequency of 7.37 MHz. For example, the user may be able to tune the frequency of the FRC
oscillator within a range of +/- 12% (or 960 kHz) in steps of 1.5% around the factory-calibrated frequency
setting, as follows:
TUN<3:0> = 0111 provides the highest frequency
......
TUN<3:0> = 0000 provides the factory-calibrated frequency
......
TUN<3:0> = 1000 provides the lowest frequency
Note: Refer to the device-specific data sheet for the exact tuning range and tuning step size for the
FRC oscillator on your device.
bit 9-8 NOSC<1:0>: New Oscillator Group Selection bits
11 = Primary oscillator
10 = Internal LPRC oscillator
01 = Internal FRC oscillator
00 = Low-Power 32 kHz Crystal oscillator (Timer1)
bit 7-6 POST<1:0>: Oscillator Postscaler Selection bits
11 = Oscillator postscaler divides clock by 64
10 = Oscillator postscaler divides clock by 16
01 = Oscillator postscaler divides clock by 4
00 = Oscillator postscaler does not alter clock
bit 5 LOCK: PLL Lock Status bit
1 = Indicates that PLL is in lock
0 = Indicates that PLL is out of lock (or disabled)
Reset on POR or BOR
Reset when a valid clock switching sequence is initiated
Set when PLL lock is achieved after a PLL start
Reset when lock is lost
Read zero when PLL is not selected as a system clock
bit 4 Unimplemented: Read as ‘0’
bit 3 CF: Clock Fail Status bit
1 = FSCM has detected a clock failure
0 = FSCM has not detected a clock failure
Reset on POR or BOR
Reset when a valid clock switching sequence is initiated
Set when clock fail detected
bit 2 Unimplemented: Read as ‘0’
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
y = Value set from Configuration bits on POR or BOR
Lower Byte:
R/W-0 R/W-0 R-0 U-0 R/W-0 U-0 R/W-0 R/W-0
POST<1:0> LOCK — CF — LPOSCEN OSWEN
bit 7 bit 0 7
bit 15 Unimplemented: Read as ‘0’
Oscillator
bit 14-12 COSC<2:0>: Current Oscillator Group Selection bits (Read-Only)
111 = PLL Oscillator; PLL source selected by FPR<4:0> bits
011 = External Oscillator; OSC1/OSC2 pins; External Oscillator configuration selected by FPR<4:0> bits
010 = LPRC internal low-power RC
001 = FRC internal fast RC
000 = LP crystal oscillator; SOSCI/SOSCO pins
Set to FOS<2:0> values on POR or BOR
Loaded with NOSC<2:0> at the completion of a successful clock switch
Set to FRC value when FSCM detects a failure and switches clock to FRC
bit 11 Unimplemented: Read as ‘0’
bit 10-8 NOSC<2:0>: New Oscillator Group Selection bits
111 = PLL Oscillator; PLL source selected by FPR<4:0> bits
011 = External Oscillator; OSC1/OSC2 pins; External Oscillator configuration selected by FPR<4:0> bits
010 = LPRC internal low-power RC
001 = FRC internal fast RC
000 = LP crystal oscillator; SOSCI/SOSCO pins
Set to FOS<2:0> values on POR or BOR
bit 7-6 POST<1:0>: Oscillator Postscaler Selection bits
11 = Oscillator postscaler divides clock by 64
10 = Oscillator postscaler divides clock by 16
01 = Oscillator postscaler divides clock by 4
00 = Oscillator postscaler does not alter clock
bit 5 LOCK: PLL Lock Status bit (Read-Only)
1 = Indicates that PLL is in lock
0 = Indicates that PLL is out of lock (or disabled)
Reset on POR or BOR
Reset when a valid clock switching sequence is initiated
Set when PLL lock is achieved after a PLL start
Reset when lock is lost
Read zero when PLL is not selected as a system clock
bit 4 Unimplemented: Read as ‘0’
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
y = Value set from Configuration bits on POR
Register 7-7: OSCTUN: FRC Oscillator Tuning Register – Oscillator System VERSION 3 Only
Upper Byte:
U-0 U-0 U-0 U-0 U-0 U-0 U-0 U-0
— — — — — — — —
bit 15 bit 8
Lower Byte:
U-0 U-0 U-0 U-0 R/W-0 R/W-0 R/W-0 R/W-0
— — — — TUN<3:0>
bit 7 bit 0 7
bit 15-4 Unimplemented: Read as ‘0’
Oscillator
bit 3-0 TUN<3:0>: The four bit field specified by TUN<3:0> allows the user to tune the Internal Fast RC oscillator
which has a nominal frequency of 7.37 MHz.
TUN<3:0> = 0111 provides the highest frequency
......
TUN<3:0> = 0000 provides the factory-calibrated frequency
......
TUN<3:0> = 1000 provides the lowest frequency
Note 1: Refer to the device-specific data sheet for the exact tuning range and tuning step size for the
FRC oscillator on your device.
2: Certain devices may have more than four TUN bits. Refer to the device-specific data sheet to
identify the number of TUN bits available to the user for tuning the FRC oscillator.
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
y = Value set from Configuration bits on POR
Oscillator
If the Primary oscillator is configured for an external clock input or an external RC network, the
OSC2 pin is not required to support the oscillator function. For these modes, the OSC2 pin can
be used as an additional device I/O pin or a clock output pin. When the OSC2 pin is used as a
clock output pin, the output frequency is FOSC/4.
The XTL mode is a Low Power/Low Frequency mode. This mode of the oscillator consumes the
least amount of power of the three Crystal modes. The XT mode is a Medium Power/Medium
Frequency mode and HS mode provides the highest oscillator frequencies with a crystal.
The EC and XT modes that use the PLL circuit provide the highest device operating frequencies.
The oscillator circuit will consume the most current in these modes because the PLL is enabled
to multiply the frequency of the oscillator.
OSC1
Note 1: A series resistor, Rs, may be required for AT strip cut crystals.
2: The internal feedback resistor, RF, is typically in the range of 2 to
10 MΩ.
3: See Section 7.7 “Determining Best Values for Crystals, Clock
Mode, C1, C2 and Rs”.
VIH
Voltage
VIL
0V
Oscillator
• stability
• crystal life
• power consumption
• simplification of the circuit
• use of standard components
• component count
7.7 Determining Best Values for Crystals, Clock Mode, C1, C2 and RS
The best method for selecting components is to apply a little knowledge and a lot of trial,
measurement and testing.
Crystals are usually selected by their parallel resonant frequency only, however, other parame-
ters may be important to your design, such as temperature or frequency tolerance. Application
Note AN588 “PICmicro® Microcontroller Oscillator Design Guide” is an excellent reference to
learn more about crystal operation and their ordering information.
The dsPIC30F internal oscillator circuit is a parallel oscillator circuit, which requires that a parallel
resonant crystal be selected. The load capacitance is usually specified in the 22 pF to 33 pF
range. The crystal will oscillate closest to the desired frequency with a load capacitance in this
range. It may be necessary to alter these values, as described later, in order to achieve other
benefits.
The Clock mode is primarily chosen based on the desired frequency of the crystal oscillator. The
main difference between the XT, XTL and HS Oscillator modes is the gain of the internal inverter
of the oscillator circuit, which allows the different frequency ranges. In general, use the oscillator
option with the lowest possible gain that still meets specifications. This will result in lower
dynamic currents (IDD). The frequency range of each Oscillator mode is the recommended
frequency cutoff, but the selection of a different Gain mode is acceptable, as long as a thorough
validation is performed (voltage, temperature and component variations, such as resistor,
capacitor and internal oscillator circuitry).
C1 and C2 (see Figure 7-3) should also be initially selected based on the load capacitance as
suggested by the crystal manufacturer and the tables supplied in the device data sheet. The
values given in the device data sheet can only be used as a starting point since the crystal
manufacturer, supply voltage, and other factors already mentioned may cause your circuit to
differ from the one used in the factory characterization process.
Ideally, the capacitance is chosen so that it will oscillate at the highest temperature and the lowest
VDD that the circuit will be expected to perform under. High temperature and low VDD both have
a limiting effect on the loop gain, such that if the circuit functions at these extremes, the designer
can be more assured of proper operation at other temperatures and supply voltage
combinations. The output sine wave should not be clipped in the highest gain environment
(highest VDD and lowest temperature) and the sine output amplitude should be large enough in
the lowest gain environment (lowest VDD and highest temperature) to cover the logic input
requirements of the clock as listed in the device data sheet.
A method for improving start-up is to use a value of C2 greater than C1. This causes a greater
phase shift across the crystal at power-up, which speeds oscillator start-up.
Besides loading the crystal for proper frequency response, these capacitors can have the effect
of lowering loop gain if their value is increased. C2 can be selected to affect the overall gain of
the circuit. A higher C2 can lower the gain if the crystal is being over driven (also, see discussion
on Rs). Capacitance values that are too high can store and dump too much current through the
crystal, so C1 and C2 should not become excessively large. Unfortunately, measuring the
wattage through a crystal is difficult, but if you do not stray too far from the suggested values you
should not have to be concerned with this.
A series resistor, Rs, is added to the circuit if, after all other external components are selected to
satisfaction, the crystal is still being overdriven. This can be determined by looking at the OSC2
pin, which is the driven pin, with an oscilloscope. Connecting the probe to the OSC1 pin will load
the pin too much and negatively affect performance. Remember that a scope probe adds its own
capacitance to the circuit, so this may have to be accounted for in your design (i.e., if the circuit
worked best with a C2 of 22 pF and scope probe was 10 pF, a 33 pF capacitor may actually be
called for). The output signal should not be clipping or flattened. Overdriving the crystal can also
lead to the circuit jumping to a higher harmonic level or even crystal damage.
The OSC2 signal should be a clean sine wave that easily spans the input minimum and maximum
of the clock input pin (4V to 5V peak-to-peak for a 5V VDD is usually good). An easy way to set
this is to again test the circuit at the minimum temperature and maximum VDD that the design will
be expected to perform in, then look at the output. This should be the maximum amplitude of the
clock output. If there is clipping or the sine wave is distorted near VDD and VSS, increasing load
capacitors may cause too much current to flow through the crystal or push the value too far from
the manufacturer’s load specification. To adjust the crystal current, add a trimmer potentiometer
between the crystal inverter output pin and C2 and adjust it until the sine wave is clean. The
crystal will experience the highest drive currents at the low temperature and high VDD extremes.
The trimmer potentiometer should be adjusted at these limits to prevent overdriving. A series
resistor, Rs, of the closest standard value can now be inserted in place of the trimpot. If Rs is too
high, perhaps more than 20 kOhms, the input will be too isolated from the output, making the
clock more susceptible to noise. If you find a value this high is needed to prevent overdriving the
7
crystal, try increasing C2 to compensate or changing the Oscillator Operating mode. Try to get a
combination where Rs is around 10k or less and load capacitance is not too far from the
Oscillator
manufacturer specification.
7.8 External Clock Input
Two of the Primary Oscillator modes use an external clock. These modes are EC and ECIO.
In the EC mode (Figure 7-5), the OSC1 pin can be driven by CMOS drivers. In this mode, the
OSC1 pin is high-impedance and the OSC2 pin is the clock output (FOSC/4). This output clock is
useful for testing or synchronization purposes.
In the ECIO mode (Figure 7-6), the OSC1 pin can be driven by CMOS drivers. In this mode, the
OSC1 pin is high-impedance and the OSC2 pin becomes a general purpose I/O pin. The feed-
back device between OSC1 and OSC2 is turned off to save current.
V DD
REXT
Internal
OSC1
Clock
CEXT dsPIC30F
VSS OSC2
FOSC/4
Although the oscillator will operate with no external capacitor (CEXT = 0 pF), a value above 20 pF
should be used for noise and stability reasons. With no or a small external capacitance, the
oscillation frequency can vary dramatically due to changes in external capacitances, such as
PCB trace capacitance and package lead frame capacitance.
The oscillator frequency, divided by 4, is available on the OSC2/CLKO pin, and can be used for
test purposes or to synchronize other logic.
Note: An external clock source should not be connected to the OSC1 pin when the
oscillator is configured for ERC or ERCIO modes.
VDD
7
REXT
OSC1 Internal
Clock
Oscillator
CEXT
dsPIC30F
VSS
I/O (OSC2)
Note: The user should verify that VDD is within specifications before the device begins to
execute code.
Note: The following graphs should be used only as approximate guidelines for RC
component selection. The actual frequency will vary based on the system
temperature and device. Please refer to the specific device data sheet for further
RC oscillator characteristic data.
5.0
4.0
3.5
REXT = 10k
3.0
Freq (MHz)
2.5
2.0
1.5
1.0
REXT = 100k
0.5
0.0
2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
Figure 7-10: Typical External RC Oscillator Frequency vs. VDD, CEXT = 100 pF
5.0
4.0
REXT = 5.1k
3.0
Freq (MHz)
REXT = 10k
2.0
1.0
REXT = 100k
0.0
2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
Figure 7-11: Typical External RC Oscillator Frequency vs. VDD, CEXT = 300 pF
300
250
REXT = 3.3k
200
REXT = 5.1k
7
Freq (kHz)
150
Oscillator
REXT = 10k
100
50
REXT = 100k
0
2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
Note: Some PLL output frequency ranges can be achieved that exceed the maximum
operating frequency of the dsPIC30F device. Refer to the “Electrical Specifications”
in the specific device data sheet for further details.
When the PLL is selected as a destination clock source in a clock switch operation (including a
Power-on Reset), the LOCK bit is cleared. The LOCK bit is set after phase lock has been
achieved. If the PLL fails to achieve lock, then the clock switching circuit will NOT switch to the
PLL output for system clock; instead, it will continue to run with the old clock source.
If the PLL fails to achieve lock at a Power-on Reset (POR) and the Fail-Safe Clock Monitor
(FSCM) is enabled, the FRC oscillator will become the device clock source and a clock failure
trap will occur.
If the PLL loses lock during normal operation for at least 4 input clock cycles, then the LOCK bit
is cleared, indicating a loss of PLL lock. Furthermore, a clock failure trap will be generated. In this
situation, the processor continues to run using the PLL clock source. The user can switch to
another clock source in the Trap Service Routine, if desired.
Note: Refer to Section 6. “Reset Interrupts” for further details about oscillator failure
traps.
Note: A loss of PLL lock during normal device operation will generate a clock failure trap,
but the system clock source will not be changed. The FSCM does not need to be
enabled to detect the loss of lock.
Oscillator
The LP oscillator will always be enabled if the LPOSCEN control bit (OSCCON<1>) is set. There
are two reasons to leave the LP oscillator running. First, keeping the LP oscillator ON at all times
allows a fast switch to the 32 kHz system clock for lower power operation. Returning to the faster
main oscillator will still require an oscillator start-up time if it is a crystal type source (see
Section 7.12 “Oscillator Start-up Timer (OST)”). Second, the oscillator should remain ON at
all times when using Timer1 as a real-time clock.
When the LPOSCEN control bit (OSCCON<1>) is cleared, the LP oscillator will only operate
when it is selected as the current device clock source (COSC<1:0> = 00). The LP oscillator will
be disabled if it is the current device clock source and the device enters Sleep mode.
Note: For more information about the oscillator failure trap, please refer to
Section 6. “Reset Interrupts”.
Note: Please refer to the “Electrical Specifications” section of the device data sheet for
TFSCM specification values.
Oscillator
control bits (OSCCON<7:6>).
To ensure a clean clock transition, there is some delay before a clock change occurs. The clock
postscaler does not change the clock selection multiplexer until a falling edge on the divide-by-64
output occurs. In effect, the switching delay could be up to 64 system clock cycles depending on
when the POST<1:0> control bits are written. Figure 7-13 shows the postscaler operation for
three different postscaler changes.
System
Clock Input 00
(from Clock Switch
div. by 4 01
and Control Logic) Postscaled
Counter div. by 16 10 System Clock
div. by 64 11
POST1
POST0
System
Clock
Divide
by 4
Divide
by 16
Divide
by 64
POST<1:0> 01 10 00 11
Postscaled
System
Clock
1:4 1:16 1:1 1:64
Note: This diagram demonstrates the clock postscaler function only. The divide ratios shown in the timing diagram
are not correct.
Note: The Primary oscillator has multiple operating modes (EC, RC, XT, FRC etc.). The
Operating mode of the Primary oscillator is determined by the FPR Configuration
bits in the FOSC device Configuration register. (Refer to 7.3 “Oscillator Configura-
tion” for further details.)
Oscillator
of the NOSC<1:0> control bits. If they are the same, then the clock switch is a redundant
operation. In this case, the OSWEN bit is cleared automatically and the clock switch is
aborted.
7. If a valid clock switch has been initiated, the LOCK (OSCCON<5>) and the CF
(OSCCON<3>) Status bits are cleared.
8. The new oscillator is turned on by the hardware if it is not currently running. If a crystal
oscillator must be turned on, the hardware will wait until the OST expires. If the new
source is using the PLL, then the hardware waits until a PLL lock is detected (LOCK = 1).
9. The hardware waits for 10 clock cycles from the new clock source and then performs the
clock switch.
10. The hardware clears the OSWEN bit to indicate a successful clock transition. In addition,
the NOSC<1:0> bit values are transferred to the COSC<1:0> Status bits.
11. The clock switch is completed. The old clock source will be turned off at this time, with the
following exceptions:
• The LPRC oscillator will stay on if the WDT or FSCM is enabled.
• The LP oscillator will stay on if LPOSCEN = 1 (OSCCON<1>).
Note: The processor will continue to execute code throughout the clock switching
sequence. Timing sensitive code should not be executed during this time.
System Clock
OSWEN
Note: The system clock can be any selected source – Primary, Secondary, FRC or LPRC.
The following code sequence shows how to unlock the OSCCON register and begin a clock
switch operation:
;Place the new oscillator selection in W0
;OSCCONH (high byte) Unlock Sequence
MOV #OSCCONH, w1
MOV #0x78, w2
MOV #0x9A, w3
MOV.B w2, [w1]
MOV.B w3, [w1] 7
;Set new oscillator selection
MOV.B WREG, OSCCONH
Oscillator
;OSCCONL (low byte) unlock sequence
MOV #OSCCONL, w1
MOV.B #0x01, w0
MOV #0x46, w2
MOV #0x57, w3
MOV.B w2, [w1]
MOV.B w3, [w1]
The following code sequence would be used to ABORT an unsuccessful clock switch:
MOV OSCCON,W0 ; Read OSCCON into W0
BCLR W0, #OSWEN ; Clear bit 0 in W0
MOV #OSCCON,W1 ; pointer to OSCCON
MOV.B #0x46,W2 ; first unlock code
MOV.B #0x57,W3 ; second unlock code
MOV.B W2, [W1] ; write first unlock code
MOV.B W3, [W1] ; write second unlock code
MOV.B W0, [W1] ; ABORT the switch
Question 1: When looking at the OSC2 pin after power-up with an oscilloscope, there is
no clock. What can cause this?
Answer:
1. Entering Sleep mode with no source for wake-up (such as, WDT, MCLR, or an interrupt).
Verify that the code does not put the device to Sleep without providing for wake-up. If it is
possible, try waking it up with a low pulse on MCLR. Powering up with MCLR held low will
also give the crystal oscillator more time to start-up, but the Program Counter will not
advance until the MCLR pin is high.
2. The wrong Clock mode is selected for the desired frequency. For a blank device, the
default oscillator is EC + 16x PLL. Most parts come with the clock selected in the Default
mode, which will not start oscillation with a crystal or resonator. Verify that the Clock mode
has been programmed correctly.
3. The proper power-up sequence has not been followed. If a CMOS part is powered through
an I/O pin prior to power-up, bad things can happen (latch-up, improper start-up, etc.). It
is also possible for brown-out conditions, noisy power lines at start-up, and slow VDD rise
times to cause problems. Try powering up the device with nothing connected to the I/O,
and power-up with a known, good, fast rise, power supply. Refer to the power-up
information in the device data sheet for considerations on brown-out and power-up
sequences.
4. The C1 and C2 capacitors attached to the crystal have not been connected properly or
are not the correct values. Make sure all connections are correct. The device data sheet
values for these components will usually get the oscillator running; however, they just
might not be the optimal values for your design.
Question 2: The device starts, but runs at a frequency much higher than the resonant
frequency of the crystal.
Answer: The gain is too high for this oscillator circuit. Refer to Section 7.6 “Crystal Oscilla-
tors/Ceramic Resonators” to aid in the selection of C2 (may need to be higher), Rs (may be
needed) and Clock mode (wrong mode may be selected). This is especially possible for low
frequency crystals, like the common 32.768 kHz.
Question 3: The design runs fine, but the frequency is slightly off. What can be done to
adjust this?
Answer: Changing the value of C1 has some effect on the oscillator frequency. If a SERIES
resonant crystal is used, it will resonate at a different frequency than a PARALLEL resonant
crystal of the same frequency call-out. Ensure that you are using a PARALLEL resonant crystal.
Question 4: The board works fine, then suddenly quits or loses time.
Answer: Other than the obvious software checks that should be done to investigate losing time,
it is possible that the amplitude of the oscillator output is not high enough to reliably trigger the
oscillator input. Look at the C1 and C2 values and ensure that the device Configuration bits are
correct for the desired oscillator mode.
Question 5: If I put an oscilloscope probe on an oscillator pin, I don’t see what I expect.
Why?
Answer: Remember that an oscilloscope probe has capacitance. Connecting the probe to the
oscillator circuitry will modify the oscillator characteristics. Consider using a low capacitance
(active) probe.
Oscillator
HIGHLIGHTS
This section of the manual contains the following topics:
Reset
8.14 Revision History ........................................................................................................... 8-19
8.1 Introduction
The Reset module combines all Reset sources and controls the device Master Reset Signal,
SYSRST. The following is a list of device Reset sources:
• POR: Power-on Reset
• EXTR: Pin Reset (MCLR)
• SWR: RESET Instruction
• WDTR: Watchdog Timer Reset
• BOR: Brown-out Reset
• TRAPR: Trap Conflict Reset
• IOPR: Illegal Opcode Reset
• UWR: Uninitialized W Register Reset
A simplified block diagram of the Reset module is shown in Figure 8-1. Any active source of
Reset will make the SYSRST signal active. Many registers associated with the CPU and periph-
erals are forced to a known “Reset state”. Most registers are unaffected by a Reset; their status
is unknown on POR and unchanged by all other Resets.
Note: Refer to the specific peripheral or CPU section of this manual for register Reset
states.
All types of device Reset will set a corresponding status bit in the RCON register to indicate the
type of Reset (see Register 8-1). A POR will clear all bits except for the POR and BOR bits
(RCON<2:1>), which are set. The user may set or clear any bit at any time during code execution.
The RCON bits only serve as status bits. Setting a particular Reset status bit in software will not
cause a device Reset to occur.
The RCON register also has other bits associated with the Low Voltage Detect module,
Watchdog Timer, and device power saving states. The function of these bits is discussed in other
sections of this manual.
RESET
Instruction
Glitch Filter
MCLR
Sleep or Idle
WDT
Module
Trap Conflict
Illegal Opcode
Uninitialized W Register
Lower Byte:
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-1 R/W-1
EXTR SWR SWDTEN WDTO SLEEP IDLE BOR POR
bit 7 bit 0
Reset
bit 7 EXTR: External Reset (MCLR) Pin bit
1 = A Master Clear (pin) Reset has occurred
0 = A Master Clear (pin) Reset has not occurred
bit 6 SWR: Software RESET (Instruction) Flag bit
1 = A RESET instruction has been executed
0 = A RESET instruction has not been executed
bit 5 SWDTEN: Software Enable/Disable of WDT bit
1 = WDT is turned on
0 = WDT is turned off
Note: If FWDTEN fuse bit is ‘1’ (unprogrammed), the WDT is ALWAYS ENABLED, regardless of the
SWDTEN bit setting.
bit 4 WDTO: Watchdog Timer Time-out Flag bit
1 = WDT Time-out has occurred
0 = WDT Time-out has not occurred
bit 3 SLEEP: Wake From Sleep Flag bit
1 = Device has been in Sleep mode
0 = Device has not been in Sleep mode
bit 2 IDLE: Wake-up From Idle Flag bit
1 = Device was in Idle mode
0 = Device was not in Idle mode
Note: All of the Reset status bits may be set or cleared in software. Setting one of these bits in software
does not cause a device Reset.
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Table 8-1: Oscillator Selection vs. Type of Reset (Clock Switching Enabled)
Reset Type Clock Source Selected Based On
POR Oscillator Configuration Fuses
BOR Oscillator Configuration Fuses
EXTR COSC Control bits (OSCCON<13:12>)
WDTR COSC Control bits (OSCCON<13:12>)
SWR COSC Control bits (OSCCON<13:12>)
Reset
After the Power-on Reset pulse is generated, the POR circuit inserts a small delay, TPOR, which
is nominally 10 μs and ensures that internal device bias circuits are stable. Furthermore, a user
selected Power-up Time-out (TPWRT) may be applied. The TPWRT parameter is based on device
configuration bits and can be 0 ms (no delay), 4 ms, 16 ms or 64 ms. The total delay time at
device power-up is TPOR + TPWRT. When these delays have expired, SYSRST will be released
on the next leading edge of the instruction cycle clock, and the PC will jump to the Reset vector.
The timing for the SYSRST signal is shown in Figure 8-2. A Power-on Reset is initialized when
VDD falls below a threshold voltage, VT. The POR delay time is inserted when VDD crosses the
POR circuit threshold voltage. Finally, the PWRT delay time, TPWRT, is inserted before SYSRST
is released.
The power-on event will set the POR and BOR status bits (RCON<1:0>).
VPOR
Time
TPOR
POR Circuit
Time
System Reset is released
after Power-up Timer
expires.
TPWRT
(0 ms, 4 ms, 16 ms or 64 ms)
SYSRST
Time
Note: When the device exits the Reset condition (begins normal operation), the device
operating parameters (voltage, frequency, temperature, etc.) must be within their
operating ranges, otherwise the device will not function correctly. The user must
ensure that the delay between the time power is first applied and the time SYSRST
becomes inactive is long enough to get all operating parameters within
specification.
VDD VDD
D R
R1
MCLR
C dsPIC30F
8
Note 1: The value of R should be low enough so that the voltage drop across it does not violate
the VIH specification of the MCLR pin.
2: R1 will limit any current flowing into MCLR from external capacitor C in the event of
MCLR/VPP pin breakdown, due to Electrostatic Discharge (ESD) or Electrical Overstress
Reset
(EOS).
Note: The BOR voltage trip points indicated here are nominal values provided for design
guidance only. Refer to the “Electrical Specifications” in the specific device data
sheet for BOR voltage limit specifications.
On a BOR, the device will select the system clock source based on the device configuration bit
values (FPR<3:0>, FOS<1:0>). The PWRT time-out (TPWRT), if enabled, will be applied before
SYSRST is released.
If a crystal oscillator source is selected, the Brown-out Reset will invoke the Oscillator Start-up
Timer (OST). The system clock is held until OST expires. If a system clock source is derived from
the PLL, then the clock will be held until the LOCK bit (OSCCON<5>) is set.
The BOR status bit (RCON<1>) will be set to indicate that a BOR has occurred.
The BOR circuit, if enabled, will continue to operate while in Sleep or Idle modes and will reset
the device should VDD fall below the BOR threshold voltage.
Refer to the “Electrical Specifications” section of the appropriate device data sheet for the BOR
electrical specifications.
Typical brown-out scenarios are shown in Figure 8-4. As shown, a PWRT delay (if enabled) will
be initiated each time VDD rises above the VBOR trip point.
VDD
VBOR
TPWRT
SYSRST
VDD
VBOR
TPWRT
SYSRST
VDD
VBOR
TPWRT
SYSRST
Reset
uninitialized until written to. An attempt to use an uninitialized register as an address pointer will
reset the device. Furthermore, the IOPUWR status bit (RCON<14>) will be set.
Note: The status bits in the RCON register should be cleared after they are read so that
the next RCON register value after a device Reset will be meaningful.
Table 8-2 provides a summary of the Reset flag bit operation.
Reset
Software Any clock — — —
Illegal Opcode Any Clock — — —
Uninitialized W Any Clock — — —
Trap Conflict Any Clock — — —
Note 1: TPOR = Power-on Reset delay (10 μs nominal).
2: TPWRT = Additional “power-up” delay as determined by the FPWRT<1:0>
configuration bits. This delay is 0 ms, 4 ms, 16 ms or 64 ms nominal.
3: TOST = Oscillator Start-up Timer. A 10-bit counter counts 1024 oscillator periods
before releasing the oscillator clock to the system.
4: TLOCK = PLL lock time (20 μs nominal).
5: TFSCM = Fail-Safe Clock Monitor delay (100 μs nominal).
When the system clock source is provided by a crystal oscillator and/or the PLL, a small delay,
TFSCM, will automatically be inserted after the POR and PWRT delay times. The FSCM will not
begin to monitor the system clock source until this delay expires. The FSCM delay time is
nominally 100 μs and provides additional time for the oscillator and/or PLL to stabilize. In most
cases, the FSCM delay will prevent an oscillator failure trap at a device Reset when the PWRT
is disabled.
Figure 8-5: Device Reset Delay, Crystal + PLL Clock Source, PWRT Disabled
Reset
SYSRST
Oscillator
OSC Delay
System OSC
FSCM enabled.
TFSCM
FSCM
The Reset time line shown in Figure 8-6 is similar to that shown in Figure 8-5, except that the
PWRT has been enabled to increase the amount of delay time before SYSRST is released.
The FSCM, if enabled, will begin to monitor the system clock after TFSCM expires. Note that the
additional PWRT delay time added to TFSCM provides ample time for the system clock source to
stabilize in most cases.
Figure 8-6: Device Reset Delay, Crystal + PLL Clock Source, PWRT Enabled
TPOR TPWRT
SYSRST
TFSCM
FSCM
TFSCM short
compared to
TPWRT.
The Reset time line in Figure 8-7 shows an example when an EC + PLL clock source is used as
the system clock and the PWRT is enabled. This example is similar to the one shown in
Figure 8-6, except that the oscillator start-up timer delay, TOST, does not occur.
TPOR TPWRT
SYSRST
TFSCM
FSCM
8
TFSCM short
compared to
TPWRT.
Reset
Note 1: Delay times shown are not drawn to scale.
2: FSCM, if enabled, monitors system clock at expiration of TPOR + TPWRT + TFSCM.
3: TLOCK not inserted when PLL is is disabled.
The Reset time line shown in Figure 8-8 shows an example where an EC without PLL, or RC
system clock source is selected and the PWRT is disabled. Note that this configuration provides
minimal Reset delays. The POR delay is the only delay time that occurs before device operation
begins. No FSCM delay will occur if the FSCM is enabled, because the system clock source is
not derived from a crystal oscillator or the PLL.
SYSRST
OSC Delay
FSCM
Question 3: The BOR module does not have the programmable trip points that my
application needs. How can I work around this?
Answer: There are some applications where the device’s programmable BOR trip point levels
may still not be at the desired level for the application. Figure 8-9 shows a possible circuit for
external brown-out protection, using the MCP100 system supervisor.
VDD
VDD
8
MCP100
VSS RST
MCLR
Reset
dsPIC30F
Question 4: I initialized a W register with a 16-bit address, but the device appears to
reset when I attempt to use the register as an address.
Answer: Because all data addresses are 16 bit values, the uninitialized W register logic only
recognizes that a register has been initialized correctly if it was subjected to a word load. Two
byte moves to a W register, even if successive, will not work, resulting in a device Reset if the W
register is used as an address pointer in an operation.
Note: Please visit the Microchip web site (www.microchip.com) for additional Application
Notes and code examples for the dsPIC30F Family of devices.
Reset
NOTES:
HIGHLIGHTS
This section of the manual contains the following topics:
Detect (LVD)
Low Voltage
9.1 Introduction
The LVD module is applicable to battery operated applications. As the battery drains its energy,
the battery voltage slowly drops. The battery source impedance also increases as it loses energy.
The LVD module is used to detect when the battery voltage (and therefore, the VDD of the device)
drops below a threshold, which is considered near the end of battery life for the application. This
allows the application to gracefully shutdown its operation.
The LVD module uses an internal reference voltage for comparison. The threshold voltage, VLVD,
is programmable during run-time.
Figure 9-1 shows a possible application battery voltage curve. Over time, the device voltage
decreases. When the device voltage equals voltage VLVD, the LVD logic generates an interrupt.
This occurs at time TA. The application software then has until the device voltage is no longer in
valid operating range to shutdown the system. Voltage point VB is the minimum valid operating
voltage specification. This gives a time TB. The total time for shutdown is TB – TA.
VLVD
VMIN
Voltage
Time TA TB
Legend:
VLVD = LVD trip point
VMIN = Minimum valid device operating voltage
Figure 9-2 shows the block diagram for the LVD module. A comparator uses an internally
generated reference voltage as the set point. When the selected tap output of the device voltage
is lower than the reference voltage, the LVDIF bit (IFS2<10>) is set.
Each node in the resistor divider represents a “trip point” voltage. This voltage is software
programmable to any one of 16 values.
16 to 1 MUX
LVDIF
Detect (LVD)
Low Voltage
9.1.1.1 LVD Trip Point Selection
The LVDL<3:0> bits (RCON<11:8>) will choose the LVD trip point. There are 15 trip point options
that may be selected from the internal voltage divider connected to VDD. If none of the trip point
options are suitable for the application, there is one option that allows the LVD sample voltage to
be applied externally on the LVDIN pin. (Refer to the specific device data sheet for the pin
location.) The nominal trip point voltage for the external LVD input is 1.24 volts. The LVD external
input option requires that the user select values for an external voltage divider circuit that will
generate a LVD interrupt at the desired VDD.
Lower Byte:
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-1 R/W-1
EXTR SWR SWDTEN WDTO SLEEP IDLE BOR POR
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Note: See Section 8. “Reset” for a description of other bits in the RCON register.
Note: The system design should ensure that the application software is given adequate
time to save values before the device exits the valid operating range, or is forced
into a Brown-out Reset.
Depending on the power source for the device, the supply voltage may decrease relatively
slowly. This means that the LVD module does not need to be constantly operating. To decrease
the current requirements, the LVD circuitry only needs to be enabled for short periods where the
voltage is checked. After doing the check, the LVD module may be disabled.
Once the VDD has fallen below the programmed LVD threshold, the LVDIF bit will remain set.
When the LVD module has interrupted the CPU, one of two actions may be taken in the ISR:
1. Clear the LVDIE control bit to disable further LVD module interrupts and take the
appropriate shutdown procedures.
or
2. Decrease the LVD voltage threshold using the LVDL control bits and clear the LDVIF 9
status bit. This technique can be used to track a gradually decreasing battery voltage.
Detect (LVD)
Low Voltage
9.2.2 Current Consumption for LVD Operation
The LVD circuit relies on an internal voltage reference circuit that is shared with other peripheral
devices, such as the Brown-out Reset (BOR) module. The internal voltage reference will be
active whenever one of its associated peripherals is enabled. For this reason, the user may not
observe the expected change in current consumption when the LVD module is disabled.
Question 3: Should I enable the BOR circuit for a battery powered application?
Answer: The BOR circuit is intended to protect the device from improper operation due to power
supply fluctuations caused by the AC line voltage. The BOR is typically not required for battery
applications and can be disabled for lower current consumption.
Note: Please visit the Microchip web site (www.microchip.com) for additional Application
Notes and code examples for the dsPIC30F Family of devices.
Detect (LVD)
Low Voltage
HIGHLIGHTS
This section of the manual contains the following topics:
10
WDT and Power
Saving Modes
10.1 Introduction
This section addresses the Watchdog Timer (WDT) and Power Saving modes of the dsPIC30F
device family. The dsPIC DSC devices have two reduced Power modes that can be entered
through execution of the PWRSAV instruction:
• Sleep Mode: The CPU, system clock source, and any peripherals that operate on the
system clock source are disabled. This is the lowest Power mode for the device.
• Idle Mode: The CPU is disabled, but the system clock source continues to operate.
Peripherals continue to operate, but can optionally be disabled.
The WDT, when enabled, operates from the internal LPRC clock source and can be used to
detect system software malfunctions by resetting the device if the WDT has not been cleared in
software. Various WDT time-out periods can be selected using the WDT postscaler. The WDT
can also be used to wake the device from Sleep or Idle mode.
Note: SLEEP_MODE and IDLE_MODE are constants defined in the assembler include
file for the selected device.
The Power Saving modes can be exited as a result of an enabled interrupt, WDT time-out, or a
device Reset. When the device exits one of these two Operating modes, it is said to ‘wake-up’.
The characteristics of the Power Saving modes are described in subsequent sections.
The processor will exit, or ‘wake-up’, from Sleep on one of the following events:
• On any interrupt source that is individually enabled
• On any form of device Reset
• On a WDT time-out
Note: Please refer to the “Electrical Specifications” section of the dsPIC30F device data
sheet for TPOR, TFSCM and TLOCK specification values.
The processor will wake from Idle mode on the following events:
• On any interrupt that is individually enabled.
• On any source of device Reset.
• On a WDT time-out.
Upon wake-up from Idle, the clock is re-applied to the CPU and instruction execution begins
immediately starting with the instruction following the PWRSAV instruction, or the first instruction
in the ISR.
10
WDT and Power
Saving Modes
SWDTEN
Enable WDT FWDTEN
LPRC 2
FWPSA1
Control FWPSA0
CLRWDT Instr.
PWRSAV Instr.
If the FWDTEN device configuration bit is set, then the WDT is always enabled. However, the
WDT can be optionally controlled in the user software when the FWDTEN configuration bit has
been programmed to ‘0’.
The WDT is enabled in software by setting the SWDTEN control bit (RCON<5>). The SWDTEN
control bit is cleared on any device Reset. The software WDT option allows the user to enable
the WDT for critical code segments and disable the WDT during non-critical segments for
maximum power savings.
The WDT has two clock prescalers, Prescaler A and Prescaler B, to allow a wide variety of
time-out periods. Prescaler A can be configured for 1:1, 1:8, 1:64 or 1:512 divide ratios. Prescaler
B can be configured for any divide ratio from 1:1 through 1:16. Time-out periods that range
between 2 ms and 16 seconds (nominal) can be achieved using the prescalers.
The prescaler settings are selected using the FWPSA<1:0> (Prescaler A) and FWPSB<3:0>
(Prescaler B) configuration bits in the FWDT Device Configuration register. The FWPSA<1:0>
and FWPSB<3:0> values are written during device programming. For more information on the
WDT prescaler configuration bits, please refer to Section 24. “Device Configuration”.
The time-out period of the WDT is calculated as follows:
Equation 10-1: WDT Time-out Period
Note: The WDT time-out period is directly related to the frequency of the LPRC oscillator.
The frequency of the LPRC oscillator will vary as a function of device operating
voltage and temperature. Please refer to the specific dsPIC30F device data sheet
for LPRC clock frequency specifications.
10
WDT and Power
Saving Modes
Table 10-2: WDT Time-out Period vs. Prescale A and Prescale B Settings
Note: If a PMD bit is set, the corresponding module is disabled after a delay of 1 instruction
cycle. Similarly, if a PMD bit is cleared, the corresponding module is enabled after a
delay of 1 instruction cycle (assuming the module control registers are already
configured to enable module operation).
Please check individual device data sheet for specific operational details of the PMD register.
10
WDT and Power
Saving Modes
Question 1: The device resets even though I have inserted a CLRWDT instruction in my
main software loop.
Answer: Make sure that the software loop that contains the CLRWDT instruction meets the
minimum specification of the WDT (not the typical value). Also, make sure that interrupt
processing time has been accounted for.
Question 3: How do I tell which peripheral woke the device from Sleep or Idle mode?
Answer: You can poll the IF bits for each enabled interrupt source to determine the source of
wake-up.
Note: Please visit the Microchip web site (www.microchip.com) for additional Application
Notes and code examples for the dsPIC30F Family of devices.
10
WDT and Power
Saving Modes
NOTES:
10
WDT and Power
Saving Modes
I/O Ports
Section 11. I/O Ports
HIGHLIGHTS
This section of the manual contains the following topics:
I/O Ports
device pins (except VDD, VSS, MCLR, and OSC1/CLKI) are shared between the peripherals and
the general purpose I/O ports.
The general purpose I/O ports allow the dsPIC30F to monitor and control other devices. Most I/O
pins are multiplexed with alternate function(s). The multiplexing will depend on the peripheral
features on the device variant. In general, when a peripheral is functioning, that pin may not be
used as a general purpose I/O pin.
Figure 11-1 shows a block diagram of a typical I/O port. This block diagram does not take into
account peripheral functions that may be multiplexed onto the I/O pin.
Data Bus D Q
WR TRIS CK
TRIS Latch
D Q I/O pin
WR LAT
WR PORT CK
Data Latch
Read LAT
Read Port
Note: The total number of ports and available I/O pins will depend on the device variant.
In a given device, all of the bits in a port control register may not be implemented.
Refer to the specific device data sheet for further details.
I/O Ports
while a few are user settable. The I/O pin may be read through the input data path, but the output
driver for the I/O port bit is generally disabled.
An I/O port that shares a pin with another peripheral is always subservient to the peripheral. The
peripheral’s output buffer data and control signals are provided to a pair of multiplexers. The
multiplexers select whether the peripheral, or the associated port, has ownership of the output
data and control signals of the I/O pin. Figure 11-2 shows how ports are shared with other
peripherals, and the associated I/O pin to which they are connected.
Note: In order to use PORTB pins for digital I/O, the corresponding bits in the ADPCFG
register must be set to ‘1’, even if the A/D module is turned off.
PIO Module
Peripheral Multiplexers
Read TRIS
Peripheral A Enable
Peripheral B Enable
Data Bus D Q 0
0
WR TRIS CK Peripheral B o.e. 1
TRIS Latch Peripheral A o.e. 1
I/O pin
D Q 0
WR LAT 0
WR Port CK Peripheral B Data 1
Data Latch Peripheral A Data 1
Read LAT
PERA/PERB/PIO
Read Port
Peripheral A Input R
Peripheral B Input R
Some of the functions assigned to an I/O pin may be input functions that do not take control of
the pin output driver. An example of one such peripheral is the Input Capture module. If the I/O
pin associated with the Input Capture is configured as an output, using the appropriate
TRIS control bit, the user can manually affect the state of the Input Capture pin through its
corresponding PORT register. This behavior can be useful in some situations, especially for
testing purposes, when no external signal is connected to the input pin.
Referring to Figure 11-2, the organization of the peripheral multiplexers will determine if the peripheral
input pin can be manipulated in software using the PORT register. The conceptual peripherals shown
in this figure disconnect the PORT data from the I/O pin when the peripheral function is enabled.
In general, the following peripherals allow their input pins to be controlled manually through the
PORT registers:
• External Interrupt pins
• Timer Clock Input pins
• Input Capture pins
• PWM Fault pins
Most serial communication peripherals, when enabled, take full control of the I/O pin, so that the
input pins associated with the peripheral cannot be affected through the corresponding PORT
registers. These peripherals include the following:
• SPITM
• I2CTM
• DCI
• UART
• CAN
When a peripheral is enabled the associated pin output drivers are typically module controlled
while a few are user settable. The term "Module Control" means that the associated port pin out-
put driver is disabled and the pin can only be controlled and accessed by the peripheral. The term
"User Settable" means that the associated peripheral port pin output driver is user configurable
via the associated TRISx SFR. The TRISx register must be set properly for the peripheral to func-
tion properly. For "User Settable" peripheral pins, the actual port pin state can always be read
via the PORTx SFR.
An Input Capture peripheral makes a good example of a User Settable peripheral. The user must
write the associated TRIS register to configure the Input Capture pin as an input. Since the I/O
pin circuitry is still active when the Input Capture is enabled, a 'trick' can be used to manually
produce capture events using software. The Input Capture pin is configured as an output using
the associated TRIS register. Then, the software can write values to the corresponding LAT reg-
ister drive to internally control the Input Capture pin and force capture events.
As another example an INTx pin can be configured as an output and then by writing to the asso-
ciated LATx bit an INTx interrupt, if enabled, can be generated.
The UART is an example of a Module Control peripheral. When the UART is enabled, the PORT
and TRIS registers have no effect and cannot be used to read or write the RX and TX pins. Most
communication peripheral functions available on the dsPIC are Module Control peripherals.
For example, the SPI module can be configured for Master mode in which only the SDO pin is
required. In this scenario the SDI pin can be configured as a general purpose output pin by clear-
ing (setting to a logic "0") the associated TRISx bit. Table 11-1 presents a summary of the dsPIC
peripherals and associated Pin Output Control and Port pin read status.
I/O Ports
Peripheral Pins TRISx - Pin Output Control
“Enabled State” Pin Read
SPI™ SDOx <DISSDO = 1>, User Settable Yes
(x = 1 or 2) <DISSDO = 0>, Module Control
SDIx User Settable Yes
SCKx Module Control Yes
SSx <SSEN = 0>, User Settable Yes
<SSEN = 1>, Module Control
UART UxRX Module Control Yes
(x = 1 or 2) UxTX <UTXEN = 0>, User Settable Yes
<UTXEN = 1>, Module Control
I2C™ SCL Module Control Yes
SDA Module Control Yes
Input Change Notice CN0 - CN23 User Settable Yes
Input Capture IC1 - IC8 User Settable Yes
Output Compare OC1 - OC8 Module Control Yes
Data Converter COFS Module Control Yes
Interface CSCK Module Control Yes
CSDI Module Control Yes
CSDO Module Control Yes
Motor Control PWM PWMx Module Control Yes
FLTA/B User Settable Yes
QEI QEA Module Control (QEI mode) Yes
User Settable (16-bit Timer mode)
QEB Module Control (QEI mode) Yes
User Settable (16-bit Timer mode)
INDX Module Control (QEIM<2:0> = 100 or Yes
110)
User Settable in all other modes
CAN CxRX Module Control Yes
(x = 1 or 2) CxTX Module Control Yes
INTx INT0 - INT5 User Settable Yes
CN0PUE
(CNPU1<0>)
CN0
D Q
pin
CN0 Change
C
CN
Interrupt
D Q
CN0IE (CNEN1<0>)
CN1 Change
CN1-CN23
Details Not
Shown CN23 Change
I/O Ports
1. Ensure that the CN pin is configured as a digital input by setting the associated bit in the
TRISx register.
2. Enable interrupts for the selected CN pins by setting the appropriate bits in the CNEN1
and CNEN2 registers.
3. Turn on the weak pull-up devices (if desired) for the selected CN pins by setting the
appropriate bits in the CNPU1 and CNPU2 registers.
4. Clear the CNIF (IFS0<15>) interrupt flag.
5. Select the desired interrupt priority for CN interrupts using the CNIP<2:0> control bits
(IPC3<14:12>).
6. Enable CN interrupts using the CNIE (IEC0<15>) control bit.
When a CN interrupt occurs, the user should read the PORT register associated with the CN
pin(s). This will clear the mismatch condition and setup the CN logic to detect the next pin
change. The current PORT value can be compared to the PORT read value obtained at the last
CN interrupt to determine the pin that changed.
The CN pins have a minimum input pulse width specification. Refer to the “Electrical
Specifications” section of the device data sheet for further details.
Lower Byte:
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
CN7IE CN6IE CN5IE CN4IE CN3IE CN2IE CN1IE CN0IE
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
CN23IE CN22IE CN21IE CN20IE CN19IE CN18IE CN17IE CN16IE
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
I/O Ports
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
CN15PUE CN14PUE CN13PUE CN12PUE CN11PUE CN10PUE CN9PUE CN8PUE
bit 15 bit 8
Lower Byte:
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
CN7PUE CN6PUE CN5PUE CN4PUE CN3PUE CN2PUE CN1PUE CN0PUE
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
CN23PUE CN22PUE CN21PUE CN20PUE CN19PUE CN18PUE CN17PUE CN16PUE
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Note: Please visit the Microchip web site (www.microchip.com) for additional Application
Notes and code examples for the dsPIC30F Family of devices.
I/O Ports
This is the initial released revision of this document.
Revision B
This revision incorporates additional technical content for the dsPIC30F I/O Ports module.
Revision C
There were no technical content revisions to this section of the manual, however, this section was
updated to reflect Revision C throughout the manual.
Revision D
Section 11.3.1.2 “Pin Control Summary” was added to this revision.
HIGHLIGHTS
This section of the manual contains the following major topics:
12
12.1 Introduction .................................................................................................................. 12-2
12.2 Timer Variants .............................................................................................................. 12-3
Timers
12.3 Control Registers ......................................................................................................... 12-6
12.4 Modes of Operation ..................................................................................................... 12-9
12.5 Timer Prescalers ........................................................................................................ 12-14
12.6 Timer Interrupts.......................................................................................................... 12-14
12.7 Reading and Writing 16-bit Timer Module Registers ................................................. 12-15
12.8 Low Power 32 kHz Crystal Oscillator Input ................................................................ 12-15
12.9 32-bit Timer Configuration.......................................................................................... 12-16
12.10 32-bit Timer Modes of Operation ............................................................................... 12-18
12.11 Reading and Writing into 32-bit Timers...................................................................... 12-21
12.12 Timer Operation in Power Saving States ................................................................... 12-21
12.13 Peripherals Using Timer Modules .............................................................................. 12-22
12.14 Design Tips ................................................................................................................ 12-24
12.15 Related Application Notes.......................................................................................... 12-25
12.16 Revision History ......................................................................................................... 12-26
12.1 Introduction
Depending on the specific variant, the dsPIC30F device family offers several 16-bit timers. These
timers are designated as Timer1, Timer2, Timer3, ..., etc.
Each timer module is a 16-bit timer/counter consisting of the following readable/writable
registers:
• TMRx: 16-bit timer count register
• PRx: 16-bit period register associated with the timer
• TxCON: 16-bit control register associated with the timer
Each timer module also has the associated bits for interrupt control:
• Interrupt Enable Control bit (TxIE) 12
• Interrupt Flag Status bit (TxIF)
• Interrupt Priority Control bits (TxIP<2:0>)
With certain exceptions, all of the 16-bit timers have the same functional circuitry. The 16-bit
Timers
timers are classified into three types to account for their functional differences:
• Type A time base
• Type B time base
• Type C time base
Some 16-bit timers can be combined to form a 32-bit timer.
This section does not describe the dedicated timers that are associated with peripheral devices.
For example, this includes the time bases associated with the Motor Control PWM module and
the Quadrature Encoder Interface (QEI) module.
Note: Please refer to the device data sheet for the available timers and the type of each.
PRx
Equal
Comparator x 16 TSYNC
1 Sync
TMRx
Reset
0
0
TxIF
Event Flag 1 Q D TGATE
Q CK
TGATE
TGATE
TCS
(Note 1) TCKPS<1:0>
SOSCO TON 2
1X
SOSCI
TCY 00
12
PRx
Equal
Comparator x 16
Timers
TMRx Sync
Reset
0
TxIF
Event Flag 1 Q D TGATE
Q CK
TGATE
TGATE
TCS
TCKPS<1:0>
TON 2
TxCKI 1X
Gate Prescaler
Sync 01 1, 8, 64, 256
TCY 00
PRx
TMRx
Reset
0
TxIF
Event Flag 1 Q D TGATE
Q CK
TGATE
TGATE
TCS TCKPS<1:0>
TON 2
TxCK Sync 1X
Prescaler
01 1, 8, 64, 256
TCY 00
Note: In certain variants of the dsPIC30F family, the TxCK pin may not be available. Refer to the device data
sheet for the I/O pin details. In such cases, the timer must use the system clock (FOSC/4) as its input
clock, unless it is configured for 32-bit operation.
Lower Byte:
U-0 R/W-0 R/W-0 R/W-0 U-0 R/W-0 R/W-0 U-0
— TGATE TCKPS<1:0> — TSYNC TCS — 12
bit 7 bit 0
Timers
1 = Starts the timer
0 = Stops the timer
bit 14 Unimplemented: Read as ‘0’
bit 13 TSIDL: Stop in Idle Mode bit
1 = Discontinue timer operation when device enters Idle mode
0 = Continue timer operation in Idle mode
bit 12-7 Unimplemented: Read as ‘0’
bit 6 TGATE: Timer Gated Time Accumulation Enable bit
1 = Gated time accumulation enabled
0 = Gated time accumulation disabled
(TCS must be set to ‘0’ when TGATE = 1. Reads as ‘0’ if TCS = 1)
bit 5-4 TCKPS<1:0>: Timer Input Clock Prescale Select bits
11 = 1:256 prescale value
10 = 1:64 prescale value
01 = 1:8 prescale value
00 = 1:1 prescale value
bit 3 Unimplemented: Read as ‘0’
bit 2 TSYNC: Timer External Clock Input Synchronization Select bit
When TCS = 1:
1 = Synchronize external clock input
0 = Do not synchronize external clock input
When TCS = 0:
This bit is ignored. Read as ‘0’. Timer1 uses the internal clock when TCS = 0.
bit 1 TCS: Timer Clock Source Select bit
1 = External clock from pin TxCK
0 = Internal clock (FOSC/4)
bit 0 Unimplemented: Read as ‘0’
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
U-0 R/W-0 R/W-0 R/W-0 R/W-0 U-0 R/W-0 U-0
— TGATE TCKPS<1:0> T32 — TCS —
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
U-0 R/W-0 R/W-0 R/W-0 U-0 U-0 R/W-0 U-0
— TGATE TCKPS<1:0> — — TCS —
bit 7 bit 0
12
bit 15 TON: Timer On bit
1 = Starts 16-bit TMRx
0 = Stops 16-bit TMRx
Timers
bit 14 Unimplemented: Read as ‘0’
bit 13 TSIDL: Stop in Idle Mode bit
1 = Discontinue module operation when device enters Idle mode
0 = Continue module operation in Idle mode
bit 12-7 Unimplemented: Read as ‘0’
bit 6 TGATE: Timer Gated Time Accumulation Enable bit
1 = Timer gated time accumulation enabled
0 = Timer gated time accumulation disabled (Read as ‘0’ if TCS = 1)
(TCS must be set to logic ‘0’ when TGATE = 1)
bit 5-4 TCKPS<1:0>: Timer Input Clock Prescale Select bits
11 = 1:256 prescale value
10 = 1:64 prescale value
01 = 1:8 prescale value
00 = 1:1 prescale value
bit 3-2 Unimplemented: Read as ‘0’
bit 1 TCS: Timer Clock Source Select bit
1 = External clock from pin TxCK
0 = Internal clock (FOSC/4)
bit 0 Unimplemented: Read as ‘0’
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Note: Only Type A time bases support the External Asynchronous Clock mode.
Example 12-1: Initialization Code for 16-bit Timer Using System Clock
__T1Interrupt:
BCLR IFS0, #T1IF ; Reset Timer1 interrupt flag
; User code goes here.
RETFIE ; Return from ISR
Note: The external input clock must meet certain minimum high time and low time
Timers
requirements when Timerx is used in the Synchronous Counter mode. Refer to the
device data sheet “Electrical Specifications” section for further details.
Example 12-2: Initialization Code for 16-bit Synchronous Counter Mode Using an
External Clock Input
; The following code example will enable Timer1 interrupts, load the
; Timer1 Period register and start Timer1 using an external clock
; and a 1:8 prescaler setting.
__T1Interrupt:
BCLR IFS0, #T1IF ; Reset Timer1 interrupt flag
; User code goes here.
RETFIE ; Return from ISR
12.4.3 Type A Timer Asynchronous Counter Mode Using External Clock Input
A Type A time base has the ability to operate in an Asynchronous Counting mode, using an
external clock source connected to the TxCK pin. When the TSYNC control bit (TxCON<2>) is
cleared, the external clock input is not synchronized with the device system clock source. The
time base continues to increment asynchronously to the internal device clock.
The asynchronous operation time base is beneficial for the following applications:
• The time base can operate during Sleep mode and can generate an interrupt on period
register match that will wake-up the processor.
• The time base can be clocked from the low power 32 kHz oscillator for real-time clock
applications
Please see Section 12.12.1 “Timer Operation in Sleep Mode” for more details..
Note 1: Only Type A time bases support the Asynchronous Counter mode.
2: The external input clock must meet certain minimum high time and low time
requirements when Timerx is used in the Asynchronous Counter mode. Refer to the
device data sheet “Electrical Specifications” section for further details.
3: Unexpected results may occur when reading Timer1, in asynchronous mode.
Example 12-3: Initialization Code for 16-bit Asynchronous Counter Mode Using an
External Clock Input
; The following code example will enable Timer1 interrupts, load the
; Timer1 Period register and start Timer1 using an asynchronous
; external clock and a 1:8 prescaler setting.
__T1Interrupt:
BCLR IFS0, #T1IF ; Reset Timer1 interrupt flag
; User code goes here.
RETFIE ; Return from ISR
Timers
Please refer to the device data sheet for the external clock timing specifications associated with
the time bases.
Note: The timer will not interrupt the CPU when a timer period match occurs in Gate Time
Accumulation mode.
The resolution of the timer count is directly related to the timer clock period. For a timer prescaler
of 1:1, the timer clock period is one instruction cycle. For a timer prescaler of 1:256, the timer
clock period is 256 times the instruction cycle. The timer clock resolution can be associated to
the pulse width of the gate signal. Refer to the “Electrical Specifications” section in the device
data sheet for further details on the gate width pulse requirements.
TxCK pin
Example 12-4: Initialization Code for 16-bit Gated Time Accumulation Mode
; The following code example will enable Timer2 interrupts, load the
; Timer2 Period register and start Timer2 using an internal clock
; and an external gate signal. On the falling edge of the gate
; signal a Timer2 interrupt occurs. The interrupt service
; routine must clear the Timer2 interrupt status flag in software .
__T2Interrupt:
BCLR IFS0, #T2IF ; Reset Timer2 interrupt flag
; User code goes here.
RETFIE ; Return from ISR
Timers
• The timer count matches the respective period register and the timer module is not
operating in Gated Time Accumulation mode.
• The falling edge of the “gate” signal is detected when the timer is operating in Gated Time
Accumulation mode.
The TxIF bit must be cleared in software.
A timer is enabled as a source of interrupt via the respective timer interrupt enable bit, TxIE.
Furthermore, the interrupt priority level bits (TxIP<2:0>) must be written with a non-zero value in
order for the timer to be a source of interrupt. Refer to Section 6. “Reset Interrupts” for further
details.
Note: A special case occurs when the period register is loaded with 0x0000 and the timer
is enabled. No timer interrupts will be generated for this configuration.
TMR2 47FD 47FE 47FF 4800 0000 0001 0002 0003 0004 0005
TMR2 Resets Here
PR2 4800
Cleared by User
TxIF
Note: Refer to the device data sheet for information on the specific Type B and Type C
time bases that can be combined. 12
The following configuration settings assume Timer3 is a Type C time base and Timer2 is a Type B
time base:
Timers
• TON (T2CON<15>) = 1.
• T32 (T2CON<3>) = 1.
• TCKPS<1:0> (T2CON<5:4>) are used to set the Prescaler mode for Timer2
(Type B time base).
• The TMR3:TMR2 register pair contains the 32-bit value of the timer module; the TMR3
(Type C time base) register is the Most Significant Word, while the TMR2 (Type B time
base) register is the Least Significant Word of the 32-bit timer value.
• The PR3:PR2 register pair contains the 32-bit period value that is used for comparison with
the TMR3:TMR2 timer value.
• T3IE (IEC0<7>) is used to enable the 32-bit timer interrupt for this configuration.
• T3IF (IFS0<7>) is used as a status flag for the timer interrupt.
• T3IP<2:0> (IPC1<14:12>) sets the interrupt priority level for the 32-bit timer.
• T3CON<15:0> are “don’t care” bits.
A block diagram representation of the 32-bit timer module using Timer2 and Timer3 as an
example is shown in Figure 12-6.
Figure 12-6: Type B-Type C Timer Pair Block Diagram (32-bit Timer)
Data Bus<15:0>
TMR3HLD
16
16
Write TMR2
Read TMR2
16
Reset
TMR3 TMR2 Sync
MSWord LSWord
Comparator x 32
Equal
ADC Event Trigger
PR3 PR2
0
T3IF
Event Flag
1 Q D TGATE (T2CON<6>)
Q CK
TGATE
TGATE
(T2CON<6>)
TCS
TCKPS<1:0>
TON 2
T2CKI 1X
Prescaler
Gate
01 1, 8, 64, 256
Sync
TCY 00
Note 1: This block diagram assumes Timer3 is a Type C time base, Timer2 is a Type B time base.
2: Timer configuration bit, T32 (T2CON<3>), must be set to ‘1’ for a 32-bit timer/counter operation. All control
bits are respective to the T2CON register.
Timers
Example 12-5: Initialization Code for 32-bit Timer Using Instruction Cycle as
Input Clock
; The following code example will enable Timer3 interrupts, load the
; Timer3:Timer2 Period Register and start the 32-bit timer module
; consisting of Timer3 and Timer2.
; When a 32-bit period match interrupt occurs, the user must clear
; the Timer3 interrupt status flag in software.
__T3Interrupt:
BCLR IFS0, #T3IF ; Reset Timer3 interrupt flag
; User code goes here.
RETFIE ; Return from ISR
Example 12-6: Initialization Code for 32-bit Synchronous Counter Mode Using an
External Clock Input
; When a 32-bit period match interrupt occurs, the user must clear
; the Timer3 interrupt status flag in the software.
__T3Interrupt:
BCLR IFS0, #T3IF ; Reset Timer3 interrupt flag
; User code goes here.
RETFIE ; Return from ISR
Example 12-7: Initialization Code for 32-bit Gated Time Accumulation Mode
12
; The following code example will enable Timer2 interrupts, load the
; Timer3:Timer2 Period register and start the 32-bit timer module
; consisting of Timer3 and Timer2. When a 32-bit period match occurs
Timers
; the timer will simply roll over and continue counting.
__T3Interrupt:
BCLR IFS0, #T3IF ; Reset Timer3 interrupt flag
; User code goes here.
RETFIE ; Return from ISR
To write a value to the TMR3:TMR2 register pair, the user should first write the MSWord to the
TMR3HLD register. When the LSWord of the timer value is written to TMR2, the contents of
TMR3HLD will automatically be transferred to the TMR3 register.
Note: Asynchronous counter operation is only supported for the Timer1 module.
When all of the above conditions are met, Timer1 will continue to count and detect period
matches when the device is in Sleep mode. When a match between the timer and the period
register occurs, the TxIF bit will be set and an interrupt can be generated to optionally wake the
device from Sleep. Refer to Section 10. “Watchdog Timer and Power Saving Modes” for
further details.
When executing the SLEEP instruction in asynchronous mode using a 32.768 kHz real time
oscillator to keep track of real time in seconds, it is important to insure the crystal connected to
the inputs is operating. This can be done by checking for a non-zero value in TMR1 and then
executing the SLEEP instruction. Failure to do so may result in a normal sleep execution with no
wake-up from sleep due to timer time out.
Example Code:
mov.b #0x46,w1 ; follow write sequence …
mov.b #0x57,w2 ; for OSCCONL writes.
mov #OSCCONL,w3
mov.b w1,[w3]
mov.b w2,[w3]
bset OSCCONL,#LPOSCEN ;enable 32Khz external xtal
clr TMR1 ; set up TMR1 for …
mov #0x7FFF,W0 ;interrupts every 1.0 Sec
mov W0,PR1
Timers
module will stop in Idle mode.
12.13 Peripherals Using Timer Modules
DS70059D-page 12-23
TMR3HLD 0108 Timer3 Holding Register (used in 32-bit mode only) 0000 0000 0000 0000
TMR3 010A Timer3 Register 0000 0000 0000 0000
PR2 010C Timer2 Period Register 1111 1111 1111 1111
PR3 010E Timer3 Period Register 1111 1111 1111 1111
T2CON 0110 TON — TSIDL — — — — — — TGATE TCKPS1 TCKPS0 T32 — TCS — 0000 0000 0000 0000
T3CON 0112 TON — TSIDL — — — — — — TGATE TCKPS1 TCKPS0 — — TCS — 0000 0000 0000 0000
TMR4 0114 Timer4 Register 0000 0000 0000 0000
TMR5HLD 0116 Timer5 Holding Register (used in 32-bit mode only) 0000 0000 0000 0000
TMR5 0118 Timer5 Register 0000 0000 0000 0000
PR4 011A Timer4 Period Register 1111 1111 1111 1111
PR5 011C Timer5 Period Register 1111 1111 1111 1111
T4CON 011E TON — TSIDL — — — — — — TGATE TCKPS1 TCKPS0 T32 — TCS — 0000 0000 0000 0000
T5CON 0120 TON — TSIDL — — — — — — TGATE TCKPS1 TCKPS0 — — TCS — 0000 0000 0000 0000
IFS0 0084 CNIF MI2CIF SI2CIF NVMIF ADIF U1TXIF U1RXIF SPI1IF T3IF T2IF OC2IF IC2IF T1IF OC1IF IC1IF INT01F 0000 0000 0000 0000
IFS1 0086 IC61F IC5IF IC4IF IC3IF C1IF SPI2IF U2TXIF U2RXIF INT2IF T5IF T4IF OC4IF OC3IF IC8IF IC7IF INT1IF 0000 0000 0000 0000
dsPIC30F Family Reference Manual
IEC0 008C CNIE MI2CIE IC2IE NVMIE ADIE U1TXIE U1RXIE SPI1IE T3IE T2IE OC2IE IC2IE T1IE OC1IE IC1IE INT0IE 0000 0000 0000 0000
IEC1 008E IC6IE IC5IE IC4IE IC3IE C1IE SPI2IE U2TXIE U2RXIE INT2IE T5IE T4IE OC4IE OC3IE IC8IE IC7IE INT1IE 0000 0000 0000 0000
IPC0 0094 — T1IP<2:0> — OC1IP<2:0> — IC1IP<2:0> INT0IP<2:0> 0100 0100 0100 0100
IPC1 0096 — T3IP<2:0> — T2IP<2:0> — OC2IP<2:0> IC2IP<2:0> 0100 0100 0100 0100
IPC5 009E — INT2IP<2:0> — T5IP<2:0> — T4IP<2:0> OC4IP<2:0> 0100 0100 0100 0100
Note: Please refer to the device data sheet for specific memory map details.
Question 1: Can a timer module be used to wake the device from Sleep mode?
Answer: Yes, but only Timer1 has the ability to wake the device from Sleep mode. This is
because Timer1 allows the TMR1 register to increment from an external, unsynchronized clock
source. When the TMR1 register is equal to the PR1 register, the device will wake from Sleep
mode, if Timer1 interrupts have been enabled using the T1IE control bit. Refer to Section
12.12.1 “Timer Operation in Sleep Mode” for further details.
Timers
appropriate registers can be updated.
Power-Down
Detect
dsPIC30FXXX
8
OSC1
Current Sink
VDD 4
S1
Backup
Battery CN0
S2
TMR1
CN1
S3
SOSCO CN2
S4
32.768 kHz
CN3
SOSCI
VSS
In this example, a 32.768 kHz crystal is used as the time base for the Real-Time Clock. If the
clock needs to be updated at 1 second intervals, then the period register, PR1, must be loaded
with a value to allow the Timer1 to PR1 match at the desired rate. In the case of a 1 second
Timer1 match event, the PR1 register should be loaded with a value of 0x8000.
Note: The TMR1 register should never be written for correct real-time clock functionality,
since the Timer1 clock source is asynchronous to the system clock. Writes to the
TMR1 register may corrupt the real-time counter value, resulting in inaccurate
timekeeping.
Note: Please visit the Microchip web site (www.microchip.com) for additional Application
Notes and code examples for the dsPIC30F Family of devices.
Timers
HIGHLIGHTS
This section of the manual contains the following major topics:
Input Capture
13.12 Related Application Notes.......................................................................................... 13-13
13.13 Revision History ......................................................................................................... 13-14
13.1 Introduction
This section describes the Input Capture module and its associated Operational modes. The
Input Capture module is used to capture a timer value from one of two selectable time bases,
upon an event on an input pin. The Input Capture features are quite useful in applications
requiring frequency (Time Period) and pulse measurement. Figure 13-1 depicts a simplified
block diagram of the Input Capture module.
Refer to the specific device data sheet for further information on the number of channels
available in a particular device. All Input Capture channels are functionally identical. In this
section, an ‘x’ in the pin name or register name denotes the specific Input Capture channel.
The Input Capture module has multiple Operating modes, which are selected via the ICxCON
register. The Operating modes include:
• Capture timer value on every falling edge of input applied at the ICx pin
• Capture timer value on every rising edge of input applied at the ICx pin
• Capture timer value on every fourth rising edge of input applied at the ICx pin
• Capture timer value on every 16th rising edge of input applied at the ICx pin
• Capture timer value on every rising and every falling edge of input applied at the ICx pin
The Input Capture module has a four-level FIFO buffer. The number of capture events required
to generate a CPU interrupt can be selected by the user.
16 16
1 0 ICTMR
(ICxCON<7>)
Prescaler Edge Detection Logic FIFO
Counter and R/W
(1, 4, 16) Clock Synchronizer Logic
ICx pin
3 ICM<2:0>(ICxCON<2:0>)
Mode Select
FIFO
ICBNE, ICOV(ICxCON<4:3>)
ICxBUF
ICxI<1:0>
Interrupt
ICxCON Logic
System Bus
Set Flag ICxIF
(in IFSn Register)
Note: An ‘x’ in a signal, register or bit name denotes the number of the capture channel.
Lower Byte:
R/W-0 R/W-0 R/W-0 R-0, HC R-0, HC R/W-0 R/W-0 R/W-0
ICTMR ICI<1:0> ICOV ICBNE ICM<2:0>
bit 7 bit 0
Input Capture
1 = TMR2 contents are captured on capture event
0 = TMR3 contents are captured on capture event
Note: Timer selections may vary. Refer to the device data sheet for details.
bit 6-5 ICI<1:0>: Select Number of Captures per Interrupt bits
11 = Interrupt on every fourth capture event
10 = Interrupt on every third capture event
01 = Interrupt on every second capture event
00 = Interrupt on every capture event
bit 4 ICOV: Input Capture Overflow Status Flag (Read Only) bit
1 = Input capture overflow occurred
0 = No input capture overflow occurred
bit 3 ICBNE: Input Capture Buffer Empty Status (Read Only) bit
1 = Input capture buffer is not empty, at least one more capture value can be read
0 = Input capture buffer is empty
bit 2-0 ICM<2:0>: Input Capture Mode Select bits
111 = Input Capture functions as interrupt pin only, when device is in Sleep or Idle mode
(Rising edge detect only, all other control bits are not applicable.)
110 = Unused (module disabled)
101 = Capture mode, every 16th rising edge
100 = Capture mode, every 4th rising edge
011 = Capture mode, every rising edge
010 = Capture mode, every falling edge
001 = Capture mode, every edge (rising and falling)
(ICI<1:0> does not control interrupt generation for this mode.)
000 = Input capture module turned off
Legend:
HC = Cleared in Hardware HS = Set in Hardware
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Figure 13-2: Simple Capture Event Timing Diagram, Time Base Prescaler = 1:1
ICx pin
See Note 1
Note 1: A capture signal edge that occurs in this region will result in a capture buffer entry value of 1 or 2 timer counts from
the capture signal edge.
Figure 13-3: Simple Capture Event Timing Diagram, Time Base Prescaler = 1:4
TCY
ICxIF Set
Input Capture
ICx pin
Capture Data n
; The following code example will set the Input Capture 1 module
; for interrupts on every second capture event, capture on every
; fourth rising edge and select Timer 2 as the time-base. This
; code example clears ICxCON to avoid unexpected interrupts.
; The following code shows how to read the capture buffer when
; an interrupt is generated. W0 contains the capture buffer address.
__IC1Interrupt:
BCLR IFS0, #IC1IF ; Reset respective interrupt flag 13
MOV [w0++], [w1++] ; Read and save off first capture entry
Input Capture
MOV [w0], [w1] ; Read and save off second capture entry
; Remaining user code here
RETFIE ; Return from ISR
Note: It is recommended that the user turn off the capture module (i.e., clear ICM<2:0>
(ICxCON<2:0>)) before switching to a new mode. If the user switches to a new
Capture mode, the prescaler counter is not cleared. Therefore, it is possible that the
first capture event and its associated interrupt is generated due to a non-zero
prescaler counter (at the time of switching modes).
TMRy n-3 n-2 n-1 n n+1 n+2 n+3 n+4 n+5 n+6
ICx pin
Input Capture
The input capture module can also be configured to function as an external interrupt pin. For this
mode, the ICI<1:0> (ICxCON<6:5>) bits must be set to ‘00’. Interrupts will be generated
independently of buffer reads.
This wake-up feature is quite useful for adding extra external pin interrupts. The following
conditions are true when the input capture module is used in this mode:
• The capture prescaler counter is not utilized while in this mode.
• The ICI<1:0>(ICxCON<6:5>) bits are not applicable.
IFS0 0084 CNIF MI2CIF SI2CIF NVMIF ADIF U1TXIF U1RXIF SPI1IF T3IF T2IF OC2IF IC2IF T1IF OC1IF IC1IF INT0F 0000 0000 0000 0000
IFS1 0086 IC6IF IC5IF IC4IF IC3IF C1IF SPI2IF U2TXIF U2RXIF INT2IF T5IF T4IF OC4IF OC3IF IC8IF IC7IF INT1IF 0000 0000 0000 0000
IEC0 008C CNIE MI2CIE SI2CIE IR12 ADIE U1TXIE U1RXIE SPI1IE T3IE T2IE OC2IE IC2IE T1IE OC1IE IC1IE INT0IE 0000 0000 0000 0000
IEC1 008E IC6IE EI30 IC4IE IC3IE C1IE SPI2IE U2TXIE U2RXIE INT2IE T5IE T4IE OC4IE OC3IE IC8IE IC7IE INT1IE 0000 0000 0000 0000
IPC0 0094 — T1IP<2:0> — OC1IP<2:0> — IC1IP<2:0> — INT0IP<2:0> 0100 0100 0100 0100
DS70060C-page 13-11
Section 13. Input Capture
Input Capture
13
dsPIC30F Family Reference Manual
Question 1: Can the Input Capture module be used to wake the device from Sleep
mode?
Answer: Yes. When the Input Capture module is configured to ICM<2:0> = ‘111’ and the
respective channel interrupt enable bit is asserted, ICxIE = 1, a rising edge on the capture pin
will wake-up the device from Sleep (see Section 13.8 “Input Capture Operation in Power
Saving States”).
Note: Please visit the Microchip web site (www.microchip.com) for additional Application
Notes and code examples for the dsPIC30F Family of devices.
13
Input Capture
HIGHLIGHTS
This section of the manual contains the following major topics:
14
Compare
Output
14.1 Introduction
The Output Compare module has the ability to compare the value of a selected time base with
the value of one or two compare registers (depending on the Operation mode selected).
Furthermore, it has the ability to generate a single output pulse, or a train of output pulses, on a
compare match event. Like most dsPIC peripherals, it also has the ability to generate
interrupts-on- compare match events.
The dsPIC30F device may have up to eight output compare channels, designated OC1, OC2,
OC3, etc. Refer to the specific device data sheet for the number of channels available in a
particular device. All output compare channels are functionally identical. In this section, an ‘x’ in
the pin, register or bit name denotes the specific output compare channel.
Each output compare channel can use one of two selectable time bases. The time base is
selected using the OCTSEL bit (OCxCON<3>). Please refer to the device data sheet for the
specific timers that can be used with each output compare channel number.
OCxRS(1)
Output S Q
OCxR(1) OCx(1)
Logic R
3 Output Enable
OCM<2:0>
Mode Select OCFA or OCFB
Comparator (see Note 2)
0 1 OCTSEL 0 1
16 16
Note 1: Where ‘x’ is shown, reference is made to the registers associated with the respective output compare
channels 1 through 8.
2: OCFA pin controls OC1-OC4 channels. OCFB pin controls OC5-OC8 channels.
3: Each output compare channel can use one of two selectable time bases. Refer to the device data sheet
for the time bases associated with the module.
Lower Byte:
U-0 U-0 U-0 R-0, HC R/W-0 R/W-0 R/W-0 R/W-0
— — — OCFLT OCTSEL OCM<2:0>
bit 7 bit 0
Compare
Output
101 = Initialize OCx pin low, generate continuous output pulses on OCx pin
100 = Initialize OCx pin low, generate single output pulse on OCx pin
011 = Compare event toggles OCx pin
010 = Initialize OCx pin high, compare event forces OCx pin low
001 = Initialize OCx pin low, compare event forces OCx pin high
000 = Output compare channel is disabled
Legend:
HC = Cleared in Hardware
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Note 1: It is recommended that the user turn off the output compare module (i.e., clear
OCM<2:0> (OCxCON<2:0>)) before switching to a new mode.
2: In this section, a reference to any SFRs associated with the selected timer source
is indicated by a ‘y’ suffix. For example, PRy is the Period register for the selected
timer source, while TyCON is the Timer Control register for the selected timer
source.
To configure the output compare module for this mode, set control bits OCM<2:0> = ‘001’. The
compare time base should also be enabled. Once this Compare mode has been enabled, the
output pin, OCx, will be initially driven low and remain low until a match occurs between the TMRy
and OCxR registers. Referring to Figure 14-2, there are some key timing events to note:
• The OCx pin is driven high one instruction clock after the compare match occurs between
the compare time base and the OCxR register. The OCx pin will remain high until a mode
change has been made, or the module is disabled.
• The compare time base will count up to the value contained in the associated period
register and then reset to 0x0000 on the next instruction clock.
• The respective channel interrupt flag, OCxIF, is asserted 2 instruction clocks after the OCx
pin is driven high.
Figure 14-2: Single Compare Mode: Set OCx High on Compare Match Event
TMRy 3000 3001 3002 3003 3004 3FFF 4000 0000 0001
TMRy Resets Here
PRy 4000
OCxR 3002
OCxIF
Note: An ‘x’ represents the output compare channel number. A ‘y’ represents the time base number.
14
Compare
Output
To configure the output compare module for this mode, set control bits OCM<2:0> = ‘010’. The
compare time base must also be enabled. Once this Compare mode has been enabled, the
output pin, OCx, will be initially driven high and remain high until a match occurs between the
Timer and OCxR registers. Referring to Figure 14-3, there are some key timing events to note:
• The OCx pin is driven low one instruction clock after the compare match occurs between
the compare time base and the OCxR register. The OCx pin will remain low until a mode
change has been made, or the module is disabled.
• The compare time base will count up to the value contained in the associated period
register and then reset to 0x0000 on the next instruction clock.
• The respective channel interrupt flag, OCxIF, is asserted 2 instruction clocks after OCx pin
is driven low.
Figure 14-3: Single Compare Mode: Force OCx Low on Compare Match Event
TMRy 47FE 47FF 4800 4801 4802 4BFF 4C00 0000 0001
TMRy Resets Here
PRy 4C00
OCxR 4800
OCx pin
OCxIF
Note: An ‘x’ represents the output compare channel number. A ‘y’ represents the time base number.
To configure the output compare module for this mode, set control bits OCM<2:0> = ‘011’. In
addition, Timer 2 or Timer 3 must be selected and enabled. Once this Compare mode has been
enabled, the output pin, OCx, will be initially driven low and then toggle on each and every
subsequent match event between the Timer and OCxR registers. Referring to Figure 14-4 and
Figure 14-5, there are some key timing events to note:
• The OCx pin is toggled one instruction clock after the compare match occurs between the
compare time base and the OCxR register. The OCx pin will remain at this new state until
the next toggle event, or until a mode change has been made, or the module is disabled.
• The compare time base will count up to the contents in the period register and then reset to
0x0000 on the next instruction clock.
• The respective channel interrupt flag, OCxIF, is asserted 2 instruction clocks after the OCx
pin is toggled.
Note: The internal OCx pin output logic is set to a logic ‘0’ on a device Reset. However,
the operational OCx pin state for the Toggle mode can be set by the user software.
Example 14-1 shows a code example for defining the desired initial OCx pin state
in the Toggle mode of operation.
Figure 14-4: Single Compare Mode: Toggle Output on Compare Match Event (PR2 > OCxR)
TMRy 0500 0501 0502 0600 0000 0001 0500 0501 0502
TMRy Resets Here
PRy 0600
OCxR 0500
OCx pin
Cleared by User
2 TCY
OCxIF
Note: An ‘x’ represents the output compare channel number. A ‘y’ represents the time base number.
14
Figure 14-5: Single Compare Mode: Toggle Output on Compare Match Event (PR2 = OCxR)
Compare
1 Instruction Clock Period
Output
TMR2 0500 0000 0001 0500 0000 0001 0500 0000 0001
TMRy Resets Here TMRy Resets Here
PR2 0500
OCxR 0500
OCx pin
2 TCY 2 TCY 2 TCY
OCxIF
Note: An ‘x’ represents the output compare channel number. A ‘y’ represents the time base number.
Example 14-2 shows example code for the configuration and interrupt service of the Single
Compare mode toggle event.
__OC1Interrupt:
BCLR IFS0, #OC1IF ; Reset respective interrupt flag
; Remaining user code here
RETFIE ; Return from ISR
To configure the Output Compare module for the Single Output Pulse mode, set control bits
OCM<2:0> = ‘100’. In addition, the compare time base must be selected and enabled. Once this
mode has been enabled, the output pin, OCx, will be driven low and remain low until a match
occurs between the time base and OCxR registers. Referring to Figure 14-6 and Figure 14-7,
there are some key timing events to note:
• The OCx pin is driven high one instruction clock after the compare match occurs between
the compare time base and OCxR register. The OCx pin will remain high until the next
match event occurs between the time base and the OCxRS register. At this time, the pin
will be driven low. The OCx pin will remain low until a mode change has been made, or the
module is disabled.
• The compare time base will count up to the value contained in the associated period
register and then reset to 0x0000 on the next instruction clock.
• If the time base period register contents are less than the OCxRS register contents, then no
falling edge of the pulse is generated. The OCx pin will remain high until
OCxRS <= PRy, or a mode change or Reset condition has occurred.
• The respective channel interrupt flag, OCxIF, is asserted 2 instruction clocks after the OCx
pin is driven low (falling edge of single pulse).
Figure 14-6 depicts the General Dual Compare mode generating a single output pulse.
Figure 14-7 depicts another timing example where OCxRS > PRy. In this example, no falling
edge of the pulse is generated since the compare time base resets before counting up to
0x4100.
14
Compare
Output
TMRy 3000 3001 3002 3003 3004 3005 3006 4000 0000
TMRy Resets Here
PRy 4000
OCxR 3000
OCxRS 3003
OCx pin
2 TCY
OCxIF
Cleared by User
Note 1: An ‘x’ represents the output compare channel number. A ‘y’ represents the time base number.
2: OCxR = Compare Register, OCxRS = Secondary Compare Register.
Figure 14-7: Dual Compare Mode: Single Output Pulse (OCxRS > PR2)
TMRy 3000 3001 3002 3003 3004 3005 3006 4000 0000
TMRy Resets Here
PRy 4000
OCxR 3000
OCxRS 4100
OCx pin
Compare Interrupt does not occur
OCxIF
Note 1: An ‘x’ represents the output compare channel number. A ‘y’ represents the time base number.
2: OCxR = Compare Register, OCxRS = Secondary Compare Register.
When control bits OCM<2:0> (OCxCON<2:0>) are set to ‘100’, the selected output compare
channel initializes the OCx pin to the low state and generates a single output pulse.
To generate a single output pulse, the following steps are required (these steps assume timer
source is initially turned off, but this is not a requirement for the module operation):
1. Determine the instruction clock cycle time. Take into account the frequency of the external
clock to the timer source (if one is used) and the timer prescaler settings.
2. Calculate time to the rising edge of the output pulse relative to the TMRy start value
(0x0000).
3. Calculate the time to the falling edge of the pulse based on the desired pulse width and
the time to the rising edge of the pulse.
4. Write the values computed in steps 2 and 3 above into the compare register, OCxR, and
the secondary compare register, OCxRS, respectively.
5. Set timer period register, PRy, to value equal to or greater than value in OCxRS, the
secondary compare register.
6. Set OCM<2:0> = ‘100’ and the OCTSEL (OCxCON<3>) bit to the desired timer source.
The OCx pin state will now be driven low.
7. Set the TON (TyCON<15>) bit to ‘1’, which enables the compare time base to count.
8. Upon the first match between TMRy and OCxR, the OCx pin will be driven high.
9. When the incrementing timer, TMRy, matches the secondary compare register, OCxRS,
the second and trailing edge (high-to-low) of the pulse is driven onto the OCx pin. No
additional pulses are driven onto the OCx pin and it remains at low. As a result of the
second compare match event, the OCxIF interrupt flag bit set, which will result in an
interrupt if it is enabled, by setting the OCxIE bit. For further information on peripheral
interrupts, refer to Section 6. “Reset Interrupts”.
10. To initiate another single pulse output, change the timer and compare register settings, if
needed, and then issue a write to set OCM<2:0> (OCxCON<2:0>) bits to ‘100’. Disabling
and re-enabling of the timer and clearing the TMRy register are not required, but may be
advantageous for defining a pulse from a known event time boundary.
The output compare module does not have to be disabled after the falling edge of the output
pulse. Another pulse can be initiated by rewriting the value of the OCxCON register.
14
Compare
Output
Example 14-3 shows example code for configuration of the single output pulse event.
__OC1Interrupt:
BCLR IFS0, #OC1IF ; Reset respective interrupt flag
; Remaining user code here
RETFIE ; Return from ISR
14.3.2.3 Special Cases for Dual Compare Mode Generating a Single Output Pulse
Depending on the relationship of the OCxR, OCxRS and PRy values, the output compare module
has a few unique conditions which should be understood. These special conditions are specified
in Table 14-1, along with the resulting behavior of the module.
Table 14-1: Special Cases for Dual Compare Mode Generating a Single Output Pulse
SFR Logical Output
Special Conditions Operation
Relationship at OCx
PRy >= OCxRS and OCxR = 0 In the first iteration of the TMRy counting from 0x0000 up to Pulse will be
OCxRS > OCxR Initialize TMRy = 0 PRy, the OCx pin remains low, no pulse is generated. After the delayed by the
TMRy resets to zero (on period match), the OCx pin goes high value in the PRy
due to match with OCxR. Upon the next TMRy to OCxRS register
match, the OCx pin goes low and remains there. The OCxIF depending on
bit will be set as a result of the second compare. setup
There are two alternative initial conditions to consider:
a] Initialize TMRy = 0 and set OCxR >= 1
b] Initialize TMRy = PRy (PRy > 0) and set OCxR = 0
PRy >= OCxR and OCxR >= 1 and TMRy counts up to OCxR and on a compare match event (i.e., Pulse
OCxR >= OCxRS PRy >= 1 TMRy = OCxR), the OCx pin is driven to a high state. TMRy
then continues to count and eventually resets on period match
(i.e., PRy =TMRy). The timer then restarts from 0x0000 and
counts up to OCxRS, and on a compare match event (i.e.,
TMRy = OCxRS), the OCx pin is driven to a low state. The
OCxIF bit will be set as a result of the second compare.
OCxRS > PRy and None Only the rising edge will be generated at the OCx pin. The Rising edge/
PRy >= OCxR OCxIF will not be set. transition to high
OCxR = OCxRS = None An output pulse delayed 2 instruction clock periods upon the Delayed pulse
PRy = 0x0000 match of the timer and period register is generated at the OCx
pin. The OCxIF bit will be set as a result of the second
compare.
OCxR > PRy None Unsupported mode, timer resets prior to match condition. Remains low
Note 1: In all the cases considered herein, the TMRy register is assumed to be initialized to 0x0000.
2: OCxR = Compare Register, OCxRS = Secondary Compare Register, TMRy = Timery Count,
PRy = Timery Period Register.
14
Compare
Output
Figure 14-8: Dual Compare Mode: Continuous Output Pulse (PR2 = OCxRS)
TMRy 3000 3001 3002 3003 0000 3000 3001 3002 3003 0000 3000
TMRy Resets Here TMRy Resets Here
PRy 3003
OCxR 3000
OCxRS 3003
OCx pin
2 TCY 2 TCY
OCxIF
Cleared by User
Note 1: An ‘x’ represents the output compare channel number. A ‘y’ represents the time base number.
2: OCxR = Compare Register, OCxRS = Secondary Compare Register.
Figure 14-9: Dual Compare Mode: Continuous Output Pulse (PR2 = OCxRS)
TMRy 3000 3001 3002 3003 0000 3000 3001 3002 3003 0000 3000
TMRy Resets Here TMRy Resets Here
PRy 3003
OCxR 3000
OCxRS 3003
OCx pin
Compare Interrupt does not Occur
OCxIF
Note 1: An ‘x’ represents the output compare channel number. A ‘y’ represents the time base number.
2: OCxR = Compare Register, OCxRS = Secondary Compare Register.
When control bits OCxM<2:0> (OCxCON<2:0>) are set to ‘101’, the selected output compare
channel initializes the OCx pin to the low state and generates output pulses on each and every
compare match event.
For the user to configure the module for the generation of a continuous stream of output pulses,
the following steps are required (these steps assume timer source is initially turned off, but this
is not a requirement for the module operation):
1. Determine the instruction clock cycle time. Take into account the frequency of the external
clock to the timer source (if one is used) and the timer prescaler settings.
2. Calculate time to the rising edge of the output pulse relative to the TMRy start value
(0x0000).
3. Calculate the time to the falling edge of the pulse, based on the desired pulse width and
the time to the rising edge of the pulse.
4. Write the values computed in step 2 and 3 above into the compare register, OCxR, and
the secondary compare register, OCxRS, respectively.
5. Set timer period register, PRy, to value equal to or greater than value in OCxRS, the
secondary compare register.
14
6. Set OCM<2:0> = ‘101’ and the OCTSEL (OCxCON<3>) bit to the desired timer source.
The OCx pin state will now be driven low.
Compare
7. Enable the compare time base by setting the TON (TyCON<15>) bit to ‘1’.
Output
8. Upon the first match between TMRy and OCxR, the OCx pin will be driven high.
9. When the compare time base, TMRy, matches the secondary compare register, OCxRS,
the second and trailing edge (high-to-low) of the pulse is driven onto the OCx pin.
10. As a result of the second compare match event, the OCxIF interrupt flag bit set.
11. When the compare time base and the value in its respective period register match, the
TMRy register resets to 0x0000 and resumes counting.
12. Steps 8 through 11 are repeated and a continuous stream of pulses is generated,
indefinitely. The OCxIF flag is set on each OCxRS-TMRy compare match event.
Example 14-4 shows example code for configuration of the continuous output pulse event.
__OC1Interrupt:
BCLR IFS0, #OC1IF ; Reset respective interrupt flag
; Remaining user code here
RETFIE ; Return from ISR
14.3.2.6 Special Cases for Dual Compare Mode Generating Continuous Output Pulses
Depending on the relationship of the OCxR, OCxRS and PRy values, the output compare module
may not provide the expected results. These special cases are specified in Table 14-2, along with
the resulting behavior of the module.
Table 14-2: Special Cases for Dual Compare Mode Generating Continuous Output Pulses
SFR Logical Output
Special Conditions Operation
Relationship at OCx
PRy >= OCxRS and OCxR = 0 In the first iteration of the TMRy counting from 0x0000 up Continuous pulses with
OCxRS > OCxR Initialize TMRy = 0 to PRy, the OCx pin remains low, no pulse is generated. the first pulse delayed
After the TMRy resets to zero (on period match), the OCx by the value in the PRy
pin goes high. Upon the next TMRy to OCxRS match, the register, depending on
OCx pin goes low. If OCxR = 0 and PRy = OCxRS, the pin setup.
will remain low for one clock cycle, then be driven high
until the next TMRy to OCxRS match. The OCxIF bit will
be set as a result of the second compare.
There are two alternative initial conditions to consider:
a] Initialize TMRy = 0 and set OCxR >= 1
b] Initialize TMRy = PRy (PRy > 0) and set OCxR = 0
PRy >= OCxR and OCxR >= 1 and TMRy counts up to OCxR and on a compare match event Continuous pulses
OCxR >= OCxRS PRy >= 1 (i.e., TMRy = OCxR), the OCx pin is driven to a high state.
TMRy then continues to count and eventually resets on
period match (i.e., PRy =TMRy). The timer then restarts
from 0x0000 and counts up to OCxRS, and on a compare
match event (i.e., TMRy = OCxR), the OCx pin is driven to
a low state. The OCxIF bit will be set as a result of the
second compare.
OCxRS > PRy and None Only one transition will be generated at the OCx pin until Rising edge/
PRy >= OCxR the OCxRS register contents have been changed to a transition to high
value less than or equal to the period register contents
(PRy). OCxIF is not set until then.
OCxR = OCxRS = None Continuous output pulses are generated at the OCx pin. First pulse is delayed.
PRy = 0x0000 The first pulse is delayed 2 instruction clock periods upon Continuous pulses
the match of the timer and period register. The OCxIF bit are generated.
will be set as a result of the second compare.
OCxR > PRy None Unsupported mode, Timer resets prior to match condition. Remains low
Note 1: In all the cases considered herein, the TMRy register is assumed to be initialized to 0x0000.
2: OCxR = Compare Register, OCxRS = Secondary Compare Register, TMRy = Timery Count,
PRy = Timery Period Register.
14
Compare
Output
Note: The OCxR register should be initialized before the Output Compare module is first
enabled. The OCxR register becomes a read only duty cycle register when the
module is operated in the PWM modes. The value held in OCxR will become the
PWM duty cycle for the first PWM period. The contents of the duty cycle buffer
register, OCxRS, will not be transferred into OCxR until a time base period match
occurs.
An example PWM output waveform is shown in Figure 14-10.
Period = (PRy + 1)
1 2 3
1 Timery is cleared and new duty cycle value is loaded from OCxRS into OCxR.
2 Timer value equals value in the OCxR register, OCx Pin is driven low.
3 Timer overflow, value from OCxRS is loaded into OCxR, OCx pin driven high.
TyIF interrupt flag is asserted.
When the Output Compare mode bits, OCM<2:0> (OCxCON<2:0>), are set to ‘111’, the selected
output compare channel is configured for the PWM mode of operation. All functions described in
Section 14.3.3, “Pulse Width Modulation Mode” apply, with the addition of input Fault
protection.
Fault protection is provided via the OCFA and OCFB pins. The OCFA pin is associated with the
output compare channels 1 through 4, while the OCFB pin is associated with the output compare
channels 5 through 8.
If a logic ‘0’ is detected on the OCFA/OCFB pin, the selected PWM output pin(s) are placed in
the high impedance state. The user may elect to provide a pull-down or pull-up resistor on the
PWM pin to provide for a desired state if a Fault condition occurs. The shutdown of the PWM
output is immediate and is not tied to the device clock source. This state will remain until:
• The external Fault condition has been removed and
• The PWM mode is re-enabled by writing to the appropriate mode bits, OCM<2:0>
(OCxCON<2:0>).
As a result of the Fault condition, the respective interrupt flag, OCxIF bit, is asserted and an
interrupt will be generated, if enabled. Upon detection of the Fault condition, the OCFLT bit
(OCx-CON<4>) is asserted high (logic ‘1’). This bit is a read only bit and will only be cleared once
the external Fault condition has been removed and the PWM mode is re-enabled, by writing to
the appropriate mode bits, OCM<2:0> (OCxCON<2:0>).
Note: The external Fault pins, if enabled for use, will continue to control the OCx output
pins, while the device is in Sleep or Idle mode.
The PWM period is specified by writing to PRy, the Timery period register. The PWM period can
be calculated using the following formula:
Equation 14-1: Calculating the PWM Period
Note: A PRy value of N will produce a PWM period of N + 1 time base count cycles. For 14
example: a value of 7 written into the PRy register will yield a period consisting of 8
time base cycles.
Compare
Output
The PWM duty cycle is specified by writing to the OCxRS register. The OCxRS register can be
written to at any time, but the duty cycle value is not latched into OCxR until a match between
PRy and TMRy occurs (i.e., the period is complete). This provides a double buffer for the PWM
duty cycle and is essential for glitchless PWM operation. In the PWM mode, OCxR is a read only
register.
Some important boundary parameters of the PWM duty cycle include:
• If the duty cycle register, OCxR, is loaded with 0x0000, the OCx pin will remain low
(0% duty cycle).
• If OCxR is greater than PRy (timer period register), the pin will remain high (100% duty
cycle).
• If OCxR is equal to PRy, the OCx pin will be low for one time base count value and high for
all other count values.
See Figure 14-11 for PWM mode timing details. Table 14-3 and Table 14-4 show example PWM
frequencies and resolutions for a device operating at 10 and 30 MIPs, respectively.
Find the maximum resolution of the duty cycle that can be used with a 48 kHz frequency
and a 40 MHz device clock rate.
TMR3 0005 0000 0001 0002 0003 0004 0005 0000 0001 0002 0003 0004 0005
PR3 0005
OCx pin
TyIF is Set
OCxR = OCxRS TyIF is Set
OCxR = OCxRS
Note 1: An ‘x’ represents the output compare channel number. A ‘y’ represents the time base number.
2: OCxR = Compare Register, OCxRS = Secondary Compare Register.
Table 14-3: Example PWM Frequencies and Resolutions at 10 MIPs (FOSC = 40 MHz)
PWM Frequency 19 Hz 153 Hz 305 Hz 2.44 kHz 9.77 kHz 78.1 kHz 313 kHz
Timer Prescaler Ratio 8 1 1 1 1 1 1
Period Register Value 0xFFFF 0xFFFF 0x7FFF 0x0FFF 0x03FF 0x007F 0x001F
Resolution (bits) 16 16 15 12 10 7 5
Table 14-4: Example PWM Frequencies and Resolutions at 30 MIPs (FOSC = 120 MHz)
PWM Frequency 57 Hz 458 Hz 916 Hz 7.32 kHz 29.3 kHz 234 kHz 938 kHz
Timer Prescaler Ratio 8 1 1 1 1 1 1
Period Register Value 0xFFFF 0xFFFF 0x7FFF 0x0FFF 0x03FF 0x007F 0x001F
Resolution (bits) 16 16 15 12 10 7 5 14
Compare
Output
Example 14-6 shows configuration and interrupt service code for the PWM mode of operation.
__T2Interrupt:
BCLR IFS0, #T21IF ; Reset respective interrupt flag
; Remaining user code here
RETFIE ; Return from ISR
Note: The external Fault pins, if enabled for use, will continue to control the associated
OCx output pins while the device is in Sleep or Idle mode.
Compare
OC3 O — Output Compare/PWM Channel 3
Output
OC4 O — Output Compare/PWM Channel 4
OC5 O — Output Compare/PWM Channel 5
OC6 O — Output Compare/PWM Channel 6
OC7 O — Output Compare/PWM Channel 7
OC8 O — Output Compare/PWM Channel 8
OCFA I ST PWM Fault Protection A Input (For Channels 1-4)
OCFB I ST PWM Fault Protection B Input (For Channels 5 -8)
Legend: ST = Schmitt Trigger input with CMOS levels, I = Input, O = Output
DS70061C-page 14-24
PR3 010E Period Register 3 1111 1111 1111 1111
T2CON 0110 TON — TSIDL — — — — — — TGATE TCKPS1 TCKPS0 T32 — TCS — 0000 0000 0000 0000
T3CON 0112 TON — TSIDL — — — — — — TGATE TCKPS1 TCKPS0 — — TCS — 0000 0000 0000 0000
OC1RS 0180 Output Compare 1 Secondary Register uuuu uuuu uuuu uuuu
OC1R 0182 Output Compare 1 Register uuuu uuuu uuuu uuuu
OC1CON 0184 — — OCSIDL — — — — — — — — OCFLT OCTSEL OCM<2:0> 0000 0000 0000 0000
OC2RS 0186 Output Compare 2 Secondary Register uuuu uuuu uuuu uuuu
OC2R 0188 Output Compare 2 Register uuuu uuuu uuuu uuuu
OC2CON 018A — — OCSIDL — — — — — — — — OCFLT OCTSEL OCM<2:0> 0000 0000 0000 0000
OC3RS 018C Output Compare 3 Secondary Register uuuu uuuu uuuu uuuu
OC3R 018E Output Compare 3 Register uuuu uuuu uuuu uuuu
OC3CON 0190 — — OCSIDL — — — — — — — — OCFLT OCTSEL OCM<2:0> 0000 0000 0000 0000
OC4RS 0192 Output Compare 4 Secondary Register uuuu uuuu uuuu uuuu
OC4R 0194 Output Compare 4 Register uuuu uuuu uuuu uuuu
OC4CON 0196 — — OCSIDL — — — — — — — — OCFLT OCTSEL OCM<2:0> 0000 0000 0000 0000
dsPIC30F Family Reference Manual
OC5RS 0198 Output Compare 5 Secondary Register uuuu uuuu uuuu uuuu
OC5R 019A Output Compare 5 Register uuuu uuuu uuuu uuuu
OC5CON 019C — — OCSIDL — — — — — — — — OCFLT OCTSEL OCM<2:0> 0000 0000 0000 0000
OC6RS 019E Output Compare 6 Secondary Register uuuu uuuu uuuu uuuu
OC6R 01A0 Output Compare 6 Register uuuu uuuu uuuu uuuu
OC6CON 01A2 — — OCSIDL — — — — — — — — OCFLT OCTSEL OCM<2:0> 0000 0000 0000 0000
OC7RS 01A4 Output Compare 7 Secondary Register uuuu uuuu uuuu uuuu
OC7R 01A6 Output Compare 7 Register uuuu uuuu uuuu uuuu
OC7CON 01A8 — — OCSIDL — — — — — — — — OCFLT OCTSEL OCM<2:0> 0000 0000 0000 0000
OC8RS 01AA Output Compare 8 Secondary Register uuuu uuuu uuuu uuuu
OC8R 01AC Output Compare 8 Register uuuu uuuu uuuu uuuu
OC8CON 01AE — — OCSIDL — — — — — — — — OCFLT OCTSEL OCM<2:0> 0000 0000 0000 0000
IFS0 0084 CNIF MI2CIF SI2CIF NVMIF ADIF U1TXIF U1RXIF SPI1IF T3IF T2IF OC2IF IC2IF T1IF OC1IF IC1IF INT0 0000 0000 0000 0000
Legend: u = uninitialized
Note: The register map will depend on the number of output compare modules on the device. Please refer to the device data sheet for details.
IFS1 0086 IC6IF IC5IF IC4IF IC3IF C1IF SPI2IF U2TXIF U2RXIF INT2IF T5IF T4IF OC4IF OC3IF IC8IF IC7IF INT1IF 0000 0000 0000 0000
IFS2 0088 — — — FLTBIF FLTAIF LVDIF DCIIF QEIIF PWMIF C2IF INT4IF INT3IF OC8IF OC7IF OC6IF OC5IF 0000 0000 0000 0000
IEC0 008C CNIE MI2CIE SI2CIE NVMIE ADIE U1TXIE U1RXIE SPI1IE T3IE T2IE OC2IE IC2IE T1IE OC1IE IC1IE INT0IE 0000 0000 0000 0000
IEC1 008E IC6IE IC5IE IC4IE IC3IE C1IE SPI2IE U2TXIE U2RXIE INT2IE T5IE T4IE OC4IE OC3IE IC8IE IC7IE INT1IE 0000 0000 0000 0000
IEC2 0090 — — — FLTBIE FLTAIE LVDIE DCIIE QEIIE PWMIE C2IE INT4IE INT3IE OC8IE OC7IE OC6IE OC5IE 0000 0000 0000 0000
IPC0 0094 — T1IP<2:0> — OC1IP<2:0> — IC1IP<2:0> — INT0IP<2:0> 0100 0100 0100 0100
IPC1 0096 — T3IP<2:0> — T2IP<2:0> — OC2IP<2:0> — IC2IP<2:0> 0100 0100 0100 0100
IPC5 009E — INT2IP<2:0> — T5IP<2:0> — T4IP<2:0> — OC4IP<2:0> 0100 0100 0100 0100
IPC8 00A4 — OC8IP<2:0> — OC7IP<2:0> — OC6IP<2:0> — OC5IP<2:0> 0100 0100 0100 0100
Legend: u = uninitialized
Note: The register map will depend on the number of output compare modules on the device. Please refer to the device data sheet for details.
Section 14. Output Compare
DS70061C-page 14-25
Compare
14
Output
dsPIC30F Family Reference Manual
Question 1: The Output Compare pin stops functioning even when the OCSIDL bit is not
set. Why?
Answer: This is most likely to occur when the TSIDL bit (TxCON<13>) of the associated timer
source is set. Therefore, it is the timer that actually goes into Idle mode when the PWRSAV
instruction is executed.
Question 2: Can I use the Output Compare modules with the selected time base
configured for 32-bit mode?
Answer: No. The T32 bit (TxCON<3>) should be cleared when the timer is used with an output
compare module.
Note: Please visit the Microchip web site (www.microchip.com) for additional Application
Notes and code examples for the dsPIC30F Family of devices.
14
Compare
Output
HIGHLIGHTS
This section of the manual contains the following topics:
15
Motor Control
PWM
15.1 Introduction
The motor control PWM (MCPWM) module simplifies the task of generating multiple,
synchronized pulse width modulated outputs. In particular, the following power and motion
control applications are supported:
• Three-Phase AC Induction Motor
• Switched Reluctance (SR) Motor
• Brushless DC (BLDC) Motor
• Uninterruptable Power Supply (UPS)
The PWM module has the following features:
• Dedicated time base supports TCY/2 PWM edge resolution
• Two output pins for each PWM generator
• Complementary or independent operation for each output pin pair
• Hardware dead time generators for complementary mode
• Output pin polarity programmed by device configuration bits
• Multiple output modes:
- Edge aligned mode
- Center aligned mode
- Center aligned mode with double updates
- Single event mode
• Manual override register for PWM output pins
• Duty cycle updates are configurable to be immediate or synchronized to the PWM
• Hardware fault input pins with programmable function
• Special Event Trigger for synchronizing A/D conversions
• Each output pin associated with the PWM can be individually enabled
The 6-output MCPWM module is useful for single or 3-phase power application, while the 8
MCPWM can support 4-phase motor applications. Table 15-1 provides a feature summary for
6- and 8-output MCPWM modules. Both modules can support multiple single phase loads. The
8-output MCPWM also provides increased flexibility in an application because it supports two
fault pins and two programmable dead times. These features are discussed in greater detail in
subsequent sections.
A simplified block diagram of the MCPWM module is shown in Figure 15-1.
PWMCON1
PWM enable and mode SFRs
PWMCON2
DTCON1
Dead time control SFRs
DTCON2
FLTACON
Fault pin control SFRs
FLTBCON
PWM Generator #1
PDC1
16-bit data bus
Channel 1
Comparator Dead Time PWM1H
Generator and
Override Logic PWM1L
Comparator
PWM Generator Channel 3 PWM3H
#3 Dead Time
Generator and PWM3L
PTMR period register
Override Logic
FLTA
FLTB
Special Event
Comparator Postscaler Special Event Trigger for A/D converter
SEVTCMP 15
Motor Control
PWM
Note 1: Details of PWM Generator #2, #3 and #4 not shown for clarity.
2: Logic within dashed lines not present on 6-output MCPWM module.
Lower Byte:
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
PTOPS<3:0> PTCKPS<1:0> PTMOD<1:0>
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
15
Motor Control
PWM
Lower Byte:
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
PTMR <7:0>
bit 7 bit 0
bit 15 PTDIR: PWM Time Base Count Direction Status bit (Read Only)
1 = PWM time base is counting down
0 = PWM time base is counting up
bit 14-0 PTMR <14:0>: PWM Timebase Register Count Value
Legend:
R = Readable bit W = Writable bit U = Unimplemented, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
PTPER <7:0>
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
SEVTCMP <7:0>
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
R/W-1 R/W-1 R/W-1 R/W-1 R/W-1 R/W-1 R/W-1 R/W-1
PEN4H PEN3H PEN2H PEN1H PEN4L PEN3L PEN2L PEN1L
bit 7 bit 0
Note 1: Reset condition of the PENxH and PENxL bits depend on the value of the PWM/PIN device
configuration bit in the FBORPOR Device Configuration Register.
PWM
Legend:
R = Readable bit W = Writable bit U = Unimplemented, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
U-0 U-0 U-0 U-0 U-0 R/W-0 R/W-0 R/W-0
— — — — — IUE OSYNC UDIS
bit 7 bit 0
Lower Byte:
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
DTAPS<1:0> DTA<5:0>
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
15
Motor Control
PWM
Lower Byte:
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
DTS4A DTS4I DTS3A DTS3I DTS2A DTS2I DTS1A DTS1I
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
R/W-0 U-0 U-0 U-0 R/W-0 R/W-0 R/W-0 R/W-0
FLTAM — — — FAEN4 FAEN3 FAEN2 FAEN1
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
15
Motor Control
PWM
Lower Byte:
R/W-0 U-0 U-0 U-0 R/W-0 R/W-0 R/W-0 R/W-0
FLTBM — — — FBEN4 FBEN3 FBEN2 FBEN1
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
POUT4H POUT4L POUT3H POUT3L POUT2H POUT2L POUT1H POUT1L
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
PWM Duty Cycle #1 bits 7-0
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
15
Motor Control
PWM
Lower Byte:
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
PWM Duty Cycle #2 bits 7-0
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
PWM Duty Cycle #3 bits 7-0
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
PWM Duty Cycle #4 bits 7-0
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Middle Byte:
U-0 U-0 U-0 U-0 U-0 R/P R/P R/P
— — — — — PWMPIN HPOL LPOL
bit 15 bit 8
Lower Byte:
R/P U-0 R/P R/P U-0 U-0 R/P R/P
BOREN — BORV<1:0> — — FPWRT<1:0>
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
P = Programmable configuration bit
Zero match
Period match PTEN
Clock
PTMOD1
Control
PTMOD0
TCY Prescaler
1:1, 1:4, 1:16, 1:64
Timer reset
Up/Down
Gated
Time Base period register Duty Cycle
Load
Gated Period load Immediate
Period load
Update
Enable (IUE)
PTPER
Zero Postscaler
match 1:1-1:16
Interrupt
PTIF
Control
Period
match
PTMOD1
PTMOD0
The PWM time base can be configured for four different modes of operation:
1. Free Running mode
2. Single Event mode
3. Continuous Up/Down Count mode
4. Continuous Up/Down Count mode with interrupts for double-updates.
These four modes are selected by the PTMOD<1:0> control bits (PTCON<1:0>).
Note: The mode of the PWM time base determines the type of PWM signal that is
generated by the module. (See Section 15.4.2, Section 15.4.3 and Section 15.4.4
for more details.)
15
Motor Control
PWM
Figure 15-3: PWM Period Buffer Updates in Free Running Count Mode
PTMR Value
New PTPER value
FCY
PTPER = -1
FPWM • (PTMR Prescaler)
Example:
FCY = 20 MHz
FPWM = 20,000 Hz
PTMR Prescaler = 1:1
20,000,000
PTPER = -1
20,000 • 1
= 1000 -1
= 999
FCY
PTPER = -1
FPWM • (PTMR Prescaler) • 2
Example:
FCY = 20 MHz
FPWM = 20,000 Hz
PTMR Prescaler = 1:1
20,000,000
PTPER = -1
20,000 • 1 • 2
= 500 -1
= 499
log ⎛⎝ ------------------⎞⎠
2T PWM
T CY
Resolution = --------------------------------
log ( 2 )
The PWM resolutions and frequencies are shown in Table 15-2 for a selection of execution
speeds and PTPER values. The PWM frequencies in Table 15-2 are for edge-aligned (Free
Running PTMR) PWM mode. For center aligned modes (Up/Down PTMR mode), the PWM
frequencies will be 1/2 the values as indicated in Table 15-3.
Table 15-2: Example PWM Frequencies and Resolutions, 1:1 Prescaler, Edge Aligned
PWM
PDCx Value for PWM
TCY (FCY) PTPER Value PWM Frequency
100% Resolution
33 ns (30 MHz) 0x7FFF 0xFFFF 16 bits 915 Hz
33 ns (30 MHz) 0x3FF 0x7FF 11 bits 29.3 kHz
50 ns (20 MHz) 0x7FFF 0xFFFF 16 bits 610 Hz
50 ns (20 MHz) 0x1FF 0x3FF 10 bits 39.1 kHz
100 ns (10 MHz) 0x7FFF 0xFFFF 16 bits 305 Hz
100 ns (10 MHz) 0xFF 0x1FF 9 bits 39.1 kHz
200 ns (5 MHz) 0x7FFF 0xFFFF 16 bits 153 Hz
200 ns (5 MHz) 0x7F 0xFF 8 bits 39.1 kHz
Table 15-3: Example PWM Frequencies and Resolutions, 1:1 Prescaler, Center
Aligned PWM
PDCx Value for PWM
TCY (FCY) PTPER Value PWM Frequency
100% Resolution
33 ns (30 MHz) 0x7FFF 0xFFFF 16 bits 458 Hz
33 ns (30 MHz) 0x3FFF 0x7FFF 15 bits 916 Hz
50 ns (20 MHz) 0x7FFF 0xFFFF 16 bits 305 Hz
50 ns (20 MHz) 0x1FFF 0x3FFF 14 bits 1.22 kHz
100 ns (10 MHz) 0x7FFF 0xFFFF 16 bits 153 Hz
100 ns (10 MHz) 0xFFF 0x1FFF 13 bits 1.22 kHz
200 ns (5 MHz) 0x7FFF 0xFFFF 16 bits 76.3 Hz
200 ns (5 MHz) 0x7FF 0xFFF 12 bits 1.22 kHz
The MCPWM module has the ability to produce PWM signal edges with TCY/2 resolution. PTMR
increments every TCY with a 1:1 prescaler. To achieve TCY/2 edge resolution, PDCx<15:1> is
compared to PTMR<14:0> to determine a duty cycle match. PDCx<0> determines whether the
PWM signal edge will occur at the TCY or the TCY/2 boundary. When a 1:4, 1:16 or a 1:64
prescaler is used with the PWM time base, PDCx<0> is compared to the MSbit of the prescaler
counter clock to determine when the PWM edge should occur.
PTMR and PDCx resolutions are depicted in Figure 15-5. It is shown that PTMR resolution is TCY
and PDCx resolution is TCY/2 for 1:1 prescaler selection.
Figure 15-5: PTMR and PDCx Resolution Timing Diagram. Free Running Mode and 1:1
Prescaler Selection
TCY
PTPER = 10
TCY
PTMR
PDCx = 14 TCY/2
PDCx = 15
15
Motor Control
PWM
14 0 N-bit Prescaler
PTMR N 2 1 TCY
15
15-bit Edge
PWM Edge Event
comparison Logic
15 15 1 0 1-Bit Comparison
PDCx
Note: PDCx<0> is compared to the FOSC/2 signal when the prescaler is 1:1.
PTPER
PDC2
PWM2H
Period
PDC1
PDC2
PTEN
PWM2H
PWM1H
PWMIF
15
Motor Control
PWM
Period/2
PTPER
PTMR
PDC1 Value
PDC2
PWM1H
PWM2H
PDCx
Value
Period
Note: Any write to the PDCx registers will immediately update the duty cycle when the
PWM time base is disabled (PTEN = 0). This allows a duty cycle change to take
effect before PWM signal generation is enabled.
When the PWM time base is operating in the Up/Down Counting mode (PTMOD<1:0> = 10),
duty cycles are updated when the value of the PTMR register is zero and the PWM time base
begins to count upwards. Figure 15-10 indicates the times when the duty cycle updates occur
for this mode of the PWM time base.
When the PWM time base is in the Up/Down Counting mode with double updates
(PTMOD<1:0> = 11), duty cycles are updated when the value of the PTMR register is zero and
when the value of the PTMR register matches the value in the PTPER register. Figure 15-11
indicates the times when the duty cycle updates occur for this mode of the PWM time base.
PWM output
PTMR Value
PTIF
Figure 15-11: Duty Cycle Update Times in Up/Down Count Mode with Double Updates
PWM output
PTMR Value
Figure 15-12: Duty Cycle Update Times When Immediate Updates Are Enabled (IUE = 1)
PWM Output
PTMR Value
+V
3 Phase
1H 2H 3H Load
1L 2L 3L
The Complementary mode is selected for each PWM I/O pin pair by clearing the appropriate
PMODx bit in PWMCON1. The PWM I/O pins are set to complementary mode by default upon a
device reset.
Figure 15-15: Dead Time Unit Block Diagram for One Output Pin Pair
Zero Compare
Dead Time
Select Logic
PWM
Generator
Input
PWM Generator
PWMxH
Dead time = 0
PWMxL
PWMxH
Non-zero
dead time
PWMxL
Note: The dead time assignment logic is only applicable to dsPIC variants that contain the
8-output PWM module. The 6-output PWM module uses dead time A only.
The DTCON2 register contains control bits that allow the two programmable dead times to be
assigned to each of the complementary outputs. There are two dead time assignment control
bits for each of the complementary outputs. For example, the DTS1A and DTS1I control bits
select the dead times to be used for the PWM1H/PWM1L complementary output pair. The pair
of dead time selection control bits are referred to as the ‘dead-time-select-active’ and
‘dead-time-select-inactive’ control bits, respectively. The function of each bit in a pair is as
follows:
• The DTSxA control bit selects the dead time that is to be inserted before the high-side
output is driven active.
• The DTSxI control bit selects the dead time that is to be inserted before the low-side PWM
active is driven active.
Table 15-4 summarizes the function of each dead time selection control bit.
Dead Time
DT =
Prescale Value • TCY 15
Motor Control
Table 15-5 shows example dead time ranges as a function of the input clock prescaler selected
and the device operating frequency.
1H
1L
Figure 15-18: PWM Block Diagram for One Output Pin Pair, Independent Mode
PWMxL
Note: Dead time insertion is still performed when PWM channels are overridden manually.
15
Motor Control
PWM
1 2 3 4 5 6
PWM3H
PWM3L
PWM2H
PWM2L
PWM1H
PWM1L
Note: Switching times between states 1-6 are controlled by user software.
The state switch is controlled by writing a new value to OVDCON.
STATE
1 2 3 4
PWM4H
PWM4L
PWM3H
PWM3L
PWM2H
PWM2L
PWM1H
PWM1L
Note: Switching times between states 1-4 are controlled by user software. The state switch
is controlled by writing a new value to OVDCON. The PWM outputs are operated in the
independent mode for this example.
15
Motor Control
PWM
When a fault pin is enabled and driven low, the PWM pins are immediately driven to their
programmed fault states regardless of the values in the PDCx and OVDCON registers. The fault
action has priority over all other PWM control registers.
A fault condition must be cleared by the external circuitry driving the fault input pin high and
clearing the fault interrupt flag (Latched mode only). After the fault pin condition has been
cleared, the PWM module will restore the PWM output signals on the next PWM period or
half-period boundary. For edge aligned PWM generation, the PWM outputs will be restored when
PTMR = 0. For center aligned PWM generation, the PWM outputs will be restored when PTMR
= 0 or PTMR = PTPER, whichever event occurs first.
An exception to these rules will occur when the PWM time base is disabled (PTEN = 0). If the
PWM time base is disabled, the PWM module will restore the PWM output signals immediately
after the fault condition has been cleared.
15
Motor Control
PWM
Note: When the FLTA pin is programmed for Latched mode, the PWM outputs will not
return to the Fault B states or normal operation until the Fault A interrupt flag has
been cleared and the FLTA pin is de-asserted.
Note: The user should exercise caution when controlling the fault inputs in software. If the
TRIS bit for the fault pin is cleared, then the fault input cannot be driven externally.
PWM Period
PTMR
FLTA
Note: Arrows indicate the time when normal PWM operation is restored.
PTMR
Return to
normal
Duty cycle = 50% operation
FLTA
FLTAIF
PTMR
Return to
normal
Duty cycle = 50% operation
FLTA
FLTB
Note: Immediate updates must be disabled (IUE = 0) in order to use the PWM update
lockout feature.
; This code example drives all PWM pins to the inactive state
; before executing the PWRSAV instruction.
The Fault A and Fault B input pins, if enabled to control the PWM pins via the FLTxCON registers,
will continue to function normally when the device is in Sleep mode. If one of the fault pins is
driven low while the device is in Sleep, the PWM outputs will be driven to the programmed fault
states in the FLTxCON register.
The fault input pins also have the ability to wake the CPU from Sleep mode. If the fault interrupt
enable bit is set (FLTxIE = 1), then the device will wake from Sleep when the fault pin is driven
low. If the fault pin interrupt priority is greater than the current CPU priority, then program
execution will start at the fault pin interrupt vector location upon wake-up. Otherwise, execution
will continue from the next instruction following the PWRSAV instruction.
15
Motor Control
PWM
DS70062D-page 15-40
IPC10 00A8 — FLTAIP<2:0> — — — — — — — — — — — — 0100 0100 0100 0100
IPC11 00AA — — — — — — — — — — — — — FLTBIP<2:> 0000 0000 0000 0000
PTCON 01C0 PTEN — PTSIDL — — — — — PTOPS<3:0> PTCKPS<1:0> PTMOD<1:0> 0000 0000 0000 0000
PTMR 01C2 PTDIR PWM Time Base register 0000 0000 0000 0000
PTPER 01C4 — PWM Time Base Period register 0111 1111 1111 1111
SEVTCMP 01C6 SEVTDIR PWM Special Event Compare register 0000 0000 0000 0000
PWMCON1 01C8 — — — — PMOD4 PMOD3 PMOD2 PMOD1 PEN4H PEN3H PEN2H PEN1H PEN4L PEN3L PEN2L PEN1L 0000 0000 0000 0000
PWMCON2 01CA — — — — SEVOPS<3:0> — — — — — IUE OSYNC UDIS 0000 0000 0000 0000
DTCON1 01CC DTBPS<1:0> Dead Time B Value register DTAPS<1:0> Dead Time A Value register 0000 0000 0000 0000
DTCON2 01CE — — — — — — — — DTS4A DTS4I DTS3A DTS3I DTS2A DTS2I DTS1A DTS1I 0000 0000 0000 0000
FLTACON 01D0 FAOV4H FAOV4L FAOV3H FAOV3L FAOV2H FAOV2L FAOV1H FAOV1L FLTAM — — — FAEN4 FAEN3 FAEN2 FAEN1 0000 00-0 0000 0000
FLTBCON 01D2 FBOV4H FBOV4L FBOV3H FBOV3L FBOV2H FBOV2L FBOV1H FBOV1L FLTBM — — — FBEN4 FBEN3 FBEN2 FBEN1 0000 0000 0000 0000
OVDCON 01D4 POVD4H POVD4L POVD3H POVD3L POVD2H POVD2L POVD1H POVD1L POUT4H POUT4L POUT3H POUT3L POUT2H POUT2L POUT1H POUT1L 1111 1111 00-0 0000
PDC1 01D6 PWM Duty Cycle #1 register 0000 0000 0000 0000
PDC2 01D8 PWM Duty Cycle #2 register 0000 0000 0000 0000
PDC3 01DA PWM Duty Cycle #3 register 0000 0000 0000 0000
PDC4 01DC PWM Duty Cycle #4 register 0000 0000 0000 0000
Note 1: Reset state of PENxx control bits depends on the state of the PWMPIN device configuration bit.
dsPIC30F Family Reference Manual
2: Shaded register and bit locations not implemented for the 6-output MCPWM module.
3: The IUE bit is not implemented on the dsPIC30F6010 device.
DS70062D-page 15-41
PWM
15
Motor Control
dsPIC30F Family Reference Manual
Note: Please visit the Microchip web site (www.microchip.com) for additional Application
Notes and code examples for the dsPIC30F Family of devices.
15
Motor Control
PWM
NOTES:
Quadrature Encoder
Interface (QEI)
Section 16. Quadrature Encoder Interface (QEI)
HIGHLIGHTS
This section of the manual contains the following major topics:
QEA
QEB
INDX
01 00 10 11
Reverse Travel
QEA
QEB
INDX
11 10 00 01
Quadrature Encoder
The QEI consists of quadrature decoder logic to interpret the Phase A and Phase B signals and
Interface (QEI)
an up/down counter to accumulate the count. Digital glitch filters on the inputs condition the
input signal. Figure 16-2 depicts a simplified block diagram of the QEI Module.
The QEI module includes:
• Three input pins for two phase signals and index pulse
• Programmable digital noise filters on inputs
• Quadrature decoder providing counter pulses and count direction
• 16-bit up/down position counter
• Count direction status
• X2 and X4 count resolution
• 2 modes of position counter reset
• General Purpose16-bit timer/counter mode
• Interrupts generated by QEI or counter events
Clock TCY
Divider
Digital
QEA Filter
CLOCK
Digital Quadrature 16-Bit Up/Down Reset
QEB Filter Decoder Counter
DIR
Logic (POSCNT)
Comparator/ EQUAL
Digital
INDX Filter Zero Detect
Note: The POSCNT register allows byte accesses, however, reading the register in byte
mode may result in partially updated values in subsequent reads. Either use word
mode reads/writes or ensure that the counter is not counting during byte operations.
Register 16-1 and Register 16-3 define the QEI module control and digital filter control registers,
QEICON and DFLTCON.
Quadrature Encoder
Upper Byte:
Interface (QEI)
R/W-0 U-0 R/W-0 R-0 R/W-0 R/W-0 R/W-0 R/W-0
CNTERR — QEISIDL INDEX UPDN QEIM<2:0>
bit 15 bit 8
Lower Byte:
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
SWPAB PCDOUT TQGATE TQCKPS<1:0> POSRES TQCS UDSRC
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Quadrature Encoder
Upper Byte:
Interface (QEI)
U-0 U-0 U-0 U-0 U-0 U-0 U-0 R/W-0
— — — — — — — CEID
bit 15 bit 8
Lower Byte:
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
QEOUT QECK<2:0> INDOUT INDCK<2:0>
bit 7 bit 0
Note: The available control bits in the DFLTCON Register may vary depending on the dsPIC30F device
that is used. Refer to Register 16-2 and Register 16-3 for details.
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Register 16-3: DFLTCON: Digital Filter Control Register (All dsPIC30F devices except dsPIC30F6010)
Upper Half:
U-0 U-0 U-0 U-0 U-0 R/W-0 R/W-0 R/W-0
— — — — — IMV<1:0> CEID
bit 15 bit 8
Lower Half:
R/W-0 R/W-0 U-0 U-0 U-0 U-0
QEOUT QECK<2:0> — — — —
bit 7 bit 0
Note: The available control bits in the DFLTCON Register may vary depending on the dsPIC30F device
that is used. Refer to Register 16-2 and Register 16-3 for details.
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
y = Value set from configuration bits on POR or BOR
Quadrature Encoder
The digital noise filter section is responsible for rejecting noise on the incoming index and
Interface (QEI)
quadrature signals. Schmitt trigger inputs and a three-clock cycle delay filter combine to reject
low level noise and large, short duration noise spikes that typically occur in noise-prone
applications such as a motor system applications.
The filter ensures that the filtered output signals are not permitted to change until a stable value
has been registered for three consecutive filter cycles.
The rate of the filter clocks determines the low passband of the filter. A slower filter clock results
in a passband rejecting lower frequencies than a faster filter clock. The filter clock is the device
FCY clock divided by a programmable divisor.
Setting the QEOUT bit (DFLTCON<7>) enables the filter for channels QEA and QEB. The
QECK<2:0> bits (DFLTCON<6:4>) specify the filter clock divisor used for channels QEA and
QEB. Setting the INDOUT bit (DFLTCON<3>) enables the filter for the index channel. The
INDCK<2:0> bits (DFLTCON<2:0>) specify the filter clock divisor used for the index channel. At
reset, the filters for all channels are disabled.
Some devices do not have separate control bits for the QEx input digital filters and the INDX
input digital filter. For these devices, the QEOUT and QECK<2:0> control bits set the digital filter
characteristics for both the QEA/QEB and INDX pins. See Register 16-2 and Register 16-3 for
more information.
Figure 16-4 depicts a simplified block diagram for the digital noise filter.
Non-filtered
0 QEn
Filter
Filtered 1 Output
QEOUT
J Q
CK
QEn K
D Q D Q D Q D Q
pin
TCY CK CK CK CK CK CK CK
Clock
Divider TCY
Circuit
QECK<2:0>
Note: ‘n’ denotes the phase input, A or B.
Figure 16-5: Signal Propagation Through Filter, 1:1 Filter Clock Divide
TCY
QEn Pin
QEn Filter
QEA
QEB
count_clock
POSCNT +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 -1 -1 -1 -1 -1 -1 -1 -1 -1
UPDN
When QEIM1 = 0, the ‘x2’ measurement mode is selected and the QEI logic only looks at the
rising and falling edge of the Phase A input for the position counter increment rate. Every rising
and falling edge of the Phase A signal causes the position counter to increment or decrement.
The Phase B signal is still utilized for the determination of the counter direction, exactly like the
x4 measurement mode.
QEA
QEB
count_clock
POSCNT +1 +1 +1 +1 +1 -1 -1 -1 -1
UPDN
Quadrature Encoder
Interface (QEI)
The lead/lag test is performed by the quadrature decoder logic to determine the phase
relationship of the QEA and QEB signals and hence whether to increment or decrement the
POSCNT register. The Table 16-1 clarifies the lead/lag test.
Quadrature Encoder
Interface (QEI)
When the QEIM0 bit is ‘1’, the position counter will reset on a match of the position count with
predetermined high and low values. The index pulse reset mechanism is not utilized.
For this mode the position counter reset mechanism operates as follows: (See Figure 16-8 for
related timing details).
- If the encoder is traveling in the forward direction e.g., QEA leads QEB, and the value
in the POSCNT register matches the value in the MAXCNT register, POSCNT will
reset to zero on the next occurring quadrature pulse edge that increments
POSCNT. An interrupt event is generated on this rollover event.
- If the encoder is travelling in the reverse direction e.g., QEB leads QEA, and the value
in the POSCNT register counts down to ‘0’, the POSCNT is loaded with the value in
the MAXCNT register on the next occurring quadrature pulse edge that
decrements POSCNT. An interrupt event is generated on this underflow event.
When using MAXCNT as a position limit, remember the position counter will count at either 2X
or 4X of the encoder counts. For standard rotary encoders, the appropriate value to write to
MAXCNT would be 4N – 1 for 4x position mode and 2N – 1 for 2x position mode, where N is the
number of counts per revolution of the encoder.
For absolute position information where the range of the system exceeds 216, it is also
appropriate to load a value of 0xFFFF into the MAXCNT register. The module will generate an
interrupt on rollover or underflow of the position counter.
QEA
QEB
count_clock
POSCNT 0001 0002 0003 0004 0005 0006 0000 0001 0002 0003 0002 0001 0000 0006 0005 0004 0003 0002 0001
UPDN
0006
MAXCNT
Quadrature
State 1 2 3 4 1 2 3 4 1 2 2 1 4 3 2 1 4 3 2 1 4 3 2
QEA
QEB
INDX
count_clock
POSCNT 00E3 00E4 00E5 00E6 0000 0001 0002 0003 0004 0005 0004 0003 0002 0001 0000 00E6 00E5 00E4 00E3 00E2 00E1 00E0
UPDN
Incremental encoders from different manufacturers use differing timing for the index pulse. The
index pulse may be aligned to any of the 4 quadrature states and may have a pulse width of
either a full cycle (4 quadrature states), a half cycle (2 quadrature states) or a quarter cycle
(1 quadrature state). Index pulses of a full cycle width or a half cycle width are normally termed
‘ungated’ and index pulses of a quarter cycle width are normally termed ‘gated’.
Regardless of the type of index pulse provided, the QEI maintains symmetry of the count as the
wheel reverses direction. This means the index pulse must reset the position counter at the
same relative quadrature state transition as the wheel rotates in the forward or reverse
direction.
For example, in Figure 16-9, the first index pulse is recognized and resets POSCNT as the
quadrature state changes from 4 to 1 as highlighted in the diagram. The QEI latches the state of
this transition. Any subsequent index pulse detection will use that state transition for the reset.
As the wheel reverses, the index pulse again occurs, however the reset of the position counter
cannot occur until the quadrature state changes from 1 to 4, again highlighted in the diagram.
Note: The QEI index logic ensures that the POSCNT register is always adjusted at the
same position relative to the index pulse, regardless of the direction of travel.
Quadrature Encoder
Interface (QEI)
The IMV<2:0> control bits are available on some dsPIC devices that have the QEI module. (See
Register 16-3). These control bits allow the user to select the state of the QEA and QEB signals
for which an index pulse reset will occur.
Devices that do not have these control bits will select the QEA and QEB states automatically
during the first occurrence of an index pulse.
The INDEX bit (QEICON<12>) provides status of the logic state on the index pin. This status bit
is very useful in position control systems during the “homing” sequence, where the system
searches for a reference position. The index bit indicates the status of the index pin after being
processed by the digital filter, if it is enabled.
16.5.3.4 Using the Index Pin and MAXCNT for Error Checking
When the counter operates in reset on index pulse mode, the QEI will also detect POSCNT
register boundary conditions. This may be used to detect system errors in the incremental
encoder system.
For example, assume a wheel encoder has 100 lines. When utilized in x4 measurement mode
and reset on the index pulse, the counter should count from 0 to 399 (0x018E) and reset. If the
POSCNT register ever achieves the values of 0xFFFF or 0x0190, some sort of system error
has occurred.
The contents of the POSCNT register is compared with MAXCNT + 1, if counting up, and with
0xFFFF, if counting down. If the QEI detects one of these values, a position count error
condition is generated by setting the CNTERR bit (QEICON<15>) and optionally generating a
QEI interrupt.
If the CEID control bit (DFLTCON<8>) is cleared (default), then a QEI interrupt will be generated
when a position count error is detected. If the CEID control bit is set, then an interrupt will not
occur.
The position counter continues to count encoder edges after detecting a position count error. No
interrupt is generated for subsequent position count error events until CNTERR is cleared by
the user.
The position counter reset enable bit, POSRES (QEICON<2>) enables reset of the position
counter when the index pulse is detected. This bit only applies when the QEI module is
configured for modes, QEIM<2:0> = ‘100’ or ‘110’.
If the POSRES bit is set to a logic ‘1’ then the position counter is reset when the index pulse is
detected as described in this section.
If the POSRES bit is set to a logic ‘0’, then the position counter is not reset when the index pulse
is detected. The position counter will continue counting up or down and be reset on the rollover
or underflow condition. The QEI continues to generate interrupts on the detection of the index
pulse.
Note: Changing operational modes, i.e., from QEI to Timer or Timer to QEI will not affect
the Timer/Position Count Register contents.
TQGATE
TQCS
TQCKPS
TCY 2
00
Gated Prescaler
01 1, 8, 64, 256
TCY
Programmable Synchronize TQGATE
QEA 10
Digital Filter Det
11 TQGATE
1 QEIF
D Q Event
UDSRC CK Q Flag
0
UPDN 0
16-bit Up/Down Counter
Programmable (POSCNT)
QEB 1
Digital Filter Reset
Comparator/Zero Detect
Equal
Quadrature Encoder
Interface (QEI)
The QEI timer can increment or decrement. This is a unique feature over most other timers.
When the timer is configured to count up, the timer (POSCNT) will increment until the count
matches the period register (MAXCNT). The timer resets to zero and restarts incrementing.
When the timer is configured to count down, the timer (POSCNT) will decrement until the count
matches the period register (MAXCNT). The timer resets to zero and restarts decrementing.
When the timer is configured to count down some general operation guidelines must be
followed for correct operation.
1. The MAXCNT register will serve as the period match register but because the counter is
decrementing, the desired match value is 2 count. For example, to count 0x1000 clocks,
the period register must be loaded with 0xF000.
2. On a match condition, the timer resets to zero.
Either an I/O pin or a SFR control bit specify the count direction control.
Control bit UDSRC (QEICON<0>) determines what controls the timer count direction state.
When UDSRC = 1, the timer count direction is controlled from the QEB pin. If the QEB pin is ’1’,
the count direction will be incrementing. If the QEB pin is ‘0’, the count direction will be
decrementing.
When UDSRC = 0, the timer count direction is controlled from the UPDN bit (QEICON<11>).
When UPDN = 1, the timer increments. When UPDN = 0, the timer decrements.
TQGATE
UDSRC
TQCS
QEA QEB INDX UPDN
QEIM<2:0>
pin pin pin pin
Quadrature Encoder
Interface (QEI)
16.9.1 When the Device Enters Sleep
When the device enters Sleep mode, the QEI will cease all operations. POSCNT will stop at the
current value. The QEI will not respond to active signals on the QEA, QEB, INDX or UPDN pins.
The QEICON register will remain unchanged.
If the QEI is configured as a timer/counter, QEIM<2:0> = ‘001’, and the clock is provided
externally, TQCS = 1, the module will also cease operation during Sleep mode.
When the module wakes up, the quadrature decoder will accept the next transition on the QEA
or QEB signals and compare that transition to the last transition before Sleep to determine the
next action.
DS70063C-page 16-20
ADPCFG PCFG15 PCFG14 PCFG13 PCFG12 PCFG11 PCFG10 PCFG9 PCFG8 PCFG7 PCFG6 PCFG5 PCFG4 PCFG3 PCFG2 PCFG1 PCFG0 0000 0000 0000 0000
INTCON1 NSTDIS — — — — OVATE OVBTE COVTE — — — MATHERR ADDRERR STKERR OSCFAIL — 0000 0000 0000 0000
INTCON2 ALTIVT — — — — — — — — — — INT4EP INT3EP INT2EP INT1EP INT0EP 0000 0000 0000 0000
IFS2 — — — FLTBIF FLTAIF LVDIF DCIIF QEIIF PWMIF C2IF INT4IF INT3IF OC8IF OC7IF OC6IF OC5IF 0000 0000 0000 0000
IEC2 — — — FLTBIE FLTAIE LVDIE DCIIE QEIIE PWMIE C2IE INT4IE INT3IE OC8IE OC7IE OC6IE OC5IE 0000 0000 0000 0000
IPC10 — FLTAIP<2:0> — LVDIP<2:0> — DCIIP<2:0> — QEIIP<2:0> 0100 0100 0100 0100
Note: The available control bits in the DFLTCON Register may vary depending on the dsPIC30F device that is used. Refer to Register 16-2 and Register 16-3 for
details.
Note: On many devices, the QEI pins are multiplexed with analog input pins. You will need to ensure that the QEI pins are configured as digital pins using the
ADPCFG control register.
dsPIC30F Family Reference Manual
Quadrature Encoder
Interface (QEI)
Question 1: I have initialized the QEI, but the POSCNT Register does not seem to
change when quadrature signals are applied to the QEA/QEB pins.
Answer: On many devices, the QEI pins are multiplexed with analog input pins. You will need to
ensure that the QEI pins are configured as digital pins using the ADPCFG control register.
Question: 3 My encoder has a 90° Index Pulse and the count does not reset properly.
Answer: Depending on how the count clock is generated and which quadrature state transition
is used for the index pulse, a 1/4 cycle index pulse may not be recognized before the required
transition. To fix this, use a filter on the quadrature clocks which has a higher filter prescaler
than that of the index pulse. This has the effect of delaying the quadrature clocks somewhat,
allowing for proper detection of the index pulse.
Figure 16-11: Reset by Index Mode (90° Index Pulse) – Up/Down Position Counter
Quadrature
State 2 3 4 1 2 3 4 1 2 2 1 4 3 2 1 4 3 2 1 4 3 2
QEA Filter
QEB Filter
INDX
count_clock
POSCNT 00E4 0000 0001 0002 0003 0002 0001 0000 00E4 00E3 00E2
UPDN
Note: Please visit the Microchip web site (www.microchip.com) for additional Application
Notes and code examples for the dsPIC30F Family of devices.
Quadrature Encoder
Revision A
Interface (QEI)
This is the initial released revision of this document.
Revision B
This revision provides expanded information for the dsPIC30F Quadrature Encoder Interface
(QEI) module.
Revision C
This revision incorporates all known errata at the time of this document update.
NOTES:
HIGHLIGHTS
This section of the manual contains the following major topics:
17
17.1 Introduction .................................................................................................................. 17-2
Converter
10-bit A/D
17.2 Control Registers ......................................................................................................... 17-4
17.3 A/D Result Buffer ......................................................................................................... 17-4
17.4 A/D Terminology and Conversion Sequence ............................................................. 17-11
17.5 A/D Module Configuration.......................................................................................... 17-13
17.6 Selecting the Voltage Reference Source ................................................................... 17-13
17.7 Selecting the A/D Conversion Clock .......................................................................... 17-13
17.8 Selecting Analog Inputs for Sampling ........................................................................ 17-14
17.9 Enabling the Module .................................................................................................. 17-16
17.10 Specifying the Sample/Conversion Sequence........................................................... 17-16
17.11 How to Start Sampling ............................................................................................... 17-17
17.12 How to Stop Sampling and Start Conversions ........................................................... 17-18
17.13 Controlling Sample/Conversion Operation................................................................. 17-29
17.14 Specifying How Conversion Results are Written Into the Buffer ................................ 17-30
17.15 Conversion Sequence Examples............................................................................... 17-31
17.16 A/D Sampling Requirements...................................................................................... 17-45
17.17 Reading the A/D Result Buffer................................................................................... 17-46
17.18 Transfer Function ....................................................................................................... 17-47
17.19 A/D Accuracy/Error .................................................................................................... 17-47
17.20 Connection Considerations........................................................................................ 17-47
17.21 Initialization ................................................................................................................ 17-48
17.22 A/D Conversion Speeds............................................................................................. 17-49
17.23 Operation During Sleep and Idle Modes.................................................................... 17-55
17.24 Effects of a Reset....................................................................................................... 17-55
17.25 Special Function Registers Associated with the 10-bit A/D Converter ...................... 17-56
17.26 Design Tips ................................................................................................................ 17-57
17.27 Related Application Notes.......................................................................................... 17-58
17.28 Revision History ......................................................................................................... 17-59
17.1 Introduction
The dsPIC30F 10-bit A/D converter has the following key features:
• Successive Approximation (SAR) conversion
• Up to 1 Msps conversion speed
• Up to 16 analog input pins
• External voltage reference input pins
• Four unipolar differential S/H amplifiers
• Simultaneous sampling of up to four analog input pins
• Automatic Channel Scan mode
• Selectable conversion trigger source
• 16 word conversion result buffer
• Selectable Buffer Fill modes
• Four result alignment options
• Operation during CPU Sleep and Idle modes
A block diagram of the 10-bit A/D is shown in Figure 17-1. The 10-bit A/D converter can have up
to 16 analog input pins, designated AN0-AN15. In addition, there are two analog input pins for
external voltage reference connections. These voltage reference inputs may be shared with
other analog input pins. The actual number of analog input pins and external voltage reference
input configuration will depend on the specific dsPIC30F device. Refer to the device data sheet
for further details.
The analog inputs are connected via multiplexers to four S/H amplifiers, designated CH0-CH3.
One, two, or four of the S/H amplifiers may be enabled for acquiring input data. The analog input
multiplexers can be switched between two sets of analog inputs during conversions. Unipolar
differential conversions are possible on all channels using certain input pins (see Figure 17-1).
An Analog Input Scan mode may be enabled for the CH0 S/H amplifier. A Control register
specifies which analog input channels will be included in the scanning sequence.
The 10-bit A/D is connected to a 16-word result buffer. Each 10-bit result is converted to one of
four 16-bit output formats when it is read from the buffer.
AVDD
VREF+
AVSS
VREF-
AN0 AN0
AN3 +
CH1
S/H ADC
AN6 -
AN9
VREF- 17
AN1 10-bit Result Conversion Logic
AN1
AN4 + CH2
Converter
10-bit A/D
S/H
AN7 -
Data Format
AN10 16-word, 10-bit
VREF- Dual Port
RAM
Bus Interface
AN2 AN2
AN5 +
CH3
S/H
AN8 - CH1,CH2,
AN11 CH3,CH0 Sample/Sequence
VREF- Sample Control
0000
0001 Input
0010 Switches Input MUX
AN3 0011 Control
AN4 0100
AN5 0101
AN6 0110
AN7 0111
AN8 1000
AN9 1001
AN10 1010
AN11 1011
AN12 1100
AN13 1101
AN14 1110
Note: VREF+, VREF- inputs may be shared with other analog inputs. See device data sheet for details.
Lower Byte:
R/W-0 R/W-0 R/W-0 U-0 R/W-0 R/W-0 R/W-0 R/C-0
HC, HS HC, HS
SSRC<2:0> — SIMSAM ASAM SAMP DONE
bit 7 bit 0 17
bit 15 ADON: A/D Operating Mode bit
Converter
10-bit A/D
1 = A/D converter module is operating
0 = A/D converter is off
bit 14 Unimplemented: Read as ‘0’
bit 13 ADSIDL: Stop in Idle Mode bit
1 = Discontinue module operation when device enters Idle mode
0 = Continue module operation in Idle mode
bit 12-10 Unimplemented: Read as ‘0’
bit 9-8 FORM<1:0>: Data Output Format bits
11 = Signed Fractional (DOUT = sddd dddd dd00 0000)
10 = Fractional (DOUT = dddd dddd dd00 0000)
01 = Signed Integer (DOUT = ssss sssd dddd dddd)
00 = Integer (DOUT = 0000 00dd dddd dddd)
bit 7-5 SSRC<2:0>: Conversion Trigger Source Select bits
111 = Internal counter ends sampling and starts conversion (auto convert)
110 = Reserved
101 = Reserved
100 = Reserved
011 = Motor Control PWM interval ends sampling and starts conversion
010 = GP Timer3 compare ends sampling and starts conversion
001 = Active transition on INT0 pin ends sampling and starts conversion
000 = Clearing SAMP bit ends sampling and starts conversion
bit 4 Unimplemented: Read as ‘0’
bit 3 SIMSAM: Simultaneous Sample Select bit (only applicable when CHPS = 01 or 1x)
1 = Samples CH0, CH1, CH2, CH3 simultaneously (when CHPS = 1x)
or
Samples CH0 and CH1 simultaneously (when CHPS = 01)
0 = Samples multiple channels individually in sequence
bit 2 ASAM: A/D Sample Auto-Start bit
1 = Sampling begins immediately after last conversion completes. SAMP bit is auto set
0 = Sampling begins when SAMP bit set
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
HC = Hardware clear HS = Hardware set C = Clearable by software
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
R-0 U-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
BUFS — SMPI<3:0> BUFM ALTS
bit 7 bit 0
17
bit 15-13 VCFG<2:0>: Voltage Reference Configuration bits
Converter
10-bit A/D
A/D VREFH A/D VREFL
000 AVDD AVSS
001 External VREF+ pin AVSS
010 AVDD External VREF- pin
011 External VREF+ pin External VREF- pin
1XX AVDD AVSS
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
R/W-0 U-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
ADRC — ADCS<5:0>
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
CH123NA<1:0> CH123SA CH0NA CH0SA<3:0>
bit 7 bit 0
17
bit 15-14 CH123NB<1:0>: Channel 1, 2, 3 Negative Input Select for MUX B Multiplexer Setting bits
Same definition as bits 6-7 (Note)
Converter
10-bit A/D
bit 13 CH123SB: Channel 1, 2, 3 Positive Input Select for MUX B Multiplexer Setting bit
Same definition as bit 5 (Note)
bit 12 CH0NB: Channel 0 Negative Input Select for MUX B Multiplexer Setting bit
Same definition as bit 4 (Note)
bit 11-8 CH0SB<3:0>: Channel 0 Positive Input Select for MUX B Multiplexer Setting bits
Same definition as bits 3-0 (Note)
bit 7-6 CH123NA<1:0>: Channel 1, 2, 3 Negative Input Select for MUX A Multiplexer Setting bits
11 = CH1 negative input is AN9, CH2 negative input is AN10, CH3 negative input is AN11
10 = CH1 negative input is AN6, CH2 negative input is AN7, CH3 negative input is AN8
0x = CH1, CH2, CH3 negative input is VREF-
bit 5 CH123SA: Channel 1, 2, 3 Positive Input Select for MUX A Multiplexer Setting bit
1 = CH1 positive input is AN3, CH2 positive input is AN4, CH3 positive input is AN5
0 = CH1 positive input is AN0, CH2 positive input is AN1, CH3 positive input is AN2
bit 4 CH0NA: Channel 0 Negative Input Select for MUX A Multiplexer Setting bit
1 = Channel 0 negative input is AN1
0 = Channel 0 negative input is VREF-
bit 3-0 CH0SA<3:0>: Channel 0 Positive Input Select for MUX A Multiplexer Setting bits
1111 = Channel 0 positive input is AN15
1110 = Channel 0 positive input is AN14
1101 = Channel 0 positive input is AN13
||
||
||
0001 = Channel 0 positive input is AN1
0000 = Channel 0 positive input is AN0
Note: The analog input multiplexer supports two input setting configurations, denoted MUX A and MUX
B. ADCHS<15:8> determine the settings for MUX B, and ADCHS<7:0> determine the settings
for MUX A. Both sets of control bits function identically.
Note: The ADCHS register description and functionality will vary depending on the number of A/D
inputs available on the selected device. Please refer to the specific device data sheet for
additional details on this register.
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
PCFG7 PCFG6 PCFG5 PCFG4 PCFG3 PCFG2 PCFG1 PCFG0
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
CSSL7 CSSL6 CSSL5 CSSL4 CSSL3 CSSL2 CSSL1 CSSL0
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Converter
10-bit A/D
SAMP control bit in the user software or automatically by a conversion trigger source.
Conversion time is the time required for the A/D converter to convert the voltage held by the S/H
amplifier. The A/D is disconnected from the analog input pin at the end of the sample time. The
A/D converter requires one A/D clock cycle (TAD) to convert each bit of the result plus one
additional clock cycle. A total of 12 TAD cycles are required to perform the complete conversion.
When the conversion time is complete, the result is loaded into one of 16 A/D Result registers
(ADCBUF0...ADCBUFF), the S/H can be reconnected to the input pin, and a CPU interrupt may
be generated.
The sum of the sample time and the A/D conversion time provides the total conversion time.
There is a minimum sample time to ensure that the S/H amplifier will give the desired accuracy
for the A/D conversion (see Section 17.16 “A/D Sampling Requirements”). Furthermore, there
are multiple input clock options for the A/D converter. The user must select an input clock option
that does not violate the minimum TAD specification.
The 10-bit A/D converter allows many options for specifying the sample/convert sequence. The
sample/convert sequence can be very simple, such as the one shown in Figure 17-3. The
example in Figure 17-3 uses only one S/H amplifier. A more elaborate sample/convert sequence
performs multiple conversions using more than one S/H amplifier. The 10-bit A/D converter can
use two S/H amplifiers to perform two conversions in a sample/convert sequence or four S/H
amplifiers with four conversions. The number of S/H amplifiers, or channels per sample, used in
the sample/convert sequence is determined by the CHPS control bits.
A sample/convert sequence that uses multiple S/H channels can be simultaneously sampled or
sequentially sampled, as controlled by the SIMSAM bit (ADCON1<3>). Simultaneously sampling
multiple signals ensures that the snapshot of the analog inputs occurs at precisely the same time
for all inputs. Sequential sampling takes a snapshot of each analog input just before conversion
starts on that input, and the sampling of multiple inputs is not correlated.
AN0
AN1
AN2
AN3
Simultaneous Sequential
Sampling Sampling
The start time for sampling can be controlled in software by setting the SAMP control bit. The
start of the sampling time can also be controlled automatically by the hardware. When the A/D
converter operates in the Auto-Sample mode, the S/H amplifier(s) is reconnected to the analog
input pin at the end of the conversion in the sample/convert sequence. The auto-sample function
is controlled by the ASAM control bit (ADCON1<2>).
The conversion trigger source ends the sampling time and begins an A/D conversion or a
sample/convert sequence. The conversion trigger source is selected by the SSRC control bits.
The conversion trigger can be taken from a variety of hardware sources, or can be controlled
manually in software by clearing the SAMP control bit. One of the conversion trigger sources is
an auto-conversion. The time between auto-conversions is set by a counter and the A/D clock.
The Auto-Sample mode and auto-conversion trigger can be used together to provide endless
automatic conversions without software intervention.
An interrupt may be generated at the end of each sample/convert sequence or multiple
sample/convert sequences as determined by the value of the SMPI control bits ADCON2<5:2>.
The number of sample/convert sequences between interrupts can vary between 1 and 16. The
user should note that the A/D conversion buffer holds 16 results when the SMPI value is selected.
The total number of conversion results between interrupts is the product of the channels per
sample and the SMPI value. The total number of conversions between interrupts should not
exceed the buffer length.
Converter
10-bit A/D
• Select how conversion results are presented in the buffer ADCON1<9:8>
• Select interrupt rate ADCON2<5:9>
• Turn on A/D module ADCON1<15>
2. Configure A/D interrupt (if required)
• Clear ADIF bit
• Select A/D interrupt priority
The options for each configuration step are described in the subsequent sections.
17.6 Selecting the Voltage Reference Source
The voltage references for A/D conversions are selected using the VCFG<2:0> control bits
(ADCON2<15:13>). The upper voltage reference (VREFH) and the lower voltage reference
(VREFL) may be the internal AVDD and AVSS voltage rails or the VREF+ and VREF- input pins.
The external voltage reference pins may be shared with the AN0 and AN1 inputs on low pin count
devices. The A/D converter can still perform conversions on these pins when they are shared
with the VREF+ and VREF- input pins.
The voltages applied to the external reference pins must meet certain specifications. Refer to the
“Electrical Specifications” section of the device data sheet for further details.
Note: External VREF+ amd VREF- must be selected for conversion rates above 500 ksps.
See Section 17.22 “A/D Conversion Speeds” for further details.
TCY (ADCS + 1)
TAD =
2
2TAD
ADCS = –1
TCY
For correct A/D conversions, the A/D conversion clock (TAD) must be selected to ensure a
minimum TAD time of 83.33 nsec (see Section 17.22 “A/D Conversion Speeds” for further
details).
The A/D converter has a dedicated internal RC clock source that can be used to perform
conversions. The internal RC clock source should be used when A/D conversions are performed
while the dsPIC30F is in Sleep mode. The internal RC oscillator is selected by setting the ADRC
bit (ADCON3<7>). When the ADRC bit is set, the ADCS<5:0> bits have no effect on the A/D
operation.
17.8 Selecting Analog Inputs for Sampling
All Sample-and-Hold Amplifiers have analog multiplexers (see Figure 17-1) on both their
non-inverting and inverting inputs to select which analog input(s) are sampled. Once the
sample/convert sequence is specified, the ADCHS bits determine which analog inputs are
selected for each sample.
Additionally, the selected inputs may vary on an alternating sample basis or may vary on a
repeated sequence of samples.
The same analog input can be connected to two or more sample and hold channels to improve
conversion rates.
Note: Different devices will have different numbers of analog inputs. Verify the analog
input availability against the device data sheet.
Note 1: When reading the A/D Port register, any pin configured as an analog input reads as
a ‘0’.
2: Analog levels on any pin that is defined as a digital input (including the AN15:AN0
pins) may cause the input buffer to consume current that is out of the device’s
specification.
The ALTS bit (ADCON2<0>) causes the module to alternate between two sets of inputs that are
selected during successive samples.
The inputs specified by CH0SA<3:0>, CH0NA, CHXSA and CHXNA<1:0> are collectively called
the MUX A inputs. The inputs specified by CH0SB<3:0>, CH0NB, CHXSB and CHXNB<1:0> are
collectively called the MUX B inputs. When the ALTS bit is ‘1’ , the module will alternate between
the MUX A inputs on one sample and the MUX B inputs on the subsequent sample.
For channel 0, if the ALTS bit is ‘0’, only the inputs specified by CH0SA<3:0> and CH0NA are
selected for sampling.
If the ALTS bit is ‘1’, on the first sample/convert sequence for channel 0, the inputs specified by
CH0SA<3:0> and CH0NA are selected for sampling. On the next sample convert sequence for 17
channel 0, the inputs specified by CH0SB<3:0> and CH0NB are selected for sampling. This
pattern will repeat for subsequent sample conversion sequences.
Converter
10-bit A/D
Note that if multiple channels (CHPS = 01 or 1x) and simultaneous sampling (SIMSAM = 1) are
specified, alternating inputs will change every sample because all channels are sampled on
every sample time. If multiple channels (CHPS = 01 or 1x) and sequential sampling (SIMSAM
= 0) are specified, alternating inputs will change only on each sample of a particular channel.
Channel 0 has the ability to scan through a selected vector of inputs. The CSCNA bit
(ADCON2<10>) enables the CH0 channel inputs to be scanned across a selected number of
analog inputs. When CSCNA is set, the CH0SA<3:0> bits are ignored.
The ADCSSL register specifies the inputs to be scanned. Each bit in the ADCSSL register
corresponds to an analog input. Bit 0 corresponds to AN0, bit 1 corresponds to AN1 and so on.
If a particular bit in the ADCSSL register is ‘1’, the corresponding input is part of the scan
sequence. The inputs are always scanned from lower to higher numbered inputs, starting at the
first selected channel after each interrupt occurs.
Note: If the number of scanned inputs selected is greater than the number of samples
taken per interrupt, the higher numbered inputs will not be sampled.
The ADCSSL bits only specify the input of the positive input of the channel. The CH0NA bit still
selects the input of the negative input of the channel during scanning.
If the ALTS bit is ‘1’, the scanning only applies to the MUX A input selection. The MUX B input
selection, as specified by the CH0SB<3:0>, will still select the alternating channel 0 input. When
the input selections are programmed in this manner, the channel 0 input will alternate between a
set of scanning inputs specified by the ADCSSL register and a fixed input specified by the
CH0SB bits.
The analog input multiplexer can be configured so that the same input pin is connected to two or
more sample and hold channels. The A/D converts the value held on one S/H channel, while the
second S/H channel acquires a new input sample.
As with the channel 0 inputs, the ALTS bit (ADCON2<0>) causes the module to alternate
between two sets of inputs that are selected during successive samples for channel 1,2 and 3.
The MUX A inputs specified by CHXSA and CHXNA<1:0> always select the input when
ALTS = 0.
The MUX A inputs alternate with the MUX B inputs specified by CHXSB and CHXNB<1:0> when
ALTS = 1.
17.9 Enabling the Module
When the ADON bit (ADCON1<15>) is ‘1’, the module is in Active mode and is fully powered and
functional.
When ADON is ‘0’, the module is disabled. The digital and analog portions of the circuit are
turned off for maximum current savings.
In order to return to the Active mode from the Off mode, the user must wait for the analog stages
to stabilize. For the stabilization time, refer to the Electrical Characteristics section of the device
data sheet.
Note: The SSRC<2:0>, SIMSAM, ASAM, CHPS<1:0>, SMPI<3:0>, BUFM and ALTS bits,
as well as the ADCON3 and ADCSSL registers, should not be written to while
ADON = 1. This would lead to indeterminate results.
Converter
10-bit A/D
00 x Sample CH0, Convert CH0 1 Figure 17-4,
Figure 17-5,
Figure 17-6,
Figure 17-7,
Figure 17-10,
Figure 17-11,
Figure 17-14,
Figure 17-15
01 0 Sample CH0, Convert CH0 2
Sample CH1, Convert CH1
1x 0 Sample CH0, Convert CH0 4 Figure 17-9,
Sample CH1, Convert CH1 Figure 17-13,
Sample CH2, Convert CH2 Figure 17-20
Sample CH3, Convert CH3
01 1 Sample CH0, CH1 simultaneously 1 Figure 17-18
Convert CH0
Convert CH1
1x 1 Sample CH0, CH1, CH2, CH3 1 Figure 17-8
simultaneously
Convert CH0 Figure 17-12,
Convert CH1 Figure 17-16,
Convert CH2 Figure 17-17,
Convert CH3 Figure 17-9,
17.11.2 Automatic
Setting the ASAM bit (ADCON1<2>) causes the A/D to automatically begin sampling a channel
whenever a conversion is not active on that channel. One of several options can be used to end
sampling and complete the conversions. If the SIMSAM bit specifies sequential sampling,
sampling on a channel resumes after the conversion of that channel completes. If the SIMSAM
bit specifies simultaneous sampling, sampling on a channel resumes after the conversion of all
channels completes. For an example, see Figure 17-5.
Note: The available conversion trigger sources may vary depending on the dsPIC30F
device variant. Please refer to the specific device data sheet for the available
conversion trigger sources.
Note: The SSRC selection bits should not be changed when the A/D module is enabled.
If the user wishes to change the conversion trigger source, the A/D module should
be disabled first by clearing the ADON bit (ADCON1<15>).
17.12.1 Manual
When SSRC<2:0> = 000, the conversion trigger is under software control. Clearing the SAMP
bit (ADCON1<1>) starts the conversion sequence.
Figure 17-4 is an example where setting the SAMP bit initiates sampling and clearing the SAMP
bit terminates sampling and starts conversion. The user software must time the setting and
clearing of the SAMP bit to ensure adequate sampling time of the input signal. See Example 17-1
for code example.
Figure 17-4: Converting 1 Channel, Manual Sample Start, Manual Conversion Start
ADCLK
TSAMP TCONV
SAMP
DONE
ADCBUF0
Figure 17-5 is an example where setting the ASAM bit initiates automatic sampling and clearing
the SAMP bit terminates sampling and starts conversion. After the conversion completes, the
module will automatically return to a sampling state. The SAMP bit is automatically set at the start
of the sample interval. The user software must time the clearing of the SAMP bit to ensure
adequate sampling time of the input signal, understanding that the time between clearing of the
SAMP bit includes the conversion time as well as the sampling time. See Example 17-2 for code
example.
Figure 17-5: Converting 1 Channel, Automatic Sample Start, Manual Conversion Start
ADCLK
TAD0
TSAMP TCONV
TAD0
TSAMP TCONV 17
SAMP
Converter
10-bit A/D
DONE
ADCBUF0
TSMP = SAMC<4:0>*TAD
When using only 1 S/H channel or simultaneous sampling, SAMC must always be programmed
for at least one clock cycle. When using multiple S/H channels with sequential sampling,
programming SAMC for zero clock cycles will result in the fastest possible conversion rate. See
Example 17-3 for code example.
Figure 17-6: Converting 1 Channel, Manual Sample Start, TAD Based Conversion Start
ADCLK
TSAMP TCONV
= 16 TAD
SAMP
DONE
ADCBUF0
As shown in Figure 17-7, using the Auto-Convert Conversion Trigger mode (SSRC = 111) in
combination with the Auto-Sample Start mode (ASAM = 1), allows the A/D module to schedule
sample/conversion sequences with no intervention by the user or other device resources. This
“Clocked” mode allows continuous data collection after module initialization. See Example 17-4
for code example.
Note: This A/D configuration must be enabled for the conversion rate of 750 ksps (see
Section 17.22 “A/D Conversion Speeds” for details)
Figure 17-7: Converting 1 Channel, Auto-Sample Start, TAD Based Conversion Start 17
ADCLK
Converter
10-bit A/D
TSAMP TCONV TSAMP TCONV
= 16 TAD = 16 TAD
SAMP
DONE
ADCBUF0
ADCBUF1
As shown in Figure 17-8 when using simultaneous sampling, the SAMC value specifies the
sampling time. In the example, SAMC specifies a sample time of 3 TAD. Because automatic
sample start is active, sampling will start on all channels after the last conversion ends and will
continue for 3 A/D clocks. See Example 17-5 for code example.
Figure 17-8: Converting 4 Channels, Auto-Sample Start, TAD Conversion Start, Simultaneous Sampling
ADCLK
TCONV TCONV TCONV TCONV TCONV TCONV
TSAMP
ch0_samp
ch1_samp
ch2_samp
ch3_samp
ADCBUF0
ADCBUF1
ADCBUF2
ADCBUF3
DONE
SAMP
ADCSSL = 0;
ADCON3 = 0x0302; // Auto Sampling 3 Tad, Tad = internal 2 Tcy
ADCON2 = 0x030C; // CHPS = 1x implies simultaneous ...
// sample CH0 to CH3
// SMPI = 0011 for interrupt after 4 converts
As shown in Figure 17-9 when using sequential sampling, the sample time precedes each
conversion time. In the example, 3 TAD clocks are added for sample time for each channel.
Note: This A/D configuration must be enabled for the configuration rates of 1 Msps and
600 ksps (see Section 17.22 “A/D Conversion Speeds” for further details).
Figure 17-9: Converting 4 Channels, Auto-Sample Start, TAD Conversion Start, Sequential Sampling
ADCLK
TCONV TCONV TCONV TCONV TCONV
17
TSAMP TSAMP
ch0_samp
Converter
10-bit A/D
ch1_samp
ch2_samp
ch3_samp
ADRES(0)
ADRES(1)
ADRES(2)
ADRES(3)
DONE =0
SAMP
17.12.2.4 Sample Time Considerations Using Clocked Conversion Trigger and Automatic Sampling
Different sample/conversion sequences provide different available sampling times for the S/H
channel to acquire the analog signal. The user must ensure the sampling time exceeds the
sampling requirements, as outlined in Section 17.16 “A/D Sampling Requirements”.
Assuming that the module is set for automatic sampling and using a clocked conversion trigger,
the sampling interval is determined by the sample interval specified by the SAMC bits.
If the SIMSAM bit specifies simultaneous sampling or only one channel is active, the sampling
time is the period specified by the SAMC bit.
Equation 17-3: Available Sampling Time, Simultaneous Sampling
If the SIMSAM bit specifies sequential sampling, the total interval used to convert all channels is
the number of channels times the sampling time and conversion time. The sampling time for an
individual channel is the total interval minus the conversion time for that channel.
Equation 17-4: Available Sampling Time, Simultaneous Sampling
When SSRC<2:0> = 001, the A/D conversion is triggered by an active transition on the INT0 pin.
The INT0 pin may be programmed for either a rising edge input or a falling edge input.
The A/D is configured in this Trigger mode by setting SSRC<2:0> = 010. When a match occurs
between the 32-bit timer TMR3/TMR2 and the 32-bit Combined Period register PR3/PR2, a
special ADC trigger event signal is generated by Timer3. This feature does not exist for the
TMR5/TMR4 timer pair. Refer to Section 12. “Timers” for more details.
The PWM module has an event trigger that allows A/D conversions to be synchronized to the
PWM time base. When SSRC<2:0> = 011, the A/D sampling and conversion times occur at any
user programmable point within the PWM period. The special event trigger allows the user to
minimize the delay between the time when A/D conversion results are acquired and the time
when the duty cycle value is updated. Refer to Section 15. “Motor Control PWM” for more
details.
Using the modes where an external event trigger pulse ends sampling and starts conversion
(SSRC = 001, 10, 011) may be used in combination with auto-sampling (ASAM = 1) to cause
the A/D to synchronize the sample conversion events to the trigger pulse source. For example,
in Figure 17-11 where SSRC = 010 and ASAM = 1, the A/D will always end sampling and start
conversions synchronously with the timer compare trigger event. The A/D will have a sample
conversion rate that corresponds to the timer comparison event rate. See Example 17-6 for code
example.
Figure 17-10: Converting 1 Channel, Manual Sample Start, Conversion Trigger Based Conversion Start
Conversion
Trigger
ADCLK
TSAMP TCONV
SAMP
ADCBUF0
Figure 17-11: Converting 1 Channel, Auto-Sample Start, Conversion Trigger Based Conversion Start
Conversion
Trigger
ADCLK
TSAMP TCONV TSAMP TCONV
SAMP
DONE
ADCBUF0
17
ADCBUF1
Converter
10-bit A/D
Example 17-6: Converting 1 Channel, Auto-Sample Start, Conversion Trigger Based
Conversion Start Code
As shown in Figure 17-12 when using simultaneous sampling, the sampling will start on all
channels after setting the ASAM bit or when the last conversion ends. Sampling will stop and
conversions will start when the conversion trigger occurs.
Figure 17-12: Converting 4 Channels, Auto-Sample Start, Trigger Conversion Start, Simultaneous Sampling
TSEQ
Conversion
Trigger
ADCLK
TCONV TCONV TCONV TCONV
TSAMP TSAMP
ch0_samp
ch1_samp
ch2_samp
ch3_samp
ADCBUF0
ADCBUF1
ADCBUF2
ADCBUF3
Cleared
DONE in software
SAMP
As shown in Figure 17-13 when using sequential sampling, sampling for a particular channel
will stop just prior to converting that channel and will resume after the conversion has stopped.
Figure 17-13: Converting 4 Channels, Auto-Sample Start, Trigger Conversion Start, Sequential Sampling
TSEQ
Conversion
Trigger
ADCLK
TCONV TCONV TCONV TCONV
17
ch0_samp
TSAMP
TSAMP
Converter
10-bit A/D
ch1_samp
TSAMP
ch2_samp
TSAMP
ch3_samp
TSAMP
ADCBUF0
ADCBUF1
ADCBUF2
ADCBUF3
Cleared
DONE in software
SAMP
Different sample/conversion sequences provide different available sampling times for the S/H
channel to acquire the analog signal. The user must ensure the sampling time exceeds the
sampling requirements, as outlined in Section 17.16 “A/D Sampling Requirements”.
Assuming that the module is set for automatic sampling and an external trigger pulse is used as
the conversion trigger, the sampling interval is a portion of the trigger pulse interval.
If the SIMSAM bit specifies simultaneous sampling, the sampling time is the trigger pulse period
less the time required to complete the specified conversions.
Equation 17-5: Available Sampling Time, Simultaneous Sampling
If the SIMSAM bit specifies sequential sampling, the sampling time is the trigger pulse period less
the time required to complete only one conversion.
Equation 17-6: Available Sampling Time, Sequential Sampling
Converter
10-bit A/D
sample/conversion sequences after starting sampling and re-occur on each equivalent number
of samples. Note that the interrupts are specified in terms of samples and not in terms of
conversions or data samples in the buffer memory.
When the SIMSAM bit specifies sequential sampling, regardless of the number of channels
specified by the CHPS bits, the module samples once for each conversion and data sample in
the buffer. Therefore, the value specified by the SMPI bits will correspond to the number of data
samples in the buffer, up to the maximum of 16.
When the SIMSAM bit specifies simultaneous sampling, the number of data samples in the buffer
is related to the CHPS bits. Algorithmically, the channels/sample times the number of samples
will result in the number of data sample entries in the buffer. To avoid loss of data in the buffer
due to overruns, the SMPI bits must be set to the desired buffer size divided by the channels per
sample.
Disabling the A/D interrupt is not done with the SMPI bits. To disable the interrupt, clear the ADIE
analog module interrupt enable bit.
17.14 Specifying How Conversion Results are Written Into the Buffer
As conversions are completed, the module writes the results of the conversions into the A/D
result buffer. This buffer is a RAM array of sixteen 10-bit words. The buffer is accessed through
16 address locations within the SFR space named ADCBUF0...ADCBUFF.
User software may attempt to read each A/D conversion result as it is generated, however, this
would consume too much CPU time. Generally, to simplify the code, the module will fill the buffer
with results and then generate an interrupt when the buffer is filled.
Converter
10-bit A/D
Figure 17-14: Converting One Channel 16 Times/Interrupt
Conversion
Trigger TSAMP TSAMP TSAMP TSAMP
ADCLK
TCONV TCONV TCONV TCONV
ASAM
SAMP
DONE
ADCBUF0
ADCBUF1
ADCBUFE
ADCBUFF
ADIF
17.15.2 Example: A/D Conversions While Scanning Through All Analog Inputs
Figure 17-15 and Table 17-3 illustrate a very typical setup where all available analog input
channels are sampled by one sample and hold channel, CH0, and converted. The set CSCNA
bit specifies scanning of the A/D inputs to the CH0 positive input. Other conditions are similar to
Subsection 17.15.1.
Initially, the AN0 input is sampled by CH0 and converted. The result is stored in the ADCBUF
buffer. Then the AN1 input is sampled and converted. This process of scanning the inputs
repeats 16 times until the buffer is full and then the module generates an interrupt. The entire
process will then repeat.
Converter
10-bit A/D
Trigger TSAMP TSAMP TSAMP TSAMP
ADCLK
TCONV TCONV TCONV TCONV
ASAM
SAMP
DONE
ADCBUF0
ADCBUF1
ADCBUFE
ADCBUFF
ADIF
17.15.3 Example: Sampling Three Inputs Frequently While Scanning Four Other Inputs
Figure 17-16 and Table 17-4 shows how the A/D converter could be configured to sample three
inputs frequently using sample/hold channels CH1, CH2 and CH3; while four other inputs are
sampled less frequently by scanning them using sample/hold channel CH0. In this case, only
MUX A inputs are used, and all 4 channels are sampled simultaneously. Four different inputs
(AN4, AN5, AN6, AN7) are scanned in CH0, whereas AN0, AN1 and AN2 are the fixed inputs for
CH1, CH2 and CH3, respectively. Thus, in every set of 16 samples, AN0, AN1 and AN2 would
be sampled 4 times, while AN4, AN5, AN6 and AN7 would be sampled only once each.
Figure 17-16: Converting Three Inputs, Four Times and Four Inputs, One Time/Interrupt
17
Conversion
Trigger TSAMP TSAMP TSAMP
Converter
ADCLK
10-bit A/D
TCONVTCONVTCONVTCONV TCONVTCONVTCONVTCONV TCONVTCONVTCONVTCONV
ASAM
SAMP
DONE
ADCBUF0
ADCBUF1
ADCBUF2
ADCBUF3
ADCBUFC
ADCBUFD
ADCBUFE
ADCBUFF
ADIF
Table 17-4: Converting Three Inputs, Four Times and Four Inputs, One Time/Interrupt
Figure 17-17: Converting Four Inputs, One Time/Interrupt Using Dual 8-Word Buffers
17
Conversion
Trigger TSAMP TSAMP TSAMP
Converter
10-bit A/D
ADCLK
TCONVTCONVTCONVTCONV TCONVTCONVTCONVTCONV TCONVTCONVTCONVTCONV
SAMP
BUFS
ADCBUF0
ADCBUF1
ADCBUF2
ADCBUF3
ADCBUF8
ADCBUF9
ADCBUFA
ADCBUFB
ADIF
Table 17-5: Converting Four Inputs, One Time/Interrupt Using Dual 8-Word Buffers
Converter
10-bit A/D
channels.
Figure 17-18: Converting Two Sets of Two Inputs Using Alternating Input Selections
Conversion
Trigger TSAMP TSAMP TSAMP TSAMP TSAMP
ADCLK
TCONVTCONV TCONVTCONV TCONVTCONV TCONVTCONV TCONVTCONV
Input to
CH0 AN1 AN15 AN15 AN1 AN15
Input to
CH1 AN0 AN3-AN9 AN3-AN9 AN0 AN3-AN9
ASAM
SAMP
Cleared
DONE in software
BUFS
ADCBUF0
ADCBUF1
ADCBUF2
ADCBUF3
ADCBUF4
ADCBUF5
ADCBUF6
ADCBUF7
ADCBUF8
ADCBUF9
ADCBUFA
ADCBUFB
ADIF
Cleared by Software
Table 17-6: Converting Two Sets of Two Inputs Using Alternating Input Selections
Converter
10-bit A/D
Trigger TSAMP TSAMP TSAMP
ADCLK
TCONVTCONVTCONVTCONV TCONVTCONVTCONVTCONV TCONVTCONVTCONVTCONV
ASAM
SAMP
DONE
ADCBUF0
ADCBUF1
ADCBUF2
ADCBUF3
ADCBUFC
ADCBUFD
ADCBUFE
ADCBUFF
ADIF
Converter
Conversion
10-bit A/D
Trigger TSAMP TSAMP TSAMP
ADCLK
TCONVTCONVTCONVTCONV TCONVTCONVTCONVTCONV TCONVTCONVTCONVTCONV
ASAM
SAMP
DONE
ADCBUF0
ADCBUF1
ADCBUF2
ADCBUF3
ADCBUFC
ADCBUFD
ADCBUFE
ADCBUFF
ADIF
Converter
10-bit A/D
operation.
At least 1 TAD time period should be allowed between conversions for the sample time. For more
details, see the device electrical specifications.
CHOLD
VA CPIN I leakage = DAC capacitance
VT = 0.6V ± 500 nA = 4.4 pF
VSS
Note: CPIN value depends on device package and is not tested. Effect of CPIN negligible if Rs ≤ 5 kΩ.
RAM Contents: d09 d08 d07 d06 d05 d04 d03 d02 d01 d00
Read to Bus:
Integer 0 0 0 0 0 0 d09 d08 d07 d06 d05 d04 d03 d02 d01 d00
Signed Integer d09 d09 d09 d09 d09 d09 d09 d08 d07 d06 d05 d04 d03 d02 d01 d00
Fractional (1.15) d09 d08 d07 d06 d05 d04 d03 d02 d01 d00 0 0 0 0 0 0
Signed Fractional (1.15) d09 d08 d07 d06 d05 d04 d03 d02 d01 d00 0 0 0 0 0 0
1023/1024 11 1111 1111 0000 0011 1111 1111 0000 0001 1111 1111 1111 1111 1100 0000 0111 1111 1100 0000
= 1023 = 511 = 0.999 = 0.499
1022/1024 11 1111 1110 0000 0011 1111 1110 0000 0001 1111 1110 1111 1111 1000 0000 0111 1111 1000 0000
= 1022 = 5 10 = 0.998 = 0.498
•••
513/1024 10 0000 0001 0000 0010 0000 0001 0000 0000 0000 0001 1000 0000 0100 0000 0 000 0000 0100 0000
= 513 = 1 = 0.501 = 0.001
512/1024 10 0000 0000 0000 0010 0000 0000 0000 0000 0000 0000 1000 0000 0000 0000 0000 0000 0000 0000
= 512 = 0 = 0.500 = 0.000
511/1024 01 1111 1111 0000 0001 1111 1111 1111 1111 1111 1111 0111 1111 1100 0000 1111 1111 1100 0000
= 511 = -1 = .499 = -0.001
•••
1/1024 00 0000 0001 0000 0000 0000 0001 1111 1110 0000 0001 0000 0000 0100 0000 1000 0000 0100 0000
= 1 = -511 = 0.001 = -0.499
0/1024 00 0000 0000 0000 0000 0000 0000 1111 1110 0000 0000 0000 0000 0000 0000 1000 0000 0000 0000
= 0 = -512 = 0.000 = -0.500
Converter
10-bit A/D
11 1111 1111 (= 1023)
11 1111 1110 (= 1022)
00 0000 0001 (= 1)
00 0000 0000 (= 0)
VREFL VREFH
VREFH – VREFL 512*(VREFH – VREFL) 1023*(VREFH – VREFL)
VREFL + VREFL + VREFL +
1024 1024 1024
(VINH – VINL)
17.21 Initialization
Example 17-7 shows a simple initialization code example for the A/D module.
In this particular configuration, all 16 analog input pins, AN0-AN15, are set up as analog inputs.
Operation in Idle mode is disabled output data is in unsigned fractional format, and AVDD and
AVSS are used for VREFH and VREFL. The start of sampling, as well as start of conversion
(conversion trigger), are performed manually in software. The CH0 S/H amplifier is used for
conversions. Scanning of inputs is disabled, and an interrupt occurs after every sample/convert
sequence (1 conversion result). The A/D conversion clock is TCY/2.
Since sampling is started manually by setting the SAMP bit (ADCON1<1>) after each conversion
is complete, the auto-sample time bits, SAMC<4:0> (ADCON3<12:8>), are ignored. Moreover,
since the start of conversion (i.e., end of sampling) is also triggered manually, the SAMP bit
needs to be cleared each time a new sample needs to be converted.
TAD Sampling
A/D Speed Rs Max VDD Temperature A/D Channels Configuration
Minimum Time Min
Up to 1 83.33 ns 12 TAD 500 Ω 4.5V to 5.5V -40°C to +85°C
17
VREF- VREF+
MSps(1)
CH1, CH2 or CH3
ANx
S/H
ADC
CH0
Converter
10-bit A/D
S/H
CHX
ANx
S/H ADC
Up to 600 138.89 ns 12 TAD 500 Ω 3.0V to 5.5V -40°C to +125°C VREF- VREF+
ksps(1)
CH1, CH2 or CH3
ANx
S/H
ADC
CH0
S/H
ANx CHX
S/H ADC
ANx or VREF-
ANx CHX
S/H ADC
ANx or VREF-
Note 1: External VREF- and VREF+ pins must be used for correct operation. See Figure 17-25 for recommended
circuit.
The following figure depicts the recommended circuit for the conversion rates above 500 ksps.
The dsPIC30F6010 is shown as an example.
VDD
80
79
78
77
76
75
74
73
72
69
68
67
66
65
64
63
62
61
VSS
VDD
1 60
2 59
3 58
4 57
5 56
55 VDD VDD VDD
6
7 54
C8 C7 C6
8 53 1 μF 0.1 μF 0.01 μF
9 52
10 VSS
dsPIC30F6010
VDD VSS 50
VDD 49 VDD
13 VDD
14 47
VDD VDD VDD
15 46
16 45
C5 C4 C3
17 44 1 μF 0.1 μF 0.01 μF
18 43
19 42
VDD 20 41
VREF+
VREF-
AVDD
AVSS
VDD
VSS
21
22
27
28
29
30
33
34
35
36
37
38
39
40
R2
10
C2 C1 VDD
R1
0.1 μF 0.01 μF 10
VDD
The configuration procedures below give the required setup values for the conversion speeds
above 500 ksps.
For conversions at 1 Msps for a single analog input, at least two sample and hold channels must
be enabled. The analog input multiplexer must be configured so that the same input pin is con-
nected to both sample and hold channels. The A/D converts the value held on one S/H channel,
while the second S/H channel acquires a new input sample.
The A/D converter can also be used to sample multiple analog inputs using multiple sample and
hold channels. In this case, the total 1 Msps conversion rate is divided among the different input
signals. For example, four inputs can be sampled at a rate of 250 ksps for each signal or two
inputs could be sampled at a rate of 500 ksps for each signal. Sequential sampling must be used
in this configuration to allow adequate sampling time on each input.
The following configuration items are required to achieve a 1 Msps conversion rate.
• Comply with conditions provided in Table 17-9.
• Connect external VREF+ and VREF- pins following the recommended circuit shown in 17
Figure 17-26.
• Set SSRC<2:0> = 111 in the ADCON1 register to enable the auto convert option.
Converter
10-bit A/D
• Enable automatic sampling by setting the ASAM control bit in the ADCON1 register.
• Enable sequential sampling by clearing the SIMSAM bit in the ADCON1 register.
• Enable at least two sample and hold channels by writing the CHPS<1:0> control bits in the
ADCON2 register.
• Configure at least 2 conversions between interrupts, since at least two sample and hold
channels, by writing the SMPI<3:0> control bits in the ADCON2 register.
• Configure the A/D clock period to be:
1
= 83.33 ns
12 x 1,000,000
Figure 17-26: Converting 1 Input Pin Using Two Channels at 1Msps, Auto-Sample Start, 12 TAD Sampling
Time
ADCLK
TSAMP TCONV TCONV TCONV TCONV
ch0_samp
ch1_samp
ADRES(0)
DONE = 0
SAMP
Figure 17-27: Converting 1 Channel at 750 ksps, Auto-Sample Start, 2 TAD Sampling Time
TSAMP TSAMP
= 2 TAD = 2 TAD
ADCLK
TCONV TCONV
= 12 TAD = 12 TAD
SAMP
DONE
17
ADCBUF0
Converter
10-bit A/D
ADCBUF1
Example 17-9: Converting 1 Channel at 750 ksps, Auto-Sample Start, 2 TAD Sampling
Time Code Example
ADPCFG = 0xFFFB; // all PORTB = Digital; RB2 = analog
ADCON1 = 0x00E0; // SSRC bit = 111 implies internal
// counter ends sampling and starts
// converting.
ADCHS = 0x0002; // Connect RB2/AN2 as CH0 input
// in this example RB2/AN2 is the input
ADCSSL = 0;
ADCON3 = 0x0203; // Sample time = 2Tad, Tad = 95.24 ns @ 21 MIPS
// which will give 1 / (14 * 95.24 ns) = 750 ksps
ADCON2 = 0x6004; // Select external VREF+ and VREF- pins
// Interrupt after every 2 samples
ADCON1bits.ADON = 1; // turn ADC ON
while (1) // repeat continuously
{
ADCValue = 0; // clear value
ADC16Ptr = &ADCBUF0; // initialize ADCBUF pointer
IFS0bits.ADIF = 0; // clear ADC interrupt flag
ADCON1bits.ASAM = 1; // auto start sampling
// for 31Tad then go to conversion
while (!IFS0bits.ADIF); // conversion done?
ADCON1bits.ASAM = 0; // yes then stop sample/convert
for (count = 0; count <2; count++) // average the 2 ADC value
ADCValue = ADCValue + *ADC16Ptr++;
ADCValue = ADCValue >> 1;
} // repeat
When performing conversions at 600 ksps for a single analog input, at least two sample and hold
channels must be enabled. The analog input multiplexer must be configured so that the same
input pin is connected to both sample and hold channels. The A/D converts the value held on one
S/H channel, while the second S/H channel acquires a new input sample.
The A/D converter can also be used to sample multiple analog inputs using multiple sample and
hold channels. In this case, the total 600 ksps conversion rate is divided among the different input
signals. For example, four inputs can be sampled at a rate of 150 ksps for each signal or two
inputs could be sampled at a rate of 300 ksps for each signal. Sequential sampling must be used
in this configuration to allow adequate sampling time on each input.
The following configuration items are required to achieve a 600 ksps conversion rate.
• Comply with conditions provided in Table 17-9.
• Connect external VREF+ and VREF- pins following the recommended circuit shown in
Figure 17-10.
• Set SSRC<2:0> = 111 in the ADCON1 register to enable the auto convert option.
• Enable automatic sampling by setting the ASAM control bit in the ADCON1 register.
• Enable sequential sampling by clearing the SIMSAM bit in the ADCON1 register.
• Enable at least two sample and hold channels by writing the CHPS<1:0> control bits in the
ADCON2 register.
• Configure at least 2 conversions between interrupts, since at least two sample and hold
channels, by writing the SMPI<3:0> control bits in the ADCON2 register.
• Configure the A/D clock period to be:
1
= 138.89 ns
12 x 600,000
Converter
10-bit A/D
The A/D module can operate during Sleep mode if the A/D clock source is set to the internal A/D
RC oscillator (ADRC = 1). This eliminates digital switching noise from the conversion. When the
conversion is completed, the DONE bit will be set and the result loaded into the A/D result buffer,
ADCBUF.
If the A/D interrupt is enabled (ADIE = 1), the device will wake-up from Sleep when the A/D
interrupt occurs. Program execution will resume at the A/D Interrupt Service Routine if the A/D
interrupt is greater than the current CPU priority. Otherwise, execution will continue from the
instruction after the PWRSAV instruction that placed the device in Sleep mode.
If the A/D interrupt is not enabled, the A/D module will then be turned off, although the ADON bit
will remain set.
To minimize the effects of digital noise on the A/D module operation, the user should select a
conversion trigger source that ensures the A/D conversion will take place in Sleep mode. The
automatic conversion trigger option can be used for sampling and conversion in Sleep
(SSRC<2:0> = 111). To use the automatic conversion option, the ADON bit should be set in the
instruction prior to the PWRSAV instruction.
Note: For the A/D module to operate in Sleep, the A/D clock source must be set to RC
(ADRC = 1).
DS70064D-page 17-56
INTCON1 0080 NSTDIS — — — — OVATE OVBTE COVTE — — — MATHERR ADDRERR STKERR OSCFAIL — 0000 0000 0000 0000
INTCON2 0082 ALTIVT — — — — — — — — — — INT4EP INT3EP INT2EP INT1EP INT0EP 0000 0000 0000 0000
IFS0 0084 CNIF MI2CIF SI2CIF NVMIF ADIF U1TXIF U1RXIF SPI1IF T3IF T2IF OC2IF IC2IF T1IF OC1IF IC1IF INT0 0000 0000 0000 0000
IEC0 008C CNIE MI2CIE SI2CIE NVMIE ADIE U1TXIE U1RXIE SPI1IE T3IE T2IE OC2IE IC2IE T1IE OC1IE IC1IE INT0IE 0000 0000 0000 0000
IPC2 0098 — ADIP<2:0> — U1TXIP<2:0> — U1RXIP<2:0> — SPI1IP<2:0> 0100 0100 0100 0100
ADCBUF0 0280 ADC Data Buffer 0 uuuu uuuu uuuu uuuu
ADCBUF1 0282 ADC Data Buffer 1 uuuu uuuu uuuu uuuu
ADCBUF2 0284 ADC Data Buffer 2 uuuu uuuu uuuu uuuu
ADCBUF3 0286 ADC Data Buffer 3 uuuu uuuu uuuu uuuu
ADCBUF4 0288 ADC Data Buffer 4 uuuu uuuu uuuu uuuu
ADCBUF5 028A ADC Data Buffer 5 uuuu uuuu uuuu uuuu
ADCBUF6 028C ADC Data Buffer 6 uuuu uuuu uuuu uuuu
ADCBUF7 028E ADC Data Buffer 7 uuuu uuuu uuuu uuuu
ADCBUF8 0290 ADC Data Buffer 8 uuuu uuuu uuuu uuuu
ADCBUF9 0292 ADC Data Buffer 9 uuuu uuuu uuuu uuuu
ADCBUFA 0294 ADC Data Buffer 10 uuuu uuuu uuuu uuuu
dsPIC30F Family Reference Manual
Question 1: How can I optimize the system performance of the A/D converter?
Answer:
1. Make sure you are meeting all of the timing specifications. If you are turning the module
off and on, there is a minimum delay you must wait before taking a sample. If you are
changing input channels, there is a minimum delay you must wait for this as well and
finally, there is TAD, which is the time selected for each bit conversion. This is selected in
ADCON3 and should be within a certain range as specified in the Electrical Characteris-
tics. If TAD is too short, the result may not be fully converted before the conversion is
terminated, and if TAD is made too long, the voltage on the sampling capacitor can decay
before the conversion is complete. These timing specifications are provided in the 17
“Electrical Specifications” section of the device data sheets.
2. Often the source impedance of the analog signal is high (greater than 10 kΩ), so the
Converter
10-bit A/D
current drawn from the source to charge the sample capacitor can affect accuracy. If the
input signal does not change too quickly, try putting a 0.1 μF capacitor on the analog input.
This capacitor will charge to the analog voltage being sampled and supply the
instantaneous current needed to charge the 4.4 pF internal holding capacitor.
3. Put the device into Sleep mode before the start of the A/D conversion. The RC clock
source selection is required for conversions in Sleep mode. This technique increases
accuracy because digital noise from the CPU and other peripherals is minimized.
Note: Please visit the Microchip web site (www.microchip.com) for additional Application
Notes and code examples for the dsPIC30F Family of devices.
Converter
10-bit A/D
NOTES:
HIGHLIGHTS
This section of the manual contains the following major topics:
Converter
12-bit A/D
18.13 Specifying How Conversion Results are Written into the Buffer ................................ 18-19
18.14 Conversion Sequence Examples............................................................................... 18-21
18.15 A/D Sampling Requirements...................................................................................... 18-26
18.16 Reading the A/D Result Buffer................................................................................... 18-27
18.17 Transfer Function ....................................................................................................... 18-28
18.18 A/D Accuracy/Error .................................................................................................... 18-28
18.19 Connection Considerations........................................................................................ 18-28
18.20 Initialization ................................................................................................................ 18-29
18.21 A/D Conversion Speeds............................................................................................. 18-30
18.22 Operation During Sleep and Idle Modes.................................................................... 18-33
18.23 Effects of a Reset....................................................................................................... 18-33
18.24 Special Function Registers Associated with the 12-bit A/D Converter ...................... 18-34
18.25 Design Tips ................................................................................................................ 18-35
18.26 Related Application Notes.......................................................................................... 18-36
18.27 Revision History ......................................................................................................... 18-37
18.1 Introduction
The dsPIC30F 12-bit A/D converter has the following key features:
• Successive Approximation Register (SAR) conversion
• Up to 200 ksps conversion speed
• Up to 16 analog input pins
• External voltage reference input pins
• Unipolar differential S/H amplifier
• Automatic Channel Scan mode
• Selectable conversion trigger source
• 16-word conversion result buffer
• Selectable Buffer Fill modes
• Four result alignment options
• Operation during CPU Sleep and Idle modes
A block diagram of the 12-bit A/D is shown in Figure 18-1. The 12-bit A/D converter can have up
to 16 analog input pins, designated AN0-AN15. In addition, there are two analog input pins for
external voltage reference connections. These voltage reference inputs may be shared with
other analog input pins. The actual number of analog input pins and external voltage reference
input configuration will depend on the specific dsPIC30F device. Refer to the dsPIC30F device
data sheets (DS70082 and DS70083) for further details.
The analog inputs are connected via multiplexers to the S/H amplifier, designated CH0. The
analog input multiplexer can be switched between two sets of analog inputs during conversions.
Unipolar differential conversions are possible using certain input pins (see Figure 18-1).
An Analog Input Scan mode may be enabled for the CH0 S/H amplifier. A Control register
specifies which analog input channels will be included in the scanning sequence.
The 12-bit A/D is connected to a 16-word result buffer. Each 12-bit result is converted to one of
four 16-bit output formats when it is read from the buffer.
AVDD
AVSS
VREF+
VREF-
0000 Comparator
AN0
DAC
0001
AN1
0010
AN2
0011 12-bit SAR Conversion Logic
AN3
0100
AN4
Format
Data
0101 16-word, 12-bit
AN5 Dual Port
RAM
Bus Interface
0110
AN6
0111
AN7
1000 Sample/Sequence
AN8 Sample Control
1001
AN9
1010
18
Input
AN10 Input MUX
Switches
1011 Control
AN11
Converter
12-bit A/D
1100
AN12
1101
AN13
1110
AN14
1111
AN15
VREF- S/H CH0
AN1
Lower Byte:
R/W-0 R/W-0 R/W-0 U-0 U-0 R/W-0 R/W-0 R/C-0
HC, HS HC, HS
SSRC<2:0> — — ASAM SAMP DONE
bit 7 bit 0
Converter
12-bit A/D
bit 7-5 SSRC<2:0>: Conversion Trigger Source Select bits
111 = Internal counter ends sampling and starts conversion (auto convert)
110 = Reserved
101 = Reserved
100 = Reserved
011 = Motor Control PWM interval ends sampling and starts conversion
010 = General purpose Timer3 compare ends sampling and starts conversion
001 = Active transition on INT0 pin ends sampling and starts conversion
000 = Clearing SAMP bit ends sampling and starts conversion
bit 4-3 Unimplemented: Read as ‘0’
bit 2 ASAM: A/D Sample Auto-Start bit
1 = Sampling begins immediately after last conversion completes. SAMP bit is auto set.
0 = Sampling begins when SAMP bit set
bit 1 SAMP: A/D Sample Enable bit
1 = At least one A/D sample/hold amplifier is sampling
0 = A/D sample/hold amplifiers are holding
When ASAM = 0, writing ‘1’ to this bit will start sampling.
When SSRC = 000, writing ‘0’ to this bit will end sampling and start conversion.
bit 0 DONE: A/D Conversion Status bit
1 = A/D conversion is done
0 = A/D conversion is not done
Clearing this bit will not effect any operation in progress.
Cleared by software or start of a new conversion.
Legend:
R = Readable bit W = Writable bit C = Clearable by software
HC = Hardware clear HS = Hardware set U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
R-0 U-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
BUFS — SMPI<3:0> BUFM ALTS
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
R/W-0 U-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
ADRC — ADCS<5:0>
bit 7 bit 0
Converter
12-bit A/D
000000 = TCY/2 • (ADCS<5:0> + 1) = TCY/2
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
U-0 U-0 U-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
— — — CH0NA CH0SA<3:0>
bit 7 bit 0
Note: The analog input multiplexer supports two input setting configurations, denoted MUX A and
MUX B. ADCHS<15:8> determines the settings for MUX B, and ADCHS<7:0> determines the
settings for MUX A. Both sets of control bits function identically.
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
PCFG7 PCFG6 PCFG5 PCFG4 PCFG3 PCFG2 PCFG1 PCFG0
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Converter
12-bit A/D
CSSL15 CSSL14 CSSL13 CSSL12 CSSL11 CSSL10 CSSL9 CSSL8
bit 15 bit 8
Lower Byte:
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
CSSL7 CSSL6 CSSL5 CSSL4 CSSL3 CSSL2 CSSL1 CSSL0
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
The start time for sampling can be controlled in software by setting the SAMP control bit. The
start of the sampling time can also be controlled automatically by the hardware. When the A/D
converter operates in the Auto Sample mode, the S/H amplifier(s) is reconnected to the analog
input pin at the end of the conversion in the sample/convert sequence. The auto sample function
is controlled by the ASAM control bit.
The conversion trigger source ends the sampling time and begins an A/D conversion or a
sample/convert sequence. The conversion trigger source is selected by the SSRC control bits.
The conversion trigger can be taken from a variety of hardware sources or can be controlled
manually in software by clearing the SAMP control bit. One of the conversion trigger sources is
an auto conversion. The time between auto conversions is set by a counter and the A/D clock.
The Auto Sample mode and auto conversion trigger can be used together to provide endless
automatic conversions without software intervention.
An interrupt may be generated at the end of each sample/convert sequence or multiple
sample/convert sequences, as determined by the value of the SMPI control bits. The number of
sample/convert sequences between interrupts can vary between 1 and 16.
18.5 A/D Module Configuration
The following steps should be followed for performing an A/D conversion:
1. Configure the A/D module
• Select voltage reference source to match expected range on analog inputs
• Select the analog conversion clock to match desired data rate with processor clock
• Determine how sampling will occur
• Determine how inputs will be allocated to the S/H channel
• Select how conversion results are presented in the buffer 18
• Select interrupt rate
• Turn on A/D module
Converter
12-bit A/D
2. Configure A/D interrupt (if required)
• Clear ADIF bit
• Select A/D interrupt priority
The options for each configuration step are described in the subsequent sections.
Note: The SSRC<2:0>, SIMSAM, ASAM, CHPS<1:0>, SMPI<3:0>, BUFM and ALTS bits,
as well as the ADCON3 and ADCSSL registers, should not be written to while
ADON = 1. This would lead to indeterminate results.
Note: External VREF+ and VREF- pins must be selected for the conversion rates above 100
ksps. See Section 18.21 “A/D Conversion Speeds” for further details.
TCY (ADCS + 1)
TAD =
2
2TAD
ADCS = –1
TCY
For correct A/D conversions, the A/D conversion clock (TAD) must be selected to ensure a
minimum TAD time of 333.33 nsec (see Section 18.21 “A/D Conversion Speeds” for further
details).
The A/D converter has a dedicated internal RC clock source that can be used to perform
conversions. The internal RC clock source should be used when A/D conversions are performed
while the dsPIC30F is in Sleep mode. The internal RC oscillator is selected by setting the ADRC
bit (ADCON3<7>). When the ADRC bit is set, the ADCS<5:0> bits have no effect on the A/D
operation.
18.8 Selecting Analog Inputs for Sampling
The Sample-and-Hold Amplifier has analog multiplexers (see Figure 18-1) on both its
non-inverting and inverting inputs, to select which analog input(s) are sampled. Once the
sample/convert sequence is specified, the ADCHS bits determine which analog inputs are
selected for each sample.
Additionally, the selected inputs may vary on an alternating sample basis, or may vary on a
repeated sequence of samples.
Note: Different devices will have different numbers of analog inputs. Verify the analog
input availability against the device data sheet.
Note 1: When reading a port register, any pin configured as an analog input reads as a ‘0’.
2: Analog levels on any pin that is defined as a digital input (including the AN15:AN0
pins) may cause the input buffer to consume current that is out of the device’s
specification.
The ALTS bit (ADCON2<0>) causes the module to alternate between two sets of inputs that are
selected during successive samples.
The inputs specified by CH0SA<3:0>, CH0NA, CHXSA and CHXNA<1:0> are collectively called
the MUX A inputs. The inputs specified by CH0SB<3:0>, CH0NB, CHXSB and CHXNB<1:0> are
collectively called the MUX B inputs. When the ALTS bit is ‘1’, the module will alternate between
the MUX A inputs on one sample and the MUX B inputs on the subsequent sample.
For channel 0, if the ALTS bit is ‘0’, only the inputs specified by CH0SA<3:0> and CH0NA are
selected for sampling.
If the ALTS bit is ‘1’ on the first sample/convert sequence for channel 0, the inputs specified by
CH0SA<3:0> and CH0NA are selected for sampling. On the next sample convert sequence for
channel 0, the inputs specified by CH0SB<3:0> and CH0NB are selected for sampling. This
pattern will repeat for subsequent sample conversion sequences.
Channel 0 has the ability to scan through a selected vector of inputs. The CSCNA bit
18
(ADCON2<10>) enables the CH0 channel inputs to be scanned across a selected number of
analog inputs. When CSCNA is set, the CH0SA<3:0> bits are ignored.
Converter
12-bit A/D
The ADCSSL register specifies the inputs to be scanned. Each bit in the ADCSSL register
corresponds to an analog input. Bit 0 corresponds to AN0, bit 1 corresponds to AN1 and so on.
If a particular bit in the ADCSSL register is ‘1’, the corresponding input is part of the scan
sequence. The inputs are always scanned from lower to higher numbered inputs, starting at the
first selected channel after each interrupt occurs.
Note: If the number of scanned inputs selected is greater than the number of samples
taken per interrupt, the higher numbered inputs will not be sampled.
The ADCSSL bits only specify the input of the positive input of the channel. The CH0NA bit still
selects the input of the negative input of the channel during scanning.
If the ALTS bit is ‘1’, the scanning only applies to the MUX A input selection. The MUX B input
selection, as specified by the CH0SB<3:0>, will still select the alternating input. When the input
selections are programmed in this manner, the input will alternate between a set of scanning
inputs specified by the ADCSSL register and a fixed input specified by the CH0SB bits.
18.10.1 Manual
Setting the SAMP bit (ADCON1<1>) causes the A/D to begin sampling. One of several options
can be used to end sampling and complete the conversions. Sampling will not resume until the
SAMP bit is once again set. For an example, see Figure 18-3.
18.10.2 Automatic
Setting the ASAM bit (ADCON1<2>) causes the A/D to automatically begin sampling a channel
whenever a conversion is not active on that channel. One of several options can be used to end
sampling and complete the conversions. Sampling on a channel resumes after the conversion of
that channel completes. For an example, see Figure 18-4.
Note: The available conversion trigger sources may vary depending on the dsPIC30F
device variant. Please refer to the specific device data sheet for the available
conversion trigger sources.
Note: The SSRC selection bits should not be changed when the A/D module is enabled.
If the user wishes to change the conversion trigger source, the A/D module should
be disabled first by clearing the ADON bit (ADCON1<15>).
18.11.1 Manual
When SSRC<2:0> = 000, the conversion trigger is under software control. Clearing the SAMP
bit (ADCON1<1>) starts the conversion sequence.
Figure 18-3 is an example where setting the SAMP bit initiates sampling and clearing the SAMP
bit, terminates sampling and starts conversion. The user software must time the setting and
clearing of the SAMP bit to ensure adequate sampling time of the input signal.
Figure 18-3: Converting 1 Channel, Manual Sample Start, Manual Conversion Start
ADCLK
TSAMP TCONV
SAMP
DONE
ADCBUF0
Figure 18-4 is an example where setting the ASAM bit initiates automatic sampling and clearing
the SAMP bit, terminates sampling and starts conversion. After the conversion completes, the
module will automatically return to a sampling state. The SAMP bit is automatically set at the start 18
of the sample interval. The user software must time the clearing of the SAMP bit to ensure
adequate sampling time of the input signal, understanding that the time between clearing of the
SAMP bit includes the conversion time, as well as the sampling time.
Converter
12-bit A/D
Figure 18-4: Converting 1 Channel, Automatic Sample Start, Manual Conversion Start
ADCLK
TSAMP TCONV TSAMP TCONV
TAD0 TAD0
SAMP
ADCBUF0
TSMP = SAMC<4:0>*TAD
SAMC must always be programmed for at least 1 clock cycle to ensure sampling requirements are
met.
Figure 18-5 shows how to use the clocked conversion trigger with the sampling started by the user
software.
Figure 18-5: Converting 1 Channel, Manual Sample Start, TAD Based Conversion Start
ADCLK
TSAMP TCONV
SAMP
DONE
ADCBUF0
As shown in Figure 18-6, using the Auto-Convert Conversion Trigger mode (SSRC = 111) in
combination with the Auto-Sample Start mode (ASAM = 1) allows the A/D module to schedule
sample/conversion sequences with no intervention by the user or other device resources. This
“Clocked” mode allows continuous data collection after module initialization..
Note: This A/D configuration must be enabled for the conversion rate of 200 ksps (see
Section 18.21 “A/D Conversion Speeds” for details).
Figure 18-6: Converting 1 Channel, Auto-Sample Start, TAD Based Conversion Start
ADCLK
TSAMP TCONV TSAMP TCONV
SAMP
Reset by
DONE software
ADCBUF0
ADCBUF1
18
18.11.2.2 Sample Time Considerations Using Clocked Conversion Trigger and Automatic Sampling
Converter
12-bit A/D
The user must ensure the sampling time exceeds the sampling requirements as outlined in
Section 18.15 “A/D Sampling Requirements”.
Assuming that the module is set for automatic sampling and using a clocked conversion trigger,
the sampling interval is specified by the SAMC bits.
When SSRC<2:0> = 001, the A/D conversion is triggered by an active transition on the INT0 pin.
The INT0 pin may be programmed for either a rising edge input or a falling edge input.
The A/D is configured in this Trigger mode by setting SSRC<2:0> = 010. When a match occurs
between the 32-bit timer TMR3/TMR2 and the 32-bit Combined Period register PR3/PR2, a
special ADC trigger event signal is generated by Timer3. This feature does not exist for the
TMR5/TMR4 timer pair. Refer to Section 12. “Timers” for more details.
The PWM module has an event trigger that allows A/D conversions to be synchronized to the
PWM time base. When SSRC<2:0> = 011, the A/D sampling and conversion times occur at any
user programmable point within the PWM period. The special event trigger allows the user to
minimize the delay between the time when A/D conversion results are acquired and the time
when the duty cycle value is updated. Refer to Section 15. “Motor Control PWM” for more
details.
The modes where an external event trigger pulse ends sampling and starts conversion
(SSRC = 001, 010, 011) may be used in combination with auto sampling (ASAM = 1) to cause
the A/D to synchronize the sample conversion events to the trigger pulse source. For example,
in Figure 18-8 where SSRC = 010 and ASAM = 1, the A/D will always end sampling and start
conversions synchronously with the timer compare trigger event. The A/D will have a sample
conversion rate that corresponds to the timer comparison event rate.
Figure 18-7: Manual Sample Start, Conversion Trigger Based Conversion Start
Conversion Trigger
ADCLK
TSAMP TCONV
SAMP
ADCBUF0
Conversion Trigger
ADCLK
TSAMP TCONV TSAMP TCONV
SAMP
Reset by
DONE software
ADCBUF0
ADCBUF1
Different sample/conversion sequences provide different available sampling times for the S/H
channel to acquire the analog signal. The user must ensure the sampling time exceeds the
sampling requirements, as outlined in Section 18.15 “A/D Sampling Requirements”.
Assuming that the module is set for automatic sampling and an external trigger pulse is used as
the conversion trigger, the sampling interval is a portion of the trigger pulse interval.
The sampling time is the trigger pulse period, less the time required to complete the conversion.
Equation 18-3: Available Sampling Time, Sequential Sampling
TSMP = Trigger Pulse Interval (TSEQ) – Conversion Time (TCONV)
TSMP = TSEQ – TCONV
Note: TSEQ is the trigger pulse interval time.
Converter
12-bit A/D
sample/convert sequence, however, sampling will not automatically resume after a subsequent
conversion.
Conversion
Trigger
TSAMP TSAMP TSAMP TSAMP
ADCLK
TCONV TCONV TCONV TCONV
ASAM
SAMP
18
DONE
Converter
12-bit A/D
ADCBUF0
ADCBUF1
ADCBUFE
ADCBUFF
ADIF
Converter
12-bit A/D
Convert CH0, Write Buffer 0xC
Sample MUX A Inputs: AN0 -> CH0
Convert CH0, Write Buffer 0xD
Sample MUX A Inputs: AN0 -> CH0
Convert CH0, Write Buffer 0xE
Sample MUX A Inputs: AN0 -> CH0
Convert CH0, Write Buffer 0xF
Interrupt
Repeat
18.14.2 Example: A/D Conversions While Scanning Through All Analog Inputs
Figure 18-10 and Table 18-2 illustrate a typical setup, where all available analog input channels
are sampled and converted. The set CSCNA bit specifies scanning of the A/D inputs to the CH0
positive input. Other conditions are similar to Subsection 18.14.1.
Initially, the AN0 input is sampled by CH0 and converted. The result is stored in the ADCBUF
buffer. Then the AN1 input is sampled and converted. This process of scanning the inputs
repeats 16 times until the buffer is full and then the module generates an interrupt. The entire
process will then repeat.
Conversion
Trigger TSAMP TSAMP TSAMP TSAMP
ADCLK
TCONV TCONV TCONV TCONV
ASAM
SAMP
DONE
ADCBUF0
ADCBUF1
ADCBUFE
ADCBUFF
ADIF
Converter
12-bit A/D
Convert CH0, Write Buffer 0xC
Sample MUX A Inputs: AN13 -> CH0
Convert CH0, Write Buffer 0xD
Sample MUX A Inputs: AN14 -> CH0
Convert CH0, Write Buffer 0xE
Sample MUX A Inputs: AN15 -> CH0
Convert CH0, Write Buffer 0xF
Interrupt
Repeat
CHOLD
VA CPIN I leakage = DAC capacitance
VT = 0.6V ± 500 nA = 18 pF
VSS
Note: CPIN value depends on device package and is not tested. Effect of CPIN negligible if Rs ≤ 2.5 kΩ.
RAM Contents: d11 d10 d09 d08 d07 d06 d05 d04 d03 d02 d01 d00
Read to Bus:
Integer 0 0 0 0 d11 d10 d09 d08 d07 d06 d05 d04 d03 d02 d01 d00
Signed Integer d11 d11 d11 d11 d11 d10 d09 d08 d07 d06 d05 d04 d03 d02 d01 d00
Fractional d11 d10 d09 d08 d07 d06 d05 d04 d03 d02 d01 d00 0 0 0 0
18
Signed Fractional (1.15) d11 d10 d09 d08 d07 d04 d03 d02 d01 d00 d01 d00 0 0 0 0
Converter
12-bit A/D
Table 18-3: Numerical Equivalents of Various Result Codes
12-bit 16-bit Unsigned 16-bit Signed 16-bit Unsigned 16-bit Signed
VIN/VREF
Output Code Integer Format Integer Format Fractional Format Fractional Format
4095/4096 1111 1111 1111 0000 1111 1111 1111 0000 0111 1111 1111 1111 1111 1111 0000 0111 1111 1111 0000
= 4095 = 2047 = 0.9998 = 0.9995
4094/4096 1111 1111 1110 0000 1111 1111 1110 0000 0111 1111 1110 1111 1111 1110 0000 0111 1111 1110 0000
= 4094 = 2046 = 0.9995 = 0.9990
•••
2049/4096 1000 0000 0001 0000 1000 0000 0001 0000 0000 0000 0001 1000 0000 0001 0000 0000 0000 0001 0000
= 2049 = 1 = 0.5002 = 0.0005
2048/4096 1000 0000 0000 0000 1000 0000 0000 0000 0000 0000 0000 1000 0000 0000 0000 0000 0000 0000 0000
= 2048 = 0 = 0.500 = 0.000
2047/4096 0111 1111 1111 0000 0111 1111 1111 1111 1111 1111 1111 0111 1111 1111 0000 1111 1111 1111 0000
= 2047 = -1 = 0.4998 = -0.0005
•••
1/4096 0000 0000 0001 0000 0000 0000 0001 1111 1000 0000 0001 0000 0000 0001 0000 1000 0000 0001 0000
= 1 = -2047 = 0.0002 = -0.9995
0/4096 0000 0000 0000 0000 0000 0000 0000 1111 1000 0000 0000 0000 0000 0000 0000 1000 0000 0000 0000
= 0 = -2048 = 0.000 = -1.000
Output
Code
1111 1111 1111 (= 4095)
1111 1111 1110 (= 4094)
18.20 Initialization
Example 18-4 shows a simple initialization code example for the A/D module.
In this particular configuration, all 16 analog input pins, AN0-AN15, are set up as analog inputs.
Operation in Idle mode is disabled, output data is in unsigned fractional format, and AVDD and
AVSS are used for VREFH and VREFL. The start of sampling, as well as the start of conversion
(conversion trigger), are performed manually in software. Scanning of inputs is disabled and an
interrupt occurs after every sample/convert sequence (1 conversion result). The A/D conversion
clock is TCY/2; AN0 is converted.
Since sampling is started manually by setting the SAMP bit (ADCON1<1>) after each conversion
is complete, the auto-sample time bits, SAMC<4:0> (ADCON3<12:8>), are ignored. Moreover,
since the start of conversion (i.e., end of sampling) is also triggered manually, the SAMP bit
needs to be cleared each time a new sample needs to be converted.
Converter
12-bit A/D
; Interrupt every sample
TAD Sampling
A/D Speed Rs Max VDD Temperature A/D Channels Configuration
Minimum Time Min
Up to 200 333.33 ns 1 TAD 2.5 kΩ 4.5V to 5.5V -40°C to +85°C
ksps(1)
VREF- VREF+
CHX
ANx
S/H ADC
ANx CHX
S/H ADC
ANx or VREF-
Note 1: External VREF- and VREF+ pins must be used for correct operation. See Figure 18-14 for recommended
circuit.
The following figure depicts the recommended circuit for the conversion rates above 100 ksps.
The dsPIC30F6014 is shown as an example.
80
79
78
77
76
75
74
73
72
69
68
67
66
65
64
63
62
61
VSS
VDD
1 60
2 59
3 58
4 57
5 56
55 VDD VDD VDD
6
7 54
C8 C7 C6
8 53 1 μF 0.1 μF 0.01 μF
9 52
10 VSS
dsPIC30F6014
VDD VSS 50
VDD 49 VDD
13 VDD
14 47
VDD VDD VDD
15
16
46
45
18
C5 C4 C3
17 44 1 μF 0.1 μF 0.01 μF
18 43
Converter
12-bit A/D
19 42
VDD 20 41
VREF+
VREF-
AVDD
AVSS
VDD
VSS
21
22
27
28
29
30
33
34
35
36
37
38
39
40
R2
10
C2 C1 VDD
R1
0.1 μF 0.01 μF 10
VDD
The configuration procedures below give the required setup values for the conversion speeds
above 100 ksps.
The following figure shows the timing diagram of the A/D running at 200 ksps. The TAD selection
in conjunction with the guidelines described above allows a conversion speed of 200 ksps. See
Example 18-1 for code example.
Figure 18-15: Converting 1 Channel at 200 ksps, Auto-Sample Start, 1 TAD Sampling Time
TSAMP TSAMP
= 1 TAD = 1 TAD
ADCLK
TCONV TCONV
= 14 TAD = 14 TAD
SAMP
DONE
ADCBUF0
ADCBUF1
Example 18-1: Converting at 200 ksps, Auto-Sample Start, 1 TAD Sampling Time Code Example
ADPCFG = 0xFFFB; // all PORTB = Digital; RB2 = analog
ADCON1 = 0x00E0; // SSRC bit = 111 implies internal
// counter ends sampling and starts
// converting.
ADCHS = 0x0002; // Connect RB2/AN2 as CH0 input
// in this example RB2/AN2 is the input
ADCSSL = 0;
ADCON3 = 0x0113; // Sample time = 1Tad, Tad = 333.33 ns @ 30 MIPS
// which will give 1 / (15 * 333.33 ns) = 200 ksps
ADCON2 = 0x6004; // Select external VREF+ and VREF- pins
// Interrupt after every 2 samples
ADCON1bits.ADON = 1; // turn ADC ON
while (1) // repeat continuously
{
ADCValue = 0; // clear value
ADC16Ptr = &ADCBUF0; // initialize ADCBUF pointer
IFS0bits.ADIF = 0; // clear ADC interrupt flag
ADCON1bits.ASAM = 1; // auto start sampling
// for 31Tad then go to conversion
while (!IFS0bits.ADIF); // conversion done?
ADCON1bits.ASAM = 0; // yes then stop sample/convert
for (count = 0; count <2; count++)// average the 2 ADC value
ADCValue = ADCValue + *ADC16Ptr++;
ADCValue = ADCValue >> 1;
} // repeat
Converter
12-bit A/D
conversion trigger source that ensures the A/D conversion will take place in Sleep mode. The
automatic conversion trigger option can be used for sampling and conversion in Sleep
(SSRC<2:0> = 111). To use the automatic conversion option, the ADON bit should be set in the
instruction prior to the PWRSAV instruction.
Note: For the A/D module to operate in Sleep, the A/D clock source must be set to RC
(ADRC = 1).
DS70065D-page 18-34
INTCON1 0080 NSTDIS — — — — OVATE OVBTE COVTE — — — MATHERR ADDRERR STKERR OSCFAIL — 0000 0000 0000 0000
INTCON2 0082 ALTIVT — — — — — — — — — — INT4EP INT3EP INT2EP INT1EP INT0EP 0000 0000 0000 0000
IFS0 0084 CNIF MI2CIF SI2CIF NVMIF ADIF U1TXIF U1RXIF SPI1IF T3IF T2IF OC2IF IC2IF T1IF OC1IF IC1IF INT0 0000 0000 0000 0000
IEC0 008C CNIE MI2CIE SI2CIE NVMIE ADIE U1TXIE U1RXIE SPI1IE T3IE T2IE OC2IE IC2IE T1IE OC1IE IC1IE INT0IE 0000 0000 0000 0000
IPC2 0098 — ADIP<2:0> — U1TXIP<2:0> — U1RXIP<2:0> — SPI1IP<2:0> 0100 0100 0100 0100
ADCBUF0 0280 ADC Data Buffer 0 uuuu uuuu uuuu uuuu
ADCBUF1 0282 ADC Data Buffer 1 uuuu uuuu uuuu uuuu
ADCBUF2 0284 ADC Data Buffer 2 uuuu uuuu uuuu uuuu
ADCBUF3 0286 ADC Data Buffer 3 uuuu uuuu uuuu uuuu
ADCBUF4 0288 ADC Data Buffer 4 uuuu uuuu uuuu uuuu
ADCBUF5 028A ADC Data Buffer 5 uuuu uuuu uuuu uuuu
ADCBUF6 028C ADC Data Buffer 6 uuuu uuuu uuuu uuuu
ADCBUF7 028E ADC Data Buffer 7 uuuu uuuu uuuu uuuu
ADCBUF8 0290 ADC Data Buffer 8 uuuu uuuu uuuu uuuu
uuuu uuuu uuuu uuuu
dsPIC30F Family Reference Manual
Question 1: How can I optimize the system performance of the A/D converter?
Answer:
1. Make sure you are meeting all of the timing specifications. If you are turning the module
off and on, there is a minimum delay you must wait before taking a sample. If you are
changing input channels, there is a minimum delay you must wait for this as well, and
finally, there is TAD, which is the time selected for each bit conversion. This is selected in
ADCON3 and should be within a certain range, as specified in the Electrical Characteris-
tics. If TAD is too short, the result may not be fully converted before the conversion is
terminated, and if TAD is made too long, the voltage on the sampling capacitor can decay
before the conversion is complete. These timing specifications are provided in the
“Electrical Specifications” section of the device data sheets.
2. Often, the source impedance of the analog signal is high (greater than 10 kΩ), so the
current drawn from the source by leakage, and to charge the sample capacitor, can affect
accuracy. If the input signal does not change too quickly, try putting a 0.1 μF capacitor on
the analog input. This capacitor will charge to the analog voltage being sampled and
supply the instantaneous current needed to charge the 18 pF internal holding capacitor.
3. Put the device into Sleep mode before the start of the A/D conversion. The RC clock
source selection is required for conversions in Sleep mode. This technique increases
accuracy, because digital noise from the CPU and other peripherals is minimized.
Converter
Question 3: My combination of channels/sample and samples/interrupt is greater than
12-bit A/D
the size of the buffer. What will happen to the buffer?
Answer: This configuration is not recommended. The buffer will contain unknown results.
Note: Please visit the Microchip web site (www.microchip.com) for additional Application
Notes and code examples for the dsPIC30F Family of devices.
18
Converter
12-bit A/D
NOTES:
HIGHLIGHTS
This section of the manual contains the following major topics:
19
UART
19.1 Introduction
The Universal Asynchronous Receiver Transmitter (UART) module is one of the serial I/O
modules available in the dsPIC30F device family. The UART is a full-duplex asynchronous sys-
tem that can communicate with peripheral devices, such as personal computers, RS-232 and
RS-485 interfaces.
The primary features of the UART module are:
• Full-duplex 8- or 9-bit data transmission through the UxTX and UxRX pins
• Even, Odd or No Parity options (for 8-bit data)
• One or two Stop bits
• Fully integrated Baud Rate Generator with 16-bit prescaler
• Baud rates ranging from 29 bps to 1.875 Mbps at FCY = 30 MHz
• 4-deep First-In-First-Out (FIFO) transmit data buffer
• 4-deep FIFO receive data buffer
• Parity, Framing and Buffer Overrun error detection
• Support for 9-bit mode with Address Detect (9th bit = 1)
• Transmit and Receive Interrupts
• Loopback mode for diagnostic support
Note: Each dsPIC30F device variant may have one or more UART modules. An ‘x’ used
in the names of pins, control/status bits and registers denotes the particular module.
Refer to the specific device data sheets for more details.
A simplified block diagram of the UART is shown in Figure 19-1. The UART module consists of
the key important hardware elements:
• Baud Rate Generator
• Asynchronous Transmitter
• Asynchronous Receiver
UART Receiver
UxRX
Lower Byte:
R/W-0 R/W-0 R/W-0 U-0 U-0 R/W-0 R/W-0 R/W-0
WAKE LPBACK ABAUD — — PDSEL<1:0> STSEL
bit 7 bit 0
UART
bit 2-1 PDSEL<1:0>: Parity and Data Selection bits
11 = 9-bit data, no parity
10 = 8-bit data, odd parity
01 = 8-bit data, even parity
00 = 8-bit data, no parity
bit 0 STSEL: Stop Selection bit
1 = 2 Stop bits
0 = 1 Stop bit
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
R/W-0 R/W-0 R/W-0 R-1 R-0 R-0 R/C-0 R-0
URXISEL<1:0> ADDEN RIDLE PERR FERR OERR URXDA
bit 7 bit 0
bit 1 OERR: Receive Buffer Overrun Error Status bit (Read/Clear Only)
1 = Receive buffer has overflowed
0 = Receive buffer has not overflowed
bit 0 URXDA: Receive Buffer Data Available bit (Read Only)
1 = Receive buffer has data, at least one more character can be read
0 = Receive buffer is empty
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’ C = Bit can be cleared
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
19
UART
Lower Byte:
R-0 R-0 R-0 R-0 R-0 R-0 R-0 R-0
URX<7:0>
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
W-x W-x W-x W-x W-x W-x W-x W-x
UTX<7:0>
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
BRG<7:0>
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
19
UART
FCY
Baud Rate =
16 • (UxBRG + 1)
FCY
UxBRG = –1
16 • Baud Rate
Example 19-1 shows the calculation of the baud rate error for the following conditions:
• FCY = 4 MHz
• Desired Baud Rate = 9600
The maximum baud rate possible is FCY / 16 (for UxBRG = 0), and the minimum baud rate
possible is FCY / (16 * 65536).
Writing a new value to the UxBRG register causes the BRG timer to be reset (cleared). This
ensures the BRG does not wait for a timer overflow before generating the new baud rate.
0.3 0.3 0.0 6249 0.3 +0.01 5207 0.3 0.0 4166 0.3 +0.01 3332
1.2 1.1996 0.0 1562 1.2001 +0.01 1301 1.1996 0.0 1041 1.2005 +0.04 832
2.4 2.4008 0.0 780 2.4002 +0.01 650 2.3992 0.0 520 2.3981 -0.08 416
9.6 9.6154 +0.2 194 9.5859 -0.15 162 9.6154 +0.2 129 9.6154 +0.16 103
19.2 19.1327 -0.4 97 19.2901 0.47 80 19.2308 +0.2 64 19.2308 +0.16 51
38.4 38.2653 -0.4 48 38.1098 -0.76 40 37.8788 -1.4 32 38.4615 +0.16 25
56 56.8182 +1.5 32 55.8036 -0.35 27 56.8182 +1.5 21 55.5556 -0.79 17
115 117.1875 +1.9 15 111.6071 -2.95 13 113.6364 -1.2 10 111.1111 -3.38 8
250 250 0.0 4 250 0.0 3
500 500 0.0 1
MIN. 0.0286 0.0 65535 0.0238 0.0 65535 0.019 0.0 65535 0.015 0.0 65535
MAX. 1875 0.0 0 1562.5 0.0 0 1250 0.0 0 1000 0.0 0
0.3 0.3 0.0 2499 0.3 0.0 2082 0.2999 -0.02 1666 0.3 0.0 1599
1.2 1.2 0.0 624 1.1996 0.0 520 1.199 -0.08 416 1.2 0.0 399
2.4 2.3962 -0.2 312 2.4038 +0.2 259 2.4038 +0.16 207 2.4 0.0 199
9.6 9.6154 -0.2 77 9.6154 +0.2 64 9.6154 +0.16 51 9.6 0.0 49
19.2 19.2308 +0.2 38 18.9394 -1.4 32 19.2308 +0.16 25 19.2 0.0 24
38.4 37.5 +0.2 19 39.0625 +1.7 15 38.4615 +0.16 12
56 57.6923 -2.3 12 56.8182 +1.5 10 55.5556 -0.79 8
115 6
250 250 0.0 2 250 0.0 1
500 500 0.0 0
MIN. 0.011 0.0 65535 0.010 0.0 65535 0.008 0.0 65535 0.007 0.0 65535
MAX. 750 0.0 0 625 0.0 0 500 0.0 0 480 0.0 0
19
BAUD FCY = 5 MHz BRG
4 MHz
BRG
3.072 MHz
BRG
1.8432 MHz
BRG
RATE value value value value
% % % %
(Kbps) KBAUD ERROR
(decimal)
KBAUD ERROR
(decimal)
KBAUD ERROR
(decimal)
KBAUD ERROR
(decimal)
UART
0.3 0.2999 0.0 1041 0.3001 0.0 832 0.3 0.0 639 0.3 0.0 383
1.2 1.2019 +0.2 259 1.2019 +0.2 207 1.2 0.0 159 1.2 0.0 95
2.4 2.4038 +0.2 129 2.4038 +0.2 103 2.4 0.0 79 2.4 0.0 47
9.6 9.4697 -1.4 32 9.6154 +0.2 25 9.6 0.0 19 9.6 0.0 11
19.2 19.5313 +1.7 15 19.2308 +0.2 12 19.2 0.0 9 19.2 0.0 5
38.4 39.0625 +1.7 7 38.4 0.0 4 38.4 0.0 2
56
115
250
500
MIN. 0.005 0.0 65535 0.004 0.0 65535 0.003 0.0 65535 0.002 0.0 65535
MAX. 312.5 0.0 0 250 0.0 0 192 0.0 0 115.2 0.0 0
Note: The UxTSR register is not mapped in data memory, so it is not available to the user.
16
UxMODE UxSTA
15 9 8 7 0
– Control TSR
– Control Buffer
Transmit FIFO – Generate Flags
– Generate Interrupt
Load TSR
UxTXIF
UTXBRK
Data
UxTX Transmit Shift Register (UxTSR)
‘0’ (Start)
UxTX
16X Baud Clock
‘1’ (Stop)
from Baud Rate
Generator
Parity Parity 16 Divider
Generator
Control
19
Signals
UART
Note: ‘x’ denotes the UART number.
Transmission is enabled by setting the UTXEN enable bit (UxSTA<10>). The actual transmission
will not occur until the UxTXREG register has been loaded with data and the Baud Rate Gener-
ator (UxBRG) has produced a shift clock (Figure 19-2). The transmission can also be started by
first loading the UxTXREG register and then setting the UTXEN enable bit. Normally when trans-
mission is first started, the UxTSR register is empty, so a transfer to the UxTXREG register will
result in an immediate transfer to UxTSR. Clearing the UTXEN bit during a transmission
will cause the transmission to be aborted and will reset the transmitter. As a result, the UxTX pin
will revert to a high-impedance state.
In order to select 9-bit transmission, the PDSEL<1:0> bits (UxMODE<2:1>) should be set to ‘11’
and the ninth bit should be written to the UTX9 bit (UxTXREG<8>). A word write should be
performed to UxTXREG so that all nine bits are written at the same time.
Note: There is no parity in the case of 9-bit data transmission.
Note: When the UTXEN bit is set, the UxTXIF flag bit will also be set if UTXISEL = 0, since
the transmit buffer is not yet full (can move transmit data to the UxTXREG register).
While the UxTXIF flag bit indicates the status of the UxTXREG register, the TRMT bit
(UxSTA<8>) shows the status of the UxTSR register. The TRMT status bit is a read only bit,
which is set when the UxTSR register is empty. No interrupt logic is tied to this bit, so the user
has to poll this bit in order to determine if the UxTSR register is empty.
Note: The UTXEN bit should not be set until the UARTEN bit has been set. Otherwise,
UART transmissions will not be enabled.
Write to UxTXREG
Character 1
BCLK/16
(Shift Clock)
UxTX
Start Bit Bit 0 Bit 1 Bit 7/8 Stop Bit
Character 1
Character 1 to
Transmit Shift Reg.
TRMT bit
19
UART
Write to UxTXREG
Character 1 Character 2
BCLK/16
(Shift Clock)
UxTX Start Bit Start Bit
Bit 0 Bit 1 Bit 7/8 Stop Bit Bit 0
Character 1 Character 2
UxTXIF
(UTXISEL = 0)
UxTXIF UxTXIF Cleared by User in Software
(UTXISEL = 1)
Character 1 to Character 2 to
Transmit Shift Reg. Transmit Shift Reg.
TRMT bit
Note: The UxRSR register is not mapped in data memory, so it is not available to the user.
The data on the UxRX pin is sampled three times by a majority detect circuit to determine if a
high or a low level is present at the UxRX pin. Figure 19-5 shows the sampling scheme.
Note: The data in the receive FIFO should be read prior to clearing the OERR bit. The
FIFO is reset when OERR is cleared, which causes all data in the buffer to be lost.
The framing error bit, FERR (UxSTA<2>), is set if a Stop bit is detected as a logic low level.
The parity error bit, PERR (UxSTA<3>), is set if a parity error has been detected in the data word
at the top of the buffer (i.e., the current word). For example, a parity error would occur if the parity
is set to be even, but the total number of ones in the data has been detected to be odd. The PERR
bit is irrelevant in the 9-bit mode. The FERR and PERR bits are buffered along with the
corresponding word and should be read before reading the data word.
19
UART
Word or
Word Read Only
Byte Read UxMODE UxSTA
15 9 8 7 0
UxRXIF
9
Load RSR
LPBACK to Buffer
From UxTX
1
Control
FERR
PERR
UxRXIF
(URXISEL = 0x)
Character 1 Character 2
to UxRXREG to UxRXREG
RIDLE bit
Note: This timing diagram shows 2 characters received on the UxRX input.
UART
bit bit bit
Character 1,2,3,4 Character 5
stored in Receive held in UxRSR
FIFO
OERR Cleared by User
OERR bit
RIDLE bit
Note: This diagram shows 6 characters received without the user reading the input buffer. The 5th character received is held in the
receive shift register. An overrun error occurs at the start of the 6th character.
Note: If the Address Detect mode is enabled (ADDEN = 1), the URXISEL<1:0> control
bits should be configured so that an interrupt will be generated after every received
word. Each received data word must be checked in software for an address match
immediately after reception.
The procedure for using the Address Detect mode is as follows:
1. Set the ADDEN (UxSTA<5>) bit to enable address detect. Ensure that the URXISEL
control bits are configured to generate an interrupt after each received word.
2. Check each 8-bit address by reading the UxRXREG register, to determine if the device is
being addressed.
3. If this device has not been addressed, then discard the received word.
4. If this device has been addressed, clear the ADDEN bit to allow subsequent data bytes to
be read into the receive buffer and interrupt the CPU. If a long data packet is expected,
then the Receive Interrupt mode could be changed to buffer more than one data byte
between interrupts.
5. When the last data byte has been received, set the ADDEN bit so that only address bytes
will be received. Also, ensure that the URXISEL control bits are configured to generate an
interrupt after each received word.
UxRXIF
(Interrupt Flag)
UART
Note: This timing diagram shows a data byte followed by an address byte. The data byte is not read into the UxRXREG (receive buffer)
because ADDEN = 1 and bit 8 = 0.
19.9 Initialization
Example 19-2 is an initialization routine for the Transmitter/Receiver in 8-bit mode. Example 19-3
shows an initialization of the Addressable UART in 9-bit Address Detect mode. In both examples,
the value to load into the UxBRG register is dependent on the desired baud rate and the device
frequency.
Note: The UTXEN bit should not be set until the UARTEN bit has been set. Otherwise,
UART transmissions will not be enabled.
CLR U1STA
UART
is in progress, then the transmission is aborted and the UxTX pin is driven to logic ‘1’. Similarly,
if entry into Sleep mode occurs while a reception is in progress, then the reception is aborted.
The UART can be used to optionally wake the dsPIC device from Sleep mode on the detection
of a Start bit. If the WAKE bit (UxSTA<7>) is set, the device is in Sleep mode, and the UART
receive interrupt is enabled (UxRXIE = 1), then a falling edge on the UxRX pin will generate a
receive interrupt. The Receive Interrupt Select mode bit (URXISEL) has no effect for this
function. The UARTEN bit must be set in order to generate a wake-up interrupt.
The USIDL bit (UxMODE<13>) selects if the module will stop operation when the device enters
Idle mode, or whether the module will continue normal operation in Idle mode. If USIDL = 0, the
module will continue normal operation during Idle mode. If USIDL = 1, the module will stop in Idle
mode. Any transmission or reception in progress will be aborted.
DS70066C-page 19-22
U1TXREG — — — — — — — UTX8 Transmit Register 0000 0000 0000 0000
U1RXREG — — — — — — — URX8 Receive Register 0000 0000 0000 0000
U1BRG Baud Rate Generator Prescaler 0000 0000 0000 0000
IFS0 CNIF MI2CIF SI2CIF NVMIF ADIF U1TXIF U1RXIF SPI1IF T3IF T2IF OC2IF IC2IF T1IF OC1IF IC1IF INT0 0000 0000 0000 0000
IEC0 CNIE MI2CIE SI2CIE NVMIE ADIE U1TXIE U1RXIE SPI1IE T3IE T2IE OC2IE IC2IE T1IE OC1IE IC1IE INT0IE 0000 0000 0000 0000
IPC2 — ADIP<2:0> — U1TXIP<2:0> — U1RXIP<2:0> — SPI1IP<2:0> 0100 0100 0100 0100
Note: The registers associated with UART1 are shown for reference. See the device data sheet for the registers associated with other UART modules.
dsPIC30F Family Reference Manual
Question 1: The data I transmit with the UART does not get received correctly. What
could cause this?
Answer: The most common reason for reception errors is that an incorrect value has been
calculated for the UART baud rate generator. Ensure the value written to the UxBRG register is
correct.
Question 2: I am getting framing errors even though the signal on the UART receive pin
looks correct. What are the possible causes?
Answer: Ensure the following control bits have been setup correctly:
• UxBRG: UART Baud Rate register
• PDSEL<1:0>: Parity and Data Size Selection bits
• STSEL: Stop bit Selection
19
UART
Note: Please visit the Microchip web site (www.microchip.com) for additional Application
Notes and code examples for the dsPIC30F Family of devices.
19
UART
NOTES:
HIGHLIGHTS
This section of the manual contains the following major topics:
20
Serial Peripheral
Interface (SPI)
20.1 Introduction
The Serial Peripheral Interface (SPI) module is a synchronous serial interface useful for
communicating with other peripheral or microcontroller devices. These peripheral devices may
be Serial EEPROMs, shift registers, display drivers, A/D converters, etc. The SPI module is
compatible with Motorola's SPI and SIOP interfaces.
Depending on the variant, the dsPIC30F family offers one or two SPI modules on a single device.
SPI1 and SPI2 are functionally identical. The SPI2 module is available in many of the higher pin
count packages (64-pin and higher), while the SPI1 module is available on all devices.
Note: In this section, the SPI modules are referred together as SPIx or separately as SPI1
and SPI2. Special Function registers will follow a similar notation. For example,
SPIxCON refers to the control register for the SPI1 or SPI2 module.
The SPI serial port consists of the following Special Function Registers (SFR):
• SPIxBUF: Address in SFR space that is used to buffer data to be transmitted and data that
is received. This address is shared by the SPIxTXB and SPIxRXB registers.
• SPIxCON: A control register that configures the module for various modes of operation.
• SPIxSTAT: A status register that indicates various status conditions.
In addition, there is a 16-bit shift register, SPIxSR, that is not memory mapped. It is used for
shifting data in and out of the SPI port.
The memory mapped SFR, SPIxBUF, is the SPI Data Receive/Transmit register. Internally, the
SPIxBUF register actually comprises of two separate registers - SPIxTXB and SPIxRXB. The
Receive Buffer register, SPIxRXB, and the Transmit Buffer register, SPIxTXB, are two unidirec-
tional 16-bit registers. These registers share the SFR address named SPIxBUF. If a user writes
data to be transmitted to the SPIxBUF address, internally the data gets written to the SPIxTXB
register. Similarly, when the user reads the received data from SPIxBUF, internally the data is
read from the SPIxRXB register. This double-buffering of transmit and receive operations allows
continuous data transfers in the background. Transmission and reception occur simultaneously.
Note: The user cannot write to the SPIxTXB register or read from the SPIxRXB register
directly. All reads and writes are performed on the SPIxBUF register.
Note: The SPI module can be configured to operate using 3 or 4 pins. In the 3-pin mode,
the SSx pin is not used.
Internal
Data Bus
SPIxBUF
SPIxRXB SPIxTXB
Transmit
Receive
SPIxSR
SDIx bit0
SDOx Shift
Control
Slave Select Clock Edge
and Frame Control Select
SSx Sync Control
Secondary Primary
Prescaler Prescaler FCY
1:1 → 1:8 1, 4, 16, 64
SCKx
Note: The SPIxTXB and SPIxRXB registers are memory mapped to the SPIxBUF register.
20
Serial Peripheral
Interface (SPI)
Upper Byte:
R/W-0 U-0 R/W-0 U-0 U-0 U-0 U-0 U-0
SPIEN — SPISIDL — — — — —
bit 15 bit 8
Lower Byte:
U-0 R/W-0 U-0 U-0 U-0 U-0 R-0 R-0
HS
— SPIROV — — — — SPITBF SPIRBF
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
HC = Cleared by Hardware HS = Set by Hardware
-n = Value at Reset ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Upper Byte:
U-0 R/W-0 R/W-0 U-0 R/W-0 R/W-0 R/W-0 R/W-0
— FRMEN SPIFSD — DISSDO MODE16 SMP CKE
bit 15 bit 8
Lower Byte:
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
SSEN CKP MSTEN SPRE<2:0> PPRE<1:0>
bit 7 bit 0
20
Serial Peripheral
Interface (SPI)
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
SDOx SDIx
SDIx SDOx
Shift Register Shift Register
(SPIxSR) (SPIxSR)
Serial Clock
SCKx SCKx SPI Buffer
SPI Buffer
(SPIxBUF) (SPIxBUF)
SSx SSx
.
The following steps should be taken to set up the SPI module for the Master mode of operation:
1. If using interrupts:
• Clear the SPIxIF bit in the respective IFSn register.
• Set the SPIxIE bit in the respective IECn register.
• Write the SPIxIP bits in the respective IPCn register.
2. Write the desired settings to the SPIxCON register with MSTEN (SPIxCON<5>) = 1.
3. Clear the SPIROV bit (SPIxSTAT<6>).
4. Enable SPI operation by setting the SPIEN bit (SPIxSTAT<15>).
5. Write the data to be transmitted to the SPIxBUF register. Transmission (and Reception)
will start as soon as data is written to the SPIxBUF register.
In Master mode, the system clock is prescaled and then used as the serial clock. The prescaling
is based on the settings in the PPRE<1:0> (SPIxCON<1:0>) and SPRE<1:0> (SPIxCON<4:2>)
bits. The serial clock is output via the SCKx pin to slave devices. Clock pulses are only generated
when there is data to be transmitted. For further information, refer to Section 20.4 “SPI Master
Mode Clock Frequency”.
The CKP and CKE bits determine on which edge of the clock, data transmission occurs.
Both data to be transmitted and data that is received are respectively written into or read from
the SPIxBUF register.
The following describes the SPI module operation in Master mode:
1. Once the module is set up for Master mode of operation and enabled, data to be
transmitted is written to the SPIxBUF register. The SPITBF (SPIxSTAT<1>) bit is set.
2. The contents of SPIxTXB are moved to the shift register, SPIxSR, and the SPITBF bit is
cleared by the module.
3. A series of 8/16 clock pulses shifts out 8/16 bits of transmit data from the SPIxSR to the
SDOx pin and simultaneously shifts in the data at the SDIx pin into the SPIxSR.
4. When the transfer is complete, the following events will occur:
• The interrupt flag bit, SPIxIF, is set. SPI interrupts can be enabled by setting the
interrupt enable bit SPIxIE. The SPIxIF flag is not cleared automatically by the
hardware.
• Also, when the ongoing transmit and receive operation is completed, the contents of
the SPIxSR are moved to the SPIxRXB register.
• The SPIRBF (SPIxSTAT<0>) bit is set by the module, indicating that the receive buffer
is full. Once the SPIxBUF register is read by the user code, the hardware clears the
SPIRBF bit.
5. If the SPIRBF bit is set (receive buffer is full) when the SPI module needs to transfer data
from SPIxSR to SPIxRXB, the module will set the SPIROV (SPIxSTAT<6>) bit, indicating
an overflow condition.
6. Data to be transmitted can be written to SPIxBUF by the user software at any time as long
as the SPITBF (SPIxSTAT<1>) bit is clear. The write can occur while SPIxSR is shifting
out the previously written data, allowing continuous transmission.
Note: The SPIxSR register cannot be written into directly by the user. All writes to the
SPIxSR register are performed through the SPIxBUF register.
User writes
User writes new data
to SPIxBUF
SPIxTXB to SPIxSR during transmission
SPITBF
SCKx
(CKP = 0
CKE = 0)
4 Clock
SCKx modes
(CKP = 1 (clock
CKE = 0) output at
the SCKx
SCKx pin in
(CKP = 0
Master
CKE = 1)
mode)
SCKx
(CKP = 1
CKE = 0)
SDIx
(SMP = 0) bit0
bit7
Input
Sample Two modes
(SMP = 0) available
for SMP
SDIx control
(SMP = 1) bit (see
bit7 bit0
Note 4)
Input
Sample
(SMP = 1)
SPIxIF
SPIxSR moved
into SPIxRXB
SPIRBF
(SPIxSTAT<0>)
User reads
SPIxBUF 20
Serial Peripheral
Interface (SPI)
Note 1: Four SPI Clock modes shown to demonstrate CKP (SPIxCON<6>) and CKE (SPIxCON<8>) bit functionality only.
Only one of the four modes can be chosen for operation.
2: SDI and input sample shown for two different values of the SMP (SPIxCON<9>) bit, for demonstration purposes
only. Only one of the two configurations of the SMP bit can be chosen during operation.
3: If there are no pending transmissions, SPIxTXB is transferred to SPIxSR as soon as the user writes to SPIxBUF.
4: Operation for 8-bit mode shown. The 16-bit mode is similar.
The following steps should be taken to set up the SPI module for the Slave mode of operation:
1. Clear the SPIxBUF register.
2. If using interrupts:
• Clear the SPIxIF bit in the respective IFSn register.
• Set the SPIxIE bit in the respective IECn register.
• Write the SPIxIP bits in the respective IPCn register.
3. Write the desired settings to the SPIxCON register with MSTEN (SPIxCON<5>) = 0.
4. Clear the SMP bit.
5. If the CKE bit is set, then the SSEN bit must be set, thus enabling the SSx pin.
6. Clear the SPIROV bit (SPIxSTAT<6>) and,
7. Enable SPI operation by setting the SPIEN bit (SPIxSTAT<15>).
In Slave mode, data is transmitted and received as the external clock pulses appear on the SCKx
pin. The CKP (SPIxCON<6>) and CKE (SPIxCON<8>) bits determine on which edge of the clock
data transmission occurs.
Both data to be transmitted and data that is received are respectively written into or read from
the SPIxBUF register.
The rest of the operation of the module is identical to that in the Master mode.
A few additional features provided in the Slave mode are:
Slave Select Synchronization: The SSx pin allows a Synchronous Slave mode. If the SSEN
(SPIxCON<7>) bit is set, transmission and reception is enabled in Slave mode only if the SSx
pin is driven to a low state. The port output or other peripheral outputs must not be driven in order
to allow the SSx pin to function as an input. If the SSEN bit is set and the SSx pin is driven high,
the SDOx pin is no longer driven and will tri-state even if the module is in the middle of a
transmission. An aborted transmission will be retried the next time the SSx pin is driven low using
the data held in the SPIxTXB register. If the SSEN bit is not set, the SSx pin does not affect the
module operation in Slave mode.
SPITBF Status Flag Operation: The function of the SPITBF (SPIxSTAT<1>) bit is different in
the Slave mode of operation. The following describes the function of the SPITBF for various
settings of the Slave mode of operation:
1. If SSEN (SPIxCON<7>) is cleared, the SPITBF is set when the SPIxBUF is loaded by the
user code. It is cleared when the module transfers SPIxTXB to SPIxSR. This is similar to
the SPITBF bit function in Master mode.
2. If SSEN (SPIxCON<7>) is set, the SPITBF is set when the SPIxBUF is loaded by the user
code. However, it is cleared only when the SPIx module completes data transmission. A
transmission will be aborted when the SSx pin goes high and may be retried at a later
time. Each data word is held in SPIxTXB until all bits are transmitted to the receiver.
Note: To meet module timing requirements, the SSx pin must be enabled in Slave mode
when CKE = 1. (Refer to Figure 20-6 for details.)
Figure 20-4: SPI Slave Mode Operation: Slave Select Pin Disabled
SCKx Input
(CKP = 0
CKE = 0)
SCKx Input
(CKP = 1
CKE = 0)
SDIx Input
(SMP = 0) bit7 bit0
Input
Sample
(SMP = 0)
User writes to
SPIxBUF
SPITBF
SPISR to
SPIxRXB
SPIRBF
Note 1: Two SPI Clock modes shown only to demonstrate CKP (SPIxCON<6>) and CKE (SPIxCON<8>) bit functionality.
Any combination of CKP and CKE bits can be chosen for module operation.
2: If there are no pending transmissions or a transmission in progress, SPIxBUF is transferred to SPIxSR as soon
as the user writes to SPIxBUF.
3: Operation for 8-bit mode shown. The 16-bit mode is similar.
20
Serial Peripheral
Interface (SPI)
Figure 20-5: SPI Slave Mode Operation with Slave Select Pin Enabled
SSx
SCKx
(CKP = 0
CKE = 0)
SCKx
(CKP = 1
CKE = 0)
User writes SPIxBUF
to to
SPIxBUF SPIxSR
SPITBF
SDIx
(SMP = 0) bit7 bit0
Input
Sample
(SMP = 0)
SPIxIF
1 instruction
cycle latency
SPIxSR to
SPIxBUF
SPIRBF
User reads
SPIxBUF
Note 1: When the SSEN (SPIxCON<7>) bit is set to ‘1’, the SSx pin must be driven low so as to enable transmission and
reception in Slave mode.
2: Transmit data is held in SPIxTXB and SPITBF remains set until all bits are transmitted.
3: Operation for 8-bit mode shown. The 16-bit mode is similar.
SSx
(see Note 1)
SCK Input
(CKP = 0
CKE = 1)
SCK Input
(CKP = 1
CKE = 1)
SDI Input
(SMP = 0) bit7 bit0
Input
Sample
(SMP = 0)
SPIxIF
Write to SPISR to
SPIxBUF SPIRXB
SPITBF
SPIxRBF
Note 1: The SSx pin must be used for Slave mode operation when CKE = 1.
2: When the SSEN (SPIxCON<7>) bit is set to ‘1’, the SSx pin must be driven low so as to enable transmission and
reception in Slave mode.
3: Transmit data is held in SPIxTXB and SPITBF remains set until all bits are transmitted.
4: Operation for 8-bit mode shown. The 16-bit mode is similar.
20
Serial Peripheral
Interface (SPI)
SDOx SDIx
Serial Clock
SPI Buffer SCKx SCKx SPI Buffer
(SPIxBUF) (SPIxBUF)
SSx SSx
Frame Sync.
Pulse
Note 1: In Framed SPI modes, the SSx pin is used to transmit/receive the frame synchronization pulse.
2: Framed SPI modes require the use of all four pins (i.e., using the SSx pin is not optional).
3: The SPIxTXB and SPIxRXB registers are memory mapped to the SPIxBUF register.
When FRMEN (SPIxCON<14>) = 1 and MSTEN (SPIxCON<5>) = 1, the SCKx pin becomes an
output and the SPI clock at SCKx becomes a free running clock.
When FRMEN = 1 and MSTEN = 0, the SCKx pin becomes an input. The source clock provided
to the SCKx pin is assumed to be a free running clock.
The polarity of the clock is selected by the CKP (SPIxCON<6>) bit. The CKE (SPIxCON<8>) bit
is not used for the Framed SPI modes and should be programmed to ‘0’ by the user software.
When CKP = 0, the frame sync pulse output and the SDOx data output change on the rising edge
of the clock pulses at the SCKx pin. Input data is sampled at the SDIx input pin on the falling edge
of the serial clock.
When CKP = 1, the frame sync pulse output and the SDOx data output change on the falling
edge of the clock pulses at the SCKx pin. Input data is sampled at the SDIx input pin on the rising
edge of the serial clock.
20
Serial Peripheral
Interface (SPI)
When SPIFSD (SPIxCON<13>) = 0, the SPIx module is in the Frame Master mode of operation.
In this mode, the frame sync pulse is initiated by the module when the user software writes the
transmit data to SPIxBUF location (thus writing the SPIxTXB register with transmit data). At
the end of the frame sync pulse, the SPIxTXB is transferred to the SPIxSR and data
transmission/reception begins.
When SPIFSD (SPIxCON<13>) = 1, the module is in Frame Slave mode. In this mode, the frame
sync pulse is generated by an external source. When the module samples the frame sync pulse,
it will transfer the contents of the SPIxTXB register to the SPIxSR and data transmission/
reception begins. The user must make sure that the correct data is loaded into the SPIxBUF for
transmission before the frame sync pulse is received.
Note: Receiving a frame sync pulse will start a transmission, regardless of whether data
was written to SPIxBUF. If no write was performed, the old contents of SPIxTXB will
be transmitted.
This Framed SPI mode is enabled by setting the MSTEN (SPIxCON<5>) and FRMEN
(SPIxCON<14>) bits to ‘1’ and the SPIFSD (SPIxCON<13>) bit to ‘0’. In this mode, the serial
clock will be output continuously at the SCKx pin, regardless of whether the module is
transmitting. When the SPIxBUF is written, the SSx pin will be driven high on the next transmit
edge of the SCKx clock. The SSx pin will be high for one SCKx clock cycle. The module will start
transmitting data on the next transmit edge of the SCKx, as shown in Figure 20-8. A connection
diagram indicating signal directions for this Operating mode is shown in Figure 20-7.
SCKx
(CKP = 1)
SCKx
(CKP = 0)
SSx
This Framed SPI mode is enabled by setting the MSTEN, FRMEN and the SPIFSD bits to ‘1’.
The SSx pin is an input, and it is sampled on the sample edge of the SPI clock. When it is
sampled high, data will be transmitted on the subsequent transmit edge of the SPI clock, as
shown in Figure 20-9. The interrupt flag, SPIxIF, is set when the transmission is complete. The
user must make sure that the correct data is loaded into the SPIxBUF for transmission before the
signal is received at the SSx pin. A connection diagram indicating signal directions for this
Operating mode is shown in Figure 20-10.
SCKx
(CKP = 1)
SCK
(CKP = 0)
FSYNC
dsPIC30F PROCESSOR 2
[SPI Master, Frame Slave]
SDOx SDIx
SDIx SDOx
Serial Clock
SCKx SCKx
SSx SSx
Frame Sync.
Pulse
Note 1: In Framed SPI modes, the SSx pin is used to transmit/receive the frame synchronization
pulse.
2: Framed SPI modes require the use of all four pins (i.e., Using the SSx pin is not optional).
20
Serial Peripheral
Interface (SPI)
This framed SPI mode is enabled by setting the MSTEN (SPIxCON<5>) bit to ‘0’, the FRMEN
(SPIxCON<14>) bit to ‘1’ and the SPIFSD (SPIxCON<13>) bit to ‘0’. The input SPI clock will be
continuous in Slave mode. The SSx pin will be an output when the SPIFSD bit is low. Therefore,
when the SPIBUF is written, the module will drive the SSx pin high on the next transmit edge of
the SPI clock. The SSx pin will be driven high for one SPI clock cycle. Data will start transmitting
on the next SPI clock transmit edge. A connection diagram indicating signal directions for this
Operating mode is shown in Figure 20-11.
dsPIC30F PROCESSOR 2
[SPI Slave, Frame Slave]
SDOx SDIx
SDIx SDOx
Serial Clock
SCKx SCKx
SSx SSx
Frame Sync.
Pulse
Note 1: In Framed SPI modes, the SSx pin is used to transmit/receive the frame synchronization
pulse.
2: Framed SPI modes require the use of all four pins (i.e., Using the SSx pin is not optional).
This Framed SPI mode is enabled by setting the MSTEN (SPIxCON<5>) bit to ‘0’, the FRMEN
bit (SPIxCON<14>) to ‘1’ and the SPIFSD (SPIxCON<13>) bit to ‘1’. Therefore, both the SCKx
and SSx pins will be inputs. The SSx pin will be sampled on the sample edge of the SPI clock.
When SSx is sampled high, data will be transmitted on the next transmit edge of SCKx. A
connection diagram indicating signal directions for this Operating mode is shown in Figure 20-12.
dsPIC30F PROCESSOR 2
[SPI Master, Frame Slave]
SDOx SDIx
SDIx SDOx
Serial Clock
SCKx SCKx
SSx SSx
Frame Sync.
Pulse
Note 1: In Framed SPI modes, the SSx pin is used to transmit/receive the frame synchronization
pulse.
2: Framed SPI modes require the use of all four pins (i.e., Using the SSx pin is not optional).
Note: Note that the SCKx signal clock is not free running for normal SPI modes. It will only
run for 8 or 16 pulses when the SPIxBUF is loaded with data. It will however, be
continuous for Framed modes.
Equation 20-1 can be used to calculate the SCKx clock frequency as a function of the primary
and secondary prescaler settings.
Equation 20-1:
FCY
FSCK =
Primary Prescaler * Secondary Prescaler
Some sample SPI clock frequencies (in kHz) are shown in the table below:
Note: Not all clock rates are supported. For further information, refer to the SPI timing
specifications in the specific device data sheet.
20
Serial Peripheral
Interface (SPI)
The following are a consequence of entering Sleep mode when the SPIx module is configured
for master operation:
• The baud rate generator in the SPIx module stops and is reset.
• If the SPIx module enters Sleep mode in the middle of a transmission/reception, then the
transmission/reception is aborted. Since there is no automatic way to prevent an entry into
Sleep mode if a transmission or reception is pending, the user software must synchronize
entry into Sleep with SPI module operation to avoid aborted transmissions.
• The transmitter and receiver will stop in Sleep. The transmitter or receiver does not
continue with a partially completed transmission at wake-up.
Since the clock pulses at SCKx are externally provided for Slave mode, the module will continue
to function in Sleep mode. It will complete any transactions during the transition into Sleep. On
completion of a transaction, the SPIRBF flag is set. Consequently, the SPIxIF bit will be set. If
SPI interrupts are enabled (SPIxIE = 1), the device will wake from Sleep. If the SPI interrupt pri-
ority level is greater than the present CPU priority level, code execution will resume at the SPIx
interrupt vector location. Otherwise, code execution will continue with the instruction following the
PWRSAV instruction that previously invoked Sleep mode. The module is not reset on entering
Sleep mode if it is operating as a slave device.
Register contents are not affected when the SPIx module is going into or coming out of Sleep
mode.
20
Serial Peripheral
Interface (SPI)
DS70067C-page 20-22
SPI1BUF 0224 Transmit and Receive Buffer Address shared by SPI1TXB and SPI1RXB registers 0000 0000 0000 0000
IEC1 008E IC6IE IC5IE IC4IE IC3IE C1IE SPI2IE U2TXIE U2RXIE INT2IE T5IE T4IE OC4IE OC3IE IC8IE IC7IE INT1IE 0000 0000 0000 0000
IPC2 0098 — ADIP<2:0> — U1TXIP<2:0> — U1RXIP<2:0> — SPI1IP<2:0> 0100 0100 0100 0100
IPC6 00A0 — C1IP<2:0> — SPI2IP<2:0> — U2TXIP<2:0> — U2RXIP<2:0> 0100 0100 0100 0100
Note: Please visit the Microchip web site (www.microchip.com) for additional Application
Notes and code examples for the dsPIC30F Family of devices.
20
Serial Peripheral
Interface (SPI)
Inter-Integrated
Circuit (I2C)
Section 21. Inter-Integrated Circuit™ (I2C™)
HIGHLIGHTS
This section of the manual contains the following major topics:
21.1 Overview
The Inter-Integrated Circuit (I 2C) module is a serial interface useful for communicating with other
peripheral or microcontroller devices. These peripheral devices may be serial EEPROMs,
display drivers, A/D converters, etc.
The I 2C module can operate in any of the following I 2C systems:
• Where the dsPIC30F acts as a Slave Device
• Where the dsPIC30F acts as a Master Device in a Single Master System
(Slave may also be active)
• Where the dsPIC30F acts as a Master/Slave Device in a Multi-Master System
(Bus collision detection and arbitration available)
The I 2C module contains independent I 2C master logic and I 2C slave logic, each generating
interrupts based on their events. In multi-master systems, the software is simply partitioned into
master controller and slave controller.
When the I 2C master logic is active, the slave logic remains active also, detecting the state of the
bus and potentially receiving messages from itself in a single master system or from other
masters in a multi-master system. No messages are lost during multi-master bus arbitration.
In a multi-master system, bus collision conflicts with other masters in the system are detected
and the module provides a method to terminate then restart the message.
The I 2C module contains a baud rate generator. The I 2C baud rate generator does not consume
other timer resources in the device.
Inter-Integrated
Circuit (I2C)
Internal
Data Bus
I2CRCV
Read
Shift
SCL Clock
I2CRSR
LSB
SDA Address_Match
Match Detect
Write
I2CADD
Read
Start and
Stop bit Detect
Write
I2CSTAT
Start and Stop
bit Generate
Read
Control Logic
Collision
Detect
Write
I2CCON
Acknowledge
Read
Generation
Clock
Stretching Write
I2CTRN
Reload
Control Write
I2CBRG
BRG Down Counter
TCY/2 Read
dsPIC30F 5 kΩ 24LC256
VDD
SCL SCL VDD
MCLR
SDA SDA WP
VDD A0
4.7 μF 0.1 μF
VSS A1
A2
OSC1
OSC2
VSS
XTAL
Inter-Integrated
Circuit (I2C)
The following I2C bus protocol has been defined:
• Data transfer may be initiated only when the bus is not busy.
• During data transfer, the data line must remain stable whenever the SCL clock line is HIGH.
Changes in the data line while the SCL clock line is HIGH will be interpreted as a Start or
Stop condition.
Accordingly, the following bus conditions have been defined (Figure 21-3).
After a bus Idle state, a HIGH-to-LOW transition of the SDA line while the clock (SCL) is HIGH
determines a Start condition. All data transfers must be preceded by a Start condition.
A LOW-to-HIGH transition of the SDA line while the clock (SCL) is HIGH determines a Stop
condition. All data transfers must end with a Stop condition.
After a WAIT state, a HIGH-to-LOW transition of the SDA line while the clock (SCL) is HIGH
determines a Repeated Start condition. Repeated Starts allow a master to change bus direction
without relinquishing control of the bus.
The state of the SDA line represents valid data when, after a Start condition, the SDA line is
stable for the duration of the HIGH period of the clock signal. There is one bit of data per SCL
clock.
All data byte transmissions must be Acknowledged (ACK) or Not Acknowledged (NACK) by the
receiver. The receiver will pull the SDA line low for an ACK or release the SDA line for a NACK.
The Acknowledge is a one-bit period, using one SCL clock.
The data on the line must be changed during the LOW period of the clock signal. Devices may
also stretch the clock low time, by asserting a low on SCL line, causing a WAIT on the bus.
Both data and clock lines remain HIGH at those times after a Stop condition and before a Start
condition.
SDA NACK
ACK
Figure 21-4: A Typical I2C™ Message: Read of Serial EEPROM (Random Address Mode)
R
E
S S
I T T N S I
D A Address RA EE ADDR A EE ADDR A A Address RA Data A T D
Bus L R Byte / C High Byte C Low Byte CR Byte / C Byte C O L
Activity E T WK K K T WK K P E
Master
SDA S1 01 0 AAA0 X R 1 0 1 0 A A A1 NP
2 1 0 2 1 0
Output
Slave
SDA A A A A
Output
Each message is initiated with a “Start” condition and terminated with a “Stop” condition. The
number of the data bytes transferred between the Start and Stop conditions is determined by the
master device. As defined by the system protocol, the bytes of the message may have special
meaning such as “device address byte” or “data byte”.
In the figure, the first byte is the device address byte that must be the first part of any I 2C
message. It contains a device address and a R/W bit. Refer to “Section 26. Appendix” for
additional information on Address Byte formats. Note that R/W = 0 for this first address byte,
indicating that the master will be a transmitter and the slave will be a receiver.
The receiving device is obliged to generate an Acknowledge signal, “ACK”, after the reception of
each byte. The master device must generate an extra SCL clock, which is associated with this
Acknowledge bit.
The next 2 bytes, sent by the master to the slave, are data bytes containing the location of the
requested EEPROM data byte. The slave must Acknowledge each of the data bytes.
At this point, the slave EEPROM has the address information necessary to return the requested
data byte to the master. However, the R/W bit from the first device address byte specified master
transmission and slave reception. The bus must be turned in the other direction for the slave to
send data to the master.
To do this function without ending the message, the master sends a “Repeated Start”. The
Repeated Start is followed with a device address byte containing the same device address as
before and with the R/W = 1 to indicate slave transmission and master reception.
Inter-Integrated
Circuit (I2C)
Now the slave transmits the data byte driving the SDA line, while the master continues to
originate clocks but releases its SDA drive.
During reads, a master must terminate data requests to the slave by NOT Acknowledging
(generate a “NACK”) on the last byte of the message.
The master sends Stop to terminate the message and return the bus to an Idle state.
I2CRCV (8 bits)
Bit 7 Bit 0
I2CTRN (8 bits)
Bit 7 Bit 0
I2CBRG (9 bits)
Bit 8 Bit 0
I2CCON (16 bits)
Bit 15 Bit 0
I2CSTAT (16 bits)
Bit 15 Bit 0
I2CADD (10 bits)
Bit 9 Bit 0
Register 21-1 and Register 21-2 define the I2C module Control and Status registers, I2CCON
and I2CSTAT.
The I2CTRN is the register to which transmit data is written. This register is used when the
module operates as a master transmitting data to the slave or as a slave sending reply data to
the master. As the message progresses, the I2CTRN register shifts out the individual bits.
Because of this, the I2CTRN may not be written to unless the bus is Idle. The I2CTRN may be
reloaded while the current data is transmitting.
Data being received by either the master or the slave is shifted into a non-accessible Shift
register called I2CRSR. When a complete byte is received, the byte transfers to the I2CRCV
register. In receive operations, the I2CRSR and I2CRCV create a double-buffered receiver. This
allows reception of the next byte to begin before reading the current byte of received data.
If the module receives another complete byte before the software reads the previous byte from
the I2CRCV register, a receiver overflow occurs and sets the I2COV (I2CCON<6>). The byte in
the I2CRSR is lost.
The I2CADD register holds the slave device address. In 10-bit mode, all bits are relevant. In
7-bit addressing mode, only I2CADD<6:0> are relevant. The A10M (I2CCON<10>) specifies the
expected mode of the slave address.
Inter-Integrated
Upper Byte:
Circuit (I2C)
R/W-0 U-0 R/W-0 R/W-1 R/W-0 R/W-0 R/W-0 R/W-0
HC
I2CEN — I2CSIDL SCLREL IPMIEN A10M DISSLW SMEN
bit 15 bit 8
Lower Byte:
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
HC HC HC HC HC
GCEN STREN ACKDT ACKEN RCEN PEN RSEN SEN
bit 7 bit 0
Legend:
R = Readable C = Clearable bit U = Unimplemented bit, read as ‘0’
W = Writable HS = Set by Hardware S = Settable bit
HC = Cleared by Hardware ‘0’ = Bit cleared at POR x = Bit is unknown at POR
‘1’ = Bit is set at POR
Inter-Integrated
Upper Byte:
Circuit (I2C)
R-0 R-0 U-0 U-0 U-0 R/C-0 R-0 R-0
HS, HC HS, HC HS HS, HC HS, HC
ACKSTAT TRSTAT — — — BCL GCSTAT ADD10
bit 15 bit 8
Lower Byte:
R/C-0 R/W-0 R-0 R/C-0 R/C-0 R-0 R-0 R-0
HS HS HS, HC HS, HC HS, HC HS, HC HS, HC HS, HC
IWCOL I2COV D_A P S R_W RBF TBF
bit 7 bit 0
Legend:
R = Readable W = Writable C = Clearable bit
HC = Cleared by Hardware HS = Set by Hardware U = Unimplemented bit, read as ‘0’
‘1’ = Bit is set at POR ‘0’ = Bit cleared at POR x = Bit is unknown at POR
Inter-Integrated
The module is enabled by setting the I2CEN (I2CCON<15>) bit.
Circuit (I2C)
The I 2C module fully implements all master and slave functions. When the module is enabled,
the master and slave functions are active simultaneously and will respond according to the
software or the bus events.
When initially enabled, the module will release SDA and SCL pins, putting the bus into the Idle
state. The master functions will remain in the Idle state unless software sets a control bit to
initiate a master event. The slave functions will begin to monitor the bus. If the slave logic
detects a Start event and a valid address on the bus, the slave logic will begin a slave
transaction.
21.4.2 I 2C Interrupts
The I 2C module generates two interrupts. One interrupt is assigned to master events and the
other interrupt is assigned to slave events. These interrupts will set a corresponding interrupt
flag bit and will interrupt the software process if the corresponding interrupt enable bit is set and
the corresponding interrupt priority is high enough.
The master interrupt is called MI2CIF and is activated on completion of a master message
event.
The following events generate the MI2CIF interrupt.
• Start condition
• Stop condition
• Data transfer byte transmitted/received
• Acknowledge transmit
• Repeated Start
• Detection of a bus collision event
The slave interrupt is called SI2CIF and is activated on detection of a message directed to the
slave.
• Detection of a valid device address (including general call)
• Request to transmit data
• Reception of data
To compute the baud rate generator reload value, use the following equation.
Equation 21-1:
I2CBRG = ( FFSCL
CY – FCY
1,111,111
) –1
I2CBRG<8:0>
Reload Reload
SCL
Control
Inter-Integrated
Typical operation of the I 2C module in a system is using the I 2C to communicate with an I 2C
Circuit (I2C)
peripheral, such as an I 2C serial memory. In an I 2C system, the master controls the sequence
of all data communication on the bus. In this example, the dsPIC30F and its I 2C module have
the role of the single master in the system. As the single master, it is responsible for generating
the SCL clock and controlling the message protocol.
In the I 2C module, the module controls individual portions of the I 2C message protocol,
however, sequencing of the components of the protocol to construct a complete message is a
software task.
For example, a typical operation in a single master environment may be to read a byte from an
I 2C serial EEPROM. This example message is depicted in Figure 21-7.
To accomplish this message, the software will sequence through the following steps.
1. Assert a Start condition on SDA and SCL.
2. Send the I 2C device address byte to the slave with a write indication.
3. Wait for and verify an Acknowledge from the slave.
4. Send the serial memory address high byte to the slave.
5. Wait for and verify an Acknowledge from the slave.
6. Send the serial memory address low byte to the slave.
7. Wait for and verify an Acknowledge from the slave.
8. Assert a Repeated Start condition on SDA and SCL.
9. Send the device address byte to the slave with a read indication.
10. Wait for and verify an Acknowledge from the slave.
11. Enable master reception to receive serial memory data.
12. Generate an ACK or NACK condition at the end of a received byte of data.
13. Generate a Stop condition on SDA and SCL.
Figure 21-7: A Typical I2C™ Message: Read Of Serial EEPROM (Random Address Mode)
R
E
S S
I T T N S I
D A Address RA EE ADDR A EE ADDR A A Address RA Data A T D
Bus L R Byte / C High Byte C Low Byte CR Byte / C Byte C O L
Activity E T WK K K T WK K P E
Master
SDA S10 1 0AAA0 R 1 0 1 0 A A A1 NP
2 1 0 2 1 0
Output
Slave
SDA A A A A
Output
The I 2C module supports Master mode communication with the inclusion of Start and Stop
generators, data byte transmission, data byte reception, Acknowledge generator and a baud
rate generator.
Generally, the software will write to a control register to start a particular step, then wait for an
interrupt or poll status to wait for completion.
Subsequent sub-sections detail each of these operations
If the software writes the I2CTRN when a Start sequence is in progress, then IWCOL is set and
the contents of the transmit buffer are ignored.
Note: Because queueing of events is not allowed, writing to the lower 5 bits of I2CCON is
disabled until the Start condition is complete.
MI2CIF Interrupt
1 2 3 4
Inter-Integrated
Circuit (I2C)
Transmission of a data byte, a 7-bit device address byte or the second byte of a 10-bit address,
is accomplished by simply writing the appropriate value to the I2CTRN register. Loading this
register will start the following process:
• The software loads the I2CTRN with the data byte to transmit.
• Writing I2CTRN sets the buffer full flag bit, TBF (I2CSTAT<0>).
• The data byte is shifted out the SDA pin until all 8 bits are transmitted. Each bit of
address/data will be shifted out onto the SDA pin after the falling edge of SCL.
• On the ninth SCL clock, the module shifts in the ACK bit from the slave device and writes its
value into the ACKSTAT bit (I2CCON<15>).
• The module generates the MI2CIF interrupt at the end of the ninth SCL clock cycle.
Note that the module does not generate or validate the data bytes. The contents and usage of
the byte is dependant on the state of the message protocol maintained by the software.
Sending a 7-bit device address involves sending 1 byte to the slave. A 7-bit address byte must
contain the 7 bits of I 2C device address and a R/W bit that defines if the message will be a write
to the slave (master transmission and slave receiver) or a read from the slave (slave transmission
and master receiver).
Sending a 10-bit device address involves sending 2 bytes to the slave. The first byte contains 5
bits of I 2C device address reserved for 10-bit Addressing modes and 2 bits of the 10-bit address.
Because the next byte, which contains the remaining 8 bits of the 10-bit address must be
received by the slave, the R/W bit in the first byte must be ‘0’, indicating master transmission and
slave reception. If the message data is also directed toward the slave, the master can continue
sending the data. However, if the master expects a reply from the slave, a Repeated Start
sequence with the R/W bit at ‘1’ will change the R/W state of the message to a read of the slave.
On the falling edge of the eighth SCL clock, the TBF bit is cleared and the master will de-assert
the SDA pin allowing the slave to respond with an Acknowledge. The master will then generate
a ninth SCL clock.
This allows the slave device being addressed to respond with an ACK bit during the ninth
bit time if an address match occurs, or if data was received properly. A slave sends an
Acknowledge when it has recognized its device address (including a general call), or when the
slave has properly received its data.
The status of ACK is written into the Acknowledge status bit, ACKSTAT (I2CSTAT<15>), on the
falling edge of the ninth SCL clock. After the ninth SCL clock, the module generates the MI2CIF
interrupt and enters an Idle state until the next data byte is loaded into I2CTRN.
The ACKSTAT bit (I2CCON<15>) is cleared when the slave has sent an Acknowledge
(ACK = 0), and is set when the slave does not Acknowledge (ACK = 1).
When transmitting, the TBF bit (I2CSTAT<0>) is set when the CPU writes to I2CTRN and is
cleared when all 8 bits are shifted out.
If the software writes the I2CTRN when a transmit is already in progress (i.e., the module is still
shifting out a data byte), then IWCOL is set and the contents of the buffer are ignored. IWCOL
must be cleared in software.
Note: Because queueing of events is not allowed, writing to the lower 5 bits of I2CCON is
disabled until the transmit condition is complete.
I2CTRN
I2C™ Bus State (Q) (D) (Q) (D) (Q) (A) (Q)
TBRG TBRG
SCL (Master)
SCL (Slave)
SDA (Master) D7 D6 D5 D4 D3 D2 D1 D0
SDA (Slave)
TRSTAT
TBF
MI2CIF Interrupt
ACKSTAT
1 2 3 4 5 6 7 8
1 - Writing the I2CTRN register will start a master transmission event. TBF bit is set.
2 - Baud generator starts. The MSB of the I2CTRN drives SDA. SCL remains low. TRSTAT bit is set.
4 - Baud generator times out. SCL driven low. After SCL detected low, next bit of I2CTRN drives SDA.
5 - While SCL is low, the slave can also pull SCL low to initiate a WAIT (clock stretch).
6 - Master has already released SCL, and slave can release to end WAIT. Baud generator restarts.
7 - At falling edge of 8th SCL clock, master releases SDA. TBF bit is cleared. Slave drives ACK/NACK.
8 - At falling edge of 9th SCL clock, master generates interrupt. SCL remains low until next event.
Slave releases SDA. TRSTAT bit is clear.
Inter-Integrated
Circuit (I2C)
Setting the receive enable bit, RCEN (I2CCON<3>), enables the master to receive data from a
slave device.
Note: The lower 5 bits of I2CCON must be ‘0’ before attempting to set the RCEN bit. This
ensures the master logic is inactive.
The master logic begins to generate clocks and before each falling edge of the SCL, SDA line is
sampled and data is shifted into the I2CRSR.
After the falling edge of the eighth SCL clock:
• The RCEN bit is automatically cleared.
• The contents of the I2CRSR transfer into the I2CRCV.
• The RBF flag bit is set.
• The module generates the MI2CIF interrupt.
When the CPU reads the buffer, the RBF flag bit is automatically cleared. The software can
process the data and then do an Acknowledge sequence.
When receiving data, the RBF bit is set when an device address or data byte is loaded into
I2CRCV from I2CRSR. It is cleared when software reads the I2CRCV register.
If another byte is received in the I2CRSR while the RBF bit remains set and the previous byte
remains in the I2CRCV register, the I2COV bit is set and the data in the I2CRSR is lost.
Leaving I2COV set does not inhibit further reception. If RBF is cleared by reading the I2CRCV,
and the I2CRSR receives another byte, that byte will be transferred to the I2CRCV.
If the software writes the I2CTRN when a receive is already in progress (i.e., I2CRSR is still
shifting in a data byte), then the IWCOL bit is set and the contents of the buffer are ignored.
Note: Since queueing of events is not allowed, writing to the lower 5 bits of I2CCON is
disabled until the data reception condition is complete.
RCEN
I2C™ Bus State (Q) (Q) (D) (Q) (Q) (D) (Q)
TBRG TBRG
SCL (Master)
SCL (Slave)
SDA (Master)
SDA (Slave) D7 D6 D5 D4 D3 D2 D1 D0
I2CRCV
RBF
MI2CIF Interrupt
1 2 3 4 5 6
1 - Typically, the slave can pull SCL low (clock stretch) to request a wait to prepare data response.
The slave will drive MSB of data response on SDA when ready.
2 - Writing the RCEN bit will start a master reception event. The baud generator starts. SCL remains low.
5 - Baud generator times out. MSB of response shifted to I2CRSR. SCL driven low for next baud interval.
6 - At falling edge of 8th SCL clock, I2CRSR transferred to I2CRCV. Module clears RCEN bit.
RBF bit is set. Master generates interrupt.
Inter-Integrated
Circuit (I2C)
Setting the Acknowledge sequence enable bit, ACKEN (I2CCON<4>), enables generation of a
master Acknowledge sequence.
Note: The lower 5 bits of I2CCON must be ‘0’ (master logic inactive) before attempting to
set the ACKEN bit.
Figure 21-11 shows an ACK sequence and Figure 21-12 shows a NACK sequence. The
Acknowledge data bit, ACKDT (I2CCON<5>), specifies ACK or NACK.
After two baud periods:
• The ACKEN bit is automatically cleared.
• The module generates the MI2CIF interrupt.
If the software writes the I2CTRN when an Acknowledge sequence is in progress, then IWCOL
is set and the contents of the buffer are ignored.
Note: Because queueing of events is not allowed, writing to the lower 5 bits of I2CCON is
disabled until the Acknowledge condition is complete.
ACKDT = 0
1 2 3 4
ACKDT = 1
1 2 3 4
Note: The lower 5 bits of I2CCON must be ‘0’ (master logic inactive) before attempting to
set the PEN bit.
When the PEN bit is set, the master generates the Stop sequence as shown in Figure 21-13.
• The slave detects the Stop condition, sets the P bit (I2CSTAT<4>) and clears the S bit
(I2CSTAT<3>).
• The PEN bit is automatically cleared.
• The module generates the MI2CIF interrupt.
If the software writes the I2CTRN when a Stop sequence is in progress, then the IWCOL bit is
set and the contents of the buffer are ignored.
Note: Because queueing of events is not allowed, writing to the lower 5 bits of I2CCON is
disabled until the Stop condition is complete.
1 2 3 4 5
Inter-Integrated
Circuit (I2C)
Setting the Repeated Start sequence enable bit, RSEN (I2CCON<1>), enables generation of a
master Repeated Start sequence (see Figure 21-14).
Note: The lower 5 bits of I2CCON must be ‘0’ (master logic inactive) before attempting to
set the RSEN bit.
To generate a Repeated Start condition, software sets the RSEN bit (I2CCON<1>). The module
asserts the SCL pin low. When the module samples the SCL pin low, the module releases the
SDA pin for one baud rate generator count (TBRG). When the baud rate generator times out, if
the module samples SDA high, the module de-asserts the SCL pin. When the module samples
SCL pin high, the baud rate generator reloads and begins counting. SDA and SCL must be
sampled high for one TBRG. This action is then followed by assertion of the SDA pin low for one
TBRG while SCL is high.
The following is the Repeated Start sequence:
• The slave detects the Start condition, sets the S bit (I2CSTAT<3>) and clears the P bit
(I2CSTAT<4>).
• The RSEN bit is automatically cleared.
• The module generates the MI2CIF interrupt.
If the software writes the I2CTRN when a Repeated Start sequence is in progress, then IWCOL
is set and the contents of the buffer are ignored.
Note: Because queueing of events is not allowed, writing of the lower 5 bits of I2CCON is
disabled until the Repeated Start condition is complete.
SDA (Master) 3 - Baud generator times out. Module drives SDA low.
Baud generator restarts.
S
4 - Slave logic detects Start. Module sets S = 1, P = 0.
P
MI2CIF Interrupt 5 - The baud generator times out. Module drives SCL low.
Module clears RSEN. Master generates interrupt.
1 2 3 4 5
The software will begin a message by issuing a Start command. The software will record the state
number corresponding to Start.
As each event completes and generates an interrupt, the interrupt handler may check the state
number. So, for a Start state, the interrupt handler will confirm execution of the Start sequence
and then start a master transmission event to send the I2C device address, changing the state
number to correspond to master transmission.
On the next interrupt, the interrupt handler will again check the state, determining that a master
transmission just completed. The interrupt handler will confirm successful transmission of the
data, then move on to the next event, depending on the contents of the message.
In this manner, on each interrupt, the interrupt handler will progress through the message
protocol until the complete message is sent.
Figure 21-15 provides a more detailed examination of the same message sequence of
Figure 21-7.
Figure 21-16 shows some simple examples of messages using 7-bit addressing format.
Figure 21-17 shows an example of a 10-bit address format message sending data to a slave.
Figure 21-18 shows an example of a 10-bit address format message receiving data from a slave.
SEN
RSEN
T
RCEN
ACKEN
ACKDT
A9
A8
A11
A10
SCL
(Slave)
SDA
(Slave) A A A A D7D6D5D4D3D2D1D0
I2CTRN
TBF
I2CRCV
RBF
ACKSTAT
MI2CIF cleared by user software.
MI2CIF
1 2 3 4 5 6 7 8 9
1 - Setting the SEN bit starts a Start event. 6 - Writing the I2CTRN register starts a master transmission. The data is a resend of
the serial EE device address byte, but with R/W bit set indicating a read.
2 - Writing the I2CTRN register starts a master transmission. The data is the serial
EE device address byte, with R/W clear indicating a write. 7 - Setting the RCEN bit starts a master reception. On interrupt, the software reads
the I2CRCV register, which clears the RBF flag.
3 - Writing the I2CTRN register starts a master transmission. The data is the first
byte of the EE data address. 8 - Setting the ACKEN bit starts an Acknowledge event. ACKDT = 1 to send NACK.
4 - Writing the I2CTRN register starts a master transmission. The data is the second 9 - Setting the PEN bit starts a master Stop event.
byte of the EE data address.
5 - Setting the RSEN bit starts a Repeated Start event.
DS70068D-page 21-25
Section 21. Inter-Integrated Circuit (I2C)
Circuit (I2C)
21
Inter-Integrated
Figure 21-16: Master Message (7-bit Address: Transmission And Reception)
SEN
RSEN
RCEN
DS70068D-page 21-26
ACKEN
ACKDT
PEN
SCL
(Master) 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9
SDA
(Master) A6A5A4A3A2 A1A0 W D7D6D5D4D3D2D1D0 A6A5A4A3A2 A1A0 R N
SCL
(Slave)
SDA
(Slave) A A A D7D6D5D4D3D2D1D0
I2CTRN
TBF
I2CRCV
dsPIC30F Family Reference Manual
RBF
ACKSTAT
MI2CIF cleared by user software.
MI2CIF
1 2 3 4 5 6 7 8 9
1 - Setting the SEN bit starts a Start event. 6 - Writing the I2CTRN register starts a master transmission. The data is the
address byte with R/W bit set.
2 - Writing the I2CTRN register starts a master transmission. The data is the
address byte with R/W bit clear. 7 - Setting the RCEN bit starts a master reception.
3 - Writing the I2CTRN register starts a master transmission. The data is the 8 - Setting the ACKEN bit starts an Acknowledge event. ACKDT = 1 to send NACK.
message byte.
4 - Setting the PEN bit starts a master Stop event. 9 - Setting the PEN bit starts a master Stop event.
SEN
RSEN
T
RCEN
ACKEN
ACKDT
I2CTRN
TBF
I2CRCV
RBF
ACKSTAT
MI2CIF cleared by user software.
MI2CIF
1 2 3 4 5 6 7
1 - Setting the SEN bit starts a Start event. 5 - Writing the I2CTRN register starts a master transmission. The data is the second
byte of the message data.
2 - Writing the I2CTRN register starts a master transmission. The data is the first
6 - Writing the I2CTRN register starts a master transmission. The data is the third
byte of the address.
byte of the message data.
3 - Writing the I2CTRN register starts a master transmission. The data is the second
byte of the address. 7 - Setting the PEN bit starts a master Stop event.
4 - Writing the I2CTRN register starts a master transmission. The data is the first
byte of the message data.
DS70068D-page 21-27
Section 21. Inter-Integrated Circuit (I2C)
Circuit (I2C)
21
Inter-Integrated
Figure 21-18: Master Message (10-bit Reception)
SEN
RSEN
RCEN
DS70068D-page 21-28
ACKEN
ACKDT
PEN
SCL
(Master) 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9
SDA
(Master) 1 1 1 1 0 A9A8 W A7A6A5A4A3A2A1A0 1 1 1 1 0 A9A8 R A N
SCL
(Slave)
SDA
(Slave) A A A D7D6D5D4D3D2D1D0 D7D6D5D4D3D2D1D0
I2CTRN
TBF
I2CRCV
dsPIC30F Family Reference Manual
RBF
ACKSTAT
MI2CIF cleared in user software.
MI2CIF
1 2 3 4 5 6 7 8 9 10
1 - Setting the SEN bit starts a Start event. 6 - Setting the RCEN bit starts a master reception. On interrupt, the software reads
the I2CRCV register, which clears the RBF flag.
2 - Writing the I2CTRN register starts a master transmission. The data is the first
byte of the address with the R/W bit cleared. 7 - Setting the ACKEN bit starts an Acknowledge event. ACKDT = 0 to send ACK.
3 - Writing the I2CTRN register starts a master transmission. The data is the second 8 - Setting the RCEN bit starts a master reception.
byte of the address.
4 - Setting the RSEN bit starts a master REStart event. 9 - Setting the ACKEN bit starts an Acknowledge event. ACKDT = 1 to send NACK.
5 - Writing the I2CTRN register starts a master transmission. The data is a resend 10 - Setting the PEN bit starts a master Stop event.
of the first byte with the R/W bit set.
Inter-Integrated
The I2C protocol allows for more than one master to be attached to a system bus. Remember-
Circuit (I2C)
ing that a master can initiate message transactions and generate clocks for the bus, the
protocol has methods to account for situations where more than one master is attempting to
control the bus. Clock synchronization ensures that multiple nodes can synchronize their SCL
clocks to result in one common clock on the SCL line. Bus arbitration ensures that if more than
one node attempts a message transaction, one and only one node will be successful in
completing the message. The other nodes will lose bus arbitration and be left with a bus
collision.
TBRG TBRG
SDA (Master)
SCL (Master)
SCL (Slave)
Baud Counter 000 003 002 001 000 003 002 001 000 003
TCY
1 2 3 4 5 6
1 - The baud counter decrements twice per TCY. On rollover, the master SCL will transition.
2 - The slave has pulled SCL low to initiate a wait.
3 - At what would be the master baud counter rollover, detecting SCL low holds counter.
4 - Logic samples SCL once per TCY. Logic detects SCL high.
Inter-Integrated
Circuit (I2C)
Before issuing a Start command, the software should verify an Idle state of the bus using the S
and P status bits. Two masters may attempt to initiate a message at a similar point in time.
Typically, the masters will synchronize clocks and continue arbitration into the message until
one loses arbitration. However, certain conditions can cause a bus collision to occur during a
Start. In this case, the master that loses arbitration during the Start bit generates a bus collision
interrupt.
TBRG TBRG
1 - Master transmits bit value of ‘1’ in next SCL clock.
SCL (Master)
Module releases SDA.
SDA (Master)
2 - Another master on bus transmits bit value of ‘0’
SCL (Bus) in next SCL clock. Another master pulls SDA low.
MI2CIF Interrupt
1 2 3
10-bit
Address R
E
S First Second Command S Status
T TR N S
A Address RA Address A Data A A Address RA Data A T
Bus R Byte / C Byte C Byte CR Byte / C Byte C O
Activity T WK K K T WK K P
Master
SDA S111 1 0AA0 AAA AA A A A
R 1 1 1 1 0 A A1 NP
9 8 7 65 43 2 1 0 9 8
Output
Slave
SDA A A A A
Output
After a Start condition, the slave module will receive and check the device address. The slave
may specify either a 7-bit address or a 10-bit address. When a device address is matched, the
module will generate an interrupt to notify the software that its device is selected. Based on the
R/W bit sent by the master, the slave will either receive or transmit data. If the slave is to receive
data, the slave module automatically generates the Acknowledge (ACK), loads the I2CRCV
register with the received value currently in the I2CRSR register and notifies the software
through an interrupt. If the slave is to transmit data, the software must load the I2CTRN register.
Inter-Integrated
Circuit (I2C)
0x00 General call address or start byte
0x01-0x03 Reserved
0x04-0x77 Valid 7-bit addresses
0x78-0x7b Valid 10-bit addresses (lower 7 bits)
0x7c-0x7f Reserved
Refer to dsPIC30F Family Reference Manual (DS70046) for descriptions of register bit fields.
Following the Start condition, the module shifts 8 bits into the I2CRSR register (see
Figure 21-22). The value of register I2CRSR<7:1> is compared to the value of the
I2CADD<6:0> register. The device address is compared on the falling edge of the eighth clock
(SCL). If the addresses match, the following events occur:
1. An ACK is generated.
2. The D_A and R_W bits are cleared.
3. The module generates the SI2CIF interrupt on the falling edge of the ninth SCL clock.
4. The module will wait for the master to send data.
I2C™ Bus State (S) (D) (D) (D) (A) (Q) 1 - Detecting Start bit enables
address detection.
SCL (Master)
2 - R/W = 0 bit indicates that slave
SDA (Master) A6 A5 A4 A3 A2 A1 A0 R/W
=0 receives data bytes.
SDA (Slave) 3 - Address match of first byte clears
D_A bit. Slave generates ACK.
SI2CIF Interrupt
4 - R_W bit cleared. Slave generates
R_W interrupt.
D_A 5 - Bus waiting. Slave ready to
receive data.
ADD10
SCLREL
1 2 3 4 5
When a slave read is specified by having R/W = 1 in a 7-bit address byte, the process of
detecting the device address is similar to that for a slave write (see Figure 21-23). If the
addresses match, the following events occur:
1. An ACK is generated.
2. The D_A bit is cleared and the R_W bit is set.
3. The module generates the SI2CIF interrupt on the falling edge of the ninth SCL clock.
Since the slave module is expected to reply with data at this point, it is necessary to suspend the
operation of the I 2C bus to allow the software to prepare a response. This is done automatically
when the module clears the SCLREL bit. With SCLREL low, the slave module will pull down the
SCL clock line, causing a wait on the I 2C bus. The slave module and the I 2C bus will remain in
this state until the software writes the I2CTRN register with the response data and sets the
SCLREL bit.
Note: SCLREL will automatically clear after detection of a slave read address regardless of
the state of the STREN bit.
I2C™ Bus State (S) (D) (D) (D) (A) (Q) 1 - Detecting Start bit enables
address detection.
SCL (Master)
2 - R/W = 1 bit indicates that slave
SCL (Slave) sends data bytes.
SDA (Master) A6 A5 A4 A3 A2 A1 A0 R/W 3 - Address match of first byte clears
=1
D_A bit. Slave generates ACK.
SDA (Slave)
4 - R_W bit set. Slave generates
SI2CIF Interrupt
interrupt. SCLREL cleared.
R_W Slave pulls SCL low while
SCLREL = 0.
D_A
5 - Bus waiting. Slave prepares to
ADD10 send data.
SCLREL
1 2 3 4 5
Inter-Integrated
Circuit (I2C)
In 10-bit Address mode, the slave must receive two device address bytes (see Figure 21-24).
The five Most Significant bits (MSbs) of the first address byte specify a 10-bit address. The R/W
bit of the address must specify a write, causing the slave device to receive the second address
byte. For a 10-bit address the first byte would equal ‘11110 A9 A8 0’, where A9 and A8 are
the two MSbs of the address.
Following the Start condition, the module shifts 8 bits into the I2CRSR register. The value of reg-
ister I2CRSR<2:1> is compared to the value of the I2CADD<9:8> register. The value of
I2CRSR<7:3> is compared to ‘11110’. The device address is compared on the falling edge of
the eighth clock (SCL). If the addresses match, the following events occur:
1. An ACK is generated.
2. The D_A and R_W bits are cleared.
3. The module generates the SI2CIF interrupt on the falling edge of the ninth SCL clock.
The module does generate an interrupt after the reception of the first byte of a 10-bit address,
however this interrupt is of little use.
The module will continue to receive the second byte into I2CRSR. This time, I2CRSR<7:0> is
compared to I2CADD<7:0>. If the addresses match, the following events occur:
1. An ACK is generated.
2. The ADD10 bit is set.
3. The module generates the SI2CIF interrupt on the falling edge of the ninth SCL clock.
4. The module will wait for the master to send data or initiate a Repeated Start condition.
Note: Following a Repeated Start condition in 10-bit mode, the slave module only matches
the first 7-bit address, ‘11110 A9 A8 0’.
I2C™ Bus State (S) (D) (D) (D) (A) (D) (D) (D) (A) (Q)
SCL (Master)
R/W
SDA (Master) 1 1 1 1 0 A9 A8 =0 A7 A6 A5 A4 A3 A2 A1 A0
SDA (Slave)
SI2CIF Interrupt
R_W
D_A
ADD10
SCLREL
1 2 3 4 5 6
3 - Reception of first byte clears R_W bit. Slave logic generates interrupt.
4 - Address match of first and second byte sets ADD10 and causes slave logic to generate ACK.
5 - Reception of second byte completes 10-bit address. Slave logic generates interrupt.
The addressing procedure for the I2C bus is such that the first byte after a Start condition usually
determines which slave device the master is addressing. The exception is the general call
address, which can address all devices. When this address is used, all enabled devices should
respond with an Acknowledge. The general call address is one of eight addresses reserved for
specific purposes by the I2C protocol. It consists of all ‘0’s with R/W = 0. The general call is
always a slave write operation.
The general call address is recognized when the general call enable bit, GCEN (I2CCON<7>),
is set (see Figure 21-25). Following a Start bit detect, 8 bits are shifted into the I2CRSR and the
address is compared against the I2CADD, and is also compared to the general call address.
If the general call address matches, the following events occur:
1. An ACK is generated.
2. Slave module will set the GCSTAT bit (I2CSTAT<9>).
3. The D_A and R_W bits are cleared.
4. The module generates the SI2CIF interrupt on the falling edge of the ninth SCL clock.
5. The I2CRSR is transferred to the I2CRCV and the RBF flag bit is set (during the eighth
bit).
6. The module will wait for the master to send data.
When the interrupt is serviced, the cause for the interrupt can be checked by reading the
contents of the GCSTAT bit to determine if the device address was device specific or a general
call address.
Note that general call addresses are 7-bit addresses. If A10M bit is set, configuring the slave
module for 10-bit addresses and GCEN is set, the slave module continues to detect the 7-bit
general call address.
1 2 3 4 5
Inter-Integrated
Some I 2C system protocols require a slave to act upon all messages on the bus. For example,
Circuit (I2C)
the IPMI (Intelligent Peripheral Management Interface) bus uses I 2C nodes as message repeat-
ers in a distributed network. To allow a node to repeat all messages, the slave module must
accept all messages, regardless of the device address.
Setting the IPMIEN bit (I2CCON<11>) enables this mode (see Figure 21-26). Regardless of the
state of the I2CADD register and the A10M and GCEN bits, all addresses will be accepted.
1 2 3 4
If a 7-bit address does not match the contents of I2CADD<6:0>, the slave module will return to
an Idle state and ignore all bus activity until after the Stop condition.
If the first byte of a 10-bit address does not match the contents of I2CADD<9:8>, the slave
module will return to an Idle state and ignore all bus activity until after the Stop condition.
If the first byte of a 10-bit address matches the contents of I2CADD<9:8>, however, the second
byte of the 10-bit address does not match I2CADD<7:0>, the slave module will return to an Idle
state and ignore all bus activity until after the Stop condition.
Normally, the slave module will Acknowledge all received bytes by sending an ACK on the ninth
SCL clock. If the receive buffer is overrun, the slave module does not generate this ACK.
Overrun is indicated if either (or both):
1. The buffer full bit, RBF (I2CSTAT<1>), was set before the transfer was received.
2. The overflow bit, I2COV (I2CSTAT<6>), was set before the transfer was received.
Table 21-4 shows what happens when a data transfer byte is received, given the status of the
RBF and I2COV bits. If the RBF bit is already set when the slave module attempts to transfer to
the I2CRCV, the transfer does not occur but the interrupt is generated and the I2COV bit is set.
If both the RBF and I2COV bits are set, the slave module acts similarly. The shaded cells show
the condition where software did not properly clear the overflow condition.
Reading the I2CRCV clears the RBF bit. The I2COV is cleared by writing to a ‘0’ through
software.
When the slave module receives a data byte, the master can potentially begin sending the next
byte immediately. This allows the software controlling the slave module 9 SCL clock periods to
process the previously received byte. If this is not enough time, the slave software may want to
generate a bus WAIT period.
The STREN bit (I2CCON<6>) enables a bus WAIT to occur on slave receptions. When
STREN = 1 at the falling edge of the 9th SCL clock of a received byte, the slave module clears
the SCLREL bit. Clearing the SCLREL bit causes the slave module to pull the SCL line low,
initiating a WAIT. The SCL clock of the master and slave will synchronize, as shown in Section
21.6.2 “Master Clock Synchronization”.
When the software is ready to resume reception, the software sets SCLREL. This causes the
slave module to release the SCL line and the master resumes clocking.
Inter-Integrated
Circuit (I2C)
Receiving a slave message is a rather automatic process. The software handling the slave
protocol uses the slave interrupt to synchronize to the events.
When the slave detects the valid address, the associated interrupt will notify the software to
expect a message. On receive data, as each data byte transfers to the I2CRCV register, an
interrupt notifies the software to unload the buffer.
Figure 21-27 shows a simple receive message. Being a 7-bit address message, only one
interrupt occurs for the address bytes. Then, interrupts occur for each of four data bytes.
At an interrupt, the software may monitor the RBF, D_A and R_W bits to determine the condition
of the byte received.
Figure 21-28 shows a similar message using a 10-bit address. In this case, two bytes are
required for the address.
Figure 21-29 shows a case where the software does not respond to the received byte and the
buffer overruns. On reception of the second byte, the module will automatically NACK the master
transmission. Generally, this causes the master to resend the previous byte. The I2COV bit
indicates that the buffer has overrun. The I2CRCV buffer retains the contents of the first byte. On
reception of the third byte, the buffer is still full and again the module will NACK the master. After
this, the software finally reads the buffer. Reading the buffer will clear the RBF bit, however the
I2COV bit remains set. The software must clear the I2COV bit. The next received byte will be
moved to the I2CRCV buffer and the module will respond with a ACK.
Figure 21-30 highlights clock stretching while receiving data. Note in the previous examples,
STREN = 0 which disables clock stretching on receive messages. In this example, the software
sets STREN to enable clock stretching. When STREN = 1, the module will automatically clock
stretch after each received data byte, allowing the software more time to move the data from the
buffer. Note that if RBF = 1 at the falling edge of the 9th clock, the module will automatically clear
the SCLREL bit and pull the SCL bus line low. As shown with the second received data byte, if
the software can read the buffer and clear the RBF before the falling edge of the 9th clock, the
clock stretching will not occur. The software can also suspend the bus at any time. By clearing
the SCLREL bit, the module will pull the SCL line low after it detects the bus SCL low. The SCL
line will remain low, suspending transactions on the bus until the SCLREL bit is set.
SCL (Master) 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9
SDA (Slave) A A A A A
I2CRCV
RBF
I2COV
R_W
D_A
STREN
SCLREL
SI2CIF cleared by user software.
SI2CIF
1 2 3 4 3 4 3 4 3 4 5
3 - Next received byte is message data. Byte moved to I2CRCV register, sets RBF.
Slave generates interrupt. Slave Acknowledges reception.
DS70068D-page 21-40
Section 21. Inter-Integrated Circuit (I2C)
Circuit (I2C)
21
Inter-Integrated
Figure 21-28: Slave Message (Write Data to Slave: 10-bit Address; Address Matches; A10M=1; GCEN=0; IPMIEN=0)
SCL (Master) 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9
DS70068D-page 21-41
SDA (Slave) A A A A A
I2CRCV
RBF
I2COV
R_W
D_A
STREN
SCLREL
SI2CIF cleared by user software.
dsPIC30F Family Reference Manual
SI2CIF
1 2 3 4 5 4 5 4 5 6
1 - Slave recognizes Start event, S and P bits set/clear accordingly. 4 - Next received byte is message data. Byte moved to I2CRCV register, sets RBF.
Slave Acknowledges and generates interrupt.
2 - Slave receives address byte. High order address matches.
Slave Acknowledges and generates interrupt. Address byte not 5 - Software reads I2CRCV register. RBF bit clears.
moved to I2CRCV register.
3 - Slave receives address byte. Low order address matches. 6 - Slave recognizes Stop event, S and P bits set/clear accordingly.
Slave Acknowledges and generates interrupt. Address byte not
moved to I2CRCV register.
SCL (Master) 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9
DS70068D-page 21-42
SDA (Slave) A A N N A
I2CRCV
RBF
I2COV
R_W
D_A
STREN
SCLREL
dsPIC30F Family Reference Manual
1 2 3 4 5 6 2 5
1 - Slave receives address byte. Address matches. Slave generates interrupt. 4 - Next byte also received before I2CRCV read by software.
Address byte not moved to I2CRCV register. I2CRCV register unchanged. Slave generates interrupt.
Slave sends NACK for reception.
2 - Next received byte is message data. Byte moved to I2CRCV register, sets RBF.
Slave generates interrupt. Slave Acknowledges reception. 6 - Software reads I2CRCV register. RBF bit clears.
3 - Next byte received before I2CRCV read by software. I2CRCV register unchanged. 7 - Software clears I2COV bit.
I2COV overflow bit set. Slave generates interrupt. Slave sends NACK for reception.
SCL (Master) 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9
SDA (Slave) A A A A
I2CTRN
TBF
I2CRCV
RBF
I2COV
R_W
D_A
STREN
SCLREL
SI2CIF
1 2 3 4 5 6 3 5 7 8 9 3 5
1 - Software sets the STREN bit to enable clock stretching. 6 - Software sets SCLREL bit to release clock.
2 - Slave receives address byte. 7 - Slave does not clear SCLREL because RBF = 0 at this time.
3 - Next received byte is message data. Byte moved to I2CRCV register, sets RBF. 8 - Software may clear SCLREL to cause a clock hold. Module must detect SCL low
before asserting SCL low.
4 - Because RBF = 1 at 9th clock, automatic clock stretch begins.
Slave clears SCLREL bit. Slave pulls SCL line low to stretch clock. 9 - Software may set SCLREL to release a clock hold.
5 - Software reads I2CRCV register. RBF bit clears.
DS70068D-page 21-43
Section 21. Inter-Integrated Circuit (I2C)
Circuit (I2C)
21
Inter-Integrated
dsPIC30F Family Reference Manual
During a slave transmission message, the master expects return data immediately after
detection of the valid address with R/W = 1. Because of this, the slave module will automatically
generate a bus WAIT whenever the slave returns data.
The automatic WAIT occurs at the falling edge of the 9th SCL clock of a valid device address
byte or transmitted byte Acknowledged by the master, indicating expectation of more transmit
data.
The slave module clears the SCLREL bit. Clearing the SCLREL bit causes the slave module to
pull the SCL line low, initiating a WAIT. The SCL clock of the master and slave will synchronize
as shown in Section 21.6.2 “Master Clock Synchronization”.
When the software loads the I2CTRN and is ready to resume transmission, the software sets
SCLREL. This causes the slave module to release the SCL line and the master resumes
clocking.
Slave transmissions for 7-bit address messages are shown in Figure 21-31. When the address
matches and the R/W bit of the address indicates a slave transmission, the module will
automatically initiate clock stretching by clearing the SCLREL bit and generate an interrupt to
indicate a response byte is required. The software will write the response byte into the I2CTRN
register. As the transmission completes, the master will respond with an Acknowledge. If the
master replies with an ACK, the master expects more data and the module will again clear the
SCLREL bit and generate another interrupt. If the master responds with a NACK, no more data
is required and the module will not stretch the clock nor generate an interrupt.
Slave transmissions for 10-bit address messages require the slave to first recognize a 10-bit
address. Because the master must send two bytes for the address, the R/W bit in the first byte
of the address specifies a write. To change the message to a read, the master will send a
Repeated Start and repeat the first byte of the address with the R/W bit specifying a read. At this
point, the slave transmission begins as shown in Figure 21-32.
SCL (Master) 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9
I2CTRN
TBF
I2CRCV
RBF
I2COV
R_W
D_A
STREN
SCLREL
SI2CIF
1 2 3 4 5 6 3 4 5 6 3 4 5 7 8
1 - Slave recognizes Start event, S and P bits set/clear accordingly. 5 - After last bit, module clears TBF bit indicating buffer is available for next byte.
2 - Slave receives address byte. Address matches. Slave generates interrupt. 6 - At end of 9th clock, if master sent ACK, module clears SCLREL to suspend clock.
Address byte not moved to I2CRCV register. R_W = 1 to indicate read from slave. Slave generates interrupt.
SCLREL = 0 to suspend master clock.
7 - At end of 9th clock, if master sent NACK, no more data expected. Module does not
3 - Software writes I2CTRN with response data. TBF = 1 indicates that buffer is full. suspend clock and will generate an interrupt.
Writing I2CTRN sets D_A, indicating data byte.
8 - Slave recognizes Stop event, S and P bits set/clear accordingly.
4 - Software sets SCLREL to release clock hold. Master resumes clocking and
slave transmits data byte.
DS70068D-page 21-45
Section 21. Inter-Integrated Circuit (I2C)
Circuit (I2C)
21
Inter-Integrated
Figure 21-32: Slave Message (Read Data from Slave: 10-bit Address)
SCL (Master) 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9
DS70068D-page 21-46
SDA (Slave) A A A D7D6D5D4D3D2D1D0 D7D6D5D4D3D2D1D0
I2CTRN
TBF
I2CRCV
RBF
ADD10
R_W
D_A
dsPIC30F Family Reference Manual
STREN
SCLREL
SI2CIF
1 2 3 4 5 6 7 8 6 7 9 10
1 - Slave recognizes Start event, S and P bits set/clear accordingly. 7 - Software sets SCLREL to release clock hold. Master resumes clocking and
2 - Slave receives first address byte. Write indicated. Slave Acknowledges and slave transmits data byte.
generates interrupt. 8 - At end of 9th clock, if master sent ACK, module clears SCLREL to suspend clock.
3 - Slave receives address byte. Address matches. Slave Acknowledges and Slave generates interrupt.
generates interrupt. 9 - At end of 9th clock, if master sent NACK, no more data expected. Module does not
4 - Master sends a Repeated Start to redirect the message. suspend clock or generate interrupt.
5 - Slave receives resend of first address byte. Read indicated. Slave suspends clock. 10 - Slave recognizes Stop event, S and P bits set/clear accordingly.
6 - Software writes I2CTRN with response data.
Inter-Integrated
By definition of the I2C bus being a wired AND bus connection, pull-up resistors on the bus are
Circuit (I2C)
required, shown as RP in Figure 21-33. Series resistors, shown as RS are optional and used to
improve ESD susceptibility. The values of resistors RP and RS depend on the following
parameters:
• Supply voltage
• Bus capacitance
• Number of connected devices (input current + leakage current)
Because the device must be able to pull the bus low against RP, current drawn by RP must be
greater than the I/O pin minimum sink current IOL of 3 mA at VOL(MAX) = 0.4V for the device
output stage. For example, with a supply voltage of VDD = 5V +10%:
In a 400 kHz system, a minimum rise time specification of 300 nsec exists and in a 100 kHz
system, the specification is 1000 nsec.
Because RP must pull the bus up against the total capacitance CB with a maximum rise time of
300 nsec to 0.7 VDD, the maximum resistance for RP must be less than:
RP(MAX) = -tR / CB * ln(1 – (VIL(MAX) – VDD(MAX)) = -300 nsec / (100pf * ln(1-0.7)) = 2.5 kΩ
The maximum value for RS is determined by the desired noise margin for the low level. RS
cannot drop enough voltage to make the device VOL plus voltage across RS more than the
maximum VIL.
The SCL clock input must have a minimum high and low time for proper operation. The high and
low times of the I2C specification as well as the requirements of the I2C module, are shown in
the “Electrical Specifications” section in the specific device data sheet.
VDD + 10%
RP RP Device
RS RS
SDA
SCL
CB = 10 - 400 pF
Note: I2C devices with input levels related to VDD must have one common supply line
to which the pull-up resistor is also connected.
Inter-Integrated
Circuit (I2C)
21.9.1 When the Device Enters Sleep Mode
When the device executes a PWRSAV 0 instruction, the device enters Sleep mode. When the
device enters Sleep mode, the master and slave module abort any pending message activity
and reset the state of the modules. Any transmission/reception that is in progress will not
continue when the device wakes from Sleep. After the device returns to Operational mode, the
master module will be in an Idle state waiting for a message command and the slave module
will be waiting for a Start condition. During Sleep, the IWCOL, I2COV and BCL bits are cleared.
Additionally, because the master functions are aborted, the SEN, RSEN, PEN, RCEN, ACKEN
and TRSTAT bits are cleared. TBF and RBF are cleared and the buffers are available at
wake-up.
There is no automatic method to prevent Sleep entry if a transmission or reception is active or
pending. The software must synchronize Sleep entry with I2C operation to avoid aborted
messages.
During Sleep, the slave module will not monitor the I2C bus. Thus, it is not possible to generate
a wake-up event based on the I2C bus using the I2C module. Other interrupt inputs, such as the
interrupt-on-change inputs can be used to detect message traffic on a I2C bus and cause a
device wake-up.
Question 1: I’m operating as a bus master and transmitting data, however, slave and
receive interrupts are also occurring.
Answer: The master and slave circuits are independent. The slave module will receive events
from the bus sent by the master.
Question 2: I’m operating as a slave and I write data to the I2CTRN register, but the data
did not transmit.
Answer: The slave enters an automatic wait when preparing to transmit. Ensure that you set
the SCLREL bit to release the I2C clock.
Question 4: Operating as a slave, I receive a byte while STREN = 0. What should the
software do if it cannot process the byte before the next one is received?
Answer: Because STREN was ‘0’, the module did not generate an automatic WAIT on the
received byte. However, the software may, at any time during the message, set STREN then
clear SCLREL. This will cause a WAIT on the next opportunity to synchronize the SCL clock.
Question 7: I tried to send a Start condition on the bus, then transmit a byte by writing
to the I2CTRN register. The byte did not get transmitted. Why?
Answer: You must wait for each event on the I2C bus to complete before starting the next one.
In this case, you should poll the SEN bit to determine when the Start event completed, or wait for
the master I2C interrupt before data is written to I2CTRN.
Inter-Integrated
This section lists application notes that are related to this section of the manual. These
Circuit (I2C)
application notes may not be written specifically for the dsPIC30F Product Family, but the
concepts are pertinent and could be used with modification and possible limitations. The current
application notes related to the Inter-Integrated Circuit (I2C) module are:
Note: Please visit the Microchip web site (www.microchip.com) for additional Application
Notes and code examples for the dsPIC30F Family of devices.
HIGHLIGHTS
This section of the manual contains the following topics:
22
22.1 Introduction .................................................................................................................. 22-2
Data Converter
Interface (DCI)
22.2 Control Register Descriptions ...................................................................................... 22-2
22.3 Codec Interface Basics and Terminology..................................................................... 22-8
22.4 DCI Operation ............................................................................................................ 22-10
22.5 Using the DCI Module................................................................................................ 22-17
22.6 Operation in Power Saving Modes ............................................................................ 22-28
22.7 Registers Associated with DCI................................................................................... 22-28
22.8 Design Tips ................................................................................................................ 22-30
22.9 Related Application Notes.......................................................................................... 22-31
22.10 Revision History ......................................................................................................... 22-32
22.1 Introduction
The dsPIC Data Converter Interface (DCI) module allows simple interfacing of devices, such as
audio coder/decoders (codecs), A/D converters, and D/A converters.
The following interfaces are supported:
• Framed Synchronous Serial Transfer (Single or Multi-Channel)
• Inter-IC Sound (I2S) Interface
• AC-Link Compliant mode
Many codecs intended for use in audio applications support sampling rates between 8 kHz and
48 kHz and use one of the interface protocols listed above. The DCI automatically handles the
interface timing associated with these codecs. No overhead from the CPU is required until the
requested amount of data has been transmitted and/or received by the DCI. Up to four data
words may be transferred between CPU interrupts.
The data word length for the DCI is programmable up to 16 bits to match the data size of the
dsPIC30F CPU. However, many codecs have data word sizes greater than 16 bits. Long data
word lengths can be supported by the DCI. The DCI is configured to transmit/receive the long
word in multiple 16-bit time slots. This operation is transparent to the user and the long data word
is stored in consecutive register locations.
The DCI can support up to 16 time slots in a data frame, for a maximum frame size of 256 bits.
There are control bits for each time slot in the data frame that determine whether the DCI will
transmit/receive during the time slot.
22.2 Control Register Descriptions
The DCI has five Control registers and one Status register, which are listed below:
• DCICON1: DCI module enable and mode bits.
• DCICON2: DCI module word length, data frame length, and buffer setup.
• DCICON3: DCI module bit clock generator setup.
• DCISTAT: DCI module status information.
• RSCON: Active frame time slot control for data reception.
• TSCON: Active frame time slot control for data transmit.
In addition to these Control and Status registers, there are four Transmit registers,
TXBUF0....TXBUF3, and four Receive registers, RXBUF0....RXBUF3.
Lower Byte:
R/W-0 R/W-0 R/W-0 U-0 U-0 U-0 R/W-0 R/W-0
UNFM CSDOM DJST — — — COFSM<1:0>
bit 7 bit 0
22
bit 15 DCIEN: DCI Module Enable bit
Data Converter
Interface (DCI)
1 = Module is enabled
0 = Module is disabled
bit 14 Reserved: Read as ‘0’
bit 13 DCISIDL: DCI Stop in Idle Control bit
1 = Module will halt in CPU Idle mode
0 = Module will continue to operate in CPU Idle mode
bit 12 Reserved: Read as ‘0’
bit 11 DLOOP: Digital Loopback Mode Control bit
1 = Digital Loopback mode is enabled. CSDI and CSDO pins internally connected.
0 = Digital Loopback mode is disabled
bit 10 CSCKD: Sample Clock Direction Control bit
1 = CSCK pin is an input when DCI module is enabled
0 = CSCK pin is an output when DCI module is enabled
bit 9 CSCKE: Sample Clock Edge Control bit
1 = Data changes on serial clock falling edge, sampled on serial clock rising edge
0 = Data changes on serial clock rising edge, sampled on serial clock falling edge
bit 8 COFSD: Frame Synchronization Direction Control bit
1 = COFS pin is an input when DCI module is enabled
0 = COFS pin is an output when DCI module is enabled
bit 7 UNFM: Underflow Mode bit
1 = Transmit last value written to the Transmit registers on a transmit underflow
0 = Transmit ‘0’s on a transmit underflow
bit 6 CSDOM: Serial Data Output Mode bit
1 = CSDO pin will be tri-stated during disabled transmit time slots
0 = CSDO pin drives ‘0’s during disabled transmit time slots
bit 5 DJST: DCI Data Justification Control bit
1 = Data transmission/reception is begun during the same serial clock cycle as the frame synchronization
pulse
0 = Data transmission/reception is begun one serial clock cycle after frame synchronization pulse
bit 4-2 Reserved: Read as ‘0’
bit 1-0 COFSM<1:0>: Frame Sync Mode bits
11 = 20-bit AC-Link mode
10 = 16-bit AC-Link mode
01 = I2S Frame Sync mode
00 = Multi-Channel Frame Sync mode
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
R/W-0 R/W-0 R/W-0 U-0 R/W-0 R/W-0 R/W-0 R/W-0
COFSG<2:0> — WS<3:0>
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
BCG<7:0>
bit 7 bit 0
22
bit 15-12 Reserved: Read as ‘0’.
Data Converter
Interface (DCI)
bit 11-0 BCG<11:0>: DCI Bit Clock Generator Control bits
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
U-0 U-0 U-0 U-0 R-0 R-0 R-0 R-0
— — — — ROV RFUL TUNF TMPTY
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
RSE7 RSE6 RSE5 RSE4 RSE3 RSE2 RSE1 RSE0
bit 7 bit 0
22
bit 11 RSE<15:0>: Receive Slot Enable bits
Data Converter
Interface (DCI)
1 = CSDI data is received during the individual time slot n
0 = CSDI data is ignored during the individual time slot n
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
TSE7 TSE6 TSE5 TSE4 TSE3 TSE2 TSE1 TSE0
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Note: The details given in this section are not specific to the DCI module. This discussion
is intended to provide the user some background and terminology related to the
digital serial interface protocols found in most codec devices.
CSCK SCK
dsPIC® COFS FS
Codec (See Note)
(Controller) CSDO SDI
CSDI SDO
CSCK SCK
dsPIC®
FS
(Controller) COFS A/D #1
CSDI SDO
FSO
SCK
FS
Daisy-Chained Configuration A/D #2
SDO
to Other Devices FSO
Controller
CSCK SCK
dsPIC® COFS FS
Codec
(Controller) CSDO SDI
CSDI SDO
All interfaces have a serial transfer clock, SCK. The SCK signal may be generated by any of the
connected devices or can be provided externally. In some systems, SCK is also referred to as
the bit clock. For codecs that offer high signal fidelity, it is common for the SCK signal to be
derived from the crystal oscillator on the codec device. The protocol defines the edge of SCK on
which data is sampled. The master device generates the FS signal with respect to SCK.
The period of the FS signal delineates one data frame. This period is the same as the data
sample period. The number of SCK cycles that occur during the data frame will depend on the
type of codec that is selected. The ratio of the SCK frequency to the system sample rate is
expressed as a ratio of n, where n is the number of SCK periods per data frame.
One advantage of using a framed interface protocol is that multiple data words can be transferred
during each sample period, or data frame. Each division of the data frame is referred to as a time
slot. The time slots can be used for multiple codec data channels and/or control information. 22
Furthermore, multiple devices can be multiplexed on the same serial data pins. Each slave
device is programmed to place its data on the serial data connection during the proper time slot.
Data Converter
Interface (DCI)
The output of each slave device is tri-stated at all other times to permit other devices to use the
serial bus.
Some devices allow the FS signal to be daisy-chained via Frame Synchronization Output (FSO)
pins. A typical daisy-chained configuration is shown in Figure 22-1. When the transfer from the
first slave device has completed, a FS pulse is sent to the second device in the chain via its FSO
pin. This process continues until the last device in the chain has sent its data. The controller
(master) device should be programmed for a data frame size that accommodates all of the data
words that will be transferred.
The timing for a typical data transfer is shown in Figure 22-2. Most protocols begin the data
transfer one SCK cycle after the FS signal is detected. This example uses a 16 fs clock and
transfers four 4-bit data words per frame.
SCK
FS
SDI or SDO Time Slot 0 Time Slot 1 Time Slot 2 Time Slot 3
The timing for a typical data transfer with daisy-chained devices is shown in Figure 22-3. This
example uses a 16 fs SCK frequency and transfers two 8-bit data words per frame. After the FS
pulse is detected, the first device in the chain transfers the first 8-bit data word and generates the
FSO signal at the end of the transfer. The FSO signal begins the transfer of the second data word
from the second device in the chain.
SCK
FS
FSO
The FS pulse has a minimum active time of one SCK period so the slave device can detect the
start of the data frame. The duty cycle of the FS pulse may vary depending on the specific pro-
tocol that is used to mark certain boundaries in the data frame. For example, the I2S protocol
uses a FS signal that has a 50% duty cycle. The I2S protocol is optimized for the transfer of two
data channels (left and right channel audio information). The edges of the FS signal mark the
boundaries of the left and right channel data words. The AC-Link protocol uses a FS signal that
is high for 16 SCK periods and low for 240 SCK periods. The edges of the AC-Link FS signal
mark the boundaries of control information and data in the frame.
Note: Refer to Section 26. “Appendix” of this manual for additional information on codec
communication protocols.
BCG<11:0>
CSCKD
COFSD
WS<3:0> Frame
COFSG<3:0> Synchronization COFS
COFSM<1:0> Generator
16-bit Data Bus
Receive Registers w/
Buffer
Buffer Control
15 0
Transmit Registers w/
Buffer DCI Shift Register CSDI
CSDO
The CSCK pin provides the serial clock connection for the DCI. The CSCK pin may be configured
as an input or output using the CSCKD control bit, DCICON1<10>. When the CSCK pin is
configured as an output (CSCKD = 0), the serial clock is derived from the dsPIC30F system clock
source and supplied to external devices by the DCI. When the CSCK pin is configured as an input
(CSCKD = 1), the serial clock must be provided by an external device.
Data Converter
Interface (DCI)
enabled. The CSDO pin drives the serial bus whenever data is to be transmitted. The CSDO pin
can be tri-stated or driven to ‘0’ during serial clock periods when data is not transmitted, depend-
ing on the state of the CSDOM control bit (DCICON1<6>). The tri-state option allows other
devices to be multiplexed onto the CSDO connection.
The serial data input (CSDI) pin is configured as an input only pin when the module is enabled.
The frame synchronization (COFS) pin is used to synchronize data transfers that occur on the
CSDO and CSDI pins. The COFS pin may be configured as an input or an output. The data direc-
tion for the COFS pin is determined by the COFSD control bit (DCICON1<8>). When the COFSD
bit is cleared, the COFS pin is an output. The DCI module will generate frame synchronization
pulses to initiate a data transfer. The DCI is the master device for this configuration. When the
COFSD bit is set, the COFS pin becomes an input. Incoming synchronization signals to the
module will initiate data transfers. The DCI is a slave device when the COFSD control bit is set.
Note: The CSCK I/O pin will be controlled by the DCI module if the DCIEN bit is set OR
the bit clock generator is enabled by writing a non-zero value to BCG<11:0>. This
allows the bit clock generator to be operated independently of the DCI module.
When the CSCK pin is controlled by the DCI module, the corresponding PORT, LAT and TRIS
Control register values for the CSCK pin will be overridden and the data direction for the CSCK
pin will be controlled by the CSCKD control bit (DCICON1<10>).
If the serial clock for the DCI is to be provided by an external device, the BCG<11:0> bits should
be set to ‘0’ and the CSCKD bit set to ‘1’.
If the serial clock is to be generated by the DCI module, the BCG<11:0> control bits should be
set to a non-zero value (see Equation 22-1) and the CSCKD control bit should be set to zero.
The formula for the bit clock frequency is given in Equation 22-1.
Equation 22-1: DCI Bit Clock Generator Value
fCY
BCG<11:0> = –1
2 fCSCK
The required bit clock frequency will be determined by the system sampling rate and frame size.
Typical bit clock frequencies range from 16x to 512x the converter sample rate, depending on
the data converter and the communication protocol that is used.
Note: The BCG<11:0> bits have no effect on the operation of the DCI module when the
CSCK signal is provided externally (CSCKD = 1).
Note: The WS control bits are used only in the multi-channel and I2S modes. These bits
have no effect in AC-Link mode since the data slot sizes are fixed by the protocol.
Frame lengths up to 16 data words may be selected. The frame length in serial clock periods will
vary up to a maximum of 256 depending on the word size that is selected.
22
Data Converter
Note: The COFSG control bits will have no effect in AC-Link mode, since the frame length
Interface (DCI)
is set to 256 serial clock periods by the protocol.
Data values are always stored left-justified in the DCI registers, since audio PCM data is
represented as a signed 2’s complement fractional number. If the programmed DCI word size is
less than 16 bits, the unused LSbs in the Receive registers are set to ‘0’ by the module. Also, the
unused LSbs in the Transmit register are ignored by the module.
The Transmit and Receive registers each have a set of buffers that are not accessible by the
user. Effectively, each transmit and receive buffer location is double-buffered. The DCI transmits
data from the transmit buffers and writes received data to the receive buffers. The buffers allow
the user to read and write the RXBUF and TXBUF registers, while the DCI uses data from the
buffers.
TXBUF1 4 4 Transmit
Buffer
Select
TXBUF2
TXBUF3
BLEN
DCI
Buffer Control Shift Register
RXBUF1 4 4 Receive
Buffer
RXBUF2 Select
RXBUF3
During disabled transmit time slots, the CSDO pin can drive ‘0’s or can be tri-stated, depending
on the state of the CSDOM bit (DCICON1<6>). A given transmit time slot is disabled if its
corresponding TSEx bit is cleared in the TSCON register.
If the CSDOM bit is cleared (default), the CSDO pin will drive ‘0’s onto the CSDO pin during
disabled time slot periods. This mode is used when there are only two devices (1 master and 1
slave) attached to the serial bus.
If the CSDOM bit is set, the CSDO pin will be tri-stated during unused time slot periods. This
mode allows multiple dsPIC30F devices to share the same CSDO line in a multiplexed
application. Each device on the CSDO line is configured so that it will only transmit data during
specific time slots. No two devices should transmit data during the same time slot.
Data Converter
Interface (DCI)
The slot enable bits in the TSCON and RSCON registers function independently, with the
exception of the buffer control logic. For each time slot in a data frame, the buffer location is
advanced if either the TSEx or the RSEx bit is set for the current time slot. That is, the buffer con-
trol unit synchronizes the Transmit and Receive buffering so that the Transmit and Receive buffer
location will always be the same for each time slot in the data frame.
If the TSEx bit and the RSEx bit are both set for every time slot that is used in the data frame,
the DCI will Transmit and Receive equal amounts of data .
In some applications, the number of data words transmitted during a frame may not equal the
number of words received. As an example, assume that the DCI is configured for a 2-word data
frame, TSCON = 0x0001 and RSCON = 0x0003. This configuration would allow the DCI to
transmit one data word per frame and receive two data words per frame. Since two data words
are received for each data word that is transmitted, the user would write every other transmit
buffer location. Specifically, only TXBUF0 and TXBUF2 would be used to transmit data.
Figure 22-6: DCI Buffer Operation: TSCON = 0x0001, RSCON = 0x0003, BLEN<1:0> = 11b
TXBUF1 RXBUF1
Data Word #2
Note: User writes to TXBUF0 and TXBUF2. TXBUF1 and TXBUF3 not used by transmit logic.
22.5.1 How to Transmit and Receive Data Using the DCI Buffers, Status Bits and Interrupts
The DCI can buffer up to four data words between CPU interrupts depending on the setting of
the BLEN control bits. The buffered data can be transmitted and received in a single data frame,
or across multiple data frames, depending on the TSCON and RSCON register settings. For
example, assume BLEN<1:0> = 00b ( buffer one data word per interrupt) and TSCON = RSCON
= 0x0001. This particular configuration represents the most basic setup and would cause the
DCI to transmit/receive one data word at the beginning of every data frame. The CPU would be
interrupted after every data word transmitted/received since BLEN<1:0> = 00b.
22
For a second configuration example, assume BLEN<1:0> = 11b (buffer four data words per
interrupt) and TSCON = RSCON = 0x0001. This configuration would cause the DCI to
Data Converter
Interface (DCI)
transmit/receive one data word at the beginning of every data frame, but a CPU interrupt would
be generated after four data words were transmitted/received. This configuration would be useful
for block processing, where multiple data samples are processed at once.
For a third configuration example, assume BLEN<1:0> = 11b (buffer four data words per
interrupt) and TSCON = RSCON = 0x000F. This configuration would cause the DCI to
transmit/receive four data words at the beginning of every data frame. A CPU interrupt would be
generated every data frame in this case because the DCI was setup to buffer four data words in
a data frame. This configuration represents a typical multi-channel buffering setup.
The DCI can also be configured to buffer more than four data words per frame. For example,
assume BLEN<1:0> = 11b (buffer four data words per interrupt) and TSCON = RSCON =
0x00FF. In this configuration, the DCI will transmit/receive 8 data words per data frame. An
interrupt will be generated twice per data frame. To determine which portion of the data is in the
Transmit/Receive registers at each interrupt, the user will need to check the SLOT status bits
(DCISTAT <11:7>) in the Interrupt Service Routine to determine the current data frame position.
The Transmit and Receive registers are double-buffered, so the DCI module can work on one set
of Transmit and Receive data while the user software is manipulating the other set of data.
Because of the double-buffers, it will take three interrupt periods to receive the data, process that
data, and transmit the processed data. For each DCI interrupt, the CPU will process a data word
that was received during a prior interrupt period and generate a data word that will be transmitted
during the next interrupt period. The buffering and data processing time of the dsPIC device will
insert a two-interrupt period delay into the processed data. This data delay is negligible, in most
cases.
The DCI status flags and CPU interrupt indicate that a buffer transfer has taken place and that it
is time for the CPU to process more data. In a typical application, the following steps will occur
each time the DCI data is processed:
1. The RXBUF registers are read by the user software. The RFUL status bit (DCISTAT<2>)
will have been set by the module to indicate the Receive registers contain new data. The
RFUL bit is cleared automatically after all the active Receive registers have been read.
2. The user software will process the received data.
3. The processed data is written to the TXBUF registers. The TMPTY status bit
(DCISTAT<0>) will have been previously set to indicate that the Transmit registers are
ready for more data to be written.
For applications that are configured to Transmit and Receive data (TSCON and RSCON are
non-zero), the RFUL and TMPTY status bits can be polled in user software to determine when a
DCI buffer transfer takes place. If the DCI is only used to transmit data (RSCON = 0), then the
TMPTY bit can be polled to indicate a buffer transfer. If the DCI is configured to only receive data
(TSCON = 0), then the RFUL bit can be polled to indicate a buffer transfer.
The DCIIF status bit (IFS2<9>) is set each time a DCI buffer transfer takes place and generates
a CPU interrupt, if enabled. The DCIIF status bit is generated by the logical ORing of the RFUL
and TMPTY status bits.
Data transfers are begun by setting the DCIEN control bit (DCICON1<15>). Prior to this, the DCI
Control registers should have been initialized for the desired operating mode. (See Section
22.5.4 “Multi-Channel Operation”, Section 22.5.5 “I2S Operation”, and Section
22.5.6 “AC-Link Operation”)
A timing diagram for DCI startup is shown in Figure 22-7. In this example, the DCI is configured
for an 8-bit data word (WS<3:0> = 0111b) and an 8-bit data frame (COFSG<3:0> = 0000b). The
Multi-Channel mode (COFSM<1:0> = 00b) is used. The steps required to transmit and receive
data are described below.
1. The TXBUF registers should be pre-loaded with the first data to be transmitted before the
module is enabled. If the transmit data will be based on data received from the codec, then
the user can simply clear the TXBUF registers. This will transmit digital ‘silence’ until data
is first received into the RXBUF registers from the codec.
2. Enable the DCI module by setting the DCIEN bit (DCICON1<15>). If the DCI is the master
device, the data in the TXBUF registers will be transferred to the transmit buffers and
transmission of the first data frame will commence. Otherwise, the TXBUF data will be
held in the transmit buffers until a frame sync signal is received from the master device.
3. The TMPTY bit will be set immediately after the module is enabled and a DCI interrupt will
be generated, if enabled. At this time, the module is ready for the TXBUF registers to be
reloaded with data to be transferred on the second data frame. No data has been received
by the module at this time, so the TXBUF registers should be cleared again if the
transmitted data is calculated from the received data. The DCIIF status bit should be
cleared by the user in software if interrupts are enabled.
4. After the first data frame is transferred, the TMPTY bit will set, the RFUL status bit will be
set, and a DCI interrupt will occur, if enabled. This is the first data word received from the
device connected to the DCI.
5. The user reads the Receive register(s), automatically clearing the RFUL status bit. The
user software processes the received data at this time.
6. The Transmit register(s) is written with data to be transmitted during the next data frame.
The TMPTY status bit is cleared automatically when the write occurs. The write data may
be calculated from data that was received at the prior interrupt.
7. The next DCI interrupt occurs and the cycle repeats.
CSCK
Data 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6
Word 1 Word 2
COFS
DCIEN
TMPTY
RFUL
RXBUF RX Word 1
1 2 3 4 5 6 7
The DCI module is disabled by clearing the DCIEN control bit (DCICON1<15>). When the DCIEN
bit is cleared, the module will finish the current data frame transfer that is in progress. An interrupt
will be generated if the transmit/receive buffers need to be written/read before the end of the
frame.
The DCIEN bit must be cleared at least 3 CSCK cycles before the end of the frame disables the
module at that frame. If not, the module will disable on the next frame.
The DCI will not generate any further frame sync pulses after the DCIEN bit is cleared, nor will it
respond to an incoming frame sync pulse.
When the frame sync generator has reached the final time slot in the data frame, all state
machines associated with the DCI will be reset to their Idle state and control of the I/O pins asso- 22
ciated with the module will be released. The user may poll the SLOT<3:0> status bits
Data Converter
(DCISTAT<11:7>) after the DCIEN bit is cleared to determine when the module is Idle. The DCI
Interface (DCI)
is Idle when SLOT<3:0> = 0000b and DCIEN = 0.
When the module enters the Idle state, any data in the Receive Shadow registers will be
transferred to the RXBUF registers, and the RFUL and ROV status bits will be affected
accordingly.
FS pulse not
WS = 0011b COFSG = 0011b generated.
CSCK
Data 3 2 1 0 3 2 1 0 3 2 1 0 3 2 1 0 3 2 1 0
COFS
DCIEN
RFUL
Transmit Registers
TXBUF2
Data Converter
Interface (DCI)
CSCK
COFS
The steps required to configure the DCI for a codec using the Multi-Channel mode are provided
in this section. This Operating mode can be used for codecs with one or more data channels.
The setup is similar regardless of the number of channels.
For this setup example, a hypothetical codec will be considered. The single channel codec used
for this setup example will use a 256 fs serial clock frequency with a 16-bit data word transmitted
at the beginning of each frame.
The steps required for setup and operation are described below.
1. Determine the sample rate and data word size required by the codec. An 8 kHz sampling
rate is assumed for this example.
2. Determine the serial transfer clock frequency required by the codec. Most codecs require
a serial clock signal that is some multiple of the sampling frequency. The example codec
requires a frequency that is 256 fs, or 1.024 MHz. Therefore, a frame sync pulse must be
generated every 256 serial clock cycles to start a data transfer.
3. The DCI must be configured for the serial transfer clock. If the CSCK signal will be
generated by the DCI, clear the CSCKD control bit (DCICON1<10>) and write a value to
DCICON3 that will produce the correct clock frequency (See Section 22.4.3 “Bit Clock
Generator”). If the CSCK signal is generated by the codec or other external source, set
the CSCKD control bit and clear the DCICON3 register.
4. Clear the COFSM<1:0> control bits (DCICON1<1:0>) to set the frame synchronization
signal to Multi-Channel mode.
5. If the DCI will generate the frame sync signal (master), then clear the COFSD control bit
(DCICON1<8>). If the DCI will receive the frame sync signal (slave), then set the COFSD
control bit.
6. Clear the CSCKE control bit (DCICON1<9>) to sample incoming data on the falling edge
of CSCK. This is the typical configuration for most codecs. Refer to the codec data sheet
to ensure the correct sampling edge is used.
7. Write the WS<3:0> control bits (DCICON2<3:0>) for the desired data word size. The
example codec requires WS<3:0> = 1111b for a 16-bit data word size.
8. Write the COFSG<3:0> control bits (DCICON2<8:5>) for the desired number of data
words per frame. The WS and COFSG control bits will determine the length of the data
frame in CSCK cycles (see Section 22.4.7 “Frame Synchronization Generator”)
COFSG<3:0> = 1111b is used for this codec to provide the 256-bit data frame required
by the example codec.
9. Set the Output mode for the CSDO pin using the CSDOM control bit (DCICON1<6>). If a
single device is attached to the DCI, CSDOM can be cleared. This will force the CSDO pin
to ‘0’ during unused data time slots. You may need to set CSDOM if multiple devices are
attached to the CSDO pin.
10. Write the TSCON and RSCON registers to determine which data time slots in the frame
are to be transmitted and received, respectively. For this single channel codec, use
TSCON = RSCON = 0x0001 to enable transmission and reception during the first 16-bit
time slot of the data frame.
11. Set the BLEN control bits (DCICON2<11:10>) to buffer the desired amount of data words.
For the single channel codec, BLEN = 00 will provide an interrupt at each data frame. A
higher value of BLEN could be used for this codec to buffer multiple samples between
interrupts.
12. If interrupts are to be used, clear the DCIIF status bit (IFS2<9>) and set the DCIIE control
bit (IEC2<9>).
13. Begin operation as described in Section 22.5.1.1 “DCI Start-up and Data Buffering”.
2
22.5.5 I S Operation
The I2S Operating mode is used for codecs that require a frame sync signal that has a 50% duty
cycle. The period of the I2S frame sync signal in serial clock cycles is determined by the word
size of the codec that is connected to the DCI module. The start of a new word boundary is
marked by a high-to-low or a low-to-high transition edge on the COFS pin as shown in
Figure 22-11. I2S codecs are generally stereo or two-channel devices, with one data word
transferred during the low time of the frame sync signal and the other data word transmitted
during the high time.
CSCK
COFS
Note: A 5-bit transfer is shown here for illustration purposes. The I2S protocol does not specify
word length, this will be system dependent.
The DCI module is configured for I2S mode by writing a value of 01h to the COFSM<1:0> control
bits in the DCICON1 SFR. When operating in the I2S mode, the DCI module will generate frame
synchronization signals with a 50% duty cycle. Each edge of the frame synchronization signal
marks the boundary of a new data word transfer. Refer to the Appendix of this manual for more
information about the I2S protocol. The user must also select the frame length and data word size
using the COFSG and WS control bits in the DCICON2 SFR.
Data Converter
3. The DCI must be configured for the serial transfer clock. If the CSCK signal will be gener-
Interface (DCI)
ated by the DCI, clear the CSCKD control bit (DCICON1<10>) and write a value to
DCICON3 that will produce the correct clock frequency (see Section 22.4.3 “Bit Clock
Generator”). If the CSCK signal is generated by the codec or other external source, set
the CSCKD control bit and clear the DCICON3 register.
4. Next, set COFSM<1:0> = 01b to set the frame synchronization signal to I2S mode.
5. If the DCI will generate the frame sync signal (master), then clear the COFSD control bit
(DCICON1<8>). If the DCI will receive the frame sync signal (slave), then set the COFSD
control bit.
6. Set the CSCKE control bit (DCICON1<9>) to sample incoming data on the rising edge of
CSCK. This is the typical configuration for most I2S codecs.
7. Write the WS<3:0> control bits (DCICON2<3:0>) for the desired data word size. For the
example codec, use WS<3:0> = 1111b for a 16-bit data word size.
8. Write the COFSG<3:0> control bits (DCICON2<8:5) for the desired number of data words
per frame. The WS and COFSG control bits will determine the length of the data frame in
CSCK cycles (see Section 22.4.7 “Frame Synchronization Generator”). For this exam-
ple codec, set COFSG<3:0> = 0001b.
Note: In the I2S mode, the COFSG bits are set to the length of 1/2 of the data frame. For
this example codec, set COFSG<3:0> = 0001b (two data words per frame) to
produce a 32-bit frame. This will produce an I2S data frame that is 64 bits in length.
9. Set the Output mode for the CSDO pin using the CSDOM control bit (DCICON1<6>). If a
single device is attached to the DCI, CSDOM can be cleared. You may need to set
CSDOM if multiple devices are attached to the CSDO pin.
10. Write the TSCON and RSCON registers to determine which data time slots in the frame
are to be transmitted and received, respectively. For this codec, set TSCON = 0x0001
and RSCON = 0x0001 to enable transmission and reception during the first 16-bit time
slot of the 32-bit data frame. Adjacent time slots can be enabled to buffer data words
longer than 16 bits.
11. Set the BLEN<1:0> control bits (DCICON2<11:10>) to buffer the desired amount of data
words. For a two-channel I2S codec, BLEN<1:0> = 01b will generate an interrupt after
transferring two data words.
12. If interrupts are to be used, clear the DCIIF status bit (IFS2<9>) and set the DCIIE control
bit (IEC2<9>).
13. Begin operation as described in Section 22.5.1.1 “DCI Start-up and Data Buffering”. In
the I2S Master mode, the COFS pin will be driven high after the module is enabled and
begin transmitting the data loaded in TXBUF0.
Most I2S codecs support two channels of data and the level of the frame sync signal indicates
the channel that is transferred during that half of the data frame. The COFS pin can be polled in
software using its associated Port register to determine the present level on the pin in the DCI
Interrupt Service Routine. This will indicate which data is in the Receive register and which data
should be written to the Transmit registers for transfer on the next frame.
As per the I2S specification, a data word transfer will by default begin one serial clock cycle
following a transition of the frame sync signal. An ‘MSb left-justified’ option can be selected using
the DJST control bit (DCICON1<5>).
If DJST = 1, the I2S data transfers will be MSb left justified. The MSb of the data word will be
presented on the CSDO pin during the same serial clock cycle as the rising or falling edge of the
FS signal. After the data word has been transmitted, the state of the CSDO pin is dictated by the
CSDOM (DCICON1<6>) bit.
The left-justified data option allows two stereo codecs to be connected to the same serial bus.
Many I2S compatible devices have configuration options for left-justified or right-justified data.
The word size selection bits are set to twice the codec word length and data is read/written to the
DCI memory in a packed format. The connection details for a dual I2S codec system are shown
in Figure 22-12.
Timing diagrams for I2S mode are shown in Figure 22-13. For reference, these diagrams assume
an 8-bit word size (WS<3:0> = 0111b). Two data words per frame would be required to achieve
a 16-bit sub-frame (COFSG<3:0> = 0001b). The 3rd timing diagram in Figure 22-13 uses packed
data to read/write from two codecs. For this example, the DCI module is configured for a 16-bit
data word (WS<3:0> = 1111b). Two packed 8-bit words are written to each 16-bit location in the
DCI memory buffer.
Codec #1
®
SCK SCK
dsPIC
Device FS WS
SDO SDI
I2C™/SPI™
Codec #2
SCK
WS
SDI
I2C™/SPI™
CSCK
Data 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0
22
2. Left-Justified Data Alignment
Data Converter
Interface (DCI)
CSCK
Data 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0
CSCK
COFS Channel #1 Transfer, Word 1 Channel #1 Transfer, Word 2 Channel #2 Transfer, Word 1 Channel #2 Transfer, Word 2
Data 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0
The AC-Link data frame is 256 bits subdivided into one 16-bit control slot, followed by twelve
20-bit data slots. The AC-’97 codec usually provides the serial transfer clock signal which is
derived from a crystal oscillator as shown in Figure 22-14. The controller receives the serial clock
and generates the frame sync signal. The default data frame rate is 48 kHz. The frame sync
signal used for AC-Link systems is high for 16 CSCK periods at the beginning of the data frame
and low for 240 CSCK periods. The data transfer begins one CSCK period after the rising edge
of the frame sync signal as shown in Figure 22-16. Data is sampled by the receiving device on
the falling edge of CSCK. The control and data time slots in the AC-Link have defined uses in the
protocol as shown in Figure 22-15. Refer to the Appendix of this manual or the Intel® AC ‘97
Codec Specification, Rev 2.2 for a complete definition of the AC-Link protocol.
BIT_CLK
CSCK
24.576
SYNC MHz
COFS
dsPIC® SDATA_OUT
(AC ‘97 CSDO AC ‘97
Controller) Codec
SDATA_IN
CSDI
/RESET
I/O
256
16 20 20 20 20 20 20 20
SYNC
CSCK
COFS
The DCI module has two Operating modes for the AC-Link protocol to accommodate the 20-bit
data time slots. These Operating modes are selected by the COFSM<1:0> control bits
(DCICON1<1:0>). The first AC-Link mode is called ‘16-bit AC-Link mode’ and is selected by
setting COFSM<1:0> = 10b. The second AC-Link mode is called ‘20-bit AC-Link mode’ and is
selected by setting COFSM<1:0> = 11b.
In the 16-bit AC-Link mode, transmit and receive data word lengths are restricted to 16 bits to fit
the DCI Transmit and Receive registers. Note that this restriction only affects the 20-bit data time
slots of the AC-Link protocol. For received time slots, the incoming data will be truncated to 16
bits. For outgoing time slots, the 4 LSbs of the data word are set to ‘0’ by the module. This
Operating mode simplifies the AC-Link data frame by treating every time slot as a 16-bit time slot.
The frame sync generator maintains alignment to the time slot boundaries.
The 20-bit AC-Link mode allows all bits in the data time slots to be transmitted and received, but
does not maintain data alignment to the specific time slot boundaries defined in the AC-Link
protocol.
22
The 20-bit AC-Link mode functions similarly to the Multi-Channel mode of the DCI module,
Data Converter
Interface (DCI)
except for the duty cycle of the frame synchronization signal that is produced. The AC-Link frame
synchronization signal should remain high for 16 clock cycles and should be low for the following
240 cycles.
The 20-bit mode treats each 256-bit AC-Link frame as sixteen 16-bit time slots. In the 20-bit
AC-Link mode, the module operates as if COFSG<3:0> = 1111b and WS<3:0> = 1111b. The
data alignment for 20-bit data slots is not maintained in this Operating mode. For example, an
entire 256-bit AC-Link data frame can be transmitted and received in a packed fashion by setting
all bits in the TSCON and RSCON registers. Since the total available buffer length is 64 bits, it
would take 4 consecutive interrupts to transfer the AC-Link frame. The application software must
keep track of the current AC-Link frame segment by monitoring the SLOT<3:0> status bits
(DCISTAT<11:7>).
The module is enabled for AC-Link mode by writing 10h or 11h to the COFSM<1:0> control bits
in the DCICON1 SFR. The word size selection bits (WS<3:0>) and the frame synchronization
generator bits (COFSG<3:0>) have no effect for the 16 and 20-bit AC-Link modes since the
frame and word sizes are set by the protocol.
Most AC ‘97 codecs generate the clock signal that controls data transfers. Therefore, the CSCKD
control bit is set in software. The COFSD control bit is cleared because the DCI will generate the
FS signal from the incoming clock signal. The CSCKE bit is cleared so that data is sampled on
the rising edge.
The user must decide which time slots in the AC-Link data frame are to be buffered and set the
TSE and RSE control bits accordingly. At a minimum, it will be necessary to buffer the transmit
and receive TAG slots, so the TSCON<0> and RSCON<1> control bits should be set in software.
Note: Only the TSCON<12:0> control bits and the RSCON<12:0> control bits will have an
effect in the 16-bit AC-Link mode, since an AC-Link frame has 13 time slots.
1. The DCI must be configured to accept the serial transfer clock from the AC ’97 codec. Set
the CSCKD control bit and clear the DCICON3 register.
2. Next, set the COFSM<1:0> control bits (DCICON1<1:0>) to 10b or 11b to set the desired
AC-Link Frame Synchronization mode.
3. Clear the COFSD control bit (DCICON1<8>), so the DCI will output the frame sync signal.
4. Clear the CSCKE control bit (DCICON1<9>) to sample incoming data on the falling edge
of CSCK.
Note: The word size selection bits (WS<3:0>) and the frame synchronization generator
bits (COFSG<3:0>) have no effect for the 16- and 20-bit AC-Link modes, since the
frame and word sizes are set by the protocol.
DS70069C-page 22-29
Section 22. Data Converter Interface (DCI)
Interface (DCI)
22
Data Converter
dsPIC30F Family Reference Manual
Question 1: Can the DCI support data word lengths greater than 16-bits?
Answer: Yes. A long data word can be transmitted and received using multiple Transmit and
Receive registers. See Section 22.5.3 “Data Packing for Long Data Word Support” for
details.
Note: Please visit the Microchip web site (www.microchip.com) for additional Application 22
Notes and code examples for the dsPIC30F Family of devices.
Data Converter
Interface (DCI)
HIGHLIGHTS
This section of the manual contains the following major topics:
CAN Module
23.13 Operation in CPU Power Saving Modes.................................................................... 23-66
23.14 CAN Protocol Overview ............................................................................................. 23-68
23.15 Related Application Notes.......................................................................................... 23-72
23.16 Revision History ......................................................................................................... 23-73
23.1 Introduction
The Controller Area Network (CAN) module is a serial interface useful for communicating with
other peripherals or microcontroller devices. This interface/protocol was designed to allow
communications within noisy environments. Figure 23-1 shows an example CAN bus network.
dsPIC30F
with CAN
MCP2551
CAN Transceiver
bus
Microchip
MCP2510
SPI™
Interface dsPIC30F dsPIC30F PICmicro
PICmicro® with integrated with integrated with integrated
Microcontroller CAN CAN CAN
Note 1: ‘i’ in the register identifier denotes the specific CAN module (CAN1 or CAN2).
2: ‘n’ in the register identifier denotes the buffer, filter or mask number.
3: ‘m’ in the register identifier denotes the word number within a particular CAN data
field.
Lower Byte:
R-1 R-0 R-0 U-0 R-0 R-0 R-0 U-0
OPMODE<2:0> — ICODE<2:0> —
bit 7 bit 0
CAN Module
Note: Module will clear this bit when all transmissions aborted.
bit 11 CANCKS: CAN Master Clock Select bit
1 = FCAN clock is FCY
0 = FCAN clock is 4 FCY
bit 10-8 REQOP<2:0>: Request Operation Mode bits
111 = Set Listen All Messages mode
110 = Reserved
101 = Reserved
100 = Set Configuration mode
011 = Set Listen Only mode
010 = Set Loopback mode
001 = Set Disable mode
000 = Set Normal Operation mode
bit 7-5 OPMODE<2:0>: Operation Mode bits
Note: These bits indicate the current Operating mode of the CAN module. See description for REQOP
bits (CiCTRL<10:8>).
bit 4 Unimplemented: Read as ‘0’
Register 23-1: CiCTRL: CAN Module Control and Status Register (Continued)
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
U-0 R-0 R-0 R-0 R/W-0 U-0 R/W-0 R/W-0
— TXABT TXLARB TXERR TXREQ — TXPRI<1:0>
bit 7 bit 0
CAN Module
Note: This bit is cleared when TXREQ is set.
bit 4 TXERR: Error Detected During Transmission bit
1 = A bus error occurred while the message was being sent
0 = A bus error did not occur while the message was being sent
Note: This bit is cleared when TXREQ is set.
bit 3 TXREQ: Message Send Request bit
1 = Request message transmission
0 = Abort message transmission if TXREQ already set, otherwise no effect
Note: The bit will automatically clear when the message is successfully sent.
bit 2 Unimplemented: Read as ‘0’
bit 1-0 TXPRI<1:0>: Message Transmission Priority bits
11 = Highest message priority
10 = High intermediate message priority
01 = Low intermediate message Priority
00 = Lowest message priority
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x
SID<5:0> SRR TXIDE
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x
EID<13:6>
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
R/W-x R/W-x R/W-x R/W-x R/W-x U-0 U-0 U-0
TXRB0 DLC<3:0> — — —
bit 7 bit 0
Legend: 23
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
CAN Module
-n = Value at POR ‘1’ = Bit is set ‘0’ = bit is cleared x = Bit is unknown
Lower Byte:
R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x
CTXB<7:0>
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = bit is cleared x = Bit is unknown
Lower Byte:
R/C-0 U-0 U-0 U-0 R-0 R/W-0 R/W-0 R-0
RXFUL — — — RXRTRRO DBEN JTOFF FILHIT0
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit C = Bit can be cleared U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
R/C-0 U-0 U-0 U-0 R-0 R-0 R-0 R-0
RXFUL — — — RXRTRRO FILHIT<2:0>
bit 7 bit 0
CAN Module
100 = Acceptance filter 4 (RXF4)
011 = Acceptance filter 3 (RXF3)
010 = Acceptance filter 2 (RXF2)
001 = Acceptance filter 1 (RXF1) (Only possible when DBEN bit is set)
000 = Acceptance filter 0 (RXF0) (Only possible when DBEN bit is set)
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x
SID<5:0> SRR RXIDE
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x
EID<13:6>
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x
CRXB<7:0>
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
CAN Module
EID<5:0> RXRTR RB1
bit 15 bit 8
Lower Byte:
U-0 U-0 U-0 R/W-x R/W-x R/W-x R/W-x R/W-x
— — — RB0 DLC<3:0>
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x U-0 R/W-x
SID<5:0> — EXIDE
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x
EID<13:6>
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
U-0 U-0 U-0 U-0 U-0 U-0 U-0 U-0
— — — — — — — —
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
23
CAN Module
Lower Byte:
R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x U-0 R/W-x
SID<5:0> — MIDE
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x
EID<13:6>
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
U-0 U-0 U-0 U-0 U-0 U-0 U-0 U-0
— — — — — — — —
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
23
CAN Module
Lower Byte:
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
SJW<1:0> BRP<5:0>
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x
SEG2PHT SAM SEG1PH<2:0> PRSEG<2:0>
S
bit 7 bit 0
CAN Module
1 = Freely programmable
0 = Maximum of SEG1PH or information processing time (3 TQ’s), whichever is greater
bit 6 SAM: Sample of the CAN bus Line bit
1 = Bus line is sampled three times at the sample point
0 = Bus line is sampled once at the sample point
bit 5-3 SEG1PH<2:0>: Phase Buffer Segment 1 bits
111 = length is 8 x TQ
.
.
000 = length is 1 x TQ
bit 2-0 PRSEG<2:0>: Propagation Time Segment bits
111 = length is 8 x TQ
.
.
000 = length is 1 x TQ
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
R-0 R-0 R-0 R-0 R-0 R-0 R-0 R-0
RERRCNT<7:0>
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
IVRIE WAKIE ERRIE TX2IE TX1IE TX0IE RX1IE RX0IE
bit 7 bit 0
CAN Module
0 = Disabled
bit 4 TX2IE: Transmit Buffer 2 Interrupt Enable bit
1 = Enabled
0 = Disabled
bit 3 TX1IE: Transmit Buffer 1 Interrupt Enable bit
1 = Enabled
0 = Disabled
bit 2 TX0IE: Transmit Buffer 0 Interrupt Enable bit
1 = Enabled
0 = Disabled
bit 1 RX1IE: Receive Buffer 1 Interrupt Enable bit
1 = Enabled
0 = Disabled
bit 0 RX0IE: Receive Buffer 0 Interrupt Enable bit
1 = Enabled
0 = Disabled
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Lower Byte:
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
IVRIF WAKIF ERRIF TX2IF TX1IF TX0IF RX1IF RX0IF
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit C = Bit can be cleared U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
23
CAN Module
DS70070C-page 23-22
unused 306 — — — — — — — — — — — — — — — — xxxx
C1RXF1SID 308 — — — SID<10:6> SID<5:0> — EXIDE xxxx
C1RXF1EIDH 30A — — — — EID<17:14> EID<13:6> xxxx
C1RXF1EIDL 30C EID<5:0> — — — — — — — — — — xxxx
unused 30E — — — — — — — — — — — — — — — — xxxx
C1RXF2SID 310 — — — SID<10:6> SID<5:0> — EXIDE xxxx
C1RXF2EIDH 312 — — — — EID<17:14> EID<13:6> xxxx
C1RXF2EIDL 314 EID<5:0> — — — — — — — — — — xxxx
unused 316 — — — — — — — — — — — — — — — — xxxx
C1RXF3SID 318 — — — SID<10:6> SID<5:0> — EXIDE xxxx
C1RXF3EIDH 31A — — — — EID<17:14> EID<13:6> xxxx
C1RXF3EIDL 31C EID<5:0> — — — — — — — — — — xxxx
unused 31E — — — — — — — — — — — — — — — — xxxx
C1RXF4SID 320 — — — SID<10:6> SID<5:0> — EXIDE xxxx
dsPIC30F Family Reference Manual
DS70070C-page 23-23
Section 23. CAN
23
CAN Module
Table 23-1: CAN1 Register Map (Continued)
File Name ADR Bit Reset
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
DS70070C-page 23-24
C1RX1DLC 374 EID<0:5> RX RX — — — RX DLC[3:0] xxxx
RTR RB1 RB0
C1RX1B1 376 Receive Buffer 1 Byte 1 Receive Buffer 1 Byte 0 xxxx
C1RX1B2 378 Receive Buffer 1 Byte 3 Receive Buffer 1 Byte 2 xxxx
C1RX1B3 37A Receive Buffer 1 Byte 5 Receive Buffer 1 Byte 4 xxxx
C1RX1B4 37C Receive Buffer 1 Byte 7 Receive Buffer 1 Byte 6 xxxx
C1RX1CON 37E RX RX RX FILHIT[2:0] 0000
— — — — — — — — — —
FUL ERR RTR
R0
C1RX1SID 380 — — — SID<10:6> SID<5:0> SRR RX xxxx
IDE
C1RX1EID 382 — — — — EID<17:14> EID<13:6> xxxx
C1RX1DLC 384 EID<0:5> RX RX — — — RX DLC[3:0] xxxx
RTR RB1 RB0
C1RX0B1 386 Receive Buffer 0 Byte 1 Receive Buffer 0 Byte 0 xxxx
C1RX0B2 388 Receive Buffer 0 Byte 3 Receive Buffer 0 Byte 2 xxxx
C1RX0B3 38A Receive Buffer 0 Byte 5 Receive Buffer 0 Byte 4 xxxx
dsPIC30F Family Reference Manual
DS70070C-page 23-25
Section 23. CAN
23
CAN Module
Table 23-2: CAN2 Register Map (Continued)
File Name ADR Bit Reset
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
DS70070C-page 23-26
C2TX2DLC 404 EID<5:0> TX TX TX DLC<3:0> — — — xxxx
RTR RB1 RB0
C2TX2B1 406 Transmit Buffer 0 Byte 1 Transmit Buffer 0 Byte 0 xxxx
C2TX2B2 408 Transmit Buffer 0 Byte 3 Transmit Buffer 0 Byte 2 xxxx
C2TX2B3 40A Transmit Buffer 0 Byte 5 Transmit Buffer 0 Byte 4 xxxx
C2TX2B4 40C Transmit Buffer 0 Byte 7 Transmit Buffer 0 Byte 6 xxxx
C2TX2CON 40E — — — — — — — — — TX TX TX TX — TXPRI[1:0] 0000
ABT LARB ERR REQ
C2TX1SID 410 SID<10:6> — — — SID<5:0> SRR TX xxxx
IDE
C2TX1EID 412 EID<17:14> — — — — EID<13:6> xxxx
C2TX1DLC 414 EID<5:0> TX TX TX DLC<3:0> — — — xxxx
RTR RB1 RB0
C2TX1B1 416 Transmit Buffer 0 Byte 1 Transmit Buffer 0 Byte 0 xxxx
C2TX1B2 418 Transmit Buffer 0 Byte 3 Transmit Buffer 0 Byte 2 xxxx
C2TX1B3 41A Transmit Buffer 0 Byte 5 Transmit Buffer 0 Byte 4 xxxx
C2TX1B4 41C Transmit Buffer 0 Byte 7 Transmit Buffer 0 Byte 6 xxxx
dsPIC30F Family Reference Manual
DS70070C-page 23-27
Section 23. CAN
23
CAN Module
dsPIC30F Family Reference Manual
Acceptance Mask
BUFFERS RXM1
Acceptance Filter
RXF2
MESSAGE
MESSAGE
MTXBUFF
MTXBUFF
MTXBUFF
MSGREQ
MSGREQ
MSGREQ
TXLARB
TXLARB
TXLARB
c RXF0 RXF4 p
TXERR
TXERR
TXERR
TXABT
TXABT
TXABT
e t
Acceptance Filter Acceptance Filter
p
RXF1 RXF5
t
R Message R
X Identifier Assembly Identifier X
Message B B
Queue 0 Buffer 1
Control
Transmit Byte Sequencer Data Field Data Field
23
CAN Module
Receive RERRCNT
Error
Counter
PROTOCOL TERRCNT
ENGINE
Transmit ErrPas
Error BusOff
Counter
Protocol
Finite
CRC Generator CRC Check
State
Machine
Bit
Transmit
Timing Bit Timing
Logic
Logic Generator
CxTX CxRX
Note: x = 1 or 2
A standard data frame is generated by a node when the node wishes to transmit data. The
standard CAN data frame is shown in Figure 23-3. In common with all other frames, the frame
begins with a Start-Of-Frame bit (SOF - dominant state) for hard synchronization of all nodes.
The SOF is followed by the Arbitration field consisting of 12 bits, the 11-bit identifier (reflecting
the contents and priority of the message) and the RTR bit (Remote Transmission Request bit).
The RTR bit is used to distinguish a data frame (RTR - dominant) from a remote frame.
The next field is the Control field, consisting of 6 bits. The first bit of this field is called the Identifier
Extension (IDE) bit and is at dominant state to specify that the frame is a standard frame. The
following bit is reserved by the CAN protocol, RB0, and defined as a dominant bit. The remaining
4 bits of the Control field are the Data Length Code (DLC) and specify the number of bytes of
data contained in the message.
The data being sent follows in the Data field which is of the length defined by the DLC above (0-8
bytes).
The Cyclic Redundancy Check (CRC) field follows and is used to detect possible transmission
errors. The CRC field consists of a 15-bit CRC sequence and a delimiter bit. The message is
completed by the End-Of-Frame (EOF) field, which consists of seven recessive bits with no
bit-stuffing.
The final field is the Acknowledge field. During the ACK Slot bit the transmitting node sends out
a recessive bit. Any node that has received an error free frame acknowledges the correct
reception of the frame by sending back a dominant bit (regardless of whether the node is
configured to accept that specific message or not). The recessive Acknowledge Delimiter
completes the Acknowledge Slot and may not be overwritten by a dominant bit, except when an
error frame occurs.
In the extended CAN data frame, shown in Figure 23-4, the Start-Of-Frame bit (SOF) is followed
by the Arbitration Field consisting of 38 bits. The first 11 bits are the 11 Most Significant bits of
the 29-bit identifier (“Base-lD”). These 11 bits are followed by the Substitute Remote Request bit
(SRR), which is transmitted as recessive. The SRR is followed by the lDE bit which is recessive
to denote that the frame is an extended CAN frame. It should be noted from this, that if arbitration
remains unresolved after transmission of the first 11 bits of the identifier, and one of the nodes
involved in arbitration is sending a standard CAN frame (11-bit identifier), then the standard CAN
frame will win arbitration due to the assertion of a dominant lDE bit. Also, the SRR bit in an
extended CAN frame must be recessive to allow the assertion of a dominant RTR bit by a node
that is sending a standard CAN remote frame. The SRR and lDE bits are followed by the remain-
ing 18 bits of the identifier (“lD-Extension”) and a dominant Remote Transmission Request bit.
To enable standard and extended frames to be sent across a shared network, it is necessary to
split the 29-bit extended message identifier into 11-bit (Most Significant) and 18-bit (Least Signif-
icant) sections. This split ensures that the Identifier Extension bit (lDE) can remain at the same
bit position in both standard and extended frames.
The next field is the Control field, consisting of 6 bits. The first 2 bits of this field are reserved and
are at dominant state. The remaining 4 bits of the Control field are the Data Length Code (DLC)
and specify the number of data bytes.
The remaining portion of the frame (Data field, CRC field, Acknowledge field, End-Of-Frame and
intermission) is constructed in the same way as for a standard data frame.
A data transmission is usually performed on an autonomous basis with the data source node
(e.g., a sensor sending out a data frame). It is possible however for a destination node to request
the data from the source. For this purpose, the destination node sends a “remote frame” with an
identifier that matches the identifier of the required data frame. The appropriate data source node
will then send a data frame as a response to this remote request.
There are two differences between a remote frame and a data frame, shown in Figure 23-5. First,
the RTR bit is at the recessive state and second there is no Data field. In the very unlikely event
of a data frame and a remote frame with the same identifier being transmitted at the same time,
the data frame wins arbitration due to the dominant RTR bit following the identifier. In this way,
the node that transmitted the remote frame receives the desired data immediately.
An error frame is generated by any node that detects a bus error. An error frame, shown in 23
Figure 23-6, consists of 2 fields, an error flag field followed by an Error Delimiter field. The Error
Delimiter consists of 8 recessive bits and allows the bus nodes to restart bus communications
CAN Module
cleanly after an error. There are two forms of error flag fields. The form of the error flag field
depends on the error status of the node that detects the error.
If an error-active node detects a bus error then the node interrupts transmission of the current
message by generating an active error flag. The active error flag is composed of six consecutive
dominant bits. This bit sequence actively violates the bit-stuffing rule. All other stations recognize
the resulting bit-stuffing error and in turn generate error frames themselves, called Error Echo
Flags. The error flag field therefore consists of between six and twelve consecutive dominant bits
(generated by one or more nodes). The Error Delimiter field completes the error frame. After
completion of the error frame, bus activity retains to normal and the interrupted node attempts to
resend the aborted message.
If an error passive node detects a bus error then the node transmits an Error Passive flag
followed, again, by the Error Delimiter field. The Error Passive flag consists of six consecutive
recessive bits. From this it follows that, unless the bus error is detected by the transmitting node
or other error active receiver that is actually transmitting, the transmission of an error frame by
an error passive node will not affect any other node on the network. If the bus master node
generates an error passive flag then this may cause other nodes to generate error frames due
to the resulting bit-stuffing violation. After transmission of an error frame, an error passive node
must wait for 6 consecutive recessive bits on the bus before attempting to rejoin bus
communications.
Interframe Space separates a proceeding frame (of whatever type) from a following data or
remote frame. lnterframe Space is composed of at least 3 recessive bits, called the intermission.
This is provided to allow nodes time for internal processing of the message by receiving nodes
before the start of the next message frame. After the intermission, the bus line remains in the
recessive state (bus idle) until the next transmission starts.
If the transmitting node is in the error passive state, an additional 8 recessive bit times will be
inserted in the Interframe Space before any other message is transmitted by that node. This time
period is called the Suspend Transmit field. The Suspend Transmit field allows additional delay
time for other transmitting nodes to take control of the bus.
DS70070C-page 23-32
Inter-Frame Space
3 8 Data Frame or
Any Frame INT Suspend bus Idle Remote Frame
Transmit
Standard Data Frame
Start-Of-Frame
111111111111111111111 1110
Start-Of-Frame
ACK Del
Acknowledgment
CRC Del
DLC3
ID 10
ID3
ID0
IDE
DLC0
RB0
RTR
0 000 00000000 1 11111111
Identifier Data
Length
Code
dsPIC30F Family Reference Manual
Message
Filtering Inter-Frame Space
Stored in Transmit/Receive Buffers
Reserved Bits
Stored in Buffers 3 8 Data Frame or
Bit-Stuffing Any Frame INT Suspend bus Idle Remote Frame
Transmit
Start-Of-Frame
111111111111111111111 1110
Start-Of-Frame
Extended Data Format
11 1110
ID10
ID3
SRR
IDE
EID17
EID0
RTR
RB1
RB0
DLC3
DLC0
ID0
CRC Del
Start-Of-Frame
0 11 100 000000000000000000000001 11111111
Data
Identifier Extended Identifier Length
Code
Message
Filtering
Reserved bits
Stored in Buffers Stored in Transmit/Receive Buffers
Inter-Frame Space
Bit-Stuffing 3 8 Data Frame or
Any Frame INT Suspend bus Idle Remote Frame
Transmit
Start-Of-Frame
111111111111111111111 1110
DS70070C-page 23-33
Section 23. CAN
CAN Module
23
Figure 23-5:
DS70070C-page 23-34
Inter-Frame Space
3 8 Data Frame or
Remote Data Frame
Start-Of-Frame
111111111111111111111 1110
Start-Of-Frame
ACK Del
Acknowledgment
CRC Del
DLC3
ID 10
ID0
IDE
DLC0
RB0
RTR
0 100 1 11111111
dsPIC30F Family Reference Manual
Identifier Data
Length
Message Code Inter-Frame Space
Filtering
3 8 Data Frame or
Reserved Bits
Stored in Buffers Any Frame INT Remote Frame
Suspend bus Idle
Transmit
Bit-Stuffing
Start-Of-Frame
111111111111111111111 1110
Inter-Frame Space
3 8 Data Frame or
Any Frame INT Suspend bus Idle Remote Frame
Error Frame
Start-Of-Frame
111111111111111111111 1110
Start-Of-Frame
DLC3
ID 10
ID3
ID0
DLC0
IDE
RB0
RTR
0 000
Identifier Data
Length
Code
Message
Filtering
Reserved Bits
Error Frame
Bit-Stuffing 6 ≤6 8
Data Frame or
Remote Frame Error Echo Error Inter-Frame Space
Flag Error Delimiter
Flag
0000000 00111111110
Inter-Frame Space
3 8 Data Frame or
Any Frame INT Suspend bus Idle Remote Frame
Transmit
Star-Of-Frame
111111111111111111111 1110
DS70070C-page 23-35
Section 23. CAN
CAN Module
23
dsPIC30F Family Reference Manual
Note: Typically, if the CAN module is allowed to transmit in a particular mode of operation
and a transmission is requested immediately after the CAN module has been
placed in that mode of operation, the module waits for 11 consecutive recessive bits
on the bus before starting transmission. If the user switches to Disable Mode within
this 11-bit period, then this transmission is aborted and the corresponding TXABT
bit is set and TXREQ bit is cleared.
OSC1
REQOP<2:0> 001
000 000
CAN bus
WAKIF
WAKIE
CAN Module
Disabled
1 2 3 4 5
1 - Processor writes REQOP<2:0> while module receiving/transmitting message. Module continues with CAN message. 23
2 - Module detects 11 recessive bits. Module acknowledges Disable mode and sets OPMODE<2:0> bits. Module disables.
3 - CAN bus message will set WAKIF bit. If WAKIE = ’1’, processor will vector to the interrupt address. CAN message ignored.
CAN Module
4 - Processor writes REQOP<2:0> during CAN bus activity. Module waits for 11 recessive bits before accepting activate.
5 - Module detects 11 recessive bits. Module acknowledges Normal mode and sets OPMODE<2:0> bits. Module activates.
CAN Module
Note: In the case of Receive Buffer 0, a limited number of Acceptance Filters can be used
to enable a reception. A single bit, FILHIT0 (CiRX0CON<0>) determines which of
the 2 filters, RXF0 or RXF1, enabled the message reception.
To provide flexibility, there are several acceptance filters corresponding to each receive buffer.
There is also an implied priority to the receive buffers. RXB0 is the higher priority buffer and has
2 message acceptance filters associated with it. RXB1 is the lower priority buffer and has 4
acceptance filters associated with it. The lower number of possible acceptance filters makes the
match on RXB0 more restrictive and implies the higher priority associated with that buffer.
Additionally, if the RXB0 contains a valid message, and another valid message is received, the
RXB0 can be setup such that it will not overrun and the new message for RXB0 will be placed
into RXB1. Figure 23-8 shows a block diagram of the receive buffer, while Figure 23-9 shows a
flow chart for a receive operation.
Acceptance Mask
RXM1
Acceptance Filter
RXF2
R R
X Identifier Message Identifier X
Assembly
B B
Buffer
0 1
START
Detect
No Start of
Message
?
Yes
Generate Valid
No Message
Error
Frame Received
?
Yes
Go to Start
The RXFUL bit determines if the
receive register is empty and
23
able to accept a new message.
CAN Module
The DBEN bit determines if
RXB0 can roll over into
RXB1 if it is full.
Is No Is Yes
RXFUL = 0 DBEN = 1
? ?
Yes No
No Is
Move message into RXB0 Generate Overrun Error: Generate Overrun Error: RXFUL = 0
Set RX0OVR Set RX1OVR
?
Is Does
Generate Yes
RXnIE = 1 RXnIE = 1
? Interrupt
Yes ?
No No
Set ICODE<3:0> according
to which receive buffer the
message was loaded into
The EXIDE control bits (CiRXFnSID<0>) and the MIDE control bits (CiRXMnSID<0>) enable an
acceptance filter for standard or extended identifiers. The acceptance filters look at incoming
messages for the RXIDE bit to determine how to compare the identifiers. If the RXIDE bit is clear,
the message is a standard frame. If the RXIDE bit is set, the message is an extended frame.
If the MIDE control bit for the filter is set, then the identifier type for the filter is determined by the
EXIDE control bit for the filter. If the EXIDE control bit is cleared, then the filter will accept
standard identifiers. If the EXIDE bit is set, then the filter will accept extended identifiers. Most
CAN systems will use only standard identifiers or only extended identifiers.
If the MIDE control bit for the filter is cleared, the filter will accept both standard and extended
identifiers if a match occurs with the filter bits. This mode can be used in CAN systems that
support both standard and extended identifiers on the same bus.
As shown in the Receive Buffers Block Diagram, Figure 23-8, RXF0 and RXF1 filters with the
RXM0 mask are associated with RXB0. The filters RXF2, RXF3, RXF4 and RXF5 and the mask
RXM1 are associated with RXB1. When a filter matches and a message is loaded into the
receive buffer, the number of the filter that enabled the message reception is indicated in the
CiRXnCON register via the FILHIT bits. The CiRX0CON register contains one FILHIT Status bit
to indicate whether the RXF0 or the RXF1 filter enabled the message reception. The CiRX1CON
register contains the FILHIT<2:0> bits. They are coded as shown in Table 23-4.
The DBEN bit (CiRX0CON<2>) allows the FILHIT bits to distinguish a hit on filter RXF0 and
RXF1 in either RXB0 or overrun into RXB1.
111 = Acceptance Filter 1 (RXF1)
110 = Acceptance Filter 0 (RXF0)
001 = Acceptance Filter 1 (RXF1)
000 = Acceptance Filter 0 (RXF0)
If the DBEN bit is clear, there are 6 codes corresponding to the 6 filters. If the DBEN bit is set,
there are 6 codes corresponding to the 6 filters plus 2 additional codes corresponding to RXF0
and RXF1 filters overrun to RXB1.
If more than 1 acceptance filter matches, the FILHIT bits will encode the lowest binary value of
the filters that matched. In other words, if filter 2 and filter 4 match, FILHIT will code the value for
2. This essentially prioritizes the acceptance filters with lower numbers having priority.
23
Figure 23-10 shows a block diagram of the message acceptance filters.
CAN Module
Figure 23-10: Message Acceptance Filter
RXFn0 RXMn0
RXMn1 RxRqst
RXFn1
RXMnn
RXFnn
With the Cyclic Redundancy Check, the transmitter calculates special check bits for the bit
sequence from the start of a frame until the end of the data field. This CRC sequence is
transmitted in the CRC Field. The receiving node also calculates the CRC sequence using the
same formula and performs a comparison to the received sequence. If a mismatch is detected,
a CRC error has occurred and an Error Frame is generated. The message is repeated. The
receive error interrupt counter is incremented by one. An Interrupt will only be generated if the
error counter passes a threshold value. 23
23.6.5.2 Bit Stuffing Error
CAN Module
If, between the Start -Of-Frame and the CRC Delimiter, 6 consecutive bits with the same polarity
are detected, the bit-stuffing rule has been violated. A bit-stuffing error occurs and an error frame
is generated. The message is repeated. No interrupt will be generated upon this event.
If any type of error occurs during reception of a message, an error will be indicated by the IVRIF
bit (CiINTF<7>). This bit can be used (optionally with an interrupt) for autobaud detection with
the device in Listen Only mode. This error is not an indicator that any action needs to be taken,
but it does indicate that an error has occurred on the CAN bus.
A message has been successfully received and loaded into one of the receive buffers. This inter-
rupt is activated immediately after receiving the End-Of-Frame (EOF) field. Reading the RXnIF
flag will indicate which receive buffer caused the interrupt. Figure 23-11 depicts when the receive
buffer interrupt flag RXnIF will be set.
The Wake-up interrupt sequences are described in Section 23.13.1 “Operation in Sleep
Mode”.
EOF
EOF
EOF
EOF
EOF
EOF
EOF
ACK DELIMITER
ACK SIST BIT
CRCDEL
CRC0
CRC1
CRC2
CRC3
CRC4
CRC5
CRC6
CRC7
CRC8 23
CRC9
CRC10
CAN Module
CRC11
CRC12
CRC13
CRC14
DLC0
DLC1
STUFF
DLC2
DLC3
RB0
IDE
RTR
ID0
ID1
ID2
ID3
ID4
ID5
ID6
ID7
ID8
ID9
ID10
SOF
Receive Buffer
Interrupt Flag
CAN bit
CAN bit
Names
Timing
Data
A receive error interrupt will be indicated by the ERRIF bit (CiINTF<5>). This bit shows that an
error condition occurred. The source of the error can be determined by checking the bits in the
CAN Interrupt Status Register CiINTF. The bits in this register are related to receive and transmit
errors. The following subsequences will show which flags are linked to the receive errors.
If any type of error occurred during reception of the last message, an error will be indicated by
the IVRIF bit (CiINTF<7>). The specific error that occurred is unknown. This bit can be used
(optionally with an interrupt) for autobaud detection with the device in Listen Only mode. This
error is not an indicator that any action needs to be taken, but an indicator that an error has
occurred on the CAN bus.
The RXnOVR bit (CiINTF<15>, CiINTF<14>) indicates that an overrun condition occurred for the
receive buffer. An overrun condition occurs when the Message Assembly Buffer (MAB) has
assembled a valid received message, the message is accepted through the acceptance filters,
however, the receive buffer associated with the filter is not clear of the previous message. The
overflow error interrupt will be set and the message is discarded. While in the overrun situation,
the module will stay synchronized with the CAN bus and is able to transmit and receive
messages.
The RXWAR bit (CiINTF<8>) indicates that the Receive Error Counter has reached the CPU
warning limit of 96. When RXWAR transitions from a ‘0’ to a ‘1’, it will cause the Error Interrupt
Flag ERRIF to become set. This bit cannot be manually cleared, as it should remain an indicator
that the Receive Error Counter has reached the CPU warning limit of 96. The RXWAR bit will
become clear automatically if the Receive Error Counter becomes less than or equal to 95. The
ERRIF bit can be manually cleared allowing the interrupt service routine to be exited without
affecting the RXWAR bit.
The RXEP bit (CiINTF<11>) indicates that the Receive Error Counter has exceeded the Error
Passive limit of 127 and the module has gone to Error Passive state. When the RXEP bit transi-
tions from a ‘0’ to a ‘1’, it will cause the error interrupt flag to become set. The RXEP bit cannot
be manually cleared, as it should remain an indicator that the bus is in Error State Passive. The
RXEP bit will become clear automatically if the Receive Error Counter becomes less than or
equal to 127. The ERRIF bit can be manually cleared allowing the interrupt service routine to be
exited without affecting the RXEP bit.
23.7 Transmission
This subsection describes how the CAN module is used to transmit CAN messages.
CAN Module
The CAN module has three Transmit Buffers. Each of the three buffers occupies 14 bytes of data.
Eight of the bytes are the maximum 8 bytes of the transmitted message. Five bytes hold the
standard and extended identifiers and other message arbitration information.
The last byte is a control byte associated with each message. The information in this byte
determines the conditions under which the message will be transmitted and indicates status of
the transmission of the message.
The TXnIF bit (CiINTF<2>, CiINTF<3> or CiINTF<4>) will be set and the TXREQ bit
(CiTXnCON<3>) will be clear, indicating that the message buffer has completed a transmission.
The CPU will then load the message buffer with the contents of the message to be sent. At a
minimum, the standard identifier register CiTXnSID must be loaded. If data bytes are present in
the message, the TXBnDm registers are loaded. If the message is to use extended identifiers,
the CiTXnEID register and the EID<5:0> bits (CiTXnDLC<15:10>) are loaded and the TXIDE bit
is set (CiTXnSID<0>).
Prior to sending the message, the user must initialize the TXnIE bit (CiINTE<2>, CiINTE<3> or
CiINTE<4>) to enable or disable an interrupt when the message is sent. The user must also
initialize the transmit priority. Figure 23-12 shows a block diagram of the Transmit Buffers.
MESSAGE
MESSAGE
MESSAGE
TXLARB
TXLARB
TXLARB
TXREQ
TXREQ
TXREQ
TXERR
TXERR
TXERR
TXABT
TXABT
TXABT
TXPRI
TXPRI
TXPRI
Message
Queue
Control
Transmit Byte Sequencer
CAN bus
CiTX
TXREQ 23
CAN Module
TXnIF
TXABT
1 2 3
1 - Processor sets TXREQ while module receiving/transmitting message. Module continues with CAN message.
2 - Processor clears TXREQ while module looking for 11 recessive bits.
Module aborts pending transmission, sets TXABT bit in 2 clocks.
3 - Another module takes the available transmit slot.
CAN bus
CiTX
ABAT
TXREQ
TXnIF
TXABT
1 2 3
1 - Processor sets TXREQ while module receiving/transmitting message. Module continues with CAN message.
2 - Processor sets ABAT while module looking for 11 recessive bits. Module clears TXREQ bits.
Module aborts pending transmission, sets TXABT bit.
3 - Another module takes the available transmit slot.
CAN bus
CiTX
TXREQ
TXnIF
TXABT
1 2 3 4
1 - Processor sets TXREQ while module receiving/transmitting message. Module continues with CAN message.
2 - Module detects 11 recessive bits. Module begins transmission of queued message.
3 - Processor clears TXREQ requesting message abort. Abort cannot be acknowledged.
4 - At successful completion of transmission, TXREQ bit remains clear and TXnIF bit set. TXABT remains clear.
CAN bus
CiTX
TXREQ
TXnIF
TXLARB
1 2 3 4 5
23
CAN Module
START
The message transmission sequence begins when
the device determines that the TXREQ for any of the
Transmit registers has been set.
No Are any
TXREQ
bits = 1
?
Yes
Is No Does
CAN bus available TXREQ = 0 No
to start transmission ABAT = 1
? ?
Yes Yes
Examine TXPRI<1:0> to
Determine Highest Priority Message
Was No
message transmitted Set
successfully? TXERR = 1
Yes
Set TXREQ = 0
Does Yes
TXLARB = 1? Arbitration lost during
transmission
Yes
Generate Is
Interrupt TXnIE = 1?
No
A message can also be
aborted if a message error or
Does lost arbitration condition
TXREQ = 0 Yes occurred during transmission.
Set or TXABT =1
TXBUFE = 1 ?
The TXnIE bit determines if an
interrupt should be generated when a No
message is successfully transmitted.
Abort Transmission:
Set TXABT = 1
END
The TXREQ bit can be cleared just when a message is starting transmission, with the intent of
aborting the message. If the message is not being transmitted, the TXABT bit will be set,
indicating that the Abort was successfully processed.
When the user clears the TXREQ bit and the TXABT bit is not set two cycles later, the message
has already begun transmission.
If the message is being transmitted, the abort is not immediately processed, at some point later,
the TXnIF interrupt flag or the TXABT bit is set. If transmission has begun the message will only
be aborted if either an error or a loss of arbitration occurs.
Setting the ABAT bit will abort all pending Transmit Buffers and has the function of clearing all of
the TXREQ bits for all buffers. The boundary conditions are the same as clearing the TXREQ bit.
The TXREQ bit can be cleared when a message is just about to successfully complete transmis-
sion. Even if the TXREQ bit is cleared by the Data bus a short time before it will be cleared by
the successful transmission of the message, the TXnIF flag will still be set due to the successful
transmission. 23
23.7.6.4 Setting TXABT bit as a Message Completes
CAN Module
The boundary conditions are the same as clearing the TXREQ bit.
The TXREQ bit can be cleared when a message is just about to be lost to arbitration or an error.
If the TXREQ signal falls before the loss of arbitration signal or error signal, the result will be like
clearing TXREQ during transmission. When the arbitration is lost or the error is set, the TXABT
bit will be set, as it will see that an error has occurred while transmitting, and that the TXREQ bit
was not set.
If the TXREQ bit falls after the arbitration signal has entered the block, the result will be like
clearing TXREQ during an inactive transmit time. The TXABT bit will be set.
The boundary conditions are the same as clearing the TXREQ bit.
CAN bus
CiTX
TXREQ
TXnIF
TXERR
1 2 3 4 5
In the Acknowledge field of a message, the transmitter checks if the Acknowledge Slot (which it
has sent out as a recessive bit) contains a dominant bit. If not, no other node has received the
frame correctly. An acknowledge error has occurred and the message has to be repeated. No
error frame is generated.
lf a transmitter detects a dominant bit in one of the four segments including End-Of-Frame,
lnterframe Space, Acknowledge Delimiter or CRC Delimiter; then a form error has occurred and
an error frame is generated. The message is repeated.
A bit error occurs if a transmitter sends a dominant bit and detects a recessive bit. In the case
where the transmitter sends a recessive bit and a dominant bit is detected during the Arbitration
field and the Acknowledge Slot, no bit error is generated because normal arbitration is occurring.
CAN Module
be broken up into two groups:
• Transmission interrupts
• Transmission error interrupts
At least one of the three transmit buffers is empty (not scheduled) and can be loaded to schedule
a message for transmission. Reading the TXnIF flags in the CiINTF register will indicate which
transmit buffer is available and caused the interrupt.
A transmission error interrupt will be indicated by the ERRIF flag. This flag shows that an error
condition occurred. The source of the error can be determined by checking the error flags in the
CAN Interrupt Status register CiINTF. The flags in this register are related to receive and transmit
errors.
The TXWAR bit (CiINTF<10>) indicates that the Transmit Error Counter has reached the CPU
warning limit of 96. When this bit transitions from a ‘0’ to a ‘1’, it will cause the error interrupt flag
to become set. The TXWAR bit cannot be manually cleared, as it should remain as an indicator
that the Transmit Error Counter has reached the CPU warning limit of 96. The TXWAR bit will
become clear automatically if the Transmit Error Counter becomes less than or equal to 95. The
ERRIF flag can be manually cleared allowing the interrupt service routine to be exited without
affecting the TXWAR bit.
The TXEP bit (CiINTF<12>) indicates that the Transmit Error Counter has exceeded the Error
Passive limit of 127 and the module has gone to Error Passive state. When this bit transitions
froma ‘0’ to a ‘1’, it will cause the error interrupt flag to become set. The TXEP bit cannot be
manually cleared, as it should remain as an indicator that the bus is in Error Passive state. The
TXEP bit will become clear automatically if the Transmit Error Counter becomes less than or
equal to 127. The ERRIF flag can be manually cleared allowing the interrupt service routine to
be exited without affecting the TXEP bit.
The TXBO bit (CiINTF<13>) indicates that the Transmit Error Counter has exceeded 255 and the
module has gone to bus off state. When this bit transitions from a ‘0’ to a ‘1’, it will cause the error
interrupt flag to become set. The TXBO bit cannot be manually cleared, as it should remain as
an indicator that the bus is off. The ERRIF flag can be manually cleared allowing the interrupt
service routine to be exited without affecting the TXBO bit.
Reset
Error
RERRCNT > 127 or Active
TERRCNT > 127
128 occurrences of
11 consecutive 23
“recessive” bits
RERRCNT < 127 or
CAN Module
TERRCNT < 127
Error
Passive
Bus
Off
Input Signal
Sample Point
TQ
TQ = 2 (BRP<5:0> + 1)
FCAN
TCY
TQ = 2 • (BRP + 1) • = 2 X 2 X (1/32X106) = 125ns
4
CAN Module
CAN Baud Rate = 125 kHz
FCY = 5 MHz, CANCKS = 1
1. Select number of TQ clocks per bit time (e.g., K=16).
2. Calculate TQ from baud rate:
3
1 ⁄ ( BaudRate ) 1 ⁄ 125 ×10
TQ = -------------------------------------- = ---------------------------- = 500ns
K 16
3. Calculate BRP<5:0>:
TQ = 2 • (BRP + 1) • TCAN
BRP = ( 2T Q ⁄ T CY ) – 1
–9
2 ( 500 ×10 )
= ------------------------------
6
-–1
1 ⁄ ( 5 ×10 )
= 4
The frequencies of the oscillators in the different nodes must be coordinated in order to provide
a system-wide specified time quantum. This means that all oscillators must have a TOSC that is
a integral divisor of TQ.
23.9.6 Synchronization
To compensate for phase shifts between the oscillator frequencies of the different bus stations,
each CAN controller must be able to synchronize to the relevant signal edge of the incoming
signal. When an edge in the transmitted data is detected, the logic will compare the location of
the edge to the expected time (Synchronous Segment). The circuit will then adjust the values of
Phase1 Segment and Phase2 Segment. There are 2 mechanisms used to synchronize.
Hard Synchronization is only done whenever there is a “recessive” to “dominant” edge during bus
Idle, indicating the start of a message. After hard synchronization, the bit time counters are
restarted with Synchronous Segment. Hard synchronization forces the edge which has caused
the hard synchronization to lie within the synchronization segment of the restarted bit time.
Due to the rules of synchronization, if a hard synchronization is done, there will not be a
re-synchronization within that bit time.
23.9.6.2 Re-synchronization
CAN Module
Figure 23-21: Lengthening a Bit Period
Input Signal
TQ
Input Signal
TQ
000 ERR•WAK•TX0•TX1•TX2•RX0•RX1
001 ERR
100 ERR•TX0
011 ERR•TX0•TX1
010 ERR•TX0•TX1•TX2
110 ERR•TX0•TX1•TX2•RX0
101 ERR•TX0•TX1•TX2•RX0•RX1
23
111 ERR•TX0•TX1•TX2•RX0•RX1•WAK
CAN Module
Legend: ERR = ERRIF • ERRIE
TX0 = TX0IF • TX0IE
TX1 = TX1IF • TX1IE
TX2 = TX2IF • TX2IE
RX0 = RX0IF • RX0IE
RX1 = RX1IF • RX1IE
WAK = WAKIF • WAKIE
OSC1
TOST
CAN bus
Sleep
WAKIF
WAKIE
Processor in
SLEEP
CAN Module
1 2
Disabled
3 4 5
23
CAN Module
1 - Processor requests and receives Module Disable mode. Wake-up interrupt enabled.
2 - Processor executes SLEEP (PWRSAV #0) instruction.
3 - SOF of message wakes up processor. Oscillator start time begins. CAN message lost. WAKIF bit set.
4 - Processor completes oscillator start time. Processor resumes program or interrupt, based on GIE bits.
Processor requests Normal Operating mode. Module waits for 11 recessive bits before
accepting CAN bus activity. CAN message lost.
5 - Module detects 11 recessive bits. Module will begin to receive messages and transmit any pending messages.
If two or more bus nodes start their transmission at the same time (“Multiple Access”), collision
of the messages is avoided by bitwise arbitration (“Collision Detection/Non-Destructive
Arbitration” together with the “Wired-AND” mechanism, “dominant” bits override “recessive” bits).
Each node sends the bits of its message identifier (MSb first) and monitors the bus level. A node
that sends a recessive identifier bit but reads back a dominant one loses bus arbitration and
switches to Receive mode. This condition occurs when the message identifier of a competing
node has a lower binary value (dominant state = logic 0) and therefore, the competing node is
sending a message with a higher priority. In this way, the bus node with the highest priority
message wins arbitration without losing time by having to repeat the message. All other nodes
automatically try to repeat their transmission once the bus returns to the Idle state. It is not
permitted for different nodes to send messages with the same identifier, as arbitration could fail,
leading to collisions and errors later in the message.
The original CAN specifications (Versions 1.0, 1.2 and 2.0A) defined the message identifier as
having a length of 11 bits giving a possible 2048 message identifiers. The specification has since
been updated (to version 2.0B) to remove this limitation. CAN specification Version 2.0B allows
message identifier lengths of 11 and/or 29 bits to be used (an identifier length of 29 bits allows
over 536 million message identifiers). Version 2.0B CAN is also referred to as “Extended CAN”;
and Versions 1.0, 1.2 and 2.0A) are referred to as “Standard CAN”.
CAN Module
CAN modules specified by CAN V2.0A are only able to transmit and receive standard frames
according to the Standard CAN protocol. Messages using the 29-bit identifier cause errors. If a
device is specified by CAN V2.0B, there is one more distinction. Modules named “Part B Passive”
can only transmit and receive standard frames but tolerate extended frames without generating
error frames. “Part B Active” devices are able to transmit and receive both standard and
extended frames.
The LLC sub layer is concerned with Message Filtering, Overload Notification and Error
Recovery Management. The scope of the LLC sub layer is:
• To provide services for data transfer and for remote data request.
• To decide which messages received by the LLC sub layer are actually to be accepted.
• To provide means for error recovery management and overload notifications.
The MAC sub layer represents the kernel of the CAN protocol. The MAC sub layer defines the
transfer protocol, (i.e., controlling the Framing, Performing Arbitration, Error Checking, Error
Signalling and Fault Confinement). It presents messages received from the LLC sub layer and
accepts messages to be transmitted to the LLC sub layer. Within the MAC sub layer is where it’s
decided whether the bus is free for starting a new transmission, or whether a reception is just
starting. The MAC sub layer is supervised by a management entity called Fault Confinement
which is a self-checking mechanism for distinguishing short disturbances from permanent
failures. Also, some general features of the bit timing are regarded as part of the MAC sub layer.
The physical layer defines the actual transfer of the bits between the different nodes with respect
to all electrical properties. The PLS sub layer defines how signals are actually transmitted and
therefore deals with the description of Bit Timing, Bit Encoding and Synchronization.
The lower levels of the protocol are implemented in driver/receiver chips and the actual interface
such as twisted pair wiring or optical fiber, etc. Within one network, the physical layer has to be
the same for all nodes. The driver/receiver characteristics of the physical layer are not defined in
the CAN specification so as to allow transmission medium and signal level implementations to
be optimized for their application. The most common example of the physical transmission
medium is defined in Road Vehicles ISO11898, a multiplex wiring specification.
Application
Presentation
Session
Transport
Network
Supervisor
LLC (Logical Link Control)
Acceptance Filtering
Overload Notification
Recovery Management
CAN Module
Serialization/Deserialization
Physical Layer
Note: Please visit the Microchip web site (www.microchip.com) for additional Application
Notes and code examples for the dsPIC30F Family of devices.
23
CAN Module
NOTES:
HIGHLIGHTS
This section of the manual contains the following topics:
24
Configuration
Device
24.1 Introduction
The device Configuration registers allow each user to customize certain aspects of the device to
fit the needs of the application. Device Configuration registers are nonvolatile memory locations
in the program memory map that hold settings for the dsPIC device during power-down. The
Configuration registers hold global setup information for the device, such as the oscillator source,
Watchdog Timer mode and code protection settings.
The device Configuration registers are mapped in program memory locations, starting at address
0xF80000 and are accessible during normal device operation. This region is also referred to as
“configuration space”.
The Configuration bits can be programmed (read as ‘0’), or left unprogrammed (read as ‘1’) to
select various device configurations.
Note 1: Not all device Configuration bits shown in the subsequent Configuration register
descriptions may be available on a specific device. Refer to the device data sheet
for more information.
2: dsPIC30F devices in the General Purpose, Sensor and Motor Control families fea-
ture one of three versions of the Oscillator system – Version 1, Version 2 and Ver-
sion 3. For information on the Configuration bits of the FOSC device Configuration
register available in each of these versions, please refer to Section 7. "Oscillator”.
Middle Byte:
R/P U U U U U U U
FWDTEN — — — — — — —
bit 15 bit 8
Lower Byte:
U U R/P R/P R/P R/P R/P R/P
FWPSA<1:0> FWPSB<3:0>
bit 7 bit 0
Configuration
Legend:
Device
R = Readable bit P = Programmable bit U = Unimplemented bit
Middle Byte:
R/P U U U U R/P R/P R/P
MCLREN — — — — PWMPIN HPOL LPOL
bit 15 bit 8
Lower Byte:
R/P U R/P R/P U U R/P R/P
BOREN — BORV<1:0> — — FPWRT<1:0>
bit 7 bit 0
Middle Byte:
U U U U U U U U
— — — — — — — —
bit 15 bit 8
Lower Byte:
U U U U U U P P
— — — — — — GCP GWRP
bit 7 bit 0
Legend:
R = Readable bit P = Programmable bit U = Unimplemented bit
24
Configuration
Device
The GCP and GWRP Configuration bits in the FGS Configuration register must be
programmed/erased as a group. If one or both of the Configuration bits is programmed to a ‘0’,
a full chip erase must be performed to change the state of either bit.
Note: If the code protection Configuration fuse group (FGS<GCP:GWRP>) bits have been
programmed, an erase of the entire code-protected device is only possible at
voltages, VDD >= 4.5 volts.
24
Configuration
Device
24
Configuration
Device
HIGHLIGHTS
This section of the manual contains the following topics:
25
Development
Tool Support
Note: Some development tools described in this section are not available at the time of this
writing, however they are currently under development. Some of the product details may
change. Please check the Microchip web site or your local Microchip sales office for the
most current information and the availability of each product.
25.1 Introduction
Microchip will offer a comprehensive package of development tools and libraries to support the
dsPIC architecture. In addition, the company is partnering with many third party tool
manufacturers for additional dsPIC device support.
25.2 Microchip Hardware and Language Tools
The Microchip tools proposed include:
• MPLAB® Integrated Development Environment (IDE)
• dsPIC Language Suite, including MPLAB C30 C Compiler, Assembler, Linker and Librarian
• MPLAB SIM Software Simulator
• MPLAB ICE 4000 In-Circuit Emulator
• MPLAB ICD 2 In-Circuit Debugger
• PRO MATE® II Universal Device Programmer
• PICSTART® Plus Development Programmer
The MPLAB Integrated Development Environment (IDE) is available at no cost. MPLAB IDE
software is a desktop development environment with tool sets for developing and debugging a
microcontroller design application. MPLAB IDE allows quick changes between different develop-
ment and debugging activities. Designed for use with the Windows® operating environment, it is
a powerful, affordable, run-time development tool. It is also the common user interface for
Microchip's development systems tools, including MPLAB Editor, MPLAB ASM30 Assembler,
MPLAB SIM software simulator, MPLAB LIB30 Library, MPLAB LINK30 Linker, MPLAB ICE 4000
In-Circuit Emulators, PRO MATE II programmer and In-Circuit Debugger (ICD 2). The MPLAB
IDE gives users the flexibility to edit, compile and emulate, all from a single user interface.
Engineers can design and develop code for the dsPIC devices in the same design environment
that they have used for PICmicro® microcontrollers.
The MPLAB IDE is a 32-bit Windows-based application. It provides many advanced features for
the engineer in a modern, easy-to-use interface. MPLAB IDE integrates:
• Full featured, color coded text editor
• Easy-to-use project manager with visual display
• Source level debugging
• Enhanced source level debugging for ‘C’
- (Structures, automatic variables, etc.)
• Customizable toolbar and key mapping
• Dynamic status bar that displays processor condition at a glance
• Context sensitive, interactive on-line help
• Integrated MPLAB SIM instruction simulator
• User interface for PRO MATE II and PICSTART Plus device programmers
(sold separately)
• User interface for MPLAB ICE 4000 In-Circuit Emulator (sold separately)
• User interface for MPLAB ICD 2 In-Circuit Debugger (sold separately)
Note: This product is currently available on Microchip’s web site, www.microchip.com. The
Assembler, Linker and Librarian are included with MPLAB IDE. Contact your local
Microchip sales office for availability of the MPLAB C30 C compiler.
The Microchip Technology MPLAB C30 C compiler is a complete, easy-to-use language product.
It allows dsPIC applications codes to be written in high level C language and then be fully
converted into machine-object code for programming of the microcontroller. It simplifies develop-
ment of code by removing code obstacles and allowing the designer to focus on program flow
and not on program elements. Several options for compiling are available so the user can select
those that will maximize the efficiency of the code characteristics.
It is a fully ANSI compliant product with standard libraries for the dsPIC family of microcontrollers.
It uses the many advanced features of the dsPIC devices to provide very efficient assembly code
generation.
MPLAB C30 also provides extensions that will allow for excellent support of the hardware, such
as interrupts and peripherals. It is fully integrated with the MPLAB IDE for high level, source
debugging. Some features include:
• 16-bit native data types
• Efficient use of register-based, 3-operand instructions
• Complex Addressing modes
• Efficient multi-bit shift operations
• Efficient signed/unsigned comparisons
MPLAB C30 comes complete with its own assembler, linker and librarian. These allow the user
to write mixed mode C and assembly programs and link the resulting object files into a single
executable file. The compiler is sold separately. The assembler, linker and librarian is available
for free with MPLAB IDE.
The MPLAB SIM software simulator allows code development in a PC-hosted environment by
simulating the dsPIC device on an instruction level. On any given instruction, the data areas are
able to be examined or modified. The execution is able to be performed in Single Step, Execute
Until Break or Trace mode.(1)
The MPLAB SIM simulator fully supports symbolic debugging using the MPLAB C30 compiler
25
and assembler. The software simulator offers the flexibility to develop and debug code outside of
Development
Tool Support
Note 1: Some features, including peripheral support, have not been implemented at the
time of this writing. Please check Microchip’s web site or your local Microchip sales
office for the most current information.
Note: This product is currently under development at the time of this writing. Some of the
product details may change. Please refer to the Microchip web site or your local
Microchip sales office for the most current information and the availability of this
product.
The MPLAB ICE 4000 In-Circuit Emulator will provide the product development engineer with a
complete hardware design tool for the dsPIC devices. Software control of the emulator will be
provided by MPLAB IDE.
The MPLAB ICE 4000 will be a full-featured emulator system with enhanced trace, trigger and
data monitoring features. Interchangeable processor modules will allow the system to be easily
reconfigured for emulation of different processors.
The MPLAB ICE 4000 will support the extended, high-end PICmicro microcontrollers, the
PIC18CXXX and PIC18FXXX devices, as well as the dsPIC Family of digital signal controllers.
The modular architecture of the MPLAB ICE 4000 in-circuit emulator will allow expansion to
support new devices.
The MPLAB ICE 4000 in-circuit emulator system has been designed as a real-time emulation
system, with advanced features that are generally found on more expensive development tools.
Features will include:
• Full speed emulation, up to 50 MHz bus speed or 200 MHz external clock speed
• Low voltage emulation down to 1.8 volts
• Configured with 2 Mb program emulation memory; additional modular memory up to 16 Mb
• 64K x 136-bit wide Trace Memory
• Unlimited software breakpoints
• Complex break, trace and trigger logic
• Multi-level trigger up to 4 levels
• Filter trigger functions to trace specific event
• 16-bit Pass counter for triggering on sequential events
• 16-bit Delay counter
• 48-bit time-stamp
• Stopwatch feature
• Time between events
• Statistical performance analysis
• Code coverage analysis
• USB and parallel printer port PC connection
Note: This product is available, but does not provide support for dsPIC30F devices at this
time. Please refer to the Microchip web site for information about product upgrades.
Microchip's In-Circuit Debugger, MPLAB ICD, will be a powerful, low cost, run-time development
tool. This tool is based on the PICmicro® and dsPIC Flash devices.
The MPLAB ICD 2 will utilize the in-circuit debugging capability built into the various devices. This
feature, along with Microchip's In-Circuit Serial Programming™ protocol (ICSP™), will offer cost
effective, in-circuit debugging from the graphical user interface of MPLAB IDE. This will enable a
designer to develop and debug source code by watching variables, single-stepping and setting
break points. Running at full speed enables testing hardware in real-time. Some of its features will
include:
• Full speed operation to the range of the device
• Serial or USB PC connector
• Serial interface externally powered
• USB powered from PC interface
• Low noise power (VPP and VDD) for use with analog and other noise sensitive applications
• Operation down to 2.0V
• Can be used as an ICD or inexpensive serial programmer
• Modular application connector as MPLAB ICD
• Limited number of breakpoints
• “Smart watch” variable windows
• Some chip resources required (RAM, program memory and 2 pins)
Note: This product is available, but does not provide support for dsPIC30F devices at this
time. Please refer to the Microchip web site for information about product upgrades.
The PRO MATE II universal device programmer will be a full-featured programmer capable of
operating in Stand-alone mode, as well as PC-hosted mode.
The PRO MATE II device programmer will have programmable VDD and VPP supplies, which will
allow it to verify programmed memory at VDDMIN and VDDMAX for maximum reliability when
programming requires this capability. It will have an LCD display for instructions and error
messages and keys to enter commands. Interchangeable optional socket modules will support
all package types.
In Stand-alone mode, the PRO MATE II device programmer will be able to read, verify or program
PICmicro and dsPIC30F devices. It will also be able to set code protection in this mode.
PRO MATE II features will include:
• Runs under MPLAB IDE
• Field upgradable firmware
• DOS Command Line interface for production
• Host, Safe and “Stand-alone” operation
• Automatic downloading of object file
• SQTPSM serialization adds an unique serial number to each device programmed
• In-Circuit Serial Programming Kit (sold separately)
25
• Interchangeable socket modules supporting all package options (sold separately)
Development
Tool Support
Note: These products are currently under development at the time of this writing. Some of
the product details may change. Please refer to the Microchip web site or your local
Microchip sales office for the most current information and the availability of this
product.
Microchip is partnering with key third party tool manufacturers for the development of quality
hardware and software tools in support of the dsPIC30F Product Family. Microchip plans to offer
this initial set of tools and libraries, which will enable customers to rapidly develop their dsPIC30F
based application(s).
Microchip will expand this current list to provide our customers with additional value added ser-
vices, (i.e., repository of skilled/certified technical applications contacts, reference designs,
hardware and software developers).
Please refer to the Microchip web site (www.microchip.com) for the most current information
about third party support for the dsPIC30F Device Family.
The dsPIC30F software tools and libraries will include:
• Third Party C compilers
• Floating Point and Double Precision Math Library
• DSP Algorithm Library
• Digital Filter Design Software Utility
• Peripheral Driver Library
• CAN Library
• Real-Time Operating Systems (RTOS)
• OSEK Operating Systems
• TCP/IP Protocol Stacks
• V.22/V.22bis and V.32 ITU Specifications
The dsPIC30F hardware development board tools include:
• General Purpose Development Board
• Motor Control Development System
• Connectivity Development Board
Note: These products are currently under development at the time of this writing. Some of
the product details may change. Please refer to the Microchip web site or your local
Microchip sales office for the most current information and the availability of these
products.
In addition to the Microchip MPLAB C30 C Compiler, the dsPIC30F will be supported by ANSI C
compilers developed by IAR, HI-TECH and Custom Computer Services (CCS).
The compilers will allow dsPIC application code to be written in high level C language, and then
be fully converted into machine object code for programming of the microcontroller. Each
compiler tool will provide several options for compiling, so the user can select those that will
maximize the efficiency of the generated code characteristics.
The multiple C compiler solutions will have different price targets and features, enabling the
customer to select the compiler best suited for their application requirements.
Note: This product is currently under development at the time of this writing. Some of the
product details may change. Please refer to the Microchip web site or your local
Microchip sales office for the most current information and the availability of this
product.
The Math Library will support several standard C functions, including, but not limited to:
• sin(), cos(), tan()
• asin(), acos(), atan(),
• log(), log10()
• sqrt(), power()
• ceil(), floor()
• fmod(), frexp()
The math function routines will be developed and optimized in dsPIC30F assembly language and
will be callable from both assembly and C language. Floating point and double precision versions
of each function shall be provided. The Microchip MPLAB C30 and IAR C compilers will be
supported.
Note: This product is currently under development at the time of this writing. Some of the
product details may change. Please refer to the Microchip web site or your local
Microchip sales office for the most current information and the availability of this
product.
The DSP library will support multiple filtering, convolution, vector and matrix functions. Some of
the functions will include, but will not be limited to:
• Cascaded Infinite Impulse Response (IIR) Filters
• Correlation
• Convolution
• Finite Impulse Response (FIR) Filters
• Windowing Functions
• FFTs
• LMS Filter
• Vector Addition and Subtraction
• Vector Dot Product
• Vector Power
• Matrix Addition and Subtraction
• Matrix Multiplication
25
Development
Tool Support
Note: This product is currently under development at the time of this writing. Some of the
product details may change. Please refer to the Microchip web site or your local
Microchip sales office for the most current information and the availability of this
product.
Microchip will offer a digital filter design software tool which will enable the user to develop
optimized assembly code for Low-pass, High-pass, Band-pass and Band-stop IIR and FIR filters,
including 16-bit fractional data size filter coefficients from a graphical user interface. The
application developer will enter the required filter frequency specifications and the software tool
develops the filter code and coefficients. Ideal filter frequency response and time domain plots
are generated for analysis.
FIR filter lengths up to 513 taps and IIR filter lengths up to 10 cascaded sections will be
supported.
All IIR and FIR routines are generated in assembly language and will be callable from both
assembly and C language. The Microchip MPLAB C30 C compiler will be supported.
Note: This product is currently under development at the time of this writing. Some of the
product details may change. Please refer to the Microchip web site or your local
Microchip sales office for the most current information and the availability of this
product.
Microchip will offer a peripheral driver library that will support the setup and control of dsPIC30F
hardware peripherals, including, but not limited to:
• Analog-to-Digital Converter
• Motor Control PWM
• Quadrature Encoder Interface
• UART
• SPI™
• Data Converter Interface
• I2C™
• General Purpose Timers
• Input Capture
• Output Compare/Simple PWM
Note: This product is currently under development at the time of this writing. Some of the
product details may change. Please refer to the Microchip web site or your local
Microchip sales office for the most current information and the availability of this
product.
Microchip will offer a CAN driver library, which will support the dsPIC30F CAN peripheral. Some
of the CAN functions which will be supported are:
• Initialize CAN Module
• Set CAN Operational Mode
• Set CAN Baud Rate
• Set CAN Masks
• Set CAN Filters
• Send CAN Message
• Receive CAN Message
• Abort CAN Sequence
• Get CAN TX Error Count
• Get CAN RX Error Count
Note: This product is currently under development at the time of this writing. Some of the
product details may change. Please refer to the Microchip web site or your local
Microchip sales office for the most current information and the availability of this
product.
Real-Time Operating System (RTOS) solutions for the dsPIC30F Product Family will be
provided. These RTOS solutions will provide the necessary function calls and operating system
routines to write efficient C and/or assembly code for multi-tasking applications. In addition,
RTOS solutions will be provided that address those applications in which program and more
importantly, data memory resources, are limited. Configurable and optimized kernels will be
available to support various RTOS application requirements.
The RTOS solutions will range from a fully-true, preemptive and multi-tasking scheduler to a
cooperative type scheduler, both of which will be designed to optimally run on the dsPIC30F
devices. Depending on the RTOS implementation, some of the function calls provided in the
system kernel will be:
• Control Tasks
• Send And Receive Messages
• Handle Events
• Control Resources
• Control Semaphores
• Regulate Timing in a Variety of Ways
• Provide Memory Management
• Handle Interrupts and Swap Tasks
Most functions will be written in ANSI C, with the exception of time critical functions, which will
be optimized in assembly, thereby reducing execution time for maximum code efficiency. The 25
ANSI C and assembly routines will be supported by the Microchip MPLAB C30 C compiler.
Development
Tool Support
Electronic documentation will accompany the RTOS, enabling the user to efficiently understand
and implement the RTOS in their application.
Note: This product is currently under development at the time of this writing. Some of the
product details may change. Please refer to the Microchip web site or your local
Microchip sales office for the most current information and the availability of this
product.
Operating Systems for the vehicle software standard OSEK/VDX will be developed for support
of the dsPIC30F product family. The functionality of OSEK, “Offene Systeme und deren
Schnittstellen für die Elektronik im Kraftfahrzeug” (Open systems and the corresponding
interfaces for automotive electronics), is harmonized with VDX “Vehicle Distributed eXecutive”
yielding OSEK/VDX.
Structured and modular RTOS software implementations based on standardized interfaces and
protocols will be provided. Structured and modular implementations will provide for portability and
extendability for distributed control units for vehicles.
Various OSEK COM modules will be provided, such as:
• OSEK/COM Standard API
• OSEK/COM Communication API
• OSEK/COM Network API
• OSEK/COM Standard Protocols
• OSEK/COM Device Driver Interface
Microchip will also provide Internal and External CAN driver support. The physical layer will be
integrated into the communication controller’s hardware and will not be covered by the OSEK
specifications.
Most module functions will be developed in ANSI C, with the exception of time critical functions
and peripheral utilization, which will be optimized in assembly, thereby reducing execution time
for maximum code efficiency. The Microchip MPLAB C30 C compiler will be supported.
Note: This product is currently under development at the time of this writing. Some of the
product details may change. Please refer to the Microchip web site or your local
Microchip sales office for the most current information and the availability of this
product.
Microchip will offer various Transmission Control Protocol/Internet Protocol (TCP/IP) Stack Layer
solutions for Internet connectivity solutions implemented on the dsPIC30F product family. Both
reduced and full stack implementations will be provided, which will allow the user to select the
optimum TCP/IP stack solution for their application.
Application protocol layers, such as FTP, TFTP and SMTP, Transport and Internet layers, such
as TCP, UDP, ICMP and IP, and Network Access layers, such as PPP, SLIP, ARP and DHCP, will
be provided. Various configurations, such as a minimal UDP/IP stack will be available for limited
connectivity requirements.
Most stack protocol functions will be developed and optimized in Microchip’s MPLAB C30 C
language. Assembly language coding may be developed for specific dsPIC30F hardware
peripherals and Ethernet drivers to optimize code size and execution time. These assembly
language specific routines will be assembly and C callable.
Electronic documentation will accompany the TCP/IP protocol stack, enabling the user to
efficiently understand and implement the protocol stack in their application.
Note: This product is currently under development at the time of this writing. Some of the
product details may change. Please refer to the Microchip web site or your local
Microchip sales office for the most current information and the availability of this
product.
Microchip will offer ITU compliant V.22/V.22bis (1200/2400 bps) and V.32 (non-trellis coding at
9600 bps) modem specifications to support a range of “connected” applications.
Applications which will benefit from these modem specifications will be numerous and will fall into
many applications, some of which are listed here:
• Internet enabled home security systems
• Internet connected power, gas and water meters
• Internet connected vending machines
• Smart Appliances
• Industrial monitoring
• POS Terminals
• Set Top Boxes
• Drop Boxes
• Fire Panels
Most ITU specification modules will be developed and optimized in Microchip’s MPLAB C30 C
language. Assembly language coding may be developed for specific dsPIC30F hardware
peripherals, along with key transmitter and receiver filtering routines to optimize code size and
execution time. These assembly language specific routines will be assembly and C callable.
Electronic documentation will accompany the modem library, enabling the user to efficiently
understand and implement the library functions.
25.4 dsPIC30F Hardware Development Boards
Note: These products are currently under development at the time of this writing. Some of
the product details may change. Please refer to the Microchip web site or your local
Microchip sales office for the most current information and the availability of these
products.
Microchip will initially provide three hardware development boards, which will provide
the application developer with a tool in which to quickly prototype and validate key design
requirements. Each board will feature key dsPIC30F peripherals and support Microchip’s MPLAB
In-Circuit Debugger (ICD 2) tool for cost effective debugging and programming of the dsPIC30F
device. The three initial boards to be provided are:
• General Purpose Development Board
• Motor Control Development System
• Connectivity Development Board
25
Development
Tool Support
Note: This product is currently under development at the time of this writing. Some of the
product details may change. Please refer to the Microchip web site or your local
Microchip sales office for the most current information and the availability of this
product.
The dsPIC30F general purpose development board will provide the application designer with a
low cost development tool in which to become familiar with the dsPIC30F 16-bit architecture, high
performance peripherals and powerful instruction set. The development board will serve as an
ideal prototyping tool in which to quickly develop and validate key design requirements.
Some key features and attributes of the general purpose development board will be:
• Supports various dsPIC30F packages
• CAN communication channel
• RS-232 and RS-485 communication channels
• Codec interface with line in/out jacks
• In-Circuit Debugger interface
• MPLAB ICE 4000 emulation support
• Microchip temperature sensor
• Microchip Op Amp circuit, supporting user input signals
• Microchip Digital-to-Analog Converter
• 2x16 LCD
• General purpose prototyping area
• Various LEDS, switches and potentiometers
The general purpose development board will be shipped with a 9V power supply, RS-232 I/O
cable, preprogrammed dsPIC30F device, example software and appropriate documentation to
enable the user to exercise the development board demonstration programs.
Note: This product is currently under development at the time of this writing. Some of the
product details may change. Please refer to the Microchip web site or your local
Microchip sales office for the most current information and the availability of this
product.
The dsPIC30F motor control development system will initially provide the application developer
with three main components for quick prototyping and validation of BLDC, PMAC and ACIM
applications. The three main components will be:
• dsPIC30F Motor Control Main Board
• 3-phase Low Voltage Power Module
• 3-phase High Voltage Power Module
The main control board will support the dsPIC30F6010 device, various peripheral interfaces, and
a custom interface header system that will allow different motor power modules to be connected.
The control board also will have connectors for mechanical position sensors, such as incremental
rotary encoders and hall effect sensors, and a breadboard area for custom circuits. The main
control board will receive its power from a standard plug-in transformer.
The low voltage power module will be optimized for 3-phase motor applications that will require
a DC bus voltage less than 60 volts and will deliver up to 400W power output. The 3-phase low
voltage power module is intended to power BLDC and PMAC motors.
The high voltage power module will be optimized for 3-phase motor applications that require DC
bus voltages up to 400 volts and up to 1 kW power output. The high voltage module will have an
active power factor correction circuit that will be controlled by the dsPIC30F device. This power
module is intended for AC induction motor and power inverter applications.
Both power modules will have automatic Fault protection and electrical isolation from the control
interface. Both power module boards will provide preconditioned voltage and current signals to
the main control board. All position feedback devices that will be isolated from the motor control
circuitry, such as incremental encoders, hall-effect sensors or tachometer sensors, will be directly
connected to the main control board. Both modules will be equipped with motor braking circuits.
25
Development
Tool Support
Note: This product is currently under development at the time of this writing. Some of the
product details may change. Please refer to the Microchip web site or your local
Microchip sales office for the most current information and the availability of this
product.
The dsPIC30F connectivity development board will provide the application developer a basic
platform for developing and evaluating various connectivity solutions, implementing TCP/IP
protocol layers combined with V.22/V.22bis and V.32 (non-trellis coding) ITU specifications,
across PSTN or Ethernet communication channels.
Some key features and attributes of the connectivity development board will be:
• Supports the dsPIC30F6014 device
• Media Access Control (MAC) and PHY interface
• PSTN interface with DAA/AFE
• RS-232 and RS-485 communication channels
• In-Circuit Debugger interface
• MPLAB ICE 4000 emulation support
• Microchip temperature sensor
• Microchip Digital-to-Analog Converter
• 2x16 LCD
• General purpose prototyping area
• Various LEDs, switches and potentiometers
The connectivity development board will be shipped with a 9V power supply, RS-232 I/O cable
and preprogrammed dsPIC30F devices with example connectivity software and appropriate
documentation to enable the user to exercise the development board connectivity demo
program.
Note: Please visit the Microchip web site (www.microchip.com) for additional Application
Notes and code examples for the dsPIC30F Family of devices.
25
Development
Tool Support
Appendix
Section 26. Appendix
HIGHLIGHTS
This section of the manual contains the following topics:
Appendix
pulled high through the external pull-up resistors. The Start and Stop conditions determine the
start and stop of data transmission. The Start condition is defined as a high-to-low transition of
the SDA when the SCL is high. The Stop condition is defined as a low-to-high transition of the
SDA when the SCL is high. Figure A-1 shows the Start and Stop conditions. The master
generates these conditions for starting and terminating data transfer. Due to the definition of the
Start and Stop conditions, when data is being transmitted, the SDA line can only change state
when the SCL line is low.
SDA
SCL S P
MSb LSb
S R/W ACK
S Start Condition
R/W Read/Write pulse
ACK Acknowledge
Sent By Slave
= 0 for write
S - Start Condition
R/W - Read/Write Pulse
ACK - Acknowledge
Appendix
transfer. After each byte, the slave-receiver generates an Acknowledge bit (ACK) (Figure A-4).
When a slave-receiver doesn’t acknowledge the slave address or received data, the master
must abort the transfer. The slave must leave SDA high so that the master can generate the
Stop condition (Figure A-1).
Data
Output by
Transmitter
Data not acknowledge
Output by
Receiver
SCL from acknowledge
Master 1 2 8 9
S
Start Clock Pulse for
Condition Acknowledgment
If the master is receiving the data (master-receiver), it generates an Acknowledge signal for
each received byte of data, except for the last byte. To signal the end of data to the
slave-transmitter, the master does not generate an acknowledge (not acknowledge). The slave
then releases the SDA line so the master can generate the Stop condition. The master can also
generate the Stop condition during the Acknowledge pulse for valid termination of data transfer.
If the slave needs to delay the transmission of the next byte, holding the SCL line low will force
the master into a wait state. Data transfer continues when the slave releases the SCL line. This
allows the slave to move the received data or fetch the data it needs to transfer before allowing
the clock to start. This wait state technique can also be implemented at the bit level, Figure A-5.
SDA
MSb Acknowledgment Byte Complete Acknowledgment
Signal from Receiver Signal from Receiver
Interrupt with Receiver
Figure A-6 and Figure A-7 illustrate master-transmitter and master-receiver data transfer
sequences.
Appendix
Acknowledge pulse (not the bus-free state). This allows a master to send “commands” to the
slave and then receive the requested information or to address a different slave device. This
sequence is illustrated in Figure A-8.
(read or write)
(n bytes + acknowledge)
S Slave Address R/W A Data A/A Sr Slave Address R/W A Data A/A P
Combined format:
Sr Slave Address R/W A Slave Address A Data A Data A/A Sr Slave Address R/W A Data A Data A P
(Code + A9:A8) (A7:A0) (Code + A9:A8)
(write) (read)
Combined format - A master addresses a slave with a 10-bit address, then transmits
data to this slave and reads data from this slave.
A.4 Multi-master
The I2C protocol allows a system to have more than one master. This is called a multi-master
system. When two or more masters try to transfer data at the same time, arbitration and
synchronization occur.
A.4.1 Arbitration
Arbitration takes place on the SDA line, while the SCL line is high. The master which transmits a
high when the other master transmits a low, loses arbitration (Figure A-9) and turns off its data
output stage. A master which lost arbitration can generate clock pulses until the end of the data
byte where it lost arbitration. When the master devices are addressing the same device,
arbitration continues into the data.
DATA 2
SDA
SCL
Masters that also incorporate the slave function, and have lost arbitration must immediately
switch over to Slave-receiver mode. This is because the winning master-transmitter may be
addressing it.
Arbitration is not allowed between:
• A repeated Start condition
• A Stop condition and a data bit
• A repeated Start condition and a Stop condition
Care needs to be taken to ensure that these conditions do not occur.
Clock synchronization occurs after the devices have started arbitration. This is performed using
Appendix
a wired-AND connection to the SCL line. A high-to-low transition on the SCL line causes the
concerned devices to start counting off their low period. Once a device clock has gone low, it will
hold the SCL line low until its SCL high state is reached. The low-to-high transition of this clock
may not change the state of the SCL line if another device clock is still within its low period. The
SCL line is held low by the device with the longest low period. Devices with shorter low periods
enter a high wait-state until the SCL line comes high. When the SCL line comes high, all
devices start counting off their high periods. The first device to complete its high period will pull
the SCL line low. The SCL line high time is determined by the device with the shortest high
period, Figure A-10.
CLK 1
Counter
CLK 2 Reset
SCL
Table A-2 and Table A-3 show the specifications of a compliant I2C bus. The column titled,
Parameter No., is provided to ease the user’s correlation to the corresponding parameter in the
device data sheet. Figure A-11 and Figure A-12 show these times on the appropriate
waveforms.
SCL
91 93
90 92
SDA
Start Stop
Condition Condition
SDA MSb
Out
Appendix
No.
100 THIGH Clock high time 100 kHz mode 4.0 — μs
400 kHz mode 0.6 — μs
101 TLOW Clock low time 100 kHz mode 4.7 — μs
400 kHz mode 1.3 — μs
102 TR SDA and SCL rise 100 kHz mode — 1000 ns
time 400 kHz mode 20 + 300 ns Cb is specified to be from
0.1Cb 10 to 400 pF
103 TF SDA and SCL fall 100 kHz mode — 300 ns
time 400 kHz mode 20 + 300 ns Cb is specified to be from
0.1Cb 10 to 400 pF
90 TSU:STA Start condition setup 100 kHz mode 4.7 — μs Only relevant for repeated
time 400 kHz mode 0.6 — μs Start condition
91 THD:STA Start condition hold 100 kHz mode 4.0 — μs After this period the first
time 400 kHz mode 0.6 — μs clock pulse is generated
106 THD:DAT Data input hold time 100 kHz mode 0 — ns
400 kHz mode 0 0.9 μs
107 TSU:DAT Data input setup time 100 kHz mode 250 — ns Note 2
400 kHz mode 100 — ns
92 TSU:STO Stop condition setup 100 kHz mode 4.7 — μs
time 400 kHz mode 0.6 — μs
109 TAA Output valid from 100 kHz mode — 3500 ns Note 1
clock 400 kHz mode — 1000 ns
110 TBUF Bus free time 100 kHz mode 4.7 — μs Time the bus must be free
400 kHz mode 1.3 — μs before a new transmission
can start
D102 Cb Bus capacitive loading — 400 pF
Note 1: As a transmitter, the device must provide this internal minimum delay time to bridge the undefined region
(min. 300 ns) of the falling edge of SCL to avoid unintended generation of Start or Stop conditions.
2: A Fast mode I2C-bus device can be used in a Standard mode I2C-bus system, but the requirement
TSU;DAT ≥ 250 ns must then be met. This will automatically be the case if the device does not stretch the
LOW period of the SCL signal. If such a device does stretch the LOW period of the SCL signal, it must
output the next data bit to the SDA line,
TR max.+TSU; DAT = 1000 + 250 = 1250 ns (according to the Standard mode I2C bus specification) before
the SCL line is released.
Appendix
currently transmitting). If this is the case (and no other node wishes to start a transmission at the
same moment), node A becomes the bus master and sends its message. All other nodes switch
to Receive mode during the first transmitted bit (Start-Of-Frame bit). After correct reception of
the message (which is acknowledged by each node), each bus node checks the message
identifier and stores the message, if required. Otherwise, the message is discarded.
If two or more bus nodes start their transmission at the same time (“Multiple Access”), collision
of the messages is avoided by bitwise arbitration (“Collision Detection/Non-Destructive
Arbitration“ together with the “Wired-AND” mechanism, “dominant“ bits override “recessive”
bits). Each node sends the bits of its message identifier (MSB first) and monitors the bus level.
A node that sends a recessive identifier bit but reads back a dominant one loses bus arbitration
and switches to Receive mode. This condition occurs when the message identifier of a
competing node has a lower binary value (dominant state = logic 0) and therefore, the
competing node is sending a message with a higher priority. In this way, the bus node with the
highest priority message wins arbitration without losing time by having to repeat the message.
All other nodes automatically try to repeat their transmission once the bus returns to the Idle
state. It is not permitted for different nodes to send messages with the same identifier as
arbitration could fail leading to collisions and errors.
The original CAN specifications (versions 1.0, 1.2 and 2.0A) defined the message identifier as
having a length of 11 bits giving a possible 2048 message identifiers. The specification has
since been updated (to version 2.0B) to remove this possible limitation. CAN specification,
version 2.0B, allows message identifier lengths of 11 and/or 29 bits to be used (an identifier
length of 29 bits allows over 536 Million message identifiers). Version 2.0B CAN is also referred
to as “Extended CAN“ and versions 1.0, 1.2 and 2.0A are referred to as “Standard CAN”.
Those data frames and remote frames, which only contain the 11-bit identifier, are called
standard frames according to CAN specification V2.0A. With these frames, 2048 different
messages can be identified (identifiers 0-2047). However, the 16 messages with the lowest
priority (2032-2047) are reserved. Extended frames, according to CAN specification V2.0B,
have a 29-bit identifier. As already mentioned, this 29-bit identifier is made up of the 11-bit
identifier (“Base lD”) and the 18-bit Extended identifier (“ID Extension”).
CAN modules specified by CAN V2.0A are only able to transmit and receive standard frames
according to the Standard CAN protocol. Messages using the 29-bit identifier cause errors. If a
device is specified by CAN V2.0B, there is one more distinction. Modules named “Part B
Passive” can only transmit and receive standard frames, but tolerate extended frames without
generating error frames. “Part B Active” devices are able to transmit and receive both standard
and extended frames.
Full CAN devices do the whole bus protocol in hardware, including the acceptance filtering and
the message management. They contain several so called message objects which handle the
identifier, the data, the direction (receive or transmit) and the information Standard
CAN/Extended CAN. During the initialization of the device, the host CPU defines which
messages are to be sent and which are to be received. The host CPU is informed by interrupt if
the identifier of a received message matches with one of the programmed (receive-) message
objects. In this way. the CPU load is reduced. Using Full CAN devices, high baud rates and high
bus loads with many messages can be handled. These chips are more expensive than the
Basic CAN devices, though.
Many Full CAN chips provide a “Basic-CAN Feature”. One of their messages objects can be
programmed in a way that every message is stored there that does not match with one of the
other message objects. This can be very helpful in a number of applications.
Appendix
Application SHADED REGIONS
DEFINED BY CAN
Presentation BUS SPECIFICATION
Session
Transport
Network
Physical Layer
Appendix
• all local errors at transmitters are detected
• up to 5 randomly distributed errors in a message are detected
• burst errors of length less than 15 in a message are detected
• errors of any odd number in a message are detected
14. Error Signalling and Recovery Time – Corrupted messages are flagged by any node
detecting an error. Such messages are aborted and will be retransmitted automatically.
The recovery time from detecting an error until the start of the next message is at most 31
bit times, if there is no further error.
15. Fault Confinement – CAN nodes are able to distinguish short disturbances from
permanent failures. Defective nodes are switched off.
16. Connections – The CAN serial communication link is a bus to which a number of units may
be connected. This number has no theoretical limit. Practically the total number of units
will be limited by delay times and/or electrical loads on the bus line.
17. Single Channel – The bus consists of a single channel that carries bits. From this data
resynchronization, information can be derived. The way in which this channel is
implemented is not fixed in this specification (i.e., single wire (plus ground), two differential
wires, optical fires, etc).
18. Bus values – The bus can have one of two complementary logical values; ‘dominant’ or
‘recessive’. During simultaneous transmission of ‘dominant’ and ‘recessive’ bits, the
resulting bus value will be ‘dominant’. For example, in case of a wired-AND
implementation of the bus, the ‘dominant’ level would be represented by a logical ‘0’ and
the ‘recessive’ level by a logical ‘1’. Physical states (e.g., electrical voltage, light) that
represent the logical levels are not given in the specification.
19. Acknowledgment – All receivers check the consistency of the message being received
and will acknowledge a consistent message and flag an inconsistent message.
20. Sleep Mode; Wake-up – To reduce the system's power consumption, a CAN device may
be set into Sleep mode without any internal activity and with disconnected bus drivers.
The Sleep mode is finished with a wake-up by any bus activity or by internal conditions of
the system. On wake-up, the internal activity is restarted, although the MAC sub-layer will
be waiting for the system's oscillator to stabilize and it will then wait until it has
synchronized itself to the bus activity (by checking for eleven consecutive ‘recessive’ bits),
before the bus drivers are set to “on-bus” again.
A data frame is generated by a node when the node wishes to transmit data. The Standard CAN
Data Frame is shown in Figure B-2. In common with all other frames, the frame begins with a
Start-Of-Frame bit (SOF – dominant state) for hard synchronization of all nodes.
The SOF is followed by the Arbitration field consisting of 12 bits, the 11-bit ldentifier (reflecting
the contents and priority of the message) and the RTR bit (Remote Transmission Request bit).
The RTR bit is used to distinguish a data frame (RTR – dominant) from a remote frame.
The next field is the Control field, consisting of 6 bits. The first bit of this field is called the lDE bit
(Identifier Extension) and is at dominant state to specify that the frame is a standard frame. The
following bit is reserved, RB0, and defined as a dominant bit. The remaining 4 bits of the Control
field are the Data Length Code (DLC) and specify the number of bytes of data contained in the
message.
The data being sent follows in the Data field, which is of the length defined by the DLC above
(1-8 bytes).
The Cyclic Redundancy field (CRC) follows and is used to detect possible transmission errors.
The CRC field consists of a 15-bit CRC sequence, completed by the recessive CRC Delimiter
bit.
The final field is the Acknowledge field. During the ACK Slot bit, the transmitting node sends out
a recessive bit. Any node that has received an error free frame acknowledges the correct
reception of the frame by sending back a dominant bit (regardless of whether the node is
configured to accept that specific message or not). From this, it can be seen that CAN belongs
to the “in-bit-response” group of protocols. The recessive Acknowledge Delimiter completes the
Acknowledge slot and may not be overwritten by a dominant bit.
Appendix
(e.g., a sensor sending out a data frame). It is possible, however, for a destination node to
request the data from the source. For this purpose, the destination node sends a “remote frame”
with an identifier that matches the identifier of the required data frame. The appropriate data
source node will then send a data frame as a response to this remote request.
There are 2 differences between a remote frame and a data frame, shown in Figure B-4. First,
the RTR bit is at the recessive state and second, there is no data field. In the very unlikely event
of a data frame and a remote frame with the same identifier being transmitted at the same time,
the data frame wins arbitration due to the dominant RTR bit following the identifier. In this way,
the node that transmitted the remote frame receives the desired data immediately.
90 90
90 90
90 90
3
90 90
INT
90 90
90 90
90 90
90 90
90 90
8
90 90
Transmit
Suspend
90 90
90 90
90 90
90 90
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
90 90
Inter-Frame Space
90 90
90 90
90 90
bus Idle
90 90
90 90
90 90
0
1 1 1 0
90 90 Start-Of-Frame Start-Of-Frame
90 90 ID 10
90 90
90 90
90 90
90 90
Filtering
Message
11
90 90
12
90 90
Data Frame or
Remote Frame
Identifier
90 90 ID3
90 90
Arbitration Field
Stored in Buffers
90 90
90 90 ID0
90 90 RTR
90 90 IDE
Reserved Bits
0 0 0
90 90 RB0
90 90 DLC3
6
Field
90 90
4
Data
Control
Code
90 90
Length
90 90 DLC0
90 90
90 90
90 90
90 90
8
90 90
90 90
90 90
90 90
90 90
90 90
90 90
Bit Stuffing
90 90
Data Field
90 90
8N (≤ N ≤ 8)
90 90
90 90
Stored in Transmit/Receive Buffers
90 90
90 90
8
90 90
90 90
90 90
Data Frame (number of bits = 44 + 8N)
0 0 0 0 0 0 0 0
90 90
90 90
90 90
90 90
90 90
90 90
90 90
90 90
15
90 90
CRC
16
90 90
90 90
CRC Field
90 90
90 90
90 90
90 90
90 90
1
90 90 CRC Del
90 90 Acknowledgment
90 90 ACK Del
90 90
90 90
90 90
7
90 90
90 90 Frame
End-Of-
Any Frame
90 90
1 1 1 1 1 1 1 1
90 90
90 90
3
90 90
INT
90 90
90 90
90 90
90 90
90 90
8
90 90
Transmit
Suspend
90 90
90 90
90 90
90 90
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
90 90
90 90
Inter-Frame Space
90 90
90 90
bus Idle
90 90
90 90
90 90
1 1 1 0
90 90 Start-Of-Frame
90 90
90 90
90 90
90 90
90 90
90 90
90 90
Data Frame or
Remote Frame
90 90
90 90
90 90
Standard Data Frame Figure B-2:
dsPIC30F Family Reference Manual
DS70074C-page 26-21 © 2004 Microchip Technology Inc.
90 90
90 90
90 90
90 90
1 1
90 90
90 90
90 90
90 90
bus Idle
90 90
90 90
90 90
0
1 1 1 0
90 90 Start-Of-Frame Start-Of-Frame
90 90 ID10
90 90
90 90
90 90
90 90
90 90
11
90 90
Filtering
Data Frame or
Identifier
Remote Frame
Message
90 90 ID3
90 90
90 90
90 90 ID0
90 90 SRR
0 1
90 90 IDE
90 90 EID17
90 90
32
90 90
90 90
90 90
Stored in Buffers
Arbitration Field
90 90
90 90
90 90
90 90
18
90 90
90 90
90 90
90 90
Extended Identifier
90 90
90 90
90 90
90 90
90 90 EID0
90 90 RTR
90 90 RB1
Reserved bits
0 0 0
90 90 RB0
90 90 DLC3
6
Bit Stuffing
Field
90 90
4
Data
Control
90 90
Code
Length
90 90 DLC0
90 90
90 90
90 90
90 90
8
90 90
90 90
90 90
90 90
90 90
90 90
90 90
90 90
Data Field
90 90
8N (≤ N ≤ 8)
90 90
Stored in Transmit/Receive Buffers
90 90
Data Frame (number of bits = 64 + 8N)
90 90
90 90
8
90 90
90 90
90 90
90 90
90 90
90 90
90 90
90 90
90 90
90 90
90 90
90 90
15
90 90
16
CRC
90 90
CRC Field
90 90
90 90
90 90
90 90
90 90
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
90 90 CRC Del
90 90 Acknowledgment
90 90 ACK Del
90 90
90 90
90 90 7
90 90
90 90
Frame
Any Frame
End-Of-
90 90
1 1 1 1 1 1 1 1
90 90
90 90
90 90
INT
90 90
90 90
90 90
90 90
90 90
8
90 90
Transmit
Suspend
90 90
90 90
90 90
90 90
90 90
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
90 90
Inter-Frame Space
90 90
90 90
bus Idle
90 90
90 90
90 90
1 1 1 0
90 90 Start-Of-Frame
90 90
90 90
90 90
90 90
90 90
90 90
90 90
Data Frame or
Remote Frame
90 90
Appendix
90 90
90 90
Extended Data Format Figure B-3:
26
Section 26. Appendix
© 2004 Microchip Technology Inc. DS70074C-page 26-22
90 90
90 90
90 90
90 90
90 90
90 90
90 90
90 90
90 90
90 90
90 90
90 90
90 90
90 90
Any Frame
90 90
90 90
90 90
90 90
3
INT
90 90
90 90
90 90
90 90
90 90
8
90 90
Transmit
Suspend
90 90
90 90
90 90
90 90
90 90
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
90 90
Inter-Frame Space
90 90
90 90
bus Idle
90 90
90 90
90 90
90 90
0
1 1 1 0
Start-Of-Frame Start-Of-Frame
90 90 ID 10
90 90
90 90
90 90
90 90
Filtering
Message
11
90 90
12
90 90
Data Frame or
Remote Frame
90 90
Identifier
90 90
Arbitration Field
Stored in Buffers
90 90
90 90 ID0
90 90 RTR
90 90 IDE
90 90 Reserved Bits
1 0 0
RB0
90 90 DLC3
6
Field
90 90
4
Data
Control
90 90
Code
Length
90 90 DLC0
Bit Stuffing
90 90
90 90
90 90
90 90
90 90
90 90
90 90
15
90 90
CRC
16
90 90
90 90
CRC Field
90 90
90 90
Remote Frame (number of bits = 44)
90 90
90 90
90 90
90 90
1
CRC Del
90 90 Acknowledgment
90 90 ACK Del
90 90
90 90
90 90
7
90 90
90 90
Frame
End-Of-
Any Frame
90 90
90 90
1 1 1 1 1 1 1 1
90 90
90 90
INT
90 90
90 90
90 90
90 90
90 90
8
90 90
Transmit
Suspend
90 90
90 90
90 90
90 90
90 90
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
90 90
Inter-Frame Space
90 90
90 90
bus Idle
90 90
90 90
90 90
90 90
1 1 1 0
Start-Of-Frame
90 90
90 90
90 90
90 90
90 90
90 90
90 90
Data Frame or
Remote Frame
90 90
90 90
90 90
90 90
90 90
90 90
90 90
90 90
90 90
90 90
90 90
90 90
90 90
90 90
90 90
90 90
90 90
90 90
90 90
90 90
Remote Data Frame Figure B-4:
dsPIC30F Family Reference Manual
DS70074C-page 26-23 © 2004 Microchip Technology Inc.
90 90
90 90
90 90
90 90
90 90
90 90
90 90
90 90
90 90
90 90
90 90
90 90
90 90
Any Frame
90 90
90 90
90 90
90 90
3
INT
90 90
90 90
90 90
90 90
90 90
8
90 90
Transmit
Suspend
90 90
90 90
90 90
90 90
90 90
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
90 90
Inter-Frame Space
90 90
90 90
bus Idle
90 90
90 90
90 90
90 90
0
1 1 1 0
Start-Of-Frame Start-Of-Frame
90 90
90 90 ID 10
90 90
90 90
90 90
90 90
11
12
90 90
Data Frame or
Remote Frame
90 90
Filtering
Identifier
Message
90 90 ID3
Arbitration Field
90 90
90 90 ID0
90 90
90 90 RTR
90 90 Reserved Bits IDE
0 0 0
RB0
90 90
DLC3
6
90 90
Field
4
90 90
Data
Control
Code
Length
90 90 DLC0
90 90
90 90
Bit Stuffing
90 90
90 90
8
90 90
90 90
Interrupted Data Frame
90 90
90 90
90 90
90 90
90 90
90 90
Data Field
90 90
8N (≤ N ≤ 8)
90 90
90 90
90 90
Data Frame or
Remote Frame
90 90
8
90 90
90 90
90 90
90 90
6
90 90
Flag
Error
90 90
90 90
90 90
0 0 0 0 0 0 0
90 90
90 90
≤6
Flag
90 90
Error
Echo
90 90
90 90
90 90
90 90
Error Frame
90 90
90 90
8
Error
90 90
90 90
Delimiter
Any Frame
90 90
90 90
90 90
0 0 1 1 1 1 1 1 1 1 0
90 90
INT
90 90
90 90
90 90
90 90
90 90
8
90 90
Transmit
Suspend
90 90
Inter-Frame Space
90 90
90 90
90 90
90 90
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
90 90
Inter-Frame Space
90 90
90 90
bus Idle
90 90
90 90
90 90
90 90
1 1 1 0
Start-Of-Frame
90 90
90 90
90 90
90 90
90 90
90 90
90 90
Data Frame or
Remote Frame
90 90
90 90
90 90
90 90
90 90
90 90
Appendix
90 90
90 90
Error Frame Figure B-5:
26
Section 26. Appendix
dsPIC30F Family Reference Manual
Appendix
AC-Link Compliant mode interfaces. Many codecs intended for use in audio applications
support sampling rates between 8 kHz and 48 kHz and typically use one of the interface
protocols previously mentioned. The Data Converter Interface (DCI) module automatically
handles the interface timing associated with these codecs. No overhead from the CPU is
required until the requested amount of data has been transmitted and/or received by the DCI.
Up to four data words may be transferred between CPU interrupts.
SCK
WS
I2S Transmitter I2S Receiver Transmitter master
SD
SCK
WS
I2S Transmitter I2S Receiver Receiver master
SD
I2S Controller
SCK
I2S WS
Transmitter I2S Receiver Separate controller as master
SD
SCK
WS
Note: A 5 bit transfer is shown here for illustration purposes. The I2S protocol does
not specify word length – this is system dependent.
A 12.288 MHz BIT_CLK signal is provided by the master AC ’97 codec in a system. The
Appendix
BIT_CLK signal is an input to the AC ‘97 controller and up to three slave AC ‘97 codec devices
in the system. All data on the AC-Link transitions on the rising edge of BIT_CLK and is sampled
by the receiving device on the falling edge of BIT_CLK.
SDO is a time division multiplexed data stream sent to the AC ‘97 codec
SDI is the time division multiplexed data stream from the AC ‘97 codec.
C.3.4 SYNC
SYNC is a 48 kHz fixed rate sample synchronization signal that is supplied from the AC ‘97
controller to the AC ‘97 codec. The SYNC signal is derived by dividing the BIT_CLK signal by
256. The SYNC signal is high for 16 BIT_CLK periods and is low for 240 BIT_CLK periods. The
SYNC signal only changes on the rising edge of BIT_CLK and its period defines the boundaries
of one audio data frame.
C.3.5 Reset
The RESET signal is an input to each AC ‘97 codec in the system and resets the codec
hardware.
The AC-Link serial data stream uses a time division multiplexed (TDM) scheme with a 256-bit
data frame. Each data frame is subdivided into 13 time slots, numbered Slot #0 – Slot #12. Slot
#0 is a special time slot that contains 16 bits. The remaining 12 slots are 20-bits wide.
An example of an AC-Link frame is shown in Figure C-4. The frame begins with a rising edge of
the SYNC signal which is coincident with the rising edge of BIT_CLK. The AC ‘97 codec
samples the assertion of SYNC on the falling edge of BIT_CLK that immediately follows. This
falling edge marks the time when both the codec and controller are aware of the start of a new
frame. On the next rising edge of BIT_CLK, the codec asserts the MSb of SDATA_IN and the
codec asserts the first edge of SDATA_OUT. This sequence ensures that data transitions and
subsequent sample points for both incoming and outgoing data streams are time aligned.
Slot #0, Slot #1 and Slot #2 have special use for status and control in the AC-Link protocol. The
remaining time slots are assigned to certain types of digital audio data. The data assignment for
Slot #3 – Slot #12 is dependent on the AC ‘97 codec that is selected, so the slot usage is
summarized briefly here. For more details on slot usage, refer to the AC ‘97 Component
Specification.
Slot #0 is commonly called the ‘tag frame’. The tag frame has a bit location for each data time
slot in the AC-Link protocol. These bits are used to specify which time slots in a frame are valid
for use by the controller. A “1” in a given bit position of Slot #0 indicates that the corresponding
time slot within the current audio frame has been assigned to a data stream, and contains valid
data. If a slot is “tagged” invalid, it is the responsibility of the source of the data, (AC ‘97 codec
for the input stream, AC ’97 controller for the output stream), to stuff all bit positions with 0s
during the slot’s active time.
There are also special bits in the tag frame. The MSb of the tag frame for SDATA_OUT is a
‘Frame Valid’ Status bit. The Frame Valid bit serves as a global indicator to the codec that at
least one time slot in the frame has valid data. If the entire frame is tagged invalid, the codec
can ignore all subsequent slots in the frame. This feature is used to implement sample rates
other than 48 kHz.
The two LSbs of the SDATA_OUT tag frame indicate the codec address. Up to four AC ‘97
codecs may be connected in a system. If only one codec is used in a system, these bits remain
0’s.
The MSb of the SDATA_IN is used as a ‘Codec Ready’ Status bit. If this bit location is a ‘0’, then
the codec is powered down and/or not ready for normal operation. If the ‘Codec Ready’ bit is
set, it is the responsibility of the controller to query the status registers in the codec to see which
subsections are operable.
Slot #1 and Slot #2 also have special uses in the AC-Link protocol. These time slots are used
for address and data values when reading or writing the AC ‘97 codec control registers. These
time slots must be tagged as valid in Slot #0 in order to read and write the control registers. The
AC ‘97 Component Specification allows for sixty-four (64) 16-bit control registers in the codec.
Seven address bits are provided in the AC-Link protocol, but only even-numbered addresses
are used. The odd numbered address values are reserved.
Slot #1 and Slot #2 for the SDATA_OUT line are called the Command Address and Command
Data, respectively. The Command Address slot on the SDATA_OUT line is used to specify the
codec register address and to specify whether the register access will be a read or a write. The
Command Data slot on SDATA_OUT contains the 16-bit value that will be written to one of the
codec control registers. If a read of the codec registers is being performed, the Command Data
bits are set to ‘0’s.
Slot #1 and Slot #2 for the SDATA_IN line are called the Status Address and Status Data slots,
respectively. The Status Address time slot echos the register address that was previously sent
to the codec. If this value is ‘0’, an invalid address was previously sent to the codec.
The Status Address time slot also has ten Slot Request bits. The Slot Request bits can be
manipulated by the codec for applications with variable sample rates.
The Status Data time slot returns 16-bit data read from the codec control/status registers.
Slot #3 in the SDATA_OUT signal is used for the composite digital audio left playback stream.
For soundcard applications, this is typically the combined .WAV audio and MIDI synthesizer
output.
Slot #3 in the SDATA_IN signal is the left channel record data taken from the AC ‘97 codec input
mixer.
Slot #4 in the SDATA_OUT signal is used for the composite digital audio right playback stream.
For soundcard applications, this is typically the combined .WAV audio and MIDI synthesizer
output.
Slot #4 in the SDATA_IN signal is the right channel record data taken from the AC ‘97 codec
input mixer.
Slot #5 in the SDATA_OUT signal is used for modem DAC data. The default resolution for
Appendix
modem compatible AC ‘97 codecs is 16 bits. As in all time slots, the unused bits in the slot are
set to ‘0’.
Slot #5 in the SDATA_IN signal is used for the modem ADC data.
C.4.7 Slot #6
Slot #6 in the SDATA_OUT signal is used for PCM Center Channel DAC data in 4 or 6-channel
sound configurations.
Slot #6 in the SDATA_IN signal is used for dedicated microphone record data. The data in this
slot allows echo cancellation algorithms to be used for speakerphone applications.
C.4.8 Slot #7
Slot #7 in the SDATA_OUT signal is used for PCM Left Channel DAC data in 4 or 6-channel
sound configurations.
Slot #7 in the SDATA_IN signal is reserved for future use in the AC ‘97 Component
Specification.
C.4.9 Slot #8
Slot #8 in the SDATA_OUT signal is used for PCM Right Channel DAC data in 4 or 6-channel
sound configurations.
Slot #8 in the SDATA_IN signal is reserved for future use in the AC ‘97 Component
Specification.
C.4.10 Slot #9
Slot #9 in the SDATA_OUT signal is used for PCM LFE DAC data in 6-channel sound
configurations.
Slot #9 in the SDATA_IN signal is reserved for future use in the AC ‘97 Component
Specification.
Slot #10 is used for the modem line 2 ADC and DAC data in modem compatible devices.
Slot #11 is used for the modem handset ADC and DAC data in modem compatible devices.
The bits in Slot #12 are used for reading and writing GPIO pins in the AC ‘97 codec. The GPIO
pins are provided for modem control functions on modem compatible devices.
BIT_CLK
24.576
SYNC MHz
SDATA_OUT
AC ‘97 AC ‘97
Controller SDATA_IN
Codec
/RESET
256
16 20 20 20 20 20 20 20
SYNC
Codec Slot 1 Slot 2 Slot 3 Slot 4 Slot 5 Slot 6 Slot 7 Slot 8 Slot 9 Slot 10 Slot 11 Slot 12 ___ ___ ___
Ready Valid Valid Valid Valid Valid Valid Valid Valid Valid Valid Valid Valid
bits 11-2: On demand data request flags – 0 = send data, 1 = do NOTsend data
Appendix
bit 15 bit 0
Valid Slot 1 Slot 2 Slot 3 Slot 4 Slot 5 Slot 6 Slot 7 Slot 8 Slot 9 Slot 10 Slot 11 Slot 12 ___ Codec Codec
Frame Valid Valid Valid Valid Valid Valid Valid Valid Valid Valid Valid Valid ID ID
R/W Reserved
bit Control Register Index (set to 0)
NOTES:
Index
ADCON0 Register...........................................17-4, 18-4
Current Consumption for Operation .......................... 8-9
Configuring Analog Port Pins......................17-14, 18-12
Byte to Word Conversion................................................. 2-17
Edge Detection Mode .............................................. 13-8
Effects of a Reset........................................16-19, 17-55 C
Effects of a Reset (12-bit) ...................................... 18-33
Enabling the Module .............................................. 17-16 CAN
Enabling the Module (12-bit).................................. 18-14 Buffer Reception and Overflow Truth Table .......... 23-44
How to Start Sampling ........................................... 17-17 Message Acceptance Filters ................................. 23-12
How to Stop Sampling and Start Conversions....... 17-18 CAN Library ..................................................................... 25-9
Reading the A/D Result Buffer............................... 17-46 Capture Buffer Operation................................................. 13-8
Sampling Requirements..............................17-45, 18-26 Clock Switching
Transfer Function........................................17-47, 18-28 Aborting ................................................................... 7-36
Transfer Function (12-bit) ...................................... 18-28 Enable ..................................................................... 7-34
A/D Accuracy/Error ........................................................ 17-47 Entering Sleep Mode During ................................... 7-36
A/D Accuracy/Error (12-bit) ............................................ 18-28 Operation................................................................. 7-34
A/D Conversion Speeds......................................17-49, 18-30 Recommended Code Sequence ............................. 7-36
A/D Converter External Conversion Request .................. 6-10 Tips.......................................................................... 7-36
A/D Module Configuration .............................................. 17-13 CN
A/D Module Configuration (12-bit) ................................. 18-11 Change Notification Pins ......................................... 11-7
A/D Sampling Requirements (12-bit) ............................. 18-26 Configuration and Operation ................................... 11-8
A/D Special Event Trigger.............................................. 12-22 Control Registers..................................................... 11-7
A/D Terminology and Conversion Sequence ................. 17-11 Operation in Sleep and Idle Modes ......................... 11-8
A/D Terminology and Conversion Sequence (12-bit) .... 18-10 Code Examples
Accumulator ‘Write Back’ ................................................. 2-25 Clock Switching ....................................................... 7-37
ACK................................................................................ 21-38 Compare Mode Toggle Mode Pin State Setup........ 14-8
Acknowledge Pulse........................................................ 21-38 Compare Mode Toggle Setup and Interrupt
Address Generator Units and DSP Class Instructions....... 3-6 Servicing.......................................................... 14-8
Address Register Dependencies ..................................... 2-35 Configuration Register Write ................................... 5-15
AKS ................................................................................ 21-17 Continuous Output Pulse Setup and Interrupt
Alternate Vector Table ....................................................... 6-2 Servicing........................................................ 14-16
Arithmetic Logic Unit (ALU).............................................. 2-17 Initialization Code for 16-bit Asynchronous Counter
Mode Using an External Clock Input ............. 12-11
B Initialization Code for 16-bit Gated Time Accumulation
Mode ............................................................. 12-13
Barrel Shifter .................................................................... 2-26 Initialization Code for 16-bit Synchronous Counter Mode
Baud Rate Using an External Clock Input ....................... 12-10
Generator (BRG)...................................................... 19-8 Initialization Code for 16-bit Timer Using
Tables ...................................................................... 19-9 System Clock................................................... 12-9
BF .......................................................................21-18, 21-19 Initialization Code for 32-bit Gated Time
Bit-Reversed Addressing ................................................. 3-14 Accumulation Mode ....................................... 12-20
and Modulo Addressing ........................................... 3-15 Initialization Code for 32-bit Synchronous Counter Mode
Code Example ......................................................... 3-18 Using an External Clock Input ....................... 12-19
Intro.......................................................................... 3-14 Initialization Code for 32-bit Timer Using Instruction
Modifier Value .......................................................... 3-16 Cycle as Input Clock...................................... 12-18
Operation ................................................................. 3-15 Prescaled Capture................................................... 13-7
Block Diagrams PWM Mode Pulse Setup and Interrupt
Dedicated Port Structure.......................................... 11-2 Servicing........................................................ 14-22
DSP Engine ............................................................. 2-19 Reading from a 32-bit Timer.................................. 12-21
dsPIC30F CPU Core.................................................. 2-3 Single Output Pulse Setup and Interrupt
External Power-on Reset Circuit (For Slow VDD Servicing........................................................ 14-12
Rise Time) ......................................................... 8-7 Single Row Programming........................................ 5-14
Input Capture ........................................................... 13-2 8-bit Transmit/Receive (UART1) ........................... 19-20
Input Change Notification......................................... 11-7 9-bit Transmit/Receive (UART1), Address Detect
Low Voltage Detect (LVD) ......................................... 9-3 Enabled ......................................................... 19-20
Oscillator System ....................................................... 7-4 CODEC Interface Basics and Terminology ..................... 22-8
Output Compare Module.......................................... 14-2 Complementary PWM Output Mode.............................. 15-26
Reset System............................................................. 8-2 Configuration Bit Descriptions ......................................... 24-6
Shared Port Structure .............................................. 11-4 BOR and POR ......................................................... 24-6
Type A Timer ........................................................... 12-3 General Code Segment ........................................... 24-6
Type B - Type C Timer Pair (32-bit Timer)............. 12-17 Motor Control PWM Module .................................... 24-6
Type B Timer ........................................................... 12-4 Oscillator.................................................................. 24-6
Type C Timer ........................................................... 12-5 Connection Considerations............................................ 17-47
UART ....................................................................... 19-2 Connectivity Development Board .................................. 25-14
UART Receiver ...................................................... 19-16 Control Register Descriptions .......................................... 3-18
Index
Interrupts.................................................................. 13-9 Initiating and Terminating Data Transfer ................. 26-3
Control Bits ...................................................... 13-9 Interrupts ............................................................... 21-13
Operation in Power Saving States ......................... 13-10 Master Message Protocol States........................... 21-24
Overflow (ICOV)....................................................... 13-9 Module Operation during PWRSAV Instruction..... 21-49
Related Application Notes...................................... 13-13 Receiving Data from a Master Device ................... 21-37
Input Capture Event Modes ............................................. 13-4 Receiving Data from a Slave Device ..................... 21-19
Input Capture Registers ................................................... 13-3 Sending Data to a Master Device.......................... 21-44
Instruction Flow Types ..................................................... 2-27 Sending Data to a Slave Device............................ 21-17
Instruction Stall Cycles..................................................... 2-36 Start ......................................................................... 26-3
Internal Fast RC Oscillator (FRC) .................................... 7-31 Stop ......................................................................... 26-3
Internal Low Power RC (LPRC) Oscillator ....................... 7-32 I2C Module
Enabling ................................................................... 7-32 Multi-master Mode................................................. 21-29
Internal Voltage Reference ................................................ 9-3 Register Map ......................................................... 21-33
Interrupt Control and Status Registers............................. 6-14 10-bit Address Mode ............................................. 21-35
CORCON ................................................................. 6-14
IECx ......................................................................... 6-14 L
IFSx.......................................................................... 6-14 LAT (I/O Latch) Registers ................................................ 11-3
INTCON1, INTCON2 ............................................... 6-14 Loop Constructs .............................................................. 2-30
IPCx ......................................................................... 6-14 DO ........................................................................... 2-32
SR ............................................................................ 6-14 REPEAT .................................................................. 2-30
Interrupt Controller Low Power 32 kHz Crystal Oscillator............................... 7-31
Associated Special Function Registers.................... 6-43 Low Power 32 kHz Crystal Oscillator Input.................... 12-15
Interrupt Latency LP Oscillator
One-Cycle Instructions............................................. 6-11 Continuous Operation.............................................. 7-31
Two-Cycle Instructions............................................. 6-12 Enable ..................................................................... 7-31
Interrupt Operation ............................................................. 6-9 Intermittent Operation.............................................. 7-31
Nesting..................................................................... 6-10 Operation with Timer1 ............................................. 7-31
Return From Interrupt ................................................ 6-9 LVD
Interrupt Priority ................................................................. 6-5 Control Bits ................................................................ 9-3
Interrupt Processing Timing ............................................. 6-11 Current Consumption for Operation .......................... 9-5
Interrupt Setup Procedures .............................................. 6-42 Design Tips................................................................ 9-6
Initialization .............................................................. 6-42 Initialization Steps...................................................... 9-5
Interrupt Disable....................................................... 6-42 Operation................................................................... 9-5
Interrupt Service Routine ......................................... 6-42 Operation During Sleep and Idle Mode ..................... 9-5
Trap Service Routine ............................................... 6-42 Related Application Notes ......................................... 9-7
Interrupt Vector Table ........................................................ 6-2 Trip Point Selection ................................................... 9-3
Interrupts
Design Tips .............................................................. 6-44 M
Related Application Notes........................................ 6-45
Math Library..................................................................... 25-7
Revision History ....................................................... 6-46
Microchip Hardware and Language Tools ....................... 25-2
Interrupts Coincident with Power Save Instructions......... 10-5
Modes of Operation ......................................................... 14-4
Introduction
Compare Mode Output Driven High ........................ 14-5
Revision History ......................................................... 1-7
Compare Mode Output Driven Low ......................... 14-6
IWCOL ........................................................................... 21-22
Compare Mode Toggle Output ................................ 14-7
I2C
Dual Compare Match............................................... 14-9
Acknowledge Generation....................................... 21-21
Dual Compare, Continuous Output Pulses............ 14-14
Building Complete Master Messages .................... 21-24
Dual Compare, Generating Continuous Output Pulses
Bus Arbitration and Bus Collision........................... 21-30
Special Cases (table) .................................... 14-17
Bus Collision During a Repeated Start
Dual Compare, Single Output Pulse........................ 14-9
Condition........................................................ 21-31
Special Cases (table) .................................... 14-13
Bus Collision During a Start Condition................... 21-31
Single Compare Match ............................................ 14-4
Bus Collision During a Stop Condition ................... 21-31
Modulo Addressing ............................................................ 3-7
Bus Collision During Message Bit
Applicability.............................................................. 3-11
Transmission ................................................. 21-31
Calculation................................................................. 3-9
Bus Connection Considerations............................. 21-47
Initialization for Decrementing Buffer....................... 3-13
Communicating as a Master in a Multi-Master
Initialization for Incrementing Modulo Buffer ........... 3-12
Environment................................................... 21-29
Start and End Address Selection............................... 3-8
Communicating as a Slave .................................... 21-32
W Address Register Selection................................... 3-9
Detecting Bus Collisions and Resending
Messages ...................................................... 21-30
Detecting Start and Stop Conditions...................... 21-32
Detecting the Address............................................ 21-32
Enabling I/O ........................................................... 21-13
Modulo Start and End Address Selection Loss of Lock During Normal Device Operation........ 7-30
XMODEND Register ..................................................3-8 POR and Long Oscillator Start-up Times ........................ 8-12
XMODSRT Register................................................... 3-8 Port (I/O Port) Registers .................................................. 11-3
YMODEND Register ..................................................3-8 Power Saving Modes....................................................... 10-2
YMODSRT Register................................................... 3-8 Power-on Reset (POR)...................................................... 8-5
Motor Control Development Board................................. 25-13 Using ......................................................................... 8-7
MPLAB ICD 2 In-Circuit Debugger................................... 25-5 Power-up Timer (PWRT) ................................................... 8-7
MPLAB ICE 4000 In-Circuit Emulator .............................. 25-4 Prescaler Capture Events................................................ 13-6
MPLAB SIM Software Simulator ...................................... 25-3 Primary Oscillator ............................................................ 7-20
MPLAB 6.XX Integrated Development Environment PRO MATE II Universal Device Programmer .................. 25-5
Software ...................................................................25-2 Program Memory
Multi-Master Mode ......................................................... 21-29 Address Map ............................................................. 4-2
Multiplier........................................................................... 2-20 Counter ...................................................................... 4-4
Multiply Instructions.......................................................... 2-22 Data Access From ..................................................... 4-4
Data Storage ............................................................. 4-7
N High Word Access ..................................................... 4-7
Non-Maskable Traps.......................................................... 6-6 Low Word Access ...................................................... 4-6
Address Error ............................................................. 6-6 Program Space Visibility from Data Space................ 4-8
Arithmetic Error .......................................................... 6-6 Related Application Notes ....................................... 4-12
Oscillator Failure ........................................................ 6-6 Table Address Generation......................................... 4-6
Stack Error ................................................................. 6-6 Table Instruction Summary........................................ 4-5
Writes ............................................................. 4-10, 4-11
O Programmable Digital Noise Filters ................................. 16-9
Programmable Oscillator Postscaler ............................... 7-33
Oscillator Programmer’s Model .................................................. 2-3, 2-4
Configuration.............................................................. 7-6 Register Description .................................................. 2-4
Clock Switching Mode Configuration Bits ..........7-6 Protection Against Accidental Writes to OSCCON .......... 7-13
Design Tips .............................................................. 7-38 PSV Configuration ............................................................. 4-8
Related Application Notes........................................ 7-39 PSV Mapping with X and Y Data Spaces .................. 4-8
Resonator Start-up................................................... 7-22 Timing ...................................................................... 4-10
Revision History ....................................................... 7-40 Instruction Stalls .............................................. 4-10
System Features Summary ....................................... 7-2 Using PSV in a Repeat Loop........................... 4-10
Oscillator Control Register (OSCCON) ............................ 7-13 Pulse Width Modulation Mode ....................................... 14-18
Oscillator Mode Selection Guidelines .............................. 7-21 Duty Cycle ............................................................. 14-20
Oscillator Start-up From Sleep Mode............................... 7-23 Period .................................................................... 14-19
Oscillator Start-up Timer (OST) ....................................... 7-31 With Fault Protection Input Pin .............................. 14-19
Oscillator Switching Sequence......................................... 7-35 PWM Duty Cycle Comparison Units .............................. 15-20
OSEK Operating Systems..............................................25-10 PWM Fault Pins ............................................................. 15-34
Other dsPIC30F CPU Control Registers.......................... 2-16 PWM Output and Polarity Control.................................. 15-34
DISICNT...................................................................2-16 PWM Output Override ................................................... 15-31
MODCON................................................................. 2-16 PWM Special Event Trigger........................................... 15-38
PSVPAG .................................................................. 2-16 PWM Time Base............................................................ 15-16
TBLPAG ...................................................................2-16 PWM Update Lockout .................................................... 15-37
XBREV .....................................................................2-16
XMODSRT, XMODEND........................................... 2-16 Q
YMODSRT, YMODEND........................................... 2-16
Output Compare QEI Operation During Power Saving Modes ................. 16-19
Associated Register Map ....................................... 14-24 Quadrature Decoder ...................................................... 16-10
Design Tips ............................................................ 14-26 Quadrature Encoder Interface Interrupts ....................... 16-17
Related Application Notes...................................... 14-27
Revision History ..................................................... 14-28
R
Output Compare Operating in Power Saving States......14-23 R/W Bit.................................................................. 21-35, 26-4
Output Compare Operation in Power Saving States Read-After-Write Dependency Rules .............................. 2-36
Idle Mode ............................................................... 14-23 Reading A/D Result Buffer (12-bit) ................................ 18-27
Sleep Mode ............................................................ 14-23 Reading and Writing into 32-bit Timers ......................... 12-21
Output Compare Registers ..............................................14-3 Reading and Writing 16-bit Timer Module
Registers ............................................................... 12-15
P Real-Time Operating System (RTOS) ............................. 25-9
Peripheral Driver Library ..................................................25-8
Peripheral Module Disable (PMD) Registers ................... 10-9
Peripheral Multiplexing..................................................... 11-4
Peripherals Using Timer Modules .................................. 12-22
Phase Locked Loop (PLL)................................................7-30
Frequency Range .................................................... 7-30
Lock Status .............................................................. 7-30
Loss of Lock During a Power-on Reset ................... 7-30
Loss of Lock During Clock Switching ....................... 7-30
Index
ADCHS A/D Input Select ......................................... 17-9 CORCON (Core Control) ................................ 2-14, 6-15
ADCHS A/D Input Select (12-bit) ............................. 18-8 DCICON1 ................................................................ 22-3
ADCON1 (A/D Control) Register1........17-5, 18-5, 21-11 DCICON2 ................................................................ 22-4
ADCON1 A/D Control 1 ..................................17-5, 17-6 DCICON3 ................................................................ 22-5
ADCON1 A/D Control 1 (12-bit) ............................... 18-5 DCISTAT ................................................................. 22-6
ADCON2 (A/D Control) Register2...................17-7, 18-6 DFLTCON Digital Filter Control ...................... 16-7, 16-8
ADCON2 A/D Control 2 ........................................... 17-7 DTCON1 Dead Time Control 1................................ 15-9
ADCON2 A/D Control 2 (12-bit) ............................... 18-6 DTCON2 Dead Time Control 2.............................. 15-10
ADCON3 (A/D Control) Register3...................17-8, 18-7 FBORPOR (BOR and POR Configuration
ADCON3 A/D Control 3 ........................................... 17-8 Register) .......................................................... 24-4
ADCON3 A/D Control 3 (12-bit) ............................... 18-7 FBORPOR BOR and POR Device
ADPCFG (A/D Port Configuration) Configuration ................................................. 15-15
Register ................................................17-10, 18-9 FGS (General Code Segment Configuration
ADPCFG A/D Port Configuration ........................... 17-10 Register) .......................................................... 24-5
ADPCFG A/D Port Configuration (12-bit)................. 18-9 FLTACON Fault A Control..................................... 15-11
CiCFG1 (Baud Rate Configuration Register)......... 23-16 FLTBCON Fault B Control..................................... 15-12
CiCFG2 (Baud Rate Configuration Register 2)...... 23-17 FOSC (Oscillator Configuration
CiCTRL (CAN Module Control and Status Register) ............................................ 7-7, 7-9, 7-11
Register) .......................................................... 23-3 FWDT (Watchdog Timer Configuration
CiEC (Transmit/Receive Error Count).................... 23-18 Register) .......................................................... 24-3
CiINTE (Interrupt Enable Register) ........................ 23-19 ICxCON (Input Capture x Control)........................... 13-3
CiINTF (Interrupt Flag Register) ............................ 23-20 IEC0 (Interrupt Enable Control 0) ............................ 6-24
CiRXFnEIDH (Acceptance Filter n Extended IEC1 (Interrupt Enable Control 1) ............................ 6-26
Identifier High) ............................................... 23-12 IEC2 (Interrupt Enable Control 2) ................... 6-28, 6-29
CiRXFnEIDL (Acceptance Filter n Extended IFS0 (Interrupt Flag Status 0) .................................. 6-18
Identifier Low) ................................................ 23-13 IFS1 (Interrupt Flag Status 1) .................................. 6-20
CiRXMnEIDH (Acceptance Filter Mask n Extended IFS2 (Interrupt Flag Status 2) ......................... 6-22, 6-23
Identifier High) ............................................... 23-14 INTCON1 (Interrupt Control 1) ................................ 6-16
CiRXMnEIDL (Acceptance Filter Mask n Extended INTCON2 (Interrupt Control 2) ................................ 6-17
Identifier Low) ................................................ 23-15 IPC0 (Interrupt Priority Control 0) ............................ 6-30
CiRXMnSID (Acceptance Filter Mask n Standard IPC1 (Interrupt Priority Control 1) ............................ 6-31
Identifier) ........................................................ 23-14 IPC10 (Interrupt Priority Control 10) ........................ 6-40
CiRXnBm (Receive Buffer n Data Field IPC11 (Interrupt Priority Control 11) ........................ 6-41
Word m) ......................................................... 23-11 IPC2 (Interrupt Priority Control 2) ............................ 6-32
CiRXnDLC (Receive Buffer n Data Length IPC3 (Interrupt Priority Control 3) ............................ 6-33
Control) .......................................................... 23-11 IPC4 (Interrupt Priority Control 4) ............................ 6-34
CiRXnEID (Receive Buffer n Extended IPC5 (Interrupt Priority Control 5) ............................ 6-35
Identifier) ........................................................ 23-10 IPC6 (Interrupt Priority Control 6) ............................ 6-36
CiRXnSID (Receive Buffer n Standard IPC7 (Interrupt Priority Control 7) ............................ 6-37
Identifier) ........................................................ 23-10 IPC8 (Interrupt Priority Control 8) ............................ 6-38
CiRX0CON (Receive Buffer 0 Status and Control IPC9 (Interrupt Priority Control 9) ............................ 6-39
Register) .......................................................... 23-8 I2CSTAT (I2C Status) Register.......... 21-9, 21-10, 21-11
CiRX1CON (Receive Buffer 1 Status and Control MODCON (Modulo and Bit-Reversed Addressing
Register) .......................................................... 23-9 Control)............................................................ 3-19
CiRX1FnSID (Acceptance Filter n Standard NVMADR (Non-Volatile Memory Address) ................ 5-8
Identifier) ........................................................ 23-12 NVMADRU (Non-Volatile Memory Address) ............. 5-9
CiTXnBm (Transmit Buffer n Data Field NVMCON (Non-Volatile Memory Control) ................. 5-7
Word m) ........................................................... 23-7 NVMKEY (Non-Volatile Memory Key) ....................... 5-9
CiTXnCON (Transmit Buffer Status and Control OCxCON (Output Compare x Control) .................... 14-3
Register) .......................................................... 23-5 OVDCON Override Control ................................... 15-13
CiTXnDLC (Transmit Buffer n Data Length PDC1 PWM Duty Cycle 1...................................... 15-13
Control) ............................................................ 23-7 PDC2 PWM Duty Cycle 2...................................... 15-14
CiTXnEID PDC3 PWM Duty Cycle 3...................................... 15-14
(Transmit Buffer n Extended Identifier) ............ 23-6 PDC4 PWM Duty Cycle 4...................................... 15-15
CiTXnSID (Transmit Buffer n Standard PTCON PWM Time Base Control ........................... 15-5
Identifier) .......................................................... 23-6 PTMR PWM Time Base .......................................... 15-6
CNEN1 (Input Change Notification Interrupt PTPER PWM Time Base Period ............................. 15-6
Enable 1) ......................................................... 11-9 PWMCON1 PWM Control 1 .................................... 15-7
CNEN2 (Input Change Notification Interrupt PWMCON2 PWM Control 2 .................................... 15-8
Enable 2) ......................................................... 11-9 QEI Special Function............................................. 16-20
CNPU1 (Input Change Notification Pull-up QEICON QEI Control...................................... 16-5, 16-6
Enable 1) ....................................................... 11-10 RCON (Reset Control)........................................ 8-3, 9-4
RSCON.................................................................... 22-7
SEVTCMP Special Event Compare .........................15-7 W14 Stack Frame Pointer........................................ 2-10
SR (CPU Status) ...................................................... 2-12 Special Conditions for Interrupt Latency.......................... 6-13
SR (Status in CPU) ..................................................6-15 Special Features for Device Emulation.......................... 15-39
TSCON .................................................................... 22-7 Special Function Register Reset States .......................... 8-16
TxCON (Timer Control for Type A Time Base) ........12-6 Specifying How Conversion Results are Written Into
TxCON (Timer Control for Type B Time Base) ........12-7 Buffer ..................................................................... 17-30
TxCON (Timer Control for Type C Time Base) ........12-8 Specifying How Conversion Results are Written into
UxBRG (UARTx Baud Rate) .................................... 19-7 Buffer (12-bit)......................................................... 18-19
UxMODE (UARTx Mode) ......................................... 19-3 SSPOV .......................................................................... 21-19
UxRXREG (UARTx Receive) ................................... 19-6
UxSTA (UARTx Status and Control) ........................ 19-4 T
UxTXREG (UARTx Transmit - Write Only) .............. 19-6 Table Instruction Operation ............................................... 5-2
XBREV (X Write AGU Bit-Reversal Addressing
TCP/IP Protocol Stack ................................................... 25-10
Control) ............................................................ 3-22
Third Party C Compilers .................................................. 25-6
XMODEND (X AGU Modulo Addressing End) ......... 3-20
Third Party Hardware/Software Tools and Application
XMODSRT (X AGU Modulo Addressing Start) ........3-20
Libraries ................................................................... 25-6
YMODEND (Y AGU Modulo Addressing End) ......... 3-21
Time-base for Input Capture/Output Compare .............. 12-22
YMODSRT (Y AGU Modulo Addressing Start) ........3-21
Timer as an External Interrupt Pin ................................. 12-22
10-bit A/D Converter Special Function................... 17-56
Timer Interrupts ............................................................. 12-14
12-bit A/D Converter Special Function................... 18-34
Timer Modes of Operation ............................................... 12-9
6-Output PWM Module .......................................... 15-41
Synchronous Counter Using External Clock
8-Output PWM Module .......................................... 15-40
Input............................................................... 12-10
Reset
Timer Mode.............................................................. 12-9
Design Tips .............................................................. 8-17
Type A Timer Asynchronous Counter Mode Using
Illegal Opcode ............................................................ 8-9
External Clock Input ...................................... 12-11
Trap Conflict............................................................... 8-9
32-bit Timer............................................................ 12-18
Uninitialized W Register ............................................. 8-9
Timer Modules
Reset Sequence................................................................. 6-2
Associated Special Function Registers ................. 12-23
Returning From Interrupt..................................................6-13
Timer Operation in Power Saving States....................... 12-21
Round Logic .....................................................................2-25
Timer Operation Modes
Run-Time Self Programming (RTSP)............................... 5-10
Gated Time Accumulation ..................................... 12-12
FLASH Operations ................................................... 5-10
with Fast External Clock Source............................ 12-12
Operation ................................................................. 5-10
Timer Prescalers............................................................ 12-14
S Timer Selection................................................................ 13-4
Timer Variants ................................................................. 12-3
Saturation and Overflow Modes....................................... 2-24 Timers
Selecting A/D Conversion Clock .................................... 17-13 Design Tips............................................................ 12-24
Selecting Analog Inputs for Sampling ............................ 17-14 Related Application Notes ..................................... 12-25
Selecting Analog Inputs for Sampling (12-bit)................ 18-12 Revision History..................................................... 12-26
Selecting the A/D Conversion Clock (12-bit).................. 18-12 Timing Diagrams
Selecting the Voltage Reference Source .......................17-13 Brown-out Situations.................................................. 8-8
Selecting the Voltage Reference Source (12-bit)........... 18-11 Clock Transition ....................................................... 7-35
Setup for Continuous Output Pulse Generation............. 14-15 Clock/Instruction Cycle .............................................. 7-5
Shadow Registers .............................................................. 2-6 Data Space Access .......................................... 2-35, 3-6
DO Loop.....................................................................2-7 Dead Time ............................................................. 15-28
PUSH.S and POP.S................................................... 2-7 Device Reset Delay, Crystal + PLL Clock Source,
Simple Capture Events .................................................... 13-4 PWRT Disabled ............................................... 8-13
Sleep and Idle Modes Operation.................................... 17-55 Device Reset Delay, Crystal + PLL Clock Source,
Sleep and Idle Modes Operation (12-bit) .......................18-33 PWRT Enabled................................................ 8-14
Sleep Mode ...................................................................... 10-2 Device Reset Delay, EC + PLL Clock, PWRT
and FSCM Delay...................................................... 10-3 Enabled ........................................................... 8-15
Clock Selection on Wake-up from............................ 10-2 Device Reset Delay, EC or RC Clock, PWRT
Delay on Wake-up from ........................................... 10-3 Disabled........................................................... 8-16
Delay Times for Exit ................................................. 10-3 Dual Compare Mode.............................................. 14-10
Wake-up from on Interrupt ....................................... 10-4 Dual Compare Mode (Continuous Output Pulse,
Wake-up from on Reset ........................................... 10-4 PR2 = OCxRS) ................................... 14-14, 14-15
Wake-up from on Watchdog Time-out ..................... 10-4 Dual Compare Mode (Single Output Pulse,
Wake-up from with Crystal Oscillator or PLL ........... 10-3 OCxRS > PR2) .............................................. 14-10
Slow Oscillator Start-up.................................................... 10-3 Edge Detection Mode .............................................. 13-8
Soft Traps........................................................................... 6-6 Gated Timer Mode Operation ................................ 12-13
Arithmetic Error (Level 11) ......................................... 6-7 Interrupt Timing During a Two-Cycle Instruction ..... 6-12
Software Reset Instruction (SWR) ..................................... 8-7 Interrupt Timing for Timer Period Match ................ 12-14
Software Stack Interrupt Timing, Interrupt Occurs During 1st Cycle
Examples ................................................................... 2-9 of a Two-Cycle Instruction ............................... 6-12
Pointer........................................................................ 2-8 POR Module for Rising VDD ...................................... 8-6
Pointer Overflow ...................................................... 2-10 Postscaler Update ................................................... 7-34
Pointer Underflow .................................................... 2-10 PWM Output ............................................... 14-18, 14-21
Reception with Address Detect (ADDEN = 1)........ 19-19 Using Table Write Instructions........................................... 5-4
Return From Interrupt .............................................. 6-13 Byte Mode ................................................................. 5-5
Simple Capture Event, Time-base Holding Latches......................................................... 5-4
Prescaler = 1:1................................................. 13-5 Word Mode ................................................................ 5-4
Index
Simple Capture Event, Time-base Using the RCON Status Bits............................................ 8-10
Prescaler = 1:4................................................. 13-5
Single Compare Mode (Force OCx Low on Compare V
Match Event).................................................... 14-6 V.22/V.22bis and V.32 Specification.............................. 25-11
Single Compare Mode (Set OCx High on Compare
Match Event).................................................... 14-5 W
Single Compare Mode (Toggle Output on Compare
Match Event, PR2 = OCxR)............................. 14-7 Wake-up from Sleep and Idle .......................................... 6-10
Single Compare Mode (Toggle Output on Compare Watchdog Time-out Reset (WDTR)................................... 8-7
Match Event, PR2 > OCxR)............................. 14-7 Watchdog Timer .............................................................. 10-6
SPI Mode Timing (No SS Control) ..............20-12, 20-13 Enabling and Disabling............................................ 10-6
Transmission (Back to Back) ................................. 19-13 Operation................................................................. 10-7
Transmission (8-bit or 9-bit Data) .......................... 19-13 Operation in Sleep and Idle Modes ......................... 10-8
UART Reception .................................................... 19-17 Period Selection ...................................................... 10-7
UART Reception with Receive Overrun................. 19-17 Prescalers................................................................ 10-7
TRIS (Data Direction) Registers ...................................... 11-3 Resetting ................................................................. 10-8
Tuning the Oscillator Circuit ............................................. 7-23 Software Controlled ................................................. 10-6
Type A Timer ................................................................... 12-3 WCOL ...................................................... 21-18, 21-19, 21-21
Type B Timer ................................................................... 12-4 WDT and Power Saving Modes
Type C Timer ................................................................... 12-5 Design Tips............................................................ 10-10
Related Application Notes ..................................... 10-11
U Revision History..................................................... 10-12
Working Register Array...................................................... 2-6
UART W Register Memory Mapping .................................... 2-6
ADDEN Control Bit................................................. 19-18 W Registers and Byte Mode Instructions .................. 2-6
Alternate I/O Pins................................................... 19-10 W0 and File Register Instructions.............................. 2-6
Associated Registers ............................................. 19-22 Writing to Device Configuration Registers ....................... 5-14
Baud Rate Generator............................................... 19-8 Write Algorithm ........................................................ 5-14
Configuration.......................................................... 19-10
Control Registers ..................................................... 19-3 Z
Design Tips ............................................................ 19-23
Disabling ................................................................ 19-10 10-bit Address Mode...................................................... 21-35
Enabling ................................................................. 19-10 12-Bit A/D
Other Features....................................................... 19-21 ADCHS ........................................................... 17-4, 18-4
Auto Baud Support ........................................ 19-21 ADPCFG......................................................... 17-4, 18-4
Loopback Mode ............................................. 19-21 12-bit A/D
Operation During CPU Sleep and Operation During CPU Idle Mode............... 17-55, 18-33
Idle Modes .............................................. 19-21 Operation During CPU Sleep Mode ........... 17-55, 18-33
Receiver................................................................. 19-14 16-bit Up/Down Position Counter .................................. 16-12
Buffer (UxRXB) .............................................. 19-14 32-bit Timer Configuration ............................................. 12-16
Error Handling................................................ 19-14
Interrupt ......................................................... 19-15
Setup for Reception ....................................... 19-17
Related Application Notes...................................... 19-24
Setup for 9-bit Transmit ......................................... 19-18
Transmitter............................................................. 19-11
Buffer (UxTXB) .............................................. 19-12
Interrupt ......................................................... 19-12
Setup ............................................................. 19-13
Transmission of Break Characters ................ 19-14
Using for 9-bit Communication............................... 19-18
UART Autobaud Support ................................................. 13-9
Uninitialized W Register Reset .......................................... 2-7
USART
Initialization ............................................................ 19-20
Introduction .............................................................. 19-2
Receiving Break Characters .................................. 19-19
Revision History ..................................................... 19-25
Setup for 9-bit Reception Using Address Detect
Mode .............................................................. 19-19
Using QEI as Alternate 16-bit Timer/Counter ................ 16-16
Using Table Read Instructions ........................................... 5-3
Byte Mode.................................................................. 5-3
Word Mode ................................................................ 5-3
02/16/06