with the tool name, e.g. atmelice, samice, or edbg. Likewise,
replace interface with the used interface and the device with the full device name, e.g. atsam3s4c.
Invoking the above command should output information about the memory layout, the supply voltage for
the chip, and the fuse settings. If it fails it is likely a driver issue, which is covered by Driver and USB
Issues.
If atprogram is able to communicate with the device it means that the issue is most likely a wrong
version of JLinkArm.dll being loaded due to loader precedence. To check this, use the Procmon tool
to check what dll is being loaded.
Download the Procmon tool, open it, and configure the filter shown in the figure below. Then start Atmel
Studio. A couple of seconds after Atmel Studio has started, one line should become visible showing the
path to where the dll is being loaded from. It should be loaded from the atbackend folder inside the
Atmel Studio installation directory.
Atmel Atmel Studio [USER GUIDE]
Atmel-42167B-Atmel-Studio_User Guide-09/2016
270
Figure 11-2. Procmon Filter Configuration
If the path of the dll is different it means that Atmel Studio has picked up the wrong dll, and this dll is
incompatible with the dll shipped with Atmel Studio. An example of this is shown in the figure below.
Figure 11-3. Procmon Filter Configuration
To solve the above issue, we recommend backing up the dll that is being loaded and then replacing it with
the JLinkARM.dll found in the atbackend directory inside the Atmel Studio installation directory. This
can be done given the assumption that the dll bundled with Atmel Studio is newer than the one that is
being loaded, and the dll is backwards compatible.
Note: Remember to back up the offending JLinkARM.dll before replacing it, as it is not given that it
will be compatible with the program that deployed it.
Atmel Atmel Studio [USER GUIDE]
Atmel-42167B-Atmel-Studio_User Guide-09/2016
271
12. Document Revision History
Doc Rev. Date Comments
42167B 09/2016 Section "Power Debugger" is added
42167A 07/2016 Initial document release.
Atmel Atmel Studio [USER GUIDE]
Atmel-42167B-Atmel-Studio_User Guide-09/2016
272
Index
A
AsmToolchainOptions 3, 60
Atmel Studio 1
AVR Studio 1
C
Choose file 201
D
Device selection 26, 33
T
ToolchainOptions 5, 163, 173
Atmel Corporation 1600 Technology Drive, San Jose, CA 95110 USA T: (+1)(408) 441.0311 F: (+1)(408) 436.4200 | www.atmel.com
© 2016 Atmel Corporation. / Rev.: Atmel-42167B-Atmel-Studio_User Guide-09/2016
Atmel®
, Atmel logo and combinations thereof, Enabling Unlimited Possibilities®
, AVR®
, megaAVR®
, STK®
, tinyAVR®
, XMEGA®
, and others are registered trademarks
or trademarks of Atmel Corporation in U.S. and other countries. ARM®
, ARM Connected®
logo, Cortex®
, and others are the registered trademarks or trademarks of
ARM Ltd. Windows®
is a registered trademark of Microsoft Corporation in U.S. and or other countries. Other terms and product names may be trademarks of others.
DISCLAIMER: The information in this document is provided in connection with Atmel products. No license, express or implied, by estoppel or otherwise, to any
intellectual property right is granted by this document or in connection with the sale of Atmel products. EXCEPT AS SET FORTH IN THE ATMEL TERMS AND
CONDITIONS OF SALES LOCATED ON THE ATMEL WEBSITE, ATMEL ASSUMES NO LIABILITY WHATSOEVER AND DISCLAIMS ANY EXPRESS, IMPLIED
OR STATUTORY WARRANTY RELATING TO ITS PRODUCTS INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTY OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT,
CONSEQUENTIAL, PUNITIVE, SPECIAL OR INCIDENTAL DAMAGES (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS AND PROFITS, BUSINESS
INTERRUPTION, OR LOSS OF INFORMATION) ARISING OUT OF THE USE OR INABILITY TO USE THIS DOCUMENT, EVEN IF ATMEL HAS BEEN ADVISED
OF THE POSSIBILITY OF SUCH DAMAGES. Atmel makes no representations or warranties with respect to the accuracy or completeness of the contents of this
document and reserves the right to make changes to specifications and products descriptions at any time without notice. Atmel does not make any commitment to
update the information contained herein. Unless specifically provided otherwise, Atmel products are not suitable for, and shall not be used in, automotive
applications. Atmel products are not intended, authorized, or warranted for use as components in applications intended to support or sustain life.
SAFETY-CRITICAL, MILITARY, AND AUTOMOTIVE APPLICATIONS DISCLAIMER: Atmel products are not designed for and will not be used in connection with any
applications where the failure of such products would reasonably be expected to result in significant personal injury or death (“Safety-Critical Applications”) without
an Atmel officer's specific written consent. Safety-Critical Applications include, without limitation, life support devices and systems, equipment or systems for the
operation of nuclear facilities and weapons systems. Atmel products are not designed nor intended for use in military or aerospace applications or environments
unless specifically designated by Atmel as military-grade. Atmel products are not designed nor intended for use in automotive applications unless specifically
designated by Atmel as automotive-grade.
Atmel-8291C-AVR-XMEGA B -09/2014
This document contains complete and detailed description of all modules included in the
Atmel®AVR®XMEGA® B microcontroller family. The Atmel AVR XMEGA B is a family of lowpower,
high-performance, and peripheral-rich CMOS 8/16-bit microcontrollers based on the
AVR enhanced RISC architecture with integrated LCD controller. The available Atmel AVR
XMEGA B modules described in this manual are:
z Atmel AVR CPU
z Memories
z DMAC - Direct memory access controller
z Event system
z System clock and clock options
z Power management and sleep modes
z System control and reset
z WDT - Watchdog timer
z Interrupts and programmable multilevel interrupt controller
z PORT - I/O ports
z TC - 16-bit timer/counters
z AWeX - Advanced waveform extension
z Hi-Res - High resolution extension
z RTC - Real-time counter
z USB - Universal serial bus interface
z TWI - Two-wire serial interface
z SPI - Serial peripheral interface
z USART - Universal synchronous and asynchronous serial receiver and transmitter
z IRCOM - Infrared communication module
z AES and DES cryptographic engine
z CRC - Cyclic redundancy check
z LCD - Liquid Crystal Display controller
z ADC - Analog-to-digital converter
z AC - Analog comparator
z IEEE 1149.1 JTAG interface
z PDI - Program and debug interface
z Memory programming
z Peripheral address map
z Register summary
z Interrupt vector summary
z Instruction set summary
8-bit Atmel XMEGA B Microcontroller
XMEGA B MANUAL
XMEGA B [MANUAL] 2
Atmel-8291C-AVR-XMEGA B -09/2014
1. About the Manual
This document contains in-depth documentation of all peripherals and modules available for the Atmel AVR XMEGA B
microcontroller family. All features are documented on a functional level and described in a general sense. All peripherals
and modules described in this manual may not be present in all Atmel AVR XMEGA B devices.
For all device-specific information such as characterization data, memory sizes, modules, peripherals available and their
absolute memory addresses, refer to the device datasheets. When several instances of a peripheral exists in one device,
each instance will have a unique name. For example each port module (PORT) have unique name, such as PORTA,
PORTB, etc. Register and bit names are unique within one module instance.
For more details on applied use and code examples for peripherals and modules, refer to the Atmel AVR XMEGA
specific application notes available from http://www.atmel.com/avr.
1.1 Reading the Manual
The main sections describe the various modules and peripherals. Each section contains a short feature list and overview
describing the module. The remaining section describes the features and functions in more detail.
The register description sections list all registers and describe each register, bit and flag with their function. This includes
details on how to set up and enable various features in the module. When multiple bits are needed for a configuration
setting, these are grouped together in a bit group. The possible bit group configurations are listed for all bit groups
together with their associated Group Configuration and a short description. The Group Configuration refers to the defined
configuration name used in the Atmel AVR XMEGA assembler header files and application note source code.
The register summary sections list the internal register map for each module type.
The interrupt vector summary sections list the interrupt vectors and offset address for each module type.
1.2 Resources
A comprehensive set of development tools, application notes, and datasheets are available for download from
http://www.atmel.com/avr.
1.3 Recommended Reading
z Atmel AVR XMEGA B device datasheets
z AVR XMEGA application notes
This manual contains general modules and peripheral descriptions. The AVR XMEGA B device datasheets contains the
device-specific information. The XMEGA application notes and Atmel Software Framework contain example code and
show applied use of the modules and peripherals.
For new users, it is recommended to read the AVR1000 - Getting Started Writing C Code for Atmel XMEGA.
XMEGA B [MANUAL] 3
Atmel-8291C-AVR-XMEGA B -09/2014
2. Overview
The AVR XMEGA B microcontrollers is a family of low-power, high-performance, and peripheral-rich CMOS 8/16-bit
microcontrollers based on the AVR enhanced RISC architecture. By executing powerful instructions in a single clock
cycle, the Atmel AVR XMEGA B devices achieve throughputs approaching one million instructions per second (MIPS)
per megahertz, allowing the system designer to optimize power consumption versus processing speed.
The AVR CPU combines a rich instruction set with 32 general purpose working registers. All 32 registers are directly
connected to the arithmetic logic unit (ALU), allowing two independent registers to be accessed in a single instruction,
executed in one clock cycle. The resulting architecture is more code efficient while achieving throughputs many times
faster than conventional single-accumulator or CISC based microcontrollers.
The Atmel AVR XMEGA B devices provide the following features: in-system programmable flash with read-while-write
capabilities; internal EEPROM and SRAM; two-channel DMA controller; four-channel event system and programmable
multilevel interrupt controller; up to 53 general purpose I/O lines; 16-bit real-time counter (RTC); up to three flexible 16-bit
timer/counters with capture, compare and PWM modes; up to two USARTs; one I2
C and SMBUS compatible two-wire
serial interface (TWI); one full-speed USB 2.0 interface; one serial peripheral interface (SPI); one LCD controller
supporting display capacity up to 4 Common and up to 40 Segment terminals; CRC module; AES and DES cryptographic
engine; up to two 8-channel, 12-bit ADCs with programmable gain; up to four analog comparators with window mode;
programmable watchdog timer with separate internal oscillator; accurate internal oscillators with PLL and prescaler; and
programmable brown-out detection.
The program and debug interface (PDI), a fast, two-pin interface for programming and debugging, is available. Selected
devices also have an IEEE std. 1149.1 compliant JTAG interface, and this can also be used for on-chip debug and
programming.
The Atmel AVR XMEGA devices have five software selectable power saving modes. The idle mode stops the CPU while
allowing the SRAM, DMA controller, event system, interrupt controller, and all peripherals to continue functioning. The
power-down mode saves the SRAM and register contents, but stops the oscillators, disabling all other functions until the
next TWI, USB resume, or pin-change interrupt, or reset. In power-save mode, the asynchronous real-time counter
continues to run, allowing the application to maintain a timer base while the rest of the device is sleeping. In this mode,
the LCD controller is allowed to refresh data to the panel. In standby mode, the external crystal oscillator keeps running
while the rest of the device is sleeping. This allows very fast startup from the external crystal, combined with low power
consumption. In extended standby mode, both the main oscillator and the asynchronous timer continue to run. In this
mode, the LCD controller is allowed to refresh data to the panel. To further reduce power consumption, the peripheral
clock to each individual peripheral can optionally be stopped in active mode and idle sleep mode.
The devices are manufactured using Atmel high-density, nonvolatile memory technology. The program flash memory can
be reprogrammed in-system through the PDI or JTAG interfaces. A boot loader running in the device can use any
interface to download the application program to the flash memory. The boot loader software in the boot flash section will
continue to run while the application flash section is updated, providing true read-while-write operation. By combining an
8/16-bit RISC CPU with In-system, self-programmable flash, the Atmel AVR XMEGA is a powerful microcontroller family
that provides a highly flexible and cost effective solution for many embedded applications.
The Atmel AVR XMEGA B devices are supported with a full suite of program and system development tools, including C
compilers, macro assemblers, program debugger/simulators, programmers, and evaluation kits.
XMEGA B [MANUAL] 4
Atmel-8291C-AVR-XMEGA B -09/2014
Figure 2-1. Atmel AVR XMEGA B block diagram.
In Table 2-1 on page 5 a feature summary for the XMEGA B family is shown, split into one feature summary column for
each sub-family. Each sub-family has identical feature set, but different memory options, refer to their device datasheet
for ordering codes and memory options.
Power
Supervision
POR/BOD &
RESET
PORT A (8)
PORT B (8)
EVENT ROUTING NETWORK
DMA
Controller
BUS Matrix
SRAM
ADCA
ACA
ADCB
ACB
OCD
PORT M (8)
PDI
SEG[31..24] /
PM[0..7]
SEG[0..23]
COM[0..3]
PA[0..7]
PB[0..7]/
JTAG
Watchdog
Timer
Watchdog
Oscillator
Interrupt
Controller
DATA BUS
Prog/Debug
Controller
VCC
GND
PORT R (2)
PR[0..1]
Oscillator
Control
Real Time
Counter
Event System
Controller
JTAG
PDI_DATA
RESET /
PDI_CLK
PORT B
Sleep
Controller
DES
CRC
IRCOM
PORT G (8) SEG[39..32] /
PG[0..7]
LCD POWER[0..4]
PORT C (8)
PC[0..7] TCC0:1 USARTC0 SPIC
TWIC
PD[0..2] PE[0..7]
PORT D (3)
TCE0
USARTE0
PORT E (8)
USB
EVENT ROUTING NETWORK
AES Int. Refs.
AREFA
AREFB
Tempref
VCC/10
CPU
NVM Controller
Flash EEPROM
DATA BUS
LCD
TOSC1
TOSC2
To Clock
Generator
XTAL2 /
TOSC2
XTAL1 /
TOSC1
Oscillator
Circuits/
Clock
Generation
(Alternate)
Digital function
Analog function / Oscillators
Programming, debug, test
External clock / Crystal pins
General Purpose I/O
Ground
Power LCD
XMEGA B [MANUAL] 5
Atmel-8291C-AVR-XMEGA B -09/2014
Table 2-1. XMEGA B feature summary overview.
Feature Details / sub-family B1 B3
Pins, I/O
Total 100 64
Programmable I/O pins 53 36
Memory
Program memory (KB) 64 - 128 64 - 128
Boot memory (KB) 4 - 8 4 - 8
SRAM (KB) 4 - 8 4 - 8
EEPROM 2 2 - 4
General purpose registers 16 16
Package
TQFP 100A 64A
QFN /VQFN – 64M2
BGA 100C1/100C2 –
QTouch Sense channels 56 56
DMA Controller Channels 2 2
Event System
Channels 4 4
QDEC 1 1
Crystal Oscillator
0.4 - 16MHz XOSC Yes Yes
32.768 kHz TOSC Yes Yes
Internal Oscillator
2MHz calibrated Yes Yes
32MHz calibrated Yes Yes
128MHz PLL Yes Yes
32.768kHz calibrated Yes Yes
32kHz ULP Yes Yes
Timer / Counter
TC0 - 16-bit, 4 CC 2 1
TC1 - 16-bit, 2 CC 1 1
TC2 - 2x 8-bit 2 1
Hi-Res 1 1
AWeX 1 1
RTC 1 1
RTC32
Serial Communication
USB full-speed device 1 1
USART 2 1
SPI 1 1
TWI 1 1
XMEGA B [MANUAL] 6
Atmel-8291C-AVR-XMEGA B -09/2014
Crypto /CRC
AES-128 Yes Yes
DES Yes Yes
CRC-16 Yes Yes
CRC-32 Yes Yes
Liquid Crystal Display
Controller (LCD)
Segments 40 25
Common terminals 4 4
Analog to Digital Converter
(ADC)
2 1
Resolution (bits) 12 12
Sampling speed (kbps) 300 300
Input channels per ADC 16 8
Conversion channels 1 1
Analog Comparator (AC) 4 2
Program and Debug Interface
PDI Yes Yes
JTAG Yes Yes
Boundary scan Yes Yes
Feature Details / sub-family B1 B3
XMEGA B [MANUAL] 7
Atmel-8291C-AVR-XMEGA B -09/2014
3. Atmel AVR CPU
3.1 Features
z 8/16-bit, high-performance Atmel AVR RISC CPU
z 142 instructions
z Hardware multiplier
z 32x8-bit registers directly connected to the ALU
z Stack in RAM
z Stack pointer accessible in I/O memory space
z Direct addressing of up to 16MB of program memory and 16MB of data memory
z True 16/24-bit access to 16/24-bit I/O registers
z Efficient support for 8-, 16-, and 32-bit arithmetic
z Configuration change protection of system-critical features
3.2 Overview
All Atmel AVR XMEGA devices use the 8/16-bit AVR CPU. The main function of the CPU is to execute the code and
perform all calculations. The CPU is able to access memories, perform calculations, control peripherals, and execute the
program in the flash memory. Interrupt handling is described in a separate section, “Interrupts and Programmable
Multilevel Interrupt Controller” on page 115.
3.3 Architectural Overview
In order to maximize performance and parallelism, the AVR CPU uses a Harvard architecture with separate memories
and buses for program and data. Instructions in the program memory are executed with single-level pipelining. While one
instruction is being executed, the next instruction is pre-fetched from the program memory. This enables instructions to
be executed on every clock cycle. For a summary of all AVR instructions, refer to “Instruction Set Summary” on page
395. For details of all AVR instructions, refer to http://www.atmel.com/avr.
Figure 3-1. Block diagram of the AVR CPU architecture.
XMEGA B [MANUAL] 8
Atmel-8291C-AVR-XMEGA B -09/2014
The arithmetic logic unit (ALU) supports arithmetic and logic operations between registers or between a constant and a
register. Single-register operations can also be executed in the ALU. After an arithmetic operation, the status register is
updated to reflect information about the result of the operation.
The ALU is directly connected to the fast-access register file. The 32 x 8-bit general purpose working registers all have
single clock cycle access time allowing single-cycle arithmetic logic unit operation between registers or between a
register and an immediate. Six of the 32 registers can be used as three 16-bit address pointers for program and data
space addressing, enabling efficient address calculations.
The memory spaces are linear. The data memory space and the program memory space are two different memory
spaces.
The data memory space is divided into I/O registers, SRAM, and external RAM. In addition, the EEPROM can be
memory mapped in the data memory.
All I/O status and control registers reside in the lowest 4KB addresses of the data memory. This is referred to as the I/O
memory space. The lowest 64 addresses can be accessed directly, or as the data space locations from 0x00 to 0x3F.
The rest is the extended I/O memory space, ranging from 0x0040 to 0x0FFF. I/O registers here must be accessed as
data space locations using load (LD/LDS/LDD) and store (ST/STS/STD) instructions.
The SRAM holds data. Code execution from SRAM is not supported. It can easily be accessed through the five different
addressing modes supported in the AVR architecture. The first SRAM address is 0x2000.
Data addresses 0x1000 to 0x1FFF are reserved for memory mapping of EEPROM.
The program memory is divided in two sections, the application program section and the boot program section. Both
sections have dedicated lock bits for write and read/write protection. The SPM instruction that is used for selfprogramming
of the application flash memory must reside in the boot program section. The application section contains
an application table section with separate lock bits for write and read/write protection. The application table section can
be used for save storing of nonvolatile data in the program memory.
3.4 ALU - Arithmetic Logic Unit
The arithmetic logic unit supports arithmetic and logic operations between registers or between a constant and a register.
Single-register operations can also be executed. The ALU operates in direct connection with all 32 general purpose
registers. In a single clock cycle, arithmetic operations between general purpose registers or between a register and an
immediate are executed and the result is stored in the register file. After an arithmetic or logic operation, the status
register is updated to reflect information about the result of the operation.
ALU operations are divided into three main categories – arithmetic, logical, and bit functions. Both 8- and 16-bit
arithmetic is supported, and the instruction set allows for efficient implementation of 32-bit arithmetic. The hardware
multiplier supports signed and unsigned multiplication and fractional format.
3.4.1 Hardware Multiplier
The multiplier is capable of multiplying two 8-bit numbers into a 16-bit result. The hardware multiplier supports different
variations of signed and unsigned integer and fractional numbers:
z Multiplication of unsigned integers
z Multiplication of signed integers
z Multiplication of a signed integer with an unsigned integer
z Multiplication of unsigned fractional numbers
z Multiplication of signed fractional numbers
z Multiplication of a signed fractional number with an unsigned one
A multiplication takes two CPU clock cycles.
XMEGA B [MANUAL] 9
Atmel-8291C-AVR-XMEGA B -09/2014
3.5 Program Flow
After reset, the CPU starts to execute instructions from the lowest address in the flash program memory ‘0.’ The program
counter (PC) addresses the next instruction to be fetched.
Program flow is provided by conditional and unconditional jump and call instructions capable of addressing the whole
address space directly. Most AVR instructions use a 16-bit word format, while a limited number use a 32-bit format.
During interrupts and subroutine calls, the return address PC is stored on the stack. The stack is allocated in the general
data SRAM, and consequently the stack size is only limited by the total SRAM size and the usage of the SRAM. After
reset, the stack pointer (SP) points to the highest address in the internal SRAM. The SP is read/write accessible in the
I/O memory space, enabling easy implementation of multiple stacks or stack areas. The data SRAM can easily be
accessed through the five different addressing modes supported in the AVR CPU.
3.6 Instruction Execution Timing
The AVR CPU is clocked by the CPU clock, clkCPU. No internal clock division is used. Figure 3-2 on page 9 shows the
parallel instruction fetches and instruction executions enabled by the Harvard architecture and the fast-access register
file concept. This is the basic pipelining concept used to obtain up to 1MIPS/MHz performance with high power efficiency.
Figure 3-2. The parallel instruction fetches and instruction executions.
Figure 3-3 on page 9 shows the internal timing concept for the register file. In a single clock cycle, an ALU operation
using two register operands is executed and the result is stored back to the destination register.
Figure 3-3. Single Cycle ALU Operation
clk
1st Instruction Fetch
1st Instruction Execute
2nd Instruction Fetch
2nd Instruction Execute
3rd Instruction Fetch
3rd Instruction Execute
4th Instruction Fetch
T1 T2 T3 T4
CPU
Total Execution Time
Register Operands Fetch
ALU Operation Execute
Result Write Back
T1 T2 T3 T4
clkCPU
XMEGA B [MANUAL] 10
Atmel-8291C-AVR-XMEGA B -09/2014
3.7 Status Register
The status register (SREG) contains information about the result of the most recently executed arithmetic or logic
instruction. This information can be used for altering program flow in order to perform conditional operations. Note that
the status register is updated after all ALU operations, as specified in the instruction set reference. This will in many
cases remove the need for using the dedicated compare instructions, resulting in faster and more compact code.
The status register is not automatically stored when entering an interrupt routine nor restored when returning from an
interrupt. This must be handled by software.
The status register is accessible in the I/O memory space.
3.8 Stack and Stack Pointer
The stack is used for storing return addresses after interrupts and subroutine calls. It can also be used for storing
temporary data. The stack pointer (SP) register always points to the top of the stack. It is implemented as two 8-bit
registers that are accessible in the I/O memory space. Data are pushed and popped from the stack using the PUSH and
POP instructions. The stack grows from a higher memory location to a lower memory location. This implies that pushing
data onto the stack decreases the SP, and popping data off the stack increases the SP. The SP is automatically loaded
after reset, and the initial value is the highest address of the internal SRAM. If the SP is changed, it must be set to point
above address 0x2000, and it must be defined before any subroutine calls are executed or before interrupts are enabled.
During interrupts or subroutine calls, the return address is automatically pushed on the stack. The return address can be
two or three bytes, depending on program memory size of the device. For devices with 128KB or less of program
memory, the return address is two bytes, and hence the stack pointer is decremented/incremented by two. For devices
with more than 128KB of program memory, the return address is three bytes, and hence the SP is
decremented/incremented by three. The return address is popped off the stack when returning from interrupts using the
RETI instruction, and from subroutine calls using the RET instruction.
The SP is decremented by one when data are pushed on the stack with the PUSH instruction, and incremented by one
when data is popped off the stack using the POP instruction.
To prevent corruption when updating the stack pointer from software, a write to SPL will automatically disable interrupts
for up to four instructions or until the next I/O memory write.
3.9 Register File
The register file consists of 32 x 8-bit general purpose working registers with single clock cycle access time. The register
file supports the following input/output schemes:
z One 8-bit output operand and one 8-bit result input
z Two 8-bit output operands and one 8-bit result input
z Two 8-bit output operands and one 16-bit result input
z One 16-bit output operand and one 16-bit result input
Six of the 32 registers can be used as three 16-bit address register pointers for data space addressing, enabling efficient
address calculations. One of these address pointers can also be used as an address pointer for lookup tables in flash
program memory.
XMEGA B [MANUAL] 11
Atmel-8291C-AVR-XMEGA B -09/2014
Figure 3-4. AVR CPU general purpose working registers.
The register file is located in a separate address space, and so the registers are not accessible as data memory.
3.9.1 The X-, Y-, and Z- Registers
Registers R26..R31 have added functions besides their general-purpose usage.
These registers can form 16-bit address pointers for addressing data memory. These three address registers are called
the X-register, Y-register, and Z-register. The Z-register can also be used as an address pointer to read from and/or write
to the flash program memory, signature rows, fuses, and lock bits.
Figure 3-5. The X-, Y- and Z-registers.
7 0 Addr.
R0 0x00
R1 0x01
R2 0x02
…
R13 0x0D
General R14 0x0E
Purpose R15 0x0F
Working R16 0x10
Registers R17 0x11
…
R26 0x1A X-register Low Byte
R27 0x1B X-register High Byte
R28 0x1C Y-register Low Byte
R29 0x1D Y-register High Byte
R30 0x1E Z-register Low Byte
R31 0x1F Z-register High Byte
Bit (individually) 7 R27 0 7 R26 0
X-register XH XL
Bit (X-register) 15 8 7 0
Bit (individually) 7 R29 0 7 R28 0
Y-register YH YL
Bit (Y-register) 15 8 7 0
Bit (individually) 7 R31 0 7 R30 0
Z-register ZH ZL
Bit (Z-register) 15 8 7 0
XMEGA B [MANUAL] 12
Atmel-8291C-AVR-XMEGA B -09/2014
The lowest register address holds the least-significant byte (LSB), and the highest register address holds the mostsignificant
byte (MSB). In the different addressing modes, these address registers function as fixed displacement,
automatic increment, and automatic decrement (see the instruction set reference for details).
3.10 RAMP and Extended Indirect Registers
In order to access program memory or data memory above 64KB, the address pointer must be larger than 16 bits. This is
done by concatenating one register to one of the X-, Y-, or Z-registers. This register then holds the most-significant byte
(MSB) in a 24-bit address or address pointer.
These registers are available only on devices with external bus interface and/or more than 64KB of program or data
memory space. For these devices, only the number of bits required to address the whole program and data memory
space in the device is implemented in the registers.
3.10.1 RAMPX, RAMPY and RAMPZ Registers
The RAMPX, RAMPY and RAMPZ registers are concatenated with the X-, Y-, and Z-registers, respectively, to enable
indirect addressing of the whole data memory space above 64KB and up to 16MB.
Figure 3-6. The combined RAMPX + X, RAMPY + Y and RAMPZ + Z registers.
When reading (ELPM) and writing (SPM) program memory locations above the first 128KB of the program memory,
RAMPZ is concatenated with the Z-register to form the 24-bit address. LPM is not affected by the RAMPZ setting.
3.10.2 RAMPD Register
This register is concatenated with the operand to enable direct addressing of the whole data memory space above 64KB.
Together, RAMPD and the operand will form a 24-bit address.
Figure 3-7. The combined RAMPD + K register.
Bit (Individually) 7 0 7 0 7 0
RAMPX XH XL
Bit (X-pointer) 23 16 15 8 7 0
Bit (Individually) 7 0 7 0 7 0
RAMPY YH YL
Bit (Y-pointer) 23 16 15 8 7 0
Bit (Individually) 7 0 7 0 7 0
RAMPZ ZH ZL
Bit (Z-pointer) 23 16 15 8 7 0
Bit (Individually) 7 0 15 0
RAMPD K
Bit (D-pointer) 23 16 15 0
XMEGA B [MANUAL] 13
Atmel-8291C-AVR-XMEGA B -09/2014
3.10.3 EIND - Extended Indirect Register
EIND is concatenated with the Z-register to enable indirect jump and call to locations above the first 128KB (64K words)
of the program memory.
Figure 3-8. The combined EIND + Z register.
3.11 Accessing 16-bit Registers
The AVR data bus is 8 bits wide, and so accessing 16-bit registers requires atomic operations. These registers must be
byte-accessed using two read or write operations. 16-bit registers are connected to the 8-bit bus and a temporary register
using a 16-bit bus.
For a write operation, the low byte of the 16-bit register must be written before the high byte. The low byte is then written
into the temporary register. When the high byte of the 16-bit register is written, the temporary register is copied into the
low byte of the 16-bit register in the same clock cycle.
For a read operation, the low byte of the 16-bit register must be read before the high byte. When the low byte register is
read by the CPU, the high byte of the 16-bit register is copied into the temporary register in the same clock cycle as the
low byte is read. When the high byte is read, it is then read from the temporary register.
This ensures that the low and high bytes of 16-bit registers are always accessed simultaneously when reading or writing
the register.
Interrupts can corrupt the timed sequence if an interrupt is triggered and accesses the same 16-bit register during an
atomic 16-bit read/write operation. To prevent this, interrupts can be disabled when writing or reading 16-bit registers.
The temporary registers can also be read and written directly from user software.
3.11.1 Accessing 24- and 32-bit Registers
For 24- and 32-bit registers, the read and write access is done in the same way as described for 16-bit registers, except
there are two temporary registers for 24-bit registers and three for 32-bit registers. The least-significant byte must be
written first when doing a write, and read first when doing a read.
3.12 Configuration Change Protection
System critical I/O register settings are protected from accidental modification. The SPM instruction is protected from
accidental execution, and the LPM instruction is protected when reading the fuses and signature row. This is handled
globally by the configuration change protection (CCP) register. Changes to the protected I/O registers or bits, or
execution of protected instructions, are only possible after the CPU writes a signature to the CCP register. The different
signatures are described in the register description.
There are two modes of operation: one for protected I/O registers, and one for the protected instructions, SPM/LPM.
3.12.1 Sequence for write operation to protected I/O registers
1. The application code writes the signature that enable change of protected I/O registers to the CCP register.
2. Within four instruction cycles, the application code must write the appropriate data to the protected register. Most
protected registers also contain a write enable/change enable bit. This bit must be written to one in the same operation
as the data are written. The protected change is immediately disabled if the CPU performs write operations to
the I/O register or data memory or if the SPM, LPM, or SLEEP instruction is executed.
Bit (Individually) 7 0 7 0 7 0
EIND ZH ZL
Bit (D-pointer) 23 16 15 8 7 0
XMEGA B [MANUAL] 14
Atmel-8291C-AVR-XMEGA B -09/2014
3.12.2 Sequence for execution of protected SPM/LPM
1. The application code writes the signature for the execution of protected SPM/LPM to the CCP register.
2. Within four instruction cycles, the application code must execute the appropriate instruction. The protected change
is immediately disabled if the CPU performs write operations to the data memory or if the SLEEP instruction is
executed.
Once the correct signature is written by the CPU, interrupts will be ignored for the duration of the configuration change
enable period. Any interrupt request (including non-maskable interrupts) during the CCP period will set the
corresponding interrupt flag as normal, and the request is kept pending. After the CCP period is completed, any pending
interrupts are executed according to their level and priority. DMA requests are still handled, but do not influence the
protected configuration change enable period. A signature written by DMA is ignored.
3.13 Fuse Lock
For some system-critical features, it is possible to program a fuse to disable all changes to the associated I/O control
registers. If this is done, it will not be possible to change the registers from the user software, and the fuse can only be
reprogrammed using an external programmer. Details on this are described in the datasheet module where this feature is
available.
XMEGA B [MANUAL] 15
Atmel-8291C-AVR-XMEGA B -09/2014
3.14 Register Descriptions
3.14.1 CCP – Configuration Change Protection register
z Bit 7:0 – CCP[7:0]: Configuration Change Protection
The CCP register must be written with the correct signature to enable change of the protected I/O register or execution of
the protected instruction for a maximum period of four CPU instruction cycles. All interrupts are ignored during these
cycles. After these cycles, interrupts will automatically be handled again by the CPU, and any pending interrupts will be
executed according to their level and priority. When the protected I/O register signature is written, CCP[0] will read as
one as long as the protected feature is enabled. Similarly when the protected SPM/LPM signature is written, CCP[1] will
read as one as long as the protected feature is enabled. CCP[7:2] will always read as zero. Table 3-1 shows the
signature for the various modes.
Table 3-1. Modes of CPU change protection.
3.14.2 RAMPD – Extended Direct Addressing register
This register is concatenated with the operand for direct addressing (LDS/STS) of the whole data memory space on
devices with more than 64KB of data memory. This register is not available if the data memory, including external
memory, is less than 64KB.
z Bit 7:0 – RAMPD[7:0]: Extended Direct Addressing bits
These bits hold the MSB of the 24-bit address created by RAMPD and the 16-bit operand. Only the number of bits
required to address the available data memory is implemented for each device. Unused bits will always read as zero.
Bit 7 6 5 4 3 2 1 0
+0x04 CCP[7:0]
Read/Write W W W W W W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Signature Group Configuration Description
0x9D SPM Protected SPM/LPM
0xD8 IOREG Protected IO register
Bit 7 6 5 4 3 2 1 0
+0x08 RAMPD[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 16
Atmel-8291C-AVR-XMEGA B -09/2014
3.14.3 RAMPX – Extended X-Pointer register
This register is concatenated with the X-register for indirect addressing (LD/LDD/ST/STD) of the whole data memory
space on devices with more than 64KB of data memory. This register is not available if the data memory, including
external memory, is less than 64KB.
z Bit 7:0 – RAMPX[7:0]: Extended X-pointer Address bits
These bits hold the MSB of the 24-bit address created by RAMPX and the 16-bit X-register. Only the number of bits
required to address the available data memory is implemented for each device. Unused bits will always read as zero.
3.14.4 RAMPY – Extended Y-Pointer register
This register is concatenated with the Y-register for indirect addressing (LD/LDD/ST/STD) of the whole data memory
space on devices with more than 64KB of data memory. This register is not available if the data memory, including
external memory, is less than 64KB.
z Bit 7:0 – RAMPY[7:0]: Extended Y-pointer Address bits
These bits hold the MSB of the 24-bit address created by RAMPY and the 16-bit Y-register. Only the number of bits
required to address the available data memory is implemented for each device. Unused bits will always read as zero.
3.14.5 RAMPZ – Extended Z-Pointer register
This register is concatenated with the Z-register for indirect addressing (LD/LDD/ST/STD) of the whole data memory
space on devices with more than 64KB of data memory. RAMPZ is concatenated with the Z-register when reading
(ELPM) program memory locations above the first 64KB and writing (SPM) program memory locations above the first
128KB of the program memory.
This register is not available if the data memory, including external memory and program memory in the device, is less
than 64KB.
z Bit 7:0 – RAMPZ[7:0]: Extended Z-pointer Address bits
These bits hold the MSB of the 24-bit address created by RAMPZ and the 16-bit Z-register. Only the number of bits
required to address the available data and program memory is implemented for each device. Unused bits will always
read as zero.
Bit 7 6 5 4 3 2 1 0
+0x09 RAMPX[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
+0x0A RAMPY[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 000000
Bit 7 6 5 4 3 2 1 0
+0x0B RAMPZ[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 00000000
XMEGA B [MANUAL] 17
Atmel-8291C-AVR-XMEGA B -09/2014
3.14.6 EIND – Extended Indirect register
This register is concatenated with the Z-register for enabling extended indirect jump (EIJMP) and call (EICALL) to the
whole program memory space on devices with more than 128KB of program memory. The register should be used for
jumps to addresses below 128KB if ECALL/EIJMP are used, and it will not be used if CALL and IJMP commands are
used. For jump or call to addresses below 128KB, this register is not used. This register is not available if the program
memory in the device is less than 128KB.
z Bit 7:0 – EIND[7:0]: Extended Indirect Address bits
These bits hold the MSB of the 24-bit address created by EIND and the 16-bit Z-register. Only the number of bits
required to access the available program memory is implemented for each device. Unused bits will always read as zero.
3.14.7 SPL – Stack Pointer Register Low
The SPH and SPL register pair represent the 16-bit SP value. The SP holds the stack pointer that points to the top of the
stack. After reset, the stack pointer points to the highest internal SRAM address. To prevent corruption when updating
the stack pointer from software, a write to SPL will automatically disable interrupts for the next four instructions or until
the next I/O memory write.
Only the number of bits required to address the available data memory, including external memory, up to 64KB is
implemented for each device. Unused bits will always read as zero.
Note: 1. Refer to specific device datasheets for exact initial values.
z Bit 7:0 – SP[7:0]: Stack Pointer Register Low
These bits hold the LSB of the 16-bit stack pointer (SP).
3.14.8 SPH – Stack Pointer Register High
Note: 1. Refer to specific device datasheets for exact initial values.
z Bit 7:0 – SP[15:8]: Stack Pointer Register High
These bits hold the MSB of the 16-bit stack pointer (SP).
Bit 7 6 5 4 3 2 1 0
+0x0C EIND[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
+0x0D SP[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value(1) 0/1 0/1 0/1 0/1 0/1 0/1 0/1 0/1
Bit 7 6 5 4 3 2 1 0
+0x0E SP[15:8]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value(1) 0/1 0/1 0/1 0/1 0/1 0/1 0/1 0/1
XMEGA B [MANUAL] 18
Atmel-8291C-AVR-XMEGA B -09/2014
3.14.9 SREG – Status Register
The status register (SREG) contains information about the result of the most recently executed arithmetic or logic
instruction.
z Bit 7 – I: Global Interrupt Enable
The global interrupt enable bit must be set for interrupts to be enabled. If the global interrupt enable register is cleared,
none of the interrupts are enabled independent of the individual interrupt enable settings. This bit is not cleared by
hardware after an interrupt has occurred. This bit can be set and cleared by the application with the SEI and CLI
instructions, as described in “Instruction Set Description.” Changing the I flag through the I/O-register result in a onecycle
wait state on the access.
z Bit 6 – T: Bit Copy Storage
The bit copy instructions bit load (BLD) and bit store (BST) use the T bit as source or destination for the operated bit. A bit
from a register in the register file can be copied into this bit by the BST instruction, and this bit can be copied into a bit in
a register in the register file by the BLD instruction.
z Bit 5 – H: Half Carry Flag
The half carry flag (H) indicates a half carry in some arithmetic operations. Half carry Is useful in BCD arithmetic. See
“Instruction Set Description” for detailed information.
z Bit 4 – S: Sign Bit, S = N ⊕ V
The sign bit is always an exclusive or between the negative flag, N, and the two’s complement overflow flag, V. See
“Instruction Set Description” for detailed information.
z Bit 3 – V: Two’s Complement Overflow Flag
The two’s complement overflow flag (V) supports two’s complement arithmetic. See “Instruction Set Description” for
detailed information.
z Bit 2 – N: Negative Flag
The negative flag (N) indicates a negative result in an arithmetic or logic operation. See “Instruction Set Description” for
detailed information.
z Bit 1 – Z: Zero Flag
The zero flag (Z) indicates a zero result in an arithmetic or logic operation. See “Instruction Set Description” for detailed
information.
z Bit 0 – C: Carry Flag
The carry flag (C) indicates a carry in an arithmetic or logic operation. See “Instruction Set Description” for detailed
information.
Bit 7 6 5 4 3 2 1 0
+0x0F I THSVNZC
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 19
Atmel-8291C-AVR-XMEGA B -09/2014
3.15 Register Summary
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
+0x00 Reserved – – – – – – – –
+0x01 Reserved – – – – – – – –
+0x02 Reserved – – – – – – – –
+0x03 Reserved – – – – – – – –
+0x04 CCP CCP[7:0] 15
+0x05 Reserved – – – – – – – –
+0x06 Reserved – – – – – – – –
+0x07 Reserved – – – – – – – –
+0x08 RAMPD RAMPD[7:0] 15
+0x09 RAMPX RAMPX[7:0] 16
+0x0A RAMPY RAMPY[7:0] 16
+0x0B RAMPZ RAMPZ[7:0] 16
+0x0C EIND EIND[7:0] 17
+0x0D SPL SPL[7:0] 17
+0x0E SPH SPH[7:0] 17
+0x0F SREG I T H S V N Z C 18
XMEGA B [MANUAL] 20
Atmel-8291C-AVR-XMEGA B -09/2014
4. Memories
4.1 Features
z Flash program memory
z One linear address space
z In-system programmable
z Self-programming and boot loader support
z Application section for application code
z Application table section for application code or data storage
z Boot section for application code or bootloader code
z Separate read/write protection lock bits for all sections
z Built in fast CRC check of a selectable flash program memory section
z Data memory
z One linear address space
z Single-cycle access from CPU
z SRAM
z EEPROM
z Byte and page accessible
z Optional memory mapping for direct load and store
z I/O memory
z Configuration and status registers for all peripherals and modules
z 4 bit-accessible general purpose registers for global variables or flags
z Bus arbitration
z Safe and deterministic handling of priority between CPU, DMA controller, and other bus masters
z Separate buses for SRAM, EEPROM, I/O memory, and external memory access
z Simultaneous bus access for CPU and DMA controller
z Production signature row memory for factory programmed data
z ID for each microcontroller device type
z Serial number for each device
z Calibration bytes for factory calibrated peripherals
z User signature row
z One flash page in size
z Can be read and written from software
z Content is kept after chip erase
4.2 Overview
This section describes the different memory sections. The AVR architecture has two main memory spaces, the program
memory and the data memory. Executable code can reside only in the program memory, while data can be stored in the
program memory and the data memory. The data memory includes the internal SRAM, and EEPROM for nonvolatile
data storage. All memory spaces are linear and require no memory bank switching. Nonvolatile memory (NVM) spaces
can be locked for further write and read/write operations. This prevents unrestricted access to the application software.
A separate memory section contains the fuse bytes. These are used for configuring important system functions, and can
only be written by an external programmer.
4.3 Flash Program Memory
All XMEGA devices contain on-chip, in-system reprogrammable flash memory for program storage. The flash memory
can be accessed for read and write from an external programmer through the PDI or from application software running in
the device.
XMEGA B [MANUAL] 21
Atmel-8291C-AVR-XMEGA B -09/2014
All AVR CPU instructions are 16 or 32 bits wide, and each flash location is 16 bits wide. The flash memory is organized
in two main sections, the application section and the boot loader section, as shown in Figure 4-1 on page 21. The sizes
of the different sections are fixed, but device-dependent. These two sections have separate lock bits, and can have
different levels of protection. The store program memory (SPM) instruction, which is used to write to the flash from the
application software, will only operate when executed from the boot loader section.
The application section contains an application table section with separate lock settings. This enables safe storage of
nonvolatile data in the program memory.
Figure 4-1. Flash memory sections.
4.3.1 Application Section
The Application section is the section of the flash that is used for storing the executable application code. The protection
level for the application section can be selected by the boot lock bits for this section. The application section can not store
any boot loader code since the SPM instruction cannot be executed from the application section.
4.3.2 Application Table Section
The application table section is a part of the application section of the flash memory that can be used for storing data.
The size is identical to the boot loader section. The protection level for the application table section can be selected by
the boot lock bits for this section. The possibilities for different protection levels on the application section and the
application table section enable safe parameter storage in the program memory. If this section is not used for data,
application code can reside here.
4.3.3 Boot Loader Section
While the application section is used for storing the application code, the boot loader software must be located in the boot
loader section because the SPM instruction can only initiate programming when executing from this section. The SPM
instruction can access the entire flash, including the boot loader section itself. The protection level for the boot loader
section can be selected by the boot loader lock bits. If this section is not used for boot loader software, application code
can be stored here.
Application Flash
Section
0x000000
End Application
Start Boot Loader
Flashend
Application Table
Flash Section
Boot Loader Flash
Section
XMEGA B [MANUAL] 22
Atmel-8291C-AVR-XMEGA B -09/2014
4.3.4 Production Signature Row
The production signature row is a separate memory section for factory programmed data. It contains calibration data for
functions such as oscillators and analog modules. Some of the calibration values will be automatically loaded to the
corresponding module or peripheral unit during reset. Other values must be loaded from the signature row and written to
the corresponding peripheral registers from software. For details on calibration conditions such as temperature, voltage
references, etc., refer to the device datasheet.
The production signature row also contains an ID that identifies each microcontroller device type and a serial number for
each manufactured device. The serial number consists of the production lot number, wafer number, and wafer
coordinates for the device.
The production signature row cannot be written or erased, but it can be read from application software and external
programmers.
For accessing the production signature row, refer to “NVM Flash Commands” on page 380.
4.3.5 User Signature Row
The user signature row is a separate memory section that is fully accessible (read and write) from application software
and external programmers. It is one flash page in size, and is meant for static user parameter storage, such as calibration
data, custom serial number, identification numbers, random number seeds, etc. This section is not erased by chip erase
commands that erase the flash, and requires a dedicated erase command. This ensures parameter storage during
multiple program/erase operations and on-chip debug sessions.
4.4 Fuses and Lockbits
The fuses are used to configure important system functions, and can only be written from an external programmer. The
application software can read the fuses. The fuses are used to configure reset sources such as brownout detector,
watchdog and startup configuration.
The lock bits are used to set protection levels for the different flash sections (i.e., if read and/or write access should be
blocked). Lock bits can be written by external programmers and application software, but only to stricter protection levels.
Chip erase is the only way to erase the lock bits. To ensure that flash contents are protected even during chip erase, the
lock bits are erased after the rest of the flash memory has been erased.
An unprogrammed fuse or lock bit will have the value one, while a programmed fuse or lock bit will have the value zero.
Both fuses and lock bits are reprogrammable like the flash program memory.
For some fuse bytes, leaving them unprogrammed (0xFF) will result in invalid settings. The user must ensure that the
fuse bytes are programmed to values which give valid settings. Refer to the detailed description of the individual fuse
bytes for further information.
4.5 Data Memory
The data memory contains the I/O memory, internal SRAM, optionally memory mapped and EEPROM. The data memory
is organized as one continuous memory section, as shown in Figure 4-2 on page 23.
XMEGA B [MANUAL] 23
Atmel-8291C-AVR-XMEGA B -09/2014
Figure 4-2. Data memory map.
I/O memory, EEPROM, and SRAM will always have the same start addresses for all XMEGA devices.
4.6 Internal SRAM
The internal SRAM always starts at hexadecimal address 0x2000. SRAM is accessed by the CPU using the load
(LD/LDS/LDD) and store (ST/STS/STD) instructions.
4.7 EEPROM
All XMEGA devices have EEPROM for nonvolatile data storage. It is addressable in a separate data space (default) or
memory mapped and accessed in normal data space. The EEPROM supports both byte and page access. Memory
mapped EEPROM allows highly efficient EEPROM reading and EEPROM buffer loading. When doing this, EEPROM is
accessible using load and store instructions. Memory mapped EEPROM will always start at hexadecimal address
0x1000.
4.8 I/O Memory
The status and configuration registers for peripherals and modules, including the CPU, are addressable through I/O
memory locations. All I/O locations can be accessed by the load (LD/LDS/LDD) and store (ST/STS/STD) instructions,
which are used to transfer data between the 32 registers in the register file and the I/O memory. The IN and OUT
instructions can address I/O memory locations in the range of 0x00 to 0x3F directly. In the address range 0x00 - 0x1F,
single-cycle instructions for manipulation and checking of individual bits are available.
4.8.1 General Purpose I/O Registers
The lowest 4 I/O memory addresses are reserved as general purpose I/O registers. These registers can be used for
storing global variables and flags, as they are directly bit-accessible using the SBI, CBI, SBIS, and SBIC instructions.
4.9 Data Memory and Bus Arbitration
Since the data memory is organized as four separate sets of memories, the different bus masters (CPU, DMA controller
read and DMA controller write, etc.) can access different memory sections at the same time. See Figure 4-3 on page 24.
I/O Memory
(Up to 4 KB)
EEPROM
(Up to 4 KB)
Internal SRAM
0x0000
0x1000
0x2000
Start/End
Address Data Memory
XMEGA B [MANUAL] 24
Atmel-8291C-AVR-XMEGA B -09/2014
The USB module acts as a bus master, and is connected directly to internal SRAM through a pseudo-dual-port (PDP)
interface.
Figure 4-3. Bus access.
4.9.1 Bus Priority
When several masters request access to the same bus, the bus priority is in the following order (from higher to lower
priority):
1. Bus Master with ongoing access.
2. Bus Master with ongoing burst.
z Alternating DMA controller read and DMA controller write when they access the same data memory section.
3. Bus Master requesting burst access.
z CPU has priority.
4. Bus Master requesting bus access.
z CPU has priority.
4.10 Memory Timing
Read and write access to the I/O memory takes one CPU clock cycle. A write to SRAM takes one cycle, and a read from
SRAM takes two cycles. For burst read (DMA), new data are available every cycle. EEPROM page load (write) takes one
cycle, and three cycles are required for read. For burst read, new data are available every second cycle. Refer to the
instruction summary for more details on instructions and instruction timing.
4.11 Device ID and Revision
Each device has a three-byte device ID. This ID identifies Atmel as the manufacturer of the device and the device type. A
separate register contains the revision number of the device.
Peripherals and system modules
Bus matrix
DMA CPU
RAM
OCD
USART
SPI
Timer /
Counter
TWI
USB Interrupt
Controller
Power
Management
SRAM
External
Programming
AVR core PDI CH0
ADC
AC
Crypto
modules
Event System
Controller
Oscillator
Control
CH1
Non-Volatile
Memory
EEPROM
Flash CRC
Real Time
Counter
I/O
NVM
Controller
XMEGA B [MANUAL] 25
Atmel-8291C-AVR-XMEGA B -09/2014
4.12 I/O Memory Protection
Some features in the device are regarded as critical for safety in some applications. Due to this, it is possible to lock the
I/O register related to the clock system, the event system, and the advanced waveform extensions. As long as the lock is
enabled, all related I/O registers are locked and they can not be written from the application software. The lock registers
themselves are protected by the configuration change protection mechanism. For details, refer to “Configuration Change
Protection” on page 13.
XMEGA B [MANUAL] 26
Atmel-8291C-AVR-XMEGA B -09/2014
4.13 Register Description – NVM Controller
4.13.1 ADDR0 – Address register 0
The ADDR0, ADDR1, and ADDR2 registers represent the 24-bit value, ADDR. This is used for addressing all NVM
sections for read, write, and CRC operations.
z Bit 7:0 – ADDR[7:0]: Address Byte 0
This register gives the address low byte when accessing NVM locations.
4.13.2 ADDR1 – Address register 1
z Bit 7:0 – ADDR[15:8]: Address Byte 1
This register gives the address high byte when accessing NVM locations.
4.13.3 ADDR2 – Address register 2
z Bit 7:0 – ADDR[23:16]: Address Byte 2
This register gives the address extended byte when accessing NVM locations.
4.13.4 DATA0 – Data register 0
The DATA0, DATA1, and DATA registers represent the 24-bit value, DATA. This holds data during NVM read, write, and
CRC access.
z Bit 7:0 – DATA[7:0]: Data Byte 0
This register gives the data value byte 0 when accessing NVM locations.
Bit 7 6 5 4 3 2 1 0
+0x00 ADDR[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 1 1 1 1 1 1 1 1
Bit 7 6 5 4 3 2 1 0
+0x01 ADDR[15:8]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
+0x02 ADDR[23:16]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
+0x04 DATA[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 27
Atmel-8291C-AVR-XMEGA B -09/2014
4.13.5 DATA1 – Data register 1
z Bit 7:0 – DATA[15:8]: Data Byte 1
This register gives the data value byte 1 when accessing NVM locations.
4.13.6 DATA2 – Data register 2
z Bit 7:0 – DATA[23:16]: Data Byte 2
This register gives the data value byte 2 when accessing NVM locations.
4.13.7 CMD – Command register
z Bit 7 – Reserved
This bit is unused and reserved for future use. For compatibility with future devices, always write this bit to zero when this
register is written.
z Bit 6:0 – CMD[6:0]: Command
These bits define the programming commands for the flash. Bit 6 is only set for external programming commands. See
“Memory Programming” on page 375” for programming commands.
4.13.8 CTRLA – Control register A
z Bit 7:1 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 0 – CMDEX: Command Execute
Setting this bit will execute the command in the CMD register. This bit is protected by the configuration change protection
(CCP) mechanism. Refer to “Configuration Change Protection” on page 13 for details on the CCP.
Bit 7 6 5 4 3 2 1 0
+0x05 DATA[15:8]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
+0x06 DATA[23:16]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
+0x0A – CMD[6:0]
Read/Write R R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
+0x0B – – – – – – – CMDEX
Read/Write R RRRRRRS
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 28
Atmel-8291C-AVR-XMEGA B -09/2014
4.13.9 CTRLB – Control register B
z Bit 7:4 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 3 – EEMAPEN: EEPROM Data Memory Mapping Enable
Setting this bit enables data memory mapping of the EEPROM section. The EEPROM can then be accessed using load
and store instructions.
z Bit 2 – FPRM: Flash Power Reduction Mode
Setting this bit enables power saving for the flash memory. If code is running from the application section, the boot loader
section will be turned off, and vice versa. If access to the section that is turned off is required, the CPU will be halted for
a time equal to the start-up time from the idle sleep mode.
z Bit 1 – EPRM: EEPROM Power Reduction Mode
Setting this bit enables power saving for the EEPROM. The EEPROM will then be turned off in a manner equal to
entering sleep mode. If access is required, the bus master will be halted for a time equal to the start-up time from idle
sleep mode.
z Bit 0 – SPMLOCK: SPM Locked
This bit can be written to prevent all further self-programming. The bit is cleared at reset, and cannot be cleared from
software. This bit is protected by the configuration change protection (CCP) mechanism. Refer to “Configuration Change
Protection” on page 13 for details on the CCP.
4.13.10 INTCTRL – Interrupt Control register
z Bit 7:4 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 3:2 – SPMLVL[1:0]: SPM Ready Interrupt Level
These bits enable the interrupt and select the interrupt level, as described in “Interrupts and Programmable Multilevel
Interrupt Controller” on page 115. This is a level interrupt that will be triggered only when the NVMBUSY flag in the
STATUS register is set to zero. Thus, the interrupt should not be enabled before triggering an NVM command, as the
NVMBUSY flag will not be set before the NVM command is triggered. The interrupt should be disabled in the interrupt
handler.
z Bit 1:0 – EELVL[1:0]: EEPROM Ready Interrupt Level
These bits enable the EEPROM ready interrupt and select the interrupt level, as described in “Interrupts and
Programmable Multilevel Interrupt Controller” on page 115. This is a level interrupt that will be triggered only when the
NVMBUSY flag in the STATUS register is set to zero. Thus, the interrupt should not be enabled before triggering an NVM
command, as the NVMBUSY flag will not be set before the NVM command is triggered. The interrupt should be disabled
in the interrupt handler.
Bit 7 6 5 4 3 2 1 0
+0x0C – – – – EEMAPEN FPRM EPRM SPMLOCK
Read/Write R R R R R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
+0x0D – – – – SPMLVL[1:0] EELVL[1:0]
Read/Write R R R R R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 29
Atmel-8291C-AVR-XMEGA B -09/2014
4.13.11 STATUS – Status register
z Bit 7 – NVMBUSY: Nonvolatile Memory Busy
The NVMBUSY flag indicates if the NVM (Flash, EEPROM, lock bit) is being programmed. Once an operation is started,
this flag is set and remains set until the operation is completed. The NVMBUSY flag is automatically cleared when the
operation is finished.
z Bit 6 – FBUSY: Flash Busy
The FBUSY flag indicates if a flash programming operation is initiated. Once an operation is started, the FBUSY flag is
set and the application section cannot be accessed. The FBUSY flag is automatically cleared when the operation is
finished.
z Bit 5:2 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 1 – EELOAD: EEPROM Page Buffer Active Loading
The EELOAD flag indicates that the temporary EEPROM page buffer has been loaded with one or more data bytes. It
remains set until an EEPROM page write or a page buffer flush operation is executed. For more details, see “Flash and
EEPROM Programming Sequences” on page 377.
z Bit 0 – FLOAD: Flash Page Buffer Active Loading
The FLOAD flag indicates that the temporary flash page buffer has been loaded with one or more data bytes. It remains
set until an application page write, boot page write, or page buffer flush operation is executed. For more details, see
“Flash and EEPROM Programming Sequences” on page 377.
4.13.12 LOCKBITS – Lock Bit register
This register is a mapping of the NVM lock bits into the I/O memory space, which enables direct read access from the
application software. Refer to “LOCKBITS – Lock Bit register” on page 33 for a description.
Bit 7 6 5 4 3 2 1 0
+0x04 NVMBUSY FBUSY – – – – EELOAD FLOAD
Read/Write R R RRRR R R
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
+0x07 BLBB[1:0] BLBA[1:0] BLBAT[1:0] LB[1:0]
Read/Write R R R RRRRR
Initial Value 11111111
XMEGA B [MANUAL] 30
Atmel-8291C-AVR-XMEGA B -09/2014
4.14 Register Descriptions – Fuses and Lock Bits
4.14.1 FUSEBYTE1 – Fuse Byte1
z Bit 7:4 – WDWPER[3:0]: Watchdog Window Timeout Period
These fuse bits are used to set initial value of the closed window for the Watchdog Timer in Window Mode. During reset
these fuse bits are automatically written to the WPER bits Watchdog Window Mode Control Register. Refer to “WINCTRL
– Window Mode Control register” on page 113 for details.
z Bit 3:0 – WDPER[3:0]: Watchdog Timeout Period
These fuse bits are used to set the initial value of the watchdog timeout period. During reset these fuse bits are
automatically written to the PER bits in the watchdog control register. Refer to “CTRL – Control register” on page 112 for
details.
4.14.2 FUSEBYTE2 – Fuse Byte2
z Bit 7 – Reserved
This bit is unused and reserved for future use. For compatibility with future devices, always write this bit to one when this
register is written.
z Bit 6 – BOOTRST: Boot Loader Section Reset Vector
This fuse can be programmed so the reset vector is pointing to the first address in the boot loader flash section. The
device will then start executing from the boot loader flash section after reset.
Table 4-1. Boot reset fuse.
z Bit 5 – TOSCSEL: 32.768kHz Timer Oscillator Pin Selection
This fuse is used to select the pin location for the 32.768kHz timer oscillator (TOSC). This fuse is available only on
devices where XTAL and TOSC pins by default are shared.
Bit 7 6 5 4 3 2 1 0
+0x01 WDWPER[3:0] WDPER[3:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
+0x02 – BOOTRST TOSCSEL – – – BODPD[1:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 1 1 1 1 1 1 1 1
BOOSTRST Reset address
0 Reset vector = Boot loader reset
1 Reset vector = Application reset (address 0x0000)
XMEGA B [MANUAL] 31
Atmel-8291C-AVR-XMEGA B -09/2014
Table 4-2. TOSCSEL fuse.
Note: 1. See the device datasheet for alternate TOSC position.
z Bit 4:2 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to one
when this register is written.
z Bit 1:0 – BODPD[1:0]: BOD Operation in Power-down Mode
These fuse bits set the BOD operation mode in all sleep modes except idle mode.
For details on the BOD and BOD operation modes, refer to “Brownout Detection” on page 104.
Table 4-3. BOD operation modes in sleep modes.
4.14.3 FUSEBYTE4 – Fuse Byte4
z Bit 7:5 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to one
when this register is written.
z Bit: 4 – RSTDISBL: External Reset Disable
This fuse can be programmed to disable the external reset pin functionality. When this is done, pulling the reset pin low
will not cause an external reset. A reset is required before this bit will be read correctly after it is changed.
z Bit 3:2 – STARTUPTIME[1:0]: Start-up time
These fuse bits can be used to set at a programmable timeout period from when all reset sources are released until the
internal reset is released from the delay counter. A reset is required before these bits will be read correctly after they are
changed.
The delay is timed from the 1kHz output of the ULP oscillator. Refer to “Reset Sequence” on page 103 for details.
TOSCSEL Group configuration Description
0 ALTERNATE(1) TOSC1/2 on separate pins
1 XTAL TOSC1/2 shared with XTAL
BODPD[1:0] Description
00 Reserved
01 BOD enabled in sampled mode
10 BOD enabled continuously
11 BOD disabled
Bit 7 6 5 4 3 2 1 0
+0x04 – – – RSTDISBL STARTUPTIME[1:0] WDLOCK –
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 1 1 1 1 1 1 1 1
XMEGA B [MANUAL] 32
Atmel-8291C-AVR-XMEGA B -09/2014
Table 4-4. Start-up time
z Bit 1 – WDLOCK: Watchdog Timer Lock
The WDLOCK fuse can be programmed to lock the watchdog timer configuration. When this fuse is programmed, the
watchdog timer configuration cannot be changed, and the ENABLE bit in the watchdog CTRL register is automatically set
at reset and cannot be cleared from the application software. The WEN bit in the watchdog WINCTRL register is not set
automatically, and needs to be set from software. A reset is required before this bit will be read correctly after it is
changed.
Table 4-5. Watchdog timer lock
z Bit 0 – Reserved
This bit is unused and reserved for future use. For compatibility with future devices, always write this bit to one when this
register is written.
4.14.4 FUSEBYTE5 – Fuse Byte 5
z Bit 7:6 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to one
when this register is written.
z Bit 5:4 – BODACT[1:0]: BOD Operation in Active Mode
These fuse bits set the BOD operation mode when the device is in active and idle modes. For details on the BOD and
BOD operation modes. Refer to “Brownout Detection” on page 104.
Table 4-6. BOD operation modes in active and idle modes
STARTUPTIME[1:0 1kHz ULP oscillator cycles
00 64
01 4
10 Reserved
11 0
WDLOCK Description
0 Watchdog timer locked for modifications
1 Watchdog timer not locked
Bit 7 6 5 4 3 2 1 0
+0x05 – – BODACT[1:0] EESAVE BODLEVEL[2:0]
Read/Write R R R/W R/W R/W R/W R/W R/W
Initial Value 1 1 – – – – – –
BODACT[1:0] Description
00 Reserved
01 BOD enabled in sampled mode
10 BOD enabled continuously
11 BOD disabled
XMEGA B [MANUAL] 33
Atmel-8291C-AVR-XMEGA B -09/2014
z Bit 3 – EESAVE: EEPROM is Preserved through the Chip Erase
A chip erase command will normally erase the flash, EEPROM, and internal SRAM. If this fuse is programmed, the
EEPROM is not erased during chip erase. This is useful if EEPROM is used to store data independently of the software
revision.
Table 4-7. EEPROM preserved through chip erase
Changes to the EESAVE fuse bit take effect immediately after the write timeout elapses. Hence, it is possible to update
EESAVE and perform a chip erase according to the new setting of EESAVE without leaving and reentering programming
mode.
z Bit 2:0 – BODLEVEL[2:0]: Brownout Detection Voltage Level
These fuse bits sets the BOD voltage level. Refer to “Reset System” on page 102 for details. For BOD level nominal
values, see Table 9-2 on page 105.
4.14.5 LOCKBITS – Lock Bit register
z Bit 7:6 – BLBB[1:0]: Boot Lock Bit Boot Loader Section
These lock bits control the software security level for accessing the boot loader section. The BLBB bits can only be
written to a more strict locking. Resetting the BLBB bits is possible by executing a chip erase command.
Table 4-8. Boot lock bit for the boot loader section
EESAVE Description
0 EEPROM is preserved during chip erase
1 EEPROM is erased during chip erase
Bit 7 6 5 4 3 2 1 0
+0x07 BLBB[1:0] BLBA[1:0] BLBAT[1:0] LB[1:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 1 1 1 1 1 1 1 1
BLBB[1:0] Group Configuration Description
11 NOLOCK No lock – no restrictions for SPM and (E)LPM accessing the boot
loader section.
10 WLOCK Write lock – SPM is not allowed to write the boot loader section.
01 RLOCK
Read lock – (E)LPM executing from the application section is not
allowed to read from the boot loader section.
If the interrupt vectors are placed in the application section,
interrupts are disabled while executing from the boot loader
section.
00 RWLOCK
Read and write lock – SPM is not allowed to write to the boot loader
section, and (E)LPM executing from the application section is not
allowed to read from the boot loader section.
If the interrupt vectors are placed in the application section,
interrupts are disabled while executing from the boot loader
section.
XMEGA B [MANUAL] 34
Atmel-8291C-AVR-XMEGA B -09/2014
z Bit 5:4 – BLBA[1:0]: Boot Lock Bit Application Section
These lock bits control the software security level for accessing the application section according to Table 4-9 on page
34. The BLBA bits can only be written to a more strict locking. Resetting the BLBA bits is possible only by executing a
chip erase command.
Table 4-9. Boot lock bit for the application section
z Bit 3:2 – BLBAT[1:0]: Boot Lock Bit Application Table Section
These lock bits control the software security level for accessing the application table section for software access. The
BLBAT bits can only be written to a more strict locking. Resetting the BLBAT bits is possible only by executing a chip
erase command.
Table 4-10. Boot lock bit for the application table section
z Bit 1:0 – LB[1:0]: Lock Bits(1)
These lock bits control the security level for the flash and EEPROM during external programming. These bits are writable
only through an external programming interface. Resetting the lock bits is possible only by executing a chip erase
BLBA[1:0] Group Configuration Description
11 NOLOCK No Lock - no restrictions for SPM and (E)LPM accessing the
application section.
10 WLOCK Write lock – SPM is not allowed to write the application section.
01 RLOCK
Read lock – (E)LPM executing from the boot loader section is not
allowed to read from the application section.
If the interrupt vectors are placed in the boot loader section,
interrupts are disabled while executing from the application section.
00 RWLOCK
Read and write lock – SPM is not allowed to write to the application
section, and (E)LPM executing from the boot loader section is not
allowed to read from the application section.
If the interrupt vectors are placed in the boot loader section,
interrupts are disabled while executing from the application section.
BLBAT[1:0] Group Configuration Description
11 NOLOCK No lock – no restrictions for SPM and (E)LPM accessing the
application table section.
10 WLOCK Write lock – SPM is not allowed to write the application table
01 RLOCK
Read lock – (E)LPM executing from the boot loader section is not
allowed to read from the application table section.
If the interrupt vectors are placed in the boot loader section,
interrupts are disabled while executing from the application
section.
00 RWLOCK
Read and write lock – SPM is not allowed to write to the
application table section, and (E)LPM executing from the boot
loader section is not allowed to read from the application table
section.
If the interrupt vectors are placed in the boot loader section,
interrupts are disabled while executing from the application
section.
XMEGA B [MANUAL] 35
Atmel-8291C-AVR-XMEGA B -09/2014
command. All other access; using the TIF and OCD, is blocked if any of the Lock Bits are written to 0. These bits do not
block any software access to the memory.
Table 4-11. Lock bit protection mode.
Note: 1. Program the Fuse Bits and Boot Lock Bits before programming the Lock Bits.
LB[1:0] Group Configuration Description
11 NOLOCK3 No lock – no memory locks enabled.
10 WLOCK
Write lock – programming of the flash and EEPROM is disabled for
the programming interface. Fuse bits are locked for write from the
programming interface.
00 RWLOCK
Read and write lock – programming and read/verification of the
flash and EEPROM are disabled for the programming interface.
The lock bits and fuses are locked for read and write from the
programming interface.
XMEGA B [MANUAL] 36
Atmel-8291C-AVR-XMEGA B -09/2014
4.15 Register Description – Production Signature Row
4.15.1 RCOSC2M – Internal 2MHz Oscillator Calibration register
z Bit 7:0 – RCOSC2M[7:0]: Internal 2MHz Oscillator Calibration Value
This byte contains the oscillator calibration value for the internal 2MHz oscillator. Calibration of the oscillator is performed
during production test of the device. During reset this value is automatically loaded into calibration register B for the
2MHz DFLL. Refer to “CALB – DFLL Calibration register B” on page 92 for more details.
4.15.2 RCOSC2MA – Internal 2MHz Oscillator Calibration register
z Bit 7:0 – RCOSC2MA[7:0]: Internal 2MHz Oscillator Calibration Value
This byte contains the oscillator calibration value for the internal 2MHz oscillator. Calibration of the oscillator is performed
during production test of the device. During reset this value is automatically loaded into calibration register A for the
2MHz DFLL. Refer to “CALA – DFLL Calibration Register A” on page 92 for more details.
4.15.3 RCOSC32K – Internal 32.768kHz Oscillator Calibration register
z Bit 7:0 – RCOSC32K[7:0]: Internal 32.768kHz Oscillator Calibration Value
This byte contains the oscillator calibration value for the internal 32.768kHz oscillator. Calibration of the oscillator is
performed during production test of the device. During reset this value is automatically loaded into the calibration register
for the 32.768kHz oscillator. Refer to “RC32KCAL – 32kHz Oscillator Calibration register” on page 90 for more details.
4.15.4 RCOSC32M – Internal 32MHz Oscillator Calibration register
z Bit 7:0 – RCOSC32M[7:0]: Internal 32MHz Oscillator Calibration Value
This byte contains the oscillator calibration value for the internal 32MHz oscillator. Calibration of the oscillator is
performed during production test of the device. During reset this value is automatically loaded into calibration register B
for the 32MHz DFLL. Refer to “CALB – DFLL Calibration register B” on page 92 for more details.
Bit 7 6 5 4 3 2 1 0
0x00 RCOSC2M[7:0]
Read/Write R R R R R R R R
Initial Value x x x x x x x x
Bit 7 6 5 4 3 2 1 0
0x01 RCOSC2MA[7:0]
Read/Write R R R R R R R R
Initial Value x x x x x x x x
Bit 7 6 5 4 3 2 1 0
0x02 RCOSC32K[7:0]
Read/Write RRRR R R R R
Initial Value x x x x x x x x
Bit 7 6 5 4 3 2 1 0
0x03 RCOSC32M[7:0]
Read/Write RRRR R R R R
Initial Value x x x x x x x x
XMEGA B [MANUAL] 37
Atmel-8291C-AVR-XMEGA B -09/2014
4.15.5 RCOSC32MA – Internal 32MHz RC Oscillator Calibration register
z Bit 7:0 – RCOSC32MA[7:0]: Internal 32MHz Oscillator Calibration Value
This byte contains the oscillator calibration value for the internal 32MHz oscillator. Calibration of the oscillator is
performed during production test of the device. During reset this value is automatically loaded into calibration register A
for the 32MHz DFLL. Refer to “CALA – DFLL Calibration Register A” on page 92 for more details.
4.15.6 LOTNUM0 – Lot Number register 0
LOTNUM0, LOTNUM1, LOTNUM2, LOTNUM3, LOTNUM4 and LOTNUM5 contain the lot number for each device.
Together with the wafer number and wafer coordinates this gives a serial number for the device.
z Bit 7:0 – LOTNUM0[7:0]: Lot Number Byte 0
This byte contains byte 0 of the lot number for the device.
4.15.7 LOTNUM1 – Lot Number register 1
z Bit 7:0 – LOTNUM1[7:0]: Lot Number Byte 1
This byte contains byte 1 of the lot number for the device.
4.15.8 LOTNUM2 – Lot Number Register 2
z Bit 7:0 – LOTNUM2[7:0]: Lot Number Byte 2
This byte contains byte 2 of the lot number for the device.
Bit 7 6 5 4 3 2 1 0
0x04 RCOSC32MA[7:0]
Read/Write R R R R R R R R
Initial Value x x x x x x x x
Bit 7 6 5 4 3 2 1 0
0x08 LOTNUM0[7:0]
Read/Write R R R R R R R R
Initial Value x x x x x x x x
Bit 7 6 5 4 3 2 1 0
0x09 LOTNUM1[7:0]
Read/Write R R R R R R R R
Initial Value x x x x x x x x
Bit 7 6 5 4 3 2 1 0
0x0A LOTNUM2[7:0]
Read/Write R R R R R R R R
Initial Value x x x x x x x x
XMEGA B [MANUAL] 38
Atmel-8291C-AVR-XMEGA B -09/2014
4.15.9 LOTNUM3 – Lot Number register 3
z Bit 7:0 – LOTNUM3[7:0]: Lot Number Byte 3
This byte contains byte 3 of the lot number for the device.
4.15.10 LOTNUM4 – Lot Number register 4
z Bit 7:0 – LOTNUM4[7:0]: Lot Number Byte 4
This byte contains byte 4 of the lot number for the device.
4.15.11 LOTNUM5 – Lot Number register 5
z Bit 7:0 – LOTNUM5[7:0]: Lot Number Byte 5
This byte contains byte 5 of the lot number for the device.
4.15.12 WAFNUM – Wafer Number register
z Bit 7:0 – WAFNUM[7:0]: Wafer Number
This byte contains the wafer number for each device. Together with the lot number and wafer coordinates this gives a
serial number for the device.
Bit 7 6 5 4 3 2 1 0
0x0B LOTNUM3[7:0]
Read/Write R R R R R R R R
Initial Value x x x x x x x x
Bit 7 6 5 4 3 2 1 0
0x0C LOTNUM4[7:0]
Read/Write RRRR R R R R
Initial Value x x x x x x x x
Bit 7 6 5 4 3 2 1 0
0x0D LOTNUM5[7:0]
Read/Write R R R R R R R R
Initial Value x x x x x x x x
Bit 7 6 5 4 3 2 1 0
0x10 WAFNUM[7:0]
Read/Write R R R R R R R R
Initial Value 0 0 0 x x x x x
XMEGA B [MANUAL] 39
Atmel-8291C-AVR-XMEGA B -09/2014
4.15.13 COORDX0 – Wafer Coordinate X register 0
COORDX0, COORDX1, COORDY0 and COORDY1 contain the wafer X and Y coordinates for each device. Together
with the lot number and wafer number, this gives a serial number for each device.
z Bit 7:0 – COORDX0[7:0]: Wafer Coordinate X Byte 0
This byte contains byte 0 of wafer coordinate X for the device.
4.15.14 COORDX1 – Wafer Coordinate X register 1
z Bit 7:0 – COORDX0[7:0]: Wafer Coordinate X Byte 1
This byte contains byte 1 of wafer coordinate X for the device.
4.15.15 COORDY0 – Wafer Coordinate Y register 0
z Bit 7:0 – COORDY0[7:0]: Wafer Coordinate Y Byte 0
This byte contains byte 0 of wafer coordinate Y for the device.
4.15.16 COORDY1 – Wafer Coordinate Y register 1
z Bit 7:0 – COORDY1[7:0]: Wafer Coordinate Y Byte 1
This byte contains byte 1 of wafer coordinate Y for the device.
Bit 7 6 5 4 3 2 1 0
0x12 COORDX0[7:0]
Read/Write RRRR R R R R
Initial Value x x x x x x x x
Bit 7 6 5 4 3 2 1 0
0x13 COORDX1[7:0]
Read/Write R R R R R R R R
Initial Value x x x x x x x x
Bit 7 6 5 4 3 2 1 0
0x14 COORDY0[7:0]
Read/Write R R R R R R R R
Initial Value x x x x x x x x
Bit 7 6 5 4 3 2 1 0
0x15 COORDY1[7:0]
Read/Write R R R R R R R R
Initial Value x x x x x x x x
XMEGA B [MANUAL] 40
Atmel-8291C-AVR-XMEGA B -09/2014
4.15.17 USBCAL0 – USB Calibration register 0
USBCAL0 and USBCAL1 contain the calibration value for the USB pins. Calibration is done during production to enable
operation without requiring external components on the USB lines for the device. The calibration bytes are not loaded
automatically into the USB calibration registers, and so this must be done from software.
z Bit 7:0 – USBCAL0[7:0]: USB Pad Calibration byte 0
This byte contains byte 0 of the USB pin calibration data, and must be loaded into the USB CALL register.
4.15.18 USBCAL1 – USB Pad Calibration register 1
z Bit 7:0 – USBCAL1[7:0]: USB Pad Calibration byte 1
This byte contains byte 1 of the USB pin calibration data, and must be loaded into the USB CALH register.
4.15.19 USBRCOSC – USB RCOSC Calibration
z Bit 7:0 – USBRCOSC[7:0]: 48MHz RSCOSC Calibration
This byte contains a 48MHz calibration value for the internal 32MHz oscillator. When this calibration value is written to
calibration register B for the 32MHz DFLL, the oscillator is calibrated to 48MHz to enable full-speed USB operation from
internal oscillator.
Note: The COMP2 and COMP1 registers inside the DFLL32M must be set to B71B.
4.15.20 ADCACAL0 – ADCA Calibration register 0
ADCACAL0 and ADCACAL1 contain the calibration value for the analog to digital converter A (ADCA). Calibration is
done during production test of the device. The calibration bytes are not loaded automatically into the ADC calibration
registers, so this must be done from software.
z Bit 7:0 – ADCACAL0[7:0]: ADCA Calibration Byte 0
This byte contains byte 0 of the ADCA calibration data, and must be loaded into the ADCA CALL register.
Bit 7 6 5 4 3 2 1 0
0x1A USBCAL0[7:0]
Read/Write RRRR R R R R
Initial Value x x x x x x x x
Bit 7 6 5 4 3 2 1 0
0x1B USBCAL1[7:0]
Read/Write RRRR R R R R
Initial Value xxxx x x x x
Bit 7 6 5 4 3 2 1 0
0x1C USBRCOSC[7:0]
Read/Write RRRR R R R R
Initial Value x x x x x x x x
Bit 7 6 5 4 3 2 1 0
0x20 ADCACAL0[7:0]
Read/Write RRRR R R R R
Initial Value xxxx x x x x
XMEGA B [MANUAL] 41
Atmel-8291C-AVR-XMEGA B -09/2014
4.15.21 ADCACAL1 – ADCA Calibration register 1
z Bit 7:0 – ADCACAL1[7:0]: ADCA Calibration Byte 1
This byte contains byte 1 of the ADCA calibration data, and must be loaded into the ADCA CALH register.
4.15.22 TEMPSENSE0 – Temperature Sensor Calibration register 0
TEMPSENSE0 and TEMPSENSE1 contain the 12-bit ADCA value from a temperature measurement done with the
internal temperature sensor. The measurement is done in production test at 85°C and can be used for single- or multipoint
temperature sensor calibration.
z Bit 7:0 – TEMPSENSE0[7:0]: Temperature Sensor Calibration Byte 0
This byte contains the byte 0 of the temperature measurement.
4.15.23 TEMPSENSE1 – Temperature Sensor Calibration register 1
z Bit 7:0 – TEMPSENSE1[7:0]: Temperature Sensor Calibration Byte 1
This byte contains byte 1 of the temperature measurement.
Bit 7 6 5 4 3 2 1 0
0x21 ADCACAL1[7:0]
Read/Write RRRR R R R R
Initial Value x x x x x x x x
Bit 7 6 5 4 3 2 1 0
0x2E TEMPSENSE0[7:0]
Read/Write R R R R R R R R
Initial Value x x x x x x x x
Bit 7 6 5 4 3 2 1 0
0x2F TEMPSENSE1[7:0]
Read/Write R R R R R R R R
Initial Value 0 0 0 0 x x x x
XMEGA B [MANUAL] 42
Atmel-8291C-AVR-XMEGA B -09/2014
4.16 Register Description – General Purpose I/O Memory
4.16.1 GPIORn – General Purpose I/O register n
These are general purpose registers that can be used to store data, such as global variables and flags, in the bitaccessible
I/O memory space.
4.17 Register Descriptions – MCU Control
4.17.1 DEVID0 – Device ID register 0
DEVID0, DEVID1 and DEVID2 contain the byte identification that identifies each microcontroller device type. For details
on the actual ID, refer to the device datasheets.
z Bit 7:0 – DEVID0[7:0]: Device ID Byte 0
Byte 0 of the device ID. This byte will always be read as 0x1E. This indicates that the device is manufactured by Atmel.
4.17.2 DEVID1 – Device ID register 1
z Bit 7:0 – DEVID[7:0]: Device ID Byte 1
Byte 1 of the device ID indicates the flash size of the device.
4.17.3 DEVID2 – Device ID register 2
z Bit 7:0 – DEVID2[7:0]: Device ID Byte 2
Byte 2 of the device ID indicates the device number.
Bit 7 6 5 4 3 2 1 0
+n GPIORn[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 00000
Bit 7 6 5 4 3 2 1 0
+0x00 DEVID0[7:0]
Read/Write R R RRRRRR
Initial Value 00011110
Bit 7 6 5 4 3 2 1 0
+0x01 DEVID1[7:0]
Read/Write R R RRRRRR
Initial Value 1/0 1/0 1/0 1/0 1/0 1/0 1/0 1/0
Bit 7 6 5 4 3 2 1 0
+0x02 DEVID2[7:0]
Read/Write R R RRRRRR
Initial Value 1/0 1/0 1/0 1/0 1/0 1/0 1/0 1/0
XMEGA B [MANUAL] 43
Atmel-8291C-AVR-XMEGA B -09/2014
4.17.4 REVID – Revision ID
z Bit 7:4 – Reserved
These bits are unused and reserved for future use.
z Bit 3:0 – REVID[3:0]: Revision ID
These bits contains the device revision. 0 = A, 1 = B, and so on.
4.17.5 ANAINIT – Analog Initialization register
z Bit 7:2 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 1:0 – STARTUPDLYx
Setting these bits enables sequential start of the internal components used for the ADC, DAC, and analog comparator
with the main input/output connected to that port. When this is done, the internal components such as voltage reference
and bias currents are started sequentially when the module is enabled. This reduces the peak current consumption
during startup of the module. For maximum effect, the start-up delay should be set so that it is larger than 0.5μs.
Table 4-12. Analog start-up delay
4.17.6 EVSYSLOCK – Event System Lock register
z Bit 7:1 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
Bit 7 6 5 4 3 2 1 0
+0x03 – – – – REVID[3:0]
Read/Write R RRRRRRR
Initial Value 0 0 0 0 1/0 1/0 1/0 1/0
Bit 7 6 5 4 3 2 1 0
+0x07 – – – – – – STARTUPDLYA[1:0]
Read/Write R R R R R R R/W R/W
Initial Value 0 0 0 00000
STARTUPDLYx Group Configuration Description
00 NONE Direct startup
11 2CLK 2 * CLKPER
10 8CLK 8 * CLKPER
11 32CLK 32 * CLKPER
Bit 7 6 5 4 3 2 1 0
+0x08 – – – – – – – EVSYS0LOCK
Read/Write R R R R R R R R/W
Initial Value 0 0 0 0000 0
XMEGA B [MANUAL] 44
Atmel-8291C-AVR-XMEGA B -09/2014
z Bit 0 – EVSYS0LOCK:
Setting this bit will lock all registers in the event system related to event channels 0 to 3 against further modification. The
following registers in the event system are locked: CH0MUX, CH0CTRL, CH1MUX, CH1CTRL, CH2MUX, CH2CTRL,
CH3MUX, and CH3CTRL. This bit is protected by the configuration change protection mechanism. For details, refer to
“Configuration Change Protection” on page 13.
4.17.7 AWEXLOCK – Advanced Waveform Extension Lock register
z Bit 7:1 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 0 – AWEXCLOCK: Advanced Waveform Extension Lock for TCC0
Setting this bit will lock all registers in the AWEXC module for timer/counter C0 for against further modification. This bit is
protected by the configuration change protection mechanism. For details, refer to “Configuration Change Protection” on
page 13.
Bit 7 6 5 4 3 2 1 0
+0x09 – – – – – – – AWEXCLOCK
Read/Write R R R R R R R R/W
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 45
Atmel-8291C-AVR-XMEGA B -09/2014
4.18 Register Summary - NVM Controller
4.19 Register Summary - Fuses and Lock Bits
4.20 Register Summary - Production Signature Row
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
+0x00 ADDR0 Address Byte 0 25
+0x01 ADDR1 Address Byte 1 25
+0x02 ADDR2 Address Byte 2 25
+0x03 Reserved – – – – – – – –
+0x04 DATA0 Data Byte 0 26
+0x05 DATA1 Data Byte 1 26
+0x06 DATA2 Data Byte 2 26
+0x07 Reserved – – – – – – – –
+0x08 Reserved – – – – – – – –
+0x09 Reserved – – – – – – – –
+0x0A CMD – CMD[6:0] 26
+0x0B CTRLA – – – – – – – CMDEX 27
+0x0C CTRLB – – – – EEMAPEN FPRM EPRM SPMLOCK 27
+0x0D INTCTRL – – – – SPMLVL[1:0] EELVL[1:0] 28
+0x0E Reserved – – – – – – – –
+0x0F STATUS NVMBUSY FBUSY – – – – EELOAD FLOAD 28
+0x10 LOCKBITS BLBB[1:0] BLBA[1:0] BLBAT[1:0] LB[1:0] 29
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
+0x00 Reserved – – – – – – – –
+0x01 FUSEBYTE1 WDWPER3:0] WDPER[3:0] 30
+0x02 FUSEBYTE2 – BOOTRST TOSCSEL – – – BODPD[1:0] 30
+0x03 Reserved – – – – – – – –
+0x04 FUSEBYTE4 – – – RSTDISBL STARTUPTIME[1:0] WDLOCK – 31
+0x05 FUSEBYTE5 – – BODACT[1:0] EESAVE BODLEVEL[2:0] 32
+0x06 Reserved – – – – – – – –
+0x07 LOCKBITS BLBB[1:0] BLBA[1:0] BLBAT[1:0] LB[1:0] 34
Address Auto Load Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
0x00 YES RCOSC2M RCOSC2M[7:0] 36
0x01 YES RCOSC2MA RCOSC2MA[7:0] 37
0x02 YES RCOSC32K RCOSC32K[7:0] 36
0x03 YES RCOSC32M RCOSC32M[7:0] 36
0x04 YES RCOSC32MA RCOSC32MA[7:0] 37
0x05 Reserved – – – – – – – –
0x06 Reserved – – – – – – – –
0x07 Reserved – – – – – – – –
0x08 NO LOTNUM0 LOTNUM0[7:0] 37
0x09 NO LOTNUM1 LOTNUM1[7:0] 37
0x0A NO LOTNUM2 LOTNUM2[7:0] 37
0x0B NO LOTNUM3 LOTNUM3[7:0] 38
0x0C NO LOTNUM4 LOTNUM4[7:0] 38
0x0D NO LOTNUM5 LOTNUM5[7:0] 38
0x0E Reserved – – – – – – – –
0x0F Reserved – – – – – – – –
0x10 NO WAFNUM WAFNUM[7:0] 38
0x11 Reserved – – – – – – – –
0x12 NO COORDX0 COORDX0[7:0] 39
0x13 NO COORDX1 COORDX1[7:0] 39
0x14 NO COORDY0 COORDY0[7:0] 39
0x15 NO COORDY1 COORDY1[7:0] 39
0x16 Reserved – – – – – – – –
0x17 Reserved – – – – – – – –
0x18 Reserved – – – – – – – –
0x19 Reserved – – – – – – – –
0x1A USBCAL0 USBCAL0[7:0] 40
0x1B USBCAL1 USBCAL1[7:0] 40
0x1C USBRCOSC USBRCOSC[7:0] 40
XMEGA B [MANUAL] 46
Atmel-8291C-AVR-XMEGA B -09/2014
4.21 Register Summary – General Purpose I/O Registers
4.22 Register Summary – MCU Control
4.23 Interrupt Vector Summary – NVM Controller
0x1D Reserved – – – – – – – –
0x0E Reserved – – – – – – – –
0x1E Reserved – – – – – – – –
0x20 NO ADCACAL0 ADCACAL0[7:0] 40
0x21 NO ADCACAL1 ADCACAL1{7:0] 41
0x22 Reserved – – – – – – – –
0x23 Reserved – – – – – – – –
0x24 Reserved – – – – – – – –
0x25 Reserved – – – – – – – –
0x26 Reserved – – – – – – – –
0x27 Reserved – – – – – – – –
0x28 Reserved – – – – – – – –
0x29 Reserved – – – – – – – –
0x2A Reserved – – – – – – – –
0x2B Reserved – – – – – – – –
0x2C Reserved – – – – – – – –
0x2D Reserved – – – – – – – –
0x2E NO TEMPSENSE0 TEMPSENSE0[7:0] 41
0x2F NO TEMPSENSE1 – – – – TEMPSENSE1[11:8] 41
0x38 Reserved – – – – – – – –
0x39 Reserved – – – – – – – –
0x3A Reserved – – – – – – – –
0x3B Reserved – – – – – – – –
0x3C Reserved – – – – – – – –
0x3D Reserved – – – – – – – –
0x3E Reserved – – – – – – – –
Address Auto Load Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
+0x00 GPIOR0 GPIOR[7:0] 42
+0x01 GPIOR1 GPIOR[7:0] 42
+0x02 GPIOR2 GPIOR[7:0] 42
+0x03 GPIOR3 GPIOR[7:0] 42
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
+0x00 DEVID0 DEVID0[7:0] 42
+0x01 DEVID1 DEVID1[7:0] 42
+0x02 DEVID2 DEVID2[7:0] 42
+0x03 REVID – – – – REVID[3:0] 43
+0x04 Reserved – – – – – – – –
+0x05 Reserved – – – – – – – –
+0x06 Reserved – – – – – – – –
+0x07 ANAINIT – – – – STARTUPDLYB[1:0] STARTUPDLYA[1:0] 43
+0x08 EVSYSLOCK – – – – – – – EVSYS0LOC 43
+0x09 AWEXLOCK – – – – – – – AWEXCLOCK 44
+0x0A Reserved – – – – – – – –
+0x0B Reserved – – – – – – – –
Offset Source Interrupt Description
0x00 EE_vect Nonvolatile memory EEPROM interrupt vector
0x02 SPM_vect Nonvolatile memory SPM interrupt vector
XMEGA B [MANUAL] 47
8291C–AVR–09/2014
5. DMAC - Direct Memory Access Controller
5.1 Features
z Allows high speed data transfers with minimal CPU intervention
z from data memory to data memory
z from data memory to peripheral
z from peripheral to data memory
z from peripheral to peripheral
z Two DMA channels with separate
z transfer triggers
z interrupt vectors
z addressing modes
z Programmable channel priority
z From 1 byte to 16MB of data in a single transaction
z Up to 64KB block transfers with repeat
z 1, 2, 4, or 8 byte burst transfers
z Multiple addressing modes
z Static
z Incremental
z Decremental
z Optional reload of source and destination addresses at the end of each
z Burst
z Block
z Transaction
z Optional interrupt on end of transaction
z Optional connection to CRC generator for CRC on DMA data
5.2 Overview
The two-channel direct memory access (DMA) controller can transfer data between memories and peripherals, and thus
offload these tasks from the CPU. It enables high data transfer rates with minimum CPU intervention, and frees up CPU
time. The two DMA channels enable up to two independent and parallel transfers.
The DMA controller can move data between SRAM and peripherals, between SRAM locations and directly between
peripheral registers. With access to all peripherals, the DMA controller can handle automatic transfer of data to/from
communication modules. The DMA controller can also read from memory mapped EEPROM.
Data transfers are done in continuous bursts of 1, 2, 4, or 8 bytes. They build block transfers of configurable size from 1
byte to 64KB. A repeat counter can be used to repeat each block transfer for single transactions up to 16MB. Source and
destination addressing can be static, incremental or decremental. Automatic reload of source and/or destination
addresses can be done after each burst or block transfer, or when a transaction is complete. Application software,
peripherals, and events can trigger DMA transfers.
The two DMA channels have individual configuration and control settings. This include source, destination, transfer
triggers, and transaction sizes. They have individual interrupt settings. Interrupt requests can be generated when a
transaction is complete or when the DMA controller detects an error on a DMA channel.
To allow for continuous transfers, two channels can be interlinked so that the second takes over the transfer when the
first is finished, and vice versa.
XMEGA B [MANUAL] 48
8291C–AVR–09/2014
Figure 5-1. DMA Overview.
5.3 DMA Transaction
A complete DMA read and write operation between memories and/or peripherals is called a DMA transaction. A
transaction is done in data blocks, and the size of the transaction (number of bytes to transfer) is selectable from
software and controlled by the block size and repeat counter settings. Each block transfer is divided into smaller bursts.
5.3.1 Block Transfer and Repeat
The size of the block transfer is set by the block transfer count register, and can be anything from 1 byte to 64KB.
A repeat counter can be enabled to set a number of repeated block transfers before a transaction is complete. The
repeat is from 1 to 255, and an unlimited repeat count can be achieved by setting the repeat count to zero.
5.3.2 Burst Transfer
Since the AVR CPU and DMA controller use the same data buses, a block transfer is divided into smaller burst transfers.
The burst transfer is selectable to 1, 2, 4, or 8 bytes. This means that if the DMA acquires the data bus and a transfer
request is pending, it will occupy the bus until all bytes in the burst are transferred.
A bus arbiter controls when the DMA controller and the AVR CPU can use the bus. The CPU always has priority, and so
as long as the CPU requests access to the bus, any pending burst transfer must wait. The CPU requests bus access
when it executes an instruction that writes or reads data to SRAM, I/O memory, EEPROM or the external bus interface.
For more details on memory access bus arbitration, refer to “Data Memory” on page 22.
Figure 5-2. DMA transaction.
R/W Master port
Arbitration
BUF
Bus
matrix
Arbiter
Read
Write
Slave port
Read /
Write
CTRL
DMA Channel 1
DMA trigger /
Event
DMA Channel 0
SRCADDR
TRFCNT DESTADDR
TRIGSRC
REPCNT
Control Logic
Enable
Burst
CTRLA
CTRLB
XMEGA B [MANUAL] 49
8291C–AVR–09/2014
5.4 Transfer Triggers
DMA transfers can be started only when a DMA transfer request is detected. A transfer request can be triggered from
software, from an external trigger source (peripheral), or from an event. There are dedicated source trigger selections for
each DMA channel. The available trigger sources may vary from device to device, depending on the modules or
peripherals that exist in the device. Using a transfer trigger for a module or peripherals that does not exist will have no
effect. For a list of all transfer triggers, refer to “TRIGSRC – Trigger Source” on page 57.
By default, a trigger starts a block transfer operation. When the block transfer is complete, the channel is automatically
disabled. When enabled again, the channel will wait for the next block transfer trigger. It is possible to select the trigger to
start a burst transfer instead of a block transfer. This is called a single-shot transfer, and for each trigger only one burst is
transferred. When repeat mode is enabled, the next block transfer does not require a transfer trigger. It will start as soon
as the previous block is done.
If the trigger source generates a transfer request during an ongoing transfer, this will be kept pending, and the transfer
can start when the ongoing one is done. Only one pending transfer can be kept, and so if the trigger source generates
more transfer requests when one is already pending, these will be lost.
5.5 Addressing
The source and destination address for a DMA transfer can either be static or automatically incremented or
decremented, with individual selections for source and destination. When address increment or decrement is used, the
default behaviour is to update the address after each access. The original source and destination addresses are stored
by the DMA controller, and so the source and destination addresses can be individually configured to be reloaded at the
following points:
z End of each burst transfer
z End of each block transfer
z End of transaction
z Never reloaded
5.6 Priority Between Channels
If several channels request a data transfer at the same time, a priority scheme is available to determine which channel is
allowed to transfer data. Application software can decide whether one or more channels should have a fixed priority or if
a round robin scheme should be used. A round robin scheme means that the channel that last transferred data will have
the lowest priority.
5.7 Double Buffering
To allow for continuous transfer, two channels can be interlinked so that the second takes over the transfer when the first
is finished, and vice versa. This leaves time for the application to process the data transferred by the first channel,
prepare fresh data buffers, and set up the channel registers again while the second channel is working. This is referred to
as double buffering or chained transfers.
When double buffering is enabled for a channel pair, it is important that the two channels are configured with the same
repeat count. The block sizes need not be equal, but for most applications they should be, along with the rest of the
channel’s operation mode settings.
Note that the double buffering channel pairs are limited to channels 0 and 1 as the first pair and channels 2 and 3 as the
second pair. However, it is possible to have one pair operate in double buffered mode while the other is left unused or
operating independently.
5.8 Transfer Buffers
To avoid unnecessary bus loading when doing data transfer between memories with different access timing (for
example, I/O register and external memory), the DMA controller has a four-byte buffer. Two bytes will be read from the
source address and written to this buffer before a write to the destination is started.
XMEGA B [MANUAL] 50
8291C–AVR–09/2014
5.9 Error detection
The DMA controller can detect erroneous operation. Error conditions are detected individually for each DMA channel,
and the error conditions are:
z Write to memory mapped EEPROM locations
z Reading EEPROM when the EEPROM is off (sleep entered)
z DMA controller or a busy channel is disabled in software during a transfer
5.10 Software Reset
Both the DMA controller and a DMA channel can be reset from the user software. When the DMA controller is reset, all
registers associated with the DMA controller, including channels, are cleared. A software reset can be done only when
the DMA controller is disabled.
When a DMA channel is reset, all registers associated with the DMA channel are cleared. A software reset can be done
only when the DMA channel is disabled.
5.11 Protection
In order to ensure safe operation, some of the channel registers are protected during a transaction. When the DMA
channel busy flag (CHnBUSY) is set for a channel, the user can modify only the following registers and bits:
z CTRL register
z INTFLAGS register
z TEMP registers
z CHEN, CHRST, TRFREQ, and REPEAT bits of the channel CTRL register
z TRIGSRC register
5.12 Interrupts
The DMA controller can generate interrupts when an error is detected on a DMA channel or when a transaction is
complete for a DMA channel. Each DMA channel has a separate interrupt vector, and there are different interrupt flags
for error and transaction complete.
If repeat is not enabled, the transaction complete flag is set at the end of the block transfer. If unlimited repeat is enabled,
the transaction complete flag is also set at the end of each block transfer.
XMEGA B [MANUAL] 51
8291C–AVR–09/2014
5.13 Register Description – DMA Controller
5.13.1 CTRL – Control register
z Bit 7 – ENABLE: Enable
Setting this bit enables the DMA controller. If the DMA controller is enabled and this bit is written to zero, the ENABLE bit
is not cleared before the internal transfer buffer is empty, and the DMA data transfer is aborted.
z Bit 6 – RESET: Software Reset
Writing a one to RESET will be ignored as long as DMA is enabled (ENABLE = 1). This bit can be set only when the DMA
controller is disabled (ENABLE = 0).
z Bit 5:3 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 2 – DBUFMODE: Double Buffer Mode
This bit enables the double buffer mode.
z Bit 1 – Reserved
This bit is unused and reserved for future use. For compatibility with future devices, always write this bits to zero when
this register is written.
z Bit 0 – PRIMODE: Channel Priority Mode
This bit determines the internal channel priority according to Table 5-1.
Table 5-1. Channel priority settings
5.13.2 INTFLAGS – Interrupt Status register
z Bit 7:6 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
Bit 7 6 5 4 3 2 1 0
+0x00 ENABLE RESET – – – DBUFMODE – PRIMODE
Read/Write R/W R/W R R R R/W R R/W
Initial Value 0 0 0 0 0 0 0 0
PRIMODE Group Configuration Description
0 RR01 Round robin
1 CH01 Channel0 has priority
Bit 7 6 5 4 3 2 1 0
+0x03 – – CH1ERRIF CH0ERRIF – – CH1TRNFIF CH0TRNFIF
Read/Write R R R/W R/W R R R/W R/W
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 52
8291C–AVR–09/2014
z Bit 5:4 – CHnERRIF[1:0]: Channel n Error Interrupt Flag
If an error condition is detected on DMA channel n, the CHnERRIF flag will be set. Writing a one to this bit location will
clear the flag.
z Bit 3:2 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 1:0 – CHnTRNFIF[1:0]: Channel n Transaction Complete Interrupt Flag
When a transaction on channel n has been completed, the CHnTRFIF flag will be set. If unlimited repeat count is
enabled, this flag is read as one after each block transfer. Writing a one to this bit location will clear the flag.
5.13.3 STATUS – Status register
z Bit 7:6 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 5:4 – CHnBUSY[1:0]: Channel Busy
When channel n starts a DMA transaction, the CHnBUSY flag will be read as one. This flag is automatically cleared when
the DMA channel is disabled, when the channel n transaction complete interrupt flag is set, or if the DMA channel n error
interrupt flag is set.
z Bit 3:2 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written
z Bit 1:0 – CHnPEND[1:0]: Channel Pending
If a block transfer is pending on DMA channel n, the CHnPEND flag will be read as one. This flag is automatically cleared
when the block transfer starts or if the transfer is aborted.
5.13.4 TEMPL – Temporary register Low
z Bit 7:0 – TEMP[7:0]: Temporary register 0
This register is used when reading 16- and 24-bit registers in the DMA controller. Byte 1 of the 16/24-bit register is stored
here when it is written by the CPU. Byte 1 of the 16/24-bit register is stored when byte 0 is read by the CPU. This register
can also be read and written from the user software.
Reading and writing 16- and 24-bit registers requires special attention. For details, refer to “Accessing 16-bit Registers”
on page 13.
Bit 7 6 5 4 3 2 1 0
+0x04 – – CH1BUSY CH0BUSY – – CH1PEND CH0PEND
Read/Write R R R R R R R R
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
+0x06 TEMP[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 53
8291C–AVR–09/2014
5.13.5 TEMPH – Temporary Register High
z Bit 7:0 – TEMP[15:8]: Temporary Register
This register is used when reading and writing 24-bit registers in the DMA controller. Byte 2 of the 24-bit register is stored
when it is written by the CPU. Byte 2 of the 24-bit register is stored here when byte 1 is read by the CPU. This register
can also be read and written from the user software.
Reading and writing 24-bit registers requires special attention. For details, refer to “Accessing 16-bit Registers” on page
13.
5.14 Register Description – DMA Channel
5.14.1 CTRLA – Control register A
z Bit 7 – ENABLE: Channel Enable
Setting this bit enables the DMA channel. This bit is automatically cleared when the transaction is completed. If the DMA
channel is enabled and this bit is written to zero, the CHEN bit is not cleared until the internal transfer buffer is empty and
the DMA transfer is aborted.
z Bit 6 – RESET: Software Reset
Setting this bit will reset the DMA channel. It can only be set when the DMA channel is disabled (CHEN = 0). Writing a
one to this bit will be ignored as long as the channel is enabled (CHEN=1). This bit is automatically cleared when reset is
completed.
z Bit 5 – REPEAT: Repeat Mode
Setting this bit enables the repeat mode. In repeat mode, this bit is cleared by hardware at the beginning of the last block
transfer. The REPCNT register should be configured before setting the REPEAT bit.
z Bit 4 – TRFREQ: Transfer Request
Setting this bit requests a data transfer on the DMA channel. This bit is automatically cleared at the beginning of the data
transfer. Writing this bit does not have any effect unless the channel is enabled.
z Bit 3 – Reserved
This bit is unused and reserved for future use. For compatibility with future devices, always write this bit to zero when this
register is written.
z Bit 2 – SINGLE: Single-Shot Data transfer
Setting this bit enables the single-shot mode. The channel will then do a burst transfer of BURSTLEN bytes on the
transfer trigger. A write to this bit will be ignored while the channel is enabled.
Bit 7 6 5 4 3 2 1 0
+0x07 TEMP[15:8]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 00000000
Bit 7 6 5 4 3 2 1 0
+0x00 ENABLE RESET REPEAT TRFREQ – SINGLE BURSTLEN[1:0]
Read/Write R/W R/W R/W R/W R R/W R/W R/W
Initial Value 0 0 000000
XMEGA B [MANUAL] 54
8291C–AVR–09/2014
z Bit 1:0 – BURSTLEN[1:0]: Burst Mode
These bits decide the DMA channel burst mode according to Table 5-2 on page 54. These bits cannot be changed if the
channel is busy.
Table 5-2. DMA channel burst mode
Table 5-3. Summary of triggers, transaction complete flag and channel disable according to DMA channel
configuration.
5.14.2 CTRLB – Control register B
z Bit 7 – CHBUSY: Channel Busy
When the DMA channel starts a DMA transaction, the CHBUSY flag will be read as one. This flag is automatically
cleared when the DMA channel is disabled, when the channel transaction complete interrupt flag is set or when the
channel error interrupt flag is set.
BURSTLEN[1:0] Group Configuration Description
00 1BYTE 1 byte burst mode
01 2BYTE 2 bytes burst mode
10 4BYTE 4 bytes burst mode
11 8BYTE 8 bytes burst mode
REPEAT SINGLE REPCNT Trigger Flag Set After Channel Disabled After
0 0 0 Block 1 block 1 block
0 0 1 Block 1 block 1 block
0 0 n > 1 Block 1 block 1 block
0 1 0 BURSTLEN 1 block 1 block
0 1 1 BURSTLEN 1 block 1 block
0 1 n > 1 BURSTLEN 1 block 1 block
1 0 0 Block Each block Each block
1 0 1 Transaction 1 block 1 block
1 0 n > 1 Transaction n blocks n blocks
1 1 0 BURSTLEN Each block Never
1 1 1 BURSTLEN 1 block 1 block
1 1 n > 1 BURSTLEN n blocks n blocks
Bit 7 6 5 4 3 2 1 0
+0x01 CHBUSY CHPEND ERRIF TRNIF ERRINTLVL[1:0] TRNINTLVL[1:0]
Read/Write R R R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 55
8291C–AVR–09/2014
z Bit 6 – CHPEND: Channel Pending
If a block transfer is pending on the DMA channel, the CHPEND flag will be read as one. This flag is automatically
cleared when the transfer starts or if the transfer is aborted.
z Bit 5 – ERRIF: Error Interrupt Flag
If an error condition is detected on the DMA channel, the ERRIF flag will be set and the optional interrupt is generated.
Since the DMA channel error interrupt shares the interrupt address with the DMA channel n transaction complete
interrupt, ERRIF will not be cleared when the interrupt vector is executed. This flag is cleared by writing a one to this
location.
z Bit 4 – TRNIF: Channel n Transaction Complete Interrupt Flag
When a transaction on the DMA channel has been completed, the TRNIF flag will be set and the optional interrupt is
generated. When repeat is not enabled, the transaction is complete and TRNIFR is set after the block transfer. When
unlimited repeat is enabled, TRNIF is also set after each block transfer.
Since the DMA channel transaction n complete interrupt shares the interrupt address with the DMA channel error
interrupt, TRNIF will not be cleared when the interrupt vector is executed. This flag is cleared by writing a one to this
location.
z Bit 3:2 – ERRINTLVL[1:0]: Channel Error Interrupt Level
These bits enable the interrupt for DMA channel transfer errors and select the interrupt level, as described in “Interrupts
and Programmable Multilevel Interrupt Controller” on page 115. The enabled interrupt will trigger for the conditions when
ERRIF is set.
z Bit 1:0 – TRNINTLVL[1:0]: Channel Transaction Complete Interrupt Level
These bits enable the interrupt for DMA channel transaction completes and select the interrupt level, as described in
“Interrupts and Programmable Multilevel Interrupt Controller” on page 115. The enabled interrupt will trigger for the
conditions when TRNIF is set.
5.14.3 ADDRCTRL – Address Control register
z Bit 7:6 – SRCRELOAD[1:0]: Channel Source Address Reload
These bits decide the DMA channel source address reload according to Table 5-4. A write to these bits is ignored while
the channel is busy.
Table 5-4. DMA channel source address reload settings
Bit 7 6 5 4 3 2 1 0
+0x02 SRCRELOAD[1:0] SRCDIR[1:0] DESTRELOAD[1:0] DESTDIR[1:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0000000
SRCRELOAD[1:0] Group Configuration Description
00 NONE No reload performed.
01 BLOCK DMA source address register is reloaded with initial value at end
of each block transfer.
10 BURST DMA source address register is reloaded with initial value at end
of each burst transfer.
11 TRANSACTION DMA source address register is reloaded with initial value at end
of each transaction.
XMEGA B [MANUAL] 56
8291C–AVR–09/2014
z Bit 5:4 – SRCDIR[1:0]: Channel Source Address Mode
These bits decide the DMA channel source address mode according to Table 5-5. These bits cannot be changed if the
channel is busy.
Table 5-5. DMA channel source address mode settings.
z Bit 3:2 – DESTRELOAD[1:0]: Channel Destination Address Reload
These bits decide the DMA channel destination address reload according to Table 5-6. These bits cannot be changed if
the channel is busy.
Table 5-6. DMA channel destination address reload settings
z Bit 1:0 – DESTDIR[1:0]: Channel Destination Address Mode
These bits decide the DMA channel destination address mode according to Table 5-7. These bits cannot be changed if
the channel is busy.
Table 5-7. DMA channel destination address mode settings
SRCDIR[1:0] Group Configuration Description
00 FIXED Fixed
01 INC Increment
10 DEC Decrement
11 - Reserved
DESTRELOAD[1:0] Group Configuration Description
00 NONE No reload performed.
01 BLOCK DMA channel destination address register is reloaded with
initial value at end of each block transfer.
10 BURST DMA channel destination address register is reloaded with
initial value at end of each burst transfer.
11 TRANSACTION DMA channel destination address register is reloaded with
initial value at end of each transaction.
DESTDIR[1:0] Group Configuration Description
00 FIXED Fixed
01 INC Increment
10 DEC Decrement
11 - Reserved
XMEGA B [MANUAL] 57
8291C–AVR–09/2014
5.14.4 TRIGSRC – Trigger Source
z Bit 7:0 – TRIGSRC[7:0]: Channel Trigger Source Select
These bits select which trigger source is used for triggering a transfer on the DMA channel. A zero value means that the
trigger source is disabled. For each trigger source, the value to put in the TRIGSRC register is the sum of the module’s or
peripheral’s base value and the offset value for the trigger source in the module or peripheral. Table 5-8 on page 57
shows the base value for all modules and peripherals. Table 5-9 on page 58 to Table 5-11 on page 58 shows the offset
value for the trigger sources in the different modules and peripheral types. For modules or peripherals which do not exist
for a device, the transfer trigger does not exist. Refer to the device datasheet for the list of peripherals available.
If the interrupt flag related to the trigger source is cleared or the interrupt level enabled so that an interrupt is triggered,
the DMA request will be lost. Since a DMA request can clear the interrupt flag, interrupts can be lost.
Note: For most trigger sources, the request is cleared by accessing a register belonging to the peripheral with the request. Refer to the different
peripheral chapters for how requests are generated and cleared.
Table 5-8. DMA trigger source base values for all modules and peripherals.
Bit 7 6 5 4 3 2 1 0
+0x03 TRIGSRC[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
TRIGSRC Base Value Group Configuration Description
0x00 OFF Software triggers only
0x01 SYS Event system DMA triggers base value
0x04 AES AES DMA trigger value
0x10 ADCA ADCA DMA trigger value
0x40 TCC0 Timer/counter C0 DMA triggers base value
0x46 TCC1 Timer/counter C1 triggers base value
0x4A SPIC SPI C DMA trigger value
0x4B USARTC0 USART C0 DMA triggers base value
0x60 TCD0 Timer/counter D0 DMA triggers base value
0x6A SPID SPI D DMA triggers value
0x6B USARTD0 USART D0 DMA triggers base value
0x80 TCE0 Timer/counter E0 DMA triggers base value
0x8B USARTE0 USART E0 DMA triggers base value
0xA0 TCF0 Timer/counter F0 DMA triggers base value
0xAB USARTF0 USART F0 DMA triggers base value
XMEGA B [MANUAL] 58
8291C–AVR–09/2014
Note: 1. CC channel C and D triggers are available only for timer/counters 0.
The group configuration is the “base_offset;” for example, TCC1_CCA for the timer/counter C1 CC channel A the transfer
trigger.
5.14.5 TRFCNTL – Channel Block Transfer Count register Low
The TRFCNTH and TRFCNTL register pair represents the 16-bit value TRFCNT. TRFCNT defines the number of bytes
in a block transfer. The value of TRFCNT is decremented after each byte read by the DMA channel. When TRFCNT
reaches zero, the register is reloaded with the last value written to it.
z Bit 7:0 – TRFCNT[7:0]: Channel n Block Transfer Count low byte
These bits hold the LSB of the 16-bit block transfer count.
The default value of this register is 0x1. If a user writes 0x0 to this register and fires a DMA trigger, DMA will be doing
0xFFFF transfers.
Table 5-9. DMA trigger source offset values for event system triggers.
TRGSRC Offset Value Group Configuration Description
+0x00 CH0 Event channel 0
+0x01 CH1 Event channel 1
+0x02 CH2 Event channel 2
Table 5-10. DMA trigger source offset values for timer/ counter triggers.
TRGSRC Offset Value Group Configuration Description
+0x00 OVF Overflow/underflow
+0x01 ERR Error
+0x02 CCA Compare or capture channel A
+0x03 CCB Compare or capture channel B
+0x04 CCC(1) Compare or capture channel C
+0x05 CCD(1) Compare or capture channel D
Table 5-11. DMA trigger source offset values for USART triggers.
TRGSRC Offset Value Group Configuration Description
0x00 RXC Receive complete
0x01 DRE Data register empty
Bit 7 6 5 4 3 2 1 0
+0x04 TRFCNT[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 00000000
XMEGA B [MANUAL] 59
8291C–AVR–09/2014
5.14.6 TRFCNTH – Channel Block Transfer Count register High
Reading and writing 16-bit values requires special attention. For details, refer to “Accessing 16-bit Registers” on page 13.
z Bit 7:0 – TRFCNT[15:8]: Channel n Block Transfer Count high byte
These bits hold the MSB of the 16-bit block transfer count.
The default value of this register is 0x1. If a user writes 0x0 to this register and fires a DMA trigger, DMA will be doing
0xFFFF transfers.
5.14.7 REPCNT – Repeat Counter register
REPCNT counts how many times a block transfer is performed. For each block transfer, this register will be
decremented.
When repeat mode is enabled (see REPEAT bit in “ADDRCTRL – Address Control register” on page 55), this register is
used to control when the transaction is complete. The counter is decremented after each block transfer if the DMA has to
serve a limited number of repeated block transfers. When repeat mode is enabled, the channel is disabled when
REPCNT reaches zero and the last block transfer is completed. Unlimited repeat is achieved by setting this register to
zero.
5.14.8 SRCADDR0 – Source Address 0
SRCADDR0, SRCADDR1, and SRCADDR2 represent the 24-bit value SRCADDR, which is the DMA channel source
address. SRCADDR2 is the most significant byte in the register. SRCADDR may be automatically incremented or
decremented based on settings in the SRCDIR bits in “ADDRCTRL – Address Control register” on page 55.
z Bit 7:0 – SRCADDR[7:0]: Channel Source Address byte 0
These bits hold byte 0 of the 24-bit source address.
Bit 7 6 5 4 3 2 1 0
+0x05 TRFCNT[15:8]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 00000
Bit 7 6 5 4 3 2 1 0
+0x06 REPCNT[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 000000
Bit 7 6 5 4 3 2 1 0
+0x08 SRCADDR[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 60
8291C–AVR–09/2014
5.14.9 SRCADDR1 – Channel Source Address 1
z Bit 7:0 – SRCADDR[15:8]: Channel Source Address byte 1
These bits hold byte 1 of the 24-bit source address.
5.14.10 SRCADDR2 – Channel Source Address 2
Reading and writing 24-bit values require special attention. For details, refer to “Accessing 24- and 32-bit Registers” on
page 13.
z Bit 7:0 – SRCADDR[23:16]: Channel Source Address byte 2
These bits hold byte 2 of the 24-bit source address.
5.14.11 DESTADDR0 – Channel Destination Address 0
DESTADDR0, DESTADDR1, and DESTADDR2 represent the 24-bit value DESTADDR, which is the DMA channel
destination address. DESTADDR2 holds the most significant byte in the register. DESTADDR may be automatically
incremented or decremented based on settings in the DESTDIR bits in “ADDRCTRL – Address Control register” on page
55.
z Bit 7:0 – DESTADDR[7:0]: Channel Destination Address byte 0
These bits hold byte 0 of the 24-bit source address.
Bit 7 6 5 4 3 2 1 0
+0x09 SRCADDR[15:8]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 00000
Bit 7 6 5 4 3 2 1 0
+0x0A SRCADDR[23:16]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
+0x0C DESTADDR[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 00000000
XMEGA B [MANUAL] 61
8291C–AVR–09/2014
5.14.12 DESTADDR1 – Channel Destination Address 1
z Bit 7:0 – DESTADDR[15:8]: Channel Destination Address byte 1
These bits hold byte 1 of the 24-bit source address.
5.14.13 DESTADDR2 – Channel Destination Address 2
Reading and writing 24-bit values require special attention. For details, refer to “Accessing 24- and 32-bit Registers” on
page 13.
z Bit 7:0 – DESTADDR[23:16]: Channel Destination Address byte 2
These bits hold byte 2 of the 24-bit source address.
Bit 7 6 5 4 3 2 1 0
+0x0D DESTADDR[15:8]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
+0x0E DESTADDR[23:16]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 62
8291C–AVR–09/2014
5.15 Register Summary – DMA Controller
5.16 Register Summary – DMA Channel
5.17 DMA Interrupt Vector Summary
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
+0x00 CTRL ENABLE RESET – – – DBUFMODE – PRIMODE 51
+0x01 Reserved – – – – – – – –
+0x02 Reserved – – – – – – – –
+0x03 INTFLAGS – – CH1ERRIF CH0ERRIF – – CH1TRNFIF CH0TRNFIF 51
+0x04 STATUS – – CH1BUSY CH0BUSY – – CH1PEND CH0PEND 52
+0x05 Reserved – – – – – – – –
+0x06 TEMPL TEMP[7:0] 52
+0x07 TEMPH TEMP[15:8] 53
+0x10 CH0 Offset Offset address for DMA Channel 0
+0x20 CH1 Offset Offset address for DMA Channel 1
+0x30 Reserved – – – – – – – –
+0x40 Reserved – – – – – – – –
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
+0x00 CTRLA ENABLE RESET REPEAT TRFREQ – SINGLE BURSTLEN[1:0] 53
+0x01 CTRLB CHBUSY CHPEND ERRIF TRNIF ERRINTLVL[1:0] TRNINTLVL[1:0] 54
+0x02 ADDCTRL SRCRELOAD[1:0] SRCDIR[1:0] DESTRELOAD[1:0] DESTDIR[1:0] 55
+0x03 TRIGSRC TRIGSRC[7:0] 57
+0x04 TRFCNTL TRFCNT[7:0] 58
+0x05 TRFCNTH TRFCNT[15:8] 59
+0x06 REPCNT REPCNT[7:0] 59
+0x07 Reserved – – – – – – – –
+0x08 SRCADDR0 SRCADDR[7:0] 59
+0x09 SRCADDR1 SRCADDR[15:8] 60
+0x0A SRCADDR2 SRCADDR[23:16] 60
+0x0B Reserved – – – – – – – –
+0x0C DESTADDR0 DESTADDR[7:0] 60
+0x0D DESTADDR1 DESTADDR[15:8] 61
+0x0E DESTADDR2 DESTADDR[23:16] 61
+0x0F Reserved – – – – – – – –
Offset Source Interrupt Description
0x00 CH0_vect DMA controller channel 0 interrupt vector
0x02 CH1_vect DMA controller channel 1 interrupt vector
XMEGA B [MANUAL] 63
8291C–AVR–09/2014
6. Event System
6.1 Features
z System for direct peripheral-to-peripheral communication and signaling
z Peripherals can directly send, receive, and react to peripheral events
z CPU and DMA controller independent operation
z 100% predictable signal timing
z Short and guaranteed response time
z Four event channels for up to eight different and parallel signal routings and configurations
z Events can be sent and/or used by most peripherals, clock system, and software
z Additional functions include
z Quadrature decoders
z Digital filtering of I/O pin state
z Works in active mode and idle sleep mode
6.2 Overview
The event system enables direct peripheral-to-peripheral communication and signaling. It allows a change in one
peripheral’s state to automatically trigger actions in other peripherals. It is designed to provide a predictable system for
short and predictable response times between peripherals. It allows for autonomous peripheral control and interaction
without the use of interrupts CPU or DMA controller resources, and is thus a powerful tool for reducing the complexity,
size and execution time of application code. It also allows for synchronized timing of actions in several peripheral
modules.
A change in a peripheral’s state is referred to as an event, and usually corresponds to the peripheral’s interrupt
conditions. Events can be directly passed to other peripherals using a dedicated routing network called the event routing
network. How events are routed and used by the peripherals is configured in software.
Figure 6-1 on page 64 shows a basic diagram of all connected peripherals. The event system can directly connect
together analog converters, analog comparators, I/O port pins, the real-time counter, timer/counters, IR communication
module (IRCOM) and USB interface. It can also be used to trigger DMA transactions (DMA controller). Events can also
be generated from software and the peripheral clock.
XMEGA B [MANUAL] 64
8291C–AVR–09/2014
Figure 6-1. Event system overview and connected peripherals.
The event routing network consists of four software-configurable multiplexers that control how events are routed and
used. These are called event channels, and allow for up to four parallel event configurations and routings. The maximum
routing latency is two peripheral clock cycles. The event system works in both active mode and idle sleep mode.
6.3 Events
In the context of the event system, an indication that a change of state within a peripheral has occurred is called an
event. There are two main types of events: signaling events and data events. Signaling events only indicate a change of
state while data events contain additional information about the event.
The peripheral from which the event originates is called the event generator. Within each peripheral (for example, a
timer/counter), there can be several event sources, such as a timer compare match or timer overflow. The peripheral
using the event is called the event user, and the action that is triggered is called the event action.
Timer /
Counters
USB
ADC Real Time
Counter
Port pins
CPU /
Software
DMA
Controller
IRCOM
Event Routing Network
Event
System
Controller
clkPER
Prescaler
AC
XMEGA B [MANUAL] 65
8291C–AVR–09/2014
Figure 6-2. Example of event source, generator, user, and action.
Events can also be generated manually in software.
6.3.1 Signaling Events
Signaling events are the most basic type of event. A signaling event does not contain any information apart from the
indication of a change in a peripheral. Most peripherals can only generate and use signaling events. Unless otherwise
stated, all occurrences of the word ”event” are to be understood as meaning signaling events.
6.3.2 Data Events
Data events differ from signaling events in that they contain information that event users can decode to decide event
actions based on the receiver information.
Although the event routing network can route all events to all event users, those that are only meant to use signaling
events do not have decoding capabilities needed to utilize data events. How event users decode data events is shown in
Table 6-1 on page 66.
Event users that can utilize data events can also use signaling events. This is configurable, and is described in the
datasheet module for each peripheral.
6.3.3 Peripheral Clock Events
Each event channel includes a peripheral clock prescaler with a range from 1 (no prescaling) to 32768. This enables
configurable periodic event generation based on the peripheral clock. It is possible to periodically trigger events in a
peripheral or to periodically trigger synchronized events in several peripherals. Since each event channel include a
prescaler, different peripherals can receive triggers with different intervals.
6.3.4 Software Events
Events can be generated from software by writing the DATA and STROBE registers. The DATA register must be written
first, since writing the STROBE register triggers the operation. The DATA and STROBE registers contain one bit for each
event channel. Bit n corresponds to event channel n. It is possible to generate events on several channels at the same
time by writing to several bit locations at once.
Software-generated events last for one clock cycle and will overwrite events from other event generators on that event
channel during that clock cycle.
Table 6-1 on page 66 shows the different events, how they can be manually generated, and how they are decoded.
Event User
Event
Routing
Network |
Compare Match
Over-/Underflow
Error
Timer/Counter
Syncsweep
Single
Conversion
ADC
Event Generator
Event Source Event Action
Event Action Selection
XMEGA B [MANUAL] 66
8291C–AVR–09/2014
Table 6-1. Manually generated events and decoding of events.
6.4 Event Routing Network
The event routing network routes the events between peripherals. It consists of eight multiplexers (CHnMUX), which can
each be configured to route any event source to any event users. The output from a multiplexer is referred to as an event
channel. For each peripheral, it is selectable if and how incoming events should trigger event actions. Details on
configurations can be found in the datasheet for each peripheral. The event routing network is shown in Figure 6-3 on
page 67.
STROBE DATA Data Event User Signaling Event User
0 0 No event No event
0 1 Data event 01 No event
1 0 Data event 02 Signaling event
1 1 Data event 03 Signaling event
XMEGA B [MANUAL] 67
8291C–AVR–09/2014
Figure 6-3. Event routing network.
Four multiplexers means that it is possible to route up to four events at the same time. It is also possible to route one
event through several multiplexers.
Not all XMEGA devices contain all peripherals. This only means that a peripheral is not available for generating or using
events. The network configuration itself is compatible between all devices.
6.5 Event Timing
An event normally lasts for one peripheral clock cycle, but some event sources, such as a low level on an I/O pin, will
generate events continuously. Details on this are described in the datasheet for each peripheral, but unless otherwise
stated, an event lasts for one peripheral clock cycle.
(48)
PORTA
PORTB
PORTC
PORTD
PORTE
PORTF
ADCA
TCF0 (6)
TCE0
TCD0
TCC0
TCC1
(6)
(4)
(4)
(4)
(4)
(10)
(6)
(29)
(4)
(4)
(4)
RTC
ClkPER
(8)
(8)
(8)
(8)
(8)
(8)
CH0MUX[7:0]
CH1MUX[7:0]
CH2MUX[7:0]
CH3MUX[7:0]
CH0CTRL[7:0]
CH1CTRL[7:0]
CH2CTRL[7:0]
CH3CTRL[7:0]
Event Channel 3
Event Channel 2
Event Channel 1
Event Channel 0
(6)
(16)
(2)
ACA (3)
USB (4)
XMEGA B [MANUAL] 68
8291C–AVR–09/2014
It takes a maximum of two peripheral clock cycles from when an event is generated until the event actions in other
peripherals are triggered. This ensures short and 100% predictable response times, independent of CPU or DMA
controller load or software revisions.
6.6 Filtering
Each event channel includes a digital filter. When this is enabled, an event must be sampled with the same value for a
configurable number of system clock cycles before it is accepted. This is primarily intended for pin change events.
6.7 Quadrature Decoder
The event system includes one quadrature decoder (QDEC), which enable the device to decode quadrature input on I/O
pins and send data events that a timer/counter can decode to count up, count down, or index/reset. Table 6-2
summarizes which quadrature decoder data events are available, how they are decoded, and how they can be
generated. The QDEC and related features, control and status registers are available for event channel 0.
Table 6-2. Quadrature decoder data events.
6.7.1 Quadrature Operation
A quadrature signal is characterized by having two square waves that are phase shifted 90 degrees relative to each
other. Rotational movement can be measured by counting the edges of the two waveforms. The phase relationship
between the two square waves determines the direction of rotation.
Figure 6-4. Quadrature signals from a rotary encoder.
Figure 6-4 shows typical quadrature signals from a rotary encoder. The signals QDPH0 and QDPH90 are the two
quadrature signals. When QDPH90 leads QDPH0, the rotation is defined as positive or forward. When QDPH0 leads
QDPH90, the rotation is defined as negative or reverse. The concatenation of the two phase signals is called the
quadrature state or the phase state.
STROBE DATA Data Event User Signaling Event User
0 0 No event No event
0 1 Index/reset No event
1 0 Count down Signaling event
1 1 Count up Signaling event
XMEGA B [MANUAL] 69
8291C–AVR–09/2014
In order to know the absolute rotary displacement, a third index signal (QINDX) can be used. This gives an indication
once per revolution.
6.7.2 QDEC Setup
For a full QDEC setup, the following is required:
z Tho or three I/O port pins for quadrature signal input
z Two event system channels for quadrature decoding
z One timer/counter for up, down, and optional index count
The following procedure should be used for QDEC setup:
1. Choose two successive pins on a port as QDEC phase inputs.
2. Set the pin direction for QDPH0 and QDPH90 as input.
3. Set the pin configuration for QDPH0 and QDPH90 to low level sense.
4. Select the QDPH0 pin as a multiplexer input for an event channel, n.
5. Enable quadrature decoding and digital filtering in the event channel.
6. Optional:
1. Set up a QDEC index (QINDX).
2. Select a third pin for QINDX input.
3. Set the pin direction for QINDX as input.
4. Set the pin configuration for QINDX to sense both edges.
5. Select QINDX as a multiplexer input for event channel n+1
6. Set the quadrature index enable bit in event channel n+1.
7. Select the index recognition mode for event channel n+1.
7. Set quadrature decoding as the event action for a timer/counter.
8. Select event channel n as the event source for the timer/counter.
z Set the period register of the timer/counter to ('line count' * 4 - 1), the line count of the quadrature encoder.
z Enable the timer/counter without clock prescaling.
The angle of a quadrature encoder attached to QDPH0, QDPH90 (and QINDX) can now be read directly from the
timer/counter count register. If the count register is different from BOTTOM when the index is recognized, the
timer/counter error flag is set. Similarly, the error flag is set if the position counter passes BOTTOM without the
recognition of the index.
XMEGA B [MANUAL] 70
8291C–AVR–09/2014
6.8 Register Description
6.8.1 CHnMUX – Event Channel n Multiplexer register
z Bit 7:0 – CHnMUX[7:0]: Channel Multiplexer
These bits select the event source according to Table 6-3. This table is valid for all XMEGA devices regardless of
whether the peripheral is present or not. Selecting event sources from peripherals that are not present will give the same
result as when this register is zero. When this register is zero, no events are routed through. Manually generated events
will override CHnMUX and be routed to the event channel even if this register is zero.
Table 6-3. CHnMUX[7:0] bit settings.
Bit 7 6 5 4 3 2 1 0
CHnMUX[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 00000000
CHnMUX[7:4] CHnMUX[3:0] Group Configuration Event Source
0000 0 0 0 0 None (manually generated events only)
0000 0 0 0 1 (Reserved)
0000 0 0 1 X (Reserved)
0000 0 1 X X (Reserved)
0000 1 0 0 0 RTC_OVF RTC overflow
0000 1 0 0 1 RTC_CMP RTC compare match
0000 1 0 1 0
USB start of frame on CH0(2)
USB error on CH1(2)
USB overflow on CH2(2)
USB setup on CH3(2)
0000 1 0 1 X (Reserved)
0000 1 1 X X (Reserved)
0001 0 0 0 0 ACA_CH0 ACA channel 0
0001 0 0 0 1 ACA_CH1 ACA channel 1
0001 0 0 1 0 ACA_WIN ACA window
0001 0 0 1 1 (Reserved)
0001 0 1 X X (Reserved)
0001 1 X X X (Reserved)
0010 0 0 0 0 ADCA_CH0 ADCA
0010 0 0 0 1 (Reserved)
0010 0 0 1 X (Reserved)
0010 0 1 X X (Reserved)
XMEGA B [MANUAL] 71
8291C–AVR–09/2014
Notes: 1. The description of how the ports generate events is described in “Port Event” on page 130.
2. The different USB events can be selected for only event channel, 0 to 3.
Table 6-4. Timer/counter events
0010 1 X X X (Reserved)
0011 X X X X (Reserved)
0100 X X X X (Reserved)
0101 0 n PORTA_PINn(1) PORTA pin n (n= 0, 1, 2 ... or 7)
0101 1 n PORTB_PINn(1) PORTB pin n (n= 0, 1, 2 ... or 7)
0110 0 n PORTC_PINn(1) PORTC pin n (n= 0, 1, 2 ... or 7)
0110 1 n PORTD_PINn(1) PORTD pin n (n= 0, 1, 2 ... or 7)
0111 0 n PORTE_PINn(1) PORTE pin n (n= 0, 1, 2 ... or 7)
0111 1 n PORTF_PINn(1) PORTF pin n (n= 0, 1, 2 ... or 7)
1000 M PRESCALER_M ClkPER divide by 2M (M=0 to 15)
1001 X X X X (Reserved)
1010 X X X X (Reserved)
1011 X X X X (Reserved)
1100 0 E See Table 6-4 Timer/counter C0 event type E
1100 1 E See Table 6-4 Timer/counter C1 event type E
1101 0 E See Table 6-4 Timer/counter D0 event type E
1111 1 X X X (Reserved)
1110 0 E See Table 6-4 Timer/counter E0 event type E
1111 1 X X X (Reserved)
1111 0 E See Table 6-4 Timer/counter F0 event type E
1111 1 X X X (Reserved)
T/C Event E Group Configuration Event Type
0 0 0 TCxn_OVF Over/Underflow (x = C, D, E or F) (n= 0 or 1)
0 0 1 TCxn_ERR Error (x = C, D, E or F) (n= 0 or 1)
0 1 X – (Reserved)
1 0 0 TCxn_CCA Capture or compare A (x = C, D, E or F) (n= 0 or 1)
1 0 1 TCxn_CCB Capture or compare B (x = C, D, E or F) (n= 0 or 1)
1 1 0 TCxn_CCC Capture or compare C (x = C, D, E or F) (n= 0)
1 1 1 TCxn_CCD Capture or compare D (x = C, D, E or F) (n= 0)
CHnMUX[7:4] CHnMUX[3:0] Group Configuration Event Source
XMEGA B [MANUAL] 72
8291C–AVR–09/2014
6.8.2 CHnCTRL – Event Channel n Control register
Note: 1. Only available for CH0CTRL and CH2CTRL. These bits are reserved in CH1CTRL and CH3CTRL.
z Bit 7 – Reserved
This bit is reserved and will always be read as zero. For compatibility with future devices, always write this bit to zero
when this register is written.
z Bit 6:5 – QDIRM[1:0]: Quadrature Decode Index Recognition Mode
These bits determine the quadrature state for the QDPH0 and QDPH90 signals, where a valid index signal is recognized
and the counter index data event is given according to Table 6-5. These bits should only be set when a quadrature
encoder with a connected index signal is used.These bits are available only for CH0CTRL and CH2CTRL.
Table 6-5. QDIRM bit settings.
z Bit 4 – QDIEN: Quadrature Decode Index Enable
When this bit is set, the event channel will be used as a QDEC index source, and the index data event will be enabled.
This bit is available only for CH0CTRL and CH2CTRL.
z Bit 3 – QDEN: Quadrature Decode Enable
Setting this bit enables QDEC operation.
This bit is available only for CH0CTRL and CH2CTRL.
z Bit 2:0 – DIGFILT[2:0]: Digital Filter Coefficient
These bits define the length of digital filtering used, according to Table 6-6 on page 72. Events will be passed through to
the event channel only when the event source has been active and sampled with the same level for the number of
peripheral clock cycles defined by DIGFILT.
Bit 7 6 5 4 3 2 1 0
– QDIRM[1:0](1) QDIEN(1) QDEN(1) DIGFILT[2:0]
– – – – – DIGFILT[2:0]
Read/Write R R/W R/W R/W R/W R/W R/W R
Initial Value 0 0 0 0 0 0 0 0
QDIRM[1:0] Index Recognition State
0 0 {QDPH0, QDPH90} = 0b00
0 1 {QDPH0, QDPH90} = 0b01
1 0 {QDPH0, QDPH90} = 0b10
1 1 {QDPH0, QDPH90} = 0b11
Table 6-6. Digital filter coefficient values .
DIGFILT[2:0] Group Configuration Description
000 1SAMPLE One sample
001 2SAMPLES Two samples
010 3SAMPLES Three samples
XMEGA B [MANUAL] 73
8291C–AVR–09/2014
6.8.3 STROBE – Strobe register
If the STROBE register location is written, each event channel will be set according to the STROBE[n] and corresponding
DATA[n] bit settings, if any are unequal to zero.
A single event lasting for one peripheral clock cycle will be generated.
6.8.4 DATA – Data register
This register contains the data value when manually generating a data event. This register must be written before the
STROBE register. For details, See ”STROBE – Strobe register” on page 73.
011 4SAMPLES Four samples
100 5SAMPLES Five samples
101 6SAMPLES Six samples
110 7SAMPLES Seven samples
111 8SAMPLES Eight samples
Table 6-6. Digital filter coefficient values (Continued).
DIGFILT[2:0] Group Configuration Description
Bit 7 6 5 4 3 2 1 0
+0x10 STROBE[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
+0x11 DATA[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 00000000
XMEGA B [MANUAL] 74
8291C–AVR–09/2014
6.9 Register Summary
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
+0x00 CH0MUX CH0MUX[7:0] 70
+0x01 CH1MUX CH1MUX[7:0] 70
+0x02 CH2MUX CH2MUX[7:0] 70
+0x03 CH3MUX CH3MUX[7:0] 70
+0x04 Reserved – – – – – – – –
+0x05 Reserved – – – – – – – –
+0x06 Reserved – – – – – – – –
+0x07 Reserved – – – – – – – –
+0x08 CH0CTRL – QDIRM[1:0] QDIEN QDEN DIGFILT[2:0] 72
+0x09 CH1CTRL – – – – – DIGFILT[2:0] 72
+0x0A CH2CTRL – QDIRM[1:0] QDIEN QDEN DIGFILT[2:0] 72
+0x0B CH3CTRL – – – – – DIGFILT[2:0] 72
+0x0C Reserved – – – – – – – –
+0x0D Reserved – – – – – – – –
+0x0E Reserved – – – – – – – –
+0x0F Reserved – – – – – – – –
+0x10 STROBE STROBE[7:0] 73
+0x11 DATA DATA[7:0] 73
XMEGA B [MANUAL] 75
8291C–AVR–09/2014
7. System Clock and Clock Options
7.1 Features
z Fast start-up time
z Safe run-time clock switching
z Internal oscillators:
z 32MHz run-time calibrated and tunable oscillator
z 2MHz run-time calibrated oscillator
z 32.768kHz calibrated oscillator
z 32kHz ultra low power (ULP) oscillator with 1kHz output
z External clock options
z 0.4MHz - 16MHz crystal oscillator
z 32.768kHz crystal oscillator
z External clock
z PLL with 20MHz - 128MHz output frequency
z Internal and external clock options and 1x to 31x multiplication
z Lock detector
z Clock prescalers with 1x to 2048x division
z Fast peripheral clocks running at 2 and 4 times the CPU clock
z Automatic run-time calibration of internal oscillators
z External oscillator and PLL lock failure detection with optional non-maskable interrupt
7.2 Overview
XMEGA devices have a flexible clock system supporting a large number of clock sources. It incorporates both accurate
internal oscillators and external crystal oscillator and resonator support. A high-frequency phase locked loop (PLL) and
clock prescalers can be used to generate a wide range of clock frequencies. A calibration feature (DFLL) is available,
and can be used for automatic run-time calibration of the internal oscillators to remove frequency drift over voltage and
temperature. An oscillator failure monitor can be enabled to issue a non-maskable interrupt and switch to the internal
oscillator if the external oscillator or PLL fails.
When a reset occurs, all clock sources except the 32kHz ultra low power oscillator are disabled. After reset, the device
will always start up running from the 2MHz internal oscillator. During normal operation, the system clock source and
prescalers can be changed from software at any time.
Figure 7-1 on page 76 presents the principal clock system in the XMEGA family of devices. Not all of the clocks need to
be active at a given time. The clocks for the CPU and peripherals can be stopped using sleep modes and power
reduction registers, as described in “Power Management and Sleep Modes” on page 94.
XMEGA B [MANUAL] 76
8291C–AVR–09/2014
Figure 7-1. The clock system, clock sources, and clock distribution.
Real Time
Counter Peripherals RAM AVR CPU Non-Volatile
Memory
Watchdog
Timer
Brown-out
Detector
System Clock Prescalers
USB
Prescaler
System Clock Multiplexer
(SCLKSEL)
PLLSRC
RTCSRC
DIV32
32 kHz
Int. ULP
32.768 kHz
Int. OSC
32.768 kHz
TOSC
2 MHz
Int. Osc
32 MHz
Int. Osc
0.4 – 16 MHz
XTAL
DIV32
DIV32
DIV4
XOSCSEL
PLL
USBSRC
TOSC1
TOSC2
XTAL1
XTAL2
clkSYS clkRTC
clkPER2
clkPER
clkCPU
clkPER4
clkUSB
XMEGA B [MANUAL] 77
8291C–AVR–09/2014
7.3 Clock Distribution
Figure 7-1 on page 76 presents the principal clock distribution system used in XMEGA devices.
7.3.1 System Clock - ClkSYS
The system clock is the output from the main system clock selection. This is fed into the prescalers that are used to
generate all internal clocks except the asynchronous and USB clocks.
7.3.2 CPU Clock - ClkCPU
The CPU clock is routed to the CPU and nonvolatile memory. Halting the CPU clock inhibits the CPU from executing
instructions.
7.3.3 Peripheral Clock - ClkPER
The majority of peripherals and system modules use the peripheral clock. This includes the DMA controller, event
system, interrupt controller, external bus interface and RAM. This clock is always synchronous to the CPU clock, but may
run even when the CPU clock is turned off.
7.3.4 Peripheral 2x/4x Clocks - ClkPER2/ClkPER4
Modules that can run at two or four times the CPU clock frequency can use the peripheral 2x and peripheral 4x clocks.
7.3.5 Asynchronous Clock - ClkRTC
The asynchronous clock allows the real-time counter (RTC) to be clocked directly from an external 32.768kHz crystal
oscillator or the 32 times prescaled output from the internal 32.768kHz oscillator or ULP oscillator. The dedicated clock
domain allows operation of this peripheral even when the device is in sleep mode and the rest of the clocks are stopped.
7.3.6 USB Clock - ClkUSB
The USB device module requires a 12MHz or 48MHz clock. It has a separate clock source selection in order to avoid
system clock source limitations when USB is used.
7.4 Clock Sources
The clock sources are divided in two main groups: internal oscillators and external clock sources. Most of the clock
sources can be directly enabled and disabled from software, while others are automatically enabled or disabled,
depending on peripheral settings. After reset, the device starts up running from the 2MHz internal oscillator. The other
clock sources, DFLLs and PLL, are turned off by default.
7.4.1 Internal Oscillators
The internal oscillators do not require any external components to run. For details on characteristics and accuracy of the
internal oscillators, refer to the device datasheet.
7.4.1.1 32kHz Ultra Low Power Oscillator
This oscillator provides an approximate 32kHz clock. The 32kHz ultra low power (ULP) internal oscillator is a very low
power clock source, and it is not designed for high accuracy.The oscillator employs a built-in prescaler that provides a
1kHz output, see “RTCCTRL – RTC Control register” on page 85 for details. The oscillator is automatically
enabled/disabled when it is used as clock source for any part of the device. This oscillator can be selected as the clock
source for the RTC.
7.4.1.2 32.768kHz Calibrated Oscillator
This oscillator provides an approximate 32.768kHz clock. It is calibrated during production to provide a default frequency
close to its nominal frequency. The calibration register can also be written from software for run-time calibration of the
oscillator frequency. The oscillator employs a built-in prescaler, which provides both a 32.768kHz output and a 1.024kHz
XMEGA B [MANUAL] 78
8291C–AVR–09/2014
output, see “RTCCTRL – RTC Control register” on page 85 for details.
7.4.1.3 32MHz Run-time Calibrated Oscillator
The 32MHz run-time calibrated internal oscillator is a high-frequency oscillator. It is calibrated during production to
provide a default frequency close to its nominal frequency. A digital frequency looked loop (DFLL) can be enabled for
automatic run-time calibration of the oscillator to compensate for temperature and voltage drift and optimize the oscillator
accuracy. This oscillator can also be adjusted and calibrated to any frequency between 30MHz and 55MHz. The
production signature row contains 48 MHz calibration values intended used when the oscillator is used a full-speed USB
clock source.
7.4.1.4 2MHz Run-time Calibrated Oscillator
The 2MHz run-time calibrated internal oscillator is the default system clock source after reset. It is calibrated during
production to provide a default frequency close to its nominal frequency. A DFLL can be enabled for automatic run-time
calibration of the oscillator to compensate for temperature and voltage drift and optimize the oscillator accuracy.
7.4.2 External Clock Sources
The XTAL1 and XTAL2 pins can be used to drive an external oscillator, either a quartz crystal or a ceramic resonator.
XTAL1 can be used as input for an external clock signal. The TOSC1 and TOSC2 pins is dedicated to driving a
32.768kHz crystal oscillator.
7.4.2.1 0.4MHz - 16MHz Crystal Oscillator
This oscillator can operate in four different modes optimized for different frequency ranges, all within 0.4MHz - 16MHz.
Figure 7-2 shows a typical connection of a crystal oscillator or resonator.
Figure 7-2. Crystal oscillator connection.
Two capacitors, C1 and C2, may be added to match the required load capacitance for the connected crystal.
7.4.2.2 External Clock Input
To drive the device from an external clock source, XTAL1 must be driven as shown in Figure 7-3 on page 78. In this
mode, XTAL2 can be used as a general I/O pin.
Figure 7-3. External clock drive configuration.
C1
C2
XTAL2
XTAL1
GND
General
Purpose
I/O
XTAL2
XTAL1
External
Clock
Signal
XMEGA B [MANUAL] 79
8291C–AVR–09/2014
7.4.2.3 32.768kHz Crystal Oscillator
A 32.768kHz crystal oscillator can be connected between the TOSC1 and TOSC2 pins and enables a dedicated low
frequency oscillator input circuit. A typical connection is shown in Figure 7-4 on page 79. A low power mode with reduced
voltage swing on TOSC2 is available. This oscillator can be used as a clock source for the system clock and RTC, and as
the DFLL reference clock.
Figure 7-4. 32.768kHz crystal oscillator connection.
Two capacitors, C1 and C2, may be added to match the required load capacitance for the connected crystal. For details
on recommended TOSC characteristics and capacitor load, refer to device datasheets.
7.5 System Clock Selection and Prescalers
All the calibrated internal oscillators, the external clock sources (XOSC), and the PLL output can be used as the system
clock source. The system clock source is selectable from software, and can be changed during normal operation. Built-in
hardware protection prevents unsafe clock switching. It is not possible to select a non-stable or disabled oscillator as the
clock source, or to disable the oscillator currently used as the system clock source. Each oscillator option has a status
flag that can be read from software to check that the oscillator is ready.
The system clock is fed into a prescaler block that can divide the clock signal by a factor from 1 to 2048 before it is routed
to the CPU and peripherals. The prescaler settings can be changed from software during normal operation. The first
stage, prescaler A, can divide by a factor of from 1 to 512. Then, prescalers B and C can be individually configured to
either pass the clock through or combine divide it by a factor from 1 to 4. The prescaler guarantees that derived clocks
are always in phase, and that no glitches or intermediate frequencies occur when changing the prescaler setting. The
prescaler settings are updated in accordance with the rising edge of the slowest clock.
Figure 7-5. System clock selection and prescalers.
Prescaler A divides the system clock, and the resulting clock is clkPER4. Prescalers B and C can be enabled to divide the
clock speed further to enable peripheral modules to run at twice or four times the CPU clock frequency. If Prescalers B
and C are not used, all the clocks will run at the same frequency as the output from Prescaler A.
The system clock selection and prescaler registers are protected by the configuration change protection mechanism,
employing a timed write procedure for changing the system clock and prescaler settings. For details, refer to
“Configuration Change Protection” on page 13.
C1
C2
TOSC2
TOSC1
GND
Prescaler A
1, 2, 4, ... , 512
Prescaler B
1, 2, 4
Prescaler C
1, 2
Internal 2MHz Osc.
Internal 32.768kHz Osc.
Internal 32MHz Osc.
External Oscillator or Clock.
ClkCPU
Clock Selection
ClkPER
ClkSYS
ClkPER4 ClkPER2
Internal PLL.
XMEGA B [MANUAL] 80
8291C–AVR–09/2014
7.6 PLL with 1x-31x Multiplication Factor
The built-in phase locked loop (PLL) can be used to generate a high-frequency system clock. The PLL has a userselectable
multiplication factor of from 1 to 31. The output frequency, fOUT, is given by the input frequency, fIN, multiplied
by the multiplication factor, PLL_FAC.
Four different clock sources can be chosen as input to the PLL:
z 2MHz internal oscillator
z 32MHz internal oscillator divided by 4
z 0.4MHz - 16MHz crystal oscillator
z External clock
To enable the PLL, the following procedure must be followed:
1. Enable reference clock source.
2. Set the multiplication factor and select the clock reference for the PLL.
3. Wait until the clock reference source is stable.
4. Enable the PLL.
Hardware ensures that the PLL configuration cannot be changed when the PLL is in use. The PLL must be disabled
before a new configuration can be written.
It is not possible to use the PLL before the selected clock source is stable and the PLL has locked.
The reference clock source cannot be disabled while the PLL is running.
7.7 DFLL 2MHz and DFLL 32MHz
Two built-in digital frequency locked loops (DFLLs) can be used to improve the accuracy of the 2MHz and 32MHz
internal oscillators. The DFLL compares the oscillator frequency with a more accurate reference clock to do automatic
run-time calibration of the oscillator and compensate for temperature and voltage drift. The choices for the reference
clock sources are:
z 32.768kHz calibrated internal oscillator
z 32.768kHz crystal oscillator connected to the TOSC pins
z External clock
z USB start of frame
The DFLLs divide the oscillator reference clock by 32 to use a 1.024kHz reference. The reference clock is individually
selected for each DFLL, as shown on Figure 7-6 on page 81.
f OUT f IN = ⋅ PLL_FAC
XMEGA B [MANUAL] 81
8291C–AVR–09/2014
Figure 7-6. DFLL reference clock selection.
The ideal counter value representing the frequency ratio between the internal oscillator and a 1.024kHz reference clock
is loaded into the DFLL oscillator compare register (COMP) during reset. For the 32MHz oscillator, this register can be
written from software to make the oscillator run at a different frequency or when the ratio between the reference clock
and the oscillator is different (for example when the USB start of frame is used). The 48MHz calibration values must be
read from the production signature row and written to the 32MHz CAL register before the DFLL is enabled with USB SOF
as reference source.
The value that should be written to the COMP register is given by the following formula:
When the DFLL is enabled, it controls the ratio between the reference clock frequency and the oscillator frequency. If the
internal oscillator runs too fast or too slow, the DFLL will decrement or increment its calibration register value by one to
adjust the oscillator frequency. The oscillator is considered running too fast or too slow when the error is more than a half
calibration step size.
32.768 kHz Crystal Osc
External Clock
32.768 kHz Int. Osc
DFLL32M
32 MHz Int. RCOSC
DFLL2M
2 MHz Int. RCOSC
clkRC32MCREF
clkRC2MCREF
TOSC1
TOSC2
XTAL1
DIV32 DIV32
XOSCSEL
USB Start of Frame
XMEGA B [MANUAL] 82
8291C–AVR–09/2014
Figure 7-7. Automatic run-time calibration.
The DFLL will stop when entering a sleep mode where the oscillators are stopped. After wake up, the DFLL will continue
with the calibration value found before entering sleep. The reset value of the DFLL calibration register can be read from
the production signature row.
When the DFLL is disabled, the DFLL calibration register can be written from software for manual run-time calibration of
the oscillator.
7.8 PLL and External Clock Source Failure Monitor
A built-in failure monitor is available for the PLL and external clock source. If the failure monitor is enabled for the PLL
and/or the external clock source, and this clock source fails (the PLL looses lock or the external clock source stops) while
being used as the system clock, the device will:
z Switch to run the system clock from the 2MHz internal oscillator
z Reset the oscillator control register and system clock selection register to their default values
z Set the failure detection interrupt flag for the failing clock source (PLL or external clock)
z Issue a non-maskable interrupt (NMI)
If the PLL or external clock source fails when not being used for the system clock, it is automatically disabled, and the
system clock will continue to operate normally. No NMI is issued. The failure monitor is meant for external clock sources
above 32kHz. It cannot be used for slower external clocks.
When the failure monitor is enabled, it will not be disabled until the next reset.
The failure monitor is stopped in all sleep modes where the PLL or external clock source are stopped. During wake up
from sleep, it is automatically restarted.
The PLL and external clock source failure monitor settings are protected by the configuration change protection
mechanism, employing a timed write procedure for changing the settings. For details, refer to “Configuration Change
Protection” on page 13.
DFLL CNT
COMP
0
tRCnCREF
Frequency
OK RCOSC fast,
CALA decremented
RCOSC slow,
CALA incremented
clkRCnCREF
XMEGA B [MANUAL] 83
8291C–AVR–09/2014
7.9 Register Description – Clock
7.9.1 CTRL – Control register
z Bit 7:3 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 2:0 – SCLKSEL[2:0]: System Clock Selection
These bits are used to select the source for the system clock. See Table 7-1 for the different selections. Changing the
system clock source will take two clock cycles on the old clock source and two more clock cycles on the new clock
source. These bits are protected by the configuration change protection mechanism. For details, refer to “Configuration
Change Protection” on page 13.
SCLKSEL cannot be changed if the new clock source is not stable. The old clock can not be disabled until the clock
switching is completed.
Table 7-1. System clock selection.
7.9.2 PSCTRL – Prescaler register
This register is protected by the configuration change protection mechanism. For details, refer to “Configuration Change
Protection” on page 13.
z Bit 7 – Reserved
This bit is unused and reserved for future use. For compatibility with future devices, always write this bit to zero when this
register is written.
Bit 7 6 5 4 3 2 1 0
+0x00 – – – – – SCLKSEL[2:0]
Read/Write R R R R R R/W R/W R/W
Initial Value 0 0 0 00000
SCLKSEL[2:0] Group Configuration Description
000 RC2MHZ 2MHz internal oscillator
001 RC32MHZ 32MHz internal oscillator
010 RC32KHZ 32.768kHz internal oscillator
011 XOSC External oscillator or clock
100 PLL Phase locked loop
101 – Reserved
110 – Reserved
111 – Reserved
Bit 7 6 5 4 3 2 1 0
+0x01 – PSADIV[4:0] PSBCDIV
Read/Write R R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 84
8291C–AVR–09/2014
z Bit 6:2 – PSADIV[4:0]: Prescaler A Division Factor
These bits define the division ratio of the clock prescaler A according to Table 7-2. These bits can be written at run-time
to change the frequency of the ClkPER4 clock relative to the system clock, ClkSYS.
Table 7-2. Prescaler A division factor.
z Bit 1:0 – PSBCDIV: Prescaler B and C Division Factors
These bits define the division ratio of the clock prescalers B and C according to Table 7-3. Prescaler B will set the clock
frequency for the ClkPER2 clock relative to the ClkPER4 clock. Prescaler C will set the clock frequency for the ClkPER and
ClkCPU clocks relative to the ClkPER2 clock. Refer to Figure 7-5 on page 79 fore more details.
Table 7-3. Prescaler B and C division factors.
PSADIV[4:0] Group Configuration Description
00000 1 No division
00001 2 Divide by 2
00011 4 Divide by 4
00101 8 Divide by 8
00111 16 Divide by 16
01001 32 Divide by 32
01011 64 Divide by 64
01101 128 Divide by 128
01111 256 Divide by 256
10001 512 Divide by 512
10101 – Reserved
10111 – Reserved
11001 – Reserved
11011 – Reserved
11101 – Reserved
11111 – Reserved
PSBCDIV[1:0] Group Configuration Prescaler B division Prescaler C division
00 1_1 No division No division
01 1_2 No division Divide by 2
10 4_1 Divide by 4 No division
11 2_2 Divide by 2 Divide by 2
XMEGA B [MANUAL] 85
8291C–AVR–09/2014
7.9.3 LOCK – Lock register
z Bit 7:1 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 0 – LOCK: Clock System Lock
When this bit is written to one, the CTRL and PSCTRL registers cannot be changed, and the system clock selection and
prescaler settings are protected against all further updates until after the next reset. This bit is protected by the
configuration change protection mechanism. For details, refer to “Configuration Change Protection” on page 13.
The LOCK bit can be cleared only by a reset.
7.9.4 RTCCTRL – RTC Control register
z Bit 7:4 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 3:1 – RTCSRC[2:0]: RTC Clock Source
These bits select the clock source for the real-time counter according to Table 7-4.
Table 7-4. RTC clock source selection.
z Bit 0 – RTCEN: RTC Clock Source Enable
Setting the RTCEN bit enables the selected RTC clock source for the real-time counter.
Bit 7 6 5 4 3 2 1 0
+0x02 – – – – – – – LOCK
Read/Write R R R R R R R R/W
Initial Value 00000000
Bit 7 6 5 4 3 2 1 0
+0x03 – – – – RTCSRC[2:0] RTCEN
Read/Write R R R R R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
RTCSRC[2:0] Group Configuration Description
000 ULP 1kHz from 32kHz internal ULP oscillator
001 TOSC 1.024kHz from 32.768kHz crystal oscillator on TOSC
010 RCOSC 1.024kHz from 32.768kHz internal oscillator
011 — Reserved
100 — Reserved
101 TOSC32 32.768kHz from 32.768kHz crystal oscillator on TOSC
110 RCOSC32 32.768kHz from 32.768kHz internal oscillator
111 EXTCLK External clock from TOSC1
XMEGA B [MANUAL] 86
8291C–AVR–09/2014
7.9.5 USBSCTRL – USB Control register
z Bit 7:6 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 5:3 – USBPSDIV[2:0]: USB Prescaler Division Factor
These bits define the division ratio of the USB clock prescaler according to Table 7-5. These bits are locked as long as
the USB clock source is enabled.
Table 7-5. USB prescaler division factor.
z Bit 2:1 – USBSRC[1:0]: USB Clock Source
These bits select the clock source for the USB module according to Table 7-6.
Table 7-6. USB clock source.
Note: 1. The 32MHz internal oscillator must be calibrated to 48MHz before selecting this as source for the USB device module. Refer to “DFLL 2MHz and
DFLL 32MHz” on page 80.
z Bit 0 – USBSEN: USB Clock Source Enable
Setting this bit enables the selected clock source for the USB device module.
Bit 7 6 5 4 3 2 1 0
+0x04 – – USBPSDIV[2:0] USBSRC[1:0] USBSEN
Read/Write R R R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
USBPSDIV[2:0] Group Configuration Description
000 1 No division
001 2 Divide by 2
010 4 Divide by 4
011 8 Divide by 8
100 16 Divide by 16
101 32 Divide by 32
110 — Reserved
111 — Reserved
USBSRC[1:0] Group Configuration Description
00 PLL PLL
01 RC32M 32MHz internal oscillator(1)
XMEGA B [MANUAL] 87
8291C–AVR–09/2014
7.10 Register Description – Oscillator
7.10.1 CTRL – Oscillator Control register
z Bit 7:5 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 4 – PLLEN: PLL Enable
Setting this bit enables the PLL. Before the PLL is enabled, it must be configured with the desired multiplication factor
and clock source. See ”STATUS – Oscillator Status register” on page 87.
z Bit 3 – XOSCEN: External Oscillator Enable
Setting this bit enables the selected external clock source. Refer to “XOSCCTRL – XOSC Control register” on page 88
for details on how to select the external clock source. The external clock source should be allowed time to stabilize
before it is selected as the source for the system clock. See ”STATUS – Oscillator Status register” on page 87.
z Bit 2 – RC32KEN: 32.768kHz Internal Oscillator Enable
Setting this bit enables the 32.768kHz internal oscillator. The oscillator must be stable before it is selected as the source
for the system clock. See ”STATUS – Oscillator Status register” on page 87.
z Bit 1 – RC32MEN: 32MHz Internal Oscillator Enable
Setting this bit will enable the 32MHz internal oscillator. The oscillator must be stable before it is selected as the source
for the system clock. See ”STATUS – Oscillator Status register” on page 87.
z Bit 0 – RC2MEN: 2MHz Internal Oscillator Enable
Setting this bit enables the 2MHz internal oscillator. The oscillator must be stable before it is selected as the source for
the system clock. See ”STATUS – Oscillator Status register” on page 87.
By default, the 2MHz internal oscillator is enabled and this bit is set.
7.10.2 STATUS – Oscillator Status register
z Bit 7:5 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 4 – PLLRDY: PLL Ready
This flag is set when the PLL has locked on the selected frequency and is ready to be used as the system clock source.
z Bit 3 – XOSCRDY: External Clock Source Ready
This flag is set when the external clock source is stable and is ready to be used as the system clock source.
z Bit 2 – RC32KRDY: 32.768kHz Internal Oscillator Ready
This flag is set when the 32.768kHz internal oscillator is stable and is ready to be used as the system clock source.
Bit 7 6 5 4 3 2 1 0
+0x00 – – – PLLEN XOSCEN RC32KEN RC32MEN RC2MEN
Read/Write R R R R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 1
Bit 7 6 5 4 3 2 1 0
+0x01 – – – PLLRDY XOSCRDY RC32KRDY RC32MRDY RC2MRDY
Read/Write R R R R R R R R
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 88
8291C–AVR–09/2014
z Bit 1 – RC32MRDY: 32MHz Internal Oscillator Ready
This flag is set when the 32MHz internal oscillator is stable and is ready to be used as the system clock source.
z Bit 0 – RC2MRDY: 2MHz Internal Oscillator Ready
This flag is set when the 2MHz internal oscillator is stable and is ready to be used as the system clock source.
7.10.3 XOSCCTRL – XOSC Control register
z Bit 7:6 – FRQRANGE[1:0]: 0.4 - 16MHz Crystal Oscillator Frequency Range Select
These bits select the frequency range for the connected crystal oscillator according to Table 7-7.
Table 7-7. 16MHz crystal oscillator frequency range selection.
z Bit 5 – X32KLPM: Crystal Oscillator 32.768kHz Low Power Mode
Setting this bit enables the low power mode for the 32.768kHz crystal oscillator. This will reduce the swing on the TOSC2
pin.
z Bit 4 – XOSCPWR: Crystal Oscillator Drive
Setting this bit will increase the current in the 0.4MHz - 16MHz crystal oscillator and increase the swing on the XTAL2
pin. This allows for driving crystals with higher load or higher frequency than specified by the FRQRANGE bits.
z Bit 3:0 – XOSCSEL[3:0]: Crystal Oscillator Selection
These bits select the type and start-up time for the crystal or resonator that is connected to the XTAL or TOSC pins. See
Table 7-8 on page 89 for crystal selections. If an external clock or external oscillator is selected as the source for the
system clock, see “CTRL – Oscillator Control register” on page 87. This configuration cannot be changed.
Bit 7 6 5 4 3 2 1 0
+0x02 FRQRANGE[1:0] X32KLPM XOSCPWR XOSCSEL[3:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0000
FRQRANGE[1:0] Group Configuration Typical Frequency Range
Recommended Range for
Capacitors C1 and C2 (pF)
00 04TO2 0.4MHz - 2MHz 100-300
01 2TO9 2MHz - 9MHz 10-40
10 9TO12 9MHz - 12MHz 10-40
11 12TO16 12MHz - 16MHz 10-30
XMEGA B [MANUAL] 89
8291C–AVR–09/2014
Table 7-8. External oscillator selection and start-up time..
Notes: 1. This option should be used only when frequency stability at startup is not important for the application. The option is not suitable for crystals.
2. This option is intended for use with ceramic resonators. It can also be used when the frequency stability at startup is not important for the
application.
3. When the external oscillator is used as the reference for a DFLL, only EXTCLK and 32KHZ can be selected.
7.10.4 XOSCFAIL – XOSC Failure Detection register
z Bit 7:4 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 3 – PLLFDIF: PLL Fault Detection Flag
If PLL failure detection is enabled, PLLFDIF is set when the PLL looses lock. Writing logic one to this location will clear
PLLFDIF.
z Bit 2 – PLLFDEN: PLL Fault Detection Enable
Setting this bit will enable PLL failure detection. A non-maskable interrupt will be issued when PLLFDIF is set.
This bit is protected by the configuration change protection mechanism. Refer to “Configuration Change Protection” on
page 13 for details.
z Bit 1 – XOSCFDIF: Failure Detection Interrupt Flag
If the external clock source oscillator failure monitor is enabled, XOSCFDIF is set when a failure is detected. Writing logic
one to this location will clear XOSCFDIF.
z Bit 0 – XOSCFDEN: Failure Detection Enable
Setting this bit will enable the failure detection monitor, and a non-maskable interrupt will be issued when XOSCFDIF is
set.
This bit is protected by the configuration change protection mechanism. Refer to “Configuration Change Protection” on
page 13 for details. Once enabled, failure detection can only be disabled by a reset.
XOSCSEL[3:0] Group Configuration Selected Clock Source Start-up Time
0000 EXTCLK(3) External Clock 6 CLK
0010 32KHZ(3) 32.768kHz TOSC 16K CLK
0011 XTAL_256CLK(1) 0.4MHz - 16MHz XTAL 256 CLK
0111 XTAL_1KCLK(2) 0.4MHz - 16MHz XTAL 1K CLK
1011 XTAL_16KCLK 0.4MHz - 16MHz XTAL 16K CLK
Bit 7 6 5 4 3 2 1 0
+0x03 – – – – PLLFDIF PLLFDEN XOSCFDIF XOSCFDEN
Read/Write R R R R R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 90
8291C–AVR–09/2014
7.10.5 RC32KCAL – 32kHz Oscillator Calibration register
z Bit 7:0 – RC32KCAL[7:0]: 32.768kHz Internal Oscillator Calibration bits
This register is used to calibrate the 32.768kHz internal oscillator. A factory-calibrated value is loaded from the signature
row of the device and written to this register during reset, giving an oscillator frequency close to 32.768kHz. The register
can also be written from software to calibrate the oscillator frequency during normal operation.
7.10.6 PLLCTRL – PLL Control register
z Bit 7:6 – PLLSRC[1:0]: Clock Source
The PLLSRC bits select the input source for the PLL according to Table 7-9.
Table 7-9. PLL clock source.
Notes: 1. The 32.768kHz TOSC cannot be selected as the source for the PLL. An external clock must be a minimum 0.4MHz to be used as the source clock.
z Bit 5 – PLLDIV: PLL Divided Output Enable
Setting this bit will divide the output from the PLL by 2.
z Bit 4:0 – PLLFAC[4:0]: Multiplication Factor
These bits select the multiplication factor for the PLL. The multiplication factor can be in the range of from 1x to 31x.
7.10.7 DFLLCTRL – DFLL Control register
z Bit 7:3 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
Bit 7 6 5 4 3 2 1 0
+0x04 RC32KCAL[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value x xxxxxxx
Bit 7 6 5 4 3 2 1 0
+0x05 PLLSRC[1:0] PLLDIV PLLFAC[4:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
PLLSRC[1:0] Group Configuration PLL Input Source
00 RC2M 2MHz internal oscillator
01 — Reserved
10 RC32M 32MHz internal oscillator
11 XOSC External clock source(1)
Bit 7 6 5 4 3 2 1 0
+0x06 – – – – – RC32MCREF[1:0] RC2MCREF
Read/Write R R R R R R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 91
8291C–AVR–09/2014
z Bit 2:1 – RC32MCREF[1:0]: 32MHz Oscillator Calibration Reference
These bits are used to select the calibration source for the 32MHz DFLL according to the Table 7-10. These bits will
select only which calibration source to use for the DFLL. In addition, the actual clock source that is selected must enabled
and configured for the calibration to function.
Table 7-10. 32MHz oscillator reference selection.
z Bit 0 – RC2MCREF: 2MHz Oscillator Calibration Reference
This bit is used to select the calibration source for the 2MHz DFLL. By default, this bit is zero and the 32.768kHz internal
oscillator is selected. If this bit is set to one, the 32.768kHz crystal oscillator on TOSC is selected as the reference. This
bit will select only which calibration source to use for the DFLL. In addition, the actual clock source that is selected must
enabled and configured for the calibration to function.
7.11 Register Description – DFLL32M/DFLL2M
7.11.1 CTRL – DFLL Control register
z Bit 7:1 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 0 – ENABLE: DFLL Enable
Setting this bit enables the DFLL and auto-calibration of the internal oscillator. The reference clock must be enabled and
stable before the DFLL is enabled.
After disabling the DFLL, the reference clock can not be disabled before the ENABLE bit is read as zero.
RC32MCREF[1:0] Group Configuration Description
00 RC32K 32.768kHz internal oscillator
01 XOSC32 32.768kHz crystal oscillator on TOSC
10 USBSOF USB start of frame
11 – Reserved
Bit 7 6 5 4 3 2 1 0
+0x00 – – – – – – – ENABLE
Read/Write R R R R R R R R/W
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 92
8291C–AVR–09/2014
7.11.2 CALA – DFLL Calibration Register A
The CALA and CALB registers hold the 13-bit DFLL calibration value that is used for automatic run-time calibration of the
internal oscillator. When the DFLL is disabled, the calibration registers can be written by software for manual run-time
calibration of the oscillator. The oscillators will also be calibrated according to the calibration value in these registers
when the DFLL is disabled.
z Bit 7 – Reserved
This bit is unused and reserved for future use. For compatibility with future devices, always write this bit to zero when this
register is written.
z Bit 6:0 – CALA[6:0]: DFLL Calibration Bits
These bits hold the part of the oscillator calibration value that is used for automatic runtime calibration. A factorycalibrated
value is loaded from the signature row of the device and written to this register during reset, giving an oscillator
frequency approximate to the nominal frequency for the oscillator. The bits cannot be written when the DFLL is enabled.
7.11.3 CALB – DFLL Calibration register B
z Bit 7:6 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 5:0 – CALB[5:0]: DFLL Calibration bits
These bits hold the part of the oscillator calibration value that is used to select the oscillator frequency. A factorycalibrated
value is loaded from the signature row of the device and written to this register during reset, giving an oscillator
frequency approximate to the nominal frequency for the oscillator. These bits are not changed during automatic run-time
calibration of the oscillator. The bits cannot be written when the DFLL is enabled. When calibrating to a frequency
different from the default, the CALA bits should be set to a middle value to maximize the range for the DFLL.
7.11.4 COMP1 – DFLL Compare register 1
The COMP1 and COMP2 register pair represent the frequency ratio between the oscillator and the reference clock. The
initial value for these registers is the ratio between the internal oscillator frequency and a 1.024kHz reference
z Bit 7:0 – COMP1[7:0]: Compare value byte 1
These bits hold byte 1 of the 16-bit compare register.
Bit 7 6 5 4 3 2 1 0
+0x02 – CALA[6:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 x x x x x x x
Bit 7 6 5 4 3 2 1 0
+0x03 – – CALB[5:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 x x x x x x
Bit 7 6 5 4 3 2 1 0
+0x05 COMP[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 93
8291C–AVR–09/2014
7.11.5 COMP2 – DFLL Compare register 2
z Bit 7:0 – COMP2[15:8]: Compare Register value byte 2
These bits hold byte 2 of the 16-bit compare register.
Table 7-11. Nominal DFLL32M COMP values for different output frequencies.
Bit 7 6 5 4 3 2 1 0
+0x06 COMP[15:8]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 00000000
Oscillator Frequency (MHz) COMP Value (ClkRCnCREF = 1.024kHz)
30.0 0x7270
32.0 0x7A12
34.0 0x81B3
36.0 0x8954
38.0 0x90F5
40.0 0x9896
42.0 0xA037
44.0 0xA7D8
46.0 0xAF79
48.0 0xB71B
50.0 0xBEBC
52.0 0xC65D
54.0 0xCDFE
XMEGA B [MANUAL] 94
8291C–AVR–09/2014
7.12 Register Summary - Clock
7.13 Register Summary - Oscillator
7.14 Register Summary - DFLL32M/DFLL2M
7.15 Oscillator Failure Interrupt Vector Summary
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
+0x00 CTRL – – – – – SCLKSEL[2:0] 83
+0x01 PSCTRL – PSADIV[4:0] PSBCDIV[1:0] 83
+0x02 LOCK – – – – – – – LOCK 85
+0x03 RTCCTRL – – – – RTCSRC[2:0] RTCEN 85
+0x04 USBSCTR – – USBPSDIV[2:0] USBSRC[1:0] USBSEN 85
+0x05 Reserved – – – – – – – –
+0x06 Reserved – – – – – – – –
+0x07 Reserved – – – – – – – –
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
+0x00 CTRL – – – PLLEN XOSCEN RC32KEN R32MEN RC2MEN 87
+0x01 STATUS – – – PLLRDY XOSCRDY RC32KRD R32MRDY RC2MRDY 87
+0x02 XOSCCTR FRQRANGE[1:0] X32KLPM XOSCPW XOSCSEL[3:0] 88
+0x03 XOSCFAIL – – – – PLLFDIF PLLFDEN XOSCFDIF XOSCFDEN 89
+0x04 RC32KCAL RC32KCAL[7:0] 90
+0x05 PLLCTRL PLLSRC[1:0] – PLLFAC[4:0] 90
+0x06 DFLLCTRL – – – – – RC32MCREF[1:0] RC2MCREF 90
+0x07 Reserved – – – – – – – –
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
+0x00 CTRL – – – – – – – ENABLE 91
+0x01 Reserved – – – – – – – –
+0x02 CALA – CALA[6:0] 92
+0x03 CALB – – CALB[5:0] 92
+0x04 Reserved – – – – – – – –
+0x05 COMP1 COMP[7:0] 92
+0x06 COMP2 COMP[15:8] 93
+0x07 Reserved – – – – – – – –
Offset Source Interrupt Description
0x00 OSCF_vect PLL and external oscillator failure interrupt vector (NMI)
XMEGA B [MANUAL] 95
Atmel-8291C-AVR-XMEGA B -09/2014
8. Power Management and Sleep Modes
8.1 Features
z Power management for adjusting power consumption and functions
z Five sleep modes
z Idle
z Power down
z Power save
z Standby
z Extended standby
z Power reduction register to disable clock and turn off unused peripherals in active and idle modes
8.2 Overview
Various sleep modes and clock gating are provided in order to tailor power consumption to application requirements.
This enables the XMEGA microcontroller to stop unused modules to save power.
All sleep modes are available and can be entered from active mode. In active mode, the CPU is executing application
code. When the device enters sleep mode, program execution is stopped and interrupts or a reset is used to wake the
device again. The application code decides which sleep mode to enter and when. Interrupts from enabled peripherals
and all enabled reset sources can restore the microcontroller from sleep to active mode.
In addition, power reduction registers provide a method to stop the clock to individual peripherals from software. When
this is done, the current state of the peripheral is frozen, and there is no power consumption from that peripheral. This
reduces the power consumption in active mode and idle sleep modes and enables much more fine-tuned power
management than sleep modes alone.
8.3 Sleep Modes
Sleep modes are used to shut down modules and clock domains in the microcontroller in order to save power. XMEGA
microcontrollers have five different sleep modes tuned to match the typical functional stages during application
execution. A dedicated sleep instruction (SLEEP) is available to enter sleep mode. Interrupts are used to wake the
device from sleep, and the available interrupt wake-up sources are dependent on the configured sleep mode. When an
enabled interrupt occurs, the device will wake up and execute the interrupt service routine before continuing normal
program execution from the first instruction after the SLEEP instruction. If other, higher priority interrupts are pending
when the wake-up occurs, their interrupt service routines will be executed according to their priority before the interrupt
service routine for the wake-up interrupt is executed. After wake-up, the CPU is halted for four cycles before execution
starts.
Table 8-1 on page 96 shows the different sleep modes and the active clock domains, oscillators, and wake-up sources.
XMEGA B [MANUAL] 96
Atmel-8291C-AVR-XMEGA B -09/2014
Table 8-1. Active clock domains and wake-up sources in the different sleep modes.
The wake-up time for the device is dependent on the sleep mode and the main clock source. The startup time for the
system clock source must be added to the wake-up time for sleep modes where the system clock source is not kept
running. For details on the startup time for the different oscillator options, refer to “System Clock and Clock Options” on
page 77.
The content of the register file, SRAM and registers are kept during sleep. If a reset occurs during sleep, the device will
reset, start up, and execute from the reset vector.
8.3.1 Idle Mode
In idle mode the CPU and nonvolatile memory are stopped (note that any ongoing programming will be completed), but
all peripherals, including the interrupt controller, event system and DMA controller are kept running. Any enabled
interrupt will wake the device.
8.3.2 Power-down Mode
In power-down mode, all clocks, including the real-time counter clock source, are stopped. This allows operation only of
asynchronous modules that do not require a running clock. The only interrupts that can wake up the MCU are the twowire
interface address match interrupt, asynchronous port interrupts, and the USB resume interrupt.
8.3.3 Power-save Mode
Power-save mode is identical to power down, with two exceptions:
1. If the real-time counter (RTC) is enabled, it will keep running during sleep, and the device can also wake up from
either an RTC overflow or compare match interrupt.
2. If the LCD is enabled, it will keep running during sleep, and the device can wake up from LCD frame completed
interrupt.
8.3.4 Standby Mode
Standby mode is identical to power down, with the exception that the enabled system clock sources are kept running
while the CPU, peripheral, and RTC/LCD clocks are stopped. This reduces the wake-up time.
Active Clock Domain Oscillators Wake-up Sources
Sleep Modes
CPU Clock
Peripheral and USB Clock
RTC and LCD Clock
System Clock Source
RTC Clock Source
USB Resume
Asynchronous Port Interrupts
TWI Address Match Interrupts
RTC and LCD Clock Interrupts
All Interrupts
Idle X X X X X X X X X
Power down X X X
Power save X X X X X X
Standby X X X X
Extended standby X X X X X X X
XMEGA B [MANUAL] 97
Atmel-8291C-AVR-XMEGA B -09/2014
8.3.5 Extended Standby Mode
Extended standby mode is identical to power-save mode, with the exception that the enabled system clock sources are
kept running while the CPU and peripheral clocks are stopped. This reduces the wake-up time.
8.4 Power Reduction Registers
The power reduction (PR) registers provide a method to stop the clock to individual peripherals. When this is done, the
current state of the peripheral is frozen and the associated I/O registers cannot be read or written. Resources used by the
peripheral will remain occupied; hence, the peripheral should be disabled before stopping the clock. Enabling the clock to
a peripheral again puts the peripheral in the same state as before it was stopped. This can be used in idle mode and
active modes to reduce the overall power consumption. In all other sleep modes, the peripheral clock is already stopped.
Not all devices have all the peripherals associated with a bit in the power reduction registers. Setting a power reduction
bit for a peripheral that is not available will have no effect.
8.5 Minimizing Power Consumption
There are several possibilities to consider when trying to minimize the power consumption in an AVR MCU controlled
system. In general, correct sleep modes should be selected and used to ensure that only the modules required for the
application are operating.
All unneeded functions should be disabled. In particular, the following modules may need special consideration when
trying to achieve the lowest possible power consumption.
8.5.1 Analog-to-Digital Converter - ADC
When entering idle mode, the ADC should be disabled if not used. In other sleep modes, the ADC is automatically
disabled. When the ADC is turned off and on again, the next conversion will be an extended conversion. Refer to “ADC –
Analog-to-Digital Converter” on page 326 for details on ADC operation.
8.5.2 Analog Comparator - AC
When entering idle mode, the analog comparator should be disabled if not used. In other sleep modes, the analog
comparator is automatically disabled. However, if the analog comparator is set up to use the internal voltage reference as
input, the analog comparator should be disabled in all sleep modes. Otherwise, the internal voltage reference will be
enabled, irrespective of sleep mode. Refer to “AC – Analog Comparator” on page 352 for details on how to configure the
analog comparator.
8.5.3 Brownout Detector
If the brownout detector is not needed by the application, this module should be turned off. If the brownout detector is
enabled by the BODLEVEL fuses, it will be enabled in all sleep modes, and always consume power. In the deeper sleep
modes, it can be turned off and set in sampled mode to reduce current consumption. Refer to “Brownout Detection” on
page 109 for details on how to configure the brownout detector.
8.5.4 Watchdog Timer
If the watchdog timer is not needed in the application, the module should be turned off. If the watchdog timer is enabled,
it will be enabled in all sleep modes and, hence, always consume power. Refer to “WDT – Watchdog Timer” on page 115
for details on how to configure the watchdog timer.
8.5.5 Port Pins
When entering a sleep mode, all port pins should be configured to use minimum power. Most important is to ensure that
no pins drive resistive loads. In sleep modes where the Peripheral Clock (ClkPER) is stopped, the input buffers of the
device will be disabled. This ensures that no power is consumed by the input logic when not needed.
8.5.6 On-chip Debug Systems
If the On-chip debug system is enabled and the chip enters sleep mode, the main clock source is enabled and hence
always consumes power. In the deeper sleep modes, this will contribute significantly to the total current consumption.
XMEGA B [MANUAL] 98
Atmel-8291C-AVR-XMEGA B -09/2014
8.6 Register Description – Sleep
8.6.1 CTRL – Control Register
z Bit 7:4 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 3:1 – SMODE[2:0]: Sleep Mode selection
These bits select sleep modes according to Table 8-2.
Table 8-2. Sleep mode selection.
z Bit 0 – SEN: Sleep Enable
This bit must be set to make the MCU enter the selected sleep mode when the SLEEP instruction is executed. To avoid
unintentional entering of sleep modes, it is recommended to write SEN just before executing the SLEEP instruction and
clear it immediately after waking up.
8.7 Register Description – Power Reduction
8.7.1 PRGEN – General Power Reduction register
z Bit 7 – LCD: LCD Module
Setting this bit stops the clock to the LCD module. When the bit is cleared the peripheral should be reinitialized to ensure
proper operation.
Bit 7 6 5 4 3 2 1 0
+0x00 – – – – SMODE[2:0] SEN
Read/Write R R R R R/W R/W R/W R/W
Initial Value 00000000
SMODE[2:0] Group configuration Description
000 IDLE Idle mode
001 – Reserved
010 PDOWN Power-down mode
011 PSAVE Power-save mode
100 – Reserved
101 – Reserved
110 STDBY Standby mode
111 ESTDBY Extended standby mode
Bit 7 6 5 4 3 2 1 0
+0x00 LCD USB – AES – RTC EVSYS DMA
Read/Write R/W R/W R R/W R R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 99
Atmel-8291C-AVR-XMEGA B -09/2014
z Bit 6 – USB: USB Module
Setting this bit stops the clock to the USB module. When this bit is cleared, the peripheral should be reinitialized to
ensure proper operation.
z Bit 5 – Reserved
This bit is unused and reserved for future use. For compatibility with future devices, always write this bit to zero when this
register is written.
z Bit 4 – AES: AES Module
Setting this bit stops the clock to the AES module. When this bit is cleared, the peripheral should be reinitialized to
ensure proper operation.
z Bit 3 – Reserved
This bit is unused and reserved for future use. For compatibility with future devices, always write this bit to zero when this
register is written.
z Bit 2 – RTC: Real-Time Counter
Setting this bit stops the clock to the real-time counter. When this bit is cleared, the peripheral should be reinitialized to
ensure proper operation.
z Bit 1 – EVSYS: Event System
Setting this stops the clock to the event system. When this bit is cleared, the module will continue as before it was
stopped.
z Bit 0 – DMA: DMA Controller
Setting this bit stops the clock to the DMA controller. This bit can be set only if the DMA controller is disabled.
8.7.2 PRPA/B – Power Reduction Port A/B register
Note: Disabling of analog modules stops the clock to the analog blocks themselves and not only the interfaces.
z Bit 7:2 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 1 – ADC: Power Reduction ADC
Setting this bit stops the clock to the ADC. The ADC should be disabled before stopped.
z Bit 0 – AC: Power Reduction Analog Comparator
Setting this bit stops the clock to the analog comparator. The AC should be disabled before shutdown.
8.7.3 PRPC/E – Power Reduction Port C/E Register
z Bit 7 – Reserved
This bit is unused and reserved for future use. For compatibility with future devices, always write this bit to zero when this
register is written.
Bit 7 6 5 4 3 2 1 0
+0x01/+0x02 – – – – – – ADC AC
Read/Write R R R R R R R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
+0x03/+0x04/
+0x05/+0x06 – TWI – USART0 SPI HIRES TC1 TC0
Read/Write R R/W R R/W R/W R/W R/W R/W
Initial Value 0 0000000
XMEGA B [MANUAL] 100
Atmel-8291C-AVR-XMEGA B -09/2014
z Bit 6 – TWI: Two-Wire Interface
Setting this bit stops the clock to the two-wire interface. When this bit is cleared, the peripheral should be reinitialized to
ensure proper operation.
z Bit 5 – Reserved
This bit is unused and reserved for future use. For compatibility with future devices, always write this bit to zero when this
register is written.
z Bit 4 – USART0
Setting this bit stops the clock to USART0. When this bit is cleared, the peripheral should be reinitialized to ensure proper
operation.
z Bit 3 – SPI: Serial Peripheral Interface
Setting this bit stops the clock to the SPI. When this bit is cleared, the peripheral should be reinitialized to ensure proper
operation.
z Bit 2 – HIRES: High-Resolution Extension
Setting this bit stops the clock to the high-resolution extension for the timer/counters. When this bit is cleared, the
peripheral should be reinitialized to ensure proper operation.
z Bit 1 – TC1: Timer/Counter 1
Setting this bit stops the clock to timer/counter 1. When this bit is cleared, the peripheral will continue like before the shut
down.
z Bit 0 – TC0: Timer/Counter 0
Setting this bit stops the clock to timer/counter 0. When this bit is cleared, the peripheral will continue like before the shut
down.
XMEGA B [MANUAL] 101
Atmel-8291C-AVR-XMEGA B -09/2014
8.8 Register Summary - Sleep
8.9 Register Summary - Power Reduction
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
+0x00 CTRL – – – – SMODE[2:0] SEN 98
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
+0x00 PRGEN LCD USB – AES – RTC EVSYS DMA 98
+0x01 PRPA – – – – – – ADC AC 99
+0x02 PRPB – – – – – – ADC AC 99
+0x03 PRPC – TWI – USART0 SPI HIRES TC1 TC0 99
+0x04 Reserved – – – – – – – –
+0x05 PRPE – – – USART0 – – – TC0 99
XMEGA B [MANUAL] 102
Atmel-8291C-AVR-XMEGA B -09/2014
9. Reset System
9.1 Features
z Reset the microcontroller and set it to initial state when a reset source goes active
z Multiple reset sources that cover different situations
z Power-on reset
z External reset
z Watchdog reset
z Brownout reset
z PDI reset
z Software reset
z Asynchronous operation
z No running system clock in the device is required for reset
z Reset status register for reading the reset source from the application code
9.2 Overview
The reset system issues a microcontroller reset and sets the device to its initial state. This is for situations where
operation should not start or continue, such as when the microcontroller operates below its power supply rating. If a reset
source goes active, the device enters and is kept in reset until all reset sources have released their reset. The I/O pins
are immediately tri-stated. The program counter is set to the reset vector location, and all I/O registers are set to their
initial values. The SRAM content is kept. However, if the device accesses the SRAM when a reset occurs, the content of
the accessed location can not be guaranteed.
After reset is released from all reset sources, the default oscillator is started and calibrated before the device starts
running from the reset vector address. By default, this is the lowest program memory address, 0, but it is possible to
move the reset vector to the lowest address in the boot section.
The reset functionality is asynchronous, and so no running system clock is required to reset the device. The software
reset feature makes it possible to issue a controlled system reset from the user software.
The reset status register has individual status flags for each reset source. It is cleared at power-on reset, and shows
which sources have issued a reset since the last power-on.
An overview of the reset system is shown in Figure 9-1 on page 103.
XMEGA B [MANUAL] 103
Atmel-8291C-AVR-XMEGA B -09/2014
Figure 9-1. Reset system overview.
9.3 Reset Sequence
A reset request from any reset source will immediately reset the device and keep it in reset as long as the request is
active. When all reset requests are released, the device will go through three stages before the device starts running
again:
z Reset counter delay
z Oscillator startup
z Oscillator calibration
If another reset requests occurs during this process, the reset sequence will start over again.
9.3.1 Reset Counter
The reset counter can delay reset release with a programmable period from when all reset requests are released. The
reset delay is timed from the 1kHz output of the ultra low power (ULP) internal oscillator, and in addition 24 System clock
(clkSYS) cycles are counted before reset is released. The reset delay is set by the STARTUPTIME fuse bits. The
selectable delays are shown in Table 9-1.
Table 9-1. Reset delay
MCU Status
Register (MCUSR)
Brown-out
BODLEVEL [2:0] Reset
Delay Counters TIMEOUT
PORF
BORF
EXTRF
WDRF
ULP
Oscillator
SPIKE
FILTER
Pull-up Resistor
JTRF
Watchdog
Reset
SUT[1:0]
Power-on Reset
Software
Reset
External
Reset
PDI
Reset
SUT[1:0] Number of 1kHz ULP Oscillator Clock Cycles Recommended Usage
00 64K ClkULP+ 24 ClkSYS Stable frequency at startup
01 4K ClkULP + 24 ClkSYS Slowly rising power
10 Reserved -
11 24 ClkSYS Fast rising power or BOD enabled
XMEGA B [MANUAL] 104
Atmel-8291C-AVR-XMEGA B -09/2014
Whenever a reset occurs, the clock system is reset and the internal 2MHz internal oscillator is chosen as the source for
ClkSYS.
9.3.2 Oscillator Startup
After the reset delay, the 2MHz internal oscillator clock is started, and its calibration values are automatically loaded from
the calibration row to the calibration registers.
9.4 Reset Sources
9.4.1 Power-on Reset
A power-on reset (POR) is generated by an on-chip detection circuit. The POR is activated when the VCC rises and
reaches the POR threshold voltage (VPOT), and this will start the reset sequence.
The POR is also activated to power down the device properly when the VCC falls and drops below the VPOT level.
The VPOT level is higher for falling VCCthan for rising VCC. Consult the datasheet for POR characteristics data.
Figure 9-2. MCU startup, RESET tied to VCC.
Figure 9-3. MCU startup, RESET extended externally,
9.4.2 Brownout Detection
The on-chip brownout detection (BOD) circuit monitors the VCC level during operation by comparing it to a fixed,
programmable level that is selected by the BODLEVEL fuses. If disabled, BOD is forced on at the lowest level during chip
erase and when the PDI is enabled.
When the BOD is enabled and VCC decreases to a value below the trigger level (VBOT- in Figure 9-4), the brownout reset
is immediately activated.
V
RESET
TIME-OUT
INTERNAL
RESET
t
TOUT
VPOT
VRST
CC
RESET
TIME-OUT
INTERNAL
RESET
t
TOUT
VPOT
VRST
VCC
XMEGA B [MANUAL] 105
Atmel-8291C-AVR-XMEGA B -09/2014
When VCC increases above the trigger level (VBOT+ in Figure 9-4), the reset counter starts the MCU after the timeout
period, tTOUT, has expired.
The trigger level has a hysteresis to ensure spike free brownout detection. The hysteresis on the detection level should
be interpreted as VBOT+= VBOT + VHYST/2 and VBOT- = VBOT - VHYST/2.
The BOD circuit will detect a drop in VCC only if the voltage stays below the trigger level for longer than tBOD.
Figure 9-4. Brownout detection reset.
For BOD characterization data consult the device datasheet. The programmable BODLEVEL setting is shown in Table 9-
2.
Table 9-2. Programmable BODLEVEL setting.
Notes: 1. The values are nominal values only. For accurate, actual numbers, consult the device datasheet.
2. Changing these fuse bits will have no effect until leaving programming mode.
The BOD circuit has three modes of operation:
z Disabled: In this mode, there is no monitoring of the VCC level.
z Enabled: In this mode, the VCC level is continuously monitored, and a drop in VCC below VBOT for a period of tBOD
will give a brownout reset
z Sampled: In this mode, the BOD circuit will sample the VCC level with a period identical to that of the 1kHz output
from the ultra low power (ULP) internal oscillator. Between each sample, the BOD is turned off. This mode will
BOD level Fuse BODLEVEL[2:0](2) VBOT(1) Unit
BOD level 0 111 1.6
V
BOD level 1 110 1.8
BOD level 2 101 2.0
BOD level 3 100 2.2
BOD level 4 011 2.4
BOD level 5 010 2.6
BOD level 6 001 2.8
BOD level 7 000 3.0
VCC
TIME-OUT
INTERNAL
RESET
VBOTVBOT+
t
TOUT
t
BOD
XMEGA B [MANUAL] 106
Atmel-8291C-AVR-XMEGA B -09/2014
reduce the power consumption compared to the enabled mode, but a fall in the VCC level between two positive
edges of the 1kHz ULP oscillator output will not be detected. If a brownout is detected in this mode, the BOD circuit
is set in enabled mode to ensure that the device is kept in reset until VCC is above VBOT again
The BODACT fuse determines the BOD setting for active mode and idle mode, while the BODPD fuse determines the
brownout detection setting for all sleep modes, except idle mode.
Table 9-3. BOD setting fuse decoding.
9.4.3 External Reset
The external reset circuit is connected to the external RESET pin. The external reset will trigger when the RESET pin is
driven below the RESET pin threshold voltage, VRST, for longer than the minimum pulse period, tEXT. The reset will be
held as long as the pin is kept low. The RESET pin includes an internal pull-up resistor.
Figure 9-5. External reset characteristics.
For external reset characterization data consult the device datasheet.
9.4.4 Watchdog Reset
The watchdog timer (WDT) is a system function for monitoring correct program operation. If the WDT is not reset from
the software within a programmable timout period, a watchdog reset will be given. The watchdog reset is active for one to
two clock cycles of the 2MHz internal oscillator.
BODACT[1:0]/ BODPD[1:0] Mode
00 Reserved
01 Sampled
10 Enabled
11 Disabled
CC
t
EXT
XMEGA B [MANUAL] 107
Atmel-8291C-AVR-XMEGA B -09/2014
Figure 9-6. Watchdog reset.
For information on configuration and use of the WDT, refer to the “WDT – Watchdog Timer” on page 110.
9.4.5 Software Reset
The software reset makes it possible to issue a system reset from software by writing to the software reset bit in the reset
control register.The reset will be issued within two CPU clock cycles after writing the bit. It is not possible to execute any
instruction from when a software reset is requested until it is issued.
Figure 9-7. Software reset.
9.4.6 Program and Debug Interface Reset
The program and debug interface reset contains a separate reset source that is used to reset the device during external
programming and debugging. This reset source is accessible only from external debuggers and programmers.
1-2 2MHz
CC
Cycles
1-2 2MHz
CC
Cycles
SOFTWARE
XMEGA B [MANUAL] 108
Atmel-8291C-AVR-XMEGA B -09/2014
9.5 Register Description
9.5.1 STATUS – Status register
z Bit 7:6 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 5 – SRF: Software Reset Flag
This flag is set if a software reset occurs. The flag will be cleared by a power-on reset or by writing a one to the bit
location.
z Bit 4 – PDIRF: Program and Debug Interface Reset Flag
This flag is set if a programming interface reset occurs. The flag will be cleared by a power-on reset or by writing a one to
the bit location.
z Bit 3 – WDRF: Watchdog Reset Flag
This flag is set if a watchdog reset occurs. The flag will be cleared by a power-on reset or by writing a one to the bit
location.
z Bit 2 – BORF: Brownout Reset Flag
This flag is set if a brownout reset occurs. The flag will be cleared by a power-on reset or by writing a one to the bit
location.
z Bit 1 – EXTRF: External Reset Flag
This flag is set if an external reset occurs. The flag will be cleared by a power-on reset or by writing a one to the bit
location.
z Bit 0 – PORF: Power On Reset Flag
This flag is set if a power-on reset occurs. Writing a one to the flag will clear the bit location.
9.5.2 CTRL – Control register
z Bit 7:1 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 0 – SWRST: Software Reset
Bit 7 6 5 4 3 2 1 0
+0x00 – – SRF PDIRF WDRF BORF EXTRF PORF
Read/Write R R R/W R/W R/W R/W R/W R/W
Initial Value - -------
Bit 7 6 5 4 3 2 1 0
+0x01 – – – – – – – SWRST
Read/Write R R R R R R R R/W
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 109
Atmel-8291C-AVR-XMEGA B -09/2014
When this bit is set, a software reset will occur. The bit is cleared when a reset is issued. This bit is protected by the
configuration change protection mechanism. For details, refer to “Configuration Change Protection” on page 13.
9.6 Register Summary
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
+0x00 STATUS – – SRF PDIRF WDRF BORF EXTRF PORF 108
+0x01 CTRL – – – – – – – SWRST 108
XMEGA B [MANUAL] 110
Atmel-8291C-AVR-XMEGA B -09/2014
10. WDT – Watchdog Timer
10.1 Features
z Issues a device reset if the timer is not reset before its timeout period
z Asynchronous operation from dedicated oscillator
z 1kHz output of the 32kHz ultra low power oscillator
z 11 selectable timeout periods, from 8ms to 8s.
z Two operation modes:
z Normal mode
z Window mode
z Configuration lock to prevent unwanted changes
10.2 Overview
The watchdog timer (WDT) is a system function for monitoring correct program operation. It makes it possible to recover
from error situations such as runaway or deadlocked code. The WDT is a timer, configured to a predefined timeout
period, and is constantly running when enabled. If the WDT is not reset within the timeout period, it will issue a
microcontroller reset. The WDT is reset by executing the WDR (watchdog timer reset) instruction from the application
code.
The window mode makes it possible to define a time slot or window inside the total timeout period during which WDT
must be reset. If the WDT is reset outside this window, either too early or too late, a system reset will be issued.
Compared to the normal mode, this can also catch situations where a code error causes constant WDR execution.
The WDT will run in active mode and all sleep modes, if enabled. It is asynchronous, runs from a CPU-independent clock
source, and will continue to operate to issue a system reset even if the main clocks fail.
The configuration change protection mechanism ensures that the WDT settings cannot be changed by accident. For
increased safety, a fuse for locking the WDT settings is also available.
10.3 Normal Mode Operation
In normal mode operation, a single timeout period is set for the WDT. If the WDT is not reset from the application code
before the timeout occurs, then the WDT will issue a system reset. There are 11 possible WDT timeout (TOWDT) periods,
selectable from 8ms to 8s, and the WDT can be reset at any time during the timeout period. A new WDT timeout period
will be started each time the WDT is reset by the WDR instruction. The default timeout period is controlled by fuses.
Normal mode operation is illustrated in Figure 10-1 on page 110.
Figure 10-1. Normal mode operation.
XMEGA B [MANUAL] 111
Atmel-8291C-AVR-XMEGA B -09/2014
10.4 Window Mode Operation
In window mode operation, the WDT uses two different timeout periods, a "closed" window timeout period (TOWDTW) and
the normal timeout period (TOWDT). The closed window timeout period defines a duration of from 8ms to 8s where the
WDT cannot be reset. If the WDT is reset during this period, the WDT will issue a system reset. The normal WDT timeout
period, which is also 8ms to 8s, defines the duration of the "open" period during which the WDT can (and should) be
reset. The open period will always follow the closed period, and so the total duration of the timeout period is the sum of
the closed window and the open window timeout periods. The default closed window timeout period is controlled by fuses
(both open and closed periods are controlled by fuses). The window mode operation is illustrated in Figure 10-2.
Figure 10-2. Window mode operation.
10.5 Watchdog Timer Clock
The WDT is clocked from the 1kHz output from the 32kHz ultra low power (ULP) internal oscillator. Due to the ultra low
power design, the oscillator is not very accurate, and so the exact timeout period may vary from device to device. When
designing software which uses the WDT, this device-to-device variation must be kept in mind to ensure that the timeout
periods used are valid for all devices. For more information on ULP oscillator accuracy, consult the device datasheet.
10.6 Configuration Protection and Lock
The WDT is designed with two security mechanisms to avoid unintentional changes to the WDT settings.
The first mechanism is the configuration change protection mechanism, employing a timed write procedure for changing
the WDT control registers. In addition, for the new configuration to be written to the control registers, the register’s
change enable bit must be written at the same time.
The second mechanism locks the configuration by setting the WDT lock fuse. When this fuse is set, the watchdog time
control register cannot be changed; hence, the WDT cannot be disabled from software. After system reset, the WDT will
resume at the configured operation. When the WDT lock fuse is programmed, the window mode timeout period cannot
be changed, but the window mode itself can still be enabled or disabled.
XMEGA B [MANUAL] 112
Atmel-8291C-AVR-XMEGA B -09/2014
10.7 Registers Description
10.7.1 CTRL – Control register
z Bits 7:6 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bits 5:2 – PER[3:0]: Timeout Period
These bits determine the watchdog timeout period as a number of 1kHz ULP oscillator cycles. In window mode
operation, these bits define the open window period. The different typical timeout periods are found in Table 10-1. The
initial values of these bits are set by the watchdog timeout period (WDP) fuses, which are loaded at power-on.
In order to change these bits, the CEN bit must be written to 1 at the same time. These bits are protected by the
configuration change protection mechanism. For a detailed description, refer to “Configuration Change Protection” on
page 13.
Table 10-1. Watchdog timeout periods
Note: Reserved settings will not give any timeout.
Bit 7 6 5 4 3 2 1 0
+0x00 – – PER[3:0] ENABLE CEN
Read/Write (unlocked) R R R/W R/W R/W R/W R/W R/W
Read/Write (locked) R RRRRRRR
Initial Value (x = fuse) 0 0 XXXXX0
PER[3:0] Group Configuration Typical Timeout Periods
0000 8CLK 8ms
0001 16CLK 16ms
0010 32CLK 32ms
0011 64CLK 64ms
0100 128CLK 0.128s
0101 256CLK 0.256s
0110 512CLK 0.512s
0111 1KCLK 1.0s
1000 2KCLK 2.0s
1001 4KCLK 4.0s
1010 8KCLK 8.0s
1011 – Reserved
1100 – Reserved
1101 – Reserved
1110 – Reserved
1111 – Reserved
XMEGA B [MANUAL] 113
Atmel-8291C-AVR-XMEGA B -09/2014
z Bit 1 – ENABLE: Enable
This bit enables the WDT. Clearing this bit disables the watchdog timer.
In order to change this bit, the CEN bit in “CTRL – Control register” on page 112 must be written to one at the same time.
This bit is protected by the configuration change protection mechanism, For a detailed description, refer to “Configuration
Change Protection” on page 13.
z Bit 0 – CEN: Change Enable
This bit enables the ability to change the configuration of the “CTRL – Control register” on page 112. When writing a new
value to this register, this bit must be written to one at the same time for the changes to take effect. This bit is protected
by the configuration change protection mechanism. For a detailed description, refer to “Configuration Change Protection”
on page 13.
10.7.2 WINCTRL – Window Mode Control register
z Bit 7:6 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 5:2 – WPER[3:0]: Window Mode Timeout Period
These bits determine the closed window period as a number of 1kHz ULP oscillator cycles in window mode operation.
The typical different closed window periods are found in Table 10-2. The initial values of these bits are set by the
watchdog window timeout period (WDWP) fuses, and are loaded at power-on. In normal mode these bits are not in use.
In order to change these bits, the WCEN bit must be written to one at the same time. These bits are protected by the
configuration change protection mechanism. For a detailed description, refer to “Configuration Change Protection” on
page 13.
Table 10-2. Watchdog closed window periods
Bit 7 6 5 4 3 2 1 0
+0x01 – – WPER[3:0] WEN WCEN
Read/Write (unlocked) R R R/W R/W R/W R/W R/W R/W
Read/Write (locked) R R R R R R R/W R/W
Initial Value (x = fuse) 0 0 XXXXX0
WPER[3:0] Group Configuration Typical Closed Window Periods
0000 8CLK 8ms
0001 16CLK 16ms
0010 32CLK 32ms
0011 64CLK 64ms
0100 128CLK 0.128s
0101 256CLK 0.256s
0110 512CLK 0.512s
0111 1KCLK 1.0s
1000 2KCLK 2.0s
1001 4KCLK 4.0s
XMEGA B [MANUAL] 114
Atmel-8291C-AVR-XMEGA B -09/2014
Note: Reserved settings will not give any timeout for the window.
z Bit 1 – WEN: Window Mode Enable
This bit enables the window mode. In order to change this bit, the WCEN bit in “WINCTRL – Window Mode Control
register” on page 113 must be written to one at the same time. This bit is protected by the configuration change
protection mechanism. For a detailed description, refer to “Configuration Change Protection” on page 13.
z Bit 0 – WCEN: Window Mode Change Enable
This bit enables the ability to change the configuration of the “WINCTRL – Window Mode Control register” on page 113.
When writing a new value to this register, this bit must be written to one at the same time for the changes to take effect.
This bit is protected by the configuration change protection mechanism, but not protected by the WDT lock fuse.
10.7.3 STATUS – Status register
z Bit 7:1 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 0 – SYNCBUSY: Synchronization Busy Flag
This flag is set after writing to the CTRL or WINCTRL registers and the data are being synchronized from the system
clock to the WDT clock domain. This bit is automatically cleared after the synchronization is finished. Synchronization will
take place only when the ENABLE bit for the Watchdog Timer is set.
10.8 Register Summary
1010 8KCLK 8.0s
1011 – Reserved
1100 – Reserved
1101 – Reserved
1110 – Reserved
1111 – Reserved
WPER[3:0] Group Configuration Typical Closed Window Periods
Bit 7 6 5 4 3 2 1 0
+0x02 – – – – – – – SYNCBUSY
Read/Write R R R R R R R R
Initial Value 0 0 0 0 0 0 0 0
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
+0x00 CTRL – – PER[3:0] ENABLE CEN 112
+0x01 WINCTRL – – WPER[3:0] WEN WCEN 113
+0x02 STATUS – – – – – – – SYNCBUSY 114
XMEGA B [MANUAL] 115
Atmel-8291C-AVR-XMEGA B -09/2014
11. Interrupts and Programmable Multilevel Interrupt Controller
11.1 Features
z Short and predictable interrupt response time
z Separate interrupt configuration and vector address for each interrupt
z Programmable multilevel interrupt controller
z Interrupt prioritizing according to level and vector address
z Three selectable interrupt levels for all interrupts: low, medium and high
z Selectable, round-robin priority scheme within low-level interrupts
z Non-maskable interrupts for critical functions
z Interrupt vectors optionally placed in the application section or the boot loader section
11.2 Overview
Interrupts signal a change of state in peripherals, and this can be used to alter program execution. Peripherals can have
one or more interrupts, and all are individually enabled and configured. When an interrupt is enabled and configured, it
will generate an interrupt request when the interrupt condition is present. The programmable multilevel interrupt
controller (PMIC) controls the handling and prioritizing of interrupt requests. When an interrupt request is acknowledged
by the PMIC, the program counter is set to point to the interrupt vector, and the interrupt handler can be executed.
All peripherals can select between three different priority levels for their interrupts: low, medium, and high. Interrupts are
prioritized according to their level and their interrupt vector address. Medium-level interrupts will interrupt low-level
interrupt handlers. High-level interrupts will interrupt both medium- and low-level interrupt handlers. Within each level, the
interrupt priority is decided from the interrupt vector address, where the lowest interrupt vector address has the highest
interrupt priority. Low-level interrupts have an optional round-robin scheduling scheme to ensure that all interrupts are
serviced within a certain amount of time.
Non-maskable interrupts (NMI) are also supported, and can be used for system critical functions.
11.3 Operation
Interrupts must be globally enabled for any interrupts to be generated. This is done by setting the global interrupt enable
( I ) bit in the CPU status register. The I bit will not be cleared when an interrupt is acknowledged. Each interrupt level
must also be enabled before interrupts with the corresponding level can be generated.
When an interrupt is enabled and the interrupt condition is present, the PMIC will receive the interrupt request. Based on
the interrupt level and interrupt priority of any ongoing interrupts, the interrupt is either acknowledged or kept pending
until it has priority. When the interrupt request is acknowledged, the program counter is updated to point to the interrupt
vector. The interrupt vector is normally a jump to the interrupt handler; the software routine that handles the interrupt.
After returning from the interrupt handler, program execution continues from where it was before the interrupt occurred.
One instruction is always executed before any pending interrupt is served.
The PMIC status register contains state information that ensures that the PMIC returns to the correct interrupt level when
the RETI (interrupt return) instruction is executed at the end of an interrupt handler. Returning from an interrupt will return
the PMIC to the state it had before entering the interrupt. The status register (SREG) is not saved automatically upon an
interrupt request. The RET (subroutine return) instruction cannot be used when returning from the interrupt handler
routine, as this will not return the PMIC to its correct state.
XMEGA B [MANUAL] 116
Atmel-8291C-AVR-XMEGA B -09/2014
Figure 11-1. Interrupt controller overview.
11.4 Interrupts
All interrupts and the reset vector each have a separate program vector address in the program memory space. The
lowest address in the program memory space is the reset vector. All interrupts are assigned individual control bits for
enabling and setting the interrupt level, and this is set in the control registers for each peripheral that can generate
interrupts. Details on each interrupt are described in the peripheral where the interrupt is available.
All interrupts have an interrupt flag associated with it. When the interrupt condition is present, the interrupt flag will be set,
even if the corresponding interrupt is not enabled. For most interrupts, the interrupt flag is automatically cleared when
executing the interrupt vector. Writing a logical one to the interrupt flag will also clear the flag. Some interrupt flags are
not cleared when executing the interrupt vector, and some are cleared automatically when an associated register is
accessed (read or written). This is described for each individual interrupt flag.
If an interrupt condition occurs while another, higher priority interrupt is executing or pending, the interrupt flag will be set
and remembered until the interrupt has priority. If an interrupt condition occurs while the corresponding interrupt is not
enabled, the interrupt flag will be set and remembered until the interrupt is enabled or the flag is cleared by software.
Similarly, if one or more interrupt conditions occur while global interrupts are disabled, the corresponding interrupt flag
will be set and remembered until global interrupts are enabled. All pending interrupts are then executed according to their
order of priority.
Interrupts can be blocked when executing code from a locked section; e.g., when the boot lock bits are programmed.
This feature improves software security. Refer to “Memory Programming” on page 375 for details on lock bit settings.
Interrupts are automatically disabled for up to four CPU clock cycles when the configuration change protection register is
written with the correct signature. Refer to “Configuration Change Protection” on page 13 for more details.
11.4.1 NMI – Non-Maskable Interrupts
Which interrupts represent NMI and which represent regular interrupts cannot be selected. Non-maskable interrupts
must be enabled before they can be used. Refer to the device datasheet for NMI present on each device.
An NMI will be executed regardless of the setting of the I bit, and it will never change the I bit. No other interrupts can
interrupt a NMI handler. If more than one NMI is requested at the same time, priority is static according to the interrupt
vector address, where the lowest address has highest priority.
11.4.2 Interrupt Response Time
The interrupt response time for all the enabled interrupts is three CPU clock cycles, minimum; one cycle to finish the
ongoing instruction and two cycles to store the program counter to the stack. After the program counter is pushed on the
stack, the program vector for the interrupt is executed. The jump to the interrupt handler takes three clock cycles.
Peripheral 1
Interrupt Controller
INT REQ
INT LEVEL
INT REQ
INT LEVEL CPU INT REQ
CTRL
LEVEL Enable
CPU.SREG
Global
Interrupt
Enable
Priority
decoder
STATUS
INTPRI
INT ACK
INT ACK
Peripheral n
INT LEVEL
INT REQ
INT ACK
CPU
CPU INT ACK
CPU ”RETI”
Sleep
Controller
Wake-up
XMEGA B [MANUAL] 117
Atmel-8291C-AVR-XMEGA B -09/2014
If an interrupt occurs during execution of a multicycle instruction, this instruction is completed before the interrupt is
served. See Figure 11-2 on page 117 for more details.
Figure 11-2. Interrupt execution of a multicycle instruction.
If an interrupt occurs when the device is in sleep mode, the interrupt execution response time is increased by five clock
cycles. In addition, the response time is increased by the start-up time from the selected sleep mode.
A return from an interrupt handling routine takes four to five clock cycles, depending on the size of the program counter.
During these clock cycles, the program counter is popped from the stack and the stack pointer is incremented.
XMEGA B [MANUAL] 118
Atmel-8291C-AVR-XMEGA B -09/2014
11.5 Interrupt level
The interrupt level is independently selected for each interrupt source. For any interrupt request, the PMIC also receives
the interrupt level for the interrupt. The interrupt levels and their corresponding bit values for the interrupt level
configuration of all interrupts is shown in Table 11-1.
Table 11-1. Interrupt levels
The interrupt level of an interrupt request is compared against the current level and status of the interrupt controller. An
interrupt request of a higher level will interrupt any ongoing interrupt handler from a lower level interrupt. When returning
from the higher level interrupt handler, the execution of the lower level interrupt handler will continue.
11.6 Interrupt priority
Within each interrupt level, all interrupts have a priority. When several interrupt requests are pending, the order in which
interrupts are acknowledged is decided both by the level and the priority of the interrupt request. Interrupts can be
organized in a static or dynamic (round-robin) priority scheme. High- and medium-level interrupts and the NMI will always
have static priority. For low-level interrupts, static or dynamic priority scheduling can be selected.
11.6.1 Static priority
Interrupt vectors (IVEC) are located at fixed addresses. For static priority, the interrupt vector address decides the priority
within one interrupt level, where the lowest interrupt vector address has the highest priority. Refer to the device datasheet
for the interrupt vector table with the base address for all modules and peripherals with interrupt capability. Refer to the
interrupt vector summary of each module and peripheral in this manual for a list of interrupts and their corresponding
offset address within the different modules and peripherals.
Interrupt Level Configuration Group Configuration Description
00 OFF Interrupt disabled.
01 LO Low-level interrupt
10 MED Medium-level interrupt
11 HI High-level interrupt
XMEGA B [MANUAL] 119
Atmel-8291C-AVR-XMEGA B -09/2014
Figure 11-3. Static priority.
11.6.2 Round-robin Scheduling
To avoid the possible starvation problem for low-level interrupts with static priority, where some interrupts might never be
served, the PMIC offers round-robin scheduling for low-level interrupts. When round-robin scheduling is enabled, the
interrupt vector address for the last acknowledged low-level interrupt will have the lowest priority the next time one or
more interrupts from the low level is requested.
Figure 11-4. Round-robin scheduling.
XMEGA B [MANUAL] 120
Atmel-8291C-AVR-XMEGA B -09/2014
11.7 Interrupt vector locations
Table 11-2 shows reset and Interrupt vectors placement for the various combinations of BOOTRST and IVSEL settings.
If the program never enables an interrupt source, the Interrupt Vectors are not used, and regular program code can be
placed at these locations. This is also the case if the Reset Vector is in the Application section while the Interrupt Vectors
are in the Boot section or vice versa.
Table 11-2. Reset and interrupt vectors placement
BOOTRST IVSEL Reset Address Interrupt Vectors Start Address
1 0 0x0000 0x0002
1 1 0x0000 Boot Reset Address + 0x0002
0 0 Boot Reset Address 0x0002
0 1 Boot Reset Address Boot Reset Address + 0x0002
XMEGA B [MANUAL] 121
Atmel-8291C-AVR-XMEGA B -09/2014
11.8 Register Description
11.8.1 STATUS – Status register
z Bit 7 – NMIEX: Non-Maskable Interrupt Executing
This flag is set if a non-maskable interrupt is executing. The flag will be cleared when returning (RETI) from the interrupt
handler.
z Bit 6:3 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 2 – HILVLEX: High-level Interrupt Executing
This flag is set when a high-level interrupt is executing or when the interrupt handler has been interrupted by an NMI. The
flag will be cleared when returning (RETI) from the interrupt handler.
z Bit 1 – MEDLVLEX: Medium-level Interrupt Executing
This flag is set when a medium-level interrupt is executing or when the interrupt handler has been interrupted by an
interrupt from higher level or an NMI. The flag will be cleared when returning (RETI) from the interrupt handler.
z Bit 0 – LOLVLEX: Low-level Interrupt Executing
This flag is set when a low-level interrupt is executing or when the interrupt handler has been interrupted by an interrupt
from higher level or an NMI. The flag will be cleared when returning (RETI) from the interrupt handler.
11.8.2 INTPRI – Interrupt priority register
z Bit 7:0 – INTPRI: Interrupt Priority
When round-robin scheduling is enabled, this register stores the interrupt vector of the last acknowledged low-level
interrupt. The stored interrupt vector will have the lowest priority the next time one or more low-level interrupts are
pending. The register is accessible from software to change the priority queue. This register is not reinitialized to its initial
value if round-robing scheduling is disabled, and so if default static priority is needed, the register must be written to zero.
Bit 7 6 5 4 3 2 1 0
+0x00 NMIEX – – – – HILVLEX MEDLVLEX LOLVLEX
Read/Write R R R R R R R R
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
+0x01 INTPRI[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 00000000
XMEGA B [MANUAL] 122
Atmel-8291C-AVR-XMEGA B -09/2014
11.8.3 CTRL – Control register
z Bit 7 – RREN: Round-robin Scheduling Enable
When the RREN bit is set, the round-robin scheduling scheme is enabled for low-level interrupts. When this bit is cleared,
the priority is static according to interrupt vector address, where the lowest address has the highest priority.
z Bit 6 – IVSEL: Interrupt Vector Select
When the IVSEL bit is cleared (zero), the interrupt vectors are placed at the start of the application section in flash. When
this bit is set (one), the interrupt vectors are placed in the beginning of the boot section of the flash. Refer to the device
datasheet for the absolute address.
This bit is protected by the configuration change protection mechanism. Refer to “Configuration Change Protection” on
page 13 for details.
z Bit 5:3 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 2 – HILVLEN: High-level Interrupt Enable (1)
When this bit is set, all high-level interrupts are enabled. If this bit is cleared, high-level interrupt requests will be ignored.
z Bit 1 – MEDLVLEN: Medium-level Interrupt Enable(1)
When this bit is set, all medium-level interrupts are enabled. If this bit is cleared, medium-level interrupt requests will be
ignored.
z Bit 0 – LOLVLEN: Low-level Interrupt Enable(1)
When this bit is set, all low-level interrupts are enabled. If this bit is cleared, low-level interrupt requests will be ignored.
Note: 1. Ignoring interrupts will be effective one cycle after the bit is cleared.
11.9 Register Summary
Bit 7 6 5 4 3 2 1 0
+0x02 RREN IVSEL – – – HILVLEN MEDLVLEN LOLVLEN
Read/Write R/W R/W R R R R/W R/W R/W
Initial Value 0 00000 0 0
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
+0x00 STATUS NMIEX – – – – HILVLEX MEDLVLEX LOLVLEX 121
+0x01 INTPRI INTPRI[7:0] 121
+0x02 CTRL RREN IVSEL – – – HILVLEN MEDLVLEN LOLVLEN 122
XMEGA B [MANUAL] 123
Atmel-8291C-AVR-XMEGA B -09/2014
12. I/O Ports
12.1 Features
z General purpose input and output pins with individual configuration
z Output driver with configurable driver and pull settings:
z Totem-pole
z Wired-AND
z Wired-OR
z Bus-keeper
z Inverted I/O
z Input with synchronous and/or asynchronous sensing with interrupts and events
z Sense both edges
z Sense rising edges
z Sense falling edges
z Sense low level
z Optional pull-up and pull-down resistor on input and Wired-OR/AND configurations
z Asynchronous pin change sensing that can wake the device from all sleep modes
z Two port interrupts with pin masking per I/O port
z Efficient and safe access to port pins
z Hardware read-modify-write through dedicated toggle/clear/set registers
z Configuration of multiple pins in a single operation
z Mapping of port registers into bit-accessible I/O memory space
z Peripheral clocks output on port pin
z Real-time counter clock output to port pin
z Event channels can be output on port pin
z Remapping of digital peripheral pin functions
z Selectable USART, SPI, and timer/counter input/output pin locations
12.2 Overview
AVR XMEGA microcontrollers have flexible general purpose I/O ports. One port consists of up to eight port pins: pin 0 to
7. Each port pin can be configured as input or output with configurable driver and pull settings. They also implement
synchronous and asynchronous input sensing with interrupts and events for selectable pin change conditions.
Asynchronous pin-change sensing means that a pin change can wake the device from all sleep modes, included the
modes where no clocks are running.
All functions are individual and configurable per pin, but several pins can be configured in a single operation. The pins
have hardware read-modify-write (RMW) functionality for safe and correct change of drive value and/or pull resistor
configuration. The direction of one port pin can be changed without unintentionally changing the direction of any other
pin.
The port pin configuration also controls input and output selection of other device functions. It is possible to have both the
peripheral clock and the real-time clock output to a port pin, and available for external use. The same applies to events
from the event system that can be used to synchronize and control external functions. Other digital peripherals, such as
USART, SPI, and timer/counters, can be remapped to selectable pin locations in order to optimize pin-out versus
application needs.
Figure 12-1 on page 124 shows the I/O pin functionality and the registers that are available for controlling a pin.
XMEGA B [MANUAL] 124
Atmel-8291C-AVR-XMEGA B -09/2014
Figure 12-1. General I/O pin functionality.
12.3 I/O Pin Use and Configuration
Each port has one data direction (DIR) register and one data output value (OUT) register that are used for port pin
control. The data input value (IN) register is used for reading the port pins. In addition, each pin has a pin configuration
(PINnCTRL) register for additional pin configuration.
Direction of the pin is decided by the DIRn bit in the DIR register. If DIRn is written to one, pin n is configured as an output
pin. If DIRn is written to zero, pin n is configured as an input pin.
When direction is set as output, the OUTn bit in OUT is used to set the value of the pin. If OUTn is written to one, pin n is
driven high. If OUTn is written to zero, pin n is driven low.
The IN register is used for reading pin values. A pin value can always be read regardless of whether the pin is configured
as input or output, except if digital input is disabled.
The I/O pins are tri-stated when a reset condition becomes active, even if no clocks are running.
The pin n configuration (PINnCTRL) register is used for additional I/O pin configuration. A pin can be set in a totem-pole,
wired-AND, or wired-OR configuration. It is also possible to enable inverted input and output for a pin.
A totem-pole output has four possible pull configurations: totem-pole (push-pull), pull-down, pull-up, and bus-keeper. The
bus-keeper is active in both directions. This is to avoid oscillation when disabling the output. The totem-pole
Q D
R
Q D
R
Synchronizer
D Q
R
D Q
R
DIRn
OUTn
PINnCTRL
INn
Pxn
D Q
R
C
o
n
t
r
o
l
L
o
g
i
c
Input Disable
Wired AND/OR
Digital Input Pin
Analog Input/Output
Inverted I/O
Pull Enable
Pull Keep
Pull Direction
XMEGA B [MANUAL] 125
Atmel-8291C-AVR-XMEGA B -09/2014
configurations with pull-up and pull-down have active resistors only when the pin is set as input. This feature eliminates
unnecessary power consumption. For wired-AND and wired-OR configuration, the optional pull-up and pull-down
resistors are active in both input and output directions.
Since pull configuration is configured through the pin configuration register, all intermediate port states during switching
of the pin direction and pin values are avoided.
The I/O pin configurations are summarized with simplified schematics in Figure 12-2 on page 125 to Figure 12-7 on page
127.
12.3.1 Totem-pole
In the totem-pole (push-pull) configuration, the pin is driven low or high according to the corresponding bit setting in the
OUT register. In this configuration, there is no current limitation for sink or source other than what the pin is capable of. If
the pin is configured for input, the pin will float if no external pull resistor is connected.
Figure 12-2. I/O pin configuration - Totem-pole (push-pull).
12.3.1.1 Totem-pole with Pull-down
In this mode, the configuration is the same as for totem-pole mode, expect the pin is configured with an internal pull-down
resistor when set as input.
Figure 12-3. I/O pin configuration - Totem-pole with pull-down (on input).
XMEGA B [MANUAL] 126
Atmel-8291C-AVR-XMEGA B -09/2014
12.3.1.2 Totem-pole with Pull-up
In this mode, the configuration is as for totem-pole, expect the pin is configured with internal pull-up when set as input.
Figure 12-4. I/O pin configuration - Totem-pole with pull-up (on input).
12.3.2 Bus-keeper
In the bus-keeper configuration, it provides a weak bus-keeper that will keep the pin at its logic level when the pin is no
longer driven to high or low. If the last level on the pin/bus was 1, the bus-keeper configuration will use the internal pull
resistor to keep the bus high. If the last logic level on the pin/bus was 0, the bus-keeper will use the internal pull resistor
to keep the bus low.
Figure 12-5. I/O pin configuration - Totem-pole with bus-keeper.
XMEGA B [MANUAL] 127
Atmel-8291C-AVR-XMEGA B -09/2014
12.3.3 Wired-OR
In the wired-OR configuration, the pin will be driven high when the corresponding bits in the OUT and DIR registers are
written to one. When the OUT register is set to zero, the pin is released, allowing the pin to be pulled low with the internal
or an external pull-resistor. If internal pull-down is used, this is also active if the pin is set as input.
Figure 12-6. Output configuration - Wired-OR with optional pull-down.
12.3.4 Wired-AND
In the wired-AND configuration, the pin will be driven low when the corresponding bits in the OUT and DIR registers are
written to zero. When the OUT register is set to one, the pin is released allowing the pin to be pulled high with the internal
or an external pull-resistor. If internal pull-up is used, this is also active if the pin is set as input.
Figure 12-7. Output configuration - Wired-AND with optional pull-up.
XMEGA B [MANUAL] 128
Atmel-8291C-AVR-XMEGA B -09/2014
12.4 Reading the Pin Value
Independent of the pin data direction, the pin value can be read from the IN register, as shown in Figure 12-1 on page
124. If the digital input is disabled, the pin value cannot be read. The IN register bit and the preceding flip-flop constitute
a synchronizer. The synchronizer introduces a delay on the internal signal line. Figure 12-8 on page 128 shows a timing
diagram of the synchronization when reading an externally applied pin value. The maximum and minimum propagation
delays are denoted as tpd,max and tpd,min, respectively.
Figure 12-8. Synchronization when reading a pin value.
XMEGA B [MANUAL] 129
Atmel-8291C-AVR-XMEGA B -09/2014
12.5 Input Sense Configuration
Input sensing is used to detect an edge or level on the I/O pin input. The different sense configurations that are available
for each pin are detection of a rising edge, falling edge, or any edge or detection of a low level. High level can be
detected by using the inverted input configuration. Input sensing can be used to trigger interrupt requests (IREQ) or
events when there is a change on the pin.
The I/O pins support synchronous and asynchronous input sensing. Synchronous sensing requires the presence of the
peripheral clock, while asynchronous sensing does not require any clock.
Figure 12-9. Input sensing.
12.6 Port Interrupt
Each port has two interrupt vectors, and it is configurable which pins on the port will trigger each interrupt. Port interrupts
must be enabled before they can be used. Which sense configurations can be used to generate interrupts is dependent
on whether synchronous or asynchronous input sensing is available for the selected pin.
For synchronous sensing, all sense configurations can be used to generate interrupts. For edge detection, the changed
pin value must be sampled once by the peripheral clock for an interrupt request to be generated.
For asynchronous sensing, only port pin 2 on each port has full asynchronous sense support. This means that for edge
detection, pin 2 will detect and latch any edge and it will always trigger an interrupt request. The other port pins have
limited asynchronous sense support. This means that for edge detection, the changed value must be held until the device
wakes up and a clock is present. If the pin value returns to its initial value before the end of the device wake-up time, the
device will still wake up, but no interrupt request will be generated.
A low level can always be detected by all pins, regardless of a peripheral clock being present or not. If a pin is configured
for low-level sensing, the interrupt will trigger as long as the pin is held low. In active mode, the low level must be held
until the completion of the currently executing instruction for an interrupt to be generated. In all sleep modes, the low level
must be kept until the end of the device wake-up time for an interrupt to be generated. If the low level disappears before
the end of the wake-up time, the device will still wake up, but no interrupt will be generated.
Table 12-1, Table 12-2, and Table 12-3 on page 130 summarize when interrupts can be triggered for the various input
sense configurations.
D Q
R
INVERTED I/O
Interrupt
Control
D Q
R
Pxn
Synchronizer
INn
EDGE
DETECT
Synchronous sensing
EDGE
DETECT
Asynchronous sensing
IRQ
Synchronous
Events
Asynchronous
Events
XMEGA B [MANUAL] 130
Atmel-8291C-AVR-XMEGA B -09/2014
Table 12-1. Synchronous sense support.
Table 12-2. Full asynchronous sense support.
Table 12-3. Limited asynchronous sense support.
12.7 Port Event
Port pins can generate an event when there is a change on the pin. The sense configurations decide the conditions for
each pin to generate events. Event generation requires the presence of a peripheral clock, and asynchronous event
generation is not possible. For edge sensing, the changed pin value must be sampled once by the peripheral clock for an
event to be generated.
For level sensing, a low-level pin value will not generate events, and a high-level pin value will continuously generate
events. For events to be generated on a low level, the pin configuration must be set to inverted I/O.
Table 12-4. Event sense support
Sense Settings Supported Interrupt Description
Rising edge Yes Always triggered
Falling edge Yes Always triggered
Any edge Yes Always triggered
Low level Yes Pin level must be kept unchanged during wake up
Sense Settings Supported Interrupt Description
Rising edge Yes Always triggered
Falling edge Yes Always triggered
Both edges Yes Always triggered
Low level Yes Pin level must be kept unchanged during wake up
Sense Settings Supported Interrupt Description
Rising edge No -
Falling edge No -
Any edge Yes Pin value must be kept unchanged during wake up
Low level Yes Pin level must be kept unchanged during wake up
Sense Settings Signal event Data event
Rising edge Rising edge Pin value
Falling edge Falling edge Pin value
Both edge Any edge Pin value
Low level Pin value Pin value
XMEGA B [MANUAL] 131
Atmel-8291C-AVR-XMEGA B -09/2014
12.8 Alternate Port Functions
Most port pins have alternate pin functions in addition to being a general purpose I/O pin. When an alternate function is
enabled, it might override the normal port pin function or pin value. This happens when other peripherals that require pins
are enabled or configured to use pins. If and how a peripheral will override and use pins is described in the section for
that peripheral.
The port override signals and related logic (grey) are shown in Figure 12-10 on page 131. These signals are not
accessible from software, but are internal signals between the overriding peripheral and the port pin.
Figure 12-10. Port override signals and related logic.
Q D
R
Q D
R
Synchronizer
D Q
R
D Q
R
DIRn
OUTn
PINnCTRL
INn
Pxn
D Q
R
C
o
n
t
r
o
l
L
o
g
i
c
Digital Input Disable (DID)
Wired AND/OR
Digital Input Pin
Analog Input/Output
Inverted I/O
Pull Enable
Pull Keep
Pull Direction
DID Override Enable
DID Override Value
OUT Override Enable
OUT Override Value
DIR Override Enable
DIR Override Value
XMEGA B [MANUAL] 132
Atmel-8291C-AVR-XMEGA B -09/2014
12.9 Clock and Event Output
It is possible to output the peripheral clock and event channel 0 events to a pin. This can be used to clock, control, and
synchronize external functions and hardware to internal device timing. The output port pin is selectable. If an event
occurs, it remains visible on the port pin as long as the event lasts; normally one peripheral clock cycle.
12.10 Multi-pin configuration
The multi-pin configuration function is used to configure multiple port pins using a single write operation to only one of the
port pin configuration registers. A mask register decides which port pin is configured when one port pin register is written,
while avoiding several pins being written the same way during identical write operations.
12.11 Virtual Ports
Virtual port registers allow the port registers to be mapped virtually in the bit-accessible I/O memory space. When this is
done, writing to the virtual port register will be the same as writing to the real port register. This enables the use of I/O
memory-specific instructions, such as bit-manipulation instructions, on a port register that normally resides in the
extended I/O memory space. There are four virtual ports, and so four ports can be mapped at the same time.
XMEGA B [MANUAL] 133
Atmel-8291C-AVR-XMEGA B -09/2014
12.12 Register Descriptions – Ports
12.12.1 DIR – Data Direction register
z Bit 7:0 – DIR[7:0]: Data Direction
This register sets the data direction for the individual pins of the port. If DIRn is written to one, pin n is configured as an
output pin. If DIRn is written to zero, pin n is configured as an input pin.
12.12.2 DIRSET – Data Direction Set Register
z Bit 7:0 – DIRSET[7:0]: Port Data Direction Set
This register can be used instead of a read-modify-write to set individual pins as output. Writing a one to a bit will set the
corresponding bit in the DIR register. Reading this register will return the value of the DIR register.
12.12.3 DIRCLR – Data Direction Clear register
z Bit 7:0 – DIRCLR[7:0]: Port Data Direction Clear
This register can be used instead of a read-modify-write to set individual pins as input. Writing a one to a bit will clear the
corresponding bit in the DIR register. Reading this register will return the value of the DIR register.
Bit 7 6 5 4 3 2 1 0
+0x00 DIR[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 00000000
Bit 7 6 5 4 3 2 1 0
+0x01 DIRSET[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0000000
Bit 7 6 5 4 3 2 1 0
+0x02 DIRCLR[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 134
Atmel-8291C-AVR-XMEGA B -09/2014
12.12.4 DIRTGL – Data Direction Toggle register
z Bit 7:0 – DIRTGL[7:0]: Port Data Direction Toggle
This register can be used instead of a read-modify-write to toggle the direction of individual pins. Writing a one to a bit will
toggle the corresponding bit in the DIR register. Reading this register will return the value of the DIR register.
12.12.5 OUT – Data Output Value register
z Bit 7:0 – OUT[7:0]: Port Data Output value
This register sets the data output value for the individual pins of the port. If OUTn is written to one, pin n is driven high. If
OUTn is written to zero, pin n is driven low. For this setting to have any effect, the pin direction must be set as output.
12.12.6 OUTSET – Data Output Value Set register
z Bit 7:0 – OUTSET[7:0]: Data Output Value Set
This register can be used instead of a read-modify-write to set the output value of individual pins to one. Writing a one to
a bit will set the corresponding bit in the OUT register. Reading this register will return the value in the OUT register.
12.12.7 OUTCLR – Data Output Value Clear register
z Bit 7:0 – OUTCLR[7:0]: Data Output Value Clear
This register can be used instead of a read-modify-write to set the output value of individual pins to zero. Writing a one to
a bit will clear the corresponding bit in the OUT register. Reading this register will return the value in the OUT register.
Bit 7 6 5 4 3 2 1 0
+0x03 DIRTGL[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 00000000
Bit 7 6 5 4 3 2 1 0
+0x04 OUT[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0000
Bit 7 6 5 4 3 2 1 0
+0x05 OUTSET[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
+0x06 OUTCLR[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 000000
XMEGA B [MANUAL] 135
Atmel-8291C-AVR-XMEGA B -09/2014
12.12.8 OUTTGL – Data Output Value Toggle register
z Bit 7:0 – OUTTGL[7:0]: Port Data Output Value Toggle
This register can be used instead of a read-modify-write to toggle the output value of individual pins. Writing a one to a bit
will toggle the corresponding bit in the OUT register. Reading this register will return the value in the OUT register.
12.12.9 IN – Data Input Value register
z Bit 7:0 – IN[7:0]: Data Input Value
This register shows the value present on the pins if the digital input driver is enabled. INn shows the value of pin n of the
port. The input is not sampled and cannot be read if the digital input buffers are disabled.
12.12.10INTCTRL – Interrupt Control register
z Bit 7:4 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 3:2/1:0 – INTnLVL[1:0]: Interrupt n Level
These bits enable port interrupt n and select the interrupt level as described in “Interrupts and Programmable Multilevel
Interrupt Controller” on page 115.
Bit 7 6 5 4 3 2 1 0
+0x07 OUTTGL[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
+0x08 IN[7:0]
Read/Write RRRRRRRR
Initial Value 0 0000000
Bit 7 6 5 4 3 2 1 0
+0x09 – – – – INT1LVL[1:0] INT0LVL[1:0]
Read/Write R R R R R/W R/W R/W R/W
Initial Value 0 0000000
XMEGA B [MANUAL] 136
Atmel-8291C-AVR-XMEGA B -09/2014
12.12.11INT0MASK – Interrupt 0 Mask register
z Bit 7:0 – INT0MSK[7:0]: Interrupt 0 Mask bits
These bits are used to mask which pins can be used as sources for port interrupt 0. If INT0MASKn is written to one, pin
n is used as source for port interrupt 0.The input sense configuration for each pin is decided by the PINnCTRL registers.
12.12.12INT1MASK – Interrupt 1 Mask register
z Bit 7:0 – INT1MASK[7:0]: Interrupt 1 Mask bits
These bits are used to mask which pins can be used as sources for port interrupt 1. If INT1MASKn is written to one, pin
n is used as source for port interrupt 1.The input sense configuration for each pin is decided by the PINnCTRL registers.
12.12.13INTFLAGS – Interrupt Flag register
z Bit 7:2 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 1:0 – INTnIF: Interrupt n Flag
The INTnIF flag is set when a pin change/state matches the pin's input sense configuration, and the pin is set as source
for port interrupt n. Writing a one to this flag's bit location will clear the flag. For enabling and executing the interrupt, refer
to the interrupt level description.
Bit 7 6 5 4 3 2 1 0
+0x0A INT0MSK[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
+0x0B INT1MSK[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0000000
Bit 7 6 5 4 3 2 1 0
+0x0C – – – – – – INT1IF INT0IF
Read/Write R R R R R R R/W R/W
Initial Value 00000000
XMEGA B [MANUAL] 137
Atmel-8291C-AVR-XMEGA B -09/2014
12.12.14REMAP – Pin Remap register
The pin remap functionality is available for PORTC - PORTF only.
z Bit 7:6 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 5 – SPI: SPI Remap
Setting this bit to one will swap the pin locations of the SCK and MOSI pins to have pin compatibility between SPI and
USART when the USART is operating as a SPI master.
z Bit 4 – USART0: USART0 Remap
Setting this bit to one will move the pin location of USART0 from Px[3:0] to Px[7:4].
z Bit 3 – TC0D: Timer/Counter 0 Output Compare D
Setting this bit will move the location of OC0D from Px3 to Px7.
z Bit 2 – TC0C: Timer/Counter 0 Output Compare C
Setting this bit will move the location of OC0C from Px2 to Px6.
z Bit 1 – TC0B: Timer/Counter 0 Output Compare B
Setting this bit will move the location of OC0B from Px1 to Px5. If this bit is set and PWM from both timer/counter 0 and
timer/counter 1 is enabled, the resulting PWM will be an OR-modulation between the two PWM outputs.
z Bit 0 – TC0A: Timer/Counter 0 Output Compare A
Setting this bit will move the location of OC0A from Px0 to Px4. If this bit is set and PWM from both timer/counter 0 and
timer/counter 1 is enabled, the resulting PWM will be an OR-modulation between the two PWM outputs. See Figure 12-
11.
Figure 12-11.I/O timer/counter.
Bit 7 6 5 4 3 2 1 0
+0x0E – – SPI USART0 TC0D TC0C TC0B TC0A
Read/Write R R R/W R/W R/W R/W R/W R/W
Initial Value 0 0000000
OC0A
OC1A
OCA
XMEGA B [MANUAL] 138
Atmel-8291C-AVR-XMEGA B -09/2014
12.12.15PINnCTRL – Pin n Configuration Register
z Bit 7 – Reserved
This bit is unused and reserved for future use. For compatibility with future devices, always write this bit to zero when this
register is written.
z Bit 6 – INVEN: Inverted I/O Enable
Setting this bit will enable inverted output and input data on pin n.
z Bit 5:3 – OPC: Output and Pull Configuration
These bits set the output/pull configuration on pin n according to Table 12-5.
Table 12-5. Output/pull configuration
z Bit 2:0 – ISC[2:0]: Input/Sense Configuration
These bits set the input and sense configuration on pin n according to Table 12-6 on page 138. The sense configuration
decides how the pin can trigger port interrupts and events. If the input buffer is not disabled, the input cannot be read in
the IN register.
Table 12-6. Input/sense configuration.
Bit 7 6 5 4 3 2 1 0
– INVEN OPC[2:0] ISC[2:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
OPC[2:0] Group Configuration
Description
Output Configuration Pull Configuration
000 TOTEM Totem-pole (N/A)
001 BUSKEEPER Totem-pole Bus-keeper
010 PULLDOWN Totem-pole Pull-down (on input)
011 PULLUP Totem-pole Pull-up (on input)
100 WIREDOR Wired-OR (N/A)
101 WIREDAND Wired-AND (N/A)
110 WIREDORPULL Wired-OR Pull-down
111 WIREDANDPULL Wired-AND Pull-up
ISC[2:0] Group Configuration Description
000 BOTHEDGES Sense both edges
001 RISING Sense rising edge
010 FALLING Sense falling edge
011 LEVEL Sense low level(1)
XMEGA B [MANUAL] 139
Atmel-8291C-AVR-XMEGA B -09/2014
Note: 1. A low-level pin value will not generate events, and a high-level pin value will continuously generate events.
2. Only PORTA - PORTF support the input buffer disable option. If the pin is used for analog functionality, such as AC or ADC, it is recommended to
configure the pin to INPUT_DISABLE.
100 – Reserved
101 – Reserved
110 – Reserved
111 INTPUT_DISABLE Digital input buffer disabled(2)
ISC[2:0] Group Configuration Description
XMEGA B [MANUAL] 140
Atmel-8291C-AVR-XMEGA B -09/2014
12.13 Register Descriptions – Port Configuration
12.13.1 MPCMASK – Multi-pin Configuration Mask register
z Bit 7:0 – MPCMASK[7:0]: Multi-pin Configuration Mask
The MPCMASK register enables configuration of several pins of a port at the same time. Writing a one to bit n makes pin
n part of the multi-pin configuration. When one or more bits in the MPCMASK register is set, writing any of the PINnCTRL
registers will update only the PINnCTRL registers matching the mask in the MPCMASK register for that port. The
MPCMASK register is automatically cleared after any PINnCTRL register is written.
12.13.2 VPCTRLA – Virtual Port-map Control register A
z Bit 7:4 – VP1MAP: Virtual Port 1 Mapping
These bits decide which ports should be mapped to Virtual Port 1. The registers DIR, OUT, IN, and INTFLAGS will be
mapped. Accessing the virtual port registers is equal to accessing the actual port registers. See Table 12-7 on page 141
for configuration.
z Bit 3:0 – VP0MAP: Virtual Port 0 Mapping
These bits decide which ports should be mapped to Virtual Port 0. The registers DIR, OUT, IN, and INTFLAGS will be
mapped. Accessing the virtual port registers is equal to accessing the actual port registers. See Table 12-7 on page 141
for configuration.
12.13.3 VPCTRLB – Virtual Port-map Control register B
z Bit 7:4 – VP3MAP: Virtual Port 3 Mapping
These bits decide which ports should be mapped to Virtual Port 3. The registers DIR, OUT, IN, and INTFLAGS will be
mapped. Accessing the virtual port registers is equal to accessing the actual port registers. See Table 12-7 on page 141
for configuration.
Bit 7 6 5 4 3 2 1 0
+0x00 MPCMASK[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
+0x02 VP1MAP[3:0] VP0MAP[3:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 000000
Bit 7 6 5 4 3 2 1 0
+0x03 VP3MAP[3:0] VP2MAP[3:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 141
Atmel-8291C-AVR-XMEGA B -09/2014
z Bit 3:0 – VP2MAP: Virtual Port 2 Mapping
These bits decide which ports should be mapped to Virtual Port 2. The registers DIR, OUT, IN, and INTFLAGS will be
mapped. Accessing the virtual port registers is equal to accessing the actual port registers. See Table 12-7 on page 141
for configuration.
Table 12-7. Virtual port mapping
12.13.4 CLKEVOUT – Clock and Event Out register
z Bit 7 – CLKEVPIN: Clock and Event Output Pin Select
Setting this pin enables output of clock and event pins on port pin 4 instead of port pin 7.
z Bit 6 – RTCOUT: RTC Clock Output Enable
Setting this bit enables output of the RTC clock source on PORTC pin 6.
z Bit 5:4 – EVOUT[1:0]: Event Output Port
These bits decide which port event channel 0 from the event system will be output to. Pin 7 on the selected port is the
default used, and the CLKOUT bits must be set differently from those of EVOUT. The port pin must be configured as
output for the event to be available on the pin.
VPnMAP[3:0] Group Configuration Description
0000 PORTA PORTA mapped to Virtual Port n
0001 PORTB PORTB mapped to Virtual Port n
0010 PORTC PORTC mapped to Virtual Port n
0011 PORTD PORTD mapped to Virtual Port n
0100 PORTE PORTE mapped to Virtual Port n
0101 PORTF PORTF mapped to Virtual Port n
0110 PORTG PORTG mapped to Virtual Port n
0111 PORTH PORTH mapped to Virtual Port n
1000 PORTJ PORTJ mapped to Virtual Port n
1001 PORTK PORTK mapped to Virtual Port n
1010 PORTL PORTL mapped to Virtual Port n
1011 PORTM PORTM mapped to Virtual Port n
1100 PORTN PORTN mapped to Virtual Port n
1101 PORTP PORTP mapped to Virtual Port n
1110 PORTQ PORTQ mapped to Virtual Port n
1111 PORTR PORTR mapped to Virtual Port n
Bit 7 6 5 4 3 2 1 0
+0x04 CLKEVPIN RTCOUT EVOUT[1:0] CLKOUTSEL[1:0] CLKOUT[1:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 142
Atmel-8291C-AVR-XMEGA B -09/2014
Table 12-8 on page 142 shows the possible configurations.
z Bits 3:2 – CLKOUTSEL[1:0]: Clock Output Select
These bits are used to select which of the peripheral clocks will be output to the port pin if CLKOUT is configured.
z Bit 1:0 – CLKOUT[1:0]: Clock Output Port
These bits decide which port the peripheral clock will be output to. Pin 7 on the selected port is the default used. The
CLKOUT setting will override the EVOUT setting. Thus, if both are enabled on the same port pin, the peripheral clock will
be visible. The port pin must be configured as output for the clock to be available on the pin.
Table 12-10 shows the possible configurations.
Table 12-8. Event output pin selection.
EVOUT[1:0] Group Configuration Description
00 OFF Event output disabled
01 PC Event channel 0 output on PORTC
10 PD Event channel 0 output on PORTD
11 PE Event channel 0 output on PORTE
Table 12-9. Clock output clock selection.
CLKOUTSEL[1:0] Group Configuration Description
00 CLK1X CLKPER output to pin
01 CLK2X CLKPER2 output to pin
10 CLK4X CLKPER4 output to pin
11 – (Reserved)
Table 12-10. Clock output port configurations.
CLKOUT[1:0] Group Configuration Description
00 OFF Clock output disabled
01 PC Clock output on PORTC
10 PD Clock output on PORTD
11 PE Clock output on PORTE
XMEGA B [MANUAL] 143
Atmel-8291C-AVR-XMEGA B -09/2014
12.13.5 EVCTRL – Event Control register
z Bit 7:3 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 2:0 – EVOUTSEL[2:0]: Event Channel Output Selection
These bits define which channel from the event system is output to the port pin. Table 12-11 shows the available
selections.
Bit 7 6 5 4 3 2 1 0
+0x06 – – – – – EVOUTSEL[2:0]
Read/Write R R R R R R/W R/W R/W
Initial Value 0 0 0 0 0 000
Table 12-11. Event channel output selection.
EVOUTSEL[2:0] Group Configuration Description
000 0 Event channel 0 output to pin
001 1 Event channel 1 output to pin
010 2 Event channel 2 output to pin
011 3 Event channel 3 output to pin
100 4 Event channel 4 output to pin
101 5 Event channel 5 output to pin
110 6 Event channel 6 output to pin
111 7 Event channel 7 output to pin
XMEGA B [MANUAL] 144
Atmel-8291C-AVR-XMEGA B -09/2014
12.14 Register Descriptions – Virtual Port
12.14.1 DIR – Data Direction register
z Bit 7:0 – DIR[7:0]: Data Direction
This register sets the data direction for the individual pins in the port mapped by VPCTRLA, virtual port-map control
register A or VPCTRLB, virtual port-map control register B. When a port is mapped as virtual, accessing this register is
identical to accessing the actual DIR register for the port.
12.14.2 OUT – Data Output Value register
z Bit 7:0 – OUT[7:0]: Data Output value
This register sets the data output value for the individual pins in the port mapped by VPCTRLA, virtual port-map control
register A or VPCTRLB, virtual port-map control register B. When a port is mapped as virtual, accessing this register is
identical to accessing the actual OUT register for the port.
12.14.3 IN – Data Input Value register
z Bit 7:0 – IN[7:0]: Data Input value
This register shows the value present on the pins if the digital input buffer is enabled. The configuration of VPCTRLA,
virtual port-map control register A or VPCTRLB, virtual port-map control register A, decides the value in the register.
When a port is mapped as virtual, accessing this register is identical to accessing the actual IN register for the port.
Bit 7 6 5 4 3 2 1 0
+0x00 DIR[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 00000000
Bit 7 6 5 4 3 2 1 0
+0x01 OUT[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0000000
Bit 7 6 5 4 3 2 1 0
+0x02 IN[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 145
Atmel-8291C-AVR-XMEGA B -09/2014
12.14.4 INTFLAGS – Interrupt Flag register
z Bit 7:2 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 1:0 – INTnIF: Interrupt n Flag
The INTnIF flag is set when a pin change/state matches the pin's input sense configuration, and the pin is set as source
for port interrupt n. Writing a one to this flag's bit location will clear the flag. For enabling and executing the interrupt, refer
to the interrupt level description. The configuration of VPCTRLA, virtual port-map control register A, or VPCTRLB, Virtual
Port-map Control Register B, decides which flags are mapped. When a port is mapped as virtual, accessing this register
is identical to accessing the actual INTFLAGS register for the port.
Bit 7 6 5 4 3 2 1 0
+0x03 – – – – – – INT1IF INT0IF
Read/Write R R R R R R R/W R/W
Initial Value 00000000
XMEGA B [MANUAL] 146
Atmel-8291C-AVR-XMEGA B -09/2014
12.15 Register Summary – Ports
12.16 Register Summary – Port Configuration
12.17 Register Summary – Virtual Ports
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
+0x00 DIR DIR[7:0] 133
+0x01 DIRSET DIRSET[7:0] 133
+0x02 DIRCLR DIRCLR[7:0] 133
+0x03 DIRTGL DIRTGL[7:0] 134
+0x04 OUT OUT[7:0] 134
+0x05 OUTSET OUTSET[7:0] 134
+0x06 OUTCLR OUTCLR[7:0] 134
+0x07 OUTTGL OUTTGL[7:0] 135
+0x08 IN IN[7:0] 135
+0x09 INTCTRL – – – – INT1LVL[1:0] INT0LVL[1:0] 135
+0x0A INT0MASK INT0MSK[7:0] 136
+0x0B INT1MASK INT1MSK[7:0] 136
+0x0C INTFLAGS – – – – – – INT1IF INT0IF 136
+0x0D Reserved – – – – – – – –
+0x0E REMAP – – SPI USART0 TC0D TC0C TC0B TC0A 137
+0x0F Reserved – – – – – – – –
+0x10 PIN0CTRL – INVEN OPC[2:0] ISC[2:0] 138
+0x11 PIN1CTRL – INVEN OPC[2:0] ISC[2:0] 138
+0x12 PIN2CTRL – INVEN OPC[2:0] ISC[2:0] 138
+0x13 PIN3CTRL – INVEN OPC[2:0] ISC[2:0] 138
+0x14 PIN4CTRL – INVEN OPC[2:0] ISC[2:0] 138
+0x15 PIN5CTRL – INVEN OPC[2:0] ISC[2:0] 138
+0x16 PIN6CTRL – INVEN OPC[2:0] ISC[2:0] 138
+0x17 PIN7CTRL – INVEN OPC[2:0] ISC[2:0] 138
+0x18 Reserved – – – – – – – –
+0x19 Reserved – – – – – – – –
+0x1A Reserved – – – – – – – –
+0x1B Reserved – – – – – – – –
+0x1C Reserved – – – – – – – –
+0x1D Reserved – – – – – – – –
+0x1E Reserved – – – – – – – –
+0x1F Reserved – – – – – – – –
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
+0x00 MPCMASK MPCMASK[7:0] 140
+0x01 Reserved – – – – – – – –
+0x02 VPCTRLA VP1MAP[3:0] VP0MAP[3:0] 140
+0x03 VPCTRLB VP3MAP[3:0] VP2MAP[3:0] 140
+0x04 CLKEVOU CLKEVPIN RTCOUT EVOUT[1:0] CLKOUTSEL CLKOUT[1:0] 141
+0x05 Reserved – – – – – – – –
+0x06 EVCTRL – – – – – EVCTRL[2:0] 143
+0x07 Reserved – – – – – – – –
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
+0x00 DIR DIR[7:0] 144
+0x01 OUT OUT[7:0] 144
+0x02 IN IN[7:0] 144
+0x03 INTFLAGS – – – – – – INT1IF INT0IF 145
XMEGA B [MANUAL] 147
Atmel-8291C-AVR-XMEGA B -09/2014
12.18 Interrupt Vector Summary – Ports
Offset Source Interrupt Description
0x00 INT0_vect Port interrupt vector 0 offset
0x02 INT1_vect Port interrupt vector 1 offset
XMEGA B [MANUAL] 148
Atmel-8291C-AVR-XMEGA B -09/2014
13. TC0/1 – 16-bit Timer/Counter Type 0 and 1
13.1 Features
z 16-bit timer/counter
z 32-bit timer/counter support by cascading two timer/counters
z Up to four compare or capture (CC) channels
z Four CC channels for timer/counters of type 0
z Two CC channels for timer/counters of type 1
z Double buffered timer period setting
z Double buffered capture or compare channels
z Waveform generation:
z Frequency generation
z Single-slope pulse width modulation
z Dual-slope pulse width modulation
z Input capture:
z Input capture with noise cancelling
z Frequency capture
z Pulse width capture
z 32-bit input capture
z Timer overflow and error interrupts/events
z One compare match or input capture interrupt/event per CC channel
z Can be used with event system for:
z Quadrature decoding
z Count and direction control
z Capture
z Can be used with DMA and to trigger DMA transactions
z High-resolution extension
z Increases frequency and waveform resolution by 4x (2-bit) or 8x (3-bit)
z Advanced waveform extension:
z Low- and high-side output with programmable dead-time insertion (DTI)
z Event controlled fault protection for safe disabling of drivers
13.2 Overview
Atmel AVR XMEGA devices have a set of flexible, 16-bit timer/counters (TC). Their capabilities include accurate program
execution timing, frequency and waveform generation, and input capture with time and frequency measurement of digital
signals. Two timer/counters can be cascaded to create a 32-bit timer/counter with optional 32-bit capture.
A timer/counter consists of a base counter and a set of compare or capture (CC) channels. The base counter can be
used to count clock cycles or events. It has direction control and period setting that can be used for timing. The CC
channels can be used together with the base counter to do compare match control, frequency generation, and pulse
width waveform modulation, as well as various input capture operations. A timer/counter can be configured for either
capture or compare functions, but cannot perform both at the same time.
A timer/counter can be clocked and timed from the peripheral clock with optional prescaling or from the event system.
The event system can also be used for direction control and capture trigger or to synchronize operations.
There are two differences between timer/counter type 0 and type 1. Timer/counter 0 has four CC channels, and
timer/counter 1 has two CC channels. All information related to CC channels 3 and 4 is valid only for timer/counter 0.
Only Timer/Counter 0 has the split mode feature that split it into two 8-bit Timer/Counters with four compare channels
each.
XMEGA B [MANUAL] 149
Atmel-8291C-AVR-XMEGA B -09/2014
Some timer/counters have extensions to enable more specialized waveform and frequency generation. The advanced
waveform extension (AWeX) is intended for motor control and other power control applications. It enables low- and highside
output with dead-time insertion, as well as fault protection for disabling and shutting down external drivers. It can
also generate a synchronized bit pattern across the port pins. The high-resolution (hi-res) extension can be used to
increase the waveform output resolution by four or eight times by using an internal clock source running up to four times
faster than the peripheral clock.
A block diagram of the 16-bit timer/counter with extensions and closely related peripheral modules (in grey) is shown in
Figure 13-1 on page 149.
Figure 13-1. 16-bit timer/counter and closely related peripherals.
13.2.1 Definitions
The following definitions are used throughout the documentation:
Table 13-1. Timer/counter definitions
In general, the term “timer” is used when the timer/counter clock control is handled by an internal source, and the term
“counter” is used when the clock control is handled externally (e.g. counting external events). When used for compare
operations, the CC channels are referred to as “compare channels.” When used for capture operations, the CC channels
are referred to as “capture channels.”
Name Description
BOTTOM The counter reaches BOTTOM when it becomes zero.
MAX The counter reaches MAXimum when it becomes all ones.
TOP
The counter reaches TOP when it becomes equal to the highest value in the count sequence. The TOP
value can be equal to the period (PER) or the compare channel A (CCA) register setting. This is selected
by the waveform generator mode.
UPDATE The timer/counter signals an update when it reaches BOTTOM or TOP, depending on the waveform
generator mode.
XMEGA B [MANUAL] 150
Atmel-8291C-AVR-XMEGA B -09/2014
13.3 Block Diagram
Figure 13-2 on page 150 shows a detailed block diagram of the timer/counter without the extensions.
Figure 13-2. Timer/counter block diagram.
The counter register (CNT), period registers with buffer (PER and PERBUF), and compare and capture registers with
buffers (CCx and CCxBUF) are 16-bit registers. All buffer register have a buffer valid (BV) flag that indicates when the
buffer contains a new value.
During normal operation, the counter value is continuously compared to zero and the period (PER) value to determine
whether the counter has reached TOP or BOTTOM.
The counter value is also compared to the CCx registers. These comparisons can be used to generate interrupt
requests, request DMA transactions or generate events for the event system. The waveform generator modes use these
comparisons to set the waveform period or pulse width.
A prescaled peripheral clock and events from the event system can be used to control the counter. The event system is
also used as a source to the input capture. Combined with the quadrature decoding functionality in the event system
(QDEC), the timer/counter can be used for quadrature decoding.
Base Counter
Compare/Capture
(Unit x = {A,B,C,D})
Counter
=
CCx
CCBUFx
Waveform
Generation
BV
=
PERBUF
PER
CNT
BV
= 0
"count"
"clear"
"direction"
"load" Control Logic
CTRLD
CTRLA
OVF/UNF
(INT/DMA Req.)
ERRIF
(INT Req.)
TOP
"match" CCxIF
(INT/DMA
Req.)
Control Logic
Clock Select "ev" UPDATE
BOTTOM
OCx Out
Event
Select
XMEGA B [MANUAL] 151
Atmel-8291C-AVR-XMEGA B -09/2014
13.4 Clock and Event Sources
The timer/counter can be clocked from the peripheral clock (clkPER) or the event system, and Figure 13-3 shows the clock
and event selection.
Figure 13-3. Clock and event selection.
The peripheral clock is fed into a common prescaler (common for all timer/counters in a device). Prescaler outputs from 1
to 1/1024 are directly available for selection by the timer/counter. In addition, the whole range of prescaling from 1 to 215
times is available through the event system.
Clock selection (CLKSEL) selects one of the prescaler outputs directly or an event channel as the counter (CNT) input.
This is referred to as normal operation of the counter. For details, refer to “Normal Operation” on page 152. By using the
event system, any event source, such as an external clock signal on any I/O pin, may be used as the clock input.
In addition, the timer/counter can be controlled via the event system. The event selection (EVSEL) and event action
(EVACT) settings are used to trigger an event action from one or more events. This is referred to as event action
controlled operation of the counter. For details, refer to “Event Action Controlled Operation” on page 153. When event
action controlled operation is used, the clock selection must be set to use an event channel as the counter input.
By default, no clock input is selected and the timer/counter is not running.
13.5 Double Buffering
The period register and the CC registers are all double buffered. Each buffer register has a buffer valid (BV) flag, which
indicates that the buffer register contains a valid, i.e. new, value that can be copied into the corresponding period or CC
register. When the period register and CC channels are used for a compare operation, the buffer valid flag is set when
data is written to the buffer register and cleared on an UPDATE condition. This is shown for a compare register in Figure
13-4 on page 152.
clkPER /
2{0,...,15}
CKSEL
CNT
EVACT
clkPER /
{1,2,4,8,64,256,1024}
Common
Prescaler clkPER
event channels
(Encoding)
Event System
EVSEL Control Logic
events
XMEGA B [MANUAL] 152
Atmel-8291C-AVR-XMEGA B -09/2014
Figure 13-4. Period and compare double buffering.
When the CC channels are used for a capture operation, a similar double buffering mechanism is used, but in this case
the buffer valid flag is set on the capture event, as shown in Figure 13-5. For capture, the buffer register and the
corresponding CCx register act like a FIFO. When the CC register is empty or read, any content in the buffer register is
passed to the CC register. The buffer valid flag is passed to set the CCx interrupt flag (IF) and generate the optional
interrupt.
Figure 13-5. Capture double buffering.
Both the CCx and CCxBUF registers are available as an I/O register. This allows initialization and bypassing of the buffer
register and the double buffering function.
13.6 Counter Operation
Depending on the mode of operation, the counter is cleared, reloaded, incremented, or decremented at each
timer/counter clock input.
13.6.1 Normal Operation
In normal operation, the counter will count in the direction set by the direction (DIR) bit for each clock until it reaches TOP
or BOTTOM. When up-counting and TOP is reached, the counter will be set to zero when the next clock is given. When
down-counting, the counter is reloaded with the period register value when BOTTOM is reached.
BV
UPDATE
"write enable" "data write"
=
CNT
"match"
CCxBUF
EN CCx
EN
BV
"capture"
IF
CNT
CCxBUF
EN CCx
EN
"INT/DMA
request" data read
XMEGA B [MANUAL] 153
Atmel-8291C-AVR-XMEGA B -09/2014
Figure 13-6. Normal operation.
As shown in Figure 13-6, it is possible to change the counter value when the counter is running. The write access has
higher priority than count, clear, or reload, and will be immediate. The direction of the counter can also be changed
during normal operation.
Normal operation must be used when using the counter as timer base for the capture channels.
13.6.2 Event Action Controlled Operation
The event selection and event action settings can be used to control the counter from the event system. For the counter,
the following event actions can be selected:
z Event system controlled up/down counting.
z Event n will be used as count enable.
z Event n+1 will be used to select between up (1) and down (0). The pin configuration must be set to low level
sensing.
z Event system controlled quadrature decode counting.
13.6.3 32-bit Operation
Two timer/counters can be used together to enable 32-bit counter operation. By using two timer/counters, the overflow
event from one timer/counter (least-significant timer) can be routed via the event system and used as the clock input for
another timer/counter (most-significant timer).
13.6.4 Changing the Period
The counter period is changed by writing a new TOP value to the period register. If double buffering is not used, any
period update is immediate, as shown in Figure 13-7 on page 153.
Figure 13-7. Changing the period without buffering.
CNT
BOTTOM
MAX
"update"
TOP
CNT written
DIR
CNT
MAX
New TOP written to
PER that is higher
than current CNT
Counter Wraparound
New TOP written to
PER that is lower
than current CNT
"update"
"write"
BOTTOM
XMEGA B [MANUAL] 154
Atmel-8291C-AVR-XMEGA B -09/2014
A counter wraparound can occur in any mode of operation when up-counting without buffering, as shown in Figure 13-8.
This due to the fact that CNT and PER are continuously compared, and if a new TOP value that is lower than current
CNT is written to PER, it will wrap before a compare match happen.
Figure 13-8. Unbuffered dual-slope operation.
When double buffering is used, the buffer can be written at any time and still maintain correct operation. The period
register is always updated on the UPDATE condition, as shown for dual-slope operation in Figure 13-9. This prevents
wraparound and the generation of odd waveforms.
Figure 13-9. Changing the period using buffering.
13.7 Capture Channel
The CC channels can be used as capture channels to capture external events and give them a timestamp. To use
capture, the counter must be set for normal operation.
Events are used to trigger the capture; i.e., any events from the event system, including pin change from any pin, can
trigger a capture operation. The event source select setting selects which event channel will trigger CC channel A. The
subsequent event channels then trigger events on subsequent CC channels, if configured. For example, setting the
event source select to event channel 2 results in CC channel A being triggered by event channel 2, CC channel B
triggered by event channel 3, and so on.
CNT
MAX
New TOP written to
PER that is higher
than current CNT
New TOP written to
PER that is lower
than current CNT
"update"
"write"
Counter Wraparound
BOTTOM
CNT
MAX
New Period written to
PERBUF that is higher
than current CNT
New Period written to
PERBUF that is lower
than current CNT
"update"
"write"
New PER is updated
with PERBUF value.
BOTTOM
XMEGA B [MANUAL] 155
Atmel-8291C-AVR-XMEGA B -09/2014
Figure 13-10.Event source selection for capture operation.
The event action setting in the timer/counter will determine the type of capture that is done.
The CC channels must be enabled individually before capture can be done. When the capture condition occur, the
timer/counter will time-stamp the event by copying the current CNT value in the count register into the enabled CC
channel register.
When an I/O pin is used as an event source for the capture, the pin must be configured for edge sensing. For details on
sense configuration on I/O pins, refer to “Input Sense Configuration” on page 129. If the period register value is lower
than 0x8000, the polarity of the I/O pin edge will be stored in the most-significant bit (msb) of the capture register. If the
msb of the capture register is zero, a falling edge generated the capture. If the msb is one, a rising edge generated the
capture.
13.7.1 Input Capture
Selecting the input capture event action makes the enabled capture channel perform an input capture on an event. The
interrupt flags will be set and indicate that there is a valid capture result in the corresponding CC register. At the same
time, the buffer valid flags indicate valid data in the buffer registers.
The counter will continuously count from BOTTOM to TOP, and then restart at BOTTOM, as shown in Figure 13-11. The
figure also shows four capture events for one capture channel.
Figure 13-11.Input capture timing.
13.7.2 Frequency Capture
Selecting the frequency capture event action makes the enabled capture channel perform an input capture and restart on
positive edge events. This enables the timer/counter to measure the period or frequency of a signal directly. The capture
result will be the time (T) from the previous timer/counter restart until the event occurred. This can be used to calculate
the frequency (f) of the signal:
Event System
CH0MUX
CH1MUX
CHnMUX
Rotate
Event channel n
Event Source Selection
CCA capture
CCB capture
CCC capture
CCD capture
Event channel 0
Event channel 1
events
CNT
TOP
BOTTOM
Capture 0 Capture 1 Capture 2 Capture 3
f 1
T = ---
XMEGA B [MANUAL] 156
Atmel-8291C-AVR-XMEGA B -09/2014
Figure 13-12 on page 156 shows an example where the period of an external signal is measured twice.
Figure 13-12.Frequency capture of an external signal.
Since all capture channels use the same counter (CNT), only one capture channel must be enabled at a time. If two
capture channels are used with different sources, the counter will be restarted on positive edge events from both input
sources, and the result will have no meaning.
13.7.3 Pulse Width Capture
Selecting the pulse width measure event action makes the enabled compare channel perform the input capture action on
falling edge events and the restart action on rising edge events. The counter will then restart on positive edge events,
and the input capture will be performed on the negative edge event. The event source must be an I/O pin, and the sense
configuration for the pin must be set to generate an event on both edges. Figure 13-13 on page 156 shows and example
where the pulse width is measured twice for an external signal.
Figure 13-13.Pulse width capture of an external signal.
Period (T)
external signal
events
CNT
MAX
BOTTOM
"capture"
Pulsewitdh (tp)
external signal
events
CNT
MAX
BOTTOM
"capture"
XMEGA B [MANUAL] 157
Atmel-8291C-AVR-XMEGA B -09/2014
13.7.4 32-bit Input Capture
Two timer/counters can be used together to enable true 32-bit input capture. In a typical 32-bit input capture setup, the
overflow event of the least-significant timer is connected via the event system and used as the clock input for the mostsignificant
timer.
The most-significant timer will be updated one peripheral clock period after an overflow occurs for the least-significant
timer. To compensate for this, the capture event for the most-significant timer must be equally delayed by setting the
event delay bit for this timer.
13.7.5 Capture Overflow
The timer/counter can detect buffer overflow of the input capture channels. When both the buffer valid flag and the
capture interrupt flag are set and a new capture event is detected, there is nowhere to store the new timestamp. If a
buffer overflow is detected, the new value is rejected, the error interrupt flag is set, and the optional interrupt is
generated.
13.8 Compare Channel
Each compare channel continuously compares the counter value (CNT) with the CCx register. If CNT equals CCx, the
comparator signals a match. The match will set the CC channel's interrupt flag at the next timer clock cycle, and the
event and optional interrupt are generated.
The compare buffer register provides double buffer capability equivalent to that for the period buffer. The double
buffering synchronizes the update of the CCx register with the buffer value to either the TOP or BOTTOM of the counting
sequence according to the UPDATE condition. The synchronization prevents the occurrence of odd-length, nonsymmetrical
pulses for glitch-free output.
13.8.1 Waveform Generation
The compare channels can be used for waveform generation on the corresponding port pins. To make the waveform
visible on the connected port pin, the following requirements must be fulfilled:
1. A waveform generation mode must be selected.
2. Event actions must be disabled.
3. The CC channels used must be enabled. This will override the corresponding port pin output register.
4. The direction for the associated port pin must be set to output.
Inverted waveform output is achieved by setting the invert output bit for the port pin.
13.8.2 Frequency (FRQ) Waveform Generation
For frequency generation the period time (T) is controlled by the CCA register instead of PER. The waveform generation
(WG) output is toggled on each compare match between the CNT and CCA registers, as shown in Figure 13-14 on page
158.
XMEGA B [MANUAL] 158
Atmel-8291C-AVR-XMEGA B -09/2014
Figure 13-14.Frequency waveform generation.
The waveform frequency (fFRQ) is defined by the following equation:
where N represents the prescaler divider used. The waveform generated will have a maximum frequency of half of the
peripheral clock frequency (fclkPER) when CCA is set to zero (0x0000) and no prescaling is used. This also applies when
using the hi-res extension, since this increases the resolution and not the frequency.
13.8.3 Single-slope PWM Generation
For single-slope PWM generation, the period (T) is controlled by PER, while CCx registers control the duty cycle of the
WG output. Figure 13-15 shows how the counter counts from BOTTOM to TOP and then restarts from BOTTOM. The
waveform generator (WG) output is set on the compare match between the CNT and CCx registers and cleared at TOP.
Figure 13-15.Single-slope pulse width modulation.
The PER register defines the PWM resolution. The minimum resolution is 2 bits (PER=0x0003), and the maximum
resolution is 16 bits (PER=MAX).
The following equation calculate the exact resolution for single-slope PWM (RPWM_SS):
The single-slope PWM frequency (fPWM_SS) depends on the period setting (PER) and the peripheral clock frequency
(fclkPER), and can be calculated by the following equation:
CNT
MAX
"update"
TOP
Period (T) Direction Change CNT written
BOTTOM
WG Output
f FRQ
fclkPER
2N CCA ( ) + 1 = ----------------------------------
CNT
MAX
TOP
Period (T) "match"
BOTTOM
WG Output
CCx=BOTTOM
CCx
CCx=TOP "update"
RPWM_SS
log( ) PER 1 +
log( ) 2 = ---------------------------------
XMEGA B [MANUAL] 159
Atmel-8291C-AVR-XMEGA B -09/2014
where N represents the prescaler divider used. The waveform generated will have a maximum frequency of half of the
peripheral clock frequency (fclkPER) when CCA is set to zero (0x0000) and no prescaling is used. This also applies when
using the hi-res extension, since this increases the resolution and not the frequency.
13.8.4 Dual-slope PWM
For dual-slope PWM generation, the period (T) is controlled by PER, while CCx registers control the duty cycle of the WG
output. Figure 13-16 shows how for dual-slope PWM the counter counts repeatedly from BOTTOM to TOP and then from
TOP to BOTTOM. The waveform generator output is set on BOTTOM, cleared on compare match when up-counting,
and set on compare match when down-counting.
Figure 13-16.Dual-slope pulse width modulation.
Using dual-slope PWM results in a lower maximum operation frequency compared to the single-slope PWM operation.
The period register (PER) defines the PWM resolution. The minimum resolution is 2 bits (PER=0x0003), and the
maximum resolution is 16 bits (PER=MAX).
The following equation calculate the exact resolution for dual-slope PWM (RPWM_DS):
The PWM frequency depends on the period setting (PER) and the peripheral clock frequency (fclkPER), and can be
calculated by the following equation:
N represents the prescaler divider used. The waveform generated will have a maximum frequency of half of the
peripheral clock frequency (fclkPER) when CCA is set to zero (0x0000) and no prescaling is used. This also applies when
using the hi-res extension, since this increases the resolution and not the frequency.
13.8.5 Port Override for Waveform Generation
To make the waveform generation available on the port pins, the corresponding port pin direction must be set as output.
The timer/counter will override the port pin values when the CC channel is enabled (CCENx) and a waveform generation
mode is selected.
f PWM_SS
fclkPER
N( ) PER 1 + = -----------------------------
CNT
MAX
TOP
Period (T)
BOTTOM
WG Output
CCx=BOTTOM
CCx
CCx=TOP "match"
"update"
RPWM_DS
log( ) PER 1 +
log( ) 2 = ---------------------------------
f PWM_DS
fclkPER
2NPER = --------------------
XMEGA B [MANUAL] 160
Atmel-8291C-AVR-XMEGA B -09/2014
Figure 13-17 on page 160 shows the port override for a timer/counter. The timer/counter CC channel will override the
port pin output value (OUT) on the corresponding port pin. Enabling inverted I/O on the port pin (INVEN) inverts the
corresponding WG output.
Figure 13-17.Port override for timer/counter 0 and 1.
13.9 Interrupts and events
The timer/counter can generate both interrupts and events. The counter can generate an interrupt on overflow/underflow,
and each CC channel has a separate interrupt that is used for compare or capture. In addition, an error interrupt can be
generated if any of the CC channels is used for capture and a buffer overflow condition occurs on a capture channel.
Events will be generated for all conditions that can generate interrupts. For details on event generation and available
events, refer to “Event System” on page 63.
13.10 DMA Support
The interrupt flags can be used to trigger DMA transactions. Table 13-2 lists the transfer triggers available from the
timer/counter and the DMA action that will clear the transfer trigger. For more details on using DMA, refer to “DMAC -
Direct Memory Access Controller” on page 47.
Table 13-2. DMA request sources
13.11 Timer/Counter Commands
A set of commands can be given to the timer/counter by software to immediately change the state of the module. These
commands give direct control of the UPDATE, RESTART, and RESET signals.
An update command has the same effect as when an update condition occurs. The update command is ignored if the
lock update bit is set.
The software can force a restart of the current waveform period by issuing a restart command. In this case the counter,
direction, and all compare outputs are set to zero.
A reset command will set all timer/counter registers to their initial values. A reset can be given only when the
timer/counter is not running (OFF).
OUT
CCExEN INVEN
OCx Waveform
Request Acknowledge Comment
OVFIF/UNFIF
DMA controller writes to CNT
DMA controller writes to PER
DMA controller writes to PERBUF
DMA controller writes to DTHSBUF or DTLSBUF in
AWeX when in Pattern Generation Mode
ERRIF N/A
CCxIF DMA controller access of CCx
DMA controller access of CCxBUF
Input capture operation
Output compare operation
XMEGA B [MANUAL] 161
Atmel-8291C-AVR-XMEGA B -09/2014
13.12 Register Description
13.12.1 CTRLA – Control register A
z Bit 7:4 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 3:0 – CLKSEL[3:0]: Clock Select
These bits select the clock source for the timer/counter according to Table 13-3.
CLKSEL=0001 must be set to ensure a correct output from the waveform generator when the hi-res extension is
enabled.
Table 13-3. Clock select options
13.12.2 CTRLB – Control register B
z Bit 7:4 – CCxEN: Compare or Capture Enable
Setting these bits in the FRQ or PWM waveform generation mode of operation will override the port output register for the
corresponding OCn output pin. When input capture operation is selected, the CCxEN bits enable the capture operation
for the corresponding CC channel.
Bit 7 6 5 4 3 2 1 0
+0x00 – – – – CLKSEL[3:0]
Read/Write R R R R R/W R/W R/W R/W
Initial Value 00000000
CLKSEL[3:0] Group Configuration Description
0000 OFF None (i.e, timer/counter in OFF state)
0001 DIV1 Prescaler: Clk
0010 DIV2 Prescaler: Clk/2
0011 DIV4 Prescaler: Clk/4
0100 DIV8 Prescaler: Clk/8
0101 DIV64 Prescaler: Clk/64
0110 DIV256 Prescaler: Clk/256
0111 DIV1024 Prescaler: Clk/1024
1nnn EVCHn Event channel n, n= [0,...,7]
Bit 7 6 5 4 3 2 1 0
+0x01 CCDEN CCCEN CCBEN CCAEN – WGMODE[2:0]
Read/Write R/W R/W R/W R/W R R/W R/W R/W
Initial Value 00000000
XMEGA B [MANUAL] 162
Atmel-8291C-AVR-XMEGA B -09/2014
z Bit 3 – Reserved
This bit is unused and reserved for future use. For compatibility with future devices, always write this bit to zero when this
register is written.
z Bit 2:0 – WGMODE[2:0]: Waveform Generation Mode
These bits select the waveform generation mode, and control the counting sequence of the counter, TOP value,
UPDATE condition, interrupt/event condition, and type of waveform that is generated according to Table 13-4.
No waveform generation is performed in the normal mode of operation. For all other modes, the result from the waveform
generator will only be directed to the port pins if the corresponding CCxEN bit has been set to enable this. The port pin
direction must be set as output.
Table 13-4. Timer waveform generation mode.
13.12.3 CTRLC – Control register C
z Bit 7:4 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 3:0 – CMPx: Compare Output Value x
These bits allow direct access to the waveform generator's output compare value when the timer/counter is set in the
OFF state. This is used to set or clear the WG output value when the timer/counter is not running.
WGMODE[2:0]
Group
Configuration
Mode of
Operation Top Update OVFIF/Event
000 NORMAL Normal PER TOP TOP
001 FRQ Frequency CCA TOP TOP
010 Reserved - - -
011 SINGLESLOPE Single-slope
PWM PER BOTTOM BOTTOM
100 Reserved - - -
101 DSTOP Dual-slope PWM PER BOTTOM TOP
110 DSBOTH Dual-slope PWM PER BOTTOM TOP and BOTTOM
111 DSBOTTOM Dual-slope PWM PER BOTTOM BOTTOM
Bit 7 6 5 4 3 2 1 0
+0x02 – – – – CMPD CMPC CMPB CMPA
Read/Write R R R R R/W R/W R/W R/W
Initial Value 0 0 0 0 0000
XMEGA B [MANUAL] 163
Atmel-8291C-AVR-XMEGA B -09/2014
13.12.4 CTRLD – Control register D
z Bit 7:5 – EVACT[2:0]: Event Action
These bits define the event action the timer will perform on an event according to Table 13-5 on page 163.
The EVSEL setting will decide which event source or sources have control in this case.
Table 13-5. Timer event action selection.
Selecting any of the capture event actions changes the behavior of the CCx registers and related status and control bits
to be used for capture. The error status flag (ERRIF) will indicate a buffer overflow in this configuration. See “Event
Action Controlled Operation” on page 153 for further details.
z Bit 4 – EVDLY: Timer Delay Event
When this bit is set, the selected event source is delayed by one peripheral clock cycle. This is intended for 32-bit input
capture operation. Adding the event delay is necessary to compensate for the carry propagation delay when cascading
two counters via the event system.
z Bit 3:0 – EVSEL[3:0]:Timer Event Source Select
These bits select the event channel source for the timer/counter. For the selected event channel to have any effect, the
event action bits (EVACT) must be set according to Table 13-6. When the event action is set to a capture operation, the
selected event channel n will be the event channel source for CC channel A, and event channel (n+1)%8, (n+2)%8, and
(n+3)%8 will be the event channel source for CC channel B, C, and D.
Table 13-6. Timer event source selection
Bit 7 6 5 4 3 2 1 0
+0x03 EVACT[2:0] EVDLY EVSEL[3:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
EVACT[2:0] Group Configuration Event Action
000 OFF None
001 CAPT Input capture
010 UPDOWN Externally controlled up/ down count
011 QDEC Quadrature decode
100 RESTART Restart waveform period
101 FRQ Frequency capture
110 PW Pulse width capture
111 Reserved
EVSEL[3:0] Group Configuration Event Source
0000 OFF None
0001 – Reserved
0010 – Reserved
0011 – Reserved
XMEGA B [MANUAL] 164
Atmel-8291C-AVR-XMEGA B -09/2014
13.12.5 CTRLE – Control register E
z Bit 7:2 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 1:0 – BYTEM[1:0]: Byte Mode
These bits select the timer/counter operation mode according to Table 13-7.
Table 13-7. Clock select
13.12.6 INTCTRLA – Interrupt Enable register A
z Bit 7:4 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
0100 – Reserved
0101 – Reserved
0110 – Reserved
0111 – Reserved
1nnn CHn Event channel n, n={0,...,7}
EVSEL[3:0] Group Configuration Event Source
Bit 7 6 5 4 3 2 1 0
+0x04 – – – – – – BYTEM[1:0]
Read/Write R R R R R R R R/W
Initial Value 00000000
BYTEM[1:0] Group Configuration Description
00 NORMAL Timer/counter is set to normal mode (timer/counter type 0)
01 BYTEMODE Upper byte of the counter (CNTH) will be set to zero after each counter
clock cycle
10 SPLITMODE Timer/counter 0 is split into two 8-bit timer/counters (timer/counter type 2)
11 – Reserved
Bit 7 6 5 4 3 2 1 0
+0x06 – – – – ERRINTLVL[1:0] OVFINTLVL[1:0]
Read/Write R R R R R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 165
Atmel-8291C-AVR-XMEGA B -09/2014
z Bit 3:2 – ERRINTLVL[1:0]:Timer Error Interrupt Level
These bits enable the timer error interrupt and select the interrupt level as described in “Interrupts and Programmable
Multilevel Interrupt Controller” on page 115.
z Bit 1:0 – OVFINTLVL[1:0]:Timer Overflow/Underflow Interrupt Level
These bits enable the timer overflow/underflow interrupt and select the interrupt level as described in “Interrupts and
Programmable Multilevel Interrupt Controller” on page 115.
13.12.7 INTCTRLB – Interrupt Enable register B
z Bit 7:0 – CCxINTLVL[7:0] - Compare or Capture x Interrupt Level
These bits enable the timer compare or capture interrupt for channel x and select the interrupt level as described in
“Interrupts and Programmable Multilevel Interrupt Controller” on page 115.
13.12.8 CTRLFCLR/CTRLFSET – Control register F Clear/Set
This register is mapped into two I/O memory locations, one for clearing (CTRLxCLR) and one for setting the register bits
(CTRLxSET) when written. Both memory locations will give the same result when read.
The individual status bit can be set by writing a one to its bit location in CTRLxSET, and cleared by writing a one to its bit
location in CTRLxCLR. This allows each bit to be set or cleared without use of a read-modify-write operation on a single
register.
13.12.8.1 CTRLFCLR
13.12.8.2 CTRLFSET
z Bit 7:4 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 3:2 – CMD[1:0]: Command
These bits can be used for software control of update, restart, and reset of the timer/counter. The command bits are
always read as zero.
Bit 7 6 5 4 3 2 1 0
+0x07 CCDINTLVL[1:0] CCCINTLVL[1:0] CCBINTLVL[1:0] CCAINTLVL[1:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0000000
Bit 7 6 5 4 3 2 1 0
+0x08 – – – – CMD[1:0] LUPD DIR
Read/Write R R R R R R R/W R/W
Initial Value 0 0 0 00000
Bit 7 6 5 4 3 2 1 0
+0x09 – – – – CMD[1:0] LUPD DIR
Read/Write R R R R R/W R/W R/W R/W
Initial Value 0 0 0 00000
XMEGA B [MANUAL] 166
Atmel-8291C-AVR-XMEGA B -09/2014
Table 13-8. Command selections
z Bit 1 – LUPD: Lock Update
When this bit is set, no update of the buffered registers is performed, even though an UPDATE condition has occurred.
Locking the update ensures that all buffers, including DTI buffers, are valid before an update is performed.
This bit has no effect when input capture operation is enabled.
z Bit 0 – DIR: Counter Direction
When zero, this bit indicates that the counter is counting up (incrementing). A one indicates that the counter is in the
down-counting (decrementing) state.
Normally this bit is controlled in hardware by the waveform generation mode or by event actions, but this bit can also be
changed from software.
13.12.9 CTRLGCLR/CTRLGSET – Control register G Clear/Set
Refer to “CTRLFCLR/CTRLFSET – Control register F Clear/Set” on page 165 for information on how to access this type
of status register.
z Bit 7:5 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 4:1 – CCxBV: Compare or Capture x Buffer Valid
These bits are set when a new value is written to the corresponding CCxBUF register. These bits are automatically
cleared on an UPDATE condition.
Note that when input capture operation is used, this bit is set on a capture event and cleared if the corresponding CCxIF
is cleared.
z Bit 0 – PERBV: Period Buffer Valid
This bit is set when a new value is written to the PERBUF register. This bit is automatically cleared on an UPDATE
condition.
CMD Group Configuration Command Action
00 NONE None
01 UPDATE Force update
10 RESTART Force restart
11 RESET Force hard reset (ignored if T/C is not in OFFstate)
Bit 7 6 5 4 3 2 1 0
+0x0A/ +0x0B – – – CCDBV CCCBV CCBBV CCABV PERBV
Read/Write R R R R/W R/W R/W R/W R/W
Initial Value 0 0 0 00000
XMEGA B [MANUAL] 167
Atmel-8291C-AVR-XMEGA B -09/2014
13.12.10INTFLAGS – Interrupt Flag register
z Bit 7:4 – CCxIF: Compare or Capture Channel x Interrupt Flag
The compare or capture interrupt flag (CCxIF) is set on a compare match or on an input capture event on the
corresponding CC channel.
For all modes of operation except for capture, the CCxIF will be set when a compare match occurs between the count
register (CNT) and the corresponding compare register (CCx). The CCxIF is automatically cleared when the
corresponding interrupt vector is executed.
For input capture operation, the CCxIF will be set if the corresponding compare buffer contains valid data (i.e., when
CCxBV is set). The flag will be cleared when the CCx register is read. Executing the interrupt vector in this mode of
operation will not clear the flag.
The flag can also be cleared by writing a one to its bit location.
The CCxIF can be used for requesting a DMA transfer. A DMA read or write access of the corresponding CCx or
CCxBUF will then clear the CCxIF and release the request.
z Bit 3:2 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 1 – ERRIF: Error Interrupt Flag
This flag is set on multiple occasions, depending on the mode of operation.
In the FRQ or PWM waveform generation mode of operation, ERRIF is set on a fault detect condition from the fault
protection feature in the AWeX extention. For timer/counters which do not have the AWeX extention available, this flag is
never set in FRQ or PWM waveform generation mode.
For capture operation, ERRIF is set if a buffer overflow occurs on any of the CC channels.
For event controlled QDEC operation, ERRIF is set when an incorrect index signal is given.
This flag is automatically cleared when the corresponding interrupt vector is executed. The flag can also be cleared by
writing a one to this location.
z Bit 0 – OVFIF: Overflow/Underflow Interrupt Flag
This flag is set either on a TOP (overflow) or BOTTOM (underflow) condition, depending on the WGMODE setting.
OVFIF is automatically cleared when the corresponding interrupt vector is executed. The flag can also be cleared by
writing a one to its bit location.
OVFIF can also be used for requesting a DMA transfer. A DMA write access of CNT, PER, or PERBUF will then clear the
OVFIF bit.
Bit 7 6 5 4 3 2 1 0
+0x0C CCDIF CCCIF CCBIF CCAIF – – ERRIF OVFIF
Read/Write R/W R/W R/W R/W R R R/W R/W
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 168
Atmel-8291C-AVR-XMEGA B -09/2014
13.12.11TEMP – Temporary bits for 16-bit Access
The TEMP register is used for single-cycle, 16-bit access to the 16-bit timer/counter registers by the CPU. The DMA
controller has a separate temporary storage register. There is one common TEMP register for all the 16-bit Timer/counter
registers.
For more details, refer to “Accessing 16-bit Registers” on page 13.
13.12.12CNTL – Counter register Low
The CNTH and CNTL register pair represents the 16-bit value, CNT. CNT contains the 16-bit counter value in the
timer/counter. CPU and DMA write access has priority over count, clear, or reload of the counter.
For more details on reading and writing 16-bit registers, refer to “Accessing 16-bit Registers” on page 13.
z Bit 7:0 – CNT[7:0]: Counter low byte
These bits hold the LSB of the 16-bit counter register.
13.12.13CNTH – Counter register High
z Bit 7:0 – CNT[15:8]: Counter high byte
These bits hold the MSB of the 16-bit counter register.
13.12.14PERL – Period register Low
The PERH and PERL register pair represents the 16-bit value, PER. PER contains the 16-bit TOP value in the
timer/counter.
z Bit 7:0 – PER[7:0]: Period low byte
These bits hold the LSB of the 16-bit period register.
Bit 7 6 5 4 3 2 1 0
+0x0F TEMP[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 00000
Bit 7 6 5 4 3 2 1 0
+0x20 CNT[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
+0x21 CNT[15:8]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 00000000
Bit 7 6 5 4 3 2 1 0
+0x26 PER[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 1 1 111111
XMEGA B [MANUAL] 169
Atmel-8291C-AVR-XMEGA B -09/2014
13.12.15PERH – Period register High
z Bit 7:0 – PER[15:8]: Period high byte
These bits hold the MSB of the 16-bit period register.
13.12.16CCxL – Compare or Capture x register Low
The CCxH and CCxL register pair represents the 16-bit value, CCx. These 16-bit register pairs have two functions,
depending of the mode of operation.
For capture operation, these registers constitute the second buffer level and access point for the CPU and DMA.
For compare operation, these registers are continuously compared to the counter value. Normally, the outputs form the
comparators are then used for generating waveforms.
CCx registers are updated with the buffer value from their corresponding CCxBUF register when an UPDATE condition
occurs.
z Bit 7:0 – CCx[7:0]: Compare or Capture x low byte
These bits hold the LSB of the 16-bit compare or capture register.
13.12.17CCxH – Compare or Capture x register High
z Bit 7:0 – CCx[15:8]: Compare or Capture x high byte
These bits hold the MSB of the 16-bit compare or capture register.
Bit 7 6 5 4 3 2 1 0
+0x27 PER[15:8]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 1 1 1 1 1 1 1 1
Bit 7 6 5 4 3 2 1 0
CCx[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
CCx[15:8]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 170
Atmel-8291C-AVR-XMEGA B -09/2014
13.12.18PERBUFL – Timer/Counter Period Buffer Low
The PERBUFH and PERBUFL register pair represents the 16-bit value, PERBUF. This 16-bit register serves as the
buffer for the period register (PER). Accessing this register using the CPU or DMA will affect the PERBUFV flag.
z Bit 7:0 – PERBUF[7:0]: Period Buffer low byte
These bits hold the LSB of the 16-bit period buffer register.
13.12.19PERBUFH – Timer/Counter Period Buffer High
z Bit 7:0 – PERBUF[15:8]: Period Buffer high byte
These bits hold the MSB of the 16-bit period buffer register.
13.12.20CCxBUFL – Compare or Capture x Buffer register Low
The CCxBUFH and CCxBUFL register pair represents the 16-bit value, CCxBUF. These 16-bit registers serve as the
buffer for the associated compare or capture registers (CCx). Accessing any of these registers using the CPU or DMA
will affect the corresponding CCxBV status bit.
z Bit 7:0 – CCxBUF[7:0]: Compare or Capture Buffer low byte
These bits hold the LSB of the 16-bit compare or capture buffer register.
Bit 7 6 5 4 3 2 1 0
+0x36 PERBUF[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 1 1111111
Bit 7 6 5 4 3 2 1 0
+0x37 PERBUF[15:8]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 1 1 1 1 1 1 1 1
Bit 7 6 5 4 3 2 1 0
CCxBUFx[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 00000000
XMEGA B [MANUAL] 171
Atmel-8291C-AVR-XMEGA B -09/2014
13.12.21CCxBUFH – Compare or Capture x Buffer register High
z Bit 7:0 – CCxBUF[15:8]: Compare or Capture Buffer high byte
These bits hold the MSB of the 16-bit compare or capture buffer register.
Bit 7 6 5 4 3 2 1 0
CCxBUF[15:8]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 172
Atmel-8291C-AVR-XMEGA B -09/2014
13.13 Register Summary
13.14 Interrupt Vector Summary
Note: 1. Available only on timer/counters with four compare or capture channels.
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
+0x00 CTRLA – – – – CLKSEL[3:0] 161
+0x01 CTRLB CCDEN CCCEN CCBEN CCAEN – WGMODE[2:0] 161
+0x02 CTRLC – – – – CMPD CMPC CMPB CMPA 162
+0x03 CTRLD EVACT[2:0] EVDLY EVSEL[3:0] 163
+0x04 CTRLE – – – – – – BYTEM 164
+0x05 Reserved – – – – – – – –
+0x06 INTCTRLA – – – – ERRINTLVL[1:0] OVINTLVL[1:0] 164
+0x07 INTCTRLB CCCINTLVL[1:0] CCCINTLVL[1:0] CCBINTLVL[1:0] CCAINTLVL[1:0] 164
+0x08 CTRLFCLR – – – – CMD[1:0] LUPD DIR 165
+0x09 CTRLFSET – – – – CMD[1:0] LUPD DIR 166
+0x0A CTRLGCLR – – – CCDBV CCCBV CCBBV CCABV PERBV 166
+0x0B CTRLGSET – – – CCDBV CCCBV CCBBV CCABV PERBV 166
+0x0C INTFLAGS CCDIF CCCIF CCBIF CCAIF – – ERRIF OVFIF 167
+0x0D Reserved – – – – – – – –
+0x0E Reserved – – – – – – – –
+0x0F TEMP TEMP[7:0] 168
+0x10 to Reserved – – – – – – – –
+0x20 CNTL CNT[7:0] 168
+0x21 CNTH CNT[15:8] 168
+0x22 to Reserved – – – – – – – –
+0x26 PERL PER[7:0] 168
+0x27 PERH PER[8:15] 169
+0x28 CCAL CCA[7:0] 169
+0x29 CCAH CCA[15:8] 169
+0x2A CCBL CCB[7:0] 169
+0x2B CCBH CCB[15:8] 169
+0x2C CCCL CCC[7:0] 169
+0x02D CCCH CCC[15:8] 169
+0x2E CCDL CCD[7:0] 169
+0x2F CCDH CCD[15:8] 169
+0x30 to Reserved – – – – – – – –
+0x36 PERBUFL PERBUF[7:0] 170
+0x37 PERBUFH PERBUF[15:8] 170
+0x38 CCABUFL CCABUF[7:0] 170
+0x39 CCABUFH CCABUF[15:8] 171
+0x3A CCBBUFL CCBBUF[7:0] 170
+0x3B CCBBUFH CCBBUF[15:8] 171
+0x3C CCCBUFL CCCBUF[7:0] 170
+0x3D CCCBUFH CCCBUF[15:8] 171
+0x3E CCDBUFL CCDBUF[7:0] 170
+0x3F CCDBUFH CCDBUF[15:8] 171
Offset Source Interrupt Description
0x00 OVF_vect Timer/counter overflow/underflow interrupt vector offset
0x02 ERR_vect Timer/counter error interrupt vector offset
0x04 CCA_vect Timer/counter compare or capture channel A interrupt vector offset
0x06 CCB_vect Timer/counter compare or capture channel B interrupt vector offset
0x08 CCC_vect(1) Timer/counter compare or capture channel C interrupt vector offset
0x0A CCD_vect(1) Timer/counter compare or capture channel D interrupt vector offset
XMEGA B [MANUAL] 173
Atmel-8291C-AVR-XMEGA B -09/2014
14. TC2 – 16-bit Timer/Counter Type 2
14.1 Features
z A system of two eight-bit timer/counters
z Low-byte timer/counter
z High-byte timer/counter
z Eight compare channels
z Four compare channels for the low-byte timer/counter
z Four compare channels for the high-byte timer/counter
z Waveform generation
z Single slope pulse width modulation
z Timer underflow interrupts/events
z One compare match interrupt/event per compare channel for the low-byte timer/counter
z Can be used with the event system for count control
z Can be used to trigger DMA transactions
14.2 Overview
A timer/counter 2 is realized when a timer/counter 0 is set in split mode. It is a system of two eight-bit
timer/counters, each with four compare channels. This results in eight configurable pulse width modulation (PWM)
channels with individually controlled duty cycles, and is intended for applications that require a high number of PWM
channels.
The two eight-bit timer/counters in this system are referred to as the low-byte timer/counter and high-byte timer/counter,
respectively. The difference between them is that only the low-byte timer/counter can be used to generate compare
match interrupts, events and DMA triggers.
The two eight-bit timer/counters have a shared clock source and separate period and compare settings. They can be
clocked and timed from the peripheral clock, with optional prescaling, or from the event system. The counters are always
counting down.
The timer/counter 2 is set back to timer/counter 0 by setting it in normal mode; hence, one timer/counter can exist only as
either type 0 or type 2.
A detailed block diagram of the timer/counter 2 showing the low-byte (L) and high-byte (H) timer/counter register split and
compare modules is shown in Figure 14-1 on page 174.
XMEGA B [MANUAL] 174
Atmel-8291C-AVR-XMEGA B -09/2014
14.3 Block Diagram
Figure 14-1. Block diagram of the 16-bit timer/counter 0 with split mode.
14.4 Clock Sources
The timer/counter can be clocked from the peripheral clock (clkPER) and from the event system. Figure 14-2 shows the
clock and event selection.
Figure 14-2. Clock selection.
Base Counter
Compare
(Unit x = {A,B,C,D})
Counter
HPER
= 0
Control Logic
CTRLA
HUNF
(INT/DMA Req.)
BOTTOML
LPER
Compare
(Unit x = {A,B,C,D})
Waveform
Generation
LCMPx
(INT/DMA
Req.)
OCLx Out
=
LCMPx
"match"
BOTTOMH
LCNT "count low"
"load low"
=
HCMPx
Waveform
Generation
"match"
OCHx Out
= 0
"count high"
"load high"
HCNT
Clock Select
LUNF
(INT/DMA Req.)
clkPER /
2{0,...,15}
CLKSEL
CNT
clkPER /
{1,2,4,8,64,256,1024}
Common
Prescaler clkPER
event channels
Event
System events
XMEGA B [MANUAL] 175
Atmel-8291C-AVR-XMEGA B -09/2014
The peripheral clock (clkPER) is fed into the common prescaler (common for all timer/counters in a device). A selection of
prescaler outputs from 1 to 1/1024 is directly available. In addition, the whole range of time prescalings from 1 to 215 is
available through the event system.
The clock selection (CLKSEL) selects one of the clock prescaler outputs or an event channel for the high-byte counter
(HCNT) and low-byte counter (LCNT). By using the event system, any event source, such as an external clock signal, on
any I/O pin can be used as the clock input.
By default, no clock input is selected, and the counters are not running.
14.5 Counter Operation
The counters will always count in single-slope mode. Each counter counts down for each clock cycle until it reaches
BOTTOM, and then reloads the counter with the period register value at the following clock cycle.
Figure 14-3. Counter operation.
As shown in Figure 14-3, the counter can change the counter value while running. The write access has higher priority
than the count clear, and reloads and will be immediate.
14.5.1 Changing the Period
The counter period is changed by writing a new TOP value to the period register. Since the counter is counting down, the
period register can be written at any time without affecting the current period, as shown in Figure 14-4 on page 175. This
prevents wraparound and generation of odd waveforms.
Figure 14-4. Changing the period.
14.6 Compare Channel
Each compare channel continuously compares the counter value with the CMPx register. If CNT equals CMPx, the
comparator signals a match. For the low-byte timer/counter, the match will set the compare channel's interrupt flag at the
next timer clock cycle, and the event and optional interrupt is generated. The high-byte timer/counter does not have
compare interrupt/event.
CNT
BOTTOM
MAX
"reload" TOP
CNT written
CNT
MAX
New TOP written to
PER that is higher
than current CNT
New TOP written to
PER that is lower
than current CNT
"reload"
"write"
BOTTOM
XMEGA B [MANUAL] 176
Atmel-8291C-AVR-XMEGA B -09/2014
14.6.1 Waveform Generation
The compare channels can be used for waveform generation on the corresponding port pins. To make the waveform
visible on the connected port pin, the following requirements must be fulfilled:
1. The compare channels to be used must be enabled. This will override the corresponding port pin output register.
2. The direction for the associated port pin must be set to output.
Inverted waveform output can be achieved by setting invert I/O on the port pin. Refer to “I/O Ports” on page 123 for more
details.
14.6.2 Single-slope PWM Generation
For PWM generation, the period (T) is controlled by the PER register, while the CMPx registers control the duty cycle of
the waveform generator (WG) output. Figure 14-5 on page 176 shows how the counter counts from TOP to BOTTOM,
and then restarts from TOP. The WG output is set on the compare match between the CNT and CMPx registers, and
cleared at BOTTOM.
Figure 14-5. Single-slope pulse width modulation.
The PER register defines the PWM resolution. The minimum resolution is two bits (PER=0x0003), and the maximum
resolution is eight bits (PER=MAX).
The following equation is used to calculate the exact resolution for a single-slope PWM (RPWM_SS) waveform:
The single, slow PWM frequency (fPWM_SS) depends on the period setting (PER) and the peripheral clock frequency
(fPER), and it is calculated by using the following equation:
where N represents the prescaler divider used (1, 2, 4, 8, 64, 256, 1024, or event channel n).
14.6.3 Port Override for Waveform Generation
To make the waveform generation available on the port pins, the corresponding port pin direction must be set as output.
The timer/counter will override the port pin values when the CMP channel is enabled (LCMPENx/HCMPENx).
Figure 14-6 on page 177 shows the port override for the low- and high-byte timer/counters. For the low-byte
timer/counter, CMP channels A to D will override the output value (OUTxn) of port pins 0 to 3 on the corresponding port
pins (Pxn). For the high-byte timer/counter, CMP channels E to H will override port pins 4 to 7. Enabling inverted I/O on
the port pin (INVENxn) inverts the corresponding WG output.
CNT
MAX
TOP
Period (T) "match"
BOTTOM
WG Output
CMPx=BOT
CMPx
CMPx=TOP
RPWM_SS
log( ) PER 1 +
log( ) 2 = ---------------------------------
f PWM_SS
f PER
N( ) PER 1 + = -----------------------------
XMEGA B [MANUAL] 177
Atmel-8291C-AVR-XMEGA B -09/2014
Figure 14-6. Port override for low- and high-byte timer/counters.
14.7 Interrupts and Events
The timer/counters can generate interrupts and events. The counter can generate an interrupt on underflow, and each
CMP channel for the low-byte counter has a separate compare interrupt.
Events will be generated for all conditions that can generate interrupts. For details on event generation and available
events, refer to “Event System” on page 63.
14.8 DMA Support
Timer/counter underflow and compare interrupt flags can trigger a DMA transaction. The acknowledge condition that
clears the flag/request is listed in Table 14-1.
Table 14-1. DMA request sources.
14.9 Timer/Counter Commands
A set of commands can be given to the timer/counter by software to immediately change the state of the module. These
commands give direct control of the update, restart, and reset signals.
The software can force a restart of the current waveform period by issuing a restart command. In this case the counter,
direction, and all compare outputs are set to zero.
A reset command will set all timer/counter registers to their initial values. A reset can only be given when the
timer/counter is not running (OFF).
OUT
LCMPENx /
HCMPENx
INVEN
OCx Waveform
Request Acknowledge Comment
LUNFIF DMAC writes to LCNT
DMAC writes to LPER
HUNFIF DMAC writes to HCNT
DMAC writes to HPER
CCIF{D,C,B,A} DMAC access of
LCMP{D,C,B,A}
Output compare operation
XMEGA B [MANUAL] 178
Atmel-8291C-AVR-XMEGA B -09/2014
14.10 Register Description
14.10.1 CTRLA – Control register A
z Bit 7:4 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 3:0 – CLKSEL[3:0]: Clock Select
These bits select clock source for the timer/counter according to Table 14-2. The clock select is identical for both highand
low-byte timer/counters.
Table 14-2. Clock select
14.10.2 CTRLB – Control register B
z Bit 7:0 – HCMPENx/LCMPENx: High/Low Byte Compare Enable x
Setting these bits will enable the compare output and override the port output register for the corresponding OCn output
pin.
Bit 7 6 5 4 3 2 1 0
+0x00 – – – – CLKSEL[3:0]
Read/Write R R R R R/W R/W R/W R/W
Initial Value 00000000
CLKSEL[3:0] Group Configuration Description
0000 OFF None (i.e., timer/counter in OFF state)
0001 DIV1 Prescaler: ClkPER
0010 DIV2 Prescaler: ClkPER/2
0011 DIV4 Prescaler: ClkPER/4
0100 DIV8 Prescaler: ClkPER/8
0101 DIV64 Prescaler: ClkPER/64
0110 DIV256 Prescaler: ClkPER/256
0111 DIV1024 Prescaler: ClkPER/1024
1nnn EVCHn Event channel n, n= [0,...,7]
Bit 7 6 5 4 3 2 1 0
+0x01 HCMPEND HCMPENC HCMPENB HCMPENA LCMPEND LCMPENC LCMPENB LCMPENA
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 000000
XMEGA B [MANUAL] 179
Atmel-8291C-AVR-XMEGA B -09/2014
14.10.3 CTRLC – Control register C
z Bit 7:0 – HCMPx/LCMPx: High/Low Compare x Output Value
These bits allow direct access to the waveform generator's output compare value when the timer/counter is OFF. This is
used to set or clear the WG output value when the timer/counter is not running.
14.10.4 CTRLE – Control register E
z Bit 7:2 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 0:1 – BYTEM[1:0]: Byte Mode
These bits select the timer/counter operation mode according to Table 14-3.
Table 14-3. Byte mode.
Bit 7 6 5 4 3 2 1 0
+0x02 HCMPD HCMPC HCMPB HCMPA LCMPD LCMPC LCMPB LCMPA
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0000
Bit 7 6 5 4 3 2 1 0
+0x04 – – – – – – BYTEM[1:0]
Read/Write R R R R R R R/W R/W
Initial Value 00000000
BYTEM[1:0] Group Configuration Description
00 NORMAL Timer/counter is set to normal mode (timer/counter type 0)
01 BYTEMODE Upper byte of the counter (HCNT) will be set to zero after each counter
clock.
10 SPLITMODE Timer/counter is split into two eight-bit timer/counters (timer/counter type
2)
11 — Reserved
XMEGA B [MANUAL] 180
Atmel-8291C-AVR-XMEGA B -09/2014
14.10.5 INTCTRLA – Interrupt Enable register A
z Bit 7:4 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 3:2 – HUNFINTLVL[1:0]: High-byte Timer Underflow Interrupt Level
These bits enable the high-byte timer underflow interrupt and select the interrupt level, as described in “Interrupts and
Programmable Multilevel Interrupt Controller” on page 115. The enabled interrupt will be triggered when HUNFIF in the
INTFLAGS register is set.
z Bit 1:0 – LUNFINTLVL[1:0]: Low-byte Timer Underflow Interrupt Level
These bits enable the low-byte timer underflow interrupt and select the interrupt level, as described in “Interrupts and
Programmable Multilevel Interrupt Controller” on page 115. The enabled interrupt will be triggered when LUNFIF in the
INTFLAGS register is set.
14.10.6 INTCTRLB – Interrupt Enable register B
z Bit 7:0 – LCMPxINTLVL[1:0]: Low-byte Compare x Interrupt Level
These bits enable the low-byte timer compare interrupt and select the interrupt level, as described in “Interrupts and
Programmable Multilevel Interrupt Controller” on page 115. The enabled interrupt will be triggered when LCMPxIF in the
INTFLAGS register is set.
14.10.7 CTRLF – Control register F
z Bit 7:4 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 3:2 – CMD[1:0]: Timer/Counter Command
These command bits are used for software control of timer/counter update, restart, and reset. The command bits are
always read as zero. The CMD bits must be used together with CMDEN.
Bit 7 6 5 4 3 2 1 0
+0x06 – – – – HUNFINTLVL[1:0] LUNFINTLVL[1:0]
Read/Write R R R R R/W R/W R/W R/W
Initial Value 0 0 0 0 0000
Bit 7 6 5 4 3 2 1 0
+0x07 LCMPDINTLVL[1:0] LCMPCINTLVL[1:0] LCMPBINTLVL[1:0] LCMPAINTLVL[1:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0000000
Bit 7 6 5 4 3 2 1 0
+0x08 – – – – CMD[1:0] CMDEN[1:0]
Read/Write R R R R R/W R/W R/W R/W
Initial Value 0 0 0 00000
XMEGA B [MANUAL] 181
Atmel-8291C-AVR-XMEGA B -09/2014
Table 14-4. Command selections.
z Bit 1:0 – CMDEN[1:0]: Command Enable
These bits are used to indicate for which timer/counter the command (CMD) is valid.
Table 14-5. Command enable selections.
14.10.8 INTFLAGS – Interrupt Flag register
z Bit 7:4 – LCMPxIF: Compare Channel x Interrupt Flag
The compare interrupt flag (LCMPxIF) is set on a compare match on the corresponding CMP channel.
For all modes of operation, LCMPxIF will be set when a compare match occurs between the count register (LCNT) and
the corresponding compare register (LCMPx). The LCMPxIF is automatically cleared when the corresponding interrupt
vector is executed. The flag can also be cleared by writing a one to its bit location.
z Bit 3:2 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 1 – HUNFIF: High-byte Timer Underflow Interrupt Flag
HUNFIF is set on a BOTTOM (underflow) condition. This flag is automatically cleared when the corresponding interrupt
vector is executed. The flag can also be cleared by writing a one to its bit location.
z Bit 0 – LUNFIF: Low-byte Timer Underflow Interrupt Flag
LUNFIF is set on a BOTTOM (underflow) condition. This flag is automatically cleared when the corresponding interrupt
vector is executed. The flag can also be cleared by writing a one to its bit location.
CMD Group Configuration Description
00 NONE None
01 — Reserved
10 RESTART Force restart
11 RESET Force hard reset (ignored if T/C is not in OFF state)
CMDEN Group Configuration Description
00 – Reserved
01 LOW Command valid for low-byte T/C
10 HIGH Command valid for high-byte T/C
11 BOTH Command valid for both low-byte and high-byte T/C
Bit 7 6 5 4 3 2 1 0
+0x0C LCMPDIF LCMPCIF LCMPBIF LCMPAIF – – HUNFIF LUNFIF
Read/Write R/W R/W R/W R/W R R R/W R/W
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 182
Atmel-8291C-AVR-XMEGA B -09/2014
14.10.9 LCNT – Low-byte Count register
z Bit 7:0 – LCNT[7:0]
LCNT contains the eight-bit counter value for the low-byte timer/counter. The CPU and DMA write accesses have priority
over count, clear, or reload of the counter.
14.10.10HCNT – High-byte Count register
z Bit 7:0 – HCNT[7:0]
HCNT contains the eight-bit counter value for the high-byte timer/counter. The CPU and DMA write accesses have
priority over count, clear, or reload of the counter.
14.10.11LPER – Low-byte Period register
z Bit 7:0 – LPER[7:0]
LPER contains the eight-bit period value for the low-byte timer/counter.
14.10.12HPER – High-byte Period register
z Bit 7:0 – HPER[7:0]
HPER contains the eight-bit period for the high-byte timer/counter.
Bit 7 6 5 4 3 2 1 0
+0x20 LCNT[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 00000000
Bit 7 6 5 4 3 2 1 0
+0x21 HCNT[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
+0x27 LPER[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
+0x26 HPER[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 000000
XMEGA B [MANUAL] 183
Atmel-8291C-AVR-XMEGA B -09/2014
14.10.13LCMPx – Low-byte Compare register x
z Bit 7:0 – LCMPx[7:0], x=[A, B, C, D]
LCMPx contains the eight-bit compare value for the low-byte timer/counter.
These registers are all continuously compared to the counter value. Normally, the outputs from the comparators are then
used for generating waveforms.
14.10.14HCMPx – High-byte Compare register x
z Bit 7:0 – HCMPx[7:0], x=[A, B, C, D]
HCMPx contains the eight-bit compare value for the high-byte timer/counter.
These registers are all continuously compared to the counter value. Normally the outputs from the comparators are then
used for generating waveforms.
Bit 7 6 5 4 3 2 1 0
LCMPx[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
HCMPx[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 184
Atmel-8291C-AVR-XMEGA B -09/2014
14.11 Register Summary
14.12 Interrupt Vector Summary
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
+0x00 CTRLA – – – – CLKSEL[3:0] 178
+0x01 CTRLB HCMPDEN HCMPCEN HCMPBEN HCMPAEN LCMPDEN LCMPCEN LCMPBEN LCMPAEN 178
+0x02 CTRLC HCMPD HCMPC HCMPB HCMPA LCMPD LCMPC LCMPB LCMPA 179
+0x03 Reserved – – – – – – – –
+0x04 CTRLE – – – – – – BYTEM[1:0] 179
+0x05 Reserved – – – – – – – –
+0x06 INTCTRLA – – – – HUNFINTLVL[1:0] LUNFINTLVL[1:0] 180
+0x07 INTCTRLB LCMPDINTLVL[1:0] LCMPCINTLVL[1:0] LCMPBINTLVL[1:0] LCMPAINTLVL[1:0] 180
+0x08 Reserved – – – – – – – –
+0x09 CTRLF – – – – CMD[1:0] CMDEN[1:0] 180
+0x0A Reserved – – – – – – – –
+0x0B Reserved – – – – – – – –
+0x0C INTFLAGS LCMPDIF LCMPCIF LCMPBIF LCMPAIF – – HUNFIF LUNFIF 181
+0x0D Reserved – – – – – – – –
+0x0E Reserved – – – – – – – –
+0x0F Reserved – – – – – – – –
+0x10 to Reserved – – – – – – – –
+0x20 LCNT Low-byte Timer/Counter Count Register 182
+0x21 HCNT High-byte Timer/Counter Count Register 182
+0x22 to Reserved – – – – – – – –
+0x26 LPER Low-byte Timer/Counter Period Register 182
+0x27 HPER High-byte Timer/Counter Period Register 183
+0x28 LCMPA Low-byte Compare Register A 183
+0x29 HCMPA High-byte Compare Register A 183
+0x2A LCMPB Low-byte Compare Register B 183
+0x2B HCMPB High-byte Compare Register B 183
+0x2C LCMPC Low-byte Compare Register C 183
+0x02D HCMPC High-byte Compare Register C 183
+0x2E LCMPD Low-byte Compare Register D 183
+0x2F HCMPD High-byte Compare Register D 183
+0x30 to Reserved – – – – – – – –
Offset Source Interrupt Description
0x00 LUNF_vect Low-byte Timer/counter underflow interrupt vector offset
0x02 HUNF_vect High-byte Timer/counter underflow interrupt vector offset
0x4 LCMPA_vect Low-byte Timer/counter compare channel A interrupt vector offset
0x6 LCMPB_vect Low-byte Timer/counter compare channel B interrupt vector offset
0x8 LCMPC_vect Low-byte Timer/counter compare channel C interrupt vector offset
0x0A LCMPD_vect Low-byte Timer/counter compare channel D interrupt vector offset
XMEGA B [MANUAL] 185
Atmel-8291C-AVR-XMEGA B -09/2014
15. AWeX – Advanced Waveform Extension
15.1 Features
z Waveform output with complementary output from each compare channel
z Four dead-time insertion (DTI) units
z 8-bit resolution
z Separate high and low side dead-time setting
z Double buffered dead time
z Optionally halts timer during dead-time insertion
z Pattern generation unit creating synchronised bit pattern across the port pins
z Double buffered pattern generation
z Optional distribution of one compare channel output across the port pins
z Event controlled fault protection for instant and predictable fault triggering
15.2 Overview
The advanced waveform extension (AWeX) provides extra functions to the timer/counter in waveform generation (WG)
modes. It is primarily intended for use with different types of motor control and other power control applications. It
enables low- and high side output with dead-time insertion and fault protection for disabling and shutting down external
drivers. It can also generate a synchronized bit pattern across the port pins.
Figure 15-1. Advanced waveform extention and closely related peripherals (grey).
As shown in Figure 15-1 on page 185, each of the waveform generator outputs from timer/counter 0 are split into a
complimentary pair of outputs when any AWeX features are enabled. These output pairs go through a dead-time
insertion (DTI) unit that generates the non-inverted low side (LS) and inverted high side (HS) of the WG output with deadtime
insertion between LS and HS switching. The DTI output will override the normal port value according to the port
Timer/Counter 0
AWeX
WG
Channel A
DTI
Channel A
WG
Channel B
DTI
Channel B
WG
Channel C
DTI
Channel C
WG
Channel D
DTI
Channel D
Port
Override
Pattern
Generation
Px0
Px1
Px2
Px3
Px4
Px5
Px6
Px7
Event
System
Fault
Protection
XMEGA B [MANUAL] 186
Atmel-8291C-AVR-XMEGA B -09/2014
override setting. Refer to “I/O Ports” on page 123 for more details.
The pattern generation unit can be used to generate a synchronized bit pattern on the port it is connected to. In addition,
the WG output from compare channel A can be distributed to and override all the port pins. When the pattern generator
unit is enabled, the DTI unit is bypassed.
The fault protection unit is connected to the event system, enabling any event to trigger a fault condition that will disable
the AWeX output. The event system ensures predictable and instant fault reaction, and gives flexibility in the selection of
fault triggers.
15.3 Port Override
The port override logic is common for all the timer/counter extensions. Figure 15-2 on page 187 shows a schematic
diagram of the port override logic. When the dead-time enable (DTIENx) bit is set, the timer/counter extension takes
control over the pin pair for the corresponding channel. Given this condition, the output override enable (OOE) bits take
control over the CCxEN bits.
XMEGA B [MANUAL] 187
Atmel-8291C-AVR-XMEGA B -09/2014
Figure 15-2. Timer/counter extensions and port override logic.
15.4 Dead-time Insertion
The dead-time insertion (DTI) unit generates OFF time where the non-inverted low side (LS) and inverted high side (HS)
of the WG output are both low. This OFF time is called dead time, and dead-time insertion ensures that the LS and HS
never switch simultaneously.
The DTI unit consists of four equal dead-time generators, one for each compare channel in timer/counter 0. Figure 15-3
on page 188 shows the block diagram of one DTI generator. The four channels have a common register that controls the
OUT0
OUTOVEN0
CCAEN
DTICCAEN
INVEN0
OUT1
OUTOVEN1
CCBEN INVEN1
Px0
Px1
Channel
A
DTI
LS
HS
OC0A
OC0B
OCALS
OCAHS
WG 0A
WG 0B
WG 0A
CWCM
OUT2
OUTOVEN2
CCCEN
DTICCBEN
INVEN2
OUT3
OUTOVEN3
CCDEN INVEN3
Px2
Px3
Channel
B
DTI
LS
HS
OC0C
OC0D
OCBLS
OCBHS
WG 0C
WG 0D
OUT4
OUTOVEN4
CCAEN
DTICCCEN
INVEN4
OUT5
OUTOVEN5
CCBEN INVEN5
Px4
Px5
Channel
C
DTI
LS
HS
OC1A
OC1B
OCCLS
OCCHS
WG 1A
WG 1B
OUT6
OUTOVEN6
DTICCDEN
INVEN6
OUT7
OUTOVEN7
INVEN7
Px6
Px7
Channel
D
DTI
LS
HS
OCDLS
OCDHS
WG 0B
WG 0D
WG 0C
"0"
"0"
XMEGA B [MANUAL] 188
Atmel-8291C-AVR-XMEGA B -09/2014
dead time. The high side and low side have independent dead-time setting, and the dead-time registers are double
buffered.
Figure 15-3. Dead-time generator block diagram.
As shown in Figure 15-4 on page 188, the 8-bit dead-time counter is decremented by one for each peripheral clock cycle,
until it reaches zero. A nonzero counter value will force both the low side and high side outputs into their OFF state.
When a change is detected on the WG output, the dead-time counter is reloaded according to the edge of the input. A
positive edge initiates a counter reload of the DTLS register, and a negative edge a reload of DTHS register.
Figure 15-4. Dead-time generator timing diagram.
15.5 Pattern Generation
The pattern generator unit reuses the DTI registers to produce a synchronized bit pattern across the port it is connected
to. In addition, the waveform generator output from compare channel A (CCA) can be distributed to and override all the
port pins. These features are primarily intended for handling the commutation sequence in brushless DC motor (BLDC)
and stepper motor applications. A block diagram of the pattern generator is shown in “Pattern generator block diagram.”
on page 189. For each port pin where the corresponding OOE bit is set, the multiplexer will output the waveform from
CCA.
Dead Time Generator
Edge Detect
BV BV
D Q
= 0
DTLSBUF
DTLS
DTHSBUF
DTHS
"DTLS"
(To PORT)
"DTHS"
(To PORT)
Counter EN
LOAD
WG output
"dti_cnt"
"WG output"
"DTLS"
"DTHS"
tDTILS tDTIHS
T
tP
XMEGA B [MANUAL] 189
Atmel-8291C-AVR-XMEGA B -09/2014
Figure 15-5. Pattern generator block diagram.
As with the other timer/counter double buffered registers, the register update is synchronized to the UPDATE condition
set by the waveform generation mode. If the synchronization provided is not required by the application, the application
code can simply access the DTIOE and PORTx registers directly.
The pin directions must be set for any output from the pattern generator to be visible on the port.
15.6 Fault Protection
The fault protection feature enables fast and deterministic action when a fault is detected. The fault protection is event
controlled. Thus, any event from the event system can be used to trigger a fault action, such as over-current indication
from analog comparator or ADC measurements.
When fault protection is enabled, an incoming event from any of the selected event channels can trigger the event action.
Each event channel can be separately enabled as a fault protection input, and the specified event channels will be ORed
together, allowing multiple event sources to be used for fault protection at the same time.
15.6.1 Fault Actions
When a fault is detected, the direction clear action will clear the direction (DIR) register in the associated port, setting all
port pins as tri-stated inputs.
The fault detection flag is set, the timer/counter’s error interrupt flag is set, and the optional interrupt is generated.
There is maximum of two peripheral clock cycles from when an event occurs in a peripheral until the fault protection
triggers the event action. Fault protection is fully independent of the CPU and DMA, but requires the peripheral clock to
run.
15.6.2 Fault Restore Modes
How the AWeX and timer/counter return from the fault state to normal operation after a fault, when the fault condition is
no longer active, can be selected from one of two different modes:
z In latched mode, the waveform output will remain in the fault state until the fault condition is no longer active and
the fault detect flag has been cleared by software. When both of these conditions are met, the waveform output will
return to normal operation at the next UPDATE condition.
z In cycle-by-cycle mode the waveform output will remain in the fault state until the fault condition is no longer active.
When this condition is met, the waveform output will return to normal operation at the next UPDATE condition.
Timer/Counter 0 (TCx0)
BV DTLSBUF BV
OUTOVEN
DTHSBUF
OUTx
UPDATE CCA WG output
EN EN
1 to 8
Expand
Px[7:0]
XMEGA B [MANUAL] 190
Atmel-8291C-AVR-XMEGA B -09/2014
When returning from a fault state the DIR[7:0] bits corresponding to the enabled DTI channels are restored. OUTOVEN is
unaffected by the fault except that writing to the register from software is blocked.
The UPDATE condition used to restore normal operation is the same as the one in the timer/counter.
15.6.3 Change Protection
To avoid unintentional changes in the fault protection setup, all the control registers in the AWeX extension can be
protected by writing the corresponding lock bit in the advanced waveform extension lock register. For more details, refer
to “I/O Memory Protection” on page 25 and “AWEXLOCK – Advanced Waveform Extension Lock register” on page 44.
When the lock bit is set, control register A, the output override enable register, and the fault detection event mask register
cannot be changed.
To avoid unintentional changes in the fault event setup, it is possible to lock the event system channel configuration by
writing the corresponding event system lock register. For more details, refer to “I/O Memory Protection” on page 25 and
“EVSYSLOCK – Event System Lock register” on page 43.
15.6.4 On-Chip Debug
When fault detection is enabled, an on-chip debug (OCD) system receives a break request from the debugger, which will
by default function as a fault source. When an OCD break request is received, the AWeX and corresponding
timer/counter will enter a fault state, and the specified fault action will be performed.
After the OCD exits from the break condition, normal operation will be started again. In cycle-by-cycle mode, the
waveform output will start on the first UPDATE condition after exit from break, while in latched mode, the fault condition
flag must be cleared in software before the output will be restored. This feature guarantees that the output waveform
enters a safe state during a break.
It is possible to disable this feature.
XMEGA B [MANUAL] 191
Atmel-8291C-AVR-XMEGA B -09/2014
15.7 Register Description
15.7.1 CTRL – Control register
z Bit 7:6 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 5 – PGM: Pattern Generation Mode
Setting this bit enables the pattern generation mode. This will override the DTI, and the pattern generation reuses the
dead-time registers for storing the pattern.
z Bit 4 – CWCM: Common Waveform Channel Mode
If this bit is set, the CC channel A waveform output will be used as input for all the dead-time generators. CC channel B,
C, and D waveforms will be ignored.
z Bit 3:0 – DTICCxEN: Dead-Time Insertion CCx Enable
Setting these bits enables the dead-time generator for the corresponding CC channel. This will override the timer/counter
waveform outputs.
15.7.2 FDEMASK – Fault Detect Event Mask register
z Bit 7:0 – FDEVMASK[7:0]: Fault Detect Event Mask
These bits enable the corresponding event channel as a fault condition input source. Events from all event channels will
be ORed together, allowing multiple sources to be used for fault detection at the same time. When a fault is detected, the
fault detect flag (FDF) is set and the fault detect action (FDACT) will be performed.
Bit 7 6 5 4 3 2 1 0
+0x00 – – PGM CWCM DTICCDEN DTICCCEN DTICCBEN DTICCAEN
Read/Write R R R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
+0x02 FDEVMASK[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 000000
XMEGA B [MANUAL] 192
Atmel-8291C-AVR-XMEGA B -09/2014
15.7.3 FDCTRL - Fault Detection Control register
z Bit 7:5 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 4 – FDDBD: Fault Detection on Debug Break Detection
By default, when this bit is cleared and fault protection is enabled, and OCD break request is treated as a fault. When this
bit is set, an OCD break request will not trigger a fault condition.
z Bit 3 – Reserved
This bit is unused and reserved for future use. For compatibility with future devices, always write this bit to zero when this
register is written.
z Bit 2 – FDMODE: Fault Detection Restart Mode
This bit sets the fault protection restart mode. When this bit is cleared, latched mode is used, and when it is set, cycle-bycycle
mode is used.
In latched mode, the waveform output will remain in the fault state until the fault condition is no longer active and the FDF
has been cleared by software. When both conditions are met, the waveform output will return to normal operation at the
next UPDATE condition.
In cycle-by-cycle mode, the waveform output will remain in the fault state until the fault condition is no longer active.
When this condition is met, the waveform output will return to normal operation at the next UPDATE condition.
z Bit 1:0 – FDACT[1:0]: Fault Detection Action
These bits define the action performed, according to Table 15-1, when a fault condition is detected.
Table 15-1. Fault action.
Bit 7 6 5 4 3 2 1 0
+0x03 – – – FDDBD – FDMODE FDACT[1:0]
Read/Write R R R R/W R R/W R/W R/W
Initial Value 00000000
FDACT[1:0] Group Configuration Description
00 NONE None (fault protection disabled)
01 – Reserved
10 – Reserved
11 CLEARDIR Clear all direction (DIR) bits which correspond to the enabled DTI
channel(s); i.e., tri-state the outputs
XMEGA B [MANUAL] 193
Atmel-8291C-AVR-XMEGA B -09/2014
15.7.4 STATUS – Status register
z Bit 7:3 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 2 – FDF: Fault Detect Flag
This flag is set when a fault detect condition is detected; i.e., when an event is detected on one of the event channels
enabled by FDEVMASK. This flag is cleared by writing a one to its bit location.
z Bit 1 – DTHSBUFV: Dead-time High Side Buffer Valid
If this bit is set, the corresponding DT buffer is written and contains valid data that will be copied into the DTLS register on
the next UPDATE condition. If this bit is zero, no action will be taken. The connected timer/counter unit’s lock update
(LUPD) flag also affects the update for dead-time buffers.
z Bit 0 – DTLSBUFV: Dead-time Low Side Buffer Valid
If this bit is set, the corresponding DT buffer is written and contains valid data that will be copied into the DTHS register
on the next UPDATE condition. If this bit is zero, no action will be taken. The connected timer/counter unit's lock update
(LUPD) flag also affects the update for dead-time buffers.
15.7.5 DTBOTH – Dead-time Concurrent Write to Both Sides
z Bit 7:0 – DTBOTH: Dead-time Both Sides
Writing to this register will update the DTHS and DTLS registers at the same time (i.e., at the same I/O write access).
15.7.6 DTBOTHBUF – Dead-time Concurrent Write to Both Sides Buffer register
z Bit 7:0 – DTBOTHBUF: Dead-time Both Sides Buffer
Writing to this memory location will update the DTHSBUF and DTLSBUF registers at the same time (i.e., at the same I/O
write access).
Bit 7 6 5 4 3 2 1 0
+0x04 – – – – – FDF DTHSBUFV DTLSBUFV
Read/Write R R R R R R/W R/W R/W
Initial Value 00000 0 0 0
Bit 7 6 5 4 3 2 1 0
+0x06 DTBOTH[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 00000000
Bit 7 6 5 4 3 2 1 0
+0x07 DTBOTHBUF[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 00000000
XMEGA B [MANUAL] 194
Atmel-8291C-AVR-XMEGA B -09/2014
15.7.7 DTLS – Dead-time Low Side register
z Bit 7:0 – DTLS: Dead-time Low Side
This register holds the number of peripheral clock cycles for the dead-time low side.
15.7.8 DTHS – Dead-time High Side register
z Bit 7:0 – DTHS: Dead-time High Side
This register holds the number of peripheral clock cycles for the dead-time high side.
15.7.9 DTLSBUF – Dead-time Low Side Buffer register
z Bit 7:0 – DTLSBUF: Dead-time Low Side Buffer
This register is the buffer for the DTLS register. If double buffering is used, valid content in this register is copied to the
DTLS register on an UPDATE condition.
15.7.10 DTHSBUF – Dead-time High Side Buffer register
z Bit 7:0 – DTHSBUF: Dead-time High Side Buffer
This register is the buffer for the DTHS register. If double buffering is used, valid content in this register is copied to the
DTHS register on an UPDATE condition.
Bit 7 6 5 4 3 2 1 0
+0x08 DTLS[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
+0x09 DTHS[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
+0x0A DTLSBUF[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 00000000
Bit 7 6 5 4 3 2 1 0
+0x0B DTHSBUF[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 00000000
XMEGA B [MANUAL] 195
Atmel-8291C-AVR-XMEGA B -09/2014
15.7.11 OUTOVEN – Output Override Enable register
Note: 1. Can be written only if the fault detect flag (FDF) is zero.
z Bit 7:0 – OUTOVEN[7:0]: Output Override Enable
These bits enable override of the corresponding port output register (i.e., one-to-one bit relation to pin position). The port
direction is not overridden.
15.8 Register Summary
Bit 7 6 5 4 3 2 1 0
+0x0C OUTOVEN[7:0]
Read/Write R/W(1) R/W(1) R/W(1) R/W(1) R/W(1) R/W(1) R/W(1) R/W(1)
Initial Value 0 0 0 0 0 0 0 0
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Pag
+0x00 CTRL – – PGM CWCM DTICDAE DTICCCE DTICCBEN DTICCAEN 191
+0x01 Reserved – – – – – – – –
+0x02 FDEMASK FDEVMASK[7:0] 191
+0x03 FDCTRL – – – FDDBD – FDMODE FDACT[1:0] 192
+0x04 STATUS – – – – – FDF DTBHSV DTBLSV 193
+0x05 Reserved – – – – – – – –
+0x06 DTBOTH DTBOTH[7:0] 193
+0x07 DTBOTHBUF DTBOTHBUF[7:0] 193
+0x08 DTLS DTLS[7:0] 194
+0x09 DTHS DTHS[7:0] 194
+0x0A DTLSBUF DTLSBUF[7:0] 194
+0x0B DTHSBUF DTHSBUF[7:0] 194
+0x0C OUTOVEN OUTOVEN[7:0] 195
XMEGA B [MANUAL] 196
Atmel-8291C-AVR-XMEGA B -09/2014
16. Hi-Res – High-Resolution Extension
16.1 Features
z Increases waveform generator resolution up to 8x (3 bits)
z Supports frequency, single-slope PWM, and dual-slope PWM generation
z Supports the AWeX when this is used for the same timer/counter
16.2 Overview
The high-resolution (hi-res) extension can be used to increase the resolution of the waveform generation output from a
timer/counter by four or eight. It can be used for a timer/counter doing frequency, single-slope PWM, or dual-slope PWM
generation. It can also be used with the AWeX if this is used for the same timer/counter.
The hi-res extension uses the peripheral 4x clock (ClkPER4). The system clock prescalers must be configured so the
peripheral 4x clock frequency is four times higher than the peripheral and CPU clock frequency when the hi-res extension
is enabled. Refer to “System Clock Selection and Prescalers” on page 79 for more details.
Figure 16-1. Timer/counter operation with hi-res extension enabled.
When the hi-res extension is enabled, the timer/counter must run from a non-prescaled peripheral clock. The
timer/counter will ignore its two least-significant bits (lsb) in the counter, and counts by four for each peripheral clock
cycle. Overflow/underflow and compare match of the 14 most-significant bits (msb) is done in the timer/counter. Count
and compare of the two lsb is handled and compared in the hi-res extension running from the peripheral 4x clock.
The two lsb of the timer/counter period register must be set to zero to ensure correct operation. If the count register is
read from the application code, the two lsb will always be read as zero, since the timer/counter run from the peripheral
clock. The two lsb are also ignored when generating events.
When the hi-res plus feature is enabled, the function is the same as with the hi-res extension, but the resolution will
increase by eight instead of four. This also means that the 3 lsb are handled by the hi-res extension instead of 2 lsb, as
when only hi-res is enabled. The extra resolution is achieved by counting on both edges of the peripheral 4x clock.
The hi-res extension will not output any pulse shorter than one peripheral clock cycle; i.e., a compare value lower than
four will have no visible output.
CNT[15:2]
HiRes
CCxBUF[15:0]
= 0 =
" match" =
PER[15:2] 0
Waveform
Generation
BOTTOM TOP
Time /Counter
CCx[15:2] [1:0]
2 2 2
0
AWeX
Fault
Protection
Dead - Time
Insertion
Pattern
Generation
clkPER clkPER4
Pxn
XMEGA B [MANUAL] 197
Atmel-8291C-AVR-XMEGA B -09/2014
16.3 Register Description
16.3.1 CTRLA – Control register A
z Bit 7:3 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 2 – HRPLUS: High Resolution Plus
Setting this bit enables high resolution plus. Hi-res plus is the same as hi-res, but will increase the resolution by eight (3
bits) instead of four.
The extra resolution is achieved by operating at both edges of the peripheral 4x clock.
z Bit 1:0 – HREN[1:0]: High Resolution Enable
These bits enables the high-resolution mode for a timer/counter according to Table 16-1.
Setting one or both HREN bits will enable high-resolution waveform generation output for the entire general purpose I/O
port. This means that both timer/counters connected to the same port must enable hi-res if both are used for generating
PWM or FRQ output on pins.
Table 16-1. High resolution enable.
16.4 Register Summary
Bit 7 6 5 4 3 2 1 0
+0x00 – – – – – HRPLUS HREN[1:0]
Read/Write R R R R R R/W R/W R/W
Initial Value 00000000
HREN[1:0] High Resolution Enabled
00 None
01 Timer/counter 0
10 Timer/counter 1
11 Both timer/counters
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
+0x00 CTRLA – – – – – HRPLUS HREN[1:0] 197
XMEGA B [MANUAL] 198
Atmel-8291C-AVR-XMEGA B -09/2014
17. RTC – Real-Time Counter
17.1 Features
z 16-bit resolution
z Selectable clock source
z 32.768kHz external crystal
z External clock
z 32.768kHz internal oscillator
z 32kHz internal ULP oscillator
z Programmable 10-bit clock prescaling
z One compare register
z One period register
z Clear counter on period overflow
z Optional interrupt/event on overflow and compare match
17.2 Overview
The 16-bit real-time counter (RTC) is a counter that typically runs continuously, including in low-power sleep modes, to
keep track of time. It can wake up the device from sleep modes and/or interrupt the device at regular intervals.
The reference clock is typically the 1.024kHz output from a high-accuracy crystal of 32.768kHz, and this is the
configuration most optimized for low power consumption. The faster 32.768kHz output can be selected if the RTC needs
a resolution higher than 1ms. The RTC can also be clocked from an external clock signal, the 32.768kHz internal
oscillator or the 32kHz internal ULP oscillator.
The RTC includes a 10-bit programmable prescaler that can scale down the reference clock before it reaches the
counter. A wide range of resolutions and time-out periods can be configured. With a 32.768kHz clock source, the
maximum resolution is 30.5μs, and time-out periods can range up to 2000 seconds. With a resolution of 1s, the
maximum timeout period is more than18 hours (65536 seconds). The RTC can give a compare interrupt and/or event
when the counter equals the compare register value, and an overflow interrupt and/or event when it equals the period
register value.
Figure 17-1. Real-time counter overview.
32.768kHz Crystal Osc
32.768kHz Int. Osc
TOSC1
TOSC2
External Clock
DIV32
DIV32
32kHz int ULP (DIV32)
RTCSRC
10-bit
prescaler
clkRTC
CNT
PER
COMP
=
=
”match”/
Compare
TOP/
Overflow
XMEGA B [MANUAL] 199
Atmel-8291C-AVR-XMEGA B -09/2014
17.2.1 Clock Domains
The RTC is asynchronous, operating from a different clock source independently of the main system clock and its
derivative clocks, such as the peripheral clock. For control and count register updates, it will take a number of RTC clock
and/or peripheral clock cycles before an updated register value is available in a register or until a configuration change
has effect on the RTC. This synchronization time is described for each register. Refer to “RTCCTRL – RTC Control
register” on page 85 for selecting the asynchronous clock source for the RTC.
17.2.2 Interrupts and Events
The RTC can generate both interrupts and events. The RTC will give a compare interrupt and/or event at the first count
after the counter value equals the Compare register value. The RTC will give an overflow interrupt request and/or event
at the first count after the counter value equals the Period register value. The overflow will also reset the counter value to
zero.
Due to the asynchronous clock domain, events will be generated only for every third overflow or compare match if the
period register is zero. If the period register is one, events will be generated only for every second overflow or compare
match. When the period register is equal to or above two, events will trigger at every overflow or compare match, just as
the interrupt request.
XMEGA B [MANUAL] 200
Atmel-8291C-AVR-XMEGA B -09/2014
17.3 Register Descriptions
17.3.1 CTRL – Control register
z Bit 7:3 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 2:0 – PRESCALER[2:0]: Clock Prescaling factor
These bits define the prescaling factor for the RTC clock according to Table 17-1.
Table 17-1. Real-time counter clock prescaling factor.
17.3.2 STATUS – Status register
z Bit 7:1 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 0 – SYNCBUSY: Synchronization Busy Flag
This flag is set when the CNT, CTRL, PER, or COMP register is busy synchronizing between the RTC clock and system
clock domains. THis flag is automatically cleared when the synchronisation is complete
Bit 7 6 5 4 3 2 1 0
+0x00 – – – – – PRESCALER[2:0]
Read/Write R R R R R R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
PRESCALER[2:0] Group Configuration RTC Clock Prescaling
000 OFF No clock source, RTC stopped
001 DIV1 RTC clock / 1 (no prescaling)
010 DIV2 RTC clock / 2
011 DIV8 RTC clock / 8
100 DIV16 RTC clock / 16
101 DIV64 RTC clock / 64
110 DIV256 RTC clock / 256
111 DIV1024 RTC clock / 1024
Bit 7 6 5 4 3 2 1 0
+0x01 – – – – – – – SYNCBUSY
Read/Write RRRRRRR R
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 201
Atmel-8291C-AVR-XMEGA B -09/2014
17.3.3 INTCTRL – Interrupt Control register
z Bit 7:4 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 3:2 – COMPINTLVL[1:0]: Compare Match Interrupt Enable
These bits enable the RTC compare match interrupt and select the interrupt level, as described in “Interrupts and
Programmable Multilevel Interrupt Controller” on page 115. The enabled interrupt will trigger when COMPIF in the
INTFLAGS register is set.
z Bit 1:0 – OVFINTLVL[1:0]: Overflow Interrupt Enable
These bits enable the RTC overflow interrupt and select the interrupt level, as described in “Interrupts and Programmable
Multilevel Interrupt Controller” on page 115. The enabled interrupt will trigger when OVFIF in the INTFLAGS register is
set.
17.3.4 INTFLAGS – Interrupt Flag register
z Bit 7:2 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 1 – COMPIF: Compare Match Interrupt Flag
This flag is set on the next count after a compare match condition occurs. It is cleared automatically when the RTC
compare match interrupt vector is executed. The flag can also be cleared by writing a one to its bit location.
z Bit 0 – OVFIF: Overflow Interrupt Flag
This flag is set on the next count after an overflow condition occurs. It is cleared automatically when the RTC overflow
interrupt vector is executed. The flag can also be cleared by writing a one to its bit location.
Bit 7 6 5 4 3 2 1 0
+0x02 – – – – COMPINTLVL[1:0] OVFINTLVL[1:0]
Read/Write R R R R R/W R/W R/W R/W
Initial Value 0 0000000
Bit 7 6 5 4 3 2 1 0
+0x03 – – – – – – COMPIF OVFIF
Read/Write R R R R R R R/W R/W
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 202
Atmel-8291C-AVR-XMEGA B -09/2014
17.3.5 TEMP – Temporary register
z Bit 7:0 – TEMP[7:0]: Temporary bits
This register is used for 16-bit access to the counter value, compare value, and TOP value registers. The low byte of the
16-bit register is stored here when it is written by the CPU. The high byte of the 16-bit register is stored when the low byte
is read by the CPU. For more details, refer to “Accessing 16-bit Registers” on page 13.
17.3.6 CNTL – Counter register Low
The CNTH and CNTL register pair represents the 16-bit value, CNT. CNT counts positive clock edges on the prescaled
RTC clock. Reading and writing 16-bit values requires special attention. Refer to “Accessing 16-bit Registers” on page 13
for details.
Due to synchronization between the RTC clock and system clock domains, there is a latency of two RTC clock cycles
from updating the register until this has an effect. Application software needs to check that the SYNCBUSY flag in the
“STATUS – Status register” on page 200 is cleared before writing to this register.
z Bit 7:0 – CNT[7:0]: Counter Value low byte
These bits hold the LSB of the 16-bit real-time counter value.
17.3.7 CNTH – Counter Register High
z Bit 7:0 – CNT[15:8]: Counter Value high byte
These bits hold the MSB of the 16-bit real-time counter value.
Bit 7 6 5 4 3 2 1 0
+0x04 TEMP[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
+0x08 CNT[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 000000
Bit 7 6 5 4 3 2 1 0
+0x09 CNT[15:8]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 203
Atmel-8291C-AVR-XMEGA B -09/2014
17.3.8 PERL – Period register Low
The PERH and PERL register pair represents the 16-bit value, PER. PER is constantly compared with the counter value
(CNT). A match will set OVFIF in the INTFLAGS register and clear CNT. Reading and writing 16-bit values requires
special attention. Refer to “Accessing 16-bit Registers” on page 13 for details.
Due to synchronization between the RTC clock and system clock domains, there is a latency of two RTC clock cycles
from updating the register until this has an effect. Application software needs to check that the SYNCBUSY flag in the
“STATUS – Status register” on page 200 is cleared before writing to this register.
z Bit 7:0 – PER[7:0]: Period low byte
These bits hold the LSB of the 16-bit RTC TOP value.
17.3.9 PERH – Period register High
z Bits 7:0 – PER[15:8]: Period high byte
These bits hold the MSB of the 16-bit RTC TOP value.
17.3.10 COMPL – Compare register Low
The COMPH and COMPL register pair represent the 16-bit value, COMP. COMP is constantly compared with the
counter value (CNT). A compare match will set COMPIF in the INTFLAGS register. Reading and writing 16-bit values
requires special attention. Refer “Accessing 16-bit Registers” on page 13 for details.
Due to synchronization between the RTC clock and system clock domains, there is a latency of two RTC clock cycles
from updating the register until this has an effect. Application software needs to check that the SYNCBUSY flag in the
“STATUS – Status register” on page 200 is cleared before writing to this register.
If the COMP value is higher than the PER value, no RTC compare match interrupt requests or events will ever be
generated.
z Bit 7:0 – COMP[7:0]: Compare value low byte
These bits hold the LSB of the 16-bit RTC compare value.
Bit 7 6 5 4 3 2 1 0
+0x0A PER[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 1 1 111111
Bit 7 6 5 4 3 2 1 0
+0x0B PER[15:8]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 1 1111111
Bit 7 6 5 4 3 2 1 0
+0x0C COMP[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 204
Atmel-8291C-AVR-XMEGA B -09/2014
17.3.11 COMPH – Compare register High
z Bit 7:0 – COMP[15:8]: Compare value high byte
These bits hold the MSB of the 16-bit RTC compare value.
Bit 76543210
+0x0D COMP[15:8]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 00000000
XMEGA B [MANUAL] 205
Atmel-8291C-AVR-XMEGA B -09/2014
17.4 Register Summary
17.5 Interrupt Vector Summary
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
+0x00 CTRL – – – – – PRESCALER[2:0] 200
+0x01 STATUS – – – – – – – SYNCBUSY 200
+0x02 INTCTRL – – – – COMPINTLVL[1:0] OVFINTLVL[1:0] 201
+0x03 INTFLAGS – – – – – – COMPIF OVFIF 201
+0x04 TEMP TEMP[7:0] 202
+0x08 CNTL CNT[7:0] 202
+0x09 CNTH CNT[15:8] 202
+0x0A PERL PER[7:0] 203
+0x0B PERH PER[15:8] 203
+0x0C COMPL COMP[7:0] 204
+0x0D COMPH COMP[15:8] 203
Offset Source Interrupt Description
0x00 OVF_vect Real-time counter overflow interrupt vector
0x02 COMP_vect Real-time counter compare match interrupt vector
XMEGA B [MANUAL] 206
Atmel-8291C-AVR-XMEGA B -09/2014
18. USB – Universal Serial Bus Interface
18.1 Features
z USB 2.0 full speed (12Mbps) and low speed (1.5Mbps) device compliant interface
z Integrated on-chip USB transceiver, no external components needed
z 16 endpoint addresses with full endpoint flexibility for up to 31 endpoints
z One input endpoint per endpoint address
z One output endpoint per endpoint address
z Endpoint address transfer type selectable to
z Control transfers
z Interrupt transfers
z Bulk transfers
z Isochronous transfers
z Configurable data payload size per endpoint, up to 1023 bytes
z Endpoint configuration and data buffers located in internal SRAM
z Configurable location for endpoint configuration data
z Configurable location for each endpoint's data buffer
z Built-in direct memory access (DMA) to internal SRAM for:
z Endpoint configurations
z Reading and writing endpoint data
z Ping-pong operation for higher throughput and double buffered operation
z Input and output endpoint data buffers used in a single direction
z CPU/DMA controller can update data buffer during transfer
z Multipacket transfer for reduced interrupt load and software intervention
z Data payload exceeding maximum packet size is transferred in one continuous transfer
z No interrupts or software interaction on packet transaction level
z Transaction complete FIFO for workflow management when using multiple endpoints
z Tracks all completed transactions in a first-come, first-served work queue
z Clock selection independent of system clock source and selection
z Minimum 1.5MHz CPU clock required for low speed USB operation
z Minimum 12MHz CPU clock required for full speed operation
z Connection to event system
z On chip debug possibilities during USB transactions
18.2 Overview
The USB module is a USB 2.0 full speed (12Mbps) and low speed (1.5Mbps) device compliant interface.
The USB supports 16 endpoint addresses. All endpoint addresses have one input and one output endpoint, for a total of
31 configurable endpoints and one control endpoint. Each endpoint address is fully configurable and can be configured
for any of the four transfer types: control, interrupt, bulk, or isochronous. The data payload size is also selectable, and it
supports data payloads up to 1023 bytes.
No dedicated memory is allocated for or included in the USB module. Internal SRAM is used to keep the configuration for
each endpoint address and the data buffer for each endpoint. The memory locations used for endpoint configurations
and data buffers are fully configurable. The amount of memory allocated is fully dynamic, according to the number of
endpoints in use and the configuration of these. The USB module has built-in direct memory access (DMA), and will
read/write data from/to the SRAM when a USB transaction takes place.
To maximize throughput, an endpoint address can be configured for ping-pong operation. When done, the input and
output endpoints are both used in the same direction. The CPU or DMA controller can then read/write one data buffer
while the USB module writes/reads the others, and vice versa. This gives double buffered communication.
XMEGA B [MANUAL] 207
Atmel-8291C-AVR-XMEGA B -09/2014
Multipacket transfer enables a data payload exceeding the maximum packet size of an endpoint to be transferred as
multiple packets without software intervention. This reduces the CPU intervention and the interrupts needed for USB
transfers.
For low-power operation, the USB module can put the microcontroller into any sleep mode when the USB bus is idle and
a suspend condition is given. Upon bus resumes, the USB module can wake up the microcontroller from any sleep
mode.
Figure 18-1. USB OUT transfer: data packet from host to USB device.
Figure 18-2. USB IN transfer: data packet from USB device to host after request from host.
18.3 Operation
This section gives an overview of the USB module operation during normal transactions. For general details on USB and
the USB protocol, please refer to http://www.usb.org and the USB specification documents.
Internal SRAM
USB
USB Endpoints
Configuration Table
USBEPPTR
USB
Buffers
ENDPOINT 1 DATA
ENDPOINT 2 DATA
ENDPOINT 3 DATA
D
A
T
A
0
D
A
T
A
0
D
A
T
A
0
D
A
T
A
1
D
A
T
A
0
D
A
T
A
1
D
A
T
A
0
D
A
T
A
1
D
A
T
A
0
D
A
T
A
1
D
A
T
A
0
BULK OUT
EPT 2
BULK OUT
EPT 3
BULK OUT
EPT 1
DP
DM
HOST
time
D
A
T
A
0
D
A
T
A
0
D
A
T
A
0
D
A
T
A
1
D
A
T
A
0
D
A
T
A
1
D
A
T
A
0
D
A
T
A
1
D
A
T
A
0
D
A
T
A
1
D
A
T
A
0
EPT 2 EPT 3 EPT 1
DP
DM
HOST
I
N
T
O
K
E
N
I
N
T
O
K
E
N
I
N
T
O
K
E
N
EPT 2 EPT 3 EPT 1
time
Internal SRAM
USB
USB Endpoints
Configuration Table
USBEPPTR
USB
Buffers
ENDPOINT 1 DATA
ENDPOINT 2 DATA
ENDPOINT 3 DATA
CPU
XMEGA B [MANUAL] 208
Atmel-8291C-AVR-XMEGA B -09/2014
18.3.1 Start of Frame
When a start of frame (SOF) token is detected and storing of the frame numbers is enabled, the frame number from the
token is stored in the frame number register (FRAMENUM) and the start of frame interrupt flag (SOFIF) in the interrupt
flag B clear/set register (INTFLAGSBCLR/SET) is set. If there was a CRC or bit-stuff error, the frame error (FRAMEERR)
flag in FRAMENUM is set.
18.3.2 SETUP
When a SETUP token is detected, the USB module fetches the endpoint control register (CTRL) from the addressed
output endpoint in the endpoint configuration table. If the endpoint type is not set to control, the USB module returns to
idle and waits for the next token packet.
Figure 18-3. SETUP transaction.
The USB module then fetches the endpoint data pointer register (DATAPTR) and waits for a DATA0 packet. If a PID
error or any other PID than DATA0 is detected, the USB module returns to idle and waits for the next token packet.
The incoming data are written to the data buffer pointed to by DATAPTR. If a bit-stuff error is detected in the incoming
data, the USB module returns to idle and waits for the next token packet. If the number of received data bytes exceeds
the endpoint's maximum data payload size, as specified by the data size (SIZE) in the endpoint CTRL register, the
remaining received data bytes are discarded. The packet will still be checked for bit-stuff and CRC errors. Software must
never report a maximum data payload size to the host that is greater than specified in SIZE. If there was a bit-stuff or
CRC error in the packet, the USB module returns to idle and waits for the next token packet.
If data was successfully received, an ACK handshake is returned to the host, and the number of received data bytes,
excluding the CRC, is written to the endpoint byte counter (CNT). If the number of received data bytes is the maximum
data payload specified by SIZE, no CRC data are written in the data buffer. If the number of received data bytes is the
maximum data payload specified by SIZE minus one, only the first CRC data byte is written in the data buffer. If the
number of received data bytes is equal or less than the data byte payload specified by SIZE minus two, the two CRC
data bytes are written in the data buffer.
Finally, the setup transaction complete flag (SETUP), data buffer 0 not acknowledge flag (NACK0), and data toggle flag
(TOGGLE) are set, while the remaining flags in the endpoint status register (STATUS) are cleared for the addressed
input and output endpoints. The setup transaction complete interrupt flag (SETUPIF) in INTFLAGSBCLR/SET is set. The
STALL flag in the endpoint CTRL register is cleared for the addressed input and output endpoints.
When a SETUP token is detected and the device address of the token packet does not match that of the endpoint, the
packet is discarded, and the USB module returns to idle and waits for the next token packet.
18.3.3 OUT
When an OUT token is detected, the USB module fetches the endpoint CTRL and STATUS register data from the
addressed output endpoint in its endpoint configuration table. If the endpoint is disabled, the USB module returns to idle
and waits for the next token packet.
SETUP
TOKEN ADDRESS ADDRESS
MATCH? ENDPOINT LEGAL
ENDPOINT?
EP TYPE
CTRL SET? PID PID OK?
DATA BIT STUFF BIT STUFF
OK? CRC OK? ACK
IDLE
No No No No
No No
READ
CONFIG
UPDATE
STATUS
STORE
DATA
Yes Yes
Yes Yes Yes Yes
CRC
XMEGA B [MANUAL] 209
Atmel-8291C-AVR-XMEGA B -09/2014
Figure 18-4. OUT transaction.
The USB module then fetches the endpoint DATAPTR register and waits for a DATA0 or DATA1 packet. If a PID error or
any other PID than DATA0 or DATA1 is detected, the USB module returns to idle and waits for the next token packet.
If the STALL flag in the endpoint CTRL register is set, the incoming data are discarded. If the endpoint is not
isochronous, and the bit stuffing and CRC of the received data are OK, a STALL handshake is returned to the host, and
the STALL interrupt flag is set.
For isochronous endpoints, data from both a DATA0 and DATA1 packet will be accepted. For other endpoint types, the
PID is checked against TOGGLE. If they don't match, the incoming data are discarded and a NAK handshake is returned
to the host. If BUSNACK0 is set, the incoming data are discarded. The overflow flag (OVF) in the endpoint STATUS
register and the overflow interrupt flag (OVFIF) in the INTFLAGSASET/CLR register are set. If the endpoint is not
isochronous, a NAK handshake is returned to the host.
The incoming data are written to the data buffer pointed to by DATAPTR. If a bit-stuff error is detected in the incoming
data, the USB module returns to idle and waits for the next token packet. If the number of received data bytes exceeds
the maximum data payload specified by SIZE, the remaining received data bytes are discarded. The packet will still be
checked for bit-stuff and CRC errors. If there was a bit-stuff or CRC error in the packet, the USB module returns to idle
and waits for the next token packet.
If the endpoint is isochronous and there was a bit-stuff or CRC error in the incoming data, the number of received data
bytes, excluding CRC, is written to the endpoint CNT register. Finally, CRC and BUSNACK0 in the endpoint and
STATUS and CRCIF in INTFLAGSASET/CLR are set.
If data was successfully received, an ACK handshake is returned to the host if the endpoint is not isochronous, and the
number of received data bytes, excluding CRC, is written to CNT. If the number of received data bytes is the maximum
data payload specified by SIZE no CRC data are written in the data buffer. If the number of received data bytes is the
maximum data payload specified by SIZE minus one, only the first CRC data byte is written in the data buffer If the
number of received data bytes is equal or less than the data payload specified by SIZE minus two, the two CRC data
bytes are written in the data buffer.
Finally, the transaction complete flag (TRNCOMPL0) and BUSNACK0 are set and TOGGLE is toggled if the endpoint is
not isochronous. The transaction complete interrupt flag (TRNIF) in INTFLAGSBCLR/SET is set. The endpoint's
configuration table address is written to the FIFO if the transaction complete FIFO mode is enabled.
OUT
TOKEN ADDRESS ADDRESS
MATCH? ENDPOINT LEGAL
ENDPOINT?
EP STATUS
ENABLED? PID PID OK?
DATA BIT STUFF BIT STUFF
OK? CRC OK? ACK
IDLE
No No No
No No
STALL &
ISO? STALL? STALL
ISO? DATA
No
BUSNACK0
SET? NAK
Yes No
No
No
READ
CONFIG
UPDATE
STATUS
STORE
DATA
STORE
DATA
No
Yes Yes Yes Yes
Yes
Yes
Yes
READ
CONFIG
PIDO/1
OK? NAK UPDATE
STATUS
No
Yes
DATA BIT STUFF CRC BIT STUFF
OK? CRC OK?
BUSNACK0
SET?
CRC
Yes No
Yes
Yes
No
Yes
No
Yes
XMEGA B [MANUAL] 210
Atmel-8291C-AVR-XMEGA B -09/2014
When an OUT token is detected and the device address of the token packet does not match that of the endpoint, the
packet is discarded and the USB module returns to idle and waits for the next token packet.
18.3.4 IN
If an IN token is detected the, the USB module fetches the endpoint CTRL and STATUS register data from the addressed
input endpoint in the endpoint configuration table. If the endpoint is disabled, the USB module returns to idle and waits for
the next token packet.
If the STALL flag in endpoint CTRL register is set, and the endpoint is not isochronous, a STALL handshake is returned
to the host, the STALL flag in the endpoint STATUS register and the STALL interrupt flag (STALLIF) in
INTFLAGSACLR/SET are set.
If BUSNACK0 is set, OVF in the endpoint STATUS register and OVFIF in the INTFLAGSACLR/SET register are set. If
the endpoint is not isochronous, a NAK handshake is returned to the host.
The data in the data buffer pointed to by the endpoint DATAPTR register are sent to the host in a DATA0 packet if the
endpoint is isochronous; otherwise, a DATA0 or DATA1 packet according to TOGGLE is sent. When the number of data
bytes specified in endpoint CNT is sent, the CRC is appended and sent to the host. If not, a ZLP handshake is returned
to the host.
For isochronous endpoints, BUSNACK0 and TRNCOMPL0 in the endpoint STATUS register are set. TRNIF is set, and
the endpoint's configuration table address is written to the FIFO if the transaction complete FIFO mode is enabled.
For all non-isochronous endpoints, the USB module waits for an ACK handshake from the host. If an ACK handshake is
not received within 16 USB clock cycles, the USB module returns to idle and waits for the next token packet. If an ACK
handshake was successfully received, BUSNACK0 and TRNCOMPL0 are set and TOGGLE is toggled. TRNIF is set and
the endpoint's configuration table address is written to the FIFO if the transaction complete FIFO mode is enabled.
When an IN token is detected and the device address of the token packet does not match that of the endpoint, the packet
is discarded and the USB module returns to idle and waits for the next token packet.
Figure 18-5. IN transaction.
IN
TOKEN ADDRESS ADDRESS
MATCH? ENDPOINT LEGAL
ENDPOINT?
EP STATUS
ENABLED?
DATA ACK PAYLOAD
OK?
IDLE
No No No
No
STALL &
NO ISO? STALL
NAK
No
READ
CONFIG
READ
DATA
READ
CONFIG
UPDATE
STATUS
Yes
Yes Yes Yes
Yes
BUSNACK0
SET? ISO? Yes No
ISO? ACK
SET?
Yes No
Yes Yes
No
No
ZLP
CRC
XMEGA B [MANUAL] 211
Atmel-8291C-AVR-XMEGA B -09/2014
18.4 SRAM Memory Mapping
The USB module uses internal SRAM to store the:
z Endpoint configuration table
z USB frame number
z Transaction complete FIFO
The endpoint pointer register (EPPTR) is used to set the SRAM address for the endpoint configuration table. The USB
frame number (FRAMENUM) and transaction complete FIFO (FIFO) locations are derived from this. The locations of
these areas are selectable inside the internal SRAM. Figure on page 211 gives the relative memory location of each
area.
Figure 18-6. SRAM memory mapping.
18.5 Clock Generation
The USB module requires a minimum 6MHz clock for USB low speed operation, and a minimum 48MHz clock for USB
full speed operation. It can be clocked from internal or external clock sources by using the internal PLL, or directly from
the 32MHz internal oscillator when it is tuned and calibrated to 48MHz. The CPU and peripherals clocks must run at a
minimum of 1.5MHz for low speed operation, and a minimum of 12MHz for full speed operation.
The USB module clock selection is independent of and separate from the main system clock selection. Selection and
setup are done using the main clock control settings. For details, refer to “System Clock and Clock Options” on page 75.
The Figure 18-7 on page 212 shows an overview of the USB module clock selection.
FIFO EP_ADDRH_MAX
EP_ADDRL_0
EP_ADDRH_0
(MAXEP+1) x 4 Bytes
Active when FIFOEN==1
ENDPOINT
DESCRIPTORS
TABLE
STATUS
CTRL
CNTL
CNTH
DATAPTRL
DATAPTRH
AUXDATAL
AUXDATAH
ENDPOINT
0 OUT
STATUS
CTRL
CNTL
CNTH
DATAPTRL
DATAPTRH
AUXDATAL
AUXDATAH
ENDPOINT
0 IN
STATUS
CTRL
CNTL
CNTH
DATAPTRL
DATAPTRH
AUXDATAL
AUXDATAH
ENDPOINT
MAXEP IN
(MAXEP+1) x 16 Bytes
FRAME
NUMBER
FRAMENUML
FRAMENUMH
2 Bytes
Active when
STFRNUM==1
0x00
0x01
0x02
0x03
0x04
0x05
0x06
0x07
(MAXEP+1)<<4
EPPTR
EPPTR +
(MAXEP+1)*16
SRAM
ADDRESS
XMEGA B [MANUAL] 212
Atmel-8291C-AVR-XMEGA B -09/2014
Figure 18-7. Clock generation configuration.
18.6 Ping-pong Operation
When an endpoint is configured for ping-pong operation, it uses the input and output data buffers to create a single,
double-buffered endpoint that can be set to input or output direction. This provides double-buffered communication, as
the CPU or DMA controller can access one of the buffers, while the other buffer is processing an ongoing transfer. Pingpong
operation is identical to the IN and OUT transactions described above, unless otherwise noted in this section. Pingpong
operation is not possible for control endpoints.
When ping-pong operation is enabled for an endpoint, the endpoint in the opposite direction must be disabled. The data
buffer, data pointer, byte counter, and auxiliary data from the enabled endpoint are used as bank 0, and,
correspondingly, bank 1 for the opposite endpoint direction.
The bank select (BANK) flag in the endpoint STATUS register indicates which data bank will be used in the next
transaction. It is updated after each transaction. The TRNCOMPL0/TRNCOMPL1, underflow/overflow (UDF/OVF), and
CRC flags in the STATUS register are set for either the enabled or the opposite endpoint direction according to the BANK
flag. The data toggle (TOGGLE), data buffer 0/1 not acknowledge (BUSNACK0 and BUSNACK1), and BANK flags are
updated for the enabled endpoint direction only.
Figure 18-8. Ping-pong operation overview.
USB module
48MHz full speed
6MHz for low speed
USBSRC
USB clock
prescaler
USBPSDIV
PLL
48MHz Internal Oscillator
Bank0
Available time for data processing by CPU to avoid NACK
Without Ping-Pong
With Ping-Pong
Bank1
Endpoint
single bank
Endpoint
Double bank
USB data packet
t
t
XMEGA B [MANUAL] 213
Atmel-8291C-AVR-XMEGA B -09/2014
18.7 Multipacket Transfers
Multipacket transfer enables a data payload exceeding the maximum data payload size of an endpoint to be transferred
as multiple packets without any software intervention. This reduces interrupts and software intervention to the higher
level USB transfer, and frees up significant CPU time. Multipacket transfer is identical to the IN and OUT transactions
described above, unless otherwise noted in this section.
The application software provides the size and address of the SRAM buffer to be processed by the USB module for a
specific endpoint, and the USB module will then split the buffer in the required USB data transfer.
Figure 18-9. Multipacket overview.
18.7.1 For Input Endpoints
The total number of data bytes to be sent is written to CNT, as for normal operation. The auxiliary data register
(AUXDATA) is used to store the number of bytes that will be sent, and must be written to zero for a new transfer.
When an IN token is received, the endpoint’s CNT and AUXDATA are fetched. If CNT minus AUXDATA is less than the
endpoint SIZE, endpoint CNT minus endpoint AUXDATA number bytes are transmitted; otherwise, SIZE number of bytes
are transmitted. If endpoint CNT is a multiple of SIZE and auto zero length packet (AZLP) is enabled, the last packet sent
will be zero length.
If a maximum payload size packet was sent (i.e., not the last transaction), AUXDATA is incremented by SIZE. TOGGLE
will be toggled after the transaction has completed if the endpoint is not isochronous. If a short packet was sent (i.e., the
last transaction), AUXDATA is incremented by the data payload. TOGGLE will be toggled if the endpoint is not
isochronous, and BUSNACK, TRNIF, and TRNCOMPL0 will be set.
18.7.2 For Output Endpoints
The number of data bytes received is stored in the endpoint’s CNT register, as for normal operation. Since the endpoint’s
CNT is updated after each transaction, it must be set to zero when setting up a new transfer. The total number of bytes to
be received must be written to AUXDATA. This value must be a multiple of SIZE, except for ISO 1023 bytes endpoints;
otherwise, excess data may be written to SRAM locations used by other parts of the application.
TOGGLE management is as for non-isochronous packets, and BUSNACK0/BUSNACK1 management is as for normal
operation.
If a maximum payload size packet is received, CNT is incremented by SIZE after the transaction has completed, and
TOGGLE toggles if the endpoint is not isochronous. If the updated endpoint CNT is equal to AUXDATA, then
BUSNACK0/BUSNACK1, TRNIF, and TRNCOMPL0/TRNCOMPL1 will be set.
If a short or oversized packet is received, the endpoint’s CNT register will be incremented by the data payload after the
transaction has completed. TOGGLE will be toggled if the endpoint is not isochronous, and BUSNACK0/BUSNACK1,
TRNIF, and TRNCOMPL0/TRNCOMPL1 will be set.
Transfer Complete Interrupt and data processing
Without multipacket
With multipacket
XMEGA B [MANUAL] 214
Atmel-8291C-AVR-XMEGA B -09/2014
18.8 Auto Zero Length Packet
Some IN transfer requires a zero length packet to be generated in order to signal end of transfer to the host. The auto
zero length packet (AZLP) function can be enabled to perform this generation automatically, thus removing the need for
application software or CPU intervention to perform this task.
18.9 Transaction Complete FIFO
The transaction complete FIFO provides a convenient way to keep track of the endpoints that have completed IN or OUT
transactions and need firmware intervention. It creates a first-come, first-served work queue for the application software.
The FIFO size is (MAXEP[3:0] + 1) × 4 bytes, and grows downward, starting from EPPTR - 1. This SRAM memory is
allocated only when the FIFO is enabled.
Figure 18-10.Transfer complete FIFO.
To manage the FIFO, a five-bit write pointer (FIFOWP) and five-bit read pointer (FIFORP) are used by the USB module
and application software, respectively. FIFORP and FIFOWP are one's complemented, and thus hold negative values.
The SRAM location of the data is the sum of EPPTR and the read or write pointer. The number of items in the FIFO is the
difference between FIFOWP and FIFORP. For the programmer, the FIFORP and FIFOWP values have to be cast to a
signed 8-bit integer, and then the offset into the FIFO from this signed integer must be deducted.
The transaction complete interrupt flag (TRNIF) in the INFLAGSB[CLR,SET] register is set to indicate a non-empty FIFO
when FIFORP != FIFOWP, cleared when they are equal, and also set when the FIFO is full.
Each time an endpoint IN or OUT transaction completes successfully, its endpoint configuration table address is stored in
the FIFO at the current write pointer position (i.e., EPPTR + 2 × FIFOWP) and FIFOWP is decremented. When the
pointer reaches the FIFO size, it wraps to zero. When application software reads FIFORP, this is decremented in the
same way. Reading the write pointer has no effect. The endpoint configuration table address can then be read directly
from (EPPTR + 2 × FIFORP).
Figure 18-11.USB transaction complete FIFO example.
USB_TC_ FIFO
TC_EP_ ADDRH_0
TC_EP_ ADDRL_0
TC_EP_ ADDRH_ MAX
ENDPOINT DESCRIPTOR TABLE
TC_EP_ ADDRH_1
TC_EP_ ADDRL_1
INTERNAL SRAM
TC_EP_ ADDRH_2
TC_EP_ ADDRH_2
FIFOWP
FIFORP
EPPTR
SRAM
ADDRESS
EPPTR –
4x( MAXEP+1)
Ep X EpY EpZ t
FIFO
X
Y
Z
FIFOWP
FIFORP
FIFO
X
Y
FIFOWP
FIFORP
FIFO
X
FIFOWP
FIFORP
FIFO
FIFOWP FIFORP
XMEGA B [MANUAL] 215
Atmel-8291C-AVR-XMEGA B -09/2014
18.10 Interrupts and Events
The USB module can generate interrupts and events. The module has 10 interrupt sources. These are split between two
interrupt vectors, the transaction complete (TRNCOMPL) interrupt and the bus event (BUSEVENT) interrupt. An interrupt
group is enabled by setting its interrupt level (INTLVL), while different interrupt sources are enabled individually or in
groups.
Figure 18-12 on page 215 summarizes the interrupts and event sources for the USB module, and shows how they are
enabled.
Figure 18-12.Interrupts and events scheme summary.
18.10.1 Transaction Complete Interrupt
The transaction complete interrupt is generated per endpoint. When an interrupt occurs, the associated endpoint number
is registered and optionally added to the FIFO. The following two interrupt sources use the interrupt vector:
SUSPENDIF SOFIE
RESUMEIF
RSTIF
CRCIF
UNFIF
OVFIF
STALLIF
BSEVIE
STALLIE
BUSSERRIE
SOFIF
SETUPIE
TRNIF
TRNIE
SETUPIF
Busevent
Interrupt request
Transaction Complete
Interrupt request
XMEGA B [MANUAL] 216
Atmel-8291C-AVR-XMEGA B -09/2014
Table 18-1. Transaction complete interrupt sources.
18.10.2 Bus Event Interrupt
The bus event (BUSEVENT) interrupt is used for all interrupts that signal various types of USB line events or error
conditions. These interrupts are related to the USB lines, and are generated for the USB module and per endpoint. The
following eight interrupts use the interrupt vector:
Table 18-2. Bus event interrupt source.
18.10.3 Events
The USB module can generate several events, and these are available to the event system, allowing latency-free
signaling to other peripherals or performance analysis of USB operation.
Table 18-3. Event sources.
18.11 VBUS Detection
Atmel AVR XMEGA devices can use any general purpose I/O pin to implement a VBUS detection function, and do not
use a dedicated VBUS detect pin.
Interrupt source Description
Transfer complete (TRNIF) An IN or OUT transaction is completed
Setup complete (SETUPIF) A SETUP transaction is completed
Interrupt source Description
Start of frame (SOFIF) A SOF token has been received
Suspend (SUSPENDIF) The bus has been idle for 3ms
Resume (RESUMEIF) A non-idle state is detected when the bus is suspended.
The interrupt is asynchronous and can wake the device from all sleep modes
Reset (RSTIF) A reset condition has been detected on the bus
Isochronous CRC error (CRCIF) A CRC or bit-stuff error has been detected in an incoming packet to an
isochronous endpoint
Underflow (UNFIF) An endpoint is unable to return data to the host
Overflow (OVFIF) An endpoint is unable to accept data from the host
STALL (STALLIF) A STALL handshake has been returned to the host
Event source Description
SETUP SETUPIF
Start of Frame SOFIF
CRC error CRCIF
Underflow/overflow UNFIF and OVFIF
XMEGA B [MANUAL] 217
Atmel-8291C-AVR-XMEGA B -09/2014
18.12 On-chip Debug
When a break point is reached during on-chip debug (OCD) sessions, the CPU clock can be below 12MHz. If this
happens, the USB module will behave as follows:
USB OCD break mode disabled: The USB module immediately acknowledges any OCD break request. The USB module
will not be able to follow up on transactions received from the USB host, and its behaviour from the host point of view is
not predictable.
USB OCD break mode enabled: The USB module will immediately acknowledge any OCD break request only if there are
no ongoing USB transactions. If there is an ongoing USB transaction, the USB module will acknowledge any OCD break
request only when the ongoing USB transaction has been completed. The USB module will NACK any further
transactions received from the USB host, whether they are SETUP, IN (ISO, BULK), or OUT (ISO, BULK).
XMEGA B [MANUAL] 218
Atmel-8291C-AVR-XMEGA B -09/2014
18.13 Register Description – USB
18.13.1 CTRLA – Control register A
z Bit 7 – ENABLE: USB Enable
Setting this bit enables the USB interface. Clearing this bit disables the USB interface and immediately aborts any
ongoing transactions.
z Bit 6 – SPEED: Speed Select
This bit selects between low and full speed operation. By default, this bit is zero, and low speed operation is selected.
Setting this bit enables full speed operation.
z Bit 5 – FIFOEN: USB FIFO Enable
Setting this bit enables the USB transaction complete FIFO, and the FIFO stores the endpoint configuration table
address of each endpoint that generates a transaction complete interrupt. Clearing this bit disables the FIFO and frees
the allocated SRAM memory.
z Bit 4 – STFRNUM: Store Frame Number Enable
Setting this bit enables storing of the last SOF token frame number in the frame number (FRAMENUM) register. Clearing
this bit disables the function.
z Bit 3:0 – MAXEP[3:0]: Maximum Endpoint Address
These bits select the number of endpoint addresses used by the USB module. Incoming packets with a higher endpoint
number than this address will be discarded. Packets with endpoint addresses lower than or equal to this address will
cause the USB module to look up the addressed endpoint in the endpoint configuration table.
18.13.2 CTRLB – Control register B
z Bit 7:5 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 4 – PULLRST: Pull during Reset
Setting this bit enables the pull-up on the USB lines to also be held when the device enters reset. The bit will be cleared
on a power-on reset.
z Bit 3 – Reserved
This bit is unused and reserved for future use. For compatibility with future devices, always write this bit to zero when this
register is written.
Bit 7 6 5 4 3 2 1 0
+0x00 ENABLE SPEED FIFOEN STFRNUM MAXEP[3:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 00000000
Bit 7 6 5 4 3 2 1 0
+0x01 – – – PULLRST – RWAKEUP GNACK ATTACH
Read/Write R R R R/W R R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 219
Atmel-8291C-AVR-XMEGA B -09/2014
z Bit 2 – RWAKEUP: Remote Wake-up
Setting this bit sends an upstream resume on the USB lines if the bus is in the suspend state for at least 5 ms.
z Bit 1 – GNACK: Global NACK
When this bit is set, the USB module will NACK all incoming transactions. Expect for a SETUP packet, this prevents the
USB module from performing any on-chip SRAM access, giving all SRAM bandwidth to the CPU and/or DMA controller.
z Bit 0 – ATTACH: Attach
Setting this bit enables the internal D+ or D- pull-up (depending on the USB speed selection), and attaches the device to
the USB lines. Clearing this bit disconnects the device from the USB lines.
18.13.3 STATUS – Status register
z Bit 7:4 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 3 – URESUME: Upstream Resume
This flag is set when an upstream resume is sent.
z Bit 2 – RESUME: Resume
This flag is set when a downstream resume is received.
z Bit 1 – SUSPEND: Bus Suspended
This flag is set when the USB lines are in the suspended state (the bus has been idle for at least 3ms).
z Bit 0 – BUSRST: Bus Reset
This flag is set when a reset condition has been detected (the bus has been driven to SE0 for at least 2.5μs).
18.13.4 ADDR – Address register
z Bit 7 – Reserved
This bit is unused and reserved for future use. For compatibility with future devices, always write this bit to zero when this
register is written.
z Bit 6:0 – ADDR[6:0]: Device Address
These bits contain the USB address the device will respond to.
Bit 7 6 5 4 3 2 1 0
+0x02 – – – – URESUME RESUME SUSPEND BUSRST
Read/Write RRRRRRRR
Initial Value 00000000
Bit 7 6 5 4 3 2 1 0
+0x03 – ADDR[6:0]
Read/Write R R/W R/W R/W R/W R/W R/W R/W
Initial Value 00000000
XMEGA B [MANUAL] 220
Atmel-8291C-AVR-XMEGA B -09/2014
18.13.5 FIFOWP – FIFO Write Pointer register
z Bit 7:5 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 4:0 – FIFOWP[4:0]: FIFO Write Pointer
These bits contain the transaction complete FIFO write pointer. This register must be read only by the CPU or DMA
controller. Writing this register will flush the FIFO write and read pointers.
18.13.6 FIFORP – FIFO Read Pointer register
z Bit 7:5 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 4:0 – FIFORP[4:0]: FIFO Read Pointer
These bits contain the transaction complete FIFO read pointer. This register must only be read by the CPU or DMA
controller. Writing this register will flush the FIFO write and read pointer.
18.13.7 EPPTRL – Endpoint Configuration Table Pointer Low
The EPPTRL and EPPTRH registers represent the 16-bit value, EPPTR, that contains the address to the endpoint
configuration table. The pointer to the endpoint configuration table must be aligned to a 16-bit word; i.e., EPPTR[0] must
be zero. Only the number of bits required to address the available internal SRAM memory is implemented for each
device. Unused bits will always be read as zero.
z Bit 7:0 – EPPTR[7:0]: Endpoint Configuration Table Pointer low byte
This register contains the eight lsbs of the endpoint configuration table pointer (EPPTR).
Bit 7 6 5 4 3 2 1 0
+0x04 – – – FIFOWP[4:0]
Read/Write R R R R/W R/W R/W R/W R/W
Initial Value 00000000
Bit 7 6 5 4 3 2 1 0
+0x05 – – – FIFORP[4:0]
Read/Write R R R R/W R/W R/W R/W R/W
Initial Value 00000000
Bit 7 6 5 4 3 2 1 0
+0x06 EPPTR[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 221
Atmel-8291C-AVR-XMEGA B -09/2014
18.13.8 EPPTRH – Endpoint Configuration Table Pointer High
z Bit 7:0 – EPPTR[15:8]: Endpoint Configuration Table Pointer high byte
This register contains the eight msbs of the endpoint configuration table pointer (EPPTR).
18.13.9 INTCTRLA – Interrupt Control register A
z Bit 7 – SOFIE: Start Of Frame Interrupt Enable
Setting this bit enables the start of frame (SOF) interrupt for the conditions that set the start of frame interrupt flag
(SOFIF) in the INTFLAGSACLR/ INTFLAGSASET register. The INTLVL bits must be nonzero for the interrupts to be
generated.
z Bit 6 – BUSEVIE: Bus Event Interrupt Enable
Setting this bit will enable the interrupt for the following three bus events:
1. Suspend: An interrupt will be generated for the conditions that set the suspend interrupt flag (SUSPENDIF) in the
INTFLAGSACLR/SET register.
2. Resume: An interrupt will be generated for the conditions that set the resume interrupt flag (RESUMEIF) in the
INTFLAGSACLR/SET register.
3. Reset: An interrupt will be generated for the conditions that set the reset interrupt flag (RESETIF) in the INTFLAGSACLR/SET
register.
The INTLVL bits must be nonzero for the interrupts to be generated.
z Bit 5 – BUSERRIE: Bus Error Interrupt Enable
Setting this bit will enable the interrupt for the following three bus error events:
1. Isochronous CRC Error: An interrupt will be generated for the conditions that set the CRC interrupt flag (CRCIF) in
the INTFLAGSACLR/SET register during isochronous transfers.
2. Underflow: An interrupt will be generated for the conditions that set the underflow interrupt flag (UNFIF) in the
INTFLAGSACLR/SET register.
3. Overflow: An interrupt will be generated for the conditions that set the overflow interrupt flag (OVFIF) in the
INTFLAGSACLR/SET register.
The INTLVL bits must be nonzero for the interrupts to be generated.
z Bit 4 – STALLIE: STALL Interrupt Enable
Setting this bit enables the STALL interrupt for the conditions that set the stall interrupt flag (STALLIF) in the
INTFLAGSACLR/SET register. The INTLVL bits must be nonzero for the interrupts to be generated.
Bit 7 6 5 4 3 2 1 0
+0x07 EPPTR[15:8]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
+0x06 SOFIE BUSEVIE BUSERRIE STALLIE – – INTLVL[1:0]
Read/Write R/W R/W R/W R/W R R R/W R/W
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 222
Atmel-8291C-AVR-XMEGA B -09/2014
z Bit 3:2 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 1:0 – INTLVL[1:0]: Interrupt Level
These bits enable the USB interrupts and select the interrupt level, as described in “Interrupts and Programmable
Multilevel Interrupt Controller” on page 115. In addition, each USB interrupt source must be separately enabled.
18.13.10INTCTRLB – Interrupt Control register B
z Bit 7:2 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 1 – TRNIE: Transaction Complete Interrupt Enable
Setting this bit enables the transaction complete interrupt for IN and OUT transactions. The INTLVL bits must be nonzero
for interrupts to be generated.
z Bit 0 – SETUPIE: SETUP Transaction Complete Interrupt Enable
Setting this bit enables the SETUP Transaction Complete Interrupt for SETUP transactions. The INTLVL bits must be
non-zero for the interrupts to be generated.
18.13.11INTFLAGSACLR/ INTFLAGSASET – Clear/ Set Interrupt Flag register A
This register is mapped into two I/O memory locations, one for clearing (INTFLAGSACLR) and one for setting
(INTFLAGSASET) the flags. The individual flags can be set by writing a one to their bit locations in INFLAGSASET, and
cleared by writing a one to their bit locations in INT-FLAGSACLR. Both memory locations will provide the same result
when read, and writing zero to any bit location has no effect.
z Bit 7 – SOFIF: Start Of Frame Interrupt Flag
This flag is set when a start of frame packet has been received.
z Bit 6 – SUSPENDIF: Suspend Interrupt Flag
This flag is set when the bus has been idle for 3ms.
z Bit 5 – RESUMEIF: Resume Interrupt Flag
This flag is set when a non-idle state has been detected on the bus while the USB module is in the suspend state. This
interrupt is asynchronous, and is able to wake the CPU from sleep modes where the system clock is stopped, such as
power-down and power-save sleep modes.
z Bit 4 – RSTIF: Reset Interrupt Flag
This flag is set when a reset condition has been detected on the bus.
Bit 7 6 5 4 3 2 1 0
+0x07 – – – – – – TRNIE SETUPIE
Read/Write R R R R R R R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
+0x0A/ +0x0B SOFIF SUSPENDIF RESUMEIF RESETIF CRCIF UNFIF OVFIF STALLIF
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 223
Atmel-8291C-AVR-XMEGA B -09/2014
z Bit 3 – CRCIF: Isochronous CRC Error Interrupt Flag
This flag is set when a CRC error has been detected in an incoming data packet to an isochronous endpoint.
z Bit 2 – UNFIF: Underflow Interrupt Flag
This flag is set when the addressed endpoint in an IN transaction does not have data to send to the host.
z Bit 1 – OVFIF: Overflow Interrupt Flag
This flag is set when the addressed endpoint in an OUT transaction is not ready to accept data from the host.
z Bit 0 – STALLIF: STALL Interrupt Flag
This flag is set when the USB module has responded with a STALL handshake to either an IN or an OUT transaction.
18.13.12INTFLAGSBCLR/INTFLAGSBSET – Clear/Set Interrupt Flag register B
This register is mapped into two I/O memory locations, one for clearing (INTFLAGSBCLR) and one for setting
(INTFLAGSBSET) the flags. The individual flags can be set by writing a one to their bit locations in INFLAGSBSET, and
cleared by writing a one to their bit locations in INTFLAGSBCLR. Both memory locations will provide the same result
when read, and writing zero to any bit location has no effect.
z Bit 7:2 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 1 – TRNIF: Transaction Complete Interrupt Flag
This flag is when there is a pending packet interrupt in the FIFO.
z Bit 0 – SETUPIF: SETUP Transaction Complete Interrupt Flag
This flag is set when a SETUP transaction has completed successfully.
18.13.13CALL – Calibration register Low
CALL and CALH hold the 16-bit value, CAL. The USB PADs (D- and D+) are calibrated during production to enable
operation without requiring external components on the USB lines. The calibration value is stored in the signature row of
the device, and must be read from there and written to the CAL registers from software.
z Bit 7:0 – CAL[7:0]: PAD Calibration low byte
This byte holds the eight lsbs of CAL.
Bit 7 6 5 4 3 2 1 0
+0x0C/ +0x0D – – – – – –- TRNIF SETUPIF
Read/Write R R R R R R R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
++0x3A CAL[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 224
Atmel-8291C-AVR-XMEGA B -09/2014
18.13.14CALH – Calibration register High
z Bit 7:0 – CAL[15:8]: PAD Calibration high byte
This byte holds the eight msbs of CAL.
Bit 7 6 5 4 3 2 1 0
+0x3B CAL[15:8]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 225
Atmel-8291C-AVR-XMEGA B -09/2014
18.14 Register Description – USB Endpoint
Each of the 16 endpoint addresses have one input and one output endpoint. Each endpoint has eight bytes of
configuration/status data located in internal SRAM.
The address to the first configuration byte is (EPPTR[15:0] + 16 × endpoint address) for output endpoints and
(EPPTR[15:0] + 16 × endpoint address + 8) for input endpoints.
Some bit locations have different functions, depending on endpoint configuration type or direction, and this is reflected by
using two different names for the bit locations.
18.14.1 STATUS – Status register
Note: 1. For isochronous endpoints.
z Bit 7 – STALL: STALL Flag
This flag is set when an IN or OUT transaction has been responded to with a STALL handshake. This flag is cleared by
writing a one to its bit location.
z Bit 7 – CRC: CRC Error Flag
This flag is set for isochronous output endpoints when a CRC error has been detected in an incoming data packet. This
flag is cleared by writing a one to its bit location.
z Bit 6 – UNF/OVF: Underflow/Overflow Flag
UNF: For input endpoints, the UNF flag is set when an input endpoint is not ready to send data to the host in response of
an IN token.
OVF: For output endpoints, the OVF flag is set when an output endpoint is not ready to accept data from the host
following an OUT token.
z Bit 5 – TRNCOMPL0: Transaction Complete Flag
This flag is set when an IN or OUT transaction has completed successfully. This flag is cleared by writing a one to its bit
location.
z Bit 4 – SETUP: SETUP Transaction Complete Flag
This flag is set when a SETUP, IN, or OUT transaction has completed successfully. This flag is cleared by writing a one
to its bit location.
z Bit 4 – TRNCOMPL1: Transaction Complete Flag
This flag is set when a SETUP, IN, or OUT transaction has completed successfully. This flag is cleared by writing a one
to its bit location.
z Bit 3 – BANK: Bank Select Flag
When ping-pong mode is enabled, this bit indicates which bank will be used for the next transaction. BANK is toggled
each time a transaction has completed successfully. This bit is not sed when ping-pong is disabled. This flag is cleared
by writing a one to its bit location.
z Bit 2 – BUSNACK1: Data Buffer 1 Not Acknowledge Flag
When this flag is set, the USB module will discard incoming data to data buffer 1 in an OUT transaction, and will not
return any data from data buffer 1 in an IN transaction. For control, bulk, and interrupt endpoints, a NAK handshake is
returned. This flag is cleared by writing a one to its bit location.
Bit 7 6 5 4 3 2 1 0
+0x00
STALL
UNF/ OVF TRNCOMPL0
SETUP
BANK BUSNACK1 BUSNACK0 TOGGLE
CRC(1) TRNCOMPL1
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 226
Atmel-8291C-AVR-XMEGA B -09/2014
z Bit 1 – BUSNACK0: Data Buffer 0 Not Acknowledge Flag
When this flag is set, the USB module will discard incoming data to data buffer 0 in an OUT transaction, and will not
return any data from data buffer 0 in an IN transaction. For control, bulk, and interrupt endpoints, a NAK handshake is
returned. This flag is cleared by writing a one to its bit location.
z Bit 0 – TOGGLE: Data Toggle Flag
This indicates if a DATA0 or DATA1 PID is expected in the next data packet for an output endpoint, and if a DATA0 or
DATA1 PID will be sent in the next transaction for an input endpoint. This bit has no effect for isochronous endpoints,
where both DATA0 and DATA1 PIDs are accepted for output endpoint, and only DATA0 PIDs are sent for input
endpoints.
18.14.2 CTRL – Control
Note: 1. For isochronous endpoints.
z Bit 7:6 – TYPE[1:0]: Endpoint Type
These bits are used to enable and select the endpoint type. If the endpoint is disabled, the remaining seven endpoint
configuration bytes are never read or written by the USB module, and their SRAM locations are free to use for other
application data.
Table 18-4. Endpoint type.
z Bit 5 – MULTIPKT: Multipacket Transfer Enable
Setting this bit enables multipacket transfers. Multipacket transfer enables a data payload exceeding the maximum
packet size of an endpoint to be transferred as multiple packets without interrupts or software intervention. See
“Multipacket Transfers” on page 213 for details on multipacket transfers.
z Bit 4 – PINGPONG: Ping-pong Enable
Setting this bit enables ping-pong operation. Ping-pong operation enables both endpoints (IN and OUT) with same
address to be used in the same direction to allow double buffering and maximize throughput. The endpoint in the
opposite direction must be disabled when ping-pong operation is enabled. Ping-pong operation is not possible for control
endpoints. See “Ping-pong Operation” on page 212 for details.
z Bit 3 – INTDSBL: Interrupt Disable
Setting this bit disables all enabled interrupts from the endpoint. Hence, only the interrupt flags in the STATUS register
are updated when interrupt conditions occur. The FIFO does not store this endpoint configuration table address upon
transaction complete for the endpoint when interrupts are disabled for an endpoint. Clearing this bit enables all previously
enables interrupts again.
Bit 7 6 5 4 3 2 1 0
+0x01 TYPE[1:0] MULTIPKT PINGPONG INTDSBL STALL SIZE[1:0]
SIZE[2:0](1)
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
TYPE[1:0] Group Configuration Description
00 DISABLE Endpoint enabled
01 CONTROL Control
10 BULK Bulk/interrupt
11 ISOCHRONOUS Isochronous
XMEGA B [MANUAL] 227
Atmel-8291C-AVR-XMEGA B -09/2014
z Bit 2 – STALL: Endpoint STALL
This bit controls the STALL behavior if the endpoint.
z Bit 1:0 – BUFSIZE[1:0]: Data Size
These bits configure the maximum data payload size for the endpoint. Incoming data bytes exceeding the maximum data
payload size are discarded.
z Bit 2:0 – BUFSIZE[2:0]: Data Size
These bits configure the maximum data payload size for the endpoint when configured for isochronous operation.
Table 18-5. BUFSIZE configuration
Note: 1. Setting only available for isochronous endpoints.
18.14.3 CNTL – Counter Low register
The CNTL and CNTH registers represent the 10-bit value, CNT, that contains the number of bytes received in the last
OUT or SETUP transaction for an OUT endpoint, or the number of bytes to be sent in the next IN transaction for an IN
endpoint.
z Bit 7:0 – CNT[7:0]: Endpoint Byte Counter
This byte contains the eight lsbs of the USB endpoint counter (CNT).
BUFSIZE[2:0] Group Configuration Description
000 8 8-byte buffer size
001 16 16-byte buffer size
010 32 32-byte buffer size
011 64 64-byte buffer size
100(1) 128 128-byte buffer size
101(1) 256 256-byte buffer size
110(1) 512 512-byte buffer size
111(1) 1023 1023-byte buffer size
Bit 7 6 5 4 3 2 1 0
+0x02 CNT[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value XXXXXXXX
XMEGA B [MANUAL] 228
Atmel-8291C-AVR-XMEGA B -09/2014
18.14.4 CNTH – Counter High register
z Bit 6 – AZLP: Automatic Zero Length Packet
When this bit is set, the USB module will manage the ZLP handshake by hardware. This applies to IN endpoints only.
When this bit is zero, the ZLP handshake must be managed by firmware.
z Bit 6:2 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 1:0 – CNT[9:8]: Endpoint Byte Counter
These bits contain the two msbs of the USB endpoint counter (CNT).
18.14.5 DATAPTRL – Data Pointer Low register
The DATAPTRL and DATAPTRH registers represent the 16-bit value, DATAPTR, that contains the SRAM address to the
endpoint data buffer.
z Bit 7:0 – DATAPTR[7:0]: Endpoint Data Pointer Low
This byte contains the eight lsbs of the endpoint data pointer (DATAPTR).
18.14.6 DATAPTRH – Data Pointer High register
z Bit 15:0 - DPTR[15:8]: Endpoint Data Pointer High
This byte contains the eight msbs of the endpoint data pointer (DATAPTR).
Bit 7 6 5 4 3 2 1 0
+0x03 AZLP – – – – – CNT[9:8]
Read/Write R/W R R R R R R/W R/W
Initial Value X X X X X X X X
Bit 7 6 5 4 3 2 1 0
+0x04 DATAPTR[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value X X X X X X X X
Bit 7 6 5 4 3 2 1 0
+0x05 DATAPTR[15:8]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value X X X X X X X X
XMEGA B [MANUAL] 229
Atmel-8291C-AVR-XMEGA B -09/2014
18.14.7 AUXDATAL – Auxiliary Data Low register
The AUXDATAL and AUXDATAH registers represent the 16-bit value, AUXDATA, that is used for multipacket transfers.
For IN endpoints, AUXDATA holds the total number of bytes sent. AUXDATA should be written to zero when setting up a
new transfer. For OUT endpoints, AUXDATA holds the total data size for the complete transfer. This value must be a
multiple of the maximum packet size, except for ISO 1023-byte endpoints.
See “Multipacket Transfers” on page 213 for more details on setting up and using multipacket transfers.
z Bit 7:0 – AUXDATA[7:0]: Auxiliary Data Low
This byte contains the eight lsbs of the auxiliary data (AUXDATA). When multipacket transfer is not used, this SRAM
location is free to use for other application data.
18.14.8 AUXDATAH – Auxiliary Data High register
z Bit 7:0 – AUXDATA[15:8]: Auxiliary Data High
This byte contains the eight msbs of the auxiliary data (AUXDATA). When multipacket transfer is not used, this SRAM
location is free to use for other application data.
Bit 7 6 5 4 3 2 1 0
+0x06 AUXDATA[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value X X X X X X X X
Bit 7 6 5 4 3 2 1 0
+0x07 AUXDATA[15:8]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value X X X X X X X X
XMEGA B [MANUAL] 230
Atmel-8291C-AVR-XMEGA B -09/2014
18.15 Register Description - Frame
18.15.1 FRAMENUML – Frame Number Low register
The FRAMENUML and FRAMENUMH registers represent the 11-bit value, FRAMENUM, that holds the frame number
from the most recently received start of frame packet.
z Bit 7:0 – FRAMENUM[7:0]: Frame Number
This byte contains the eight lsbs of the frame number (FRAMENUM).
18.15.2 FRAMENUMH – Frame Number High register
z Bit 7 – FRAMEERR: Frame Error
This flag is set if a CRC or bit-stuffing error was detected in the most recently received start of frame packet.
z Bit 6:3 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 2:0 – FRAMENUM[10:8]: Frame Number
This byte contains the three msbs of the frame number (FRAMENUM).
Bit 7 6 5 4 3 2 1 0
+0x00 FRAMENUM[7:0]
Read/Write R R R R R R R R
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
+0x01 FRAMEERR – – – – FRAMENUM[10:8]
Read/Write R R R R R R R R
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 231
Atmel-8291C-AVR-XMEGA B -09/2014
18.16 Register Summary – USB Module
18.17 Register Summary – USB Endpoint
The address to the first configuration byte is (EPPTR[15:0] + 16 × endpoint address) for OUT endpoints and
(EPPTR[15:0] + 16 × endpoint address + 8) for IN endpoints.
18.18 Register Summary – Frame
The address to the frame configuration byte is (MAXEP + 1) << 4. For instance with MAXEP = 3, the first address would
be located at offset address 0x40.
18.19 USB Interrupt Vector Summary
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
+0x00 CTRLA ENABLE SPEED FIFOEN STFRNUM MAXEP[3:0] 218
+0x01 CTRLB – – – PULLRST – RWAKEUP GNACK ATTACH 218
+0x02 STATUS – – – – UPRESUM RESUME SUSPEND BUSRST 219
+0x03 ADDR – ADDR[6:0] 219
+0x04 FIFOWP – – – FIFOWP[4:0] 220
+0x05 FIFORP – – – FIFORP[4:0] 220
+0x06 EPPTRL EPPTR[7:0] 220
+0x07 EPPTRH EPPTR[15:8] 221
+0x08 INTCTRLA SOFIE BUSEVIE BUSERRIE STALLIE – – INTLVL[1:0] 221
+0x09 INTCTRLB – – – – – – TRNIE SETUPIE 222
+0x0A INFLAGSACL SOFIF SUSPENDI RESUMEIF RSTIF CRCIF UNFIF OVFIF STALLIF 222
+0x0B INFLAGSASE SOFIF SUSPENDI RESUMEIF RSTIF CRCIF UNFIF OVFIF STALLIF 222
+0x0C INFLAGSBCL – – – – – – TRNIF SETUPIF 223
+0x0D INFLAGSBSE – – – – – – TRNIF SETUPIF 223
+0x0E Reserved – – – – – – – –
+0x0F Reserved – – – – – – – –
+0x10-0X39 Reserved – – – – – – – –
+0x3A CALL CAL[7:0] 223
+0x3B CALH CAL[15:8] 224
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
+0x00 STATUS STALL OVF/UNF TRNCOMP
L0
SETUP BANK BUSNACK1 BUSNACK0 TOGGLE 225
CRC TRNCOMP Isochronous
+0x01 CTRL TYPE[1:0] MULTIPKT PINGPONG INTDSB
L
STALL BUFSIZE[1:0] 226
BUFSIZE[2:0] Isochronous
+0x02 CNTL CNT[7:0] 227
+0x03 CNTH AZLP – – – – – CNT[9:8] 228
+0x04 DATAPTR DATAPTR[7:0] 228
+0x05 DATAPTR DATAPTR[15:8] 228
+0x06 AUXDATA AUXDATA[7:0] 229
+0x07 AUXDATA AUXDATA[15:8] 229
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
+0x00 FRAMENUM FRAMENUM[7:0] 230
+0x01 FRAMENUM FRAMEER – – – – FRAMENUM[10:8] 230
Offset Source Interrupt Description
0x00 BUSEVENT_vect SOF, suspend, resume, bus reset, CRC, underflow, overflow, and stall error interrupts
0x02 TRNCOMPL_vect Transaction complete interrupt
XMEGA B [MANUAL] 232
Atmel-8291C-AVR-XMEGA B -09/2014
19. TWI – Two-Wire Interface
19.1 Features
z Bidirectional, two-wire communication interface
z Phillips I2
C compatible
z System Management Bus (SMBus) compatible
z Bus master and slave operation supported
z Slave operation
z Single bus master operation
z Bus master in multi-master bus environment
z Multi-master arbitration
z Flexible slave address match functions
z 7-bit and general call address recognition in hardware
z 10-bit addressing supported
z Address mask register for dual address match or address range masking
z Optional software address recognition for unlimited number of addresses
z Slave can operate in all sleep modes, including power-down
z Slave address match can wake device from all sleep modes
z 100kHz and 400kHz bus frequency support
z Slew-rate limited output drivers
z Input filter for bus noise and spike suppression
z Support arbitration between start/repeated start and data bit (SMBus)
z Slave arbitration allows support for address resolve protocol (ARP) (SMBus)
19.2 Overview
The two-wire interface (TWI) is a bidirectional, two-wire communication interface. It is I2
C and System Management Bus
(SMBus) compatible. The only external hardware needed to implement the bus is one pull-up resistor on each bus line.
A device connected to the bus must act as a master or a slave. The master initiates a data transaction by addressing a
slave on the bus and telling whether it wants to transmit or receive data. One bus can have many slaves and one or
several masters that can take control of the bus. An arbitration process handles priority if more than one master tries to
transmit data at the same time. Mechanisms for resolving bus contention are inherent in the protocol.
The TWI module supports master and slave functionality. The master and slave functionality are separated from each
other, and can be enabled and configured separately. The master module supports multi-master bus operation and
arbitration. It contains the baud rate generator. Both 100kHz and 400kHz bus frequency is supported. Quick command
and smart mode can be enabled to auto-trigger operations and reduce software complexity.
The slave module implements 7-bit address match and general address call recognition in hardware. 10-bit addressing is
also supported. A dedicated address mask register can act as a second address match register or as a register for
address range masking. The slave continues to operate in all sleep modes, including power-down mode. This enables
the slave to wake up the device from all sleep modes on TWI address match. It is possible to disable the address
matching to let this be handled in software instead.
The TWI module will detect START and STOP conditions, bus collisions, and bus errors. Arbitration lost, errors, collision,
and clock hold on the bus are also detected and indicated in separate status flags available in both master and slave
modes.
It is possible to disable the TWI drivers in the device, and enable a four-wire digital interface for connecting to an external
TWI bus driver. This can be used for applications where the device operates from a different VCC voltage than used by
the TWI bus.
XMEGA B [MANUAL] 233
Atmel-8291C-AVR-XMEGA B -09/2014
19.3 General TWI Bus Concepts
The TWI provides a simple, bidirectional, two-wire communication bus consisting of a serial clock line (SCL) and a serial
data line (SDA). The two lines are open-collector lines (wired-AND), and pull-up resistors (Rp) are the only external
components needed to drive the bus. The pull-up resistors provide a high level on the lines when none of the connected
devices are driving the bus
The TWI bus is a simple and efficient method of interconnecting multiple devices on a serial bus. A device connected to
the bus can be a master or slave, where the master controls the bus and all communication.
Figure 19-1 on page 233 illustrates the TWI bus topology.
Figure 19-1. TWI bus topology.
A unique address is assigned to all slave devices connected to the bus, and the master will use this to address a slave
and initiate a data transaction.
Several masters can be connected to the same bus, called a multi-master environment. An arbitration mechanism is
provided for resolving bus ownership among masters, since only one master device may own the bus at any given time.
A device can contain both master and slave logic, and can emulate multiple slave devices by responding to more than
one address.
A master indicates the start of a transaction by issuing a START condition (S) on the bus. An address packet with a slave
address (ADDRESS) and an indication whether the master wishes to read or write data (R/W) are then sent. After all
data packets (DATA) are transferred, the master issues a STOP condition (P) on the bus to end the transaction. The
receiver must acknowledge (A) or not-acknowledge (A) each byte received.
Figure 19-2 on page 234 shows a TWI transaction.
TWI
DEVICE #1
RP RP
RS RS
SDA
SCL
VCC
TWI
DEVICE #2
RS RS
TWI
DEVICE #N
RS RS
Note: RS is optional
XMEGA B [MANUAL] 234
Atmel-8291C-AVR-XMEGA B -09/2014
Figure 19-2. Basic TWI transaction diagram topology for a 7-bit address bus.
The master provides the clock signal for the transaction, but a device connected to the bus is allowed to stretch the lowlevel
period of the clock to decrease the clock speed.
19.3.1 Electrical Characteristics
The TWI module in XMEGA devices follows the electrical specifications and timing of I2
C bus and SMBus. These
specifications are not 100% compliant, and so to ensure correct behavior, the inactive bus timeout period should be set
in TWI master mode. Refer to “TWI Master Operation” on page 239 for more details.
19.3.2 START and STOP Conditions
Two unique bus conditions are used for marking the beginning (START) and end (STOP) of a transaction. The master
issues a START condition (S) by indicating a high-to-low transition on the SDA line while the SCL line is kept high. The
master completes the transaction by issuing a STOP condition (P), indicated by a low-to-high transition on the SDA line
while SCL line is kept high.
Figure 19-3. START and STOP conditions.
Multiple START conditions can be issued during a single transaction. A START condition that is not directly following a
STOP condition is called a repeated START condition (Sr).
19.3.3 Bit Transfer
As illustrated by Figure 19-4, a bit transferred on the SDA line must be stable for the entire high period of the SCL line.
Consequently the SDA value can only be changed during the low period of the clock. This is ensured in hardware by the
TWI module.
S ADDRESS P
6 ... 0
R/W ACK ACK
7 ... 0
DATA ACK/NACK
7 ... 0
DATA
SDA
SCL
S ADDRESS R/W A DATA A DATA A/A P
Address Packet Data Packet #0
Transaction
Data Packet #1
Direction
The slave provides data on the bus
The master provides data on the bus
The master or slave can provide data on the bus
SDA
SCL
START
Condition
STOP
Condition
S P
XMEGA B [MANUAL] 235
Atmel-8291C-AVR-XMEGA B -09/2014
Figure 19-4. Data validity.
Combining bit transfers results in the formation of address and data packets. These packets consist of eight data bits
(one byte) with the most-significant bit transferred first, plus a single-bit not-acknowledge (NACK) or acknowledge (ACK)
response. The addressed device signals ACK by pulling the SCL line low during the ninth clock cycle, and signals NACK
by leaving the line SCL high.
19.3.4 Address Packet
After the START condition, a 7-bit address followed by a read/write (R/W) bit is sent. This is always transmitted by the
master. A slave recognizing its address will ACK the address by pulling the data line low for the next SCL cycle, while all
other slaves should keep the TWI lines released and wait for the next START and address. The address, R/W bit, and
acknowledge bit combined is the address packet. Only one address packet for each START condition is allowed, also
when 10-bit addressing is used.
The R/W bit specifies the direction of the transaction. If the R/W bit is low, it indicates a master write transaction, and the
master will transmit its data after the slave has acknowledged its address. If the R/W bit is high, it indicates a master read
transaction, and the slave will transmit its data after acknowledging its address.
19.3.5 Data Packet
An address packet is followed by one or more data packets. All data packets are nine bits long, consisting of one data
byte and an acknowledge bit. The direction bit in the previous address packet determines the direction in which the data
are transferred.
19.3.6 Transaction
A transaction is the complete transfer from a START to a STOP condition, including any repeated START conditions in
between. The TWI standard defines three fundamental transaction modes: Master write, master read, and a combined
transaction.
Figure 19-5 on page 235 illustrates the master write transaction. The master initiates the transaction by issuing a START
condition (S) followed by an address packet with the direction bit set to zero (ADDRESS+W).
Figure 19-5. Master write transaction.
Assuming the slave acknowledges the address, the master can start transmitting data (DATA) and the slave will ACK or
NACK (A/A) each byte. If no data packets are to be transmitted, the master terminates the transaction by issuing a STOP
condition (P) directly after the address packet. There are no limitations to the number of data packets that can be
SDA
SCL
DATA
Valid
Change
Allowed
S ADDRESS W A DATA A DATA A/A P
Address Packet Data Packet
Transaction
N data packets
XMEGA B [MANUAL] 236
Atmel-8291C-AVR-XMEGA B -09/2014
transferred. If the slave signals a NACK to the data, the master must assume that the slave cannot receive any more
data and terminate the transaction.
Figure 19-6 on page 236 illustrates the master read transaction. The master initiates the transaction by issuing a START
condition followed by an address packet with the direction bit set to one (ADDRESS+R). The addressed slave must
acknowledge the address for the master to be allowed to continue the transaction.
Figure 19-6. Master read transaction.
Assuming the slave acknowledges the address, the master can start receiving data from the slave. There are no
limitations to the number of data packets that can be transferred. The slave transmits the data while the master signals
ACK or NACK after each data byte. The master terminates the transfer with a NACK before issuing a STOP condition.
Figure 19-7 illustrates a combined transaction. A combined transaction consists of several read and write transactions
separated by repeated START conditions (Sr).
Figure 19-7. Combined Transaction.
19.3.7 Clock and Clock Stretching
All devices connected to the bus are allowed to stretch the low period of the clock to slow down the overall clock
frequency or to insert wait states while processing data. A device that needs to stretch the clock can do this by
holding/forcing the SCL line low after it detects a low level on the line.
Three types of clock stretching can be defined, as shown in Figure 19-8.
Figure 19-8. Clock stretching(1).
Note: 1. Clock stretching is not supported by all I2
C slaves and masters.
If a slave device is in sleep mode and a START condition is detected, the clock stretching normally works during the
wake-up period. For AVR XMEGA devices, the clock stretching will be either directly before or after the ACK/NACK bit,
as AVR XMEGA devices do not need to wake up for transactions that are not addressed to it.
A slave device can slow down the bus frequency by stretching the clock periodically on a bit level. This allows the slave
to run at a lower system clock frequency. However, the overall performance of the bus will be reduced accordingly. Both
S ADDRESS R A DATA A DATA A P
Transaction
Address Packet Data Packet
N data packets
S ADDRESS R/W A DATA A/A Sr ADDRESS R/W DATA A/A P
Transaction
Address Packet #1 N Data Packets Address Packet #2 M Data Packets
Direction Direction
A
SDA
SCL
S
bit 7 bit 6 bit 0 ACK/NACK
Periodic clock
stretching
Random clock
stretching
Wakeup clock
stretching
XMEGA B [MANUAL] 237
Atmel-8291C-AVR-XMEGA B -09/2014
the master and slave device can randomly stretch the clock on a byte level basis before and after the ACK/NACK bit.
This provides time to process incoming or prepare outgoing data, or perform other time-critical tasks.
In the case where the slave is stretching the clock, the master will be forced into a wait state until the slave is ready, and
vice versa.
19.3.8 Arbitration
A master can start a bus transaction only if it has detected that the bus is idle. As the TWI bus is a multi-master bus, it is
possible that two devices may initiate a transaction at the same time. This results in multiple masters owning the bus
simultaneously. This is solved using an arbitration scheme where the master loses control of the bus if it is not able to
transmit a high level on the SDA line. The masters who lose arbitration must then wait until the bus becomes idle (i.e.,
wait for a STOP condition) before attempting to reacquire bus ownership. Slave devices are not involved in the arbitration
procedure.
Figure 19-9. TWI arbitration.
Figure 19-9 shows an example where two TWI masters are contending for bus ownership. Both devices are able to issue
a START condition, but DEVICE1 loses arbitration when attempting to transmit a high level (bit 5) while DEVICE2 is
transmitting a low level.
Arbitration between a repeated START condition and a data bit, a STOP condition and a data bit, or a repeated START
condition and a STOP condition are not allowed and will require special handling by software.
19.3.9 Synchronization
A clock synchronization algorithm is necessary for solving situations where more than one master is trying to control the
SCL line at the same time. The algorithm is based on the same principles used for the clock stretching previously
described. Figure 19-10 shows an example where two masters are competing for control over the bus clock. The SCL
line is the wired-AND result of the two masters clock outputs.
DEVICE1_SDA
SDA
(wired-AND)
DEVICE2_SDA
SCL
S
bit 7 bit 6 bit 5 bit 4
DEVICE1 Loses arbitration
XMEGA B [MANUAL] 238
Atmel-8291C-AVR-XMEGA B -09/2014
Figure 19-10.Clock synchronization.
A high-to-low transition on the SCL line will force the line low for all masters on the bus, and they will start timing their low
clock period. The timing length of the low clock period can vary among the masters. When a master (DEVICE1 in this
case) has completed its low period, it releases the SCL line. However, the SCL line will not go high until all masters have
released it. Consequently, the SCL line will be held low by the device with the longest low period (DEVICE2). Devices
with shorter low periods must insert a wait state until the clock is released. All masters start their high period when the
SCL line is released by all devices and has gone high. The device which first completes its high period (DEVICE1) forces
the clock line low, and the procedure is then repeated. The result is that the device with the shortest clock period
determines the high period, while the low period of the clock is determined by the device with the longest clock period.
19.4 TWI Bus State Logic
The bus state logic continuously monitors the activity on the TWI bus lines when the master is enabled. It continues to
operate in all sleep modes, including power-down.
The bus state logic includes START and STOP condition detectors, collision detection, inactive bus timeout detection,
and a bit counter. These are used to determine the bus state. Software can get the current bus state by reading the bus
state bits in the master status register. The bus state can be unknown, idle, busy, or owner, and is determined according
to the state diagram shown in Figure 19-11. The values of the bus state bits according to state are shown in binary in the
figure.
DEVICE1_SCL
SCL
(wired-AND)
Wait
State
DEVICE2_SCL
High Period
Count
Low Period
Count
XMEGA B [MANUAL] 239
Atmel-8291C-AVR-XMEGA B -09/2014
Figure 19-11.Bus state, state diagram.
After a system reset and/or TWI master enable, the bus state is unknown. The bus state machine can be forced to enter
idle by writing to the bus state bits accordingly. If no state is set by application software, the bus state will become idle
when the first STOP condition is detected. If the master inactive bus timeout is enabled, the bus state will change to idle
on the occurrence of a timeout. After a known bus state is established, only a system reset or disabling of the TWI master
will set the state to unknown.
When the bus is idle, it is ready for a new transaction. If a START condition generated externally is detected, the bus
becomes busy until a STOP condition is detected. The STOP condition will change the bus state to idle. If the master
inactive bus timeout is enabled, the bus state will change from busy to idle on the occurrence of a timeout.
If a START condition is generated internally while in idle state, the owner state is entered. If the complete transaction was
performed without interference, i.e., no collisions are detected, the master will issue a STOP condition and the bus state
will change back to idle. If a collision is detected, the arbitration is assumed lost and the bus state becomes busy until a
STOP condition is detected. A repeated START condition will only change the bus state if arbitration is lost during the
issuing of the repeated START. Arbitration during repeated START can be lost only if the arbitration has been ongoing
since the first START condition. This happens if two masters send the exact same ADDRESS+DATA before one of the
masters issues a repeated START (Sr).
19.5 TWI Master Operation
The TWI master is byte-oriented, with an optional interrupt after each byte. There are separate interrupts for master write
and master read. Interrupt flags can also be used for polled operation. There are dedicated status flags for indicating
ACK/NACK received, bus error, arbitration lost, clock hold, and bus state.
When an interrupt flag is set, the SCL line is forced low. This will give the master time to respond or handle any data, and
will in most cases require software interaction. Figure 19-12 shows the TWI master operation. The diamond shaped
symbols (SW) indicate where software interaction is required. Clearing the interrupt flags releases the SCL line.
P + Timeout
Write ADDRESS
IDLE
(0b01)
S
BUSY
(0b11)
UNKNOWN
(0b00)
OWNER
(0b10)
Arbitration
Lost
Command P
Write
ADDRESS(Sr)
Sr
(S)
RESET
P + Timeout
XMEGA B [MANUAL] 240
Atmel-8291C-AVR-XMEGA B -09/2014
Figure 19-12.TWI master operation.
The number of interrupts generated is kept to a minimum by automatic handling of most conditions. Quick command and
smart mode can be enabled to auto-trigger operations and reduce software complexity.
19.5.1 Transmitting Address Packets
After issuing a START condition, the master starts performing a bus transaction when the master address register is
written with the 7-bit slave address and direction bit. If the bus is busy, the TWI master will wait until the bus becomes idle
before issuing the START condition.
Depending on arbitration and the R/W direction bit, one of four distinct cases (M1 to M4) arises following the address
packet. The different cases must be handled in software.
19.5.1.1 Case M1: Arbitration lost or bus error during address packet
If arbitration is lost during the sending of the address packet, the master write interrupt flag and arbitration lost flag are
both set. Serial data output to the SDA line is disabled, and the SCL line is released. The master is no longer allowed to
perform any operation on the bus until the bus state has changed back to idle.
A bus error will behave in the same way as an arbitration lost condition, but the error flag is set in addition to the write
interrupt and arbitration lost flags.
19.5.1.2 Case M2: Address packet transmit complete - Address not acknowledged by slave
If no slave device responds to the address, the master write interrupt flag and the master received acknowledge flag are
set. The clock hold is active at this point, preventing further activity on the bus.
19.5.1.3 Case M3: Address packet transmit complete - Direction bit cleared
If the master receives an ACK from the slave, the master write interrupt flag is set and the master received acknowledge
flag is cleared. The clock hold is active at this point, preventing further activity on the bus.
BUSY P IDLE S BUSY
Sr
P
M3
M3
M2
M2
M1
M1
R DATA
ADDRESS
W
DATA A/A
Wait for
IDLE
APPLICATION
SW
SW
Sr
P
M3
M2
SW A BUSY M4
A/A
A/A
A/A
M4
A
IDLE
IDLE
MASTER READ INTERRUPT + HOLD
MASTER WRITE INTERRUPT + HOLD
SW
SW
SW
R/W BUSY
SW Driver software
The master provides data
on the bus
Slave provides data on
the bus
A
A
R/W
BUSY M4
Bus state
Mn Diagram connections
XMEGA B [MANUAL] 241
Atmel-8291C-AVR-XMEGA B -09/2014
19.5.1.4 Case M4: Address packet transmit complete - Direction bit set
If the master receives an ACK from the slave, the master proceeds to receive the next byte of data from the slave. When
the first data byte is received, the master read interrupt flag is set and the master received acknowledge flag is cleared.
The clock hold is active at this point, preventing further activity on the bus.
19.5.2 Transmitting Data Packets
Assuming case M3 above, the master can start transmitting data by writing to the master data register. If the transfer was
successful, the slave will signal with ACK. The master write interrupt flag is set, the master received acknowledge flag is
cleared, and the master can prepare new data to send. During data transfer, the master is continuously monitoring the
bus for collisions.
The received acknowledge flag must be checked by software for each data packet transmitted before the next data
packet can be transferred. The master is not allowed to continue transmitting data if the slave signals a NACK.
If a collision is detected and the master loses arbitration during transfer, the arbitration lost flag is set.
19.5.3 Receiving Data Packets
Assuming case M4 above, the master has already received one byte from the slave. The master read interrupt flag is set,
and the master must prepare to receive new data. The master must respond to each byte with ACK or NACK. Indicating
a NACK might not be successfully executed, as arbitration can be lost during the transmission. If a collision is detected,
the master loses arbitration and the arbitration lost flag is set.
19.6 TWI Slave Operation
The TWI slave is byte-oriented with optional interrupts after each byte. There are separate slave data and address/stop
interrupts. Interrupt flags can also be used for polled operation. There are dedicated status flags for indicating
ACK/NACK received, clock hold, collision, bus error, and read/write direction.
When an interrupt flag is set, the SCL line is forced low. This will give the slave time to respond or handle data, and will in
most cases require software interaction. Figure 19-13. shows the TWI slave operation. The diamond shapes symbols
(SW) indicate where software interaction is required.
Figure 19-13.TWI slave operation.
The number of interrupts generated is kept to a minimum by automatic handling of most conditions. Quick command can
be enabled to auto-trigger operations and reduce software complexity.
Promiscuous mode can be enabled to allow the slave to respond to all received addresses.
S
S3
S2 ADDRESS A
S1
R
W
DATA A/A
DATA
P S2
Sr S3
P S2
Sr S3
SLAVE ADDRESS INTERRUPT SLAVE DATA INTERRUPT
A
Collision
(SMBus)
SW
SW SW
SW
A/A A/A
SW Release
Hold S1
A S1
SW Interrupt on STOP
Condition Enabled
S1
SW Driver software
The master provides data
on the bus
Slave provides data on
the bus
Sn Diagram connections
XMEGA B [MANUAL] 242
Atmel-8291C-AVR-XMEGA B -09/2014
19.6.1 Receiving Address Packets
When the TWI slave is properly configured, it will wait for a START condition to be detected. When this happens, the
successive address byte will be received and checked by the address match logic, and the slave will ACK a correct
address and store the address in the DATA register. If the received address is not a match, the slave will not
acknowledge and store address, and will wait for a new START condition.
The slave address/stop interrupt flag is set when a START condition succeeded by a valid address byte is detected. A
general call address will also set the interrupt flag.
A START condition immediately followed by a STOP condition is an illegal operation, and the bus error flag is set.
The R/W direction flag reflects the direction bit received with the address. This can be read by software to determine the
type of operation currently in progress.
Depending on the R/W direction bit and bus condition, one of four distinct cases (S1 to S4) arises following the address
packet. The different cases must be handled in software.
19.6.1.1 Case S1: Address packet accepted - Direction bit set
If the R/W direction flag is set, this indicates a master read operation. The SCL line is forced low by the slave, stretching
the bus clock. If ACK is sent by the slave, the slave hardware will set the data interrupt flag indicating data is needed for
transmit. Data, repeated START, or STOP can be received after this. If NACK is sent by the slave, the slave will wait for
a new START condition and address match.
19.6.1.2 Case S2: Address packet accepted - Direction bit cleared
If the R/W direction flag is cleared, this indicates a master write operation. The SCL line is forced low, stretching the bus
clock. If ACK is sent by the slave, the slave will wait for data to be received. Data, repeated START, or STOP can be
received after this. If NACK is sent, the slave will wait for a new START condition and address match.
19.6.1.3 Case S3: Collision
If the slave is not able to send a high level or NACK, the collision flag is set, and it will disable the data and acknowledge
output from the slave logic. The clock hold is released. A START or repeated START condition will be accepted.
19.6.1.4 Case S4: STOP condition received.
When the STOP condition is received, the slave address/stop flag will be set, indicating that a STOP condition, and not
an address match, occurred.
19.6.2 Receiving Data Packets
The slave will know when an address packet with R/W direction bit cleared has been successfully received. After
acknowledging this, the slave must be ready to receive data. When a data packet is received, the data interrupt flag is set
and the slave must indicate ACK or NACK. After indicating a NACK, the slave must expect a STOP or repeated START
condition.
19.6.3 Transmitting Data Packets
The slave will know when an address packet with R/W direction bit set has been successfully received. It can then start
sending data by writing to the slave data register. When a data packet transmission is completed, the data interrupt flag
is set. If the master indicates NACK, the slave must stop transmitting data and expect a STOP or repeated START
condition.
19.7 Enabling External Driver Interface
An external driver interface can be enabled. When this is done, the internal TWI drivers with input filtering and slew rate
control are bypassed. The normal I/O pin function is used, and the direction must be configured by the user software.
When this mode is enabled, an external TWI compliant tri-state driver is needed for connecting to a TWI bus.
By default, port pins 0 (Pn0) and 1 (Pn1) are used for SDA and SCL. The external driver interface uses port pins 0 to 3 for
the SDA_IN, SCL_IN, SDA_OUT, and SCL_OUT signals.
XMEGA B [MANUAL] 243
Atmel-8291C-AVR-XMEGA B -09/2014
19.8 Register Description – TWI
19.8.1 CTRL – Common Control Register
z Bit 7:3 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 2:1 – SDAHOLD[1:0]: SDA Hold Time Enable.
Setting these bits to one enables an internal hold time on SDA with respect to the negative edge of SCL.
Table 19-1. SDA hold time.
z Bit 0 – EDIEN: External Driver Interface Enable
Setting this bit enables the use of the external driver interface, and clearing this bit enables normal two-wire mode. See
Table 19-2 for details.
Table 19-2. External driver interface enable.
Bit 7 6 5 4 3 2 1 0
+0x00 – – – – – SDAHOLD[1:0] EDIEN
Read/Write R R R R R R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
SDAHOLD[1:0] Group Configuration Description
00 OFF SDA hold time off
01 50NS Typical 50ns hold time
10 300NS Typical 100ns hold time
11 400NS Typical 400ns hold time
EDIEN Mode Comment
0 Normal TWI Two-pin interface, slew rate control, and input filter.
1 External driver interface Four-pin interface, standard I/O, no slew rate control, and no input
filter.
XMEGA B [MANUAL] 244
Atmel-8291C-AVR-XMEGA B -09/2014
19.9 Register Description – TWI Master
19.9.1 CTRLA – Control register A
z Bit 7:6 – INTLVL[1:0]: Interrupt Level
These bits select the interrupt level for the TWI master interrupt, as described in “Interrupts and Programmable Multilevel
Interrupt Controller” on page 115.
z Bit 5 – RIEN: Read Interrupt Enable
Setting the read interrupt enable (RIEN) bit enables the read interrupt when the read interrupt flag (RIF) in the STATUS
register is set. In addition the INTLVL bits must be nonzero for TWI master interrupts to be generated.
z Bit 4 – WIEN: Write Interrupt Enable
Setting the write interrupt enable (WIEN) bit enables the write interrupt when the write interrupt flag (WIF) in the STATUS
register is set. In addition the INTLVL bits must be nonzero for TWI master interrupts to be generated.
z Bit 3 – ENABLE: Enable TWI Master
Setting the enable TWI master (ENABLE) bit enables the TWI master.
z Bit 2:0 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
19.9.2 CTRLB – Control register B
z Bit 7:4 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 3:2 – TIMEOUT[1:0]: Inactive Bus Timeout
Setting the inactive bus timeout (TIMEOUT) bits to a nonzero value will enable the inactive bus timeout supervisor. If the
bus is inactive for longer than the TIMEOUT setting, the bus state logic will enter the idle state.
Table 19-3 lists the timeout settings.
Bit 7 6 5 4 3 2 1 0
+0x00 INTLVL[1:0] RIEN WIEN ENABLE – – –
Read/Write R/W R/W R/W R/W R/W R R R
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
+0x01 – – – – TIMEOUT[1:0] QCEN SMEN
Read/Write R R R R R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 245
Atmel-8291C-AVR-XMEGA B -09/2014
Table 19-3. TWI master inactive bus timeout settings.
z Bit 1 – QCEN: Quick Command Enable
When quick command is enabled, the corresponding interrupt flag is set immediately after the slave acknowledges the
address (read or write interrupt). At this point, software can issue either a STOP or a repeated START condition.
z Bit 0 – SMEN: Smart Mode Enable
Setting this bit enables smart mode. When smart mode is enabled, the acknowledge action, as set by the ACKACT bit in
the CTRLC register, is sent immediately after reading the DATA register.
19.9.3 CTRLC – Control register C
z Bits 7:3 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 2 – ACKACT: Acknowledge Action
This bit defines the master's acknowledge behavior in master read mode. The acknowledge action is executed when a
command is written to the CMD bits. If SMEN in the CTRLB register is set, the acknowledge action is performed when
the DATA register is read.
Table 19-4 lists the acknowledge actions.
Table 19-4. ACKACT bit description.
z Bit 1:0 – CMD[1:0]: Command
Writing the command (CMD) bits triggers a master operation as defined by Table 19-5. The CMD bits are strobe bits, and
always read as zero. The acknowledge action is only valid in master read mode (R). In master write mode (W), a
command will only result in a repeated START or STOP condition. The ACKACT bit and the CMD bits can be written at
the same time, and then the acknowledge action will be updated before the command is triggered.
TIMEOUT[1:0] Group Configuration Description
00 DISABLED Disabled, normally used for I2
C
01 50US 50μs, normally used for SMBus at 100kHz
10 100US 100μs
11 200US 200μs
Bit 7 6 5 4 3 2 1 0
+0x02 – – – – – ACKACT CMD[1:0]
Read/Write R R R R R R/W R/W R/W
Initial Value 00000000
ACKACT Action
0 Send ACK
1 Send NACK
XMEGA B [MANUAL] 246
Atmel-8291C-AVR-XMEGA B -09/2014
Table 19-5. CMD bit description.
Writing a command to the CMD bits will clear the master interrupt flags and the CLKHOLD flag.
19.9.4 STATUS – Status register
z Bit 7 – RIF: Read Interrupt Flag
This flag is set when a byte is successfully received in master read mode; i.e., no arbitration was lost or bus error
occurred during the operation. Writing a one to this bit location will clear RIF. When this flag is set, the master forces the
SCL line low, stretching the TWI clock period. Clearing the interrupt flags will release the SCL line.
This flag is also cleared automatically when:
z Writing to the ADDR register
z Writing to the DATA register
z Reading the DATA register
z Writing a valid command to the CMD bits in the CTRLC register
z Bit 6 – WIF: Write Interrupt Flag
This flag is set when a byte is transmitted in master write mode. The flag is set regardless of the occurrence of a bus
error or an arbitration lost condition. WIF is also set if arbitration is lost during sending of a NACK in master read mode,
and if issuing a START condition when the bus state is unknown. Writing a one to this bit location will clear WIF. When
this flag is set, the master forces the SCL line low, stretching the TWI clock period. Clearing the interrupt flags will release
the SCL line.
The flag is also cleared automatically for the same conditions as RIF.
z Bit 5 – CLKHOLD: Clock Hold
This flag is set when the master is holding the SCL line low. This is a status flag and a read-only flag that is set when RIF
or WIF is set. Clearing the interrupt flags and releasing the SCL line will indirectly clear this flag.
The flag is also cleared automatically for the same conditions as RIF.
CMD[1:0] Group Configuration MODE Operation
00 NOACT X Reserved
01 START X Execute acknowledge action succeeded by
repeated START condition
10 BYTEREC
W No operation
R Execute acknowledge action succeeded by a byte
receive
11 STOP X Execute acknowledge action succeeded by issuing
a STOP condition
Bit 7 6 5 4 3 2 1 0
+0x03 RIF WIF CLKHOLD RXACK ARBLOST BUSERR BUSSTATE[1:0]
Read/Write R/W R/W R R R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 247
Atmel-8291C-AVR-XMEGA B -09/2014
z Bit 4 – RXACK: Received Acknowledge
This flag contains the most recently received acknowledge bit from the slave. This is a read-only flag. When read as zero,
the most recent acknowledge bit from the slave was ACK, and when read as one the most recent acknowledge bit was
NACK.
z Bit 3 – ARBLOST: Arbitration Lost
This flag is set if arbitration is lost while transmitting a high data bit or a NACK bit, or while issuing a START or repeated
START condition on the bus. Writing a one to this bit location will clear ARBLOST.
Writing the ADDR register will automatically clear ARBLOST.
z Bit 2 – BUSERR: Bus Error
This flag is set if an illegal bus condition has occurred. An illegal bus condition occurs if a repeated START or a STOP
condition is detected, and the number of received or transmitted bits from the previous START condition is not a multiple
of nine. Writing a one to this bit location will clear BUSERR.
Writing the ADDR register will automatically clear BUSERR.
z Bit 1:0 – BUSSTATE[1:0]: Bus State
These bits indicate the current TWI bus state as defined in Table 19-6. The change of bus state is dependent on bus
activity. Refer to the “TWI Bus State Logic” on page 238.
Table 19-6. TWI master bus state.
Writing 01 to the BUSSTATE bits forces the bus state logic into the idle state. The bus state logic cannot be forced into
any other state. When the master is disabled, and after reset, the bus state logic is disabled and the bus state is
unknown.
19.9.5 BAUD – Baud Rate register
The baud rate (BAUD) register defines the relation between the system clock and the TWI bus clock (SCL) frequency.
The frequency relation can be expressed by using the following equation:
[1]
The BAUD register must be set to a value that results in a TWI bus clock frequency (fTWI) equal or less than 100kHz or
400kHz, depending on which standard the application should comply with. The following equation [2] expresses equation
[1] solved for the BAUD value:
BUSSTATE[1:0] Group Configuration Description
00 UNKNOWN Unknown bus state
01 IDLE Idle bus state
10 OWNER Owner bus state
11 BUSY Busy bus state
Bit 7 6 5 4 3 2 1 0
+0x04 BAUD[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 00000
f TWI
f sys
2(5 + ( ) BAUD ) = ---------------------------------------[Hz]
XMEGA B [MANUAL] 248
Atmel-8291C-AVR-XMEGA B -09/2014
[2]
The BAUD register should be written only while the master is disabled.
19.9.6 ADDR – Address register
When the address (ADDR) register is written with a slave address and the R/W bit while the bus is idle, a START
condition is issued and the 7-bit slave address and the R/W bit are transmitted on the bus. If the bus is already owned
when ADDR is written, a repeated START is issued. If the previous transaction was a master read and no acknowledge
is sent yet, the acknowledge action is sent before the repeated START condition.
After completing the operation and the acknowledge bit from the slave is received, the SCL line is forced low if arbitration
was not lost. WIF is set.
If the bus state is unknown when ADDR is written, WIF is set and BUSERR is set.
All TWI master flags are automatically cleared when ADDR is written. This includes BUSERR, ARBLOST, RIF, and WIF.
The master ADDR can be read at any time without interfering with ongoing bus activity.
19.9.7 DATA – Data register
The data (DATA) register is used when transmitting and receiving data. During data transfer, data are shifted from/to the
DATA register and to/from the bus. This implies that the DATA register cannot be accessed during byte transfers, and
this is prevented by hardware. The DATA register can only be accessed when the SCL line is held low by the master; i.e.,
when CLKHOLD is set.
In master write mode, writing the DATA register will trigger a data byte transfer followed by the master receiving the
acknowledge bit from the slave. WIF and CLKHOLD are set.
In master read mode, RIF and CLKHOLD are set when one byte is received in the DATA register. If smart mode is
enabled, reading the DATA register will trigger the bus operation as set by the ACKACT bit. If a bus error occurs during
reception, WIF and BUSERR are set instead of RIF.
Accessing the DATA register will clear the master interrupt flags and CLKHOLD.
BAUD f sys
2 f TWI
= ---------------- – 5
Bit 7 6 5 4 3 2 1 0
+0x05 ADDR[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
+0x06 DATA[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 249
Atmel-8291C-AVR-XMEGA B -09/2014
19.10 Register Description – TWI Slave
19.10.1 CTRLA – Control register A
z Bit 7:6 – INTLVL[1:0]: Interrupt Level
These bits select the interrupt level for the TWI master interrupt, as described in “Interrupts and Programmable Multilevel
Interrupt Controller” on page 115.
z Bit 5 – DIEN: Data Interrupt Enable
Setting the data interrupt enable (DIEN) bit enables the data interrupt when the data interrupt flag (DIF) in the STATUS
register is set. The INTLVL bits must be nonzero for the interrupt to be generated.
z Bit 4 – APIEN: Address/Stop Interrupt Enable
Setting the address/stop interrupt enable (APIEN) bit enables the address/stop interrupt when the address/stop interrupt
flag (APIF) in the STATUS register is set. The INTLVL bits must be nonzero for interrupt to be generated.
z Bit 3 – ENABLE: Enable TWI Slave
Setting this bit enables the TWI slave.
z Bit 2 – PIEN: Stop Interrupt Enable
Setting the this bit will cause APIF in the STATUS register to be set when a STOP condition is detected.
z Bit 1 – PMEN: Promiscuous Mode Enable
By setting the this bit, the slave address match logic responds to all received addresses. If this bit is cleared, the address
match logic uses the ADDR register to determine which address to recognize as its own address.
z Bit 0 – SMEN: Smart Mode Enable
This bit enables smart mode. When Smart mode is enabled, the acknowledge action, as set by the ACKACT bit in the
CTRLB register, is sent immediately after reading the DATA register.
19.10.2 CTRLB – Control register B
z Bit 7:3 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 2 – ACKACT: Acknowledge Action
This bit defines the slave's acknowledge behavior after an address or data byte is received from the master. The
acknowledge action is executed when a command is written to the CMD bits. If the SMEN bit in the CTRLA register is
set, the acknowledge action is performed when the DATA register is read.
Table 19-7 lists the acknowledge actions.
Bit 7 6 5 4 3 2 1 0
+0x00 INTLVL[1:0] DIEN APIEN ENABLE PIEN PMEN SMEN
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0000 0 0
Bit 7 6 5 4 3 2 1 0
+0x01 – – – – – ACKACT CMD[1:0]
Read/Write R R R R R R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 250
Atmel-8291C-AVR-XMEGA B -09/2014
Table 19-7. TWI slave acknowledge actions.
z Bit 1:0 – CMD[1:0]: Command
Writing these bits trigger the slave operation as defined by Table 19-8. The CMD bits are strobe bits and always read as
zero. The operation is dependent on the slave interrupt flags, DIF and APIF. The acknowledge action is only executed
when the slave receives data bytes or address byte from the master.
Table 19-8. TWI slave command.
Writing the CMD bits will automatically clear the slave interrupt flags and CLKHOLD, and release the SCL line. The
ACKACT bit and CMD bits can be written at the same time, and then the acknowledge action will be updated before the
command is triggered.
ACKACT Action
0 Send ACK
1 Send NACK
CMD[1:0] Group Configuration DIR Operation
00 NOACT X No action
01 X Reserved
10 COMPLETE
Used to complete transaction
0 Execute acknowledge action succeeded by waiting for
any START (S/Sr) condition
1 Wait for any START (S/Sr) condition
11 RESPONSE
Used in response to an address byte (APIF is set)
0 Execute acknowledge action succeeded by reception
of next byte
1 Execute acknowledge action succeeded by DIF being
set
Used in response to a data byte (DIF is set)
0 Execute acknowledge action succeeded by waiting for
the next byte
1 No operation
XMEGA B [MANUAL] 251
Atmel-8291C-AVR-XMEGA B -09/2014
19.10.3 STATUS – Status register
z Bit 7 – DIF: Data Interrupt Flag
This flag is set when a data byte is successfully received; i.e., no bus error or collision occurred during the operation.
Writing a one to this bit location will clear DIF. When this flag is set, the slave forces the SCL line low, stretching the TWI
clock period. Clearing the interrupt flags will release the SCL line.
This flag is also cleared automatically when writing a valid command to the CMD bits in the CTRLB register
z Bit 6 – APIF: Address/Stop Interrupt Flag
This flag is set when the slave detects that a valid address has been received, or when a transmit collision is detected. If
the PIEN bit in the CTRLA register is set, a STOP condition on the bus will also set APIF. Writing a one to this bit location
will clear APIF. When set for an address interrupt, the slave forces the SCL line low, stretching the TWI clock period.
Clearing the interrupt flags will release the SCL line.
The flag is also cleared automatically for the same condition as DIF.
z Bit 5 – CLKHOLD: Clock Hold
This flag is set when the slave is holding the SCL line low.This is a status flag and a read-only bit that is set when DIF or
APIF is set. Clearing the interrupt flags and releasing the SCL line will indirectly clear this flag.
z Bit 4 – RXACK: Received Acknowledge
This flag contains the most recently received acknowledge bit from the master. This is a read-only flag. When read as
zero, the most recent acknowledge bit from the maser was ACK, and when read as one, the most recent acknowledge bit
was NACK.
z Bit 3 – COLL: Collision
This flag is set when a slave has not been able to transfer a high data bit or a NACK bit. If a collision is detected, the
slave will commence its normal operation, disable data, and acknowledge output, and no low values will be shifted out
onto the SDA line. Writing a one to this bit location will clear COLL.
The flag is also cleared automatically when a START or repeated START condition is detected.
z Bit 2 – BUSERR: TWI Slave Bus Error
This flag is set when an illegal bus condition occurs during a transfer. An illegal bus condition occurs if a repeated START
or a STOP condition is detected, and the number of bits from the previous START condition is not a multiple of nine.
Writing a one to this bit location will clear BUSERR.
For bus errors to be detected, the bus state logic must be enabled. This is done by enabling the TWI master.
z Bit 1 – DIR: Read/Write Direction
The R/W direction (DIR) flag reflects the direction bit from the last address packet received from a master. When this bit
is read as one, a master read operation is in progress. When read as zero, a master write operation is in progress.
z Bit 0 – AP: Slave Address or Stop
This flag indicates whether a valid address or a STOP condition caused the last setting of APIF in the STATUS register.
Table 19-9. TWI slave address or stop.
Bit 7 6 5 4 3 2 1 0
+0x02 DIF APIF CLKHOLD RXACK COLL BUSERR DIR AP
Read/Write R/W R/W R R R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
AP Description
0 A STOP condition generated the interrupt on APIF
1 Address detection generated the interrupt on APIF
XMEGA B [MANUAL] 252
Atmel-8291C-AVR-XMEGA B -09/2014
19.10.4 ADDR – Address register
The TWI slave address register should be loaded with the 7-bit slave address (in the seven most significant bits of
ADDR) to which the TWI will respond. The lsb of ADDR is used to enable recognition of the general call address (0x00).
z Bit 7:1 – ADDR[7:1]: TWI Slave Address
This register contains the TWI slave address used by the slave address match logic to determine if a master has
addressed the slave. The seven most-significant bits (ADDR[7:1]) represent the slave address.
When using 10-bit addressing, the address match logic only supports hardware address recognition of the first byte of a
10-bit address. By setting ADDR[7:1] = 0b11110nn, ”nn” represents bits 9 and 8 of the slave address. The next byte
received is bits 7 to 0 in the 10-bit address, and this must be handled by software.
When the address match logic detects that a valid address byte is received, APIF is set and the DIR flag is updated.
If the PMEN bit in CTRLA is set, the address match logic responds to all addresses transmitted on the TWI bus. The
ADDR register is not used in this mode.
z Bit 0 – ADDR: General Call Recognition Enable
When ADDR[0] is set, this enables general call address recognition logic so the device can respond to a general address
call that addresses all devices on the bus.
19.10.5 DATA – Data register
The data (DATA) register is used when transmitting and received data. During data transfer, data are shifted from/to the
DATA register and to/from the bus. This implies that the DATA register cannot be accessed during byte transfers, and
this is prevented by hardware. The DATA register can be accessed only when the SCL line is held low by the slave; i.e.,
when CLKHOLD is set.
When a master is reading data from the slave, data to send must be written to the DATA register. The byte transfer is
started when the master starts to clock the data byte from the slave, followed by the slave receiving the acknowledge bit
from the master. DIF and CLKHOLD are set.
When a master writes data to the slave, DIF and CLKHOLD are set when one byte has been received in the DATA
register. If smart mode is enabled, reading the DATA register will trigger the bus operation as set by the ACKACT bit.
Accessing the DATA register will clear the slave interrupt flags and CLKHOLD. When an address match occurs, the
received address will be stored in the DATA register.
Bit 7 6 5 4 3 2 1 0
+0x03 ADDR[7:1] ADDR[0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 000000
Bit 7 6 5 4 3 2 1 0
+0x04 DATA[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 253
Atmel-8291C-AVR-XMEGA B -09/2014
19.10.6 ADDRMASK – Address Mask register
z Bit 7:1 – ADDRMASK[7:1]: Address Mask
These bits can act as a second address match register or as an address mask register, depending on the ADDREN
setting.
If ADDREN is set to zero, ADDRMASK can be loaded with a 7-bit slave address mask. Each bit in ADDRMASK can
mask (disable) the corresponding address bit in the ADDR register. If the mask bit is one, the address match between the
incoming address bit and the corresponding bit in ADDR is ignored; i.e., masked bits will always match.
If ADDREN is set to one, ADDRMASK can be loaded with a second slave address in addition to the ADDR register. In
this mode, the slave will match on two unique addresses, one in ADDR and the other in ADDRMASK.
z Bit 0 – ADDREN: Address Enable
By default, this bit is zero, and the ADDRMASK bits acts as an address mask to the ADDR register. If this bit is set to
one, the slave address match logic responds to the two unique addresses in ADDR and ADDRMASK.
Bit 7 6 5 4 3 2 1 0
+0x05 ADDRMASK[7:1] ADDREN
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 254
Atmel-8291C-AVR-XMEGA B -09/2014
19.11 Register Summary - TWI
19.12 Register Summary - TWI Master
19.13 Register Summary - TWI Slave
19.14 Interrupt Vector Summary
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
+0x00 CTRL – – – – – SDAHOLD[1:0] EDIEN 243
+0x01 MASTER Offset address for TWI Master
+0x08 SLAVE Offset address for TWI Slave
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
+0x00 CTRLA INTLVL[1:0] RIEN WIEN ENABLE – – – 244
+0x01 CTRLB – – – – TIMEOUT[1:0] QCEN SMEN 244
+0x02 CTRLC – – – – – ACKACT CMD[1:0] 245
+0x03 STATUS RIF WIF CLKHOLD RXACK ARBLOST BUSERR BUSSTATE[1:0] 246
+0x04 BAUD BAUD[7:0] 247
+0x05 ADDR ADDR[7:0] 248
+0x06 DATA DATA[7:0] 248
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
+0x00 CTRLA INTLVL[1:0] DIEN APIEN ENABLE PIEN TPMEN SMEN 249
+0x01 CTRLB – – – – – ACKACT CMD[1:0] 249
+0x02 STATUS DIF APIF CLKHOLD RXACK COLL BUSERR DIR AP 251
+0x03 ADDR ADDR[7:0] 252
+0x04 DATA DATA[7:0] 252
+0x05 ADDRMAS ADDRMASK[7:1] ADDREN 253
Offset Source Interrupt Description
0x00 SLAVE_vect TWI slave interrupt vector
0x02 MASTER_vect TWI master interrupt vector
XMEGA B [MANUAL] 255
8291C–AVR–09/2014
20. SPI – Serial Peripheral Interface
20.1 Features
z Full-duplex, three-wire synchronous data transfer
z Master or slave operation
z Lsb first or msb first data transfer
z Eight programmable bit rates
z Interrupt flag at the end of transmission
z Write collision flag to indicate data collision
z Wake up from idle sleep mode
z Double speed master mode
20.2 Overview
The Serial Peripheral Interface (SPI) is a high-speed synchronous data transfer interface using three or four pins. It
allows fast communication between an XMEGA device and peripheral devices or between several microcontrollers. The
SPI supports full-duplex communication.
A device connected to the bus must act as a master or slave.The master initiates and controls all data transactions. The
interconnection between master and slave devices with SPI is shown in Figure 20-1 on page 255. The system consists of
two shift registers and a master clock generator. The SPI master initiates the communication cycle by pulling the slave
select (SS) signal low for the desired slave. Master and slave prepare the data to be sent in their respective shift
registers, and the master generates the required clock pulses on the SCK line to interchange data. Data are always
shifted from master to slave on the master output, slave input (MOSI) line, and from slave to master on the master input,
slave output (MISO) line. After each data packet, the master can synchronize the slave by pulling the SS line high.
Figure 20-1. SPI master-slave interconnection.
The SPI module is unbuffered in the transmit direction and single buffered in the receive direction. This means that bytes
to be transmitted cannot be written to the SPI DATA register before the entire shift cycle is completed. When receiving
data, a received character must be read from the DATA register before the next character has been completely shifted in.
Otherwise, the first byte will be lost.
In SPI slave mode, the control logic will sample the incoming signal on the SCK pin. To ensure correct sampling of this
clock signal, the minimum low and high periods must each be longer than two CPU clock cycles.
When the SPI module is enabled, the data direction of the MOSI, MISO, SCK, and SS pins is overridden according to
Table 20-1. The pins with user-defined direction must be configured from software to have the correct direction according
to the application.
SHIFT
ENABLE
XMEGA B [MANUAL] 256
8291C–AVR–09/2014
Table 20-1. SPI pin override and directions.
20.3 Master Mode
In master mode, the SPI interface has no automatic control of the SS line. If the SS pin is used, it must be configured as
output and controlled by user software. If the bus consists of several SPI slaves and/or masters, a SPI master can use
general purpose I/O pins to control the SS line to each of the slaves on the bus.
Writing a byte to the DATA register starts the SPI clock generator and the hardware shifts the eight bits into the selected
slave. After shifting one byte, the SPI clock generator stops and the SPI interrupt flag is set. The master may continue to
shift the next byte by writing new data to the DATA register, or can signal the end of the transfer by pulling the SS line
high. The last incoming byte will be kept in the buffer register.
If the SS pin is not used and is configured as input, it must be held high to ensure master operation. If the SS pin is set as
input and is being driven low, the SPI module will interpret this as another master trying to take control of the bus. To
avoid bus contention, the master will take the following action:
1. The master enters slave mode.
2. The SPI interrupt flag is set.
20.4 Slave Mode
In slave mode, the SPI module will remain sleeping with the MISO line tri-stated as long as the SS pin is driven high. In
this state, software may update the contents of the DATA register, but the data will not be shifted out by incoming clock
pulses on the SCK pin until the SS pin is driven low. If SS is driven low, the slave will start to shift out data on the first
SCK clock pulse. When one byte has been completely shifted, the SPI interrupt flag is set. The slave may continue
placing new data to be sent into the DATA register before reading the incoming data. The last incoming byte will be kept
in the buffer register.
When SS is driven high, the SPI logic is reset, and the SPI slave will not receive any new data. Any partially received
packet in the shift register will be dropped.
As the SS pin is used to signal the start and end of a transfer, it is also useful for doing packet/byte synchronization,
keeping the slave bit counter synchronous with the master clock generator.
20.5 Data Modes
There are four combinations of SCK phase and polarity with respect to serial data. The SPI data transfer formats are
shown in Figure 20-2. Data bits are shifted out and latched in on opposite edges of the SCK signal, ensuring sufficient
time for data signals to stabilize.
The leading edge is the first clock edge of a clock cycle. The trailing edge is the last clock edge of a clock cycle.
Pin Master Mode Slave Mode
MOSI User defined Input
MISO Input User defined
SCK User defined Input
SS User defined Input
XMEGA B [MANUAL] 257
8291C–AVR–09/2014
Figure 20-2. SPI transfer modes.
20.6 DMA Support
DMA support on the SPI module is available only in slave mode. The SPI slave can trigger a DMA transfer as one byte
has been shifted into the DATA register. It is possible, however, to use the XMEGA USART in SPI mode and then have
DMA support in master mode. For details, refer to “USART in Master SPI Mode” on page 273.
Bit 1
Bit 6
LSB
MSB
Mode 0
SAMPLE I
MOSI/MISO
CHANGE 0
MOSI PIN
CHANGE 0
MISO PIN
Mode 2
SS
MSB
LSB
Bit 6
Bit 1
Bit 5
Bit 2
Bit 4
Bit 3
Bit 3
Bit 4
Bit 2
Bit 5
MSB first (DORD = 0)
LSB first (DORD = 1)
Mode 1
SAMPLE I
MOSI/MISO
CHANGE 0
MOSI PIN
CHANGE 0
MISO PIN
Mode 3
SS
MSB
LSB
Bit 6
Bit 1
Bit 5
Bit 2
Bit 4
Bit 3
Bit 3
Bit 4
Bit 2
Bit 5
Bit 1
Bit 6
LSB
MSB
MSB first (DORD = 0)
LSB first (DORD = 1)
XMEGA B [MANUAL] 258
8291C–AVR–09/2014
20.7 Register Description
20.7.1 CTRL – Control register
z Bit 7 – CLK2X: Clock Double
When this bit is set, the SPI speed (SCK frequency) will be doubled in master mode (see Table 20-3 on page 259).
z Bit 6 – ENABLE: Enable
Setting this bit enables the SPI module. This bit must be set to enable any SPI operations.
z Bit 5 – DORD: Data Order
DORD decides the data order when a byte is shifted out from the DATA register. When DORD is written to one, the leastsignificant
bit (lsb) of the data byte is transmitted first, and when DORD is written to zero, the most-significant bit (msb) of
the data byte is transmitted first.
z Bit 4 – MASTER: Master Select
This bit selects master mode when written to one, and slave mode when written to zero. If SS is configured as an input
and driven low while master mode is set, master mode will be cleared.
z Bit 3:2 – MODE[1:0]: Transfer Mode
These bits select the transfer mode. The four combinations of SCK phase and polarity with respect to the serial data are
shown in Table 20-2. These bits decide whether the first edge of a clock cycle (leading edge) is rising or falling, and
whether data setup and sample occur on the leading or trailing edge.
When the leading edge is rising, the SCK signal is low when idle, and when the leading edge is falling, the SCK signal is
high when idle.
Table 20-2. SPI transfer mode
z Bits 1:0 – PRESCALER[1:0]: Clock Prescaler
These two bits control the SPI clock rate configured in master mode. These bits have no effect in slave mode. The
relationship between SCK and the peripheral clock frequency ( clkPER) is shown in Table 20-3.
Bit 7 6 5 4 3 2 1 0
+0x00 CLK2X ENABLE DORD MASTER MODE[1:0] PRESCALER[1:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
MODE[1:0] Group Configuration Leading Edge Trailing Edge
00 0 Rising, sample Falling, setup
01 1 Rising, setup Falling, sample
10 2 Falling, sample Rising, setup
11 3 Falling, setup Rising, sample
XMEGA B [MANUAL] 259
8291C–AVR–09/2014
Table 20-3. Relationship between SCK and the peripheral clock (ClkPER) frequency.
20.7.2 INTCTRL – Interrupt Control register
z Bit 7:2 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 1:0 – INTLVL[1:0]: Interrupt Level
These bits enable the SPI interrupt and select the interrupt level, as described in “Interrupts and Programmable Multilevel
Interrupt Controller” on page 115. The enabled interrupt will be triggered when IF in the STATUS register is set.
20.7.3 STATUS – Status register
z Bit 7 – IF: Interrupt Flag
This flag is set when a serial transfer is complete and one byte is completely shifted in/out of the DATA register. If SS is
configured as input and is driven low when the SPI is in master mode, this will also set this flag. IF is cleared by hardware
when executing the corresponding interrupt vector. Alternatively, the IF flag can be cleared by first reading the STATUS
register when IF is set, and then accessing the DATA register.
z Bit 6 – WRCOL: Write Collision Flag
The WRCOL flag is set if the DATA register is written during a data transfer. This flag is cleared by first reading the
STATUS register when WRCOL is set, and then accessing the DATA register.
z Bit 5:0 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
CLK2X PRESCALER[1:0] SCK Frequency
0 00 ClkPER/4
0 01 ClkPER/16
0 10 ClkPER/64
0 11 ClkPER/128
1 00 ClkPER/2
1 01 ClkPER/8
1 10 ClkPER/32
1 11 ClkPER/64
Bit 7 6 5 4 3 2 1 0
+0x01 – – – – – – INTLVL[1:0]
Read/Write R R R R R R R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
+0x02 IF WRCOL – – – – – –
Read/Write R R R R R R R R
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 260
8291C–AVR–09/2014
20.7.4 DATA – Data register
The DATA register is used for sending and receiving data. Writing to the register initiates the data transmission, and the
byte written to the register will be shifted out on the SPI output line. Reading the register causes the shift register receive
buffer to be read, returning the last byte successfully received.
20.8 Register Summary
20.9 Interrupt vector Summary
Bit 7 6 5 4 3 2 1 0
+0x03 DATA[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
+0x00 CTRL CLK2X ENABLE DORD MASTER MODE[1:0] PRESCALER[1:0] 258
+0x01 INTCTRL – – – – – – INTLVL[1:0] 259
+0x02 STATUS IF WRCOL – – – – – – 259
+0x03 DATA DATA[7:0] 260
Offset Source Interrupt Description
0x00 SPI_vect SPI interrupt vector
XMEGA B [MANUAL] 261
8291C–AVR–09/2014
21. USART
21.1 Features
z Full-duplex operation
z Asynchronous or synchronous operation
z Synchronous clock rates up to 1/2 of the device clock frequency
z Asynchronous clock rates up to 1/8 of the device clock frequency
z Supports serial frames with 5, 6, 7, 8, or 9 data bits and 1 or 2 stop bits
z Fractional baud rate generator
z Can generate desired baud rate from any system clock frequency
z No need for external oscillator with certain frequencies
z Built-in error detection and correction schemes
z Odd or even parity generation and parity check
z Data overrun and framing error detection
z Noise filtering includes false start bit detection and digital low-pass filter
z Separate interrupts for
z Transmit complete
z Transmit data register empty
z Receive complete
z Multiprocessor communication mode
z Addressing scheme to address a specific devices on a multi-device bus
z Enable unaddressed devices to automatically ignore all frames
z Master SPI mode
z Double buffered operation
z Configurable data order
z Operation up to 1/2 of the peripheral clock frequency
z IRCOM module for IrDA compliant pulse modulation/demodulation
21.2 Overview
The universal synchronous and asynchronous serial receiver and transmitter (USART) is a fast and flexible serial
communication module. The USART supports full-duplex communication and asynchronous and synchronous operation.
The USART can be configured to operate in SPI master mode and used for SPI communication.
Communication is frame based, and the frame format can be customized to support a wide range of standards. The
USART is buffered in both directions, enabling continued data transmission without any delay between frames. Separate
interrupts for receive and transmit complete enable fully interrupt driven communication. Frame error and buffer overflow
are detected in hardware and indicated with separate status flags. Even or odd parity generation and parity check can
also be enabled.
A block diagram of the USART is shown in Figure 21-1 on page 262. The main functional blocks are the clock generator,
the transmitter, and the receiver, which are indicated in dashed boxes.
XMEGA B [MANUAL] 262
8291C–AVR–09/2014
Figure 21-1. USART block diagram.
The clock generator includes a fractional baud rate generator that is able to generate a wide range of USART baud rates
from any system clock frequencies. This removes the need to use an external crystal oscillator with a specific frequency
to achieve a required baud rate. It also supports external clock input in synchronous slave operation.
The transmitter consists of a single write buffer (DATA), a shift register, and a parity generator. The write buffer allows
continuous data transmission without any delay between frames.
The receiver consists of a two-level receive buffer (DATA) and a shift register. Data and clock recovery units ensure
robust synchronization and noise filtering during asynchronous data reception. It includes frame error, buffer overflow,
and parity error detection.
When the USART is set in master SPI mode, all USART-specific logic is disabled, leaving the transmit and receive
buffers, shift registers, and baud rate generator enabled. Pin control and interrupt generation are identical in both modes.
The registers are used in both modes, but their functionality differs for some control settings.
An IRCOM module can be enabled for one USART to support IrDA 1.4 physical compliant pulse modulation and
demodulation for baud rates up to 115.2kbps. For details, refer to “IRCOM - IR Communication Module” on page 282.
21.3 Clock Generation
The clock used for baud rate generation and for shifting and sampling data bits is generated internally by the fractional
baud rate generator or externally from the transfer clock (XCK) pin. Five modes of clock generation are supported:
normal and double-speed asynchronous mode, master and slave synchronous mode, and master SPI mode.
PARITY
GENERATOR
BSEL [H:L]
DATA (Transmit)
CTRLA CTRLB CTRLC
BAUD RATE GENERATOR
FRACTIONAL DIVIDE
TRANSMIT SHIFT REGISTER
RECEIVE SHIFT REGISTER RxD
TxD PIN
CONTROL
DATA (Receive)
PIN
CONTROL
XCK
DATA
RECOVERY
CLOCK
RECOVERY
PIN
CONTROL
TX
CONTROL
RX
CONTROL
PARITY
CHECKER
DATA BUS
OSC
SYNC LOGIC
Clock Generator
Transmitter
Receiver
XMEGA B [MANUAL] 263
8291C–AVR–09/2014
Figure 21-2. Clock generation logic, block diagram.
21.3.1 Internal Clock Generation - The Fractional Baud Rate Generator
The fractional baud rate generator is used for internal clock generation for asynchronous modes, synchronous master
mode, and master SPI mode operation. The output frequency generated (fBAUD) is determined by the period setting
(BSEL), an optional scale setting (BSCALE), and the peripheral clock frequency (fPER). Table 21-1 contains equations for
calculating the baud rate (in bits per second) and for calculating the BSEL value for each mode of operation. It also
shows the maximum baud rate versus peripheral clock frequency. BSEL can be set to any value between 0 and 4095.
BSCALE can be set to any value between -7 and +7, and increases or decreases the baud rate slightly to provide the
fractional baud rate scaling of the baud rate generator.
When BSEL is 0, BSCALE must also be 0. Also, the value 2ABS(BSCALE) must at most be one half of the minimum number
of clock cycles a frame requires. For more details, see “Fractional Baud Rate Generation” on page 271.
Table 21-1. Equations for calculating baud rate register settings.
Note: 1. The baud rate is defined to be the transfer rate in bits per second (bps)
Baud Rate
Generator /2
BSEL
/4 /2
Sync
Register
fOSC
XCK
Pin
txclk
CLK2X
UMSEL [1]
DDR_XCK
0
1
0
1
xcki
xcko
DDR_XCK rxclk 0
1
1
0
Edge
Detector
PORT_INV
fBAUD
Operating Mode Conditions Baud Rate(1) Calculation BSEL Value Calculation
Asynchronous normal
speed mode (CLK2X = 0)
BSCALE ≥ 0
BSCALE < 0
Asynchronous double
speed mode (CLK2X = 1)
BSCALE ≥ 0
BSCALE < 0
Synchronous and master
SPI mode
f BAUD
f PER
16
≤ ------------- f BAUD
f PER
2
BSCALE ⋅ 16(BSEL + 1)
= ------------------------------------------------------------ BSEL f PER
2
BSCALE ⋅ 16 f BAUD
= -------------------------------------------------- – 1
f BAUD
f PER
16
≤ ------------- f BAUD
f PER
16((2BSCALE ⋅ BSEL ) + 1)
= ------------------------------------------------------------------ BSEL 1
2
BSCALE
--------------------- f PER
16 f BAUD
----------------------- – 1 ⎝ ⎠ ⎛ ⎞ =
f BAUD
f PER
8
≤ ------------- f BAUD
f PER
2
BSCALE ⋅ ⋅ 8 ( ) BSEL + 1
= -------------------------------------------------------------- BSEL f PER
2
BSCALE ⋅ 8 f BAUD
= ----------------------------------------------- – 1
f BAUD
f PER
8
≤ ------------- f BAUD
f PER
8((2BSCALE ⋅ BSEL ) + 1)
= --------------------------------------------------------------- BSEL 1
2
BSCALE
--------------------- f PER
8 f BAUD
-------------------- – 1 ⎝ ⎠ ⎛ ⎞ =
f BAUD
f PER
2
< ------------- f BAUD
f PER
2 ⋅ ( ) BSEL + 1 = ------------------------------------ BSEL f PER
2 f BAUD
= -------------------- – 1
XMEGA B [MANUAL] 264
8291C–AVR–09/2014
For BSEL=0, all baud rates must be achieved by changing BSEL instead of setting BSCALE:
BSEL = (2 BSCALE-1)
21.3.2 External Clock
External clock (XCK) is used in synchronous slave mode operation. The XCK clock input is sampled on the peripheral
clock frequency (fPER), and the maximum XCK clock frequency (fXCK)is limited by the following:
For each high and low period, XCK clock cycles must be sampled twice by the peripheral clock. If the XCK clock has
jitter, or if the high/low period duty cycle is not 50/50, the maximum XCK clock speed must be reduced or the peripheral
clock must be increased accordingly.
21.3.3 Double Speed Operation
Double speed operation allows for higher baud rates under asynchronous operation with lower peripheral clock
frequencies. When this is enabled, the baud rate for a given asynchronous baud rate setting shown in Table 21-1 on
page 263 will be doubled. In this mode, the receiver will use half the number of samples (reduced from 16 to 8) for data
sampling and clock recovery. Due to the reduced sampling, a more accurate baud rate setting and peripheral clock are
required. See “Asynchronous Data Reception” on page 268 for more details.
21.3.4 Synchronous Clock Operation
When synchronous mode is used, the XCK pin controls whether the transmission clock is input (slave mode) or output
(master mode). The corresponding port pin must be set to output for master mode or to input for slave mode. The normal
port operation of the XCK pin will be overridden. The dependency between the clock edges and data sampling or data
change is the same. Data input (on RxD) is sampled at the XCK clock edge which is opposite the edge where data output
(TxD) is changed.
BSCALE BSEL BSCALE BSEL
1 0 → 0 1
2 0 → 0 3
3 0 → 0 7
4 0 → 0 15
5 0 → 0 31
6 0 → 0 63
7 0 → 0 127
f XCK
f PER
4
< -------------
XMEGA B [MANUAL] 265
8291C–AVR–09/2014
Figure 21-3. Synchronous mode XCK timing.
Using the inverted I/O (INVEN) setting for the corresponding XCK port pin, the XCK clock edges used for data sampling
and data change can be selected. If inverted I/O is disabled (INVEN=0), data will be changed at the rising XCK clock
edge and sampled at the falling XCK clock edge. If inverted I/O is enabled (INVEN=1), data will be changed at the falling
XCK clock edge and sampled at the rising XCK clock edge. For more details, see “I/O Ports” on page 123.
21.3.5 Master SPI Mode Clock Generation
For master SPI mode operation, only internal clock generation is supported. This is identical to the USART synchronous
master mode, and the baud rate or BSEL setting is calculated using the same equations (see Table 21-1 on page 263).
There are four combinations of the SPI clock (SCK) phase and polarity with respect to the serial data, and these are
determined by the clock phase (UCPHA) control bit and the inverted I/O pin (INVEN) settings. The data transfer timing
diagrams are shown in Figure 21-4 on page 266. Data bits are shifted out and latched in on opposite edges of the XCK
signal, ensuring sufficient time for data signals to stabilize. The UCPHA and INVEN settings are summarized in Table 21-
2. Changing the setting of any of these bits during transmission will corrupt both the receiver and transmitter
Table 21-2. INVEN and UCPHA functionality.
The leading edge is the first clock edge of a clock cycle. The trailing edge is the last clock edge of a clock cycle.
RxD / TxD
XCK
RxD / TxD
UCPOL = 0 XCK
UCPOL = 1
Sample
Sample
SPI Mode INVEN UCPHA Leading Edge Trailing Edge
0 0 0 Rising, sample Falling, setup
1 0 1 Rising, setup Falling, sample
2 1 0 Falling, sample Rising, setup
3 1 1 Falling, setup Rising, sample
XMEGA B [MANUAL] 266
8291C–AVR–09/2014
Figure 21-4. UCPHA and INVEN data transfer timing diagrams.
21.4 Frame Formats
Data transfer is frame based, where a serial frame consists of one character of data bits with synchronization bits (start
and stop bits) and an optional parity bit for error checking. Note that this does not apply to master SPI operation (See
“SPI Frame Formats” on page 267). The USART accepts all combinations of the following as valid frame formats:
z 1 start bit
z 5, 6, 7, 8, or 9 data bits
z no, even, or odd parity bit
z 1 or 2 stop bits
A frame starts with the start bit, followed by all the data bits (least-significant bit first and most-significant bit last). If
enabled, the parity bit is inserted after the data bits, before the first stop bit. One frame can be directly followed by a start
bit and a new frame, or the communication line can return to the idle (high) state. Figure 21-5 on page 266 illustrates the
possible combinations of frame formats. Bits inside brackets are optional.
Figure 21-5. Frame formats.
21.4.1 Parity Bit Calculation
Even or odd parity can be selected for error checking. If even parity is selected, the parity bit is set to one if the number of
logical one data bits is odd (making the total number of ones even). If odd parity is selected, the parity bit is set to one if
the number of logical one data bits is even (making the total number of ones odd).
XCK
Data setup (TXD)
Data sample (RXD)
XCK
Data setup (TXD)
Data sample (RXD)
XCK
Data setup (TXD)
Data sample (RXD)
XCK
Data setup (TXD)
Data sample (RXD)
UCPOL=0 UCPOL=1
UCPHA=0 UCPHA=1
St Start bit, always low.
(n) Data bits (0 to 8).
P Parity bit, may be odd or even.
Sp Stop bit, always high.
IDLE No transfers on the communication line (RxD or TxD). The IDLE state is always high.
(IDLE) St Sp1 [Sp2] 0 2 3 4 [5] [6] [7] [8] [P] 1 (St / IDLE)
FRAME
XMEGA B [MANUAL] 267
8291C–AVR–09/2014
21.4.2 SPI Frame Formats
The serial frame in SPI mode is defined to be one character of eight data bits. The USART in master SPI mode has two
selectable frame formats:
z 8-bit data, msb first
z 8-bit data, lsb first
After a complete, 8-bit frame is transmitted, a new frame can directly follow it, or the communication line can return to the
idle (high) state.
21.5 USART Initialization
USART initialization should use the following sequence:
1. Set the TxD pin value high, and optionally set the XCK pin low.
2. Set the TxD and optionally the XCK pin as output.
3. Set the baud rate and frame format.
4. Set the mode of operation (enables XCK pin output in synchronous mode).
5. Enable the transmitter or the receiver, depending on the usage.
For interrupt-driven USART operation, global interrupts should be disabled during the initialization.
Before doing a re-initialization with a changed baud rate or frame format, be sure that there are no ongoing transmissions
while the registers are changed.
21.6 Data Transmission - The USART Transmitter
When the transmitter has been enabled, the normal port operation of the TxD pin is overridden by the USART and given
the function as the transmitter's serial output. The direction of the pin must be set as output using the direction register for
the corresponding port. For details on port pin control and output configuration, refer to “I/O Ports” on page 123.
21.6.1 Sending Frames
A data transmission is initiated by loading the transmit buffer (DATA) with the data to be sent. The data in the transmit
buffer are moved to the shift register when the shift register is empty and ready to send a new frame. The shift register is
loaded if it is in idle state (no ongoing transmission) or immediately after the last stop bit of the previous frame is
transmitted. When the shift register is loaded with data, it will transfer one complete frame.
The transmit complete interrupt flag (TXCIF) is set and the optional interrupt is generated when the entire frame in the
shift register has been shifted out and there are no new data present in the transmit buffer.
The transmit data register (DATA) can only be written when the data register empty flag (DREIF) is set, indicating that the
register is empty and ready for new data.
When using frames with fewer than eight bits, the most-significant bits written to DATA are ignored. If 9-bit characters are
used, the ninth bit must be written to the TXB8 bit before the low byte of the character is written to DATA.
21.6.2 Disabling the Transmitter
A disabling of the transmitter will not become effective until ongoing and pending transmissions are completed; i.e., when
the transmit shift register and transmit buffer register do not contain data to be transmitted. When the transmitter is
disabled, it will no longer override the TxDn pin, and the pin direction is set as input automatically by hardware, even if it
was configured as output by the user.
21.7 Data Reception - The USART Receiver
When the receiver is enabled, the RxD pin functions as the receiver's serial input. The direction of the pin must be set as
input, which is the default pin setting.
XMEGA B [MANUAL] 268
8291C–AVR–09/2014
21.7.1 Receiving Frames
The receiver starts data reception when it detects a valid start bit. Each bit that follows the start bit will be sampled at the
baud rate or XCK clock and shifted into the receive shift register until the first stop bit of a frame is received. A second
stop bit will be ignored by the receiver. When the first stop bit is received and a complete serial frame is present in the
receive shift register, the contents of the shift register will be moved into the receive buffer. The receive complete
interrupt flag (RXCIF) is set, and the optional interrupt is generated.
The receiver buffer can be read by reading the data register (DATA) location. DATA should not be read unless the
receive complete interrupt flag is set. When using frames with fewer than eight bits, the unused most-significant bits are
read as zero. If 9-bit characters are used, the ninth bit must be read from the RXB8 bit before the low byte of the
character is read from DATA.
21.7.2 Receiver Error Flags
The USART receiver has three error flags. The frame error (FERR), buffer overflow (BUFOVF) and parity error (PERR)
flags are accessible from the status register. The error flags are located in the receive FIFO buffer together with their
corresponding frame. Due to the buffering of the error flags, the status register must be read before the receive buffer
(DATA), since reading the DATA location changes the FIFO buffer.
21.7.3 Parity Checker
When enabled, the parity checker calculates the parity of the data bits in incoming frames and compares the result with
the parity bit of the corresponding frame. If a parity error is detected, the parity error flag is set.
21.7.4 Disabling the Receiver
A disabling of the receiver will be immediate. The receiver buffer will be flushed, and data from ongoing receptions will be
lost.
21.7.5 Flushing the Receive Buffer
If the receive buffer has to be flushed during normal operation, read the DATA location until the receive complete
interrupt flag is cleared.
21.8 Asynchronous Data Reception
The USART includes a clock recovery and a data recovery unit for handling asynchronous data reception. The clock
recovery unit is used for synchronizing the incoming asynchronous serial frames at the RxD pin to the internally
generated baud rate clock. It samples and low-pass filters each incoming bit, thereby improving the noise immunity of the
receiver. The asynchronous reception operational range depends on the accuracy of the internal baud rate clock, the
rate of the incoming frames, and the frame size in number of bits.
21.8.1 Asynchronous Clock Recovery
The clock recovery unit synchronizes the internal clock to the incoming serial frames. Figure 21-6 on page 269 illustrates
the sampling process for the start bit of an incoming frame. The sample rate is 16 times the baud rate for normal mode,
and eight times the baud rate for double speed mode. The horizontal arrows illustrate the synchronization variation due
to the sampling process. Note the larger time variation when using the double speed mode of operation. Samples
denoted as zero are samples done when the RxD line is idle; i.e., when there is no communication activity.
XMEGA B [MANUAL] 269
8291C–AVR–09/2014
Figure 21-6. Start bit sampling.
When the clock recovery logic detects a high (idle) to low (start) transition on the RxD line, the start bit detection
sequence is initiated. Sample 1 denotes the first zero-sample, as shown in the figure. The clock recovery logic then uses
samples 8, 9, and 10 for normal mode and samples 4, 5, and 6 for double speed mode to decide if a valid start bit is
received. If two or three samples have a low level, the start bit is accepted. The clock recovery unit is synchronized, and
the data recovery can begin. If two or three samples have a high level, the start bit is rejected as a noise spike, and the
receiver looks for the next high-to-low transition. The process is repeated for each start bit.
21.8.2 Asynchronous Data Recovery
The data recovery unit uses sixteen samples in normal mode and eight samples in double speed mode for each bit.
Figure 21-7 on page 269 shows the sampling process of data and parity bits.
Figure 21-7. Sampling of data and parity bits.
As for start bit detection, an identical majority voting technique is used on the three center samples for deciding of the
logic level of the received bit. The process is repeated for each bit until a complete frame is received. It includes the first
stop bit, but excludes additional ones. If the sampled stop bit is a 0 value, the frame error (FERR) flag will be set.
Figure 21-8 on page 269 shows the sampling of the stop bit in relation to the earliest possible beginning of the next
frame's start bit.
Figure 21-8. Stop bit and next start bit sampling.
A new high-to-low transition indicating the start bit of a new frame can come right after the last of the bits used for
majority voting. For normal speed mode, the first low level sample can be at the point marked (A) in Stop Bit Sampling
and Next Start Bit Sampling. For double speed mode, the first low level must be delayed to point (B). Point (C) marks a
stop bit of full length at nominal baud rate. The early start bit detection influences the operational range of the receiver.
1234567 8 9 10 11 12 13 14 15 16 1 2
IDLE START
0 0
BIT 0
3
0 123 4 5 678 1 2
RxD
Sample
(U2X = 0)
Sample
(U2X = 1)
1234567 8 9 10 11 12 13 14 15 16 1
BIT n
123 4 5 678 1
RxD
Sample
(CLK2X = 0)
Sample
(CLK2X = 1)
1234567 8 9 10 0/1 0/1 0/1
STOP 1
123 4 5 6 0/1
RxD
Sample
(CLK2X = 0)
Sample
(CLK2X = 1)
(A) (B) (C)
XMEGA B [MANUAL] 270
8291C–AVR–09/2014
21.8.3 Asynchronous Operational Range
The operational range of the receiver is dependent on the mismatch between the received bit rate and the internally
generated baud rate. If an external transmitter is sending using bit rates that are too fast or too slow, or if the internally
generated baud rate of the receiver does not match the external source’s base frequency, the receiver will not be able to
synchronize the frames to the start bit.
The following equations can be used to calculate the ratio of the incoming data rate and internal receiver baud rate.
Table 21-3 and Table 21-4 on page 270 list the maximum receiver baud rate error that can be tolerated. Normal speed
mode has higher tolerance of baud rate variations.
Table 21-3. Recommended maximum receiver baud rate error for normal speed mode.
Table 21-4. Recommended maximum receiver baud rate error for double speed mode.
D Sum of character size and parity size (D = 5 to 10 bits).
S Samples per bit. S = 16 for normal speed mode and S = 8 for double speed mode.
SF First sample number used for majority voting. SF = 8 for normal speed mode and SF = 4 for double speed
mode.
SM Middle sample number used for majority voting. SM = 9 for normal speed mode and SM = 5 for double speed
mode.
Rslow The ratio of the slowest incoming data rate that can be accepted in relation to the receiver baud rate.
Rfast The ratio of the fastest incoming data rate that can be accepted in relation to the receiver baud rate.
D
#(Data + Parity Bit) Rslow [%] Rfast [%] Max Total Error [%]
Recommended Max
Receiver Error [%]
5 93.20 106.67 +6.67/-6.80 ± 3.0
6 94.12 105.79 +5.79/-5.88 ± 2.5
7 94.81 105.11 +5.11/-5.19 ± 2.0
8 95.36 104.58 +4.58/-4.54 ± 2.0
9 95.81 104.14 +4.14/-4.19 ± 1.5
10 96.17 103.78 +3.78/-3.83 ± 1.5
D
#(Data + Parity Bit) Rslow [%] Rfast [%] Max Total Error [%]
Recommended Max
Receiver Error [%]
5 94.12 105.66 +5.66/-5.88 ± 2.5
6 94.92 104.92 +4.92/-5.08 ± 2.0
7 95.52 104.35 +4.35/-4.48 ± 1.5
Rslow
( ) D + 1 S
S – 1 D S⋅ SF + + = ------------------------------------------- R fast
( ) D + 2 S
( ) D + 1 S SM + = ------------------------------------
XMEGA B [MANUAL] 271
8291C–AVR–09/2014
The recommendations for the maximum receiver baud rate error assume that the receiver and transmitter equally divide
the maximum total error.
21.9 Fractional Baud Rate Generation
Fractional baud rate generation is possible for asynchronous operation due to the relatively high number of clock cycles
for each frame. Each bit is sampled sixteen times, but only the three middle samples are of importance. The total number
of samples for one frame is also relatively high. Given a 1-start, 8-data, no-parity, and 1-stop-bit frame format, and
assuming that normal speed mode is used, the total number of samples for a frame is (1+8+1)×16 or 160. As stated
earlier, the UART can tolerate some variation in clock cycles for each sample. The critical factor is the time from the
falling edge of the start bit (i.e., the clock synchronization) until the last bit's (i.e., the first stop bit’s) value is recovered.
Standard baud rate generators have the unwanted property of having large frequency steps between high baud rate
settings. The worst case is found between the BSEL values 0x000 and 0x001. Going from a BSEL value of 0x000, which
has a 10-bit frame of 160 clock cycles, to a BSEL value of 0x001, with 320 clock cycles, gives a 50% change in
frequency. Ideally, the step size should be small even between the fastest baud rates. This is where the advantage of the
fractional baud rate generator emerges.
In principle, the fractional baud rate generator works by doing uneven counting and then distributing the error evenly over
the entire frame. A typical count sequence for an ordinary baud rate generator is:
2, 1, 0, 2, 1, 0, 2, 1, 0, 2, …
which has an even period time. A baud rate clock ticks each time the counter reaches zero, and a sample of the signal
received on RxD is taken for every 16th baud rate clock tick.
For the fractional baud rate generator, the count sequence can have an uneven period:
2, 1, 0, 2, 1-1, 0, 2, 1, 0, 2, 1-1, 0,...
In this example, an extra cycle is added to every second baud clock. This gives a baud rate clock tick jitter, but the
average period has been increased by a fraction of 0.5 clock cycles.
Figure 21-9 on page 272 shows an example of how BSEL and BSCALE can be used to achieve baud rates in between
what is possible by just changing BSEL.
The impact of fractional baud rate generation is that the step size between baud rate settings has been reduced. Given a
scale factor of -1, the worst-case step then becomes from 160 to 240 clock cycles per 10-bit frame, compared to the
previous step of from 160 to 320. A higher negative scale factor gives even finer granularity. There is a limit, however, to
how high the scale factor can be. The value 2|BSCALE| must be at most half the minimum number of clock cycles of a
frame. For instance, for 10-bit frames, the minimum number of clock cycles is 160. This means that the highest
applicable scale factor is -6 (2I-6I = 64 < (160/2) = 80).
For higher BSEL settings, the scale factor can be increased.
Table 21-5 on page 272 shows BSEL and BSCALE settings when using the internal oscillators to generate the most
commonly used baud rates for asynchronous operation and how reducing the BSCALE can be used to reduce the baud
rate error even further.
8 96.00 103.90 +3.90/-4.00 ± 1.5
9 96.39 103.53 +3.53/-3.61 ± 1.5
10 96.70 103.23 +3.23/-3.30 ± 1.0
D
#(Data + Parity Bit) Rslow [%] Rfast [%] Max Total Error [%]
Recommended Max
Receiver Error [%]
XMEGA B [MANUAL] 272
8291C–AVR–09/2014
Figure 21-9. Fractional baud rate example.
Table 21-5. USART baud rate.
BSEL=0
BSCALE=0
fBAUD=fPER/8
clkBAUD8
clkBAUD8
BSEL=3
BSCALE=-6
fBAUD=fPER/8.375
clkBAUD8
BSEL=3
BSCALE=-4
fBAUD=fPER/9.5
Extra clock cycle added
Baud fOSC = 32.0000MHz
rate
(bps)
CLK2X = 0 CLK2X = 1
BSEL BSCALE Error [%] BSEL BSCALE Error [%]
2400 12 6 0.2 12 7 0.2
4800 12 5 0.2 12 6 0.2
9600 12 4 0.2 12 5 0.2
14.4k
34 2 0.8 34 3 0.8
138 0 -0.1 138 1 -0.1
19.2k 12 3 0.2 12 4 0.2
28.8k
34 1 -0.8 34 2 -0.8
137 -1 -0.1 138 0 -0.1
38.4k 12 2 0.2 12 3 0.2
57.6k
34 0 -0.8 34 1 -0.8
135 -2 -0.1 137 -1 -0.1
76.8k 12 1 0.2 12 2 0.2
115.2k
33 -1 -0.8 34 0 -0.8
131 -3 -0.1 135 -2 -0.1
230.4k
31 -2 -0.8 33 -1 -0.8
123 -4 -0.1 131 -3 -0.1
460.8k
27 -3 -0.8 31 -2 -0.8
107 -5 -0.1 123 -4 -0.1
XMEGA B [MANUAL] 273
8291C–AVR–09/2014
21.10 USART in Master SPI Mode
Using the USART in master SPI mode requires the transmitter to be enabled. The receiver can optionally be enabled to
serve as the serial input. The XCK pin will be used as the transfer clock.
As for the USART, a data transfer is initiated by writing to the DATA register. This is the case for both sending and
receiving data, since the transmitter controls the transfer clock. The data written to DATA are moved from the transmit
buffer to the shift register when the shift register is ready to send a new frame.
The transmitter and receiver interrupt flags and corresponding USART interrupts used in master SPI mode are identical
in function to their use in normal USART operation. The receiver error status flags are not in use and are always read as
zero.
Disabling of the USART transmitter or receiver in master SPI mode is identical to their disabling in normal USART
operation.
21.11 USART SPI vs. SPI
The USART in master SPI mode is fully compatible with the standalone SPI module in that:
z Timing diagrams are the same
z UCPHA bit functionality is identical to that of the SPI CPHA bit
z UDORD bit functionality is identical to that of the SPI DORD bit
When the USART is set in master SPI mode, configuration and use are in some cases different from those of the
standalone SPI module. In addition, the following differences exist:
921.6k
19 -4 -0.8 27 -3 -0.8
75 -6 -0.1 107 -5 -0.1
1.382M
7 -4 0.6 15 -3 0.6
57 -7 0.1 121 -6 0.1
1.843M
3 -5 -0.8 19 -4 -0.8
11 -7 -0.1 75 -6 -0.1
2.00M 0 0 0.0 1 0 0.0
2.304M – – –
3 -2 -0.8
47 -6 -0.1
2.5M – – –
19 -4 0.4
77 -7 -0.1
3.0M – – –
11 -5 -0.8
43 -7 -0.2
4.0M – – – 0 0 0.0
Max 2.0Mbps 4.0Mbps
Baud fOSC = 32.0000MHz
rate
(bps)
CLK2X = 0 CLK2X = 1
BSEL BSCALE Error [%] BSEL BSCALE Error [%]
XMEGA B [MANUAL] 274
8291C–AVR–09/2014
z The USART transmitter in master SPI mode includes buffering, but the SPI module has no transmit buffer
z The USART receiver in master SPI mode includes an additional buffer level
z The USART in master SPI mode does not include the SPI write collision feature
z The USART in master SPI mode does not include the SPI double speed mode feature, but this can be achieved by
configuring the baud rate generator accordingly
z Interrupt timing is not compatible
z Pin control differs due to the master-only operation of the USART in SPI master mode
A comparison of the USART in master SPI mode and the SPI pins is shown Table 21-6.
Table 21-6. Comparison of USART in master SPI mode and SPI pins.
21.12 Multiprocessor Communication Mode
The multiprocessor communication mode effectively reduces the number of incoming frames that have to be handled by
the receiver in a system with multiple microcontrollers communicating via the same serial bus. In this mode, a dedicated
bit in the frames is used to indicate whether the frame is an address or data frame type.
If the receiver is set up to receive frames that contain five to eight data bits, the first stop bit is used to indicate the frame
type. If the receiver is set up for frames with nine data bits, the ninth bit is used. When the frame type bit is one, the frame
contains an address. When the frame type bit is zero, the frame is a data frame. If 5-bit to 8-bit character frames are
used, the transmitter must be set to use two stop bits, since the first stop bit is used for indicating the frame type.
If a particular slave MCU has been addressed, it will receive the following data frames as usual, while the other slave
MCUs will ignore the frames until another address frame is received.
21.12.1 Using Multiprocessor Communication Mode
The following procedure should be used to exchange data in multiprocessor communication mode (MPCM):
1. All slave MCUs are in multiprocessor communication mode.
2. The master MCU sends an address frame, and all slaves receive and read this frame.
3. Each slave MCU determines if it has been selected.
4. The addressed MCU will disable MPCM and receive all data frames. The other slave MCUs will ignore the data
frames.
5. When the addressed MCU has received the last data frame, it must enable MPCM again and wait for a new
address frame from the master.
The process then repeats from step 2.
Using any of the 5-bit to 8-bit character frame formats is impractical, as the receiver must change between using n and
n+1 character frame formats. This makes full-duplex operation difficult, since the transmitter and receiver must use the
same character size setting.
USART SPI Comment
TxD MOSI Master out only
RxD MISO Master in only
XCK SCK Functionally identical
N/A SS Not supported by USART in master SPI mode
XMEGA B [MANUAL] 275
8291C–AVR–09/2014
21.13 IRCOM Mode of Operation
IRCOM mode can be enabled to use the IRCOM module with the USART. This enables IrDA 1.4 compliant modulation
and demodulation for baud rates up to 115.2kbps. When IRCOM mode is enabled, double speed mode cannot be used
for the USART.
For devices with more than one USART, IRCOM mode can be enabled for only one USART at a time. For details, refer to
“IRCOM - IR Communication Module” on page 282.
21.14 DMA Support
DMA support is available on UART, USRT, and master SPI mode peripherals. For details on different USART DMA
transfer triggers, refer to “Transfer Triggers” on page 49.
XMEGA B [MANUAL] 276
8291C–AVR–09/2014
21.15 Register Description
21.15.1 DATA – Data register
The USART transmit data buffer register (TXB) and USART receive data buffer register (RXB) share the same I/O
address and is referred to as USART data register (DATA). The TXB register is the destination for data written to the
DATA register location. Reading the DATA register location returns the contents of the RXB register.
For 5-bit, 6-bit, or 7-bit characters, the upper unused bits will be ignored by the transmitter and set to zero by the receiver.
The transmit buffer can be written only when DREIF in the STATUS register is set. Data written to the DATA register
when DREIF is not set will be ignored by the USART transmitter. When data are written to the transmit buffer and the
transmitter is enabled, the transmitter will load the data into the transmit shift register when the shift register is empty.
The data are then transmitted on the TxD pin.
The receive buffer consists of a two-level FIFO. Always read STATUS before DATA in order to get the correct status of
the receive buffer.
21.15.2 STATUS – Status register
z Bit 7 – RXCIF: Receive Complete Interrupt Flag
This flag is set when there are unread data in the receive buffer and cleared when the receive buffer is empty (i.e., does
not contain any unread data). When the receiver is disabled, the receive buffer will be flushed, and consequently RXCIF
will become zero.
When interrupt-driven data reception is used, the receive complete interrupt routine must read the received data from
DATA in order to clear RXCIF. If not, a new interrupt will occur directly after the return from the current interrupt. This flag
can also be cleared by writing a one to its bit location.
z Bit 6 – TXCIF: Transmit Complete Interrupt Flag
This flag is set when the entire frame in the transmit shift register has been shifted out and there are no new data in the
transmit buffer (DATA). TXCIF is automatically cleared when the transmit complete interrupt vector is executed. The flag
can also be cleared by writing a one to its bit location.
z Bit 5 – DREIF: Data Register Empty Flag
This flag indicates whether the transmit buffer (DATA) is ready to receive new data. The flag is one when the transmit
buffer is empty and zero when the transmit buffer contains data to be transmitted that has not yet been moved into the
shift register. DREIF is set after a reset to indicate that the transmitter is ready. Always write this bit to zero when writing
the STATUS register.
DREIF is cleared by writing DATA. When interrupt-driven data transmission is used, the data register empty interrupt
routine must either write new data to DATA in order to clear DREIF or disable the data register empty interrupt. If not, a
new interrupt will occur directly after the return from the current interrupt.
Bit 7 6 5 4 3 2 1 0
+0x00 RXB[[7:0]
TXB[[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 00000000
Bit 7 6 5 4 3 2 1 0
+0x01 RXCIF TXCIF DREIF FERR BUFOVF PERR – RXB8
Read/Write R R/W R R R R R R/W
Initial Value 0 0 1 0 0 0 0 0
XMEGA B [MANUAL] 277
8291C–AVR–09/2014
z Bit 4 – FERR: Frame Error
The FERR flag indicates the state of the first stop bit of the next readable frame stored in the receive buffer. The bit is set
if the received character had a frame error, i.e., the first stop bit was zero, and cleared when the stop bit of the received
data is one. This bit is valid until the receive buffer (DATA) is read. FERR is not affected by setting the number of stop
bits used, as it always uses only the first stop bit. Always write this bit location to zero when writing the STATUS register.
This flag is not used in master SPI mode operation.
z Bit 3 – BUFOVF: Buffer Overflow
This flag indicates data loss due to a receiver buffer full condition. This flag is set if a buffer overflow condition is
detected. A buffer overflow occurs when the receive buffer is full (two characters) with a new character waiting in the
receive shift register and a new start bit is detected. This flag is valid until the receive buffer (DATA) is read. Always write
this bit location to zero when writing the STATUS register.
This flag is not used in master SPI mode operation.
z Bit 2 – PERR: Parity Error
If parity checking is enabled and the next character in the receive buffer has a parity error, this flag is set. If parity check
is not enabled, this flag will always be read as zero. This bit is valid until the receive buffer (DATA) is read. Always write
this bit location to zero when writing the STATUS register. For details on parity calculation, refer to “Parity Bit Calculation”
on page 266.
This flag is not used in master SPI mode operation.
z Bit 1 – Reserved
This bit is unused and reserved for future use. For compatibility with future devices, always write this bit to zero when this
register is written.
z Bit 0 – RXB8: Receive Bit 8
RXB8 is the ninth data bit of the received character when operating with serial frames with nine data bits. When used,
this bit must be read before reading the low bits from DATA.
This bit is unused in master SPI mode operation.
21.15.3 CTRLA – Control register A
z Bit 7:6 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 5:4 – RXCINTLVL[1:0]: Receive Complete Interrupt Level
These bits enable the receive complete interrupt and select the interrupt level, as described in “Interrupts and
Programmable Multilevel Interrupt Controller” on page 115. The enabled interrupt will be triggered when the RXCIF flag
in the STATUS register is set.
z Bit 3:2 – TXCINTLVL[1:0]: Transmit Complete Interrupt Level
These bits enable the transmit complete interrupt and select the interrupt level, as described in “Interrupts and
Programmable Multilevel Interrupt Controller” on page 115. The enabled interrupt will be triggered when the TXCIF flag
in the STATUS register is set.
z Bit 1:0 – DREINTLVL[1:0]: Data Register Empty Interrupt Level
These bits enable the data register empty interrupt and select the interrupt level, as described in “Interrupts and
Programmable Multilevel Interrupt Controller” on page 115. The enabled interrupt will be triggered when the DREIF flag
in the STATUS register is set.
Bit 7 6 5 4 3 2 1 0
+0x03 – – RXCINTLVL[1:0] TXCINTLVL[1:0] DREINTLVL[1:0]
Read/Write R R R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 00000
XMEGA B [MANUAL] 278
8291C–AVR–09/2014
21.15.4 CTRLB – Control register B
z Bit 7:5 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 4 – RXEN: Receiver Enable
Setting this bit enables the USART receiver. The receiver will override normal port operation for the RxD pin, when
enabled. Disabling the receiver will flush the receive buffer, invalidating the FERR, BUFOVF, and PERR flags.
z Bit 3 – TXEN: Transmitter Enable
Setting this bit enables the USART transmitter. The transmitter will override normal port operation for the TxD pin, when
enabled. Disabling the transmitter (writing TXEN to zero) will not become effective until ongoing and pending
transmissions are completed; i.e., when the transmit shift register and transmit buffer register do not contain data to be
transmitted. When disabled, the transmitter will no longer override the TxD port.
z Bit 2 – CLK2X: Double Transmission Speed
Setting this bit will reduce the divisor of the baud rate divider from16 to 8, effectively doubling the transfer rate for
asynchronous communication modes. For synchronous operation, this bit has no effect and should always be written to
zero. This bit must be zero when the USART communication mode is configured to IRCOM.
This bit is unused in master SPI mode operation.
z Bit 1 – MPCM: Multiprocessor Communication Mode
This bit enables the multiprocessor communication mode. When the MPCM bit is written to one, the USART receiver
ignores all the incoming frames that do not contain address information. The transmitter is unaffected by the MPCM
setting. For more detailed information, see “Multiprocessor Communication Mode” on page 274.
This bit is unused in master SPI mode operation.
z Bit 0 – TXB8: Transmit Bit 8
TXB8 is the ninth data bit in the character to be transmitted when operating with serial frames with nine data bits. When
used, this bit must be written before writing the low bits to DATA.
This bit is unused in master SPI mode operation.
21.15.5 CTRLC – Control register C
Note: 1. Master SPI mode.
z Bits 7:6 – CMODE[1:0]: Communication Mode
These bits select the mode of operation of the USART as shown in Table 21-7.
Bit 7 6 5 4 3 2 1 0
+0x04 – – – RXEN TXEN CLK2X MPCM TXB8
Read/Write R R R R/W R/W R/W R/W R/W
Initial Value 0 0 0 00000
Bit 7 6 5 4 3 2 1 0
+0x05 CMODE[1:0] PMODE[1:0] SBMODE CHSIZE[2:0]
+0x05(1) CMODE[1:0] – – – UDORD UCPHA –
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0000110
XMEGA B [MANUAL] 279
8291C–AVR–09/2014
Table 21-7. CMODE bit settings.
Notes: 1. See “IRCOM - IR Communication Module” on page 282 for full description on using IRCOM mode.
2. See “USART in Master SPI Mode” on page 273 for full description of the master SPI operation.
z Bits 5:4 – PMODE[1:0]: Parity Mode
These bits enable and set the type of parity generation according to Table 21-8. When enabled, the transmitter will
automatically generate and send the parity of the transmitted data bits within each frame. The receiver will generate a
parity value for the incoming data and compare it to the PMODE setting, and if a mismatch is detected, the PERR flag in
STATUS will be set.
These bits are unused in master SPI mode operation.
Table 21-8. PMODE bit settings.
z Bit 3 – SBMODE: Stop Bit Mode
This bit selects the number of stop bits to be inserted by the transmitter according to Table 21-9. The receiver ignores
this setting.
This bit is unused in master SPI mode operation.
Table 21-9. SBODE bit settings.
z Bit 2:0 – CHSIZE[2:0]: Character Size
The CHSIZE[2:0] bits set the number of data bits in a frame according to Table 21-10 on page 280. The receiver and
transmitter use the same setting.
CMODE[1:0] Group Configuration Mode
00 ASYNCHRONOUS Asynchronous USART
01 SYNCHRONOUS Synchronous USART
10 IRCOM IRCOM(1)
11 MSPI Master SPI(2)
PMODE[1:0] Group Configuration Parity Mode
00 DISABLED Disabled
01 Reserved
10 EVEN Enabled, even parity
11 ODD Enabled, odd parity
SBMODE Stop Bit(s)
0 1
1 2
XMEGA B [MANUAL] 280
8291C–AVR–09/2014
Table 21-10. CHSIZE bit settings.
z Bit 2 – UDORD: Data Order
This bit is only for master SPI mode, and this bit sets the frame format. When written to one, the lsb of the data word is
transmitted first. When written to zero, the msb of the data word is transmitted first. The receiver and transmitter use the
same setting. Changing the setting of UDORD will corrupt all ongoing communication for both receiver and transmitter.
z Bit 1 – UCPHA: Clock Phase
This bit is only for master SPI mode, and the bit determine whether data are sampled on the leading (first) edge or tailing
(last) edge of XCKn. Refer to the “Master SPI Mode Clock Generation” on page 265 for details.
21.15.6 BAUDCTRLA – Baud Rate register A
z Bit 7:0 – BSEL[7:0]: Baud Rate bits
These are the lower 8 bits of the 12-bit BSEL value used for USART baud rate setting. BAUDCTRLB contains the four
most-significant bits. Ongoing transmissions by the transmitter and receiver will be corrupted if the baud rate is changed.
Writing BSEL will trigger an immediate update of the baud rate prescaler. See the equations in Table 21-1 on page 263.
21.15.7 BAUDCTRLB – Baud Rate register B
z Bit 7:4 – BSCALE[3:0]: Baud Rate Scale factor
These bits select the baud rate generator scale factor. The scale factor is given in two's complement form from -7
(0b1001) to +7 (0b0111). The -8 (0b1000) setting is reserved. See the equations in Table 21-1 on page 263.
z Bit 3:0 – BSEL[11:8]: Baud Rate bits
These are the upper 4 bits of the 12-bit value used for USART baud rate setting. BAUDCTRLA contains the eight leastsignificant
bits. Ongoing transmissions by the transmitter and receiver will be corrupted if the baud rate is changed.
Writing BAUDCTRLA will trigger an immediate update of the baud rate prescaler.
CHSIZE[2:0] Group Configuration Character Size
000 5BIT 5-bit
001 6BIT 6-bit
010 7BIT 7-bit
011 8BIT 8-bit
100 Reserved
101 Reserved
110 Reserved
111 9BIT 9-bit
Bit 7 6 5 4 3 2 1 0
+0x06 BSEL[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
+0x07 BSCALE[3:0] BSEL[11:8]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 281
8291C–AVR–09/2014
21.16 Register Summary
21.16.1 Register Description - USART
21.16.2 Register Description - USART in SPI Master Mode
21.17 Interrupt Vector Summary
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
+0x00 DATA DATA[7:0] 276
+0x01 STATUS RXCIF TXCIF DREIF FERR BUFOVF PERR – RXB8 276
+0x02 Reserved – – – – – – – –
+0x03 CTRLA – – RXCINTLVL[1:0] TXCINTLVL[1:0] DREINTLVL[1:0] 277
+0x04 CTRLB – – – RXEN TXEN CLK2X MPCM TXB8 278
+0x05 CTRLC CMODE[1:0] PMODE[1:0] SBMODE CHSIZE[2:0] 278
+0x06 BAUDCTRL BSEL[7:0] 280
+0x07 BAUDCTRL BSCALE[3:0] BSEL[11:8] 280
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
+0x00 DATA DATA[7:0] 276
+0x01 STATUS RXCIF TXCIF DREIF – – – – – 276
+0x02 Reserved – – – – – – – –
+0x03 CTRLA – – RXCINTLVL[1:0] TXCINTLVL[1:0] DREINTLVL[1:0] 277
+0x04 CTRLB – – – RXEN TXEN – – – 278
+0x05 CTRLC CMODE[1:0] – – – UDORD UCPHA – 278
+0x06 BAUDCTRL BSEL[7:0] 280
+0x07 BAUDCTRL BSCALE[3:0] BSEL[11:8] 280
Offset Source Interrupt Description
0x00 RXC_vect USART receive complete interrupt vector
0x02 DRE_vect USART data register empty interrupt vector
0x04 TXC_vect USART transmit complete interrupt vector
XMEGA B [MANUAL] 282
8291C–AVR–09/2014
22. IRCOM - IR Communication Module
22.1 Features
z Pulse modulation/demodulation for infrared communication
z IrDA compatible for baud rates up to 115.2kbps
z Selectable pulse modulation scheme
z 3/16 of the baud rate period
z Fixed pulse period, 8-bit programmable
z Pulse modulation disabled
z Built-in filtering
z Can be connected to and used by any USART
22.2 Overview
XMEGA devices contain an infrared communication module (IRCOM) that is IrDA compatible for baud rates up to
115.2kbps. It can be connected to any USART to enable infrared pulse encoding/decoding for that USART.
Figure 22-1. IRCOM connection to USARTs and associated port pins.
The IRCOM is automatically enabled when a USART is set in IRCOM mode. The signals between the USART and the
RX/TX pins are then routed through the module as shown in Figure 22-1 on page 282. The data on the TX/RX pins are
the inverted value of the transmitted/received infrared pulse. It is also possible to select an event channel from the event
system as input for the IRCOM receiver. This will disable the RX input from the USART pin.
For transmission, three pulse modulation schemes are available:
z 3/16 of the baud rate period
z Fixed programmable pulse time based on the peripheral clock frequency
z Pulse modulation disabled
IRCOM
Pulse
Decoding
DIF
Event System
RXDxn
TXDxn
USARTxn
....
USARTD0
USARTC0
RXDD0
TXDD0
RXDC0
TXDC0
Pulse
Encoding
decoded RXD
encoded TXD
encoded RXD
RXD...
TXD...
decoded TXD
events
XMEGA B [MANUAL] 283
8291C–AVR–09/2014
For reception, a fixed programmable minimum high-level pulse width for the pulse to be decoded as a logical 0 is used.
Shorter pulses will then be discarded, and the bit will be decoded to logical 1 as if no pulse was received.
The module can only be used in combination with one USART at a time. Thus, IRCOM mode must not be set for more
than one USART at a time. This must be ensured in the user software.
22.2.1 Event System Filtering
The event system can be used as the receiver input. This enables IRCOM or USART input from I/O pins or sources other
than the corresponding RX pin. If event system input is enabled, input from the USART's RX pin is automatically
disabled. The event system has a digital input filter (DIF) on the event channels that can be used for filtering. Refer to
“Event System” on page 63” for details on using the event system.
XMEGA B [MANUAL] 284
8291C–AVR–09/2014
22.3 Registers Description
22.3.1 TXPLCTRL – Transmitter Pulse Length Control Register
z Bit 7:0 – TXPLCTRL[7:0]: Transmitter Pulse Length Control
This 8-bit value sets the pulse modulation scheme for the transmitter. Setting this register will have no effect if IRCOM
mode is not selected by a USART.
By leaving this register value to zero, 3/16 of the baud rate period pulse modulation is used.
Setting this value from 1 to 254 will give a fixed pulse length coding. The 8-bit value sets the number of system clock
periods for the pulse. The start of the pulse will be synchronized with the rising edge of the baud rate clock.
Setting the value to 255 (0xFF) will disable pulse coding, letting the RX and TX signals pass through the IRCOM module
unaltered. This enables other features through the IRCOM module, such as half-duplex USART, loop-back testing, and
USART RX input from an event channel.
TXPCTRL must be configured before the USART transmitter is enabled (TXEN).
22.3.2 RXPLCTRL – Receiver Pulse Length Control Register
z Bit 7:0 – RXPLCTRL[7:0]: Receiver Pulse Length Control
This 8-bit value sets the filter coefficient for the IRCOM transceiver. Setting this register will have no effect if IRCOM
mode is not selected by a USART.
By leaving this register value at zero, filtering is disabled. Setting this value between 1 and 255 will enable filtering, where
x+1 equal samples are required for the pulse to be accepted.
RXPCTRL must be configured before the USART receiver is enabled (RXEN).
22.3.3 CTRL – Control Register
z Bit 7:4 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 3:0 – EVSEL [3:0]: Event Channel Selection
These bits select the event channel source for the IRCOM receiver according to Table 22-1. If event input is selected for
the IRCOM receiver, the input from the USART’s RX pin is automatically disabled.
Bit 7 6 5 4 3 2 1 0
+0x01 TXPLCTRL[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
+0x02 RXPLCTRL[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
+0x00 – – – – EVSEL[3:0]
Read/Write R R R R R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 285
8291C–AVR–09/2014
Table 22-1. Event channel selection.
22.4 Register Summary
EVSEL[3:0] Group Configuration Event Source
0000 – None
0001 – (Reserved)
0010 – (Reserved)
0011 – (Reserved)
0100 – (Reserved)
0101 – (Reserved)
0110 – (Reserved)
0111 – (Reserved)
1nnn CHn Event system channel n; n = {0, …,7}
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
+0x00 CTRL – – – – EVSEL[3:0] 284
+0x01 TXPLCTRL TXPLCTRL[7:0] 284
+0x02 RXPLCTRL RXPLCTRL[7:0] 284
XMEGA B [MANUAL] 286
8291C–AVR–09/2014
23. AES and DES Crypto Engines
23.1 Features
z Data Encryption Standard (DES) CPU instruction
z Advanced Encryption Standard (AES) crypto module
z DES Instruction
z Encryption and decryption
z DES supported
z Encryption/decryption in 16 CPU clock cycles per 8-byte block
z AES crypto module
z Encryption and decryption
z Supports 128-bit keys
z Supports XOR data load mode to the state memory
z Encryption/decryption in 375 clock cycles per 16-byte block
23.2 Overview
The Advanced Encryption Standard (AES) and Data Encryption Standard (DES) are two commonly used standards for
cryptography. These are supported through an AES peripheral module and a DES CPU instruction, and the
communication interfaces and the CPU can use these for fast, encrypted communication and secure data storage.
DES is supported by an instruction in the AVR CPU. The 8-byte key and 8-byte data blocks must be loaded into the
register file, and then the DES instruction must be executed 16 times to encrypt/decrypt the data block.
The AES crypto module encrypts and decrypts 128-bit data blocks with the use of a 128-bit key. The key and data must
be loaded into the key and state memory in the module before encryption/decryption is started. It takes 375 peripheral
clock cycles before the encryption/decryption is done. The encrypted/encrypted data can then be read out, and an
optional interrupt can be generated. The AES crypto module also has DMA support with transfer triggers when
encryption/decryption is done and optional auto-start of encryption/decryption when the state memory is fully loaded.
23.3 DES Instruction
The DES instruction is a single cycle instruction. In order to decrypt or encrypt a 64-bit (8-byte) data block, the instruction
has to be executed 16 times.
The data and key blocks must be loaded into the register file before encryption/decryption is started. The 64-bit data
block (plaintext or ciphertext) is placed in registers R0-R7, where the LSB of data is placed in R0 and the MSB of data is
placed in R7. The full 64-bit key (including parity bits) is placed in registers R8-R15, with the LSB of the key in R8 and the
MSB of the key in R15.
XMEGA B [MANUAL] 287
8291C–AVR–09/2014
Figure 23-1. Register file usage during DES encryption/decryption.
Executing one DES instruction performs one round in the DES algorithm. Sixteen rounds must be executed in increasing
order to form the correct DES ciphertext or plaintext. Intermediate results are stored in the register file (R0-R15) after
each DES instruction. After sixteen rounds, the key is located in R8-R16 and the encrypted/decrypted ciphertext/plaintext
is located in R0-R7. The instruction's operand (K) determines which round is executed, and the half carry flag (H) in the
CPU status register determines whether encryption or decryption is performed. If the half carry flag is set, decryption is
performed, and if the flag is cleared, encryption is performed.
For more details on the DES instruction, refer to the AVR instruction set manual.
23.4 AES Crypto Module
The AES crypto module performs encryption and decryption according to the Advanced Encryption Standard (FIPS-197).
The 128-bit key block and 128-bit data block (plaintext or ciphertext) must be loaded into the key and state memories in
the AES crypto module. This is done by writing the AES KEY register and STATE register sequentially with 16 bytes.
It is software selectable whether the module should perform encryption or decryption. It is also possible to enable XOR
mode, where all new data loaded to the state key is XORed with the current data in the state memory.
The AES module uses 375 clock cycles before the encrypted/decrypted plaintext/ciphertext is available for readout in the
state memory.
The following setup and use procedure is recommended:
1. Enable the AES interrupt (optional).
2. Select the AES direction to encryption or decryption.
3. Load the key data block into the AES key memory.
4. Load the data block into the AES state memory.
5. Start the encryption/decryption operation.
If more than one block is to be encrypted or decrypted, repeat the procedure from step 3.
When the encryption/decryption procedure is complete, the AES interrupt flag is set and an optional interrupt is
generated.
Register File
R0
R1
R2
R3
R4
R5
R6
R7
R8
R9
R10
R11
R12
R13
R14
R15
R16
...
R31
data0
data1
data2
data3
data4
data5
data6
data7
key0
key1
key2
key3
key4
key5
key6
key7
data key
XMEGA B [MANUAL] 288
8291C–AVR–09/2014
23.4.1 Key and State Memory
The AES key and state memory are both 16 x 8-bit memories that are accessible through the KEY and STATE registers,
respectively.
Each memory has two 4-bit address pointers used to address the memory for read and write, respectively. The initial
value of the pointers is zero. After a read or write operation to the STATE or KEY register, the appropriate pointer is
automatically incremented. Accessing (read or write) the control register (CTRL) will reset all pointers to zero. A pointer
overflow (a sequential read or write done more than 16 times) will also set the affected pointer to zero. The pointers are
not accessible from software. Read and write memory pointers are both incremented during write operations in XOR
mode.
Access to the KEY and STATE registers is possible only when encryption/decryption is not in progress.
Figure 23-2. The state memory with pointers and register.
The state memory contains the AES state throughout the encryption/decryption process. The initial value of the state is
the initial data (i.e., plaintext in the encryption mode, and ciphertext in the decryption mode). The last value of the state is
the encrypted/decrypted data.
Figure 23-3. The key memory with pointers and register.
In the AES crypto module, the following definition of the key is used:
z In encryption mode, the key is the one defined in the AES standard.
4-bit state write
address pointer
1
-
14
15
STATE
0 4-bit state read
address pointer
Reset pointer
Reset pointer
reset or access
to AES Control
reset or access
to AES Control
STATE[read pointer]
xor
XOR
I/O Data Bus
4-bit key write
address pointer
1
-
14
15
KEY
0 4-bit key read
address pointer
Reset pointer
Reset pointer
reset or
access to CTRL
reset or
access to CTRL
XMEGA B [MANUAL] 289
8291C–AVR–09/2014
z In decryption mode, the key is the last subkey of the expanded key defined in the AES standard.
In decryption mode, the key expansion procedure must be executed by software before operation with the AES crypto
module so that the last subkey is ready to be loaded through the KEY register. Alternatively, this procedure can be run in
hardware by using the AES crypto module to process a dummy data block in encryption mode using the same key. After
the end of the encryption, reading from the key memory allows the last subkey to be obtained; i.e., get the result of the
key expansion procedure. Table 23-1 shows the results of reading the key, depending on the mode (encryption or
decryption) and status of the AES crypto module.
Table 23-1. The result of reading the key memory at different stages.
23.4.2 DMA Support
The AES module can trigger a DMA transfer when the encryption/decryption procedure is complete. For more details on
DMA transfer triggers, refer to “Transfer Triggers” on page 49.
Encryption Decryption
Before data processing After data processing Before data processing After Data Processing
Same key as loaded The last subkey generated from the
loaded key Same key as loaded The initial key generated from the
last loaded subkey
XMEGA B [MANUAL] 290
8291C–AVR–09/2014
23.5 Register Description – AES
23.5.1 CTRL – Control register
z Bit 7 – START: Start/Run
Setting this bit starts the encryption/decryption procedure, and this bit remains set while the encryption/decryption is
ongoing. Writing this bit to zero will stop/abort any ongoing encryption/decryption process. This bit is automatically
cleared if the SRIF or the ERROR flags in STATUS are set.
z Bit 6 – AUTO: Auto Start Trigger
Setting this bit enables the auto-start mode. In auto-start mode, the START bit will trigger automatically and start the
encryption/decryption when all of the following conditions are met:
z The AUTO bit is set before the state memory is loaded
z All memory pointers (state read/write and key read/write) are zero
z State memory is fully loaded
If all of these conditions are not met, the encryption/decryption will be started with an incorrect key.
z Bit 5 – RESET: Software Reset
Setting this bit will reset the AES crypto module to its initial status on the next positive edge of the peripheral clock. All
registers, pointers, and memories in the module are set to their initial value. When written to one, the bit stays high for
one clock cycle before it is reset to zero by hardware.
z Bit 4 – DECRYPT: Decryption / Direction
This bit sets the direction for the AES crypto module. Writing this bit to zero will set the module in encryption mode.
Writing one to this bit sets the module in decryption mode.
z Bit 3 – Reserved
This bit is unused and reserved for future use. For compatibility with future devices, always write this bit to zero when this
register is written.
z Bit 2 – XOR: State XOR Load Enable
Setting this bit enables a XOR data load to the state memory. When this bit is set, the data loaded to the state memory
are bitwise XORed with the data currently in the state memory. Writing this bit to zero disables XOR load mode, and new
data written to the state memory will overwrite the current data.
z Bit 1:0 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
Bit 7 6 5 4 3 2 1 0
+0x00 START AUTO RESET DECRYPT – XOR – –
Read/Write R/W R/W R/W R/W R R/W R R
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 291
8291C–AVR–09/2014
23.5.2 STATUS – AES Status register
z Bit 7 – ERROR: Error
The ERROR flag indicates an illegal handling of the AES crypto module. The flag is set in the following cases:
z Setting START in the control register while the state memory and/or key memory are not fully loaded or read. This
error occurs when the total number of read/write operations from/to the STATE and KEY registers is not a multiple
of 16 before an AES start.
z Accessing (read or write) the control register while the START bit is one.
This flag can be cleared by software by writing one to its bit location.
z Bit 6:1 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 0 – SRIF: State Ready Interrupt flag
This flag is the interrupt/DMA request flag, and is set when the encryption/decryption procedure is completed and the
state memory contains valid data. As long as the flag is zero, this indicates that there is no valid encrypted/decrypted
data in the state memory.
The flag is cleared by hardware when a read access is made to the state memory (the first byte is read). Alternatively, the
bit can be cleared by writing a one to its bit location.
23.5.3 STATE – AES State register
The STATE register is used to access the state memory. Before encryption/decryption can take place, the state memory
must be written sequentially, byte-by-byte, through the STATE register. After encryption/decryption is done, the
ciphertext/plaintext can be read sequentially, byte-by-byte, through the STATE register.
Loading the initial data to the STATE register should be done after setting the appropriate AES mode and direction. This
register can not be accessed during encryption/decryption.
23.5.4 KEY – Key register
The KEY register is used to access the key memory. Before encryption/decryption can take place, the key memory must
be written sequentially, byte-by-byte, through the KEY register. After encryption/decryption is done, the last subkey can
be read sequentially, byte-by-byte, through the KEY register.
Loading the initial data to the KEY register should be done after setting the appropriate AES mode and direction.
Bit 7 6 5 4 3 2 1 0
+0x01 ERROR – – – – – – SRIF
Read/Write R/W R R R R R R R/W
Initial Value 00000000
Bit 7 6 5 4 3 2 1 0
+0x02 STATE[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0000
Bit 7 6 5 4 3 2 1 0
+0x03 KEY[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 292
8291C–AVR–09/2014
23.5.5 INTCTRL – Interrupt Control register
z Bit 7:2 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 1:0 – INTLVL[1:0]: Interrupt priority and enable
These bits enable the AES interrupt and select the interrupt level, as described in “Interrupts and Programmable
Multilevel Interrupt Controller” on page 115. The enabled interrupt will be triggered when the SRIF in the STATUS
register is set.
23.6 Register summary – AES
23.7 Interrupt vector summary
Table 23-2. AES interrupt vector and its offset word address.
Bit 7 6 5 4 3 2 1 0
+0x04 – – – – – – INTLVL[1:0]
Read/Write R R R R R R R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 bit 0 Page
+0x00 CTRL START AUTO RESET DECRYPT – XOR – – 290
+0x01 STATUS ERROR – – – – – – SRIF 291
+0x02 STATE STATE[7:0] 291
+0x03 KEY KEY[7:0] 291
+0x04 INTCTRL – – – – – – INTLVL[1:0] 292
+0x05 Reserved – – – – – – – –
+0x06 Reserved – – – – – – – –
+0x07 Reserved – – – – – – – –
Offset Source Interrupt Description
0x00 AES_vect AES interrupt vector
XMEGA B [MANUAL] 293
8291C–AVR–09/2014
24. CRC – Cyclic Redundancy Check Generator
24.1 Features
z Cyclic redundancy check (CRC) generation and checking for
z Communication data
z Program or data in flash memory
z Data in SRAM and I/O memory space
z Integrated with flash memory, DMA controller and CPU
z Continuous CRC on data going through a DMA channel
z Automatic CRC of the complete or a selectable range of the flash memory
z CPU can load data to the CRC generator through the I/O interface
z CRC polynomial software selectable to
z CRC-16 (CRC-CCITT)
z CRC-32 (IEEE 802.3)
z Zero remainder detection
24.2 Overview
A cyclic redundancy check (CRC) is an error detection technique test algorithm used to find accidental errors in data, and
it is commonly used to determine the correctness of a data transmission, and data present in the data and program
memories. A CRC takes a data stream or a block of data as input and generates a 16- or 32-bit output that can be
appended to the data and used as a checksum. When the same data are later received or read, the device or application
repeats the calculation. If the new CRC result does not match the one calculated earlier, the block contains a data error.
The application will then detect this and may take a corrective action, such as requesting the data to be sent again or
simply not using the incorrect data.
Typically, an n-bit CRC applied to a data block of arbitrary length will detect any single error burst not longer than n bits
(any single alteration that spans no more than n bits of the data), and will detect the fraction 1-2-n of all longer error
bursts. The CRC module in XMEGA devices supports two commonly used CRC polynomials; CRC-16 (CRC-CCITT) and
CRC-32 (IEEE 802.3).
z CRC-16:
z CRC-32:
Polynomial: x16+x12+x5
+1
Hex value: 0x1021
Polynomial: x32+x26+x23+x22+x16+x12+x11+x10+x8
+x7
+x5
+x4
+x2
+x+1
Hex value: 0x04C11DB7
XMEGA B [MANUAL] 294
8291C–AVR–09/2014
24.3 Operation
The data source for the CRC module must be selected in software as either flash memory, the DMA channels, or the I/O
interface. The CRC module then takes data input from the selected source and generates a checksum based on these
data. The checksum is available in the CHECKSUM registers in the CRC module. When CRC-32 polynomial is used, the
final checksum read is bit reversed and complemented (see Figure 24-1).
For the I/O interface or DMA controller, which CRC polynomial is used is software selectable, but the default setting is
CRC-16. CRC-32 is automatically used if Flash Memory is selected as the source. The CRC module operates on bytes
only.
Figure 24-1. CRC generator block diagram.
24.4 CRC on Flash memory
A CRC-32 calculation can be performed on the entire flash memory, on only the application section, on only the boot
section, or on a software selectable range of the flash memory. Other than selecting the flash as the source, all further
control and setup are done from the NVM controller. This means that the NVM controller configures the memory range to
perform the CRC on, and the CRC is started using NVM commands. Once completed, the result is available in the
checksum registers in the CRC module. For further details on setting up and performing CRC on flash memory, refer to
“Memory Programming” on page 375.
24.5 CRC on DMA Data
CRC-16 or CRC-32 calculations can be performed on data passing through any DMA channel. Once a DMA channel is
selected as the source, the CRC module will continuously generate the CRC on the data passing through the DMA
channel. The checksum is available for readout once the DMA transaction is completed or aborted. A CRC can be
DATAIN
CTRL
Flash
Memory
DMA
Controller
CRC-16 CRC-32
CHECKSUM
bit-reverse +
complement
8 16 8 32
Checksum read
crc32
XMEGA B [MANUAL] 295
8291C–AVR–09/2014
performed not only on communication data, but also on data in SRAM or I/O memory by passing these data through a
DMA channel. If the latter is done, the destination register for the DMA data can be the data input (DATAIN) register in
the CRC module.
24.6 CRC using the I/O Interface
CRC can be performed on any data by loading them into the CRC module using the CPU and writing the data to the
DATAIN register. Using this method, an arbitrary number of bytes can be written to the register by the CPU, and CRC is
done continuously for each byte. New data can be written for each cycle. The CRC complete is signaled by writing the
BUSY bit in the STATUS register.
XMEGA B [MANUAL] 296
8291C–AVR–09/2014
24.7 Register Description
24.7.1 CTRL – Control register
z Bit 7:6 – RESET[1:0]: Reset
These bits are used to reset the CRC module, and they will always be read as zero. The CRC registers will be reset one
peripheral clock cycle after the RESET[1] bit is set
Table 24-1. CRC reset.
z Bit 5 – CRC32: CRC-32 Enable
Setting this bit will enable CRC-32 instead of the default CRC-16. It cannot be changed while the BUSY flag is set.
z Bit 4 – Reserved
This bit is unused and reserved for future use. For compatibility with future devices, always write this bit to zero when this
register is written.
z Bit 3:0 – SOURCE[3:0]: Input Source
These bits select the input source for generating the CRC. The selected source is locked until either the CRC generation
is completed or the CRC module is reset. CRC generation complete is generated and signaled from the selected source
when used with the DMA controller or flash memory.
Table 24-2. CRC source select.
Bit 7 6 5 4 3 2 1 0
+0x00 RESET[1:0] CRC32 – SOURCE[3:0]
Read/Write R/W R/W R/W R R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
RESET[1:0] Group configuration Description
00 NO No reset
01 – Reserved
10 RESET0 Reset CRC with CHECKSUM to all zeros
11 RESET1 Reset CRC with CHECKSUM to all ones
SOURCE[3:0] Group configuration Description
0000 DISABLE CRC disabled
0001 IO I/O interface
0010 FLASH Flash
0011 – Reserved for future use
0100 DMACH0 DMA controller channel 0
0101 DMACH1 DMA controller channel 1
0110 DMACH2 DMA controller channel 2
0111 DMACH3 DMA controller channel 3
1xxx – Reserved for future use
XMEGA B [MANUAL] 297
8291C–AVR–09/2014
24.7.2 STATUS – Status register
z Bit 7:2 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 1 – ZERO: Checksum Zero
This flag is set if the CHECKSUM is zero when the CRC generation is complete. It is automatically cleared when a new
CRC source is selected.
When running CRC-32 and appending the checksum at the end of the packet (as little endian), the final checksum should
be 0x2144df1c, and not zero. However, if the checksum is complemented before it is appended (as little endian) to the
data, the final result in the checksum register will be zero.
See the description of CHECKSUM to read out different versions of the CHECKSUM.
z Bit 0 – BUSY: Busy
This flag is read as one when a source configuration is selected and as long as the source is using the CRC module. If
the I/O interface is selected as the source, the flag can be cleared by writing a one this location. If a DMA channel if
selected as the source, the flag is cleared when the DMA channel transaction is completed or aborted. If flash memory is
selected as the source, the flag is cleared when the CRC generation is completed.
24.7.3 DATAIN – Data Input register
z Bit 7:0 – DATAIN[7:0]: Data Input
This register is used to store the data for which the CRC checksum is computed. A new CHECKSUM is ready one clock
cycle after the DATAIN register is written.
24.7.4 CHECKSUM0 – Checksum register 0
CHECKSUM0, CHECKSUM1, CHECKSUM2, and CHECKSUM3 represent the 16- or 32-bit CHECKSUM value and the
generated CRC. The registers are reset to zero by default, but it is possible to write RESET to reset all bits to one. It is
possible to write these registers only when the CRC module is disabled. If NVM is selected as the source, reading
CHECKSUM will return a zero value until the BUSY flag is cleared. If CRC-32 is selected and the BUSY flag is cleared
(i.e., CRC generation is completed or aborted), the bit reversed (bit 31 is swapped with bit 0, bit 30 with bit 1, etc.) and
complemented result will be read from CHECKSUM. If CRC-16 is selected or the BUSY flag is set (i.e., CRC generation
is ongoing), CHECKSUM will contain the actual content.
z Bit 7:0 – CHECKSUM[7:0]: Checksum byte 0
These bits hold byte 0 of the generated CRC.
Bit 7 6 5 4 3 2 1 0
+0x02 – – – – – – ZERO BUSY
Read/Write R R R R R R R R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
+0x03 DATAIN[7:0]
Read/Write WWWWWWWW
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
+0x04 CHECKSUM[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 298
8291C–AVR–09/2014
24.7.5 CHECKSUM1 – Checksum register 1
z Bit 7:0 – CHECKSUM[15:8]: Checksum byte 1
These bits hold byte 1 of the generated CRC.
24.7.6 CHECKSUM2 – Checksum register 2
z Bit 7:0 – CHECKSUM[23:16]: Checksum byte 2
These bits hold byte 2 of the generated CRC when CRC-32 is used.
24.7.7 CHECKSUM3 – CRC Checksum register 3
z Bit 7:0 – CHECKSUM[31:24]: Checksum byte 3
These bits hold byte 3 of the generated CRC when CRC-32 is used.
24.8 Register Summary
Bit 7 6 5 4 3 2 1 0
+0x05 CHECKSUM[15:8]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
+0x06 CHECKSUM[23:16]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
+0x07 CHECKSUM[31:24]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
+0x00 CTRL RESET[1:0] CRC32 – SOURCE[3:0] 296
+0x01 STATUS – – – – – – ZERO BUSY 297
+0x02 Reserved – – – – – – – –
+0x03 DATAIN DATAIN[7:0] 297
+0x04 CHECKSU CHECKSUM[7:0] 298
+0x05 CHECKSU CHECKSUM[15:8] 298
+0x06 CHECKSU CHECKSUM[23:16] 298
+0x07 CHECKSU CHECKSUM[31:24] 298
XMEGA B [MANUAL] 299
8291C–AVR–09/2014
25. LCD – Liquid Crystal Display
25.1 Features
z Display Capacity up to 40 Segment and up to 4 Common Terminals
z Supports up to 16 GPIO's
z Shadow Display Memory Gives Full Freedom in Segment Update
z ASCII Character Mapping
z Swap Capability Option on Common and/or Segment Terminal Buses
z Supports from Static up to 1/4 Duty
z Supports Static and 1/3 Bias
z LCD Driver Active in Power Save Mode for Low Power Operation
z Software Selectable Low Power Waveform
z Flexible Selection of Frame Frequency
z Programmable Blink Mode and Frequency
z Blink on two Segment Terminals
z Uses Only 32kHz RTC Clock Source
z On-chip LCD Power Supply
z Software Contrast Adjustment Control
z Equal Source and Sink Capability to Increase LCD Life Time
z Extended Interrupt Mode for Display Update or Wake-up from Sleep Mode
25.2 Overview
An LCD display is made of several segments (pixels or complete symbols) which can be visible or invisible. A segment
has two electrodes with liquid crystal between them. These electrodes are the common terminal (COM pin) and the
segment terminal (SEG pin). When a voltage above a threshold voltage is applied across the liquid crystal, the segment
becomes visible. The voltage must alternate to avoid an electrophoresis effect in the liquid crystal, this effect degrades
the display. Hence the voltage waveform across a segment must not have a DC-component.
The LCD controller is intended for monochrome passive liquid crystal display (LCD) with up to 4 Common terminals and
up to 40 Segments terminals. If the application does not need all the LCD segments available on the XMEGA, up to 16 of
the unused LCD pins can be used as general purpose I/O pins.
The LCD controller can be clocked by an internal or an external asynchronous 32kHz clock source. This 32kHz oscillator
source selection is the same as for the Real Time Counter (RTC).
Dedicated Low Power Waveform, Contrast Control, Extended Interrupt Mode, Selectable Frame Frequency and Blink
functionality are supported to offload the CPU, reduce interrupts and reduce power consumption.
To reduce hardware design complexity, the LCD includes integrated LCD buffers, an integrated power supply voltage
and an innovative SWAP mode. Using SWAP mode, the hardware designers have more flexibility during board layout as
they can rearrange the pin sequence on Segment and/or Common Terminal Buses.
XMEGA B [MANUAL] 300
8291C–AVR–09/2014
25.2.1 Definitions
Several terms are used when describing LCD. The definitions in Table 25-1 are used throughout this document.
Table 25-1. LCD definitions.
Figure 25-1. LCD Typical Connections
25.2.2 LCD Clock Sources
The LCD controller can be clocked by an internal or an external asynchronous 32kHz clock source. This 32kHz oscillator
source selection is the same as for the Real Time Counter, RTCSRC bit-field in RTC control register (see Table 7-4 on
page 87).
The clock source must be stable to obtain accurate LCD timing and hence minimize DC voltage offset across LCD
segments.
25.2.3 LCD Prescaler
The prescaler consists of a 3-bit ripple counter and a 1 to 8-clock divider (see Figure 25-2 on page 301). The PRESC bit
selects clk LCD divided by 8 or 16 from the ripple counter.
If a finer resolution in frame rate is required, the CLKDIV bit-field can be used to divide the clock further by 1 to 8.
Output from the clock divider clk LCD_PS is used as clock source for the LCD timing.
25.2.4 LCD Display Memory
The Display Memory is available through I/O registers grouped for each common terminal.
A start of new frame triggers an update of the Shadow Display Memory. The content of Display Memory is saved into the
Shadow Display Memory. A Display Memory refresh is possible without affecting data that is sent to the panel.
LCD A passive display panel with terminals leading directly to a segment
Segment (or pixel) A LCD panel active area within the display which can be turned “ON or “OFF”. This can be a single
segment of a 7-segment character or a specific symbol (icon).
COM Common terminal
SEG Segment terminal
1 / Duty 1 / Number of common terminals on an actual LCD display
1 / Bias 1 / Number of voltage levels used driving a LCD display -1
Frame Rate Number of times the LCD segments are energized per second
Segment 0
Segment 1
Segment 2
Segment 4
Segment 5
Segment 6
SEG0
Segment 3
Segment 7
Common
Terminal 0 COM0
Common
Terminal 1 COM1
Segment
Terminal 0
SEG1
Segment
Terminal 1
SEG2
Segment
Terminal 2
SEG3
Segment
Terminal 3
XMEGA B [MANUAL] 301
8291C–AVR–09/2014
When a bit in the Display Memory is written to one, the corresponding segment will be energized (“ON”), and deenergized
(“OFF”) when this bit is written to zero.
To energize a segment, an absolute voltage above a certain threshold must be applied. This is done by setting the SEG
pin to opposite phase when the corresponding COM pin is active. For a display with more than one common terminal,
two (1/3 bias) additional voltage levels must be applied. Otherwise, non-energized segments on COM0 would be
energized for all non-selected common terminals.
Addressing COM0 starts a frame by driving an opposite phase with large amplitude on COM0 as against non addressed
COM lines. Non-energized segments are in phase with the addressed COM0, and energized segments have opposite
phase and large amplitude. For waveform figures refer to “Mode of Operation” on page 302.
DATA4 - DATA0 from Shadow Display Memory is multiplexed into the decoder. The decoder is controlled from the LCD
timing and sets up signals controlling the analog switches to produce an output waveform.
Next, COM1 is addressed, and DATA9 - DATA5 from Shadow Display Memory is input to the decoder. Addressing
continues until all COM lines are addressed according to the number of selected common terminals (duty).
25.2.5 Minimizing Power Consumption
The power consumption of the LCD controller can be minimized by:
1. Using the lowest acceptable frame rate - Refer to the LCD glass technical characteristics.
2. Using the low power waveform - “Low Power Waveform” on page 303
3. Programming the lowest possible contrast value - “CTRLF – Control register F” on page 313.
25.3 Block Diagram
Figure 25-2. LCD Controller Block Diagram
COMy
VLCD
BIAS1
CTRLF BIAS2
Analog
Switch
Array
Shadow
Display
Memory
LCD Power
Supply
Timing Control & Swap
CTRLD CTRLC
CTRLB CTRLA
Character
Mapping
CTRLH
CTRLG
CTRLE
CAPH CAPL
SEGx
INT
DATAn
DATA1
:
DATA0
Display
Memory
XMEGA B [MANUAL] 302
8291C–AVR–09/2014
25.4 Mode of Operation
25.4.1 Static Duty and Static Bias
If all segments on an LCD have one common electrode, then, each segment must have a unique segment terminal. This
kind of display is driven with the waveform shown in Figure 25-3 on page 302. SEG0-COM0 is the voltage across a
segment that is “ON”, and SEG1-COM0 is the voltage across a segment that is “OFF”.
Figure 25-3. Driving an LCD With One Common Terminal
25.4.2 1/2 Duty and 1/3 Bias
For an LCD with two common terminals (1/2 duty) a more complex waveform must be used to individually control
segments. The waveform is shown in Figure 25-4 on page 302. SEG0-COM0 is the voltage across a segment that is
“ON”, and SEG0-COM1 is the voltage across a segment that is “OFF”.
Figure 25-4. Driving an LCD With Two Common Terminals
25.4.3 1/3 Duty and 1/3 Bias
1/3 bias is usually recommended for an LCD with three common terminals (1/3 duty). The waveform is shown in Figure
25-5 on page 303. SEG0-COM0 is the voltage across a segment that is “ON” and SEG0-COM1 is the voltage across a
segment that is “OFF”.
XMEGA B [MANUAL] 303
8291C–AVR–09/2014
Figure 25-5. Driving an LCD With Three Common Terminals
25.4.4 1/4 Duty and 1/3 Bias
1/3 bias is optimal for an LCD displays with four common terminals (1/4 duty). The waveform is shown in Figure 25-6 on
page 303. SEG0-COM0 is the voltage across a segment that is ON” and SEG0-COM1 is the voltage across a segment
that is “OFF”.
Figure 25-6. Driving an LCD With Four Common Terminals
25.4.5 Low Power Waveform
To reduce toggle activity and hence power consumption, a low power waveform (LPWAV=1) can be selected. The low
power waveform requires two subsequent frames with the same display data to obtain zero DC voltage. Consequently,
the interrupt flag is only set every two frames. Default and the low power waveform is shown in Figure 25-7 on page 304
for 1/3 duty and 1/3 bias. For other selections of duty and bias, the effect is similar.
SEG0-COM0
Frame Frame
VLCD
SEG0
COM0
2/3 VLCD
GND
1/3 VLCD
VLCD
2/3 VLCD
GND
1/3 VLCD
VLCD
2/3 VLCD
GND
1/3 VLCD
-1/3 VLCD
-2/3 VLCD
- VLCD
Frame Frame
VLCD
SEG0
COM1
2/3 VLCD
GND
1/3 VLCD
VLCD
2/3 VLCD
GND
1/3 VLCD
VLCD
2/3 VLCD
GND
1/3 VLCD
-1/3 VLCD
-2/3 VLCD
- VLCD
SEG0-COM1
XMEGA B [MANUAL] 304
8291C–AVR–09/2014
Figure 25-7. Low Power Waveform With Three Common Terminals
25.4.6 Operation in Sleep Modes
The LCD will continue to operate in Idle mode, in Power-save mode and in Extended Standby mode (blinking included).
25.4.7 ASCII Character Mapping
The LCD controller can automatically handle ASCII characters. Instead of setting and clearing segments of the digit, the
user enters the ASCII code and the Digit Decoder updates itself the corresponding segment values in the Display
Memory.
Up to 4 types of character mapping are supported.
Figure 25-8. ASCII Character Mapping
Character mapping saves execution time and allows a fast return to Power-save or Extended Standby mode after display
updates.
25.4.8 Display Blanking
When BLANK is written to one, the LCD is blanked after the completion of the current frame. All segment and common
pins are driven to GND, discharging the LCD. Data in the Display Memory is preserved. Display blanking should be used
before disabling the LCD to avoid DC voltage across the segments, and a slowly fading image.
This mode differs from the one enabled by SEGON = 0 (in CTRLA register) where the segment and common pins are
always driven by the programmed waveform and where all the segments are “OFF”.
7-Segment
- 4 COM term.
- 2 SEG term.
7-Segment
- 3 COM term.
- 3 SEG term.
16-Segment
- 3 COM term.
- 6 SEG term.
14-Segment
- 4 COM term.
- 4 SEG term.
XMEGA B [MANUAL] 305
8291C–AVR–09/2014
25.4.9 Display Blinking
There are two ways to blink the display, controlled from software and controlled automatically by hardware.
25.4.9.1 Software Blinking
Setting / clearing segment(s) in the Display Memory allows software blinking. To blink simultaneously all enabled
segments, SEGON bit in CRTLA register can be used. The blink rate is software dependant.
25.4.9.2 Hardware Blinking
Up to eight segments (pixels) can be configured to automatically blink. These segments must be connected to the
segment terminal SEG1 and/or SEG0. This mode is enabled by setting the BLINKEN bit in the CTRLD register and
defining the associated common terminal(s) in the CTRLE register.The blink rate frequency is configured by using the
BLINKRATE bit-field in the CTRLD register. A segment will blink if its corresponding bit is set in the Display Memory,
otherwise it will remain “OFF”.
If all bits in the CTRLE register are set to zero, then blinking is applied to all enabled segments.
The BLINK command will come into operation at the beginning of the next LCD frame.
Table 25-2. Blinking modes.
Notes: 1. SEGON bit in CTRLA register.
25.4.10 Extended Interrupt Mode
In standard interrupt mode (XIME[4:0]=0), the LCD controller can provide an interrupt every frames. When the extended
interrupt mode is enabled, the LCD controller can provide the interrupt every XIME[4:0]+1 frames.
This mode provides an embedded time base for user. This time base can be used by the software in charge of display
updates (i.e. scrolling text, progress bar, ...).
The extended interrupt mode saves real time resources and allows the application to stay longer in Power-save or
Extended Standby mode.
25.4.11 LCD Power Supply
The LCD power supply manages all voltages for LCD buffers. The XBIAS bit in the CTRLA register defines the source of
V LCD. If XBIAS is cleared, V LCD sources voltages from the Bandgap Reference. Otherwise, V LCD must be powered
externally.
Note that when using external V LCD, the fine contrast controlled by FCONT[5:0] bits of the CRTLG register is inoperative.
SEGON(1) BLINKEN BPS1[3:0] | BPS0[3:0] Comment
0 x 0b xxxx xxxx All segments are “OFF”
1 0 0b xxxx xxxx All segments are driven by the corresponding data registers
1 1
0b 0000 0000 All segments are blinking at the blink frequency
Not equal to zero Blinking only the selected segment(s) at the blink frequency
XMEGA B [MANUAL] 306
8291C–AVR–09/2014
Table 25-3. LCD power supply pins behavior.
Notes: 1. ENABLE and XBIAS bits of the CTRLA register.
Figure 25-9. LCD Power Supply Block Diagram
Different application schemes for bias generation are shown in Figure 25-10 on page 306.
Figure 25-10.Analog Connections vs. Internal or External Bias Generation
ENABLE(1) XBIAS(1) VLCD (pin) BIAS2 BIAS1 CAPH / CAPL
0 x H.Z. H.Z. H.Z. H.Z.
1
0 VLCD
2
/3 VLCD
(also in static mode)
1
/3 VLCD
(also in static mode) Pump voltage
1 Input for VLCD
- Input for BIAS2
- H.Z. if static bias
- Input for BIAS1
- H.Z. if static bias H.Z.
BIAS1
BIAS2
VLCD
CAPL
CAPH
COMy
SEGx XBIAS
x3
x2
x1 BANDGAP
Reference
Pump
Contrast
100 nF
(1)
Internal Generation
Static or 1/3 Bias
ATxmegaB Device
CAPH
CAPL
VCC
VLCD
BIAS2
BIAS1
GND
VCC
100 nF (1)
100 nF (1)
100 nF (1)
ATxmegaB Device
CAPH
CAPL
VCC
VLCD
BIAS2
BIAS1
GND
External Generation
Static
VCC ATxmegaB Device VCC
External Generation (example)
1/3 Bias
Notes :
1: These values are provided for design guidance only. They should be optimized for the application by the designer based on actual LCD specifications.
2: Bias generation can be provided by other sources of voltage than a division resistor.
Ext.VLCD
(2)
(2)
(2)
(2)
Decoupling Decoupling
capacitors capacitors
Decoupling Decoupling
capacitor capacitor
Ext.VLCD
CAPH
CAPL
VCC
VLCD
BIAS2
BIAS1
GND
XMEGA B [MANUAL] 307
8291C–AVR–09/2014
25.4.12 Segment and Common Buses Swapping(1)
Segment and/or common buses can be swapped (mirrored) to give more flexibility for LCD interconnects. The first
segment (or common) terminal pin becomes the last one, and so on.
It is very useful in Chip on Glass (CoG), Chip on Film (CoF) or Chip on Board (CoB) technologies.
SEGSWP bit and COMSWP bit in the CRTLA register control the order of the respective terminal buses.
Note: 1. Refer to specific device datasheet for availability of this feature.
25.4.13 Port Mask
For LCD panels that do not use all the available segment terminals of the device, it is possible to mask some of the
unused pins. PMSK bit-field in the CTRLC register defines the number of segment terminals used in the application. Up
to 16 unused segment terminal pins can be used as standard GPIO pins. They are always placed at the end of the
segment terminal bus. The 8 last pins of this bus will become PG[0:7] - Port G - and the following 8 pins will become
PM[0:7] - Port M.
The GPIO functions on LCD pins are enabled if the corresponding segment terminal is masked or if the LCD controller is
disabled. A pure segment terminal - not shared with GPIO - is grounded via a pull-down resistor if it is masked or if the
LCD controller is disabled.
Note: SEGSWP bit, which reverses the segment terminal indexing, will be active even if the LCD controller is disabled
(ENABLE bit in the CRTLA register) and will thus also modify the GPIO pin mapping.
Examples of a 40-segment LCD controller:
z If 30 segments are used:
Segment terminals [39:32] = PG[0:7] , Port G (GPIO functions)
Segment terminals [31:30] = PM[0:1] , Port M (GPIO functions)
Segment terminals [29:0] = SEG[29:0] , LCD (LCD functions)
z If 20 segments are used:
Segment terminals [39:32] = PG[0:7] , Port G (GPIO functions)
Segment terminals [31:24] = PM[0:7] , Port M (GPIO functions)
Segment terminals [23:20] = GND (pull down)
Segment terminals [19:0] = SEG[19:0] , LCD (LCD functions)
XMEGA B [MANUAL] 308
8291C–AVR–09/2014
25.5 Register Description – LCD
25.5.1 CTRLA – Control register A
z Bit 7 – ENABLE: LCD Enable
Writing this bit to one enables the LCD. By writing it to zero, the LCD is turned “OFF” immediately. Turning the LCD
“OFF” while driving a display, drives the output to ground to discharge the display (apart from segment terminals which
will be controlled by GPIO settings).
z Bit 6 – XBIAS: External Bias Generation
When this bit is set, the LCD buffers which drive the intermediate voltage levels are turned “OFF”. When XBIAS is “OFF”,
an external source for V LCD is necessary.
z Bit 5 – DATLCK: Data Register Lock
Writing this bit to one freezes the Shadow Display Memory. If the Display Memory is modified, the Shadow Display
Memory is locked and the display remains unchanged. When the bit is cleared, the Shadow Display Memory is updated
when a new frame starts (see Figure 25-2 on page 301).
z Bit 4 – COMSWP: Common Terminal Bus Swap(1)
Writing this bit to one inverts the order of the common terminal bus (COM[3:0]). The common terminals disabled by
DUTY[1:0] are also affected (see Table 25-4).
Table 25-4. Common terminal bus reverse.
Note: 1. Refer to specific device datasheet for availability of this feature.
z Bit 3 – SEGSWP: Segment Terminal Bus Swap(1)
Writing this bit to one inverts completely the order of the segment terminal bus (SEG[39:0]). The segment terminals unselected
by PMSK[5:0] are also affected (see Table 25-5 on page 309).
Bit 7 6 5 4 3 2 1 0
+0x00 ENABLE XBIAS DATLCK COMSWP SEGSWP CLRDT SEGON BLANK
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
DUTY[1:0] Number of COM COMSWP = 0 COMSWP = 1
00 4 COM3,COM2,COM1,COM0 COM0,COM1,COM2,COM3
01 1 –, –, –, COM0 COM0, –, –, –
10 2 –, –, COM1, COM0 COM0, COM1, –, –
11 3 –, COM2, COM1, COM0 COM0, COM1, COM2, –
XMEGA B [MANUAL] 309
8291C–AVR–09/2014
Table 25-5. Segment terminal bus reverse (examples)
Note: 1. Refer to specific device datasheet for availability of this feature.
z Bit 2 – CLRDT: Clear Data Register
Writing this bit to one clears immediately the Display Memory (but not the control registers). The display will be blanked
after completion of a frame. This bit is automatically reset once the Display Memory is cleared.
z Bit 1 – SEGON: Segments “ON”.
Writing this bit to one enables all segments and the contents of the Display Memory is output on the LCD. Writing it to
zero, turns “OFF” all LCD segments.
This bit can be used to flash the LCD, leaving the LCD timing generator enabled.
z Bit 0 – BLANK: Blanking Display Mode
When this bit is written to one, the display will be blanked after completion of a frame. All segment and common terminals
will be driven to ground. (For more details see “Display Blanking” on page 304). This function does not modify the Display
Memory.
25.5.2 CTRLB – Control register B
z Bit 7 – PRESC: LCD Prescaler Select
The PRESC bit selects a tap point from a ripple counter. The ripple counter output can be further divided by setting the
Clock Divider (CLKDIV[2:0]). The different selections are shown in Table 25-6. Together they define the prescaler LCD
clock (clk LCD_PS), which is clocking the LCD controller.
Table 25-6. LCD prescaler selection.
PMSK[5:0] Number of SEG SEGSWP = 0 SEGSWP = 1
000100 4 (SEG [39:4] unused), SEG[3:0] SEG[0:3], (SEG[4:39] unused)
001000 8 (SEG[39:8] unused), SEG[7:0] SEG[0:7], (SEG[8:39] unused)
010000 16 (SEG[39:16] unused), SEG[15:0] SEG[0:15], (SEG[16:39] unused)
101000 40 SEG[39:0] SEG[0:39]
Bit 7 6 5 4 3 2 1 0
+0x01 PRESC CLKDIV[2:0] LPWAV – DUTY[1:0]
Read/Write R/W R/W R/W R/W R/W R R/W R/W
Initial Value 0000 0 0 0 0
PRESC
Output From Ripple Counter
clk LCD / N
Frame Rates (CLKDIV[2:0] = 0, DUTY = 1
/4 )
F(clk LCD) = 32kHz F(clk LCD) = 32768Hz
0 clk LCD / 8 500 Hz 512 Hz
1 clk LCD / 16 250 Hz 256 Hz
XMEGA B [MANUAL] 310
8291C–AVR–09/2014
z Bit 6:4 – CLKDIV[2:0]: LCD Clock Division
The CLKDIV bit-field defines the division ratio in the clock divider. The various selections are shown in Table 25-7. This
Clock Divider gives extra flexibility in frame rate setting.
Frame rate equation:
Where:
N = prescaler divider (8 or 16).
K = 8 for 1/4, 1/2 and static duty.
K = 6 for 1/3 duty.
Table 25-7. LCD clock divider (1/4 dyty).
Note that when using 1/3 duty, the frame rate is increased by 33% compared to the values listed above.
Table 25-8. Example of frame rate calculation.
z Bit 3 – LPWAV: Low Power Waveform
When LPWAV is written to one, the low power waveform is outputted on LCD pins, otherwise the standard waveform is
outputted. If this bit is modified during display operation the change takes place at the beginning of the next frame. (For
more details see “Low Power Waveform” on page 303).
z Bit 2 – Reserved
This bit is unused and reserved for future use. For compatibility with future devices, always write this bit to zero when this
register is written.
CLKDIV[2:0] Divided by
Frame Rate (1/4 Duty)
F(clk LCD) = 32 kHz F(clk LCD) = 32768 Hz
N=8 N=16 N=8 N=16
000 1 500 Hz 250 Hz 512 Hz 256 Hz
001 2 250 Hz 125 Hz 256 Hz 128 Hz
010 3 166.667 Hz 83.333 Hz 170.667 Hz 85.333 Hz
011 4 125 Hz 62.5 Hz 128 Hz 64 Hz
100 5 100 Hz 50 Hz 102.4 Hz 51.2 Hz
101 6 83.333 Hz 41.667 Hz 85.333 Hz 42.667 Hz
110 7 71.429 Hz 35.714 Hz 73.143 Hz 36.671 Hz
111 8 62.5 Hz 31.25 Hz 64 Hz 32 Hz
clk LCD Duty K PRESC N CLKDIV[2:0] Frame rate
32.768kHz Static 8 1 16 4 32768 / ( 8 x 16 x ( 1 + 4 ) ) = 51.2Hz
32.768kHz 1/2 8 1 16 4 32768 / ( 8 x 16 x ( 1 + 4 ) ) = 51.2Hz
32.768kHz 1/3 6 1 16 4 32768 / ( 6 x 16 x ( 1 + 4 ) ) = 68.267Hz
32.768kHz 1/4 8 1 16 4 32768 / ( 8 x 16 x ( 1 + 4 ) ) = 51.2Hz
FrameRate
F clkLCD ( )
(K N× × ( ) 1 + CLKDIV ) = ----------------------------------------------------------------
XMEGA B [MANUAL] 311
8291C–AVR–09/2014
z Bits 1:0 – DUTY[1:0]: Duty Select(1)
The DUTY bit-field defines the duty cycle. Common pins that are not used will be driven to ground. The different duty
selections are shown in Table 25-9.
Table 25-9. Duty cycle.
Note: 1. Refer to specific device datasheet for duty cycles availability (linked to the number of available common terminals).
25.5.3 CTRLC – Control register C
z Bits 7:6 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bits 5:0 – PMSK[5:0]: LCD Port Mask
The PMSK bit-field defines the number of port pins to be used as segment drivers. The unused pins will be driven to
ground except the 16 highest pins which become GPIO's.
25.5.4 INTCTRL – Interrupt Control register
z Bits 7:3 – XIME[4:0]: eXtended Interrupt Mode Enable
XIME bit-field defines the number of frames to be completed for one interrupt period.
Interrupt Period = ( ( XIME[4:0] + 1 ) x 2LPWAV ) frames
z For default waveforms, the FCIF flag is generated every XIME[4:0] + 1 frames. The range is 1 up to 32 frames.
z For low power waveforms requiring 2 subsequent frames, the FCIF flag is generated every
2 x ( XIME[4:0] + 1 ) frames. The range is 2 up to 64 frames.
Note: This extended interrupt mode generates a stable time base from the frame rate.
z Bit 2 – Reserved
This bit is unused and reserved for future use. For compatibility with future devices, always write this bit to zero when this
register is written.
DUTY[1:0] Duty Bias COM pins Used
0 0 1/4 1/3 COM[0:3]
0 1 Static Static COM0
1 0 1/2 1/3 COM[0:1]
1 1 1/3 1/3 COM[0:2]
Bit 7 6 5 4 3 2 1 0
+0x02 – – PMSK[5:0]
Read/Write R R R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
+0x03 XIME[4:0] – FCINTLVL[1:0]
Read/Write R/W R/W R/W R/W R/W R R/W R/W
Initial Value 0 0 000000
XMEGA B [MANUAL] 312
8291C–AVR–09/2014
z Bits 1:0 – FCINTLVL[1:0]: Interrupt Level
This bit-field enables the LCD frame completed interrupt and selects the interrupt level as described in “Interrupts and
Programmable Multilevel Interrupt Controller” on page 121. The enabled interrupt will be triggered when the FCIF flag in
the INTFLAGS register is set.
25.5.5 INTFLAGS – Interrupt Flag register
z Bits 7:1 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 0 – FCIF: LCD Frames Completed Interrupt Flag
The generation of this flag depends on the XIME value in the INTCTRL register.
This bit is set by hardware at the beginning of a frame. FCIF is cleared by hardware when executing the corresponding
interrupt handling routine. Alternatively, writing a logical one to the flag clears FCIF.
25.5.6 CTRLD – Control register D
z Bits 7:4 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 3 – BLINKEN: Blink Enable
Writing this bit to one, the blink mode starts at the frequency specified by LCD blink rate (BLINKRATE). By writing it to
zero, the LCD blink module stops. This BLINKEN bit takes effect at the beginning of the next LCD frame. (For more
details see “Display Blinking” on page 305).
z Bit 2 – Reserved
This bit is unused and reserved for future use. For compatibility with future devices, always write this bit to zero when this
register is written.
z Bits 1:0 – BLINKRATE[1:0]: LCD Blink Rate
The BLINKRATE bit-field defines the frequency of the hardware Display Blinking when the BLINKEN bit is set. Blink
frequencies are shown in Table 25-10.
Table 25-10. Blink frequencies.
Bit 7 6 5 4 3 2 1 0
+0x04 – – – – – – – FCIF
Read/Write R R R R R R R R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
+0x05 – – – – BLINKEN – BLINKRATE[1:0]
Read/Write R R R R R/W R R/W R/W
Initial Value 0 0 0 0 0 0 0 0
BLINKRATE[1:0] Blink frequency
00 4Hz
01 2Hz
10 1Hz
11 0.5Hz
XMEGA B [MANUAL] 313
8291C–AVR–09/2014
25.5.7 CTRLE – Control register E
z Bits 7:4 – BPS1[3:0]: Blink Segment Selection 1
This bit-field defines the segment which is connected on SEG1 for blinking. Each bit of BPS1[3:0] corresponds to one of
the common terminals.
z Bits 3:0 – BPS0[3:0]: Blink Segment Selection 0
This bit-field defines the segment which is connected on SEG0 for blinking. Each bit of BPS0[3:0] corresponds to one of
the common terminals.
Note: If no segment to blink is selected (BPS1[3:0] = BPS1[3:0] = 0) and if the BLINKEN bit is set, then the full display is
blinking.
25.5.8 CTRLF – Control register F
z Bits 7:6 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bits 5:0 – FCONT[5:0]: Fine Contrast
FCONT bit-field defines the maximum voltage clk LCD on segment and common pins. FCONT is a signed number (two's
complement). New values take effect at the beginning of each frame.
VLCD = 3.0 V + ( FCONT[5:0] x 0.016 V )
25.5.9 CTRLG – Control register G
z Bits 7:6 – TDG[1:0]: Type of Digit(1)
This bit-field specifies the number of segments and segment/common connections used to display a digit. See Table 25-
11 and Figure 25-11 on page 314.
Bit 7 6 5 4 3 2 1 0
+0x06 BPS1[3:0] BPS0[3:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
+0x07 – – FCONT[5:0]
Read/Write R R R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
+0x08 TDG[1:0] STSEG[5:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 00000000
XMEGA B [MANUAL] 314
8291C–AVR–09/2014
Table 25-11. Type of digits.
Note: 1. Refer to specific device datasheet for “Type of Digit” availability.
z Bits 5:0 – STSEG[5:0]: Start Segment
STSEG bit-field defines the first segment terminal used to write the decoded display. This bit-field is automatically
incremented or decremented (according to the DEC value of CTRLH register) by the number of segment terminals used
in the digit.
Figure 25-11.Segment and Common Terminal Connections for Digit
25.5.10 CTRLH – Control register H
z Bit 7 – DEC: Decrement of Start Segment
Writing this bit to one automatically decrements the STSEG bit-field of CTRLG register by the number of segment
terminals used by the digit. If this bit is written to zero, the STSEG bit-field is incremented by the number of segment
terminals used by the digit. This action takes place once the digit decoding is finished and prepares the next call to the
Digit Decoder.
z Bits 6:0 – DCODE[6:0]: Display Code
DCODE bit-field will be computed by the Digit Decoder, and converted to display codes, and then automatically written
into the Display Memory according to the STSEG value. This Digit Decoder can be used when the LCD panel is defined
with one or more of the configurations above in Figure 25-11 on page 314.
TDG[1:0] Digit Type
00 7-segment with 3 common terminals, COM[2:0]
01 7-segment with 4 common terminals, COM[3:0]
10 14-segment with 4 common terminals, COM[3:0]
11 16-segment with 3 common terminals, COM[2:0]
a
e
f
d
g
b
c
SEGn : a, b, c
SEGn+1 : d, e, f, g
COM0 : a, f
COM1 : b, g
COM2 : c, e
COM3 : d
a 7-segment with 4 COM
e
f
d
g
b
c
SEGn : b, c
SEGn+1 : a, d, g
SEGn+2 : e, f
COM0 : a, b, f
COM1 : c, e, g
COM2 : d
7-segment with 3 COM
SEGn : h, i, k, n
SEGn+1 : d, e, f
SEGn+2 : a, b, c
SEGn+3 : g, j, l, m
COM0 : a, g, h
COM1 : b, i, j, f
COM2 : c, e, k, l
COM3 : d, m, n
a 14-segment with 4 COM
e
f
d
j
b
c
k
g i
l n m
h SEGn : h, g, n
SEGn+1 : a, i, l
SEGn+2 : b, k, m
SEGn+3 : c, d, e
SEGn+4 : j, o, p
SEGn+5 : f
COM0 : h, a, b, c, j
COM1 : g, i, k, d, o
COM2 : n, l, m, p, e, f
16-segment with 3 COM
f e
a b
g
h
l
c
d
m
i k
n p o
j
Bit 7 6 5 4 3 2 1 0
+0x09 DEC DCODE[6:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0000000
XMEGA B [MANUAL] 315
8291C–AVR–09/2014
The Table 25-12 on page 315, Table 25-13 on page 316 and Table 25-14 on page 317 show the DCODE[6:0] and
display pattern.
The table entry code, DCODE [6:0], is the 7-bit ASCII code of the digit.
Table 25-12. 7-segments Character Table.
XMEGA B [MANUAL] 316
8291C–AVR–09/2014
Table 25-13. 14-segments Character Table.
XMEGA B [MANUAL] 317
8291C–AVR–09/2014
Table 25-14. 16-segments Character Table.
XMEGA B [MANUAL] 318
8291C–AVR–09/2014
25.5.11 DATA – LCD Data Memory Mapping
The Display Memory provides access to control the “ON/OFF” state for segments.
Data Memory register offset versus segment (pixel) coordinates (pixel_COM, pixel_SEG):
z LCD_offset = 0x10 + ( pixel_COM x ⎣(Max_SEG + 7 ) / 8⎦ ) + ⎣pixel_SEG / 8⎦
Where: . 0x10 is the hexadecimal offset of DATA0 register,
. Max_SEG is the maximal number of SEG terminals of the device,
.⎣xxx⎦ means the integer part of xxx.
Bit position of the segment (pixel) in the Data Memory register (between 0 and 7):
z bit_position = pixel_SEG % 8
Where: . % is the modulo operation.
Bit 76543210
+0x23 PIX159 PIX158 PIX157 PIX156 PIX155 PIX154 PIX153 PIX152 DATA19
+0x22 PIX[151:144] DATA18
+0x21 PIX[143:136] DATA17
+0x20 PIX[135:128] DATA16
+0x1F PIX[127:120] DATA15
+0x1E PIX[119:112] DATA14
+0x1D PIX[111:104] DATA13
+0x1C PIX[103:96] DATA12
+0x1B PIX[95:88] DATA11
+0x1A PIX[87:80] DATA10
+0x19 PIX[79:72] DATA9
+0x18 PIX[71:64] DATA8
+0x17 PIX[63:56] DATA7
+0x16 PIX[55:48] DATA6
+0x15 PIX[47:40] DATA5
+0x14 PIX[39:32] DATA4
+0x13 PIX[31:24] DATA3
+0x12 PIX[23:16] DATA2
+0x11 PIX[15:8] DATA1
+0x10 PIX7 PIX6 PIX5 PIX4 PIX3 PIX2 PIX1 PIX0 DATA0
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial
Value 00000000
XMEGA B [MANUAL] 319
8291C–AVR–09/2014
25.6 Register Summary – LCD
25.7 Interrupt Vector Summary
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
+0x24 to Reserved – – – – – – – –
+0x23 DATA19 PIX[159:152] 318
+0x22 DATA18 PIX[151:144] 318
+0x21 DATA17 PIX[143:136] 318
+0x20 DATA16 PIX[135:128] 318
+0x1F DATA15 PIX[127:120] 318
+0x1E DATA14 PIX[119:112] 318
+0x1D DATA13 PIX[111:104] 318
+0x1C DATA12 PIX[103:96] 318
+0x1B DATA11 PIX[95:88] 318
+0x1A DATA10 PIX[87:80] 318
+0x19 DATA9 PIX[79:72] 318
+0x18 DATA8 PIX[71:64] 318
+0x17 DATA7 PIX[63:56] 318
+0x16 DATA6 PIX[55:48] 318
+0x15 DATA5 PIX[47:40] 318
+0x14 DATA4 PIX[39:32] 318
+0x13 DATA3 PIX[31:24] 318
+0x12 DATA2 PIX[23:16] 318
+0x11 DATA1 PIX[15:8] 318
+0x10 DATA0 PIX[7:0] 318
+0x0A to Reserved – – – – – – – –
+0x09 CTRLH DEC DCODE[6:0] 314
+0x08 CTRLG TDG[1:0] STSEG[5:0] 313
+0x07 CTRLF – – FCONT[5:0] 313
+0x06 CTRLE BPS1[3:0] BPS0[3:0] 313
+0x05 CTRLD – – – – BLINKEN – BLINKRATE[1:0] 312
+0x04 INTFLAGS – – – – – – – FCIF 312
+0x03 INTCTRL XIME[4:0] – FCINTLVL[1:0] 311
+0x02 CTRLC – – PMSK[5:0] 311
+0x01 CTRLB PRESC CLKDIV[2:0] LPWAV – DUTY[1:0] 309
+0x00 CTRLA ENABLE XBIAS DATLCK COMSWP SEGSWP CLRDT SEGON BLANK 308
Offset Source Interrupt Description
0x00 LCD_vect LCD Interrupt vector
XMEGA B [MANUAL] 320
Atmel-8291C-AVR-XMEGA B -09/2014
26. ADC – Analog-to-Digital Converter
26.1 Features
z 12-bit resolution
z Up to 300 thousand samples per second
z Down to 2.3μs conversion time with 8-bit resolution
z Down to 3.35μs conversion time with 12-bit resolution
z Differential and single-ended input
z Up to 16 single-ended inputs
z Up to 16x4 differential inputs without gain
z 8x4 differential input with gain
z Built-in differential gain stage
z 1/2x, 1x, 2x, 4x, 8x, 16x, 32x, and 64x gain options
z Single, continuous and scan conversion options
z Three internal inputs
z Internal temperature sensor
z AVCC voltage divided by 10
z 1.1V bandgap voltage
z Internal and external reference options
z Compare function for accurate monitoring of user defined thresholds
z Optional DMA transfer of conversion results
z Optional event triggered conversion for accurate timing
z Optional interrupt/event on compare result
26.2 Overview
The ADC converts analog signals to digital values. The ADC has 12-bit resolution and is capable of converting up to 300
thousand samples per second (ksps). The input selection is flexible, and both single-ended and differential
measurements can be done. For differential measurements, an optional gain stage is available to increase the dynamic
range. In addition, several internal signal inputs are available. The ADC can provide both signed and unsigned results.
The ADC measurements can either be started by application software or an incoming event from another peripheral in
the device. The ADC measurements can be started with predictable timing, and without software intervention. It is
possible to use DMA to move ADC results directly to memory or peripherals when conversions are done.
Both internal and external reference voltages can be used. An integrated temperature sensor is available for use with the
ADC. The AVCC/10 and the bandgap voltage can also be measured by the ADC.
The ADC has a compare function for accurate monitoring of user defined thresholds with minimum software intervention
required.
XMEGA B [MANUAL] 321
Atmel-8291C-AVR-XMEGA B -09/2014
Figure 26-1. ADC overview.
26.3 Input Sources
Input sources are the voltage inputs that the ADC can measure and convert. Four types of measurements can be
selected:
z Differential input
z Differential input with gain
z Single-ended input
z Internal input
The input pins are used for single-ended and differential input, while the internal inputs are directly available inside the
device. In devices with two ADCs, PORTA pins can be input to ADCA and PORTB pins can be input to ADCB. For the
devices with only one ADC, input pins may be available for ADCA on both PORTA and PORTB.
The ADC is differential, and so for single-ended measurements the negative input is connected to a fixed internal value.
The four types of measurements and their corresponding input options are shown in Figure 26-2 on page 322 to Figure
26-6 on page 324.
26.3.1 Differential Input
When differential input is enabled, all input pins can be selected as positive input, and input pins 0 to 3 can be selected
as negative input. The ADC must be in signed mode when differential input is used.
CH0 Result
Compare
Register
<
> Threshold
(Int Req)
Internal 1.00V
Internal AVCC/1.6V
AREFA
AREFB
VINP
VINN
Internal
signals
S&H Σ
ADC DAC
2x
2 bits
VIN VOUT
Internal AVCC/2
ADC0
ADC15
•
•
•
ADC0
ADC7
•
•
•
Reference
Voltage
Stage
1
Stage
2
Digital Correction Logic
2 2
clkADC
CH0.CTRL REFCTRL
CH0.MUXCTRL
CTRLA EVCTRL
CTRLB
Enable
Start
Mode
Resolution
Action
Select
XMEGA B [MANUAL] 322
Atmel-8291C-AVR-XMEGA B -09/2014
Figure 26-2. Differential measurement without gain.
26.3.2 Differential Input with Gain
When differential input with gain is enabled, all input pins can be selected as positive input, and input pins 4 to 7 can be
selected as negative input. When gain is enabled, the differential input is first sampled and amplified by the gain stage
before the result is converted. The ADC must be in signed mode when differential input with gain is used.
The gain is selectable to 1/2x, 1x, 2x, 4x, 8x, 16x, 32x, and 64x gain.
Figure 26-3. Differential measurement with gain.
26.3.3 Single-ended Input
For single-ended measurements, all input pins can be used as inputs. Single-ended measurements can be done in both
signed and unsigned mode.
The negative input is connected to internal ground in signed mode.
+
- ADC0
ADC3
ADC0
ADC15
•
•
•
•
•
•
GND
INTGND
+
- ADC4
ADC7
ADC0
ADC7
•
•
•
•
•
•
GND
INTGND
½x - 64x
XMEGA B [MANUAL] 323
Atmel-8291C-AVR-XMEGA B -09/2014
Figure 26-4. Single-ended measurement in signed mode.
In unsigned mode, the negative input is connected to half of the voltage reference (VREF) voltage minus a fixed offset.
The nominal value for the offset is:
Since the ADC is differential, the input range is VREF to zero for the positive single-ended input. The offset enables the
ADC to measure zero crossing in unsigned mode, and allows for calibration of any positive offset when the internal
ground in the device is higher than the external ground. See Figure 26-11 on page 326 for details.
Figure 26-5. Single-ended measurement in unsigned mode.
26.3.4 Internal Inputs
These internal signals can be measured or used by the ADC.
z Temperature sensor
z Bandgap voltage
z AVCC scaled
z Pad and Internal Ground
The temperature sensor gives an output voltage that increases linearly with the internal temperature of the device. One
or more calibration points are needed to compute the temperature from a measurement of the temperature sensor. The
temperature sensor is calibrated at one point in production test, and the result is stored to TEMPESENSE0 and
TEMPSENSE1 in the production signature row. For more calibration condition details, refer to the device datasheet.
The bandgap voltage is an accurate internal voltage reference.
VCC can be measured directly by scaling it down by a factor of 10 before the ADC input. Thus, a VCC of 1.8V will be
measured as 0.18V, and VCC of 3.6V will be measured as 0.36V. This enables easy measurement of the VCC voltage.
The internal signals need to be enabled before they can be measured. Refer to their manual sections for Bandgap for
details of how to enable these. The sample rate for the internal signals is lower than that of the ADC. Refer to the ADC
characteristics in the device datasheets for details.
For differential measurement Pad Ground (Gnd) and Internal Gnd can be selected as negative input. Pad Gnd is the gnd
level on the pin and identical or very close to the external gnd. Internal Gnd is the internal device gnd level.
Internal Gnd is used as the negative input when other internal signals are measured in single-ended signed mode.
• +
ADC -
ADC0
ADC15
•
•
ΔV VREF = × 0.05
•
• +
ADC -
ADC0
ADC15
−ΔV VREF
____
2
•
XMEGA B [MANUAL] 324
Atmel-8291C-AVR-XMEGA B -09/2014
Figure 26-6. Internal measurements in single-ended signed mode.
To measure the internal signals in unsigned mode, the negative input is connected to a fixed value given by the formula
below, which is half of the voltage reference (VREF) minus a fixed offset, as it is for single-ended unsigned input. Refer to
Figure 26-11 on page 326 for details.
VINN = VREF/2 - ΔV
Figure 26-7. Internal measurements in unsigned mode.
26.4 Sampling Time Control
To support applications with high source output resistance, the sampling time can be increased by steps of one half ADC
clock cycle up to 64 ADC clock cycles.
26.5 Voltage Reference Selection
The following voltages can be used as the reference voltage (VREF) for the ADC:
z Accurate internal 1.00V voltage generated from the bandgap
z Internal AVCC/1.6V voltage
z Internal AVCC/2V voltage
z External voltage applied to AREF pin on PORTA
z External voltage applied to AREF pin on PORTB
Figure 26-8. ADC voltage reference selection
+
ADC -
TEMP REF
AVCC SCALED
BANDGAP REF
+
ADC -
TEMP REF
AVCC SCALED
BANDGAP REF
−ΔV VREF
____
2
Internal 1.00V
AREFB
AREFA
Internal AVCC/1.6V
Internal AVCC/2.0V VREF
XMEGA B [MANUAL] 325
Atmel-8291C-AVR-XMEGA B -09/2014
26.6 Conversion Result
The result of the analog-to-digital conversion is written to the channel result register. The ADC is either in signed or
unsigned mode. This setting is global for the ADC and for the ADC channel.
In signed mode, negative and positive results are generated. Signed mode must be used when the ADC channel is set
up for differential measurements. In unsigned mode, only single-ended or internal signals can be measured. With 12-bit
resolution, the TOP value of a signed result is 2047, and the results will be in the range -2048 to +2047 (0xF800 -
0x07FF).
The ADC transfer function can be written as:
VINP and VINN are the positive and negative inputs to the ADC.
For differential measurements, GAIN is 1/2 to 64. For single-ended and internal measurements, GAIN is always 1 and
VINP is the internal ground.
In unsigned mode, only positive results are generated. The TOP value of an unsigned result is 4095, and the results will
be in the range 0 to +4095 (0x0 - 0x0FFF).
The ADC transfer functions can be written as:
VINP is the single-ended or internal input.
The ADC can be configured to generate either an 8-bit or a 12-bit result. A result with lower resolution will be available
faster. See the “ADC Clock and Conversion Timing” on page 326 for a description on the propagation delay.
The result register is 16 bits wide, and data are stored as right adjusted 16-bit values. Right adjusted means that the
eight least-significant bits (lsb) are found in the low byte. A 12-bit result can be represented either left or right adjusted.
Left adjusted means that the eight most-significant bits (msb) are found in the high byte.
When the ADC is in signed mode, the msb represents the sign bit. In 12-bit right adjusted mode, the sign bit (bit 11) is
padded to bits 12-15 to create a signed 16-bit number directly. In 8-bit mode, the sign bit (bit 7) is padded to the entire
high byte.
Figure 26-9 on page 325 to Figure 26-11 on page 326 show the different input options, the signal input range, and the
result representation with 12-bit right adjusted mode.
Figure 26-9. Signed differential input (with gain), input range, and result representation.
RES VINP - VINN
VREF = --------------------------------- GAIN TOP +1 ⋅ ⋅ ( )
RES VINP - (-ΔV )
VREF = ---------------------------------- ⋅ ( ) TOP +1
2047
2046
2045
...
3
2
1
0
-1
...
-2045
-2046
-2047
-2048
7FF
7FE
7FD
...
3
2
1
0
FFF
FFE
...
803
802
801
800
Dec Hex
0111 1111 1111
0111 1111 1110
0111 1111 1101
...
0000 0000 0011
0000 0000 0010
0000 0000 0001
0000 0000 0000
1111 1111 1111
1111 1111 1110
...
1000 0000 0011
1000 0000 0010
1000 0000 0001
1000 0000 0000
Binary
0000 0111 1111 1111
0000 0111 1111 1110
0000 0111 1111 1101
...
0000 0000 0000 0011
0000 0000 0000 0010
0000 0000 0000 0001
0000 0000 0000 0000
1111 1111 1111 1111
1111 1111 1111 1110
...
1111 1000 0000 0011
1111 1000 0000 0010
1111 1000 0000 0001
1111 1000 0000 0000
VREF 16-bit result register
GAIN
-VREF
GAIN
0 V
VINN
RES
VINP
-2
XMEGA B [MANUAL] 326
Atmel-8291C-AVR-XMEGA B -09/2014
Figure 26-10.Signed single-ended and internal input, input range, and result representation.
Figure 26-11.Unsigned single-ended and internal input, input range, and result representation.
26.7 Compare Function
The ADC has a built-in 12-bit compare function. The ADC compare register can hold a 12-bit value that represents a
threshold voltage. The ADC channel can be configured to automatically compare its result with this compare value to
give an interrupt or event only when the result is above or below the threshold.
26.8 Starting a Conversion
Before a conversion is started, the input source must be selected. An ADC conversion can be started either by the
application software writing to the start conversion bit or from any events in the event system.
26.8.1 Input Source Scan
It is possible to select a range of consecutive input sources that is automatically scanned and measured when a
conversion is started. This is done by setting the first (lowest) positive ADC channel input using the MUX control register,
and a number of consecutive positive input sources. When a conversion is started, the first selected input source is
measured and converted, then the positive input source selection is incremented after each conversion until it reaches
the specified number of sources to scan.
26.9 ADC Clock and Conversion Timing
The ADC is clocked from the peripheral clock. The ADC can prescale the peripheral clock to provide an ADC Clock
(clkADC) that matches the application requirements and is within the operating range of the ADC.
2047
2046
2045
...
3
2
1
0
-1
-2
...
-2045
-2046
-2047
-2048
7FF
7FE
7FD
...
3
2
1
0
FFF
FFE
...
803
802
801
800
Dec Hex
0111 1111 1111
0111 1111 1110
0111 1111 1101
...
0000 0000 0011
0000 0000 0010
0000 0000 0001
0000 0000 0000
1111 1111 1111
1111 1111 1110
...
1000 0000 0011
1000 0000 0010
1000 0000 0001
1000 0000 0000
Binary
0000 0111 1111 1111
0000 0111 1111 1110
0000 0111 1111 1101
...
0000 0000 0000 0011
0000 0000 0000 0010
0000 0000 0000 0001
0000 0000 0000 0000
1111 1111 1111 1111
1111 1111 1111 1110
...
1111 1000 0000 0011
1111 1000 0000 0010
1111 1000 0000 0001
1111 1000 0000 0000
16-bit result register VREF
-VREF
0 V
VINP
VINN = GND
4095
4094
4093
...
203
202
201
200
FFF
FFE
FFD
...
0CB
0CA
0C9
0C8
Dec Hex
1111 1111 1111
1111 1111 1110
1111 1111 1101
...
0000 1100 1011
0000 1100 1010
0000 1100 1001
0000 1100 1000
Binary
0000 1111 1111 1111
0000 1111 1111 1110
0000 1111 1111 1101
...
0000 0000 1100 1011
0000 0000 1100 1010
0000 0000 1100 1001
0000 0000 1100 1000
16-bit result register
V VREF VINN = − Δ
2 GND
VREF − ΔV
VINP
...
0 0 0000 0000 0000 0000 0000 0000 0000
XMEGA B [MANUAL] 327
Atmel-8291C-AVR-XMEGA B -09/2014
Figure 26-12.ADC prescaler.
The propagation delay of an ADC measurement is given by:
RESOLUTION is the resolution, 8 or 12 bits. The propagation delay will increase by extra ADC clock cycles if the gain
stage (GAIN) is used. A new ADC conversion can start as soon as the previous is completed.
The most-significant bit (msb) of the result is converted first, and the rest of the bits are converted during the next three
(for 8-bit results) or five (for 12-bit results) ADC clock cycles. Converting one bit takes a half ADC clock period. During the
last cycle, the result is prepared before the interrupt flag is set and the result is available in the result register for readout.
26.9.1 Single Conversion without Gain
Figure 26-13 on page 327 shows the ADC timing for a single conversion without gain. The writing of the start conversion
bit, or the event triggering the conversion (START), must occur at least one peripheral clock cycle before the ADC clock
cycle on which the conversion starts (indicated with the grey slope of the START trigger).
The input source is sampled in the first half of the first cycle.
Figure 26-13.ADC timing for one single conversion without gain.
9-bit ADC Prescaler
ClkADC
PRESCALER[2:0]
CLK/4
CLK/8
CLK/16
CLK/32
CLK/64
CLK/128
ClkPER
CLK/256
CLK/512
Propagation Delay =
1 RESOLUTION + 1
2
+ + ------------------------------------------------ GAIN
f ADC
--------------------------------------------------------------------------------
clkADC
START
ADC SAMPLE
IF
CONVERTING BIT 10 9 8 7 6 5 4 3 2 1 lsb
12345678
msb
9
XMEGA B [MANUAL] 328
Atmel-8291C-AVR-XMEGA B -09/2014
Figure 26-14.ADC timing for one single conversion with increased sampling time (SAMPVAL = 6).
26.9.2 Single Conversion with Gain
Figure 26-15 on page 328 to Figure 26-17 on page 329 show the ADC timing for one single conversion with various gain
settings. As seen in the “Overview” on page 320, the gain stage is built into the ADC. Gain is achieved by running the
signal through a pipeline stage without converting. Compared to a conversion without gain, each gain multiplication of 2
adds one half ADC clock cycle propagation delay.
Figure 26-15.ADC timing for one single conversion with 2x gain.
Figure 26-16.ADC timing for one single conversion with 8x gain.
CONVERTING BIT
START
IF
ADC SAMPLE
msb 10 9 8 7 6 5 4 3 2 1 lsb
clkADC
123456789
CONVERTING BIT
START
IF
ADC SAMPLE
AMPLIFY
msb 10 9 8 7 6 5 4 3 2 1 lsb
clkADC
123456789
CONVERTING BIT
START
IF
ADC SAMPLE
AMPLIFY
msb 10 9 8 7 6 5 4 3 2 1 lsb
clkADC
123456789
XMEGA B [MANUAL] 329
Atmel-8291C-AVR-XMEGA B -09/2014
Figure 26-17.ADC timing for one single conversion with 64x gain.
26.10 ADC Input Model
The voltage input must charge the sample and hold (S/H) capacitor in the ADC in order to achieve maximum accuracy.
Seen externally, the ADC input consists of an input resistance (Rin = Rchannel + Rswitch) and the S/H capacitor (Csample).
Figure 26-18 on page 329 and Figure 26-19 on page 329 show the ADC input channel.
Figure 26-18.ADC input for single-ended measurements.
Figure 26-19.ADC input for differential measurements and differential measurements with gain.
In order to achieve n bits of accuracy, the source output resistance, Rsource, must be less than the ADC input resistance
on a pin:
where the ADC sample time, TS is one-half the ADC clock cycle given by:
For details on Rchannel, Rswitch, and Csample, refer to the ADC electrical characteristic in the device datasheet.
CONVERTING BIT
START
IF
ADC SAMPLE
AMPLIFY
msb 10 9 8 7 6 5 4 3 2 1 lsb
clkADC
123456789 10
Rsource
Ts
Csample 2
n + 1 ⋅ ln( )
---------------------------------------------- Rchannel – Rswitch ≤ –
Ts
1
2 ⋅ f ADC
≤ ---------------------
XMEGA B [MANUAL] 330
Atmel-8291C-AVR-XMEGA B -09/2014
26.11 DMA Transfer
The DMA controller can be used to transfer ADC conversion results to memory or other peripherals. A new conversion
result can trigger a DMA transaction. Refer to “DMAC - Direct Memory Access Controller” on page 47 for more details on
DMA transfers.
26.12 Interrupts and Events
The ADC can generate interrupt requests and events. The ADC channel has individual interrupt settings and interrupt
vectors. Interrupt requests and events can be generated when an ADC conversion is complete or when an ADC
measurement is above or below the ADC compare register value.
26.13 Calibration
The ADC has built-in linearity calibration. The value from the production test calibration must be loaded from the
signature row and into the ADC calibration register from software to achieve specified accuracy. User calibration of the
linearity is not needed, hence not possible. Offset and gain calibration must be done in software.
26.14 Synchronous Sampling
Starting an ADC conversion can cause an unknown delay between the start trigger or event and the actual conversion
since the peripheral clock is faster than the ADC clock. To start an ADC conversion immediately on an incoming event, it
is possible to flush the ADC of all measurements, reset the ADC clock, and start the conversion at the next peripheral
clock cycle (which then will also be the next ADC clock cycle). If this is done, the ongoing conversions in the ADC will be
lost.
The ADC can be flushed from software, or an incoming event can do this automatically. When this function is used, the
time between each conversion start trigger must be longer than the ADC propagation delay to ensure that one
conversion is finished before the ADC is flushed and the next conversion is started.
It is also important to clear pending events or start ADC conversion commands before doing a flush. If not, pending
conversions will start immediately after the flush.
XMEGA B [MANUAL] 331
Atmel-8291C-AVR-XMEGA B -09/2014
26.15 Register Description – ADC
26.15.1 CTRLA – Control register A TBD TPUBSXMEGA-116
z Bit 7:3 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 2 – CH0START: Channel Start Single Conversion
Setting this bit will start an ADC conversion. Bit is cleared by hardware when the conversion has started. Writing this bit
is equivalent to writing the START bits inside the ADC channel register.
z Bit 1 – FLUSH: Pipeline Flush
Setting this bit will flush the ADC. When this is done, the ADC clock is restarted on the next peripheral clock edge, and
the conversion in progress is aborted and lost.
After the flush and the ADC clock restart, the ADC will resume where it left off; i.e., if any conversions were pending,
these will enter the ADC and complete.
z Bit 0 – ENABLE: Enable
Setting this bit enables the ADC.
26.15.2 CTRLB – ADC Control register B
z Bit 7 – Reserved
This bit is unused and reserved for future use. For compatibility with future devices, always write this bit to zero when this
register is written.
z Bit 6:5 – CURRLIMIT[1:0]: Current Limitation
These bits can be used to limit the current consumption of the ADC by reducing the maximum ADC sample rate. The
available settings are shown in Table 26-1. The indicated current limitations are nominal values. Refer to the device
datasheet for actual current limitation for each setting.
Table 26-1. ADC current limitations.
Bit 7 6 5 4 3 2 1 0
+0x00 – – – – – CH0START FLUSH ENABLE
Read/Write R R R R R R/W R/W R/W
Initial Value 0 0000 0 00
Bit 7 6 5 4 3 2 1 0
+0x01 – CURRLIMIT[1:0] CONVMODE FREERUN RESOLUTION[1:0] –
Read/Write R R/W R/W R/W R/W R/W R/W R
Initial Value 0 0 0 0 0 0 0 0
CURRLIMIT[1:0] Group Configuration Description
00 NO No limit
01 LOW Low current limit, max. sampling rate 225kSPS
10 MED Medium current limit, max. sampling rate 150kSPS
11 HIGH High current limit, max. sampling rate 75kSPS
XMEGA B [MANUAL] 332
Atmel-8291C-AVR-XMEGA B -09/2014
z Bit 4 – CONVMODE: Conversion Mode
This bit controls whether the ADC will work in signed or unsigned mode. By default, this bit is cleared and the ADC is
configured for unsigned mode. When this bit is set, the ADC is configured for signed mode.
z Bit 3 – FREERUN: Free Running Mode
This bit controls the free running mode for the ADC. Once a conversion is finished, the next input will be sampled and
converted.
z Bit 2:1 – RESOLUTION[1:0]: Conversion Result Resolution
These bits define whether the ADC completes the conversion at 12- or 8-bit result resolution. They also define whether
the 12-bit result is left or right adjusted within the 16-bit result registers. See Table 26-2 for possible settings.
Table 26-2. ADC conversion result resolution.
z Bit 0 – Reserved
This bit is unused and reserved for future use. For compatibility with future devices, always write this bit to zero when this
register is written.
26.15.3 REFCTRL – Reference Control register
z Bit 7 – Reserved
This bit is unused and reserved for future use. For compatibility with future devices, always write this bit to zero when this
register is written.
z Bits 6:4 – REFSEL[2:0]: Reference Selection
These bits selects the reference for the ADC according to Table 26-3.
Table 26-3. ADC reference selection.
RESOLUTION[1:0] Group Configuration Description
00 12BIT 12-bit result, right adjusted
01 – Reserved
10 8BIT 8-bit result, right adjusted
11 LEFT12BIT 12-bit result, left adjusted
Bit 7 6 5 4 3 2 1 0
+0x02 – REFSEL[2:0] – – BANDGAP TEMPREF
Read/Write R R/W R/W R/W R R R/W R/W
Initial Value 0 0 0 0 0 0 0 0
REFSEL[2:0] Group Configuration Description
000 INT1V 10/11 of bandgap (1.0V)
001 INTVCC VCC/1.6
010 AREFA External reference from AREF pin on PORT A
011 AREFB External reference from AREF pin on PORT B
100 INTVCC2 VCC/2
101 - 111 – Reserved
XMEGA B [MANUAL] 333
Atmel-8291C-AVR-XMEGA B -09/2014
z Bit 3:2 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 1 – BANDGAP: Bandgap Enable
Setting this bit enables the bandgap for ADC measurement. Note that if any other functions are already using the
bandgap, this bit does not need to be set when the internal 1.00V reference is used for another ADC or if the brownout
detector is enabled.
z Bit 0 – TEMPREF: Temperature Reference Enable
Setting this bit enables the temperature sensor for ADC measurement.
26.15.4 EVCTRL – Event Control register
z Bit 7:5 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 4:3 – EVSEL[1:0]: Event Channel Input Select
These bits select which event channel will trigger the ADC channel. Each setting defines a group of event channels,
where the event channel with the lowest number will trigger ADC channel 0, the next event channel will trigger ADC
channel 1, and so on. See Table 26-4.
Table 26-4. ADC event channel select.
z Bit 2:0 – EVACT[2:0]: Event Mode
These bits select and limit how many of the selected event input channel are used, and also further limit the ADC
channels triggers. They also define more special event triggers as defined in Table 26-5.
Table 26-5. ADC event mode select.
Bit 7 6 5 4 3 2 1 0
+0x03 – – – EVSEL[1:0] EVACT[2:0]
Read/Write R R R R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
EVSEL[1:0] Group Configuration Selected Event Lines
00 0 Event channel 0 selected inputs
01 1 Event channel 1 selected inputs
10 2 Event channel 2 selected inputs
11 3 Event channel 3 selected inputs
EVACT[2:0] Group Configuration Event Input Operation Mode
000 NONE No event inputs
001 CH0 Event channel with the lowest number defined by EVSEL
triggers conversion on ADC channel
010 – Reserved
011 – Reserved
100 – Reserved
XMEGA B [MANUAL] 334
Atmel-8291C-AVR-XMEGA B -09/2014
26.15.5 PRESCALER – Clock Prescaler register
z Bit 7:3 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 2:0 – PRESCALER[2:0]: Prescaler Configuration
These bits define the ADC clock relative to the peripheral clock according to Table 26-6.
Table 26-6. ADC prescaler settings.
26.15.6 INTFLAGS – Interrupt Flag register
z Bit 7:1 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 0 – CH0IF: Interrupt Flags
This flag is set when the ADC conversion is complete. If the ADC is configured for compare mode, the interrupt flag will
be set if the compare condition is met. CH0IF is automatically cleared when the ADC interrupt vector is executed. The
flag can also be cleared by writing a one to its bit location.
101 – Reserved
110 SYNCSWEEP The ADC is flushed and restarted for accurate timing
111 – Reserved
EVACT[2:0] Group Configuration Event Input Operation Mode
Bit 7 6 5 4 3 2 1 0
+0x04 – – – – – PRESCALER[2:0]
Read/Write R R R R R R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
PRESCALER[2:0] Group Configuration Peripheral Clock Division Factor
000 DIV4 4
001 DIV8 8
010 DIV16 16
011 DIV32 32
100 DIV64 64
101 DIV128 128
110 DIV256 256
111 DIV512 512
Bit 7 6 5 4 3 2 1 0
+0x06 – – – – – – – CH0IF
Read/Write R R R R R R R R/W
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 335
Atmel-8291C-AVR-XMEGA B -09/2014
26.15.7 TEMP – Temporary register
z Bit 7:0 – TEMP[7:0]: Temporary bits
This register is used when reading 16-bit registers in the ADC controller. The high byte of the 16-bit register is stored
here when the low byte is read by the CPU. This register can also be read and written from the user software.
For more details on 16-bit register access, refer to “Accessing 16-bit Registers” on page 13.
26.15.8 SAMPCTRL – Sampling time control register
z Bit 7:6 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 5:0 – SAMPVAL[5:0]: sampling time control register
These bits control the ADC sampling time in number of half ADC prescaled clock cycles (depends of ADC_PRESCALER
value), thus controlling the ADC input impedance. Sampling time is set according to the formula:
Sampling time = (SAMPVAL + 1)*(ClkADC /2)
26.15.9 CALL – Calibration Value register Low
The CALL and CALH register pair hold the 12-bit calibration value. The ADC is calibrated during production
programming, and the calibration value must be read from the signature row and written to the CAL register from
software.
z Bit 7:0 – CAL[7:0]: ADC Calibration value
These are the eight lsbs of the 12-bit CAL value.
26.15.10CALH – Calibration Value register High
z Bit 3:0 – CAL[11:8]: Calibration value
These are the four msbs of the 12-bit CAL value.
Bit 7 6 5 4 3 2 1 0
+0x07 TEMP[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0000000
Bit 7 6 5 4 3 2 1 0
+0x08 – – SAMPVAL[5:0]
Read/Write R R R/W R/W R/W R/W R/W R/W
Initial Value 00000000
Bit 7 6 5 4 3 2 1 0
+0x0C CAL[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
+0x0D – – – – CAL[11:8]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 336
Atmel-8291C-AVR-XMEGA B -09/2014
26.15.11CH0RESH – Channel 0 Result register High
The CH0RESL and CH0RESH register pair represents the 16-bit value, CH0RES. For details on reading 16-bit registers,
refer to “Accessing 16-bit Registers” on page 13.
26.15.11.1 12-bit Mode, Left Adjusted
z Bit 7:0 – CHRES[11:4]: Channel Result High byte
These are the eight msbs of the 12-bit ADC result.
26.15.11.2 12-bit Mode, Right Adjusted
z Bit 7:4 – Reserved
These bits will in practice be the extension of the sign bit, CHRES11, when the ADC works in differential mode, and set
to zero when the ADC works in signed mode.
z Bit 3:0 – CHRES[11:8]: Channel Result High byte
These are the four msbs of the 12-bit ADC result.
26.15.11.3 8-bit Mode
z Bit 7:0 – Reserved
These bits will in practice be the extension of the sign bit, CHRES7, when the ADC works in signed mode, and set to zero
when the ADC works in single-ended mode.
26.15.12 CH0RESL – Channel 0 Result register Low
26.15.12.1 12-/8-bit Mode
z Bit 7:0 – CHRES[7:0]: Channel Result Low byte
These are the eight lsbs of the ADC result.
26.15.12.2 12-bit Mode, Left Adjusted
z Bit 7:4 – CHRES[3:0]: Channel Result Low byte
These are the four lsbs of the 12-bit ADC result.
z Bit 3:0 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
Bit 7 6 5 4 3 2 1 0
12-bit, left CHRES[11:4]
12-bit, right – – – – CHRES[11:8]
8-bit – – – – – – – –
Read/Write R R R R R R R R
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
12-/8-bit,
right CHRES[7:0]
12-bit, left CHRES[3:0] – – – –
Read/Write R R R R R R R R
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 337
Atmel-8291C-AVR-XMEGA B -09/2014
26.15.13 CMPH – Compare register High
The CMPH and CMPL register pair represents the 16-bit value, CMP. For details on reading and writing 16-bit registers,
refer to “Accessing 16-bit Registers” on page 13.
z Bit 7:0 – CMP[15:0]: Compare Value High byte
These are the eight msbs of the 16-bit ADC compare value. In signed mode, the number representation is 2's
complement, and the msb is the sign bit.
26.15.14 CMPL – Compare register Low
z Bit 7:0 – CMP[7:0]: Compare Value Low byte
These are the eight lsbs of the 16-bit ADC compare value. In signed mode, the number representation is 2's
complement.
26.16 Register Description - ADC Channel
26.16.1 CTRL – Control Register
z Bit 7 – START: START Conversion on Channel
Setting this bit will start a conversion on the channel. The bit is cleared by hardware when the conversion has started.
Setting this bit when it already is set will have no effect. Writing or reading this bit is equivalent to writing the
CH[3:0]START bits in “CTRLA – Control register A TBD TPUBSXMEGA-116” on page 331.
z Bit 6:5 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 4:2 – GAIN[2:0]: Gain Factor
These bits define the gain factor for the ADC gain stage.
See Table 26-7 on page 338. Gain is valid only with certain MUX settings. See “MUXCTRL – MUX Control registers” on
page 338.
Bit 7 6 5 4 3 2 1 0
+0x19 CMP[15:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 000000
Bit 7 6 5 4 3 2 1 0
+0x18 CMP[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 00000000
Bit 7 6 5 4 3 2 1 0
+0x00 START – – GAIN[2:0] INPUTMODE[1:0]
Read/Write R/W R R R/W R/W R/W R/W R/W
Initial Value 0 0 000000
XMEGA B [MANUAL] 338
Atmel-8291C-AVR-XMEGA B -09/2014
Table 26-7. ADC gain factor
z Bit 1:0 – INPUTMODE[1:0]: Channel Input Mode
These bits define the channel mode.
Table 26-8. Channel input modes, CONVMODE=0 (unsigned mode).
Table 26-9. Channel input modes, CONVMODE=1 (singed mode).
26.16.2 MUXCTRL – MUX Control registers
The MUXCTRL register defines the input source for the channel.
z Bit 7 – Reserved
This bit is unused and reserved for future use. For compatibility with future devices, always write this bit to zero when this
register is written.
GAIN[2:0] Group Configuration Gain Factor
000 1X 1x
001 2X 2x
010 4X 4x
011 8X 8x
100 16X 16x
101 32X 32x
110 64X 64x
111 DIV2 ½x
INPUTMODE[1:0] Group Configuration Description
00 INTERNAL Internal positive input signal
01 SINGLEENDED Single-ended positive input signal
10 – Reserved
11 – Reserved
INPUTMODE[1:0] Group Configuration Description
00 INTERNAL Internal positive input signal
01 SINGLEENDED Single-ended positive input signal
10 DIFF Differential input signal
11 DIFFWGAIN Differential input signal with gain
Bit 7 6 5 4 3 2 1 0
+0x01 – MUXPOS[3:0] MUXNEG[2:0]
Read/Write R R/W R/W R/W R/W R R/W R/W
Initial Value 0 0000000
XMEGA B [MANUAL] 339
Atmel-8291C-AVR-XMEGA B -09/2014
z Bit 6:3 – MUXPOS[3:0]: MUX Selection on Positive ADC Input
These bits define the MUX selection for the positive ADC input. Table 26-10 and Table 26-11 show the possible input
selection for the different input modes.
Table 26-10. ADC MUXPOS configuration when INPUTMODE[1:0] = 00 (internal) is used.
Table 26-11. ADC MUXPOS configuration when INPUTMODE[1:0] = 01 (single-ended) or INPUTMODE[1:0] = 10 (differential)
is used.
Table 26-12. ADC MUXPOS configuration when INPUTMODE[1:0] = 11 (differential with gain) is used.
MUXPOS[3:0] Group Configuration Description
0000 TEMP Temperature reference
0001 BANDGAP Bandgap voltage
0010 SCALEDVCC 1/10 scaled VCC
0011 – Reserved
0100-1111 – Reserved
MUXPOS[3:0] Group Configuration Description
0000 PIN0 ADC0 pin
0001 PIN1 ADC1 pin
0010 PIN2 ADC2 pin
0011 PIN3 ADC3 pin
0100 PIN4 ADC4 pin
0101 PIN5 ADC5 pin
0110 PIN6 ADC6 pin
0111 PIN7 ADC7 pin
1000 PIN8 ADC8 pin
1001 PIN9 ADC9 pin
1010 PIN10 ADC10 pin
1011 PIN11 ADC11 pin
1100 PIN12 ADC12 pin
1101 PIN13 ADC13 pin
1110 PIN14 ADC14 pin
1111 PIN15 ADC15 pin
MUXPOS[3:0] Group Configuration Description
0000 PIN0 ADC0 pin
0001 PIN1 ADC1 pin
0010 PIN2 ADC2 pin
XMEGA B [MANUAL] 340
Atmel-8291C-AVR-XMEGA B -09/2014
Depending on the device pin count and feature configuration, the actual number of analog input pins may be less than
16. Refer to the device datasheet and pin-out description for details.
z Bit 2:0 – MUXNEG[2:0]: MUX Selection on Negative ADC Input
These bits define the MUX selection for the negative ADC input when differential measurements are done. For internal or
single-ended measurements, these bits are not used.
Table 26-13 and Table 26-14 show the possible input sections.
Table 26-13. ADC MUXNEG configuration, INPUTMODE[1:0] = 10, differential without gain.
Table 26-14. ADC MUXNEG configuration, INPUTMODE[1:0] = 11, differential with gain.
0011 PIN3 ADC3 pin
0100 PIN4 ADC4 pin
0101 PIN5 ADC5 pin
0110 PIN6 ADC6 pin
0111 PIN7 ADC7 pin
1XXX – Reserved
MUXNEG[2:0] Group Configuration Analog Input
000 PIN0 ADC0 pin
001 PIN1 ADC1 pin
010 PIN2 ADC2 pin
011 PIN3 ADC3 pin
100 – Reserved
101 GND PAD ground
110 – Reserved
111 INTGND Internal ground
MUXNEG[2:0] Group Configuration Analog Input
000 PIN4 ADC4 pin
001 PIN5 ADC5 pin
010 PIN6 ADC6 pin
011 PIN7 ADC7 pin
100 INTGND Internal ground
101 – Reserved
110 – Reserved
111 GND PAD ground
MUXPOS[3:0] Group Configuration Description
XMEGA B [MANUAL] 341
Atmel-8291C-AVR-XMEGA B -09/2014
26.16.3 INTCTRL – Interrupt Control registers
z Bits 7:4 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 3:2 – INTMODE: Interrupt Mode
These bits select the interrupt mode for the channel according to Table 26-5.
Table 26-15. ADC interrupt mode.
z Bits 1:0 – INTLVL[1:0]: Interrupt Priority Level and Enable
These bits enable the ADC channel interrupt and select the interrupt level, as described in “Interrupts and Programmable
Multilevel Interrupt Controller” on page 115. The enabled interrupt will be triggered for conditions when the IF bit in the
INTFLAGS register is set.
26.16.4 INTFLAGS – Interrupt Flag registers
z Bit 7:1 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 0 – IF: Interrupt Flag
The interrupt flag is set when the ADC conversion is complete. If the channel is configured for compare mode, the flag
will be set if the compare condition is met. IF is automatically cleared when the ADC channel interrupt vector is executed.
The bit can also be cleared by writing a one to the bit location.
Bit 7 6 5 4 3 2 1 0
+0x02 – – – – INTMODE[1:0} INTLVL[1:0]
Read/Write R R R R R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
INTMODE[1:0] Group Configuration Interrupt Mode
00 COMPLETE Conversion complete
01 BELOW Compare result below threshold
10 – Reserved
11 ABOVE Compare result above threshold
Bit 7 6 5 4 3 2 1 0
+0x03 – – – – – – – IF
Read/Write R R R R R R R R/W
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 342
Atmel-8291C-AVR-XMEGA B -09/2014
26.16.5 RESH – Result register High
For all result registers and with any ADC result resolution, a signed number is represented in 2’s complement form, and
the msb represents the sign bit.
The RESL and RESH register pair represents the 16-bit value, ADCRESULT. Reading and writing 16-bit values require
special attention. Refer to “Accessing 16-bit Registers” on page 13 for details.
26.16.5.1 12-bit Mode, Left Adjusted
z Bit 7:0 – RES[11:4]: Channel Result High byte
These are the eight msbs of the 12-bit ADC result.
26.16.5.2 12-bit Mode, Right Adjusted
z Bit 7:4 – Reserved
These bits will in practice be the extension of the sign bit, CHRES11, when the ADC works in differential mode, and set
to zero when the ADC works in signed mode.
z Bits 3:0 – RES[11:8]: Channel Result High bits
These are the four msbs of the 12-bit ADC result.
26.16.5.3 8-bit Mode
z Bit 7:0 – Reserved
These bits will in practice be the extension of the sign bit, CHRES7, when the ADC works in signed mode, and set to zero
when the ADC works in single-ended mode.
26.16.6 RESL – Result register Low
26.16.6.1 12-/8-bit Mode
z Bit 7:0 – RES[7:0]: Result Low byte
These are the eight lsbs of the ADC result.
26.16.6.2 12-bit Mode, Left Adjusted
z Bit 7:4 – RES[3:0]: Result Low bits
These are the four lsbs of the 12-bit ADC result.
z Bit 3:0 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
Bit 7 6 5 4 3 2 1 0
12-bit, left.
+0x05
RES[11:4]
12-bit, right – – – – RES[11:8]
8-bit – – – – – – – –
Read/Write R R R R R R R R
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
12-/8-bit,
right +0x04 RES[7:0]
12-bit, left. RES[3:0] – – – –
Read/Write R R R R R R R R
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 343
Atmel-8291C-AVR-XMEGA B -09/2014
26.16.7 SCAN – Input Channel Scan register
Scan is enabled when COUNT is set differently than 0.
z Bit 7:4 – OFFSET[3:0]: Positive MUX Setting Offset
The channel scan is enabled when COUNT != 0 and this register contains the offset for the next input source to be
converted on ADC channel. The actual MUX setting for positive input equals MUXPOS + OFFSET. The value is
incremented after each conversion until it reaches the maximum value given by COUNT. When OFFSET is equal to
COUNT, OFFSET will be cleared on the next conversion.
z Bit 3:0 – COUNT[3:0]: Number of Input Channels Included in Scan
This register gives the number of input sources included in the channel scan. The number of input sources included is
COUNT + 1. The input channels included are the range from MUXPOS to MUXPOS + COUNT.
Bit 7 6 5 4 3 2 1 0
+0x06 OFFSET[3:0] COUNT[3:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 344
Atmel-8291C-AVR-XMEGA B -09/2014
26.17 Register Summary – ADC
This is the register summary when the ADC is configured to give standard 12-bit results. The register summaries for 8-bit and 12-
bit left adjusted will be similar, but with some changes in the result registers, CH0RESH and CH0RESL.
26.18 Register Summary – ADC Channel
26.19 Interrupt vector Summary
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
+0x00 CTRLA – – – – – CH0STAR FLUSH ENABLE 331
+0x01 CTRLB – CURRLIMIT[1:0] CONVMO FREERUN RESOLUTION[1:0] – 331
+0x02 REFCTRL – REFSEL[2:0] – – BANDGAP TEMPREF 332
+0x03 EVCTRL – – – EVSEL[1:0] EVACT[2:0] 333
+0x04 PRESCALER – – – – – PRESCALER[2:0] 334
+0x05 Reserved – – – – – – – –
+0x06 INTFLAGS – – – – – – – CH0IF 334
+0x07 TEMP TEMP[7:0] 335
+0x08 SAMPCTRL – – SAMPVAL[5:0] 335
+0x09 Reserved – – – – – – – –
+0x0A Reserved – – – – – – – –
+0x0B Reserved – – – – – – – –
+0x0C CALL CAL[7:0] 335
+0x0D CALH – – – – CAL[11:8]
+0x0E Reserved – – – – – – – –
+0x0F Reserved – – – – – – – –
+0x10 CH0RESL CH0RES[7:0] 336
+0x11 CH0RESH CH0RES[15:8] 336
+0x12 Reserved – – – – – – – –
+0x13 Reserved – – – – – – – –
+0x14 Reserved – – – – – – – –
+0x15 Reserved – – – – – – – –
+0x16 Reserved – – – – – – – –
+0x17 Reserved – – – – – – – –
+0x18 CMPL CMP[7:0] 337
+0x19 CMPH CMP[15:8] 337
+0x1A Reserved – – – – – – – –
+0x1B Reserved – – – – – – – –
+0x1C Reserved – – – – – – – –
+0x1D Reserved – – – – – – – –
+0x1E Reserved – – – – – – – –
+0x1F Reserved – – – – – – – –
+0x20 CH0 Offset Offset address for ADC channel
+0x28 Reserved – – – – – – – –
+0x30 Reserved – – – – – – – –
+0x38 Reserved – – – – – – – –
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
+0x00 CTRL START – – GAIN[2:0] INPUTMODE[1:0] 337
+0x01 MUXCTRL – MUXPOS[3:0] MUXNEG[2:0] 338
+0x02 INTCTRL – – – – INTMODE[1:0] INTLVL[1:0] 341
+0x03 INTFLAGS – – – – – – – IF 341
+0x04 RESL RES[7:0] 342
+0x05 RESH RES[15:8] 342
+0x06 SCAN OFFSET COUNT 342
+0x07 Reserved – – – – – – – –
Offset Source Interrupt Description
0x00 CH0 Analog-to-digital converter channel 0 interrupt vector
XMEGA B [MANUAL] 345
Atmel-8291C-AVR-XMEGA B -09/2014
27. AC – Analog Comparator
27.1 Features
z Selectable hysteresis
z None
z Small
z Large
z Analog comparator output available on pin
z Flexible input selection
z All pins on the port
z Bandgap reference voltage
z A 64-level programmable voltage scaler of the internal AVCC voltage
z Interrupt and event generation on:
z Rising edge
z Falling edge
z Toggle
z Window function interrupt and event generation on:
z Signal above window
z Signal inside window
z Signal below window
z Constant current source with configurable output pin selection
27.2 Overview
The analog comparator (AC) compares the voltage levels on two inputs and gives a digital output based on this
comparison. The analog comparator may be configured to generate interrupt requests and/or events upon several
different combinations of input change.
The analog comparator hysteresis can be adjusted in order to achieve the optimal operation for each application.
The input selection includes analog port pins, several internal signals, and a 64-level programmable voltage scaler. The
analog comparator output state can also be output on a pin for use by external devices.
A constant current source can be enabled and output on a selectable pin. This can be used to replace, for example,
external resistors used to charge capacitors in capacitive touch sensing applications.
The analog comparators are always grouped in pairs on each port. These are called analog comparator 0 (AC0) and
analog comparator 1 (AC1). They have identical behavior, but separate control registers. Used as pair, they can be set in
window mode to compare a signal to a voltage range instead of a voltage level.
XMEGA B [MANUAL] 346
Atmel-8291C-AVR-XMEGA B -09/2014
Figure 27-1. Analog comparator overview.
27.3 Input Sources
Each analog comparator has one positive and one negative input. Each input may be chosen from a selection of analog
input pins and internal inputs such as a AVCC voltage scaler. The digital output from the analog comparator is one when
the difference between the positive and the negative input voltage is positive, and zero otherwise.
27.3.1 Pin Inputs
Any of analog input pins on the port can be selected as input to the analog comparator.
27.3.2 Internal Inputs
Two internal inputs are available for the analog comparator:
z Bandgap reference voltage
z Voltage scaler, which provides a 64-level scaling of the internal AVCC voltage
27.4 Signal Compare
In order to start a signal comparison, the analog comparator must be configured with the preferred properties and inputs
before the module is enabled. The result of the comparison is continuously updated and available for application
software and the event system.
27.5 Interrupts and Events
The analog comparator can be configured to generate interrupts when the output toggles, when the output changes from
zero to one (rising edge), or when the output changes from one to zero (falling edge). Events are generated at all times
for the same condition as the interrupt, regardless of whether the interrupt is enabled or not.
ACnMUXCTRL ACnCTRL
Interrupt
Mode
Enable
Enable
Hysteresis
Hysteresis
AC1OUT
WINCTRL
Interrupt
Sensititivity
Control
&
Window
Function
Events
Interrupts
AC0OUT
Pin Input
Pin Input
Pin Input
Pin Input
Voltage
Scaler
Bandgap
+
AC0
-
+
AC1
-
XMEGA B [MANUAL] 347
Atmel-8291C-AVR-XMEGA B -09/2014
27.6 Window Mode
Two analog comparators on the same port can be configured to work together in window mode. In this mode, a voltage
range is defined, and the analog comparators give information about whether an input signal is within this range or not.
Figure 27-2. The Analog comparators in window mode.
27.7 Input Hysteresis
Application software can select between no-, low-, and high hysteresis for the comparison. Applying a hysteresis will help
prevent constant toggling of the output that can be caused by noise when the input signals are close to each other.
AC0
+
-
AC1
+
-
Input signal
Upper limit of window
Lower limit of window
Interrupt
sensitivity
control
Interrupts
Events
XMEGA B [MANUAL] 348
Atmel-8291C-AVR-XMEGA B -09/2014
27.8 Register Description
27.8.1 ACnCTRL – Analog Comparator n Control register
z Bit 7:6 – INTMODE[1:0]: Interrupt Modes
These bits configure the interrupt mode for analog comparator n according to Table 27-1.
Table 27-1. Interrupt settings.
z Bit 5:4 – INTLVL[1:0]: Interrupt Level
These bits enable the analog comparator n interrupt and select the interrupt level, as described in “Interrupts and
Programmable Multilevel Interrupt Controller” on page 115. The enabled interrupt will trigger according to the INTMODE
setting.
z Bit 3 – Reserved
This bit is unused and reserved for future use. For compatibility with future devices, always write this bit to zero when this
register is written.
z Bit 2:1 – HYSMODE[1:0]: Hysteresis Mode Select
These bits select the hysteresis mode according to Table 27-2. For details on actual hysteresis levels, refer to the device
datasheet.
Table 27-2. Hysteresis settings.
z Bit 0 – ENABLE: Enable
Setting this bit enables analog comparator n.
Bit 7 6 5 4 3 2 1 0
+0x00 / +0x01 INTMODE[1:0] INTLVL[1:0] – HYSMODE[2:0] ENABLE
Read/Write R/W R/W R/W R/W R R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
INTMODE[1:0] Group Configuration Description
00 BOTHEDGES Comparator interrupt or event on output toggle
01 – Reserved
10 FALLING Comparator interrupt or event on falling output edge
11 RISING Comparator interrupt or event on rising output edge
HYSMODE[1:0] Group Configuration Description
00 NO No hysteresis
01 SMALL Small hysteresis
10 LARGE Large hysteresis
11 – Reserved
XMEGA B [MANUAL] 349
Atmel-8291C-AVR-XMEGA B -09/2014
27.8.2 ACnMUXCTRL – Analog Comparator n Mux Control register
z Bit 7:6 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 5:3 – MUXPOS[2:0]: Positive Input MUX Selection
These bits select which input will be connected to the positive input of analog comparator n according to Table 27-3.
Table 27-3. Positive input MUX selection.
z Bit 2:0 – MUXNEG[2:0]: Negative Input MUX Selection
These bits select which input will be connected to the negative input of analog comparator n according to Table 27-4.
Table 27-4. Negative input MUX selection.
Bit 7 6 5 4 3 2 1 0
+0x02 / +0x03 – – MUXPOS[2:0] MUXNEG[2:0]
Read/Write R R R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
MUXPOS[2:0] Group Configuration Description
000 PIN0 Pin 0
001 PIN1 Pin 1
010 PIN2 Pin 2
011 PIN3 Pin 3
100 PIN4 Pin 4
101 PIN5 Pin 5
110 PIN6 Pin 6
111 – Reserved
MUXNEG[2:0] Group Configuration Negative Input MUX Selection
000 PIN0 Pin 0
001 PIN1 Pin 1
010 PIN3 Pin 3
011 PIN5 Pin 5
100 PIN7 Pin 7
101 – Reserved
110 BANDGAP Internal bandgap voltage
111 SCALER AVCC voltage scaler
XMEGA B [MANUAL] 350
Atmel-8291C-AVR-XMEGA B -09/2014
27.8.3 CTRLA – Control register A
z Bit 7:2 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 1 – AC1OUT: Analog Comparator 1 Output
Setting this bit makes the output of AC1 available on pin 6 of the port.
z Bit 0 – AC0OUT: Analog Comparator 0 Output
Setting this bit makes the output of AC0 available on pin 7 of the port.
27.8.4 CTRLB – Control register B
z Bit 7:6 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 5:0 – SCALEFAC[5:0]: Voltage Scaling Factor
These bits define the scaling factor for the AVcc voltage scaler. The input to the analog comparator, VSCALE, is:
27.8.5 WINCTRL – Window Function Control register
z Bit 7:5 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 4 – WEN: Window Mode Enable
Setting this bit enables the analog comparator window mode.
z Bits 3:2 – WINTMODE[1:0]: Window Interrupt Mode Settings
These bits configure the interrupt mode for the analog comparator window mode according to Table 27-5.
Bit 7 6 5 4 3 2 1 0
+0x04 – – – – – – AC1OUT AC0OUT
Read/Write R R R R R R R/W R/W
Initial Value 0 0 000000
Bit 7 6 5 4 3 2 1 0
+0x05 – – SCALEFAC[5:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 00000000
VSCALE
V CC ⋅ ( ) SCALEFAC + 1
64 = -------------------------------------------------------------
Bit 7 6 5 4 3 2 1 0
+0x06 – – – WEN WINTMODE[1:0] WINTLVL[1:0]
Read/Write R R R R/W R/W R/W R/W R/W
Initial Value 0 0 000000
XMEGA B [MANUAL] 351
Atmel-8291C-AVR-XMEGA B -09/2014
Table 27-5. Window mode interrupt settings.
z Bits 1:0 – WINTLVL[1:0]: Window Interrupt Enable
These bits enable the analog comparator window mode interrupt and select the interrupt level, as described in “Interrupts
and Programmable Multilevel Interrupt Controller” on page 115. The enabled interrupt will trigger according to the
WINTMODE setting.
27.8.6 STATUS – Status register
z Bits 7:6 – WSTATE[1:0]: Window Mode Current State
These bits show the current state of the signal if window mode is enabled according to Table 27-6.
Table 27-6. Window mode current state.
z Bit 5 – AC1STATE: Analog Comparator 1 Current State
This bit shows the current state of the output signal from AC1.
z Bit 4 – AC0STATE: Analog Comparator 0 Current State
This bit shows the current state of the output signal fromAC0.
z Bit 3 – Reserved
This bit is unused and reserved for future use. For compatibility with future devices, always write this bit to zero when this
register is written.
z Bit 2 – WIF: Analog Comparator Window Interrupt Flag
This is the interrupt flag for the window mode. WIF is set according to the WINTMODE setting in the “WINCTRL –
Window Function Control register” on page 350.
This flag is automatically cleared when the analog comparator window interrupt vector is executed. The flag can also be
cleared by writing a one to its bit location.
z Bit 1 – AC1IF: Analog Comparator 1 Interrupt Flag
This is the interrupt flag for AC1. AC1IF is set according to the INTMODE setting in the corresponding “ACnCTRL –
Analog Comparator n Control register” on page 348.
WINTMODE[1:0] Group Configuration Description
00 ABOVE Interrupt on signal above window
01 INSIDE Interrupt on signal inside window
10 BELOW Interrupt on signal below window
11 OUTSIDE Interrupt on signal outside window
Bit 7 6 5 4 3 2 1 0
+0x07 WSTATE[1:0] AC1STATE AC0STATE – WIF AC1IF AC0IF
Read/Write R/W R/W R/W R/W R R/W R/W R/W
Initial Value 0 0 000000
WSTATE[1:0] Group Configuration Description
00 ABOVE Signal is above window
01 INSIDE Signal is inside window
10 BELOW Signal is below window
11 OUTSIDE Signa is outside window
XMEGA B [MANUAL] 352
Atmel-8291C-AVR-XMEGA B -09/2014
This flag is automatically cleared when the analog comparator 1 interrupt vector is executed. The flag can also be
cleared by writing a one to its bit location.
z Bit 0 – AC0IF: Analog Comparator 0 Interrupt Flag
This is the interrupt flag for AC0. AC0IF is set according to the INTMODE setting in the corresponding “ACnCTRL –
Analog Comparator n Control register” on page 348.
This flag is automatically cleared when the analog comparator 0 interrupt vector is executed. The flag can also be
cleared by writing a one to its bit location.
27.8.7 CURRCTRL – Current Source Control register
z Bit 7 – CURRENT: Current Source Enable
Setting this bit to one will enable the constant current source.
z Bit 6:2 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 1 – AC1CURR: AC1 Current Source Output Enable
Setting this bit to one will enable the constant current source output on the pin selected by MUXNEG in AC1MUXTRL.
z Bit 0 – AC0CURR: AC0 Current Source Output Enable
Setting this bit to one will enable the constant current source output on the pin selected by MUXNEG in AC0MUXTRL.
27.8.8 CURRCALIB – Current Source Calibration register
z Bits 7:4 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero
when this register is written.
z Bit 3:0 – CALIB[3:0]: Current Source Calibration
The constant current source is calibrated during production. A calibration value can be read from the signature row and
written to the CURRCALIB register from software. Refer to device data sheet for default calibration values and user
calibration range.
Bit 7 6 5 4 3 2 1 0
+0x08 CURRENT – – – – – AC1CURR AC0CURR
Read/Write R/W R R R R R R/W R/W
Initial Value 0 0 0000 0 0
Bit 7 6 5 4 3 2 1 0
+0x09 – – – – CALIB[3:0]
Read/Write R R R R R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
XMEGA B [MANUAL] 353
Atmel-8291C-AVR-XMEGA B -09/2014
27.9 Register Summary
27.10 Interrupt vector Summary
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
+0x00 AC0CTRL INTMODE[1:0] INTLVL[1:0] – HYSMODE[1:0] ENABLE 348
+0x01 AC1CTRL INTMODE[1:0] INTLVL[1:0] – HYSMODE[1:0] ENABLE 348
+0x02 AC0MUXCTR – – MUXPOS[2:0] MUXNEG[2:0] 349
+0x03 AC1MUXCTR – – MUXPOS[2:0] MUXNEG[2:0] 349
+0x04 CTRLA – – – – – – AC1OUT ACOOUT 350
+0x05 CTRLB – – SCALEFAC5:0] 350
+0x06 WINCTRL – – – WEN WINTMODE[1:0] WINTLVL[1:0] 350
+0x07 STATUS WSTATE[1:0] AC1STATE AC0STATE – WIF AC1IF AC0IF 351
+0x08 CURRCTRL CURRENT – – – – – AC1CURR AC0CURR 352
+0x09 CURRCALIB – – – – CALIB[3:0] 352
Offset Source Interrupt Description
0x00 COMP0_vect Analog comparator 0 interrupt vector
0x02 COMP1_vect Analog comparator 1 interrupt vector
0x04 WINDOW_vect Analog comparator window interrupt vector
XMEGA B [MANUAL] 354
Atmel-8291C-AVR-XMEGA B -09/2014
28. IEEE 1149.1 JTAG Boundary Scan Interface
28.1 Features
• JTAG (IEEE Std. 1149.1-2001 compliant) interface
• Boundary scan capabilities according to the JTAG standard
• Full scan of all I/O pins
• Supports the mandatory SAMPLE, IDCODE, PRELOAD, EXTEST, and BYPASS instructions
• Supports the optional HIGHZ and CLAMP instructions
• Supports the AVR-specific PDICOM instruction for accessing the PDI
28.2 Overview
The JTAG interface is mainly intended for testing PCBs by using the JTAG boundary scan capability. Secondarily, the
JTAG interface is used to access the Program and Debug Interface (PDI) in its optional JTAG mode.
The boundary scan chain has the capability of driving and observing the logic levels on I/O pins. At the system level, all
microcontroller or board components having JTAG capabilities are connected serially by the TDI/TDO signals to form a
long shift register. An external controller sets up the devices to drive values at their output pins, and observes the input
values received from other devices. The controller compares the received data with the expected result. In this way,
boundary scan method provides a mechanism for testing the interconnections and integrity of components on printed
circuit boards by using only the four test access port (TAP) signals.
The IEEE Std. 1149.1-2001 defined mandatory JTAG instructions, IDCODE, BYPASS, SAMPLE/ PRELOAD, and
EXTEST, together with the optional CLAMP and HIGHZ instructions can be used for testing the printed circuit board.
Alternatively, the HIGHZ instruction can be used to place all I/O pins in an inactive drive state, while bypassing the
boundary scan register chain of the chip.
The AVR-specific PDICOM instruction makes it possible to use the PDI data register as an interface for accessing the
PDI for programming and debugging. This provides an alternative way to access internal programming and debugging
resources by using the JTAG interface. For more details on PDI, programming, and on-chip debugging, refer to “Program
and Debug Interface” on page 393.
The JTAGEN fuse must be programmed and the JTAGD bit in the MCUCR register must be cleared to enable the JTAG
interface and TAP. See “FUSEBYTE4 – Fuse Byte4” on page 31, and “MCUCR – Control register” on page 45 for more
details.
When using the JTAG interface for boundary scan, the JTAG TCK clock frequency can be higher than the internal device
frequency. A system clock in the device is not required for boundary scan.
28.3 TAP - Test Access Port
The JTAG interface requires and uses four device I/O pins. In JTAG terminology, these pins constitute the test access
port, or TAP. These pins are:
z TMS: Test mode select. The pin is used for navigating through the TAP-controller state machine
z TCK: Test clock. This is the JTAG clock signal, and all operation is synchronous to TCK
z TDI: Test data in. Serial input data to be shifted in to the instruction register or data register (scan chains)
z TDO: Test data out. Serial output data from the instruction register or data register
The IEEE Std. 1149.1-2001 also specifies an optional test reset signal, TRST. This signal is not available.
When the JTAGEN fuse is unprogrammed or the JTAG disable bit is set, the JTAG interface is disabled. The four TAP
pins are normal port pins, and the TAP controller is in reset. When enabled, the input TAP signals are internally pulled
high and JTAG is enabled for boundary scan operations.
XMEGA B [MANUAL] 355
Atmel-8291C-AVR-XMEGA B -09/2014
Figure 28-1. TAP controller state diagram.
The TAP controller is a 16-state, finite state machine that controls the operation of the boundary scan circuitry. The state
transitions shown in Figure 28-1 depend on the signal present on TMS (shown adjacent to each state transition) at the
time of the rising edge on TCK. The initial state after a power-on reset is the test logic reset state.
Assuming the present state is run test/idle, a typical scenario for using the JTAG interface is:
z At the TMS input, apply the sequence 1, 1, 0, 0 at the rising edges of TCK to enter the shift instruction register, or
shift IR, state. While in this state, shift the four bits of the JTAG instruction into the JTAG instruction register from
the TDI input at the rising edge of TCK. The TMS input must be held low during input of the 3 lsbs in order to
remain in the shift IR state. The msb of the instruction is shifted in when this state is left by setting TMS high. While
the instruction is shifted in from the TDI pin, the captured IR state, 0x01, is shifted out on the TDO pin. The JTAG
instruction selects a particular data register as the path between TDI and TDO and controls the circuitry
surrounding the selected data register
z Apply the TMS sequence 1, 1, 0 to reenter the run test/idle state. The instruction is latched onto the parallel output
from the shift register path in the update IR state. The exit IR, pause IR, and exit2 IR states are used only for
navigating the state machine
z At the TMS input, apply the sequence 1, 0, 0 at the rising edges of TCK to enter the shift data register, or shift DR,
state. While in this state, upload the selected data register (selected by the present JTAG instruction in the JTAG
instruction register) from the TDI input at the rising edge of TCK. In order to remain in the shift DR state, the TMS
input must be held low during the input of all bits except the msb. The msb of the data is shifted in when this state
is left by setting TMS high. While the data register is shifted in from the TDI pin, the parallel inputs to the data
register captured in the capture DR state are shifted out on the TDO pin
z Apply the TMS sequence 1, 1, 0 to reenter the run test/idle state. If the selected data register has a latched parallel
output, the latching takes place in the update DR state. The exit DR, pause DR, and exit2 DR states are used only
for navigating the state machine.
XMEGA B [MANUAL] 356
Atmel-8291C-AVR-XMEGA B -09/2014
As shown in the state diagram, the run test/idle state need not be entered between selecting JTAG instructions and using
data registers.
Note: Independently of the initial state of the TAP controller, the test logic reset state can always be entered by holding
TMS high for five TCK clock periods.
28.4 JTAG Instructions
The instruction register is four bits wide. Listed below are the JTAG instructions for boundary scan operation and the
PDICOM instruction used for accessing the PDI in JTAG mode.
The lsb is shifted in and out first for all shift registers.
The opcode for each instruction is shown beside the instruction name in hex format. The text describes which data
register is selected as the path between TDI and TDO for each instruction.
28.4.1 EXTEST; 0x1
EXTEST is the instruction for selecting the boundary scan chain as the data register for testing circuitry external to the
AVR XMEGA device package. The instruction is used for sampling external pins and loading output pins with data. For
the I/O port pins, both output control (DIR) and output data (OUT) are controllable via the scan chain, while the output
control and actual pin value are observable. The contents of the latched outputs of the boundary scan chain are driven
out as soon as the JTAG instruction register is loaded with the EXTEST instruction.
The active states are:
z Capture DR: Data on the external pins are sampled into the boundary scan chain
z Shift DR: Data in the Boundary-scan Chain are shifted by the TCK input
z Update DR: Data from the scan chain are applied to output pins
28.4.2 IDCODE; 0x3
IDCODE is the instruction for selecting the 32-bit ID register as the data register. The ID register consists of a version
number, a device number, and the manufacturer code chosen by the Joint Electron Devices Engineering Council
(JEDEC). This is the default instruction after power up.
The active states are:
z Capture DR: Data in the IDCODE register are sampled into the device identification register
z Shift DR: The IDCODE scan chain is shifted by the TCK input
28.4.3 SAMPLE/PRELOAD; 0x2
SAMPLE/PRELOAD is the instruction for preloading the output latches and taking a snapshot of the input/output pins
without affecting system operation. However, the output latches are not connected to the pins. The boundary scan chain
is selected as the data register. Since each of the SAMPLE and PRELOAD instructions implements the functionality of
the other, they share a common binary value, and can be treated as a single, merged instruction.
The active states are:
z Capture DR: Data on the external pins are sampled into the boundary scan chain
z Shift DR: The boundary scan chain is shifted by the TCK input
z Update DR: Data from the boundary scan chain are applied to the output latches, but the output latches are not
connected to the pins
28.4.4 BYPASS; 0xf
BYPASS is the instruction for selecting the bypass register for the data register. This instruction can be issued to make
the shortest possible scan chain through the device.
XMEGA B [MANUAL] 357
Atmel-8291C-AVR-XMEGA B -09/2014
The active states are:
z Capture DR: Loads a zero into the bypass register
z Shift DR: The bypass register cell between TDI and TDO is shifted
28.4.5 CLAMP; 0x4
CLAMP is an optional instruction that allows the state of the input/output pins to be determined from the preloaded output
latches. The instruction allows static pin values to be applied via the boundary scan registers while bypassing these
registers in the scan path, efficiently shortening the total length of the serial test path. The bypass register is selected as
the data register.
The active states are:
z Capture DR: Loads a zero into the bypass register
z Shift DR: The bypass register cell between TDI and TDO is shifted
28.4.6 HIGHZ; 0x5
HIGHZ is an optional instruction for putting all outputs in an inactive drive state (e.g., high impedance). The bypass
register is selected as the data register.
The active states are:
z Capture DR: Loads a zero into the bypass register
z Shift DR: The bypass register cell between TDI and TDO is shifted
28.4.7 PDICOM; 0x7
PDICOM is an AVR XMEGA specific instruction for using the JTAG TAP as an alternative interface to the PDI.
The active states are:
z Capture DR: Parallel data from the PDI are sampled into the PDICOM data register
z Shift DR: The PDICOM data register is shifted by the TCK input
z Update DR: Commands or operands are parallel-latched from the PDICOM data register into the PDI
28.5 Boundary Scan Chain
The boundary scan chain has the capability of driving and observing the logic levels on the I/O pins. To ensure a
predictable device behavior during and after the EXTEST, CLAMP, and HIGHZ instructions, the device is automatically
put in reset. During active reset, the external oscillators, analog modules, and non-default port pin settings (like pullup/down,
bus-keeper, wired-AND/OR) are disabled. It should be noted that the current device and port pin state are
unaffected by the SAMPLE and PRELOAD instructions.
28.5.1 Scanning the Port Pins
Figure 28-2 on page 358 shows the boundary scan cell used for all the bidirectional port pins. This cell is able to control
and observe both pin direction and pin value via a two-stage shift register. When no alternate port function is present,
output control corresponds to the DIR register value, output data corresponds to the OUT register value, and input data
corresponds to the IN register value (tapped before the input inverter and input synchronizer). Mode represents either an
active CLAMP or EXTEST instruction, while shift DR is set when the TAP controller is in its shift DR state.
XMEGA B [MANUAL] 358
Atmel-8291C-AVR-XMEGA B -09/2014
Figure 28-2. Boundary scan cell for bi-directional port pin.
28.5.2 Scanning the PDI Pins
Two observe-only cells are inserted to make the combined RESET and PDI_CLK pin and the PDI_DATA pin observable.
Even though the PDI_DATA pin is bidirectional, it is only made observable in order to avoid any extra logic on the
PDI_DATA output path.
Figure 28-3. An observe-only input cell.
Q D
D Q D Q
D Q
Input Data
(IN)
Output Data
(IN)
Output Control
(DIR)
Mode
Pn
Shift DR To next cell
From last cell Clock DR Update DR
0
1
0
1
0
0
1
1
En
D Q
From last
cell
Clock DR
To next cell
To system
logic
From system
pin
Shift DR
1
0
XMEGA B [MANUAL] 359
Atmel-8291C-AVR-XMEGA B -09/2014
28.6 Data Registers
The supported data registers that can be connected between TDI and TDO are:
z Bypass register (Ref: register A in Figure 28-4 on page 359).
z Device identification register (Ref: register C in Figure 28-4 on page 359).
z Boundary scan chain (Ref: register D in Figure 28-4 on page 359).
z PDICOM data register (Ref: register B in Figure 28-4 on page 359)
Figure 28-4. JTAG data register overview.
28.6.1 Bypass Register
The bypass register consists of a single shift register stage. When the bypass register is selected as the path between
TDI and TDO, the register is reset to 0 when leaving the capture DR controller state. The bypass register can be used to
shorten the scan chain on a system when the other devices are to be tested.
28.6.2 Device Identification Register
28.6.2.1 Version
Version is a 4-bit number identifying the revision of the device. The JTAG version number follows the revision of the
device. Revision A is 0x0, revision B is 0x1, and so on.
28.6.2.2 Part Number
The part number is a 16-bit code identifying the device. Refer to the device data sheets to find the correct number.
28.6.2.3 Manufacturer ID
The manufacturer ID is an 11-bit code identifying the manufacturer. For Atmel, this code is 0x01F.
D
D
TDI
A
B B B
C C C C
TDO
TMS
D
D
D
D
D
D
D D D
I/O PORTS
PDI JTAG
TCK to all TCK
registers
Internal registers
JTAG Boundary-scan chain
TAP
CTRL
MSB LSB
Bit 31 28 27 12 11 1 0
Device ID Version Part Number Manufacturer ID 1
4 bits 16 bits 11 bits 1 bit
XMEGA B [MANUAL] 360
Atmel-8291C-AVR-XMEGA B -09/2014
28.6.3 Boundary Scan Chain
The boundary scan chain has the capability of driving and observing the logic levels on all I/O pins. Refer to “Boundary
Scan Chain” on page 357 for a complete description.
28.6.4 PDICOM Data Register
The PDICOM data register is a 9-bit wide register used for serial-to-parallel and parallel-to-serial conversions of data
between the JTAG TAP and the PDI. For details, refer to “Program and Debug Interface” on page 393.
Document Footer Title [PRELIMINARY DATASHEET] 361
Atmel-8291C-AVR-XMEGA B -09/2014
29. Program and Debug Interface
29.1 Features
z Programming
̶ External programming through PDI or JTAG interfaces
z Minimal protocol overhead for fast operation
z Built-in error detection and handling for reliable operation
̶ Boot loader support for programming through any communication interface
z Debugging
̶ Nonintrusive, real-time, on-chip debug system
̶ No software or hardware resources required from device except pin connection
̶ Program flow control
z Go, Stop, Reset, Step Into, Step Over, Step Out, Run-to-Cursor
̶ Unlimited number of user program breakpoints
̶ Unlimited number of user data breakpoints, break on:
z Data location read, write, or both read and write
z Data location content equal or not equal to a value
z Data location content is greater or smaller than a value
z Data location content is within or outside a range
̶ No limitation on device clock frequency
z Program and Debug Interface (PDI)
̶ Two-pin interface for external programming and debugging
̶ Uses the Reset pin and a dedicated pin
̶ No I/O pins required during programming or debugging
z JTAG interface
̶ Four-pin, IEEE Std. 1149.1 compliant interface for programming and debugging
̶ Boundary scan capabilities according to IEEE Std. 1149.1 (JTAG)
29.2 Overview
The Program and Debug Interface (PDI) is an Atmel proprietary interface for external programming and on-chip
debugging of a device.
The PDI supports fast programming of nonvolatile memory (NVM) spaces; flash, EEPOM, fuses, lock bits, and the
user signature row. This is done by accessing the NVM controller and executing NVM controller commands, as
described in “Memory Programming” on page 407.
Debug is supported through an on-chip debug system that offers nonintrusive, real-time debug. It does not require any
software or hardware resources except for the device pin connection. Using the Atmel tool chain, it offers complete
program flow control and support for an unlimited number of program and complex data breakpoints. Application
debug can be done from a C or other high-level language source code level, as well as from an assembler and
disassembler level.
Programming and debugging can be done through two physical interfaces. The primary one is the PDI physical layer,
which is available on all devices. This is a two-pin interface that uses the Reset pin for the clock input (PDI_CLK) and
one other dedicated pin for data input and output (PDI_DATA). A JTAG interface is also available on most devices,
and this can be used for programming and debugging through the four-pin JTAG interface. The JTAG interface is
IEEE Std. 1149.1 compliant, and supports boundary scan. Any external programmer or on-chip debugger/emulator
can be directly connected to either of these interfaces. Unless otherwise stated, all references to the PDI assume
access through the PDI physical layer.
Document Footer Title [PRELIMINARY DATASHEET] 362
Atmel-8291C-AVR-XMEGA B -09/2014
Figure 29-1. The PDI with JTAG and PDI physical layers and closely related modules (grey).
29.3 PDI Physical
The PDI physical layer handles the low-level serial communication. It uses a bidirectional, half-duplex, synchronous
serial receiver and transmitter (just as a USART in USRT mode). The physical layer includes start-of-frame detection,
frame error detection, parity generation, parity error detection, and collision detection.
In addition to PDI_CLK and PDI_DATA, the PDI_DATA pin has an internal pull resistor, VCC and GND must be
connected between the External Programmer/debugger and the device. Figure 29-2 on page 362 shows a typical
connection.
Figure 29-2. PDI connection.
The remainder of this section is intended for use only by third parties developing programmers or programming
support for Atmel AVR XMEGA devices.
29.3.1 Enabling
The PDI physical layer must be enabled before use. This is done by first forcing the PDI_DATA line high for a period
longer than the equivalent external reset minimum pulse width (refer to device datasheet for external reset pulse width
data). This will disable the RESET functionality of the Reset pin, if not already disabled by the fuse settings.
Next, continue to keep the PDI_DATA line high for 16 PDI_CLK cycles. The first PDI_CLK cycle must start no later
than 100μs after the RESET functionality of the Reset pin is disabled. If this does not occur in time, the enabling
procedure must start over again. The enable sequence is shown in Figure 29-3 on page 363.
PDI
Controller
JTAG Physical
(physical layer)
PDI Physical
(physical layer)
OCD
NVM
Controller
Program and Debug Interface (PDI)
PDI_CLK
PDI_DATA
TDO
TCK
TMI
TDI
NVM
Memories
PDIBUS Internal Interfaces
PDI Connector
GND
VCC
PDI_CLK
PDI_DATA
Document Footer Title [PRELIMINARY DATASHEET] 363
Atmel-8291C-AVR-XMEGA B -09/2014
Figure 29-3. PDI physical layer enable sequence.
The Reset pin is sampled when the PDI interface is enabled. The reset register is then set according to the state of the
Reset pin, preventing the device from running code after the reset functionality of this pin is disabled.
29.3.2 Disabling
If the clock frequency on PDI_CLK is lower than approximately 10kHz, this is regarded as inactivity on the clock line.
This will automatically disable the PDI. If not disabled by a fuse, the reset function of the Reset (PDI_CLK) pin is
enabled again. This also means that the minimum programming frequency is approximately 10kHz.
29.3.3 Frame Format and Characters
The PDI physical layer uses a frame format defined as one character of eight data bits, with a start bit, a parity bit, and
two stop bits.
Figure 29-4. PDI serial frame format.
Three different characters are used, DATA, BREAK, and IDLE. The BREAK character is equal to a 12-bit length of low
level. The IDLE character is equal to a 12- bit length of high level. The BREAK and IDLE characters can be extended
beyond the 12-bit length.
Figure 29-5. Characters and timing for the PDI physical layer.
Disable RESET function on Reset (PDI_CLK) pin Activate PDI
PDI_DATA
PDI_CLK
St Start bit, always low
(0-7) Data bits (0 to 7)
P Parity bit, even parity used
Sp1 Stop bit 1, always high
Sp2 Stop bit 2, always high
St 012 3 4567P Sp1
FRAME
(IDLE) Sp2 (St/IDLE)
START 012 3 4567P STOP
1 IDLE character
BREAK
IDLE
1 DATA character
1 BREAK character
Document Footer Title [PRELIMINARY DATASHEET] 364
Atmel-8291C-AVR-XMEGA B -09/2014
29.3.4 Serial Transmission and Reception
The PDI physical layer is either in transmit (TX) or receive (RX) mode. By default, it is in RX mode, waiting for a start
bit.
The programmer and the PDI operate synchronously on the PDI_CLK provided by the programmer. The dependency
between the clock edges and data sampling or data change is fixed. As illustrated in Figure 29-6 on page 364, output
data (either from the programmer or the PDI) is always set up (changed) on the falling edge of PDI_CLK and sampled
on the rising edge of PDI_CLK.
Figure 29-6. Changing and sampling of data.
29.3.5 Serial Transmission
When a data transmission is initiated, by the PDI controller, the transmitter simply shifts out the start bit, data bits,
parity bit, and the two stop bits on the PDI_DATA line. The transmission speed is dictated by the PDI_CLK signal.
While in transmission mode, IDLE bits (high bits) are automatically transmitted to fill possible gaps between
successive DATA characters. If a collision is detected during transmission, the output driver is disabled, and the
interface is put into RX mode waiting for a BREAK character.
29.3.6 Serial Reception
When a start bit is detected, the receiver starts to collect the eight data bits. If the parity bit does not correspond to the
parity of the data bits, a parity error has occurred. If one or both of the stop bits are low, a frame error has occurred. If
the parity bit is correct, and no frame error is detected, the received data bits are available for the PDI controller.
When the PDI is in TX mode, a BREAK character signaled by the programmer will not be interpreted as a BREAK, but
will instead cause a generic data collision. When the PDI is in RX mode, a BREAK character will be recognized as a
BREAK. By transmitting two successive BREAK characters (which must be separated by one or more high bits), the
last BREAK character will always be recognized as a BREAK, regardless of whether the PDI was in TX or RX mode
initially. This is because in TX mode the first BREAK is seen as a collision. The PDI then shifts to RX mode and sees
the second BREAK as break.
29.3.7 Direction Change
In order to ensure correct timing for half-duplex operation, a guard time mechanism is used. When the PDI changes
from RX mode to TX mode, a configurable number of IDLE bits are inserted before the start bit is transmitted. The
minimum transition time between RX and TX mode is two IDLE cycles, and these are always inserted. The default
guard time value is 128 bits.
Figure 29-7. PDI direction change by inserting IDLE bits.
PDI_CLK
PDI_DATA
Sample Sample Sample
St P Sp1
1 DATA character
Sp2 IDLE bits St P
1 DATA character
Sp1 Sp2
Dir. change
PDI DATA Receive (RX) PDI DATA Transmit (TX)
Data from
PDI interface
to Programmer
Data from
Programmer to
PDI interface
Guard time
# IDLE bits
inserted
Document Footer Title [PRELIMINARY DATASHEET] 365
Atmel-8291C-AVR-XMEGA B -09/2014
The external programmer will loose control of the PDI_DATA line at the point where the PDI changes from RX to TX
mode. The guard time relaxes this critical phase of the communication. When the programmer changes from RX
mode to TX mode, a single IDLE bit, at minimum, should be inserted before the start bit is transmitted.
29.3.8 Drive Contention and Collision Detection
In order to reduce the effect of drive contention (the PDI and the programmer driving the PDI_DATA line at the same
time), a mechanism for collision detection is used. The mechanism is based on the way the PDI drives data out on the
PDI_DATA line. As shown in Figure 29-8 on page 365, the PDI output driver is active only when the output value
changes (from 0-1 or 1-0). Hence, if two or more successive bit values are the same, the value is actively driven only
on the first clock cycle. After this point, the PDI output driver is automatically tri-stated, and the PDI_DATA pin has a
bus keeper responsible for keeping the pin value unchanged until the output driver is reenabled due to a change in the
bit value.
Figure 29-8. Driving data out on the PDI_DATA using a bus keeper.
If the programmer and the PDI both drive the PDI_DATA line at the same time, drive contention will occur, as
illustrated in Figure 29-9 on page 365. Every time a bit value is kept for two or more clock cycles, the PDI is able to
verify that the correct bit value is driven on the PDI_DATA line. If the programmer is driving the PDI_DATA line to the
opposite bit value to what the PDI expects, a collision is detected.
Figure 29-9. Drive contention and collision detection on the PDI_DATA line.
As long as the PDI transmits alternating ones and zeros, collisions cannot be detected, because the PDI output driver
will be active all the time, preventing polling of the PDI_DATA line. However, the two stop bits should always be
transmitted as ones within a single frame, enabling collision detection at least once per frame.
1011 0
Output enable
PDI_CLK
PDI Output
0 1
PDI_DATA
PDI_CLK
PDI Output
PDI_DATA
1 0 X 1 1
Programmer
output
X 1
Collision detect
= Collision
Document Footer Title [PRELIMINARY DATASHEET] 366
Atmel-8291C-AVR-XMEGA B -09/2014
29.4 JTAG Physical
The JTAG physical layer handles the basic low-level serial communication over four I/O lines, TMS, TCK, TDI, and
TDO. The JTAG physical layer includes BREAK detection, parity error detection, and parity generation. For all generic
JTAG details, refer to “IEEE 1149.1 JTAG Boundary Scan Interface” on page 386.
29.4.1 Enabling
The JTAGEN fuse must be programmed and the JTAG disable bit in the MCU control register must be cleared to
enable the JTAG interface. This is done by default. When the JTAG PDICOM instruction is shifted into the JTAG
instruction register, the JTAG interface can be used to access the PDI for external programming and on-chip
debugging.
29.4.2 Disabling
The JTAG interface can be disabled by unprogramming the JTAGEN fuse or by setting the JTAG disable bit in the
MCU control register from the application code.
29.4.3 JTAG Instruction Set
The Atmel XMEGA specific JTAG instruction set consist of eight instructions related to boundary scan and PDI access
for programming. For more details on JTAG and the general JTAG instruction set, refer to “JTAG Instructions” on
page 388.
29.4.3.1 The PDICOM Instruction
When the PDICOM instruction is shifted into the JTAG instruction register, the 9-bit PDI communication register is
selected as the data register. Commands are shifted into the register as results from previous commands are shifted
out from the register. The active TAP controller states are (see “TAP - Test Access Port” on page 386):
̶ Capture DR: Parallel data from the PDI controller is sampled into the PDI communication register
̶ Shift DR: The PDI communication register is shifted by the TCK input
̶ Update DR: Commands or operands are parallel-latched into registers in the PDI controller
29.4.4 Frame Format and Characters
The JTAG physical layer supports a fixed frame format. A serial frame is defined to be one character of eight data bits
followed by one parity bit.
Figure 29-10. JTAG serial frame format
Three special data characters are used. Common among these is that the parity bit is inverted in order to force a
parity error upon reception. The BREAK character (0xBB+P1) is used by the external programmer to force the PDI to
abort any ongoing operation and bring the PDI controller into a known state. The DELAY character (0xDB+P1) is used
by the PDI to tell the programmer that it has no data ready. The EMPTY character (0xEB+P1) is used by the PDI to tell
the programmer that it has no transmission pending (i.e., the PDI is in RX-mode).
(0-7) Data/command bits, least-significant bit sent first (0 to 7)
P Parity bit, even parity used
Document Footer Title [PRELIMINARY DATASHEET] 367
Atmel-8291C-AVR-XMEGA B -09/2014
Figure 29-11. Special data characters.
29.4.5 Serial transmission and reception
The JTAG interface supports full-duplex communication. At the same time as input data is shifted in on the TDI pin,
output data is shifted out on the TDO pin. However, PDI communication relies on half-duplex data transfer. Due to
this, the JTAG physical layer operates only in either transmit (TX) or receive (RX) mode. The available JTAG bit
channel is used for control and status signalling.
The programmer and the JTAG interface operate synchronously on the TCK clock provided by the programmer. The
dependency between the clock edges and data sampling or data change is fixed. As illustrated in Figure 29-12 on
page 367, TDI and TDO is always set up (change) on the falling edge of TCK, while data always should be sampled
on the rising edge of TCK.
Figure 29-12. Changing and sampling data.
29.4.6 Serial Transmission
When data transmission is initiated, a data byte is loaded into the shift register and then out on TDO. The parity bit is
generated and appended to the data byte during transmission. The transmission speed is given by the TCK signal.
If the PDI is in TX mode (as a response to an LD instruction), and a transmission request from the PDI controller is
pending when the TAP controller enters the capture DR state, valid data will be parallel-loaded into the shift register,
and a correct parity bit will be generated and transmitted along with the data byte in the shift DR state.
If the PDI is in RX mode when the TAP controller enters the capture DR state, an EMPTY byte will be loaded into the
shift register, and the parity bit will be set (forcing a parity error) when data is shifted out in the shift DR state. This
situation occurs during normal PDI command and operand reception.
If the PDI is in TX- mode (as a response to an LD instruction), but no transmission request from the PDI controller is
pending when the TAP controller enters the capture DR state, a DELAY byte (0xDB) will be loaded into the shift
register, and the parity bit will be set (forcing a parity error) when data is shifted out in the shift DR state. This situation
occurs during data transmission if the data to be transmitted is not yet available.
Figure 29-13 on page 368 shows an uninterrupted flow of data frames from the PDI as a response to the repeated
indirect LD instruction. In this example, the device is not able to return data bytes faster than one valid byte per two
transmitted frames. Thus, intermediate DELAY characters are inserted.
Document Footer Title [PRELIMINARY DATASHEET] 368
Atmel-8291C-AVR-XMEGA B -09/2014
Figure 29-13. Data not ready marking.
If a DELAY data frame is transmitted as a response to an LD instruction, the programmer should interpret this as if the
JTAG interface had no data ready for transmission in the previous capture DR state. The programmer must initiate
repeated transfers until a valid data byte is received. The LD instruction is defined to return a specified number of valid
frames, not just a number of frames. Hence, if the programmer detects a DELAY character after transmitting an LD
instruction, the LD instruction should not be retransmitted, because the first LD response would still be pending.
29.4.7 Serial Reception
During reception, the PDI collects the eight data bits and the parity bit from TDI and shifts them into the shift register.
Every time a valid frame is received, the data is latched in to the update DR state.
The parity checker calculates the parity (even mode) of the data bits in incoming frames and compares the result with
the parity bit from the serial frame. In case of a parity error, the PDI controller is signaled.
The parity checker is active in both TX and RX modes. If a parity error is detected, the received data byte is evaluated
and compared with the BREAK character (which will always generate a parity error). In case the BREAK character is
recognized, the PDI controller is signaled.
29.5 PDI Controller
The PDI controller performs data transmission/reception on a byte level, command decoding, high-level direction
control, control and status register access, exception handling, and clock switching (PDI_CLK or TCK). The
interaction between an external programmer and the PDI controller is based on a scheme where the programmer
transmits various types of requests to the PDI controller, which in turn responds according to the specific request. A
programmer request comes in the form of an instruction, which may be followed by one or more byte operands. The
PDI controller response may be silent (e.g., a data byte is stored to a location within the device), or it may involve data
being returned to the programmer (e.g., a data byte is read from a location within the device).
29.5.1 Switching between PDI and JTAG modes
The PDI controller uses either the JTAG or PDI physical layer for establishing a connection to the programmer. Based
on this, the PDI is in either JTAG or PDI mode. When one of the modes is entered, the PDI controller registers will be
initialized, and the correct clock source will be selected. The PDI mode has higher priority than the JTAG mode.
Hence, if the PDI mode is enabled while the PDI controller is already in JTAG mode, the access layer will
automatically switch over to PDI mode. If switching physical layer without powering on/off the device, the active layer
should be disabled before the alternative physical layer is enabled.
29.5.2 Accessing Internal Interfaces
After an external programmer has established communication with the PDI, the internal interfaces are not accessible,
by default. To get access to the NVM controller and the nonvolatile memories for programming, a unique key must be
signaled by using the KEY instruction. The internal interfaces are accessed as one linear address space using a
dedicated bus (PDIBUS) between the PDI and the internal interfaces. The PDIBUS address space is shown in
Table 33-3 on page 421. The NVM controller must be enabled for the PDI controller to have any access to the NVM
interface. The PDI controller can access the NVM and NVM controller in programming mode only. The PDI controller
does not need to access the NVM controller's data or address registers when reading or writing NVM.
Document Footer Title [PRELIMINARY DATASHEET] 369
Atmel-8291C-AVR-XMEGA B -09/2014
29.5.3 NVM Programming Key
The key that must be sent using the KEY instruction is 64 bits long. The key that will enable NVM programming is:
0x1289AB45CDD888FF
29.5.4 Exception Handling
There are several situations that are considered exceptions from normal operation. The exceptions depend on
whether the PDI is in RX or TX mode and whether PDI or JTAG mode is used.
While the PDI is in RX mode, the exceptions are:
z PDI:
̶ The physical layer detects a parity error
̶ The physical layer detects a frame error
̶ The physical layer recognizes a BREAK character (also detected as a frame error)
z JTAG:
̶ The physical layer detects a parity error
̶ The physical layer recognizes a BREAK character (also detected as a parity error)
While the PDI is in TX mode, the exceptions are:
z PDI:
̶ The physical layer detects a data collision
z JTAG:
̶ The physical layer detects a parity error (on the dummy data shifted in on TDI)
̶ The physical layer recognizes a BREAK character
Exceptions are signaled to the PDI controller. All ongoing operations are then aborted, and the PDI is put in ERROR
state. The PDI will remain in ERROR state until a BREAK is sent from the external programmer, and this will bring the
PDI back to its default RX state.
Due to this mechanism, the programmer can always synchronize the protocol by transmitting two successive BREAK
characters.
29.5.5 Reset Signalling
Through the reset register, the programmer can issue a reset and force the device into reset. After clearing the reset
register, reset is released, unless some other reset source is active.
29.5.6 Instruction Set
The PDI has a small instruction set used for accessing both the PDI itself and the internal interfaces. All instructions
are byte instructions. The instructions allow an external programmer to access the PDI controller, the NVM controller
and the nonvolatile memories.
29.5.6.1 LDS - Load Data from PDIBUS Data Space using Direct Addressing
The LDS instruction is used to load data from the PDIBUS data space for read out. The LDS instruction is based on
direct addressing, which means that the address must be given as an argument to the instruction. Even though the
protocol is based on byte-wise communication, the LDS instruction supports multiple-byte addresses and data
access. Four different address/data sizes are supported: single-byte, word (two bytes), three-byte, and long (four
bytes). Multiple-byte access is broken down internally into repeated single-byte accesses, but this reduces protocol
overhead. When using the LDS instruction, the address byte(s) must be transmitted before the data transfer.
29.5.6.2 STS - Store Data to PDIBUS Data Space using Direct Addressing
The STS instruction is used to store data that are serially shifted into the physical layer shift register to locations within
the PDIBUS data space. The STS instruction is based on direct addressing, which means that the address must be
given as an argument to the instruction. Even though the protocol is based on byte-wise communication, the ST
Document Footer Title [PRELIMINARY DATASHEET] 370
Atmel-8291C-AVR-XMEGA B -09/2014
instruction supports multiple-bytes addresses and data access. Four different address/data sizes are supported:
single-byte, word (two bytes), three-byte, and long (four bytes). Multiple-byte access is broken down internally into
repeated single-byte accesses, but this reduces protocol overhead. When using the STS instruction, the address
byte(s) must be transmitted before the data transfer.
29.5.6.3 LD - Load Data from PDIBUS Data Space using Indirect Addressing
The LD instruction is used to load data from the PDIBUS data space into the physical layer shift register for serial read
out. The LD instruction is based on indirect addressing (pointer access), which means that the address must be stored
in the pointer register prior to the data access. Indirect addressing can be combined with pointer increment. In addition
to reading data from the PDIBUS data space, the LD instruction can read the pointer register. Even though the
protocol is based on byte-wise communication, the LD instruction supports multiple-byte addresses and data access.
Four different address/data sizes are supported: single-byte, word (two bytes), three-byte, and long (four bytes).
Multiple-byte access is broken down internally into repeated single-byte accesses, but this reduces the protocol
overhead.
29.5.6.4 ST - Store Data to PDIBUS Data Space using Indirect Addressing
The ST instruction is used to store data that is serially shifted into the physical layer shift register to locations within
the PDIBUS data space. The ST instruction is based on indirect addressing (pointer access), which means that the
address must be stored in the pointer register prior to the data access. Indirect addressing can be combined with
pointer increment. In addition to writing data to the PDIBUS data space, the ST instruction can write the pointer
register. Even though the protocol is based on byte-wise communication, the ST instruction supports multiple-bytes
address - and data access. Four different address/data sizes are supported; byte, word, 3 bytes, and long (4 bytes).
Multiple-bytes access is internally broken down to repeated single-byte accesses, but it reduces the protocol
overhead.
29.5.6.5 LDCS - Load Data from PDI Control and Status Register Space
The LDCS instruction is used to load data from the PDI control and status registers into the physical layer shift register
for serial read out. The LDCS instruction supports only direct addressing and single-byte access.
29.5.6.6 STCS - Store Data to PDI Control and Status Register Space
The STCS instruction is used to store data that are serially shifted into the physical layer shift register to locations
within the PDI control and status registers. The STCS instruction supports only direct addressing and single-byte
access.
29.5.6.7 KEY - Set Activation Key
The KEY instruction is used to communicate the activation key bytes required for activating the NVM interfaces.
29.5.6.8 REPEAT - Set Instruction Repeat Counter
The REPEAT instruction is used to store count values that are serially shifted into the physical layer shift register to
the repeat counter register. The instruction that is loaded directly after the REPEAT instruction operand(s) will be
repeated a number of times according to the specified repeat counter register value. Hence, the initial repeat counter
value plus one gives the total number of times the instruction will be executed. Setting the repeat counter register to
zero makes the following instruction run once without being repeated.
The REPEAT instruction cannot be repeated. The KEY instruction cannot be repeated, and will override the current
value of the repeat counter register.
29.5.7 Instruction Set Summary
The PDI instruction set summary is shown in Figure 29-14 on page 371.
Document Footer Title [PRELIMINARY DATASHEET] 371
Atmel-8291C-AVR-XMEGA B -09/2014
Figure 29-14. PDI instruction set summary.
29.6 Register Description – PDI Instruction and Addressing Registers
The PDI instruction and addressing registers are internal registers utilized for instruction decoding and PDIBUS
addressing. None of these registers are accessible as registers in a register space.
29.6.1 Instruction Register
When an instruction is successfully shifted into the physical layer shift register, it is copied into the instruction register.
The instruction is retained until another instruction is loaded. The reason for this is that the REPEAT command may
force the same instruction to be run repeatedly, requiring command decoding to be performed several times on the
same instruction.
29.6.2 Pointer Register
The pointer register is used to store an address value that specifies locations within the PDIBUS address space.
During direct data access, the pointer register is updated by the specified number of address bytes given as operand
bytes to an instruction. During indirect data access, addressing is based on an address already stored in the pointer
register prior to the access itself. Indirect data access can be optionally combined with pointer register post-increment.
LDS 0 0 0
Cmd Size A Size B
STS 0 1 0
LDCS 1 0 0
CS Address
STCS 1 1 0
KEY 1 1 1 0 0 0
REPEAT 1 0 1 0 0 0
Size B
LDS
STS
ST
0
0 1
0
0
1
1 1
LD
0
0
0
0
Cmd
LDCS (LDS Control/Status)
STCS (STS Control/Status)
KEY
0 1
1 0
1 1
REPEAT
1
1
1
1
0 0
Size B - Data size
Byte
3 Bytes
Long (4 Bytes)
0
0 1
0
0
1
1 1
Word (2 Bytes)
CS Address (CS - Control/Status reg.)
0 0 0 Register 0
Register 2
Reserved
Register 1
0
0 0 0 1
0 0 1 0
0 0 1 1
1 1 1 1 Reserved
......
0
0
Size A - Address size (direct access)
Byte
3 Bytes
Long (4 Bytes)
0
0 1
0
0
1
1 1
Word (2 Bytes)
LD 0 0 1
Cmd Ptr Size A/B
ST 0 1 1 0
0
0
0
Ptr - Pointer access (indirect access)
*(ptr)
ptr
ptr++ - Reserved
0
0 1
0
0
1
1 1
*(ptr++)
0 0
Document Footer Title [PRELIMINARY DATASHEET] 372
Atmel-8291C-AVR-XMEGA B -09/2014
The indirect access mode has an option that makes it possible to load or read the pointer register without accessing
any other registers. Any register update is performed in a little-endian fashion. Hence, loading a single byte of the
address register will always update the LSB while the most-significant bytes are left unchanged.
The pointer register is not involved in addressing registers in the PDI control and status register space (CSRS space).
29.6.3 Repeat Counter Register
The REPEAT instruction is always accompanied by one or more operand bytes that define the number of times the
next instruction should be repeated. These operand bytes are copied into the repeat counter register upon reception.
During the repeated executions of the instruction immediately following the REPEAT instruction and its operands, the
repeat counter register is decremented until it reaches zero, indicating that all repetitions have completed. The repeat
counter is also involved in key reception.
29.6.4 Operand Count Register
Immediately after an instruction (except the LDCS and STCS instructions) a specified number of operands or data
bytes (given by the size parts of the instruction) are expected. The operand count register is used to keep track of how
many bytes have been transferred.
Document Footer Title [PRELIMINARY DATASHEET] 373
Atmel-8291C-AVR-XMEGA B -09/2014
29.7 Register Description – PDI Control and Status Registers
The PDI control and status registers are accessible in the PDI control and status register space (CSRS) using the
LDCS and STCS instructions. The CSRS contains registers directly involved in configuration and status monitoring of
the PDI itself.
29.7.1 STATUS – Status register
z Bit 7:2 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits
to zero when this register is written.
z Bit 1 – NVMEN: Nonvolatile Memory Enable
This status bit is set when the key signalling enables the NVM programming interface. The external
programmer can poll this bit to verify successful enabling. Writing the NVMEN bit disables the NVM interface.
z Bit 0 – Reserved
This bit is unused and reserved for future use. For compatibility with future devices, always write this bit to zero
when this register is written.
29.7.2 RESET – Reset register
z Bit 7:0 – RESET[7:0]: Reset Signature
When the reset signature, 0x59, is written to RESET, the device is forced into reset. The device is kept in reset
until RESET is written with a data value different from the reset signature. Reading the lsb will return the status
of the reset. The seven msbs will always return the value 0x00, regardless of whether the device is in reset or
not.
29.7.3 CTRL – Control register
z Bit 7:3 – Reserved
These bits are unused and reserved for future use. For compatibility with future devices, always write these bits
to zero when this register is written.
z Bit 2:0 – GUARDTIME[2:0]: Guard Time
These bits specify the number of IDLE bits of guard time that are inserted in between PDI reception and
transmission direction changes. The default guard time is 128 IDLE bits, and the available settings are shown in
Table 29-1 on page 374. In order to speed up the communication, the guard time should be set to the lowest
safe configuration accepted. No guard time is inserted when switching from TX to RX mode.
Bit 7 6 5 4 3 2 1 0
+0x00 – – – – – – NVMEN –
Read/Write R R R R R R R/W R
Initial Value 00000000
Bit 7 6 5 4 3 2 1 0
+0x01 RESET[7:0]
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
+0x02 – – – – – GUARDTIME[2:0]
Read/Write R R R R R R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Document Footer Title [PRELIMINARY DATASHEET] 374
Atmel-8291C-AVR-XMEGA B -09/2014
Table 29-1. Guard time settings.
29.8 Register Summary
GUARDTIME Number of IDLE Bits
000 128
001 64
010 32
011 16
100 8
101 4
110 2
111 2
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
+0x00 STATUS – – – – – – NVMEN – 373
+0x01 RESET RESET[7:0] 373
+0x02 CTRL – – – – – GUARDTIME[2:0] 373
+0x03 Reserved – – – – – – – –
XMEGA B [MANUAL] 375
Atmel-8291C-AVR-XMEGA B -09/2014
30. Memory Programming
30.1 Features
z Read and write access to all memory spaces from
z External programmers
z Application software self-programming
z Self-programming and boot loader support
z Read-while-write self-programming
z CPU can run and execute code while flash is being programmed
z Any communication interface can be used for program upload/download
z External programming
z Support for in-system and production programming
z Programming through serial PDI or JTAG interface
z High security with separate boot lock bits for:
z External programming access
z Boot loader section access
z Application section access
z Application table access
z Reset fuse to select reset vector address to the start of the
z Application section, or
z Boot loader section
30.2 Overview
This section describes how to program the nonvolatile memory (NVM) in Atmel AVR XMEGA devices, and covers both
self-programming and external programming. The NVM consists of the flash program memory, user signature and
production signature rows, fuses and lock bits, and EEPROM data memory. For details on the actual memories, how
they are organized, and the register description for the NVM controller used to access the memories, refer to “Memories”
on page 20.
The NVM can be accessed for read and write from application software through self-programming and from an external
programmer. Accessing the NVM is done through the NVM controller, and the two methods of programming are similar.
Memory access is done by loading address and/or data to the selected memory or NVM controller and using a set of
commands and triggers that make the NVM controller perform specific tasks on the nonvolatile memory.
From external programming, all memory spaces can be read and written, except for the production signature row, which
can only be read. The device can be programmed in-system and is accessed through the PDI using the PDI or JTAG
physical interfaces. “External Programming” on page 388 describes PDI and JTAG in detail.
Self-programming and boot loader support allows application software in the device to read and write the flash, user
signature row and EEPROM, write the lock bits to a more secure setting, and read the production signature row and
fuses. The flash allows read-while-write self-programming, meaning that the CPU can continue to operate and execute
code while the flash is being programmed. “Self-programming and Boot Loader Support” on page 379 describes this in
detail.
For both self-programming and external programming, it is possible to run a CRC check on the flash or a section of the
flash to verify its content after programming.
The device can be locked to prevent reading and/or writing of the NVM. There are separate lock bits for external
programming access and self-programming access to the boot loader section, application section, and application table
section.
XMEGA B [MANUAL] 376
Atmel-8291C-AVR-XMEGA B -09/2014
30.3 NVM Controller
Access to the nonvolatile memories is done through the NVM controller. It controls NVM timing and access privileges,
and holds the status of the NVM, and is the common NVM interface for both external programming and selfprogramming.
For more details, refer to “Register Description” on page 393.
30.4 NVM Commands
The NVM controller has a set of commands used to perform tasks on the NVM. This is done by writing the selected
command to the NVM command register. In addition, data and addresses must be read/written from/to the NVM data and
address registers for memory read/write operations.
When a selected command is loaded and address and data are set up for the operation, each command has a trigger
that will start the operation. Based on these triggers, there are three main types of commands.
30.4.1 Action-triggered Commands
Action-triggered commands are triggered when the command execute (CMDEX) bit in the NVM control register A
(CTRLA) is written. Action-triggered commands typically are used for operations which do not read or write the NVM,
such as the CRC check.
30.4.2 NVM Read-triggered Commands
NVM read-triggered commands are triggered when the NVM is read, and this is typically used for NVM read operations.
30.4.3 NVM Write-triggered Commands
NVM write-triggered commands are triggered when the NVM is written, and this is typically used for NVM write
operations.
30.4.4 Write/Execute Protection
Most command triggers are protected from accidental modification/execution during self-programming. This is done
using the configuration change protection (CCP) feature, which requires a special write or execute sequence in order to
change a bit or execute an instruction. For details on the CCP, refer to “Configuration Change Protection” on page 13.
30.5 NVM Controller Busy Status
When the NVM controller is busy performing an operation, the busy flag in the NVM status register is set and the
following registers are blocked for write access:
z NVM command register
z NVM control A register
z NVM control B register
z NVM address registers
z NVM data registers
This ensures that the given command is executed and the operations finished before the start of a new operation. The
external programmer or application software must ensure that the NVM is not addressed when it is busy with a
programming operation.
Programming any part of the NVM will automatically block:
z All programming to other parts of the NVM
z All loading/erasing of the flash and EEPROM page buffers
z All NVM reads from external programmers
z All NVM reads from the application section
During self-programming, interrupts must be disabled or the interrupt vector table must be moved to the boot loader
sections, as described in “Interrupts and Programmable Multilevel Interrupt Controller” on page 115.
XMEGA B [MANUAL] 377
Atmel-8291C-AVR-XMEGA B -09/2014
30.6 Flash and EEPROM Page Buffers
The flash memory is updated page by page. The EEPROM can be updated on a byte-by-byte and page-by-page basis.
flash and EEPROM page programming is done by first filling the associated page buffer, and then writing the entire page
buffer to a selected page in flash or EEPROM.
The size of the page and page buffers depends on the flash and EEPROM size in each device, and details are described
in the device datasheet.
30.6.1 Flash Page Buffer
The flash page buffer is filled one word at a time, and it must be erased before it can be loaded. When loading the page
buffer with new content, the result is a binary AND between the existing content of the page buffer location and the new
value. If the page buffer is already loaded once after erase the location will most likely be corrupted.
Page buffer locations that are not loaded will have the value 0xFFFF, and this value will then be programmed into the
corresponding flash page locations.
The page buffer is automatically erased after:
z A device reset
z Executing the write flash page command
z Executing the erase and write flash page command
z Executing the signature row write command
z Executing the write lock bit command
30.6.2 EEPROM Page Buffer
The EEPROM page buffer is filled one byte at a time, and it must be erased before it can be loaded. When loading the
page buffer with new content, the result is a binary AND between the existing content of the page buffer location and the
new value. If the EEPROM page buffer is already loaded once after erase the location will most likely be corrupted.
EEPROM page buffer locations that are loaded will get tagged by the NVM controller. During a page write or page erase,
only targed locations will be written or erased. Locations that are not targed will not be written or erased, and the
corresponding EEPROM location will remain unchanged. This means that before an EEPROM page erase, data must be
loaded to the selected page buffer location to tag them. When performing an EEPROM page erase, the actual value of
the tagged location does not matter.
The EEPROM page buffer is automatically erased after:
z A system reset
z Executing the write EEPROM page command
z Executing the erase and write EEPROM page command
z Executing the write lock bit and write fuse commands
30.7 Flash and EEPROM Programming Sequences
For page programming, filling the page buffers and writing the page buffer into flash or EEPROM are two separate
operations. The sequence is same for both self-programming and external programming.
30.7.1 Flash Programming Sequence
Before programming a flash page with the data in the flash page buffer, the flash page must be erased. Programming an
un-erased flash page will corrupt its content.
The flash page buffer can be filled either before the erase flash Page operation or between a erase flash page and a
write flash page operation:
XMEGA B [MANUAL] 378
Atmel-8291C-AVR-XMEGA B -09/2014
Alternative 1:
z Fill the flash page buffer
z Perform a flash page erase
z Perform a flash page write
Alternative 2:
z Fill the flash page buffer
z Perform an atomic page erase and write
Alternative 3, fill the buffer after a page erase:
z Perform a flash page erase
z Fill the flash page buffer
z Perform a flash page write
The NVM command set supports both atomic erase and write operations, and split page erase and page write
commands. This split commands enable shorter programming time for each command, and the erase operations can be
done during non-time-critical programming execution. When using alternative 1 or 2 above for self-programming, the
boot loader provides an effective read-modify-write feature, which allows the software to first read the page, do the
necessary changes, and then write back the modified data. If alternative 3 is used, it is not possible to read the old data
while loading, since the page is already erased. The page address must be the same for both page erase and page write
operations when using alternative 1 or 3.
30.7.2 EEPROM Programming Sequence
Before programming an EEPROM page with the tagged data bytes stored in the EEPROM page buffer, the selected
locations in the EEPROM page must be erased. Programming an unerased EEPROM page will corrupt its content. The
EEPROM page buffer must be loaded before any page erase or page write operations:
Alternative 1:
z Fill the EEPROM page buffer with the selected number of bytes
z Perform a EEPROM page erase
z Perform a EEPROM page write
Alternative 2:
z Fill the EEPROM page buffer with the selected number of bytes
z Perform an atomic EEPROM page erase and write
30.8 Protection of NVM
To protect the flash and EEPROM memories from write and/or read, lock bits can be set to restrict access from external
programmers and the application software. Refer to “LOCKBITS – Lock Bit register” on page 29 for details on the
available lock bit settings and how to use them.
30.9 Preventing NVM Corruption
During periods when the VCC voltage is below the minimum operating voltage for the device, the result from a flash
memory write can be corrupt, as supply voltage is too low for the CPU and the flash to operate properly.To ensure that
the voltage is sufficient enough during a complete programming sequence of the flash memory, a voltage detector using
the POR threshold (VPOT+) level is enabled. During chip erase and when the PDI is enabled the brownout detector (BOD)
is automatically enabled at its configured level.
XMEGA B [MANUAL] 379
Atmel-8291C-AVR-XMEGA B -09/2014
Depending on the programming operation, if any of these VCC voltage levels are reached, the programming sequence
will be aborted immediately. If this happens, the NVM programming should be restarted when the power is sufficient
again, in case the write sequence failed or only partly succeeded.
30.10 CRC Functionality
It is possible to run an automatic cyclic redundancy check (CRC) on the flash program memory. When NVM is used to
control the CRC module, an even number of bytes are read, at least in the flash range mode. If the user selects a range
with an odd number of bytes, an extra byte will be read, and the checksum will not correspond to the selected range.
Refer to “CRC – Cyclic Redundancy Check Generator” on page 293 for more details.
30.11 Self-programming and Boot Loader Support
Reading and writing the EEPROM and flash memory from the application software in the device is referred to as selfprogramming.
A boot loader (application code located in the boot loader section of the flash) can both read and write the
flash program memory, user signature row, and EEPROM, and write the lock bits to a more secure setting. Application
code in the application section can read from the flash, user signature row, production signature row, and fuses, and read
and write the EEPROM.
30.11.1 Flash Programming
The boot loader support provides a real read-while-write self-programming mechanism for uploading new program code
by the device itself. This feature allows flexible application software updates controlled by the device using a boot loader
application that reside in the boot loader section in the flash. The boot loader can use any available communication
interface and associated protocol to read code and write (program) that code into the flash memory, or read out the
program memory code. It has the capability to write into the entire flash, including the boot loader section. The boot
loader can thus modify itself, and it can also erase itself from the flash if the feature is not needed anymore.
30.11.1.1 Application and Boot Loader Sections
The application and boot loader sections in the flash are different when it comes to self-programming.
z When erasing or writing a page located inside the application section, the boot loader section can be read
during the operation, and thus the CPU can run and execute code from the boot loader section
z When erasing or writing a page located inside the boot loader section, the CPU is halted during the entire
operation, and code cannot execute
The user signature row section has the same properties as the boot loader section.
Table 30-1. Summary of self-programming functionality.
30.11.1.2 Addressing the Flash
The Z-pointer is used to hold the flash memory address for read and write access. For more details on the Z-pointer,
refer to “The X-, Y-, and Z- Registers” on page 11.
Since the flash is word accessed and organized in pages, the Z-pointer can be treated as having two sections. The leastsignificant
bits address the words within a page, while the most-significant bits address the page within the flash. This is
shown in Figure 30-1 on page 380. The word address in the page (FWORD) is held by the bits [WORDMSB:1] in the Zpointer.
The remaining bits [PAGEMSB:WORDMSB+1] in the Z-pointer hold the flash page address (FPAGE). Together
FWORD and FPAGE holds an absolute address to a word in the flash.
Section being Addressed during Programming Section that can be Read during Programming CPU halted?
Application section Boot loader section No
Boot loader section None Yes
User signature row section None Yes
XMEGA B [MANUAL] 380
Atmel-8291C-AVR-XMEGA B -09/2014
For flash read operations (ELPM and LPM), one byte is read at a time. For this, the least-significant bit (bit 0) in the Zpointer
is used to select the low byte or high byte in the word address. If this bit is 0, the low byte is read, and if this bit is
1 the high byte is read.
The size of FWORD and FPAGE will depend on the page and flash size in the device. Refer to each device’s datasheet
for details.
Once a programming operation is initiated, the address is latched and the Z-pointer can be updated and used for other
operations.
Figure 30-1. Flash addressing for self-programming.
30.11.2 NVM Flash Commands
The NVM commands that can be used for accessing the flash program memory, signature row and production signature
row are listed in Table 30-2.
For self-programming of the flash, the trigger for action-triggered commands is to set the CMDEX bit in the NVM CTRLA
register (CMDEX). The read-triggered commands are triggered by executing the (E)LPM instruction (LPM). The writetriggered
commands are triggered by executing the SPM instruction (SPM).
The Change Protected column indicates whether the trigger is protected by the configuration change protection (CCP) or
not. This is a special sequence to write/execute the trigger during self-programming. For more details, refer to
“Configuration Change Protection” on page 13. CCP is not required for external programming. The two last columns
show the address pointer used for addressing and the source/destination data register.
Section 30.11.1.1 on page 379 through Section 30.11.2.14 on page 384 explain in detail the algorithm for each NVM
operation.
FPAGE FWORD 0/1
BIT
Z-Pointer
P 1 AGEMSB WORDMSB 0
PAGE INSTRUCTION WORD
PROGRAM MEMORY PAGE
WORD ADDRESS
WITHIN A PAGE
PAGE ADDRESS
WITHIN THE FLASH
FWORD
00
01
02
PAGEEND
00
01
02
FLASHEND
FPAGE
Low/High Byte select for (E)LPM
XMEGA B [MANUAL] 381
Atmel-8291C-AVR-XMEGA B -09/2014
Table 30-2. Flash self-programming commands.
Notes: 1. The flash range CRC command used byte addressing of the flash.
2. Will depend on the flash section (application or boot loader) that is actually addressed.
3. This command is qualified with the lock bits, and requires that the boot lock bits are unprogrammed.
4. When using a command that changes the normal behavior of the LPM command; READ_USER_SIG_ROW and READ_CALIB_ROW; it is recommended to
disable interrupts to ensure correct execution of the LPM instruction.
5. For consistency the name Calibration Row has been renamed to Production Signature Row throughout the document.
30.11.2.1 Read Flash
The (E)LPM instruction is used to read one byte from the flash memory.
1. Load the Z-pointer with the byte address to read.
2. Load the NVM command register (NVM CMD) with the no operation command.
3. Execute the LPM instruction.
The destination register will be loaded during the execution of the LPM instruction.
CMD[6:0] Group Configuration Description Trigger
CPU
Halted
NVM
Busy
Change
Protected
Address
Pointer
Data
Register
0x00 NO_OPERATION No operation / read flash -/(E)LPM -/N N -/N -/ Z-pointer -/Rd
Flash Page Buffer
0x23 LOAD_FLASH_BUFFER Load flash page buffer SPM N N N Z-pointer R1:R0
0x26 ERASE_FLASH_BUFFER Erase flash page buffer CMDEX N Y Y Z-pointer -
Flash
0x2B ERASE_FLASH_PAGE Erase flash page SPM N/Y(2) Y Y Z-pointer -
0x02E WRITE_FLASH_PAGE Write flash page SPM N/Y(2) Y Y Z-pointer -
0x2F ERASE_WRITE_FLASH_PAGE Erase and write flash page SPM N/Y(2) Y Y Z-pointer -
0x3A FLASH_RANGE_CRC(3) Flash range CRC CMDEX Y Y Y DATA/ADDR(1) DATA
Application Section
0x20 ERASE_APP Erase application section SPM Y Y Y Z-pointer -
0x22 ERASE_APP_PAGE Erase application section page SPM N Y Y Z-pointer -
0x24 WRITE_APP_PAGE Write application section page SPM N Y Y Z-pointer -
0x25 ERASE_WRITE_APP_PAGE Erase and write application section page SPM N Y Y Z-pointer -
0x38 APP_CRC Application section CRC CMDEX Y Y Y - DATA
Boot Loader Section
0x2A ERASE_BOOT_PAGE Erase boot loader section page SPM Y Y Y Z-pointer -
0x2C WRITE_BOOT_PAGE Write boot loader section page SPM Y Y Y Z-pointer -
0x2D ERASE_WRITE_BOOT_PAGE Erase and write boot loader section page SPM Y Y Y Z-pointer -
0x39 BOOT_CRC Boot loader section CRC CMDEX Y Y Y - DATA
User Signature Row
0x01(4) READ_USER_SIG_ROW Read user signature row LPM N N N Z-pointer Rd
0x18 ERASE_USER_SIG_ROW Erase user signature row SPM Y Y Y - -
0x1A WRITE_USER_SIG_ROW Write user signature row SPM Y Y Y - -
Production Signature (Calibration) Row(5)
0x02(4) READ_CALIB_ROW Read calibration row LPM N N N Z-pointer Rd
XMEGA B [MANUAL] 382
Atmel-8291C-AVR-XMEGA B -09/2014
30.11.2.2 Erase Flash Page Buffer
The erase flash page buffer command is used to erase the flash page buffer.
1. Load the NVM CMD with the erase flash page buffer command.
2. Set the command execute bit (NVMEX) in the NVM control register A (NVM CTRLA). This requires the timed CCP
sequence during self-programming.
The NVM busy (BUSY) flag in the NVM status register (NVM STATUS) will be set until the page buffer is erased.
30.11.2.3 Load Flash Page Buffer
The load flash page buffer command is used to load one word of data into the flash page buffer.
1. Load the NVM CMD register with the load flash page buffer command.
2. Load the Z-pointer with the word address to write.
3. Load the data word to be written into the R1:R0 registers.
4. Execute the SPM instruction. The SPM instruction is not protected when performing a flash page buffer load.
Repeat step 2-4 until the complete flash page buffer is loaded. Unloaded locations will have the value 0xFFFF.
30.11.2.4 Erase Flash Page
The erase flash page command is used to erase one page in the flash.
1. Load the Z-pointer with the flash page address to erase. The page address must be written to FPAGE. Other bits
in the Z-pointer will be ignored during this operation.
2. Load the NVM CMD register with the erase flash page command.
3. Execute the SPM instruction. This requires the timed CCP sequence during self-programming.
The BUSY flag in the NVM STATUS register will be set until the erase operation is finished. The flash section busy
(FBUSY) flag is set as long the flash is busy, and the application section cannot be accessed.
30.11.2.5 Write Flash Page
The write flash page command is used to write the flash page buffer into one flash page in the flash.
1. Load the Z-pointer with the flash page to write. The page address must be written to FPAGE. Other bits in the Zpointer
will be ignored during this operation.
2. Load the NVM CMD register with the write flash page command.
3. Execute the SPM instruction. This requires the timed CCP sequence during self-programming.
The BUSY flag in the NVM STATUS register will be set until the write operation is finished. The FBUSY flag is set as long
the flash is busy, and the application section cannot be accessed.
30.11.2.6 Flash Range CRC
The flash range CRC command can be used to verify the content in an address range in flash after a self-programming.
1. Load the NVM CMD register with the flash range CRC command.
2. Load the start byte address in the NVM address register (NVM ADDR).
3. Load the end byte address in NVM data register (NVM DATA).
4. Set the CMDEX bit in the NVM CTRLA register. This requires the timed CCP sequence during self-programming.
The BUSY flag in the NVM STATUS register will be set, and the CPU is halted during the execution of the command.
The CRC checksum will be available in the NVM DATA register.
In order to use the flash range CRC command, all the boot lock bits must be unprogrammed (no locks). The command
execution will be aborted if the boot lock bits for an accessed location are set.
30.11.2.7 Erase Application Section
The erase application command is used to erase the complete application section.
1. Load the Z-pointer to point anywhere in the application section.
2. Load the NVM CMD register with the erase application section command
XMEGA B [MANUAL] 383
Atmel-8291C-AVR-XMEGA B -09/2014
3. Execute the SPM instruction. This requires the timed CCP sequence during self-programming.
The BUSY flag in the STATUS register will be set until the operation is finished. The CPU will be halted during the
complete execution of the command.
30.11.2.8 Erase Application Section / Boot Loader Section Page
The erase application section page erase and erase boot loader section page commands are used to erase one page in
the application section or boot loader section.
1. Load the Z-pointer with the flash page address to erase. The page address must be written to ZPAGE. Other bits
in the Z-pointer will be ignored during this operation.
2. Load the NVM CMD register with the erase application/boot section page command.
3. Execute the SPM instruction. This requires the timed CCP sequence during self-programming.
The BUSY flag in the NVM STATUS register will be set until the erase operation is finished. The FBUSY flag is set as
long the flash is busy, and the application section cannot be accessed.
30.11.2.9 Application Section / Boot Loader Section Page Write
The write application section page and write boot loader section page commands are used to write the flash page buffer
into one flash page in the application section or boot loader section.
1. Load the Z-pointer with the flash page to write. The page address must be written to FPAGE. Other bits in the Zpointer
will be ignored during this operation.
2. Load the NVM CMD register with the write application section/boot loader section page command.
3. Execute the SPM instruction. This requires the timed CCP sequence during self-programming.
The BUSY flag in the NVM STATUS register will be set until the write operation is finished. The FBUSY flag is set as long
the flash is busy, and the application section cannot be accessed.
An invalid page address in the Z-pointer will abort the NVM command. The erase application section page command
requires that the Z-pointer addresses the application section, and the erase boot section page command requires that
the Z-pointer addresses the boot loader section.
30.11.2.10 Erase and Write Application Section / Boot Loader Section Page
The erase and write application section page and erase and write boot loader section page commands are used to erase
one flash page and then write the flash page buffer into that flash page in the application section or boot loader section in
one atomic operation.
1. Load the Z-pointer with the flash page to write. The page address must be written to FPAGE. Other bits in the Zpointer
will be ignored during this operation.
2. Load the NVM CMD register with the erase and write application section/boot loader section page command.
3. Execute the SPM instruction. This requires the timed CCP sequence during self-programming.
The BUSY flag in the NVM STATUS register will be set until the operation is finished. The FBUSY flag is set as long as
the flash is busy, and the application section cannot be accessed.
An invalid page address in the Z-pointer will abort the NVM command. The erase and write application section command
requires that the Z-pointer addresses the application section, and the erase and write boot section page command
requires that the Z-pointer addresses the boot loader section.
30.11.2.11 Application Section / Boot Loader Section CRC
The application section CRC and boot loader section CRC commands can be used to verify the application section and
boot loader section content after self-programming.
1. Load the NVM CMD register with the application section/ boot load section CRC command.
2. Set the CMDEX bit in the NVM CTRLA register. This requires the timed CCP sequence during self-programming.
The BUSY flag in the NVM STATUS register will be set, and the CPU is halted during the execution of the CRC
command. The CRC checksum will be available in the NVM data registers.
XMEGA B [MANUAL] 384
Atmel-8291C-AVR-XMEGA B -09/2014
30.11.2.12 Erase User Signature Row
The erase user signature row command is used to erase the user signature row.
1. Load the NVM CMD register with the erase user signature row command.
2. Execute the SPM instruction. This requires the timed CCP sequence during self-programming.
The BUSY flag in the NVM STATUS register will be set, and the CPU will be halted until the erase operation is finished.
The user signature row is NRWW.
30.11.2.13 Write User Signature Row
The write signature row command is used to write the flash page buffer into the user signature row.
1. Set up the NVM CMD register to write user signature row command.
2. Execute the SPM instruction. This requires the timed CCP sequence during self-programming.
The BUSY flag in the NVM STATUS register will be set until the operation is finished, and the CPU will be halted during
the write operation. The flash page buffer will be cleared during the command execution after the write operation, but the
CPU is not halted during this stage.
30.11.2.14 Read User Signature Row / Production Signature Row
The read user signature row and read calibration row commands are used to read one byte from the user signature row
or production signature (calibration) row.
1. Load the Z-pointer with the byte address to read.
2. Load the NVM CMD register with the read user signature row / production signature (calibration) row command
3. Execute the LPM instruction.
The destination register will be loaded during the execution of the LPM instruction.
To ensure that LPM for reading flash will be executed correctly it is advised to disable interrupt while using either of these
commands.
30.11.3 NVM Fuse and Lock Bit Commands
The NVM flash commands that can be used for accessing the fuses and lock bits are listed in Table 30-3.
For self-programming of the fuses and lock bits, the trigger for action-triggered commands is to set the CMDEX bit in the
NVM CTRLA register (CMDEX). The read-triggered commands are triggered by executing the (E)LPM instruction (LPM).
The write-triggered commands are triggered by a executing the SPM instruction (SPM).
The Change Protected column indicates whether the trigger is protected by the configuration change protection (CCP)
during self-programming or not. The last two columns show the address pointer used for addressing and the
source/destination data register.
Section 30.11.3.1 on page 385 through Section 30.11.3.2 on page 385 explain in detail the algorithm for each NVM
operation.
Table 30-3. Fuse and lock bit commands.
CMD[6:0] Group Configuration Description Trigger
CPU
Halted
Change
Protected
NVM
Busy
Address
Pointer
Data
Register
0x00 NO_OPERATION No operation - - - - - -
Fuses and Lock Bits
0x07 READ_FUSES Read fuses CMDEX Y N Y ADDR DATA
0x08 WRITE_LOCK_BITS Write lock bits CMDEX N Y Y ADDR -
XMEGA B [MANUAL] 385
Atmel-8291C-AVR-XMEGA B -09/2014
30.11.3.1 Write Lock Bits
The write lock bits command is used to program the boot lock bits to a more secure settings from software.
1. Load the NVM DATA0 register with the new lock bit value.
2. Load the NVM CMD register with the write lock bit command.
3. Set the CMDEX bit in the NVM CTRLA register. This requires the timed CCP sequence during self-programming.
The BUSY flag in the NVM STATUS register will be set until the command is finished. The CPU is halted during the
complete execution of the command.
This command can be executed from both the boot loader section and the application section. The EEPROM and flash
page buffers are automatically erased when the lock bits are written.
30.11.3.2 Read Fuses
The read fuses command is used to read the fuses from software.
1. Load the NVM ADDR register with the address of the fuse byte to read.
2. Load the NVM CMD register with the read fuses command.
3. Set the CMDEX bit in the NVM CTRLA register. This requires the timed CCP sequence during self-programming.
The result will be available in the NVM DATA0 register. The CPU is halted during the complete execution of the
command.
30.11.4 EEPROM Programming
The EEPROM can be read and written from application code in any part of the flash. Its is both byte and page accessible.
This means that either one byte or one page can be written to the EEPROM at once. One byte is read from the EEPROM
during a read.
30.11.4.1 Addressing the EEPROM
The EEPROM can be accessed through the NVM controller (I/O mapped), similar to accessing the flash program
memory, or it can be memory mapped into the data memory space to be accessed similar to SRAM.
When accessing the EEPROM through the NVM controller, the NVM address (ADDR) register is used to address the
EEPROM, while the NVM data (DATA) register is used to store or load EEPROM data.
For EEPROM page programming, the ADDR register can be treated as having two sections. The least-significant bits
address the bytes within a page, while the most-significant bits address the page within the EEPROM. This is shown in
Figure 30-2 on page 386. The byte address in the page (E2BYTE) is held by the bits [BYTEMSB:0] in the ADDR register.
The remaining bits [PAGEMSB:BYTEMSB+1] in the ADDR register hold the EEPROM page address (E2PAGE).
Together E2BYTE and E2PAGE hold an absolute address to a byte in the EEPROM. The size of E2WORD and E2PAGE
will depend on the page and flash size in the device. Refer to the device datasheet for details on this.
XMEGA B [MANUAL] 386
Atmel-8291C-AVR-XMEGA B -09/2014
Figure 30-2. I/O mapped EEPROM addressing.
When EEPROM memory mapping is enabled, loading a data byte into the EEPROM page buffer can be performed
through direct or indirect store instructions. Only the least-significant bits of the EEPROM address are used to determine
locations within the page buffer, but the complete memory mapped EEPROM address is always required to ensure
correct address mapping. Reading from the EEPROM can be done directly using direct or indirect load instructions.
When a memory mapped EEPROM page buffer load operation is performed, the CPU is halted for two cycles before the
next instruction is executed.
When the EEPROM is memory mapped, the EEPROM page buffer load and EEPROM read functionality from the NVM
controller are disabled.
30.11.5 NVM EEPROM Commands
The NVM flash commands that can be used for accessing the EEPROM through the NVM controller are listed in Table
30-4.
For self-programming of the EEPROM, the trigger for action-triggered commands is to set the CMDEX bit in the NVM
CTRLA register (CMDEX). The read-triggered command is triggered by reading the NVM DATA0 register (DATA0).
The Change Protected column indicates whether the trigger is protected by the configuration change protection (CCP)
during self-programming or not. CCP is not required for external programming. The last two columns show the address
pointer used for addressing and the source/destination data register.
Section 30.11.5.1 on page 387 through Section 30.11.5.7 on page 388 explain in detail the algorithm for each EEPROM
operation.
Table 30-4. EEPROM self-programming commands.
E2PAGE E2BYTE
BIT
NVM ADDR
PAGEMSB BYTEMSB 0
PAGE DATA BYTE
EEPROM MEMORY PAGE
BYTE ADDRESS
WITHIN A PAGE
PAGE ADDRESS
WITHIN THE EEPROM
E2BYTE
00
01
02
E2PAGEEND
E2PAGE
00
01
02
E2END
CMD[6:0] Group Configuration Description Trigger
CPU
Halted
Change
Protected
NVM
Busy
Address
Pointer
Data
Register
0x00 NO_OPERATION No operation - - - - - -
EEPROM Page Buffer
0x33 LOAD_EEPROM_BUFFER Load EEPROM page buffer DATA0 N Y N ADDR DATA0
0x36 ERASE_EEPROM _BUFFER Erase EEPROM page buffer CMDEX N Y Y - -
XMEGA B [MANUAL] 387
Atmel-8291C-AVR-XMEGA B -09/2014
30.11.5.1 Load EEPROM Page Buffer
The load EEPROM page buffer command is used to load one byte into the EEPROM page buffer.
1. Load the NVM CMD register with the load EEPROM page buffer command.
2. Load the NVM ADDR0 register with the address to write.
3. Load the NVM DATA0 register with the data to write. This will trigger the command.
Repeat steps 2-3 until the arbitrary number of bytes are loaded into the page buffer.
30.11.5.2 Erase EEPROM Page Buffer
The erase EEPROM page buffer command is used to erase the EEPROM page buffer.
1. Load the NVM CMD register with the erase EEPROM buffer command.
2. Set the CMDEX bit in the NVM CTRLA register. This requires the timed CCP sequence during self-programming.
The BUSY flag in the NVM STATUS register will be set until the operation is finished.
30.11.5.3 Erase EEPROM Page
The erase EEPROM page command is used to erase one EEPROM page.
1. Set up the NVM CMD register to the erase EEPROM page command.
2. Load the NVM ADDR register with the address of the EEPROM page to erase.
3. Set the CMDEX bit in the NVM CTRLA register. This requires the timed CCP sequence during self-programming.
The BUSY flag in the NVM STATUS register will be set until the operation is finished.
The page erase commands will only erase the locations that are loaded and tagged in the EEPROM page buffer.
30.11.5.4 Write EEPROM Page
The write EEPROM page command is used to write all locations loaded in the EEPROM page buffer into one page in
EEPROM. Only the locations that are loaded and tagged in the EEPROM page buffer will be written.
1. Load the NVM CMD register with the write EEPROM page command.
2. Load the NVM ADDR register with the address of the EEPROM page to write.
3. Set the CMDEX bit in the NVM CTRLA register. This requires the timed CCP sequence during self-programming.
The BUSY flag in the NVM STATUS register will be set until the operation is finished.
30.11.5.5 Erase and Write EEPROM Page
The erase and write EEPROM page command is used to first erase an EEPROM page and then write the EEPROM
page buffer into that page in EEPROM in one atomic operation.
1. Load the NVM CMD register with the erase and write EEPROM page command.
2. Load the NVM ADDR register with the address of the EEPROM page to write.
3. Set the CMDEX bit in the NVM CTRLA register. This requires the timed CCP sequence during self-programming.
The BUSY flag in the NVM STATUS register will be set until the operation is finished.
EEPROM
0x32 ERASE_EEPROM_PAGE Erase EEPROM page CMDEX N Y Y ADDR -
0x34 WRITE_EEPROM_PAGE Write EEPROM page CMDEX N Y Y ADDR -
0x35 ERASE_WRITE_EEPROM_PAGE Erase and write EEPROM page CMDEX N Y Y ADDR -
0x30 ERASE_EEPROM Erase EEPROM CMDEX N Y Y - -
0x06 READ_EEPROM Read EEPROM CMDEX N Y N ADDR DATA0
CMD[6:0] Group Configuration Description Trigger
CPU
Halted
Change
Protected
NVM
Busy
Address
Pointer
Data
Register
XMEGA B [MANUAL] 388
Atmel-8291C-AVR-XMEGA B -09/2014
30.11.5.6 Erase EEPROM
The erase EEPROM command is used to erase all locations in all EEPROM pages that are loaded and tagged in the
EEPROM page buffer.
1. Set up the NVM CMD register to the erase EPPROM command.
2. Set the CMDEX bit in the NVM CTRLA register. This requires the timed CCP sequence during self-programming.
The BUSY flag in the NVM STATUS register will be set until the operation is finished.
30.11.5.7 Read EEPROM
The read EEPROM command is used to read one byte from the EEPROM.
1. Load the NVM CMD register with the read EEPROM command.
2. Load the NVM ADDR register with the address to read.
3. Set the CMDEX bit in the NVM CTRLA register. This requires the timed CCP sequence during self-programming.
The data byte read will be available in the NVM DATA0 register.
30.12 External Programming
External programming is the method for programming code and nonvolatile data into the device from an external
programmer or debugger. This can be done by both in-system or in mass production programming.
For external programming, the device is accessed through the PDI and PDI controller, and using either the JTAG or PDI
physical connection. For details on PDI and JTAG and how to enable and use the physical interface, refer to “Program
and Debug Interface” on page 361. The remainder of this section assumes that the correct physical connection to the
PDI is enabled. Doing this all data and program memory spaces are mapped into the linear PDI memory space. Figure
30-3 on page 389 shows the PDI memory space and the base address for each memory space in the device.
XMEGA B [MANUAL] 389
Atmel-8291C-AVR-XMEGA B -09/2014
Figure 30-3. Memory map for PDI accessing the data and program memories.
30.12.1 Enabling External Programming Interface
NVM programming from the PDI requires enabling using the following steps:
1. Load the RESET register in the PDI with 0x59.
2. Load the NVM key in the PDI.
3. Poll NVMEN in the PDI status register (PDI STATUS) until NVMEN is set.
When the NVMEN bit in the PDI STATUS register is set, the NVM interface is enabled and active from the PDI.
30.12.2 NVM Programming
When the PDI NVM interface is enabled, all memories in the device are memory mapped in the PDI address space. The
PDI controller does not need to access the NVM controller's address or data registers, but the NVM controller must be
loaded with the correct command (i.e., to read from any NVM, the controller must be loaded with the NVM read command
FLASH_BASE = 0x0800000
EPPROM_BASE = 0x08C0000
FUSE_BASE = 0x08F0020
DATAMEM_BASE = 0x1000000
APP_BASE = FLASH_BASE
BOOT_BASE = FLASH_BASE + SIZE_APPL
PROD_SIGNATURE_BASE = 0x008E0200
USER_SIGNATURE_BASE = 0x008E0400
0x0000000
FUSES
APPLICATION
SECTION
16 MB
BOOT SECTION
0x0800000
0x08F0020
TOP=0x1FFFFFF
EEPROM
0x08E0200 SIGNATURE ROW
0x08C0000
0x08C1000
DATAMEM
(mapped IO/SRAM) 16 MB
0x1000000
1 BYTE
XMEGA B [MANUAL] 390
Atmel-8291C-AVR-XMEGA B -09/2014
before loading data from the PDIBUS address space). For the reminder of this section, all references to reading and
writing data or program memory addresses from the PDI refer to the memory map shown in Figure 30-3 on page 389.
The PDI uses byte addressing, and hence all memory addresses must be byte addresses. When filling the flash or
EEPROM page buffers, only the least-significant bits of the address are used to determine locations within the page
buffer. Still, the complete memory mapped address for the flash or EEPROM page is required to ensure correct address
mapping.
During programming (page erase and page write) when the NVM is busy, the NVM is blocked for reading.
30.12.3 NVM Commands
The NVM commands that can be used for accessing the NVM memories from external programming are listed in Table
30-5 on page 390. This is a superset of the commands available for self-programming.
For external programming, the trigger for action-triggered commands is to set the CMDEX bit in the NVM CTRLA register
(CMDEX). The read-triggered commands are triggered by a direct or indirect load instruction (LDS or LD) from the PDI
(PDI read). The write-triggered commands are triggered by a direct or indirect store instruction (STS or ST) from the PDI
(PDI write).
“ Chip Erase” on page 391 through “ Write Fuse/ Lock Bit” on page 393 explain in detail the algorithm for each NVM
operation. The commands are protected by the lock bits, and if read and write lock is set, only the chip erase and flash
CRC commands are available.
Table 30-5. NVM commands available for external programming.
CMD[6:0] Commands / Operation Trigger
Change
Protected NVM Busy
0x00 No operation - - -
0x40 Chip erase(1) CMDEX Y Y
0x43 Read NVM PDI Read N N
Flash Page Buffer
0x23 Load flash page buffer PDI Write N N
0x26 Erase flash page buffer CMDEX Y Y
Flash
0x2B Erase flash page PDI write N Y
0x2E Write flash page PDI write N Y
0x2F Erase and write flash page PDI write N Y
0x78 Flash CRC CMDEX Y Y
Application Section
0x20 Erase application section PDI write N Y
0x22 Erase application section page PDI write N Y
0x24 Write application section page PDI write N Y
0x25 Erase and write application section page PDI write N Y
0x38 Application section CRC CMDEX Y Y
Boot Loader Section
0x68 Erase boot section PDI write N Y
0x2A Erase boot loader section page PDI write N Y
0x2C Write boot loader section page PDI write N Y
XMEGA B [MANUAL] 391
Atmel-8291C-AVR-XMEGA B -09/2014
Notes: 1. If the EESAVE fuse is programmed, the EEPROM is preserved during chip erase.
2. For consistency the name Calibration Row has been renamed to Production Signature Row throughout the document.
30.12.3.1 Chip Erase
The chip erase command is used to erase the flash program memory, EEPROM and lock bits. Erasing of the EEPROM
depends on EESAVE fuse setting. Refer to “FUSEBYTE5 – Fuse Byte 5” on page 32 for details. The user signature row,
production signature (calibration) row, and fuses are not affected.
1. Load the NVM CMD register with the chip erase command.
2. Set the CMDEX bit in the NVM CTRLA register. This requires the timed CCP sequence during self-programming.
Once this operation starts, the PDI bus between the PDI controller and the NVM is disabled, and the NVMEN bit in the
PDI STATUS register is cleared until the operation is finished. Poll the NVMEN bit until this is set, indicating that the PDI
bus is enabled.
The BUSY flag in the NVM STATUS register will be set until the operation is finished.
30.12.3.2 Read NVM
The read NVM command is used to read the flash, EEPROM, fuses, and signature and production signature (calibration)
row sections.
1. Load the NVM CMD register with the read NVM command.
2. Read the selected memory address by executing a PDI read operation.
0x2D Erase and write boot loader section page PDI write N Y
0x39 Boot loader section CRC NVMAA Y Y
Production Signature (Calibration)(2) and User Signature Sections
0x01 Read user signature row PDI read N N
0x18 Erase user signature row PDI write N Y
0x1A Write user signature row PDI write N Y
0x02 Read calibration row PDI read N N
Fuses and Lock Bits
0x07 Read fuse PDI read N N
0x4C Write fuse PDI write N Y
0x08 Write lock bits CMDEX Y Y
EEPROM Page Buffer
0x33 Load EEPROM page buffer PDI write N N
0x36 Erase EEPROM page buffer CMDEX Y Y
EEPROM
0x30 Erase EEPROM CMDEX Y Y
0x32 Erase EEPROM page PDI write N Y
0x34 Write EEPROM page PDI write N Y
0x35 Erase and write EEPROM page PDI write N Y
0x06 Read EEPROM PDI read N N
CMD[6:0] Commands / Operation Trigger
Change
Protected NVM Busy
XMEGA B [MANUAL] 392
Atmel-8291C-AVR-XMEGA B -09/2014
Dedicated read EEPROM, read fuse, read signature row, and read production signature (calibration) row commands are
also available for the various memory sections. The algorithm for these commands are the same as for the read NVM
command.
30.12.3.3 Erase Page Buffer
The erase flash page buffer and erase EEPROM page buffer commands are used to erase the flash and EEPROM page
buffers.
1. Load the NVM CMD register with the erase flash/EEPROM page buffer command.
2. Set the CMDEX bit in the NVM CTRLA register.
The BUSY flag in the NVM STATUS register will be set until the operation is completed.
30.12.3.4 Load Page Buffer
The load flash page buffer and load EEPROM page buffer commands are used to load one byte of data into the flash and
EEPROM page buffers.
1. Load the NVM CMD register with the load flash/EEPROM page buffer command.
2. Write the selected memory address by doing a PDI write operation.
Since the flash page buffer is word accessed and the PDI uses byte addressing, the PDI must write the flash page buffer
in the correct order. For the write operation, the low byte of the word location must be written before the high byte. The
low byte is then written into the temporary register. The PDI then writes the high byte of the word location, and the low
byte is then written into the word location page buffer in the same clock cycle.
The PDI interface is automatically halted before the next PDI instruction can be executed.
30.12.3.5 Erase Page
The erase application section page, erase boot loader section page, erase user signature row, and erase EEPROM page
commands are used to erase one page in the selected memory space.
1. Load the NVM CMD register with erase application section/boot loader section/user signature row/EEPROM page
command.
2. Set the CMDEX bit in the NVM CTRLA register.
The BUSY flag in the NVM STATUS register will be set until the operation is finished.
30.12.3.6 Write Page
The write application section page, write boot loader section page, write user signature row, and write EEPROM page
commands are used to write a loaded flash/EEPROM page buffer into the selected memory space.
1. Load the NVM CMD register with write application section/boot loader section/user signature row/EEPROM page
command.
2. Write the selected page by doing a PDI write. The page is written by addressing any byte location within the page.
The BUSY flag in the NVM STATUS register will be set until the operation is finished.
30.12.3.7 Erase and Write Page
The erase and write application section page, erase and write boot loader section page, and erase and write EEPROM
page commands are used to erase one page and then write a loaded flash/EEPROM page buffer into that page in the
selected memory space in one atomic operation.
1. Load the NVM CMD register with erase and write application section/boot loader section/user signature
row/EEPROM page command.
2. Write the selected page by doing a PDI write. The page is written by addressing any byte location within the page.
The BUSY flag in the NVM STATUS register will be set until the operation is finished.
30.12.3.8 Erase Application/ Boot Loader/ EEPROM Section
The erase application section, erase boot loader section, and erase EEPROM section commands are used to erase the
complete selected section.
XMEGA B [MANUAL] 393
Atmel-8291C-AVR-XMEGA B -09/2014
1. Load the NVM CMD register with Erase Application/ Boot/ EEPROM Section command
2. Set the CMDEX bit in the NVM CTRLA register.
The BUSY flag in the NVM STATUS register will be set until the operation is finished.
30.12.3.9 Application / Boot Section CRC
The application section CRC and boot loader section CRC commands can be used to verify the content of the selected
section after programming.
1. Load the NVM CMD register with application/ boot loader section CRC command.
2. Set the CMDEX bit in the NVM CTRLA register. This requires the timed CCP sequence during self-programming.
The BUSY flag in the NVM STATUS register will be set until the operation is finished. The CRC checksum will be
available in the NVM DATA register.
30.12.3.10 Flash CRC
The flash CRC command can be used to verify the content of the flash program memory after programming. The
command can be executed independently of the lock bit state.
1. Load the NVM CMD register with flash CRC command.
2. Set the CMDEX bit in the NVM CTRLA register.
Once this operation starts, the PDI bus between the PDI controller and the NVM is disabled, and the NVMEN bit in the
PDI STATUS register is cleared until the operation is finished. Poll the NVMEN bit until this is set again, indicting the PDI
bus is enabled.
The BUSY flag in the NVM STATUS register will be set until the operation is finished. The CRC checksum will be
available in the NVM DATA register.
30.12.3.11 Write Fuse/ Lock Bit
The write fuse and write lock bit commands are used to write the fuses and the lock bits to a more secure setting.
1. Load the NVM CMD register with the write fuse/ lock bit command.
2. Write the selected fuse or lock bits by doing a PDI write operation.
The BUSY flag in the NVM STATUS register will be set until the command is finished.
For lock bit write, the lock bit write command can also be used.
30.13 Register Description
Refer to “Register Description – NVM Controller” on page 26 for a complete register description of the NVM controller.
Refer to “Register Description – PDI Control and Status Registers” on page 373 for a complete register description of the
PDI.
30.14 Register Summary
Refer to “Register Description – NVM Controller” on page 26 for a complete register summary of the NVM controller.
Refer to “Register Summary” on page 374 for a complete register summary of the PDI.
XMEGA B [MANUAL] 394
Atmel-8291C-AVR-XMEGA B -09/2014
31. Peripheral Module Address Map
The address maps show the base address for each peripheral and module in XMEGA. All peripherals and modules are
not present in all XMEGA devices, refer to device data sheet for the peripherals module address map for a specific
device.
Base Address Name Description Page
0x0000 GPIO General Purpose IO Registers page 42
0x0010 VPORT0 Virtual Port 0 page 132
0x0014 VPORT1 Virtual Port 1
0x0018 VPORT2 Virtual Port 2
0x001C VPORT3 Virtual Port 3
0x0030 CPU CPU page 19
0x0040 CLK Clock Control page 96
0x0048 SLEEP Sleep Controller page 101
0x0050 OSC Oscillator Control page 96
0x0060 DFLLRC32M DFLL for the 32 MHz Internal RC Oscillator page 96
0x0068 DFLLRC2M DFLL for the 2 MHz RC Oscillator
0x0070 PR Power Reduction page 98
0x0078 RST Reset Controller page 109
0x0080 WDT Watch-Dog Timer page 114
0x0090 MCU MCU Control page 42
0x00A0 PMIC Programmable Multilevel Interrupt Controller page 122
0x00B0 PORTCFG Port Configuration page 146
0x00C0 AES AES Module page 292
0x0100 DMA DMA Controller page 62
0x0180 EVSYS Event System page 74
0x01C0 NVM Non Volatile Memory (NVM) Controller page 46
0x0200 ADCA Analog to Digital Converter on port A page 344
0x0240 ADCB Analog to Digital Converter on port B
0x0380 ACA Analog Comparator pair on port A page 353
0x0390 ACB Analog Comparator pair on port B
0x0400 RTC Real Time Counter page 205
0x0480 TWIC Two Wire Interface on port C page 254
0x04C0 USB Universal Serial Bus Interface page 281
0x0600 PORTA Port A page 146
0x0620 PORTB Port B
0x0640 PORTC Port C
0x0660 PORTD Port D
0x0680 PORTE Port E
0x06C0 PORTG Port G
0x0760 PORTM Port M
0x07E0 PORTR Port R
0x0800 TCC0 Timer/Counter 0 on port C page 172
0x0840 TCC1 Timer/Counter 1 on port C
0x0880 AWEXC Advanced Waveform Extension on port C page 195
0x0890 HIRESC High Resolution Extension on port C page 197
0x08A0 USARTC0 USART 0 on port C page 281
0x08C0 SPIC Serial Peripheral Interface on port C page 260
0x08F0 IRCOM Infrared Communication Module page 285
0x0A00 TCE0 Timer/Counter 0 on port E page 172
0x0AA0 USARTE0 USART 0 on port E page 281
0x0D00 LCD LCD - Liquid Crystal Display page 319
Atmel-8291C-AVR-XMEGA B -09/2014 395
32. Instruction Set Summary
Mnemonics Operands Description Operation Flags #Clocks
Arithmetic and Logic Instructions
ADD Rd, Rr Add without Carry Rd ← Rd + Rr Z,C,N,V,S,H 1
ADC Rd, Rr Add with Carry Rd ← Rd + Rr + C Z,C,N,V,S,H 1
ADIW Rd, K Add Immediate to Word Rd ← Rd + 1:Rd + K Z,C,N,V,S 2
SUB Rd, Rr Subtract without Carry Rd ← Rd - Rr Z,C,N,V,S,H 1
SUBI Rd, K Subtract Immediate Rd ← Rd - K Z,C,N,V,S,H 1
SBC Rd, Rr Subtract with Carry Rd ← Rd - Rr - C Z,C,N,V,S,H 1
SBCI Rd, K Subtract Immediate with Carry Rd ← Rd - K - C Z,C,N,V,S,H 1
SBIW Rd, K Subtract Immediate from Word Rd + 1:Rd ← Rd + 1:Rd - K Z,C,N,V,S 2
AND Rd, Rr Logical AND Rd ← Rd • Rr Z,N,V,S 1
ANDI Rd, K Logical AND with Immediate Rd ← Rd • K Z,N,V,S 1
OR Rd, Rr Logical OR Rd ← Rd v Rr Z,N,V,S 1
ORI Rd, K Logical OR with Immediate Rd ← Rd v K Z,N,V,S 1
EOR Rd, Rr Exclusive OR Rd ← Rd ⊕ Rr Z,N,V,S 1
COM Rd One’s Complement Rd ← $FF - Rd Z,C,N,V,S 1
NEG Rd Two’s Complement Rd ← $00 - Rd Z,C,N,V,S,H 1
SBR Rd,K Set Bit(s) in Register Rd ← Rd v K Z,N,V,S 1
CBR Rd,K Clear Bit(s) in Register Rd ← Rd • ($FFh - K) Z,N,V,S 1
INC Rd Increment Rd ← Rd + 1 Z,N,V,S 1
DEC Rd Decrement Rd ← Rd - 1 Z,N,V,S 1
TST Rd Test for Zero or Minus Rd ← Rd • Rd Z,N,V,S 1
CLR Rd Clear Register Rd ← Rd ⊕ Rd Z,N,V,S 1
SER Rd Set Register Rd ← $FF None 1
MUL Rd,Rr Multiply Unsigned R1:R0 ← Rd x Rr (UU) Z,C 2
MULS Rd,Rr Multiply Signed R1:R0 ← Rd x Rr (SS) Z,C 2
MULSU Rd,Rr Multiply Signed with Unsigned R1:R0 ← Rd x Rr (SU) Z,C 2
FMUL Rd,Rr Fractional Multiply Unsigned R1:R0 ← Rd x Rr<<1 (UU) Z,C 2
FMULS Rd,Rr Fractional Multiply Signed R1:R0 ← Rd x Rr<<1 (SS) Z,C 2
FMULSU Rd,Rr Fractional Multiply Signed with Unsigned R1:R0 ← Rd x Rr<<1 (SU) Z,C 2
DES K Data Encryption if (H = 0) then R15:R0
else if (H = 1) then
R15:R0
←
←
Encrypt(R15:R0, K)
Decrypt(R15:R0, K)
1/2
Branch instructions
RJMP k Relative Jump PC ← PC + k + 1 None 2
IJMP Indirect Jump to (Z) PC(15:0)
PC(21:16)
←
←
Z,
0
None 2
EIJMP Extended Indirect Jump to (Z) PC(15:0)
PC(21:16)
←
←
Z,
EIND
None 2
JMP k Jump PC ← k None 3
Atmel-8291C-AVR-XMEGA B -09/2014 396
RCALL k Relative Call Subroutine PC ← PC + k + 1 None 2 / 3(1)
ICALL Indirect Call to (Z) PC(15:0)
PC(21:16)
←
←
Z,
0
None 2 / 3(1)
EICALL Extended Indirect Call to (Z) PC(15:0)
PC(21:16)
←
←
Z,
EIND
None 3(1)
CALL k call Subroutine PC ← k None 3 / 4(1)
RET Subroutine Return PC ← STACK None 4 / 5(1)
RETI Interrupt Return PC ← STACK I 4 / 5(1)
CPSE Rd,Rr Compare, Skip if Equal if (Rd = Rr) PC ← PC + 2 or 3 None 1 / 2 / 3
CP Rd,Rr Compare Rd - Rr Z,C,N,V,S,H 1
CPC Rd,Rr Compare with Carry Rd - Rr - C Z,C,N,V,S,H 1
CPI Rd,K Compare with Immediate Rd - K Z,C,N,V,S,H 1
SBRC Rr, b Skip if Bit in Register Cleared if (Rr(b) = 0) PC ← PC + 2 or 3 None 1 / 2 / 3
SBRS Rr, b Skip if Bit in Register Set if (Rr(b) = 1) PC ← PC + 2 or 3 None 1 / 2 / 3
SBIC A, b Skip if Bit in I/O Register Cleared if (I/O(A,b) = 0) PC ← PC + 2 or 3 None 2 / 3 / 4
SBIS A, b Skip if Bit in I/O Register Set If (I/O(A,b) =1) PC ← PC + 2 or 3 None 2 / 3 / 4
BRBS s, k Branch if Status Flag Set if (SREG(s) = 1) then PC ← PC + k + 1 None 1 / 2
BRBC s, k Branch if Status Flag Cleared if (SREG(s) = 0) then PC ← PC + k + 1 None 1 / 2
BREQ k Branch if Equal if (Z = 1) then PC ← PC + k + 1 None 1 / 2
BRNE k Branch if Not Equal if (Z = 0) then PC ← PC + k + 1 None 1 / 2
BRCS k Branch if Carry Set if (C = 1) then PC ← PC + k + 1 None 1 / 2
BRCC k Branch if Carry Cleared if (C = 0) then PC ← PC + k + 1 None 1 / 2
BRSH k Branch if Same or Higher if (C = 0) then PC ← PC + k + 1 None 1 / 2
BRLO k Branch if Lower if (C = 1) then PC ← PC + k + 1 None 1 / 2
BRMI k Branch if Minus if (N = 1) then PC ← PC + k + 1 None 1 / 2
BRPL k Branch if Plus if (N = 0) then PC ← PC + k + 1 None 1 / 2
BRGE k Branch if Greater or Equal, Signed if (N ⊕ V= 0) then PC ← PC + k + 1 None 1 / 2
BRLT k Branch if Less Than, Signed if (N ⊕ V= 1) then PC ← PC + k + 1 None 1 / 2
BRHS k Branch if Half Carry Flag Set if (H = 1) then PC ← PC + k + 1 None 1 / 2
BRHC k Branch if Half Carry Flag Cleared if (H = 0) then PC ← PC + k + 1 None 1 / 2
BRTS k Branch if T Flag Set if (T = 1) then PC ← PC + k + 1 None 1 / 2
BRTC k Branch if T Flag Cleared if (T = 0) then PC ← PC + k + 1 None 1 / 2
BRVS k Branch if Overflow Flag is Set if (V = 1) then PC ← PC + k + 1 None 1 / 2
BRVC k Branch if Overflow Flag is Cleared if (V = 0) then PC ← PC + k + 1 None 1 / 2
BRIE k Branch if Interrupt Enabled if (I = 1) then PC ← PC + k + 1 None 1 / 2
BRID k Branch if Interrupt Disabled if (I = 0) then PC ← PC + k + 1 None 1 / 2
Data transfer instructions
MOV Rd, Rr Copy Register Rd ← Rr None 1
MOVW Rd, Rr Copy Register Pair Rd+1:Rd ← Rr+1:Rr None 1
Mnemonics Operands Description Operation Flags #Clocks
Atmel-8291C-AVR-XMEGA B -09/2014 397
LDI Rd, K Load Immediate Rd ← K None 1
LDS Rd, k Load Direct from data space Rd ← (k) None 2(1)(2)
LD Rd, X Load Indirect Rd ← (X) None 1(1)(2)
LD Rd, X+ Load Indirect and Post-Increment Rd
X
←
←
(X)
X + 1
None 1(1)(2)
LD Rd, -X Load Indirect and Pre-Decrement X ← X - 1,
Rd ← (X)
←
←
X - 1
(X)
None 2(1)(2)
LD Rd, Y Load Indirect Rd ← (Y) ← (Y) None 1(1)(2)
LD Rd, Y+ Load Indirect and Post-Increment Rd
Y
←
←
(Y)
Y + 1
None 1(1)(2)
LD Rd, -Y Load Indirect and Pre-Decrement Y
Rd
←
←
Y - 1
(Y)
None 2(1)(2)
LDD Rd, Y+q Load Indirect with Displacement Rd ← (Y + q) None 2(1)(2)
LD Rd, Z Load Indirect Rd ← (Z) None 1(1)(2)
LD Rd, Z+ Load Indirect and Post-Increment Rd
Z
←
←
(Z),
Z+1
None 1(1)(2)
LD Rd, -Z Load Indirect and Pre-Decrement Z
Rd
←
←
Z - 1,
(Z)
None 2(1)(2)
LDD Rd, Z+q Load Indirect with Displacement Rd ← (Z + q) None 2(1)(2)
STS k, Rr Store Direct to Data Space (k) ← Rd None 2(1)
ST X, Rr Store Indirect (X) ← Rr None 1(1)
ST X+, Rr Store Indirect and Post-Increment (X)
X
←
←
Rr,
X + 1
None 1(1)
ST -X, Rr Store Indirect and Pre-Decrement X
(X)
←
←
X - 1,
Rr
None 2(1)
ST Y, Rr Store Indirect (Y) ← Rr None 1(1)
ST Y+, Rr Store Indirect and Post-Increment (Y)
Y
←
←
Rr,
Y + 1
None 1(1)
ST -Y, Rr Store Indirect and Pre-Decrement Y
(Y)
←
←
Y - 1,
Rr
None 2(1)
STD Y+q, Rr Store Indirect with Displacement (Y + q) ← Rr None 2(1)
ST Z, Rr Store Indirect (Z) ← Rr None 1(1)
ST Z+, Rr Store Indirect and Post-Increment (Z)
Z
←
←
Rr
Z + 1
None 1(1)
ST -Z, Rr Store Indirect and Pre-Decrement Z ← Z - 1 None 2(1)
STD Z+q,Rr Store Indirect with Displacement (Z + q) ← Rr None 2(1)
LPM Load Program Memory R0 ← (Z) None 3
LPM Rd, Z Load Program Memory Rd ← (Z) None 3
LPM Rd, Z+ Load Program Memory and PostIncrement
Rd
Z
←
←
(Z),
Z + 1
None 3
ELPM Extended Load Program Memory R0 ← (RAMPZ:Z) None 3
ELPM Rd, Z Extended Load Program Memory Rd ← (RAMPZ:Z) None 3
ELPM Rd, Z+ Extended Load Program Memory and
Post-Increment
Rd
Z
←
←
(RAMPZ:Z),
Z + 1
None 3
SPM Store Program Memory (RAMPZ:Z) ← R1:R0 None -
Mnemonics Operands Description Operation Flags #Clocks
Atmel-8291C-AVR-XMEGA B -09/2014 398
SPM Z+ Store Program Memory and PostIncrement
by 2
(RAMPZ:Z)
Z
←
←
R1:R0,
Z + 2
None -
IN Rd, A In From I/O Location Rd ← I/O(A) None 1
OUT A, Rr Out To I/O Location I/O(A) ← Rr None 1
PUSH Rr Push Register on Stack STACK ← Rr None 1(1)
POP Rd Pop Register from Stack Rd ← STACK None 2(1)
XCH Z, Rd Exchange RAM location Temp
Rd
(Z)
←
←
←
Rd,
(Z),
Temp
None 2
LAS Z, Rd Load and Set RAM location Temp
Rd
(Z)
←
←
←
Rd,
(Z),
Temp v (Z)
None 2
LAC Z, Rd Load and Clear RAM location Temp
Rd
(Z)
←
←
←
Rd,
(Z),
($FFh – Rd) • (Z)
None 2
LAT Z, Rd Load and Toggle RAM location Temp
Rd
(Z)
←
←
←
Rd,
(Z),
Temp ⊕ (Z)
None 2
Bit and bit-test instructions
LSL Rd Logical Shift Left Rd(n+1)
Rd(0)
C
←
←
←
Rd(n),
0,
Rd(7)
Z,C,N,V,H 1
LSR Rd Logical Shift Right Rd(n)
Rd(7)
C
←
←
←
Rd(n+1),
0,
Rd(0)
Z,C,N,V 1
ROL Rd Rotate Left Through Carry Rd(0)
Rd(n+1)
C
←
←
←
C,
Rd(n),
Rd(7)
Z,C,N,V,H 1
ROR Rd Rotate Right Through Carry Rd(7)
Rd(n)
C
←
←
←
C,
Rd(n+1),
Rd(0)
Z,C,N,V 1
ASR Rd Arithmetic Shift Right Rd(n) ← Rd(n+1), n=0..6 Z,C,N,V 1
SWAP Rd Swap Nibbles Rd(3..0) ↔ Rd(7..4) None 1
BSET s Flag Set SREG(s) ← 1 SREG(s) 1
BCLR s Flag Clear SREG(s) ← 0 SREG(s) 1
SBI A, b Set Bit in I/O Register I/O(A, b) ← 1 None 1
CBI A, b Clear Bit in I/O Register I/O(A, b) ← 0 None 1
BST Rr, b Bit Store from Register to T T ← Rr(b) T 1
BLD Rd, b Bit load from T to Register Rd(b) ← T None 1
SEC Set Carry C ← 1 C 1
CLC Clear Carry C ← 0 C 1
SEN Set Negative Flag N ← 1 N 1
CLN Clear Negative Flag N ← 0 N 1
SEZ Set Zero Flag Z ← 1 Z 1
CLZ Clear Zero Flag Z ← 0 Z 1
SEI Global Interrupt Enable I ← 1 I 1
CLI Global Interrupt Disable I ← 0 I 1
Mnemonics Operands Description Operation Flags #Clocks
Atmel-8291C-AVR-XMEGA B -09/2014 399
Notes: 1. Cycle times for data memory accesses assume internal memory accesses, and are not valid for accesses via the external RAM interface.
2. One extra cycle must be added when accessing Internal SRAM.
SES Set Signed Test Flag S ← 1 S 1
CLS Clear Signed Test Flag S ← 0 S 1
SEV Set Two’s Complement Overflow V ← 1 V 1
CLV Clear Two’s Complement Overflow V ← 0 V 1
SET Set T in SREG T ← 1 T 1
CLT Clear T in SREG T ← 0 T 1
SEH Set Half Carry Flag in SREG H ← 1 H 1
CLH Clear Half Carry Flag in SREG H ← 0 H 1
MCU control instructions
BREAK Break (See specific descr. for BREAK) None 1
NOP No Operation None 1
SLEEP Sleep (see specific descr. for Sleep) None 1
WDR Watchdog Reset (see specific descr. for WDR) None 1
Mnemonics Operands Description Operation Flags #Clocks
XMEGA B [MANUAL] 400
Atmel-8291C-AVR-XMEGA B -09/2014
33. Datasheet Revision History
Please note that the referring page numbers in this section are referring to this document. The referring revision in this
section are referring to the document revision.
33.1 8291C – 06/2014
33.2 8291B – 01/2013
1. Replaced RCOSC48M with USBRCOSC in Section 4.15.19 on page 40 and in Section 4.20 on page 45.
2. Changed VCC to AVCC in the section “AC – Analog Comparator” on page 345 and onwards, and in “Voltage
Reference Selection” on page 324.
3. Updated last page and footers from template of May 5 2014.
1. Added XMEGA B feature overview inTable 2-1 on page 5.
2. References to Calibration Row updated to Production Signature Row for consistency.
3. Added reference to “NVM Flash Commands” on page 380 in “Production Signature Row” on page 22.
4. Updated “LOCKBITS – Lock Bits register” on page 30. Description of Bit[1:0] updated and added a table note.
5. Title of Table 4-12 on page 35 changed to “Lock bit protection mode.”
6. Updated “TRIGSRC – Trigger Source” on page 57. The description Bit[7:0] updated.
7 Updated description of “CHnCTRL – Event Channel n Control register” on page 72.
8. Updated the formula of COMP register in “DFLL 2MHz and DFLL 32MHz” on page 82.
9. Updated Table 9-2 on page 105, the “Programmable BODLEVEL setting.”
10. Table note added to the Table 10-1 on page 112.
11. Table note added to the Table 10-2 on page 113.
12. Updated “Port Interrupt” on page 129.
13. Updated Table 12-3 on page 130. “Both edge” replaced by “Any edge”.
14. Updated “Port Event” on page 130.
15. Updated Table 12-10 on page 142, and Table 12-11 on page 143.
16. Updated “Event Action Controlled Operation” on page 153.
17. Updated Figure 13-10 on page 155. CH7MUX changed to CHnMUX.
18 Updated Table 13-2 in “DMA Support” on page 160.
19. Updated Table 14-3 on page 179. CMD changed to BYTEM[1:0]
20. Updated “Clock Domains” on page 199.
21. Updated description in “For Output Endpoints” on page 213.
22. Updated both formula of “BAUD – Baud Rate register” on page 247
23. Updated “DATA – Data register” on page 248. Added the description of ADDR[7:1] and ADDR[0]
XMEGA B [MANUAL] 401
Atmel-8291C-AVR-XMEGA B -09/2014
33.3 8291A – 07/2011
24. Updated the formula in “Fractional Baud Rate Generation” on page 271.
25. Updated Figure 21-9 on page 272, the “Fractional baud rate example.”
26. Added Table 21-5 on page 272, the “USART baud rate.”
27. Updated “ADC Input Model” on page 329.
26. Updated “Synchronous Sampling” on page 330.
27 Updated description of “Bit 3:0 – COUNT[3:0]: Number of Input Channels Included in Scan” in “SCAN – Input
Channel Scan register” on page 343
28. Updated Analog Comparator overview block diagram in Figure 27-1 on page 346.
1. Initial revision edited from XMEGA AU Manual rev A 07/11
XMEGA B [MANUAL] 402
Atmel-8291C-AVR-XMEGA B -09/2014
Table of Contents
1. About the Manual . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.1 Reading the Manual . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.2 Resources. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.3 Recommended Reading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
2. Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
3. Atmel AVR CPU . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
3.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
3.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
3.3 Architectural Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
3.4 ALU - Arithmetic Logic Unit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3.5 Program Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
3.6 Instruction Execution Timing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
3.7 Status Register . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
3.8 Stack and Stack Pointer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
3.9 Register File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
3.10 RAMP and Extended Indirect Registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
3.11 Accessing 16-bit Registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
3.12 Configuration Change Protection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
3.13 Fuse Lock . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
3.14 Register Descriptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
3.15 Register Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
4. Memories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
4.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
4.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
4.3 Flash Program Memory. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
4.4 Fuses and Lockbits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
4.5 Data Memory. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
4.6 Internal SRAM. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
4.7 EEPROM. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
4.8 I/O Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
4.9 Data Memory and Bus Arbitration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
4.10 Memory Timing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
4.11 Device ID and Revision. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
4.12 I/O Memory Protection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
4.13 Register Description – NVM Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
4.14 Register Descriptions – Fuses and Lock Bits . . . . . . . . . . . . . . . . . . . . . . . . . 30
4.15 Register Description – Production Signature Row . . . . . . . . . . . . . . . . . . . . . 36
4.16 Register Description – General Purpose I/O Memory. . . . . . . . . . . . . . . . . . . 42
4.17 Register Descriptions – MCU Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
4.18 Register Summary - NVM Controller. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
4.19 Register Summary - Fuses and Lock Bits. . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
4.20 Register Summary - Production Signature Row . . . . . . . . . . . . . . . . . . . . . . . 45
4.21 Register Summary – General Purpose I/O Registers . . . . . . . . . . . . . . . . . . . 46
4.22 Register Summary – MCU Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
4.23 Interrupt Vector Summary – NVM Controller . . . . . . . . . . . . . . . . . . . . . . . . . 46
XMEGA B [MANUAL] 403
Atmel-8291C-AVR-XMEGA B -09/2014
5. DMAC - Direct Memory Access Controller . . . . . . . . . . . . . . . . . . . . . . . . . 47
5.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
5.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
5.3 DMA Transaction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
5.4 Transfer Triggers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
5.5 Addressing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
5.6 Priority Between Channels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
5.7 Double Buffering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
5.8 Transfer Buffers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
5.9 Error detection. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
5.10 Software Reset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
5.11 Protection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
5.12 Interrupts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
5.13 Register Description – DMA Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
5.14 Register Description – DMA Channel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
5.15 Register Summary – DMA Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
5.16 Register Summary – DMA Channel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
5.17 DMA Interrupt Vector Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
6. Event System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
6.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
6.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
6.3 Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
6.4 Event Routing Network . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
6.5 Event Timing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
6.6 Filtering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
6.7 Quadrature Decoder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
6.8 Register Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
6.9 Register Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
7. System Clock and Clock Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
7.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
7.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
7.3 Clock Distribution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
7.4 Clock Sources. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
7.5 System Clock Selection and Prescalers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
7.6 PLL with 1x-31x Multiplication Factor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
7.7 DFLL 2MHz and DFLL 32MHz . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
7.8 PLL and External Clock Source Failure Monitor . . . . . . . . . . . . . . . . . . . . . . . 82
7.9 Register Description – Clock. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
7.10 Register Description – Oscillator. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
7.11 Register Description – DFLL32M/DFLL2M . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
7.12 Register Summary - Clock . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
7.13 Register Summary - Oscillator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
7.14 Register Summary - DFLL32M/DFLL2M. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
7.15 Oscillator Failure Interrupt Vector Summary . . . . . . . . . . . . . . . . . . . . . . . . . . 94
8. Power Management and Sleep Modes . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
8.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
8.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
8.3 Sleep Modes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
XMEGA B [MANUAL] 404
Atmel-8291C-AVR-XMEGA B -09/2014
8.4 Power Reduction Registers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
8.5 Minimizing Power Consumption . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
8.6 Register Description – Sleep. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
8.7 Register Description – Power Reduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
8.8 Register Summary - Sleep . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
8.9 Register Summary - Power Reduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
9. Reset System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
9.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
9.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
9.3 Reset Sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
9.4 Reset Sources. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
9.5 Register Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
9.6 Register Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
10. WDT – Watchdog Timer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
10.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
10.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
10.3 Normal Mode Operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
10.4 Window Mode Operation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
10.5 Watchdog Timer Clock . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
10.6 Configuration Protection and Lock . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
10.7 Registers Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
10.8 Register Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
11. Interrupts and Programmable Multilevel Interrupt Controller . . . . . . . 115
11.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
11.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
11.3 Operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
11.4 Interrupts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
11.5 Interrupt level . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
11.6 Interrupt priority. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
11.7 Interrupt vector locations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
11.8 Register Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
11.9 Register Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
12. I/O Ports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
12.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
12.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
12.3 I/O Pin Use and Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
12.4 Reading the Pin Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
12.5 Input Sense Configuration. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
12.6 Port Interrupt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
12.7 Port Event . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
12.8 Alternate Port Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
12.9 Clock and Event Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
12.10 Multi-pin configuration. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
12.11 Virtual Ports. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
12.12 Register Descriptions – Ports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
12.13 Register Descriptions – Port Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . 140
12.14 Register Descriptions – Virtual Port . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
12.15 Register Summary – Ports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
XMEGA B [MANUAL] 405
Atmel-8291C-AVR-XMEGA B -09/2014
12.16 Register Summary – Port Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
12.17 Register Summary – Virtual Ports. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
12.18 Interrupt Vector Summary – Ports. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
13. TC0/1 – 16-bit Timer/Counter Type 0 and 1 . . . . . . . . . . . . . . . . . . . . . . 148
13.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
13.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
13.3 Block Diagram. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
13.4 Clock and Event Sources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
13.5 Double Buffering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
13.6 Counter Operation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
13.7 Capture Channel. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
13.8 Compare Channel. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
13.9 Interrupts and events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
13.10 DMA Support. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
13.11 Timer/Counter Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
13.12 Register Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
13.13 Register Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
13.14 Interrupt Vector Summary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
14. TC2 – 16-bit Timer/Counter Type 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
14.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
14.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
14.3 Block Diagram. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
14.4 Clock Sources. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
14.5 Counter Operation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
14.6 Compare Channel. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
14.7 Interrupts and Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
14.8 DMA Support. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
14.9 Timer/Counter Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
14.10 Register Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
14.11 Register Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
14.12 Interrupt Vector Summary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
15. AWeX – Advanced Waveform Extension . . . . . . . . . . . . . . . . . . . . . . . . . 185
15.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
15.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
15.3 Port Override. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
15.4 Dead-time Insertion. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
15.5 Pattern Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
15.6 Fault Protection. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
15.7 Register Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
15.8 Register Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
16. Hi-Res – High-Resolution Extension . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
16.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
16.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
16.3 Register Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
16.4 Register Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
17. RTC – Real-Time Counter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
17.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
XMEGA B [MANUAL] 406
Atmel-8291C-AVR-XMEGA B -09/2014
17.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
17.3 Register Descriptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
17.4 Register Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
17.5 Interrupt Vector Summary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
18. USB – Universal Serial Bus Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
18.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
18.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
18.3 Operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
18.4 SRAM Memory Mapping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
18.5 Clock Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
18.6 Ping-pong Operation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
18.7 Multipacket Transfers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
18.8 Auto Zero Length Packet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
18.9 Transaction Complete FIFO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
18.10 Interrupts and Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
18.11 VBUS Detection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216
18.12 On-chip Debug . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
18.13 Register Description – USB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
18.14 Register Description – USB Endpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
18.15 Register Description - Frame . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
18.16 Register Summary – USB Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
18.17 Register Summary – USB Endpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
18.18 Register Summary – Frame . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
18.19 USB Interrupt Vector Summary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
19. TWI – Two-Wire Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
19.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
19.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
19.3 General TWI Bus Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
19.4 TWI Bus State Logic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
19.5 TWI Master Operation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
19.6 TWI Slave Operation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241
19.7 Enabling External Driver Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242
19.8 Register Description – TWI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
19.9 Register Description – TWI Master . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244
19.10 Register Description – TWI Slave . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249
19.11 Register Summary - TWI. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254
19.12 Register Summary - TWI Master. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254
19.13 Register Summary - TWI Slave. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254
19.14 Interrupt Vector Summary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254
20. SPI – Serial Peripheral Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255
20.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255
20.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255
20.3 Master Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256
20.4 Slave Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256
20.5 Data Modes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256
20.6 DMA Support. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
20.7 Register Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
20.8 Register Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260
20.9 Interrupt vector Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260
XMEGA B [MANUAL] 407
Atmel-8291C-AVR-XMEGA B -09/2014
21. USART . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
21.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
21.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
21.3 Clock Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262
21.4 Frame Formats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266
21.5 USART Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267
21.6 Data Transmission - The USART Transmitter . . . . . . . . . . . . . . . . . . . . . . . 267
21.7 Data Reception - The USART Receiver . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267
21.8 Asynchronous Data Reception . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268
21.9 Fractional Baud Rate Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271
21.10 USART in Master SPI Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273
21.11 USART SPI vs. SPI. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273
21.12 Multiprocessor Communication Mode. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274
21.13 IRCOM Mode of Operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
21.14 DMA Support. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
21.15 Register Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276
21.16 Register Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
21.17 Interrupt Vector Summary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
22. IRCOM - IR Communication Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282
22.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282
22.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282
22.3 Registers Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
22.4 Register Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285
23. AES and DES Crypto Engines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286
23.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286
23.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286
23.3 DES Instruction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286
23.4 AES Crypto Module. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
23.5 Register Description – AES. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290
23.6 Register summary – AES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292
23.7 Interrupt vector summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292
24. CRC – Cyclic Redundancy Check Generator . . . . . . . . . . . . . . . . . . . . . 293
24.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293
24.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293
24.3 Operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
24.4 CRC on Flash memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
24.5 CRC on DMA Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
24.6 CRC using the I/O Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295
24.7 Register Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296
24.8 Register Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
25. LCD – Liquid Crystal Display . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
25.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
25.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
25.3 Block Diagram. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301
25.4 Mode of Operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302
25.5 Register Description – LCD. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308
25.6 Register Summary – LCD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319
25.7 Interrupt Vector Summary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319
XMEGA B [MANUAL] 408
Atmel-8291C-AVR-XMEGA B -09/2014
26. ADC – Analog-to-Digital Converter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320
26.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320
26.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320
26.3 Input Sources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321
26.4 Sampling Time Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324
26.5 Voltage Reference Selection. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324
26.6 Conversion Result. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325
26.7 Compare Function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326
26.8 Starting a Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326
26.9 ADC Clock and Conversion Timing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326
26.10 ADC Input Model. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329
26.11 DMA Transfer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330
26.12 Interrupts and Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330
26.13 Calibration. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330
26.14 Synchronous Sampling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330
26.15 Register Description – ADC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331
26.16 Register Description - ADC Channel. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
26.17 Register Summary – ADC. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344
26.18 Register Summary – ADC Channel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344
26.19 Interrupt vector Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344
27. AC – Analog Comparator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345
27.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345
27.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345
27.3 Input Sources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346
27.4 Signal Compare . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346
27.5 Interrupts and Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346
27.6 Window Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347
27.7 Input Hysteresis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347
27.8 Register Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348
27.9 Register Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353
27.10 Interrupt vector Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353
28. IEEE 1149.1 JTAG Boundary Scan Interface . . . . . . . . . . . . . . . . . . . . . 354
28.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354
28.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354
28.3 TAP - Test Access Port. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354
28.4 JTAG Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356
28.5 Boundary Scan Chain . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357
28.6 Data Registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359
29. Program and Debug Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361
29.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361
29.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361
29.3 PDI Physical . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
29.4 JTAG Physical. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366
29.5 PDI Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368
29.6 Register Description – PDI Instruction and Addressing Registers . . . . . . . . 371
29.7 Register Description – PDI Control and Status Registers. . . . . . . . . . . . . . . 373
29.8 Register Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374
XMEGA B [MANUAL] 409
Atmel-8291C-AVR-XMEGA B -09/2014
30. Memory Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375
30.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375
30.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375
30.3 NVM Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375
30.4 NVM Commands. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376
30.5 NVM Controller Busy Status . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376
30.6 Flash and EEPROM Page Buffers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377
30.7 Flash and EEPROM Programming Sequences . . . . . . . . . . . . . . . . . . . . . . 377
30.8 Protection of NVM. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 378
30.9 Preventing NVM Corruption . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 378
30.10 CRC Functionality . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379
30.11 Self-programming and Boot Loader Support . . . . . . . . . . . . . . . . . . . . . . . . 379
30.12 External Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388
30.13 Register Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393
30.14 Register Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393
31. Peripheral Module Address Map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 394
32. Instruction Set Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395
33. Datasheet Revision History . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 400
33.1 8291C – 06/2014. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 400
33.2 8291B – 01/2013. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 400
33.3 8291A – 07/2011. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401
Table of Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 402
Atmel Corporation 1600 Technology Drive, San Jose, CA 95110 USA T: (+1)(408) 441.0311 F: (+1)(408) 436.4200 | www.atmel.com
© 2014 Atmel Corporation. All rights reserved. / Rev.: 8291C–AVR–XMEGA B –Manual–09/2014
Atmel®, Atmel logo and combinations thereof, Enabling Unlimited Possibilities®, and others are registered trademarks or trademarks of Atmel Corporation or its
subsidiaries. Other terms and product names may be trademarks of others.
DISCLAIMER: The information in this document is provided in connection with Atmel products. No license, express or implied, by estoppel or otherwise, to any intellectual property right is
granted by this document or in connection with the sale of Atmel products. EXCEPT AS SET FORTH IN THE ATMEL TERMS AND CONDITIONS OF SALES LOCATED ON THE ATMEL
WEBSITE, ATMEL ASSUMES NO LIABILITY WHATSOEVER AND DISCLAIMS ANY EXPRESS, IMPLIED OR STATUTORY WARRANTY RELATING TO ITS PRODUCTS INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY
DIRECT, INDIRECT, CONSEQUENTIAL, PUNITIVE, SPECIAL OR INCIDENTAL DAMAGES (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS AND PROFITS, BUSINESS
INTERRUPTION, OR LOSS OF INFORMATION) ARISING OUT OF THE USE OR INABILITY TO USE THIS DOCUMENT, EVEN IF ATMEL HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES. Atmel makes no representations or warranties with respect to the accuracy or completeness of the contents of this document and reserves the right to make changes to
specifications and products descriptions at any time without notice. Atmel does not make any commitment to update the information contained herein. Unless specifically provided otherwise,
Atmel products are not suitable for, and shall not be used in, automotive applications. Atmel products are not intended, authorized, or warranted for use as components in applications intended
to support or sustain life.
SAFETY-CRITICAL, MILITARY, AND AUTOMOTIVE APPLICATIONS DISCLAIMER: Atmel products are not designed for and will not be used in connection with any applications where the failure
of such products would reasonably be expected to result in significant personal injury or death (“Safety-Critical Applications”) without an Atmel officer's specific written consent. Safety-Critical
Applications include, without limitation, life support devices and systems, equipment or systems for the operation of nuclear facilities and weapons systems. Atmel products are not designed nor
intended for use in military or aerospace applications or environments unless specifically designated by Atmel as military-grade. Atmel products are not designed nor intended for use in
automotive applications unless specifically designated by Atmel as automotive-grade.
Features
• High-performance, Low-power 32-bit Atmel® AVR® Microcontroller
– Compact Single-cycle RISC Instruction Set Including DSP Instructions
– Read-modify-write Instructions and Atomic Bit Manipulation
– Performance
• Up to 64DMIPS Running at 50MHz from Flash (1 Flash Wait State)
• Up to 36DMIPS Running at 25MHz from Flash (0 Flash Wait State)
– Memory Protection Unit (MPU)
• Secure Access Unit (SAU) providing User-defined Peripheral Protection
• picoPower® Technology for Ultra-low Power Consumption
• Multi-hierarchy Bus System
– High-performance Data Transfers on Separate Buses for Increased Performance
– 12 Peripheral DMA Channels improve Speed for Peripheral Communication
• Internal High-speed Flash
– 256Kbytes, 128Kbytes, and 64Kbytes Versions
– Single-cycle Access up to 25MHz
– FlashVault Technology Allows Pre-programmed Secure Library Support for End
User Applications
– Prefetch Buffer Optimizing Instruction Execution at Maximum Speed
– 100,000 Write Cycles, 15-year Data Retention Capability
– Flash Security Locks and User-defined Configuration Area
• Internal High-speed SRAM, Single-cycle Access at Full Speed
– 32Kbytes (256Kbytes and 128Kbytes Flash) and 16Kbytes (64Kbytes Flash)
• Interrupt Controller (INTC)
– Autovectored Low-latency Interrupt Service with Programmable Priority
• External Interrupt Controller (EIC)
• Peripheral Event System for Direct Peripheral to Peripheral Communication
• System Functions
– Power and Clock Manager
– SleepWalking Power Saving Control
– Internal System RC Oscillator (RCSYS)
– 32 KHz Oscillator
– Multipurpose Oscillator, Phase Locked Loop (PLL), and Digital Frequency Locked
Loop (DFLL)
• Windowed Watchdog Timer (WDT)
• Asynchronous Timer (AST) with Real-time Clock Capability
– Counter or Calendar Mode Supported
• Frequency Meter (FREQM) for Accurate Measuring of Clock Frequency
• Universal Serial Bus (USBC)
– Full Speed and Low Speed USB Device Support
– Multi-packet Ping-pong Mode
• Six 16-bit Timer/Counter (TC) Channels
– External Clock Inputs, PWM, Capture, and Various Counting Capabilities
• 36 PWM Channels (PWMA)
– 12-bit PWM with a Source Clock up to 150MHz
• Four Universal Synchronous/Asynchronous Receiver/Transmitters (USART)
– Independent Baudrate Generator, Support for SPI
– Support for Hardware Handshaking
32142D–06/2013
32-bit Atmel
AVR
Microcontroller
ATUC256L3U
ATUC128L3U
ATUC64L3U
ATUC256L4U
ATUC128L4U
ATUC64L4U
2
32142D–06/2013
ATUC64/128/256L3/4U
• One Master/Slave Serial Peripheral Interface (SPI) with Chip Select Signals
– Up to 15 SPI Slaves can be Addressed
• Two Master and Two Slave Two-wire Interfaces (TWI), 400kbit/s I2
C-compatible
• One 8-channel Analog-to-digital Converter (ADC) with up to 12 Bits Resolution
– Internal Temperature Sensor
• Eight Analog Comparators (AC) with Optional Window Detection
• Capacitive Touch (CAT) Module
– Hardware-assisted Atmel® AVR® QTouch® and Atmel® AVR® QMatrix Touch Acquisition
– Supports QTouch and QMatrix Capture from Capacitive Touch Sensors
• QTouch Library Support
– Capacitive Touch Buttons, Sliders, and Wheels
– QTouch and QMatrix Acquisition
• Audio Bitstream DAC (ABDACB) Suitable for Stereo Audio
• Inter-IC Sound (IISC) Controller
– Compliant with Inter-IC Sound (I2
S) Specification
• On-chip Non-intrusive Debug System
– Nexus Class 2+, Runtime Control, Non-intrusive Data and Program Trace
– aWire Single-pin Programming Trace and Debug Interface, Muxed with Reset Pin
– NanoTrace Provides Trace Capabilities through JTAG or aWire Interface
• 64-pin TQFP/QFN (51 GPIO Pins), 48-pin TQFP/QFN/TLLGA (36 GPIO Pins)
• Six High-drive I/O Pins (64-pin Packages), Four High-drive I/O Pins (48-pin Packages)
• Single 1.62-3.6V Power Supply
3
32142D–06/2013
ATUC64/128/256L3/4U
1. Description
The Atmel® AVR® ATUC64/128/256L3/4U is a complete system-on-chip microcontroller based
on the AVR32 UC RISC processor running at frequencies up to 50MHz. AVR32 UC is a highperformance
32-bit RISC microprocessor core, designed for cost-sensitive embedded applications,
with particular emphasis on low power consumption, high code density, and high
performance.
The processor implements a Memory Protection Unit (MPU) and a fast and flexible interrupt controller
for supporting modern and real-time operating systems. The Secure Access Unit (SAU) is
used together with the MPU to provide the required security and integrity.
Higher computation capability is achieved using a rich set of DSP instructions.
The ATUC64/128/256L3/4U embeds state-of-the-art picoPower technology for ultra-low power
consumption. Combined power control techniques are used to bring active current consumption
down to 174µA/MHz, and leakage down to 220nA while still retaining a bank of backup registers.
The device allows a wide range of trade-offs between functionality and power consumption,
giving the user the ability to reach the lowest possible power consumption with the feature set
required for the application.
The Peripheral Direct Memory Access (DMA) controller enables data transfers between peripherals
and memories without processor involvement. The Peripheral DMA controller drastically
reduces processing overhead when transferring continuous and large data streams.
The ATUC64/128/256L3/4U incorporates on-chip Flash and SRAM memories for secure and
fast access. The FlashVault technology allows secure libraries to be programmed into the
device. The secure libraries can be executed while the CPU is in Secure State, but not read by
non-secure software in the device. The device can thus be shipped to end customers, who will
be able to program their own code into the device to access the secure libraries, but without risk
of compromising the proprietary secure code.
The External Interrupt Controller (EIC) allows pins to be configured as external interrupts. Each
external interrupt has its own interrupt request and can be individually masked.
The Peripheral Event System allows peripherals to receive, react to, and send peripheral events
without CPU intervention. Asynchronous interrupts allow advanced peripheral operation in low
power sleep modes.
The Power Manager (PM) improves design flexibility and security. The Power Manager supports
SleepWalking functionality, by which a module can be selectively activated based on peripheral
events, even in sleep modes where the module clock is stopped. Power monitoring is supported
by on-chip Power-on Reset (POR), Brown-out Detector (BOD), and Supply Monitor (SM). The
device features several oscillators, such as Phase Locked Loop (PLL), Digital Frequency
Locked Loop (DFLL), Oscillator 0 (OSC0), and system RC oscillator (RCSYS). Either of these
oscillators can be used as source for the system clock. The DFLL is a programmable internal
oscillator from 20 to 150MHz. It can be tuned to a high accuracy if an accurate reference clock is
running, e.g. the 32KHz crystal oscillator.
The Watchdog Timer (WDT) will reset the device unless it is periodically serviced by the software.
This allows the device to recover from a condition that has caused the system to be
unstable.
The Asynchronous Timer (AST) combined with the 32KHz crystal oscillator supports powerful
real-time clock capabilities, with a maximum timeout of up to 136 years. The AST can operate in
counter or calendar mode.
4
32142D–06/2013
ATUC64/128/256L3/4U
The Frequency Meter (FREQM) allows accurate measuring of a clock frequency by comparing it
to a known reference clock.
The Full-speed USB 2.0 device interface (USBC) supports several USB classes at the same
time, thanks to the rich end-point configuration.
The device includes six identical 16-bit Timer/Counter (TC) channels. Each channel can be independently
programmed to perform frequency measurement, event counting, interval
measurement, pulse generation, delay timing, and pulse width modulation.
The Pulse Width Modulation controller (PWMA) provides 12-bit PWM channels which can be
synchronized and controlled from a common timer. 36 PWM channels are available, enabling
applications that require multiple PWM outputs, such as LCD backlight control. The PWM channels
can operate independently, with duty cycles set individually, or in interlinked mode, with
multiple channels changed at the same time.
The ATUC64/128/256L3/4U also features many communication interfaces, like USART, SPI,
and TWI, for communication intensive applications. The USART supports different communication
modes, like SPI Mode and LIN Mode.
A general purpose 8-channel ADC is provided, as well as eight analog comparators (AC). The
ADC can operate in 10-bit mode at full speed or in enhanced mode at reduced speed, offering
up to 12-bit resolution. The ADC also provides an internal temperature sensor input channel.
The analog comparators can be paired to detect when the sensing voltage is within or outside
the defined reference window.
The Capacitive Touch (CAT) module senses touch on external capacitive touch sensors, using
the QTouch technology. Capacitive touch sensors use no external mechanical components,
unlike normal push buttons, and therefore demand less maintenance in the user application.
The CAT module allows up to 17 touch sensors, or up to 16 by 8 matrix sensors to be interfaced.
All touch sensors can be configured to operate autonomously without software interaction,
allowing wakeup from sleep modes when activated.
Atmel offers the QTouch library for embedding capacitive touch buttons, sliders, and wheels
functionality into AVR microcontrollers. The patented charge-transfer signal acquisition offers
robust sensing and includes fully debounced reporting of touch keys as well as Adjacent Key
Suppression® (AKS®) technology for unambiguous detection of key events. The easy-to-use
QTouch Suite toolchain allows you to explore, develop, and debug your own touch applications.
The Audio Bitstream DAC (ABDACB) converts a 16-bit sample value to a digital bitstream with
an average value proportional to the sample value. Two channels are supported, making the
ABDAC particularly suitable for stereo audio.
The Inter-IC Sound Controller (IISC) provides a 5-bit wide, bidirectional, synchronous, digital
audio link with external audio devices. The controller is compliant with the Inter-IC Sound (I2S)
bus specification.
The ATUC64/128/256L3/4U integrates a class 2+ Nexus 2.0 On-chip Debug (OCD) System,
with non-intrusive real-time trace and full-speed read/write memory access, in addition to basic
runtime control. The NanoTrace interface enables trace feature for aWire- or JTAG-based
debuggers. The single-pin aWire interface allows all features available through the JTAG interface
to be accessed through the RESET pin, allowing the JTAG pins to be used for GPIO or
peripherals.
5
32142D–06/2013
ATUC64/128/256L3/4U
2. Overview
2.1 Block Diagram
Figure 2-1. Block Diagram
INTERRUPT
CONTROLLER
ASYNCHRONOUS
TIMER
PERIPHERAL
DMA
CONTROLLER
HSB-PB
BRIDGE B
HSB-PB
BRIDGE A
S
MM M
S
S
M
EXTERNAL INTERRUPT
CONTROLLER
HIGH SPEED
BUS MATRIX
GENERALPURPOSE I/Os
GENERAL PURPOSE I/Os
PA
PB
EXTINT[5..1]
NMI
PA
PB
SPI
DMA
MISO, MOSI
NPCS[3..0]
USART0
USART1
USART2
USART3
DMA
RXD
TXD
CLK
RTS, CTS
WATCHDOG
TIMER
SCK
JTAG
INTERFACE
MCKO
MDO[5..0]
MSEO[1..0]
EVTI_N
TDO
TDI
TMS
CONFIGURATION REGISTERS BUS
256/128/64
KB S FLASH
FLASH
CONTROLLER
EVTO_N
AVR32UC CPU
NEXUS
CLASS 2+
OCD
INSTR
INTERFACE
DATA
INTERFACE
MEMORY INTERFACE
LOCAL BUS
32/16 KB
SRAM
MEMORY PROTECTION UNIT
LOCAL BUS
INTERFACE
FREQUENCY METER
PWMA[35..0] PWM CONTROLLER
TWI MASTER 0
DMA
TWI MASTER 1
TWI SLAVE 0
DMA
TWI SLAVE 1
8-CHANNEL ADC
DMA
INTERFACE
POWER MANAGER
RESET
CONTROLLER
SLEEP
CONTROLLER
CLOCK
CONTROLLER
TCK
RESET_N aWire
CAPACITIVE TOUCH
DMA
MODULE
AC INTERFACE
ACREFN
ACAN[3..0]
ACBN[3..0]
ACBP[3..0]
ACAP[3..0]
TWCK
TWD
TWALM
TWCK
TWD
TWALM
GLUE LOGIC
CONTROLLER IN[7..0]
OUT[1..0]
USB 2.0
Interface 8EP
DMA
INTER-IC SOUND
CONTROLLER
TIMER/COUNTER 0
TIMER/COUNTER 1
A[2..0]
B[2..0]
AUDIO BITSTREAM
DMA
DAC DAC0, DAC1
DACN0, DACN1
ISCK
IWS
ISDI
ISDO
IMCK
CLK
SAU S/M
S
DM
DP
SYSTEM CONTROL
INTERFACE
GCLK[9..0]
XIN32
XOUT32 OSC32K
RCSYS
XIN0
XOUT0 OSC0
DFLL
RC32K
RC120M
RC32OUT
PLL
GCLK_IN[2..0]
CSB[16:0]
SMP
CSA[16:0]
SYNC
VDIVEN
DIS
TRIGGER
ADP[1..0]
AD[8..0]
DATAOUT
ADVREFP
CLK[2..0]
6
32142D–06/2013
ATUC64/128/256L3/4U
2.2 Configuration Summary
Table 2-1. Configuration Summary
Feature ATUC256L3U ATUC128L3U ATUC64L3U ATUC256L4U ATUC128L4U ATUC64L4U
Flash 256KB 128KB 64KB 256KB 128KB 64KB
SRAM 32KB 16KB 32KB 16KB
GPIO 51 36
High-drive pins 6 4
External Interrupts 6
TWI 2
USART 4
Peripheral DMA Channels 12
Peripheral Event System 1
SPI 1
Asynchronous Timers 1
Timer/Counter Channels 6
PWM channels 36
Frequency Meter 1
Watchdog Timer 1
Power Manager 1
Secure Access Unit 1
Glue Logic Controller 1
Oscillators
Digital Frequency Locked Loop 20-150MHz (DFLL)
Phase Locked Loop 40-240MHz (PLL)
Crystal Oscillator 0.45-16MHz (OSC0)
Crystal Oscillator 32KHz (OSC32K)
RC Oscillator 120MHz (RC120M)
RC Oscillator 115kHz (RCSYS)
RC Oscillator 32kHz (RC32K)
ADC 8-channel 12-bit
Temperature Sensor 1
Analog Comparators 8
Capacitive Touch Module 1
JTAG 1
aWire 1
USB 1
Audio Bitstream DAC 1 0
IIS Controller 1 0
Max Frequency 50MHz
Packages TQFP64/QFN64 TQFP48/QFN48/TLLGA48
7
32142D–06/2013
ATUC64/128/256L3/4U
3. Package and Pinout
3.1 Package
The device pins are multiplexed with peripheral functions as described in Section .
Figure 3-1. ATUC64/128/256L4U TQFP48/QFN48 Pinout GND 1 PA09
2
PA08
3
PA03
4
PB12
5
PB00
6
PB02
7
PB03
8
PA22
9
PA06 10
PA00 11
PA05 12
13 PA02
14 PA01
15 PB13
16 PB14
17 VDDIN
18 VDDCORE
19 GND
20 PB05
21 PB04
22 RESET_N
23 PB10
24 PA21
PA14 36
VDDANA 35
ADVREFP 34
GNDANA 33
PB08 32
PB07 31
PB06 30
PB09 29
PA04 28
PA11 27
PA13 26
PA20 25
PA15 37
PA16 38
PA17 39
PA19 40
PA18 41
VDDIO 42
GND 43
PB11 44
GND 45
PA10 46
PA12 47
VDDIO 48
8
32142D–06/2013
ATUC64/128/256L3/4U
Figure 3-2. ATUC64/128/256L4U TLLGA48 Pinout GND 1 PA09
2
PA08
3
PA03
4
PB12
5
PB00
6
PB02
7
PB03
8
PA22
9
PA06 10
PA00 11
PA05 12
PA02 13
14 PA01
15 PB13
16 PB14
17 VDDIN
18 VDDCORE
19 GND
20 PB05
21 PB04
22 RESET_N
23 PB10
24 PA21
PA14 36
VDDANA 35
ADVREFP 34
GNDANA 33
PB08 32
PB07 31
PB06 30
PB09 29
PA04 28
PA11 27
PA13 26
PA20 25
PA15 37
PA16 38
PA17 39
PA19 40
PA18 41
VDDIO 42
GND 43
PB11 44
GND 45
PA10 46
PA12 47
VDDIO 48
9
32142D–06/2013
ATUC64/128/256L3/4U
Figure 3-3. ATUC64/128/256L3U TQFP64/QFN64 Pinout GND 1 PA09
2
PA08
3
PB19
4
PB20
5
PA03
6
PB12
7
PB00
8
PB02
9
PB03 10
VDDIO 11
GND 12
PA22 13
PA06 14
PA00 15
PA05 16
17 PA02
18 PA01
19 PA07
20 PB01
21 PB26
22 PB13
23 PB14
24 PB27
PB08 44
PB07 43
PB06 42
PB22 41
PB21 40
PB09 39
PA04 38
VDDIO 37
GND 36
PA11 35
PA13 34
PA20 33
PA15 49
PA16 50
PA17 51
PA19 52
PA18 53
PB23 54
PB24 55
PB11 56
PB15 57
PB16 58
PB17 59
PB18 60
25 VDDIN
26
27 GND
28 PB05
29 PB04
30
31 PB10
32 PA21
PA14 48
VDDANA 47
ADVREFP 46
GNDANA 45
PB25 61
PA10 62
PA12 63
VDDIO 64
VDDCORE
RESET_N
10
32142D–06/2013
ATUC64/128/256L3/4U
Peripheral Multiplexing on I/O lines
3.1.1 Multiplexed Signals
Each GPIO line can be assigned to one of the peripheral functions. The following table
describes the peripheral signals multiplexed to the GPIO lines.
Table 3-1. GPIO Controller Function Multiplexing
48-
pin
64-
pin
Pin
Name
G
PI
O Supply
Pad
Type
GPIO Function
ABCDE F GH
11 15 PA00 0 VDDIO Normal
I/O
USART0-
TXD
USART1-
RTS
SPINPCS[2]
PWMAPWMA[0]
SCIFGCLK[0]
CATCSA[2]
14 18 PA01 1 VDDIO Normal
I/O
USART0-
RXD
USART1-
CTS
SPINPCS[3]
USART1-
CLK
PWMAPWMA[1]
ACIFBACAP[0]
TWIMS0-
TWALM
CATCSA[1]
13 17 PA02 2 VDDIO Highdrive
I/O
USART0-
RTS
ADCIFBTRIGGER
USART2-
TXD TC0-A0 PWMAPWMA[2]
ACIFBACBP[0]
USART0-
CLK
CATCSA[3]
4 6 PA03 3 VDDIO Normal
I/O
USART0-
CTS
SPINPCS[1]
USART2-
TXD TC0-B0 PWMAPWMA[3]
ACIFBACBN[3]
USART0-
CLK
CATCSB[3]
28 38 PA04 4 VDDIO Normal
I/O SPI-MISO TWIMS0-
TWCK
USART1-
RXD TC0-B1 PWMAPWMA[4]
ACIFBACBP[1]
CATCSA[7]
12 16 PA05 5 VDDIO Normal
I/O (TWI) SPI-MOSI TWIMS1-
TWCK
USART1-
TXD TC0-A1 PWMAPWMA[5]
ACIFBACBN[0]
TWIMS0-
TWD
CATCSB[7]
10 14 PA06 6 VDDIO
Highdrive
I/O,
5V
tolerant
SPI-SCK USART2-
TXD
USART1-
CLK TC0-B0 PWMAPWMA[6]
EICEXTINT[2]
SCIFGCLK[1]
CATCSB[1]
19 PA07 7 VDDIO Normal
I/O (TWI)
SPINPCS[0]
USART2-
RXD
TWIMS1-
TWALM
TWIMS0-
TWCK
PWMAPWMA[7]
ACIFBACAN[0]
EICNMI
(EXTINT[0])
CATCSB[2]
3 3 PA08 8 VDDIO Highdrive
I/O
USART1-
TXD
SPINPCS[2]
TC0-A2 ADCIFBADP[0]
PWMAPWMA[8]
CATCSA[4]
2 2 PA09 9 VDDIO Highdrive
I/O
USART1-
RXD
SPINPCS[3]
TC0-B2 ADCIFBADP[1]
PWMAPWMA[9]
SCIFGCLK[2]
EICEXTINT[1]
CATCSB[4]
46 62 PA10 10 VDDIO Normal
I/O
TWIMS0-
TWD TC0-A0 PWMAPWMA[10]
ACIFBACAP[1]
SCIFGCLK[2]
CATCSA[5]
27 35 PA11 11 VDDIN Normal
I/O
PWMAPWMA[11]
47 63 PA12 12 VDDIO Normal
I/O
USART2-
CLK TC0-CLK1 CAT-SMP PWMAPWMA[12]
ACIFBACAN[1]
SCIFGCLK[3]
CATCSB[5]
26 34 PA13 13 VDDIN Normal
I/O
GLOCOUT[0]
GLOCIN[7]
TC0-A0 SCIFGCLK[2]
PWMAPWMA[13]
CAT-SMP EICEXTINT[2]
CATCSA[0]
36 48 PA14 14 VDDIO Normal
I/O
ADCIFBAD[0]
TC0-CLK2 USART2-
RTS CAT-SMP PWMAPWMA[14]
SCIFGCLK[4]
CATCSA[6]
37 49 PA15 15 VDDIO Normal
I/O
ADCIFBAD[1]
TC0-CLK1 GLOCIN[6]
PWMAPWMA[15]
CATSYNC
EICEXTINT[3]
CATCSB[6]
38 50 PA16 16 VDDIO Normal
I/O
ADCIFBAD[2]
TC0-CLK0 GLOCIN[5]
PWMAPWMA[16]
ACIFBACREFN
EICEXTINT[4]
CATCSA[8]
11
32142D–06/2013
ATUC64/128/256L3/4U
39 51 PA17 17 VDDIO Normal
I/O (TWI) TC0-A1 USART2-
CTS
TWIMS1-
TWD
PWMAPWMA[17]
CAT-SMP CAT-DIS CATCSB[8]
41 53 PA18 18 VDDIO Normal
I/O
ADCIFBAD[4]
TC0-B1 GLOCIN[4]
PWMAPWMA[18]
CATSYNC
EICEXTINT[5]
CATCSB[0]
40 52 PA19 19 VDDIO Normal
I/O
ADCIFBAD[5]
TC0-A2 TWIMS1-
TWALM
PWMAPWMA[19]
SCIFGCLK_IN[
0]
CAT-SYNC CATCSA[10]
25 33 PA20 20 VDDIN Normal
I/O
USART2-
TXD TC0-A1 GLOCIN[3]
PWMAPWMA[20]
SCIFRC32OUT
CATCSA[12]
24 32 PA21 21 VDDIN
Normal
I/O (TWI,
5V
tolerant,
SMBus)
USART2-
RXD
TWIMS0-
TWD TC0-B1 ADCIFBTRIGGER
PWMAPWMA[21]
PWMAPWMAOD
[21]
SCIFGCLK[0]
CATSMP
9 13 PA22 22 VDDIO Normal
I/O
USART0-
CTS
USART2-
CLK TC0-B2 CAT-SMP PWMAPWMA[22]
ACIFBACBN[2]
CATCSB[10]
6 8 PB00 32 VDDIO Normal
I/O
USART3-
TXD
ADCIFBADP[0]
SPINPCS[0]
TC0-A1 PWMAPWMA[23]
ACIFBACAP[2]
TC1-A0 CATCSA[9]
20 PB01 33 VDDIO Highdrive
I/O
USART3-
RXD
ADCIFBADP[1]
SPI-SCK TC0-B1 PWMAPWMA[24]
TC1-A1 CATCSB[9]
7 9 PB02 34 VDDIO Normal
I/O
USART3-
RTS
USART3-
CLK SPI-MISO TC0-A2 PWMAPWMA[25]
ACIFBACAN[2]
SCIFGCLK[1]
CATCSB[11]
8 10 PB03 35 VDDIO Normal
I/O
USART3-
CTS
USART3-
CLK SPI-MOSI TC0-B2 PWMAPWMA[26]
ACIFBACBP[2]
TC1-A2 CATCSA[11]
21 29 PB04 36 VDDIN
Normal
I/O (TWI,
5V
tolerant,
SMBus)
TC1-A0 USART1-
RTS
USART1-
CLK
TWIMS0-
TWALM
PWMAPWMA[27]
PWMAPWMAOD
[27]
TWIMS1-
TWCK
CATCSA[14]
20 28 PB05 37 VDDIN
Normal
I/O (TWI,
5V
tolerant,
SMBus)
TC1-B0 USART1-
CTS
USART1-
CLK
TWIMS0-
TWCK
PWMAPWMA[28]
PWMAPWMAOD
[28]
SCIFGCLK[3]
CATCSB[14]
30 42 PB06 38 VDDIO Normal
I/O TC1-A1 USART3-
TXD
ADCIFBAD[6]
GLOCIN[2]
PWMAPWMA[29]
ACIFBACAN[3]
EICNMI
(EXTINT[0])
CATCSB[13]
31 43 PB07 39 VDDIO Normal
I/O TC1-B1 USART3-
RXD
ADCIFBAD[7]
GLOCIN[1]
PWMAPWMA[30]
ACIFBACAP[3]
EICEXTINT[1]
CATCSA[13]
32 44 PB08 40 VDDIO Normal
I/O TC1-A2 USART3-
RTS
ADCIFBAD[8]
GLOCIN[0]
PWMAPWMA[31]
CATSYNC
EICEXTINT[2]
CATCSB[12]
29 39 PB09 41 VDDIO Normal
I/O TC1-B2 USART3-
CTS
USART3-
CLK
PWMAPWMA[32]
ACIFBACBN[1]
EICEXTINT[3]
CATCSB[15]
23 31 PB10 42 VDDIN Normal
I/O TC1-CLK0 USART1-
TXD
USART3-
CLK
GLOCOUT[1]
PWMAPWMA[33]
SCIFGCLK_IN[
1]
EICEXTINT[4]
CATCSB[16]
44 56 PB11 43 VDDIO Normal
I/O TC1-CLK1 USART1-
RXD
ADCIFBTRIGGER
PWMAPWMA[34]
CATVDIVEN
EICEXTINT[5]
CATCSA[16]
5 7 PB12 44 VDDIO Normal
I/O TC1-CLK2 TWIMS1-
TWALM
CATSYNC
PWMAPWMA[35]
ACIFBACBP[3]
SCIFGCLK[4]
CATCSA[15]
15 22 PB13 45 VDDIN USB I/O USBC-DM USART3-
TXD TC1-A1 PWMAPWMA[7]
ADCIFBADP[1]
SCIFGCLK[5]
CATCSB[2]
16 23 PB14 46 VDDIN USB I/O USBC-DP USART3-
RXD TC1-B1 PWMAPWMA[24]
SCIFGCLK[5]
CATCSB[9]
Table 3-1. GPIO Controller Function Multiplexing
12
32142D–06/2013
ATUC64/128/256L3/4U
3.2 See Section 3.3 for a description of the various peripheral signals.
Refer to ”Electrical Characteristics” on page 897 for a description of the electrical properties of
the pin types used.
3.2.1 TWI, 5V Tolerant, and SMBUS Pins
Some normal I/O pins offer TWI, 5V tolerance, and SMBUS features. These features are only
available when either of the TWI functions or the PWMAOD function in the PWMA are selected
for these pins.
Refer to the ”Electrical Characteristics” on page 897 for a description of the electrical properties
of the TWI, 5V tolerance, and SMBUS pins.
57 PB15 47 VDDIO Highdrive
I/O
ABDACBCLK
IISCIMCK
SPI-SCK TC0-CLK2 PWMAPWMA[8]
SCIFGCLK[3]
CATCSB[4]
58 PB16 48 VDDIO Normal
I/O
ABDACBDAC[0]
IISC-ISCK USART0-
TXD
PWMAPWMA[9]
SCIFGCLK[2]
CATCSA[5]
59 PB17 49 VDDIO Normal
I/O
ABDACBDAC[1]
IISC-IWS USART0-
RXD
PWMAPWMA[10]
CATCSB[5]
60 PB18 50 VDDIO Normal
I/O
ABDACBDACN[0]
IISC-ISDI USART0-
RTS
PWMAPWMA[12]
CATCSA[0]
4 PB19 51 VDDIO Normal
I/O
ABDACBDACN[1]
IISC-ISDO USART0-
CTS
PWMAPWMA[20]
EICEXTINT[1]
CATCSA[12]
5 PB20 52 VDDIO Normal
I/O
TWIMS1-
TWD
USART2-
RXD
SPINPCS[1]
TC0-A0 PWMAPWMA[21]
USART1-
RTS
USART1-
CLK
CATCSA[14]
40 PB21 53 VDDIO Normal
I/O
TWIMS1-
TWCK
USART2-
TXD
SPINPCS[2]
TC0-B0 PWMAPWMA[28]
USART1-
CTS
USART1-
CLK
CATCSB[14]
41 PB22 54 VDDIO Normal
I/O
TWIMS1-
TWALM
SPINPCS[3]
TC0-CLK0 PWMAPWMA[27]
ADCIFBTRIGGER
SCIFGCLK[0]
CATCSA[8]
54 PB23 55 VDDIO Normal
I/O SPI-MISO USART2-
RTS
USART2-
CLK TC0-A2 PWMAPWMA[0]
CAT-SMP SCIFGCLK[6]
CATCSA[4]
55 PB24 56 VDDIO Normal
I/O SPI-MOSI USART2-
CTS
USART2-
CLK TC0-B2 PWMAPWMA[1]
ADCIFBADP[1]
SCIFGCLK[7]
CATCSA[2]
61 PB25 57 VDDIO Normal
I/O
SPINPCS[0]
USART1-
RXD TC0-A1 PWMAPWMA[2]
SCIFGCLK_IN[
2]
SCIFGCLK[8]
CATCSA[3]
21 PB26 58 VDDIO Normal
I/O SPI-SCK USART1-
TXD TC0-B1 PWMAPWMA[3]
ADCIFBADP[0]
SCIFGCLK[9]
CATCSB[3]
24 PB27 59 VDDIN Normal
I/O
USART1-
RXD TC0-CLK1 PWMAPWMA[4]
ADCIFBADP[1]
EICNMI
(EXTINT[0])
CATCSA[9]
Table 3-1. GPIO Controller Function Multiplexing
13
32142D–06/2013
ATUC64/128/256L3/4U
3.2.2 Peripheral Functions
Each GPIO line can be assigned to one of several peripheral functions. The following table
describes how the various peripheral functions are selected. The last listed function has priority
in case multiple functions are enabled on the same pin.
3.2.3 JTAG Port Connections
If the JTAG is enabled, the JTAG will take control over a number of pins, irrespectively of the I/O
Controller configuration.
3.2.4 Nexus OCD AUX Port Connections
If the OCD trace system is enabled, the trace system will take control over a number of pins, irrespectively
of the I/O Controller configuration. Two different OCD trace pin mappings are
possible, depending on the configuration of the OCD AXS register. For details, see the AVR32
UC Technical Reference Manual.
Table 3-2. Peripheral Functions
Function Description
GPIO Controller Function multiplexing GPIO and GPIO peripheral selection A to H
Nexus OCD AUX port connections OCD trace system
aWire DATAOUT aWire output in two-pin mode
JTAG port connections JTAG debug port
Oscillators OSC0, OSC32
Table 3-3. JTAG Pinout
48-pin 64-pin Pin name JTAG pin
11 15 PA00 TCK
14 18 PA01 TMS
13 17 PA02 TDO
4 6 PA03 TDI
Table 3-4. Nexus OCD AUX Port Connections
Pin AXS=1 AXS=0
EVTI_N PA05 PB08
MDO[5] PA10 PB00
MDO[4] PA18 PB04
MDO[3] PA17 PB05
MDO[2] PA16 PB03
MDO[1] PA15 PB02
MDO[0] PA14 PB09
14
32142D–06/2013
ATUC64/128/256L3/4U
3.2.5 Oscillator Pinout
The oscillators are not mapped to the normal GPIO functions and their muxings are controlled
by registers in the System Control Interface (SCIF). Please refer to the SCIF chapter for more
information about this.
3.2.6 Other Functions
The functions listed in Table 3-6 are not mapped to the normal GPIO functions. The aWire DATA
pin will only be active after the aWire is enabled. The aWire DATAOUT pin will only be active
after the aWire is enabled and the 2_PIN_MODE command has been sent. The WAKE_N pin is
always enabled. Please refer to Section 6.1.4.2 on page 44 for constraints on the WAKE_N pin.
EVTO_N PA04 PA04
MCKO PA06 PB01
MSEO[1] PA07 PB11
MSEO[0] PA11 PB12
Table 3-4. Nexus OCD AUX Port Connections
Pin AXS=1 AXS=0
Table 3-5. Oscillator Pinout
48-pin 64-pin Pin Name Oscillator Pin
3 3 PA08 XIN0
46 62 PA10 XIN32
26 34 PA13 XIN32_2
2 2 PA09 XOUT0
47 63 PA12 XOUT32
25 33 PA20 XOUT32_2
Table 3-6. Other Functions
48-pin 64-pin Pin Name Function
27 35 PA11 WAKE_N
22 30 RESET_N aWire DATA
11 15 PA00 aWire DATAOUT
15
32142D–06/2013
ATUC64/128/256L3/4U
3.3 Signal Descriptions
The following table gives details on signal name classified by peripheral.
Table 3-7. Signal Descriptions List
Signal Name Function Type
Active
Level Comments
Audio Bitstream DAC - ABDACB
CLK D/A Clock out Output
DAC1 - DAC0 D/A Bitstream out Output
DACN1 - DACN0 D/A Inverted bitstream out Output
Analog Comparator Interface - ACIFB
ACAN3 - ACAN0 Negative inputs for comparators "A" Analog
ACAP3 - ACAP0 Positive inputs for comparators "A" Analog
ACBN3 - ACBN0 Negative inputs for comparators "B" Analog
ACBP3 - ACBP0 Positive inputs for comparators "B" Analog
ACREFN Common negative reference Analog
ADC Interface - ADCIFB
AD8 - AD0 Analog Signal Analog
ADP1 - ADP0 Drive Pin for resistive touch screen Output
TRIGGER External trigger Input
aWire - AW
DATA aWire data I/O
DATAOUT aWire data output for 2-pin mode I/O
Capacitive Touch Module - CAT
CSA16 - CSA0 Capacitive Sense A I/O
CSB16 - CSB0 Capacitive Sense B I/O
DIS Discharge current control Analog
SMP SMP signal Output
SYNC Synchronize signal Input
VDIVEN Voltage divider enable Output
External Interrupt Controller - EIC
NMI (EXTINT0) Non-Maskable Interrupt Input
EXTINT5 - EXTINT1 External interrupt Input
Glue Logic Controller - GLOC
IN7 - IN0 Inputs to lookup tables Input
OUT1 - OUT0 Outputs from lookup tables Output
Inter-IC Sound (I2S) Controller - IISC
16
32142D–06/2013
ATUC64/128/256L3/4U
IMCK I2S Master Clock Output
ISCK I2S Serial Clock I/O
ISDI I2S Serial Data In Input
ISDO I2S Serial Data Out Output
IWS I2S Word Select I/O
JTAG module - JTAG
TCK Test Clock Input
TDI Test Data In Input
TDO Test Data Out Output
TMS Test Mode Select Input
Power Manager - PM
RESET_N Reset Input Low
Pulse Width Modulation Controller - PWMA
PWMA35 - PWMA0 PWMA channel waveforms Output
PWMAOD35 -
PWMAOD0
PWMA channel waveforms, open drain
mode Output Not all channels support open
drain mode
System Control Interface - SCIF
GCLK9 - GCLK0 Generic Clock Output Output
GCLK_IN2 - GCLK_IN0 Generic Clock Input Input
RC32OUT RC32K output at startup Output
XIN0 Crystal 0 Input Analog/
Digital
XIN32 Crystal 32 Input (primary location) Analog/
Digital
XIN32_2 Crystal 32 Input (secondary location) Analog/
Digital
XOUT0 Crystal 0 Output Analog
XOUT32 Crystal 32 Output (primary location) Analog
XOUT32_2 Crystal 32 Output (secondary location) Analog
Serial Peripheral Interface - SPI
MISO Master In Slave Out I/O
MOSI Master Out Slave In I/O
NPCS3 - NPCS0 SPI Peripheral Chip Select I/O Low
SCK Clock I/O
Timer/Counter - TC0, TC1
A0 Channel 0 Line A I/O
A1 Channel 1 Line A I/O
A2 Channel 2 Line A I/O
Table 3-7. Signal Descriptions List
17
32142D–06/2013
ATUC64/128/256L3/4U
Note: 1. ADCIFB: AD3 does not exist.
B0 Channel 0 Line B I/O
B1 Channel 1 Line B I/O
B2 Channel 2 Line B I/O
CLK0 Channel 0 External Clock Input Input
CLK1 Channel 1 External Clock Input Input
CLK2 Channel 2 External Clock Input Input
Two-wire Interface - TWIMS0, TWIMS1
TWALM SMBus SMBALERT I/O Low
TWCK Two-wire Serial Clock I/O
TWD Two-wire Serial Data I/O
Universal Synchronous Asynchronous Receiver Transmitter - USART0, USART1, USART2, USART3
CLK Clock I/O
CTS Clear To Send Input Low
RTS Request To Send Output Low
RXD Receive Data Input
TXD Transmit Data Output
Table 3-7. Signal Descriptions List
Table 3-8. Signal Description List, Continued
Signal Name Function Type
Active
Level Comments
Power
VDDCORE Core Power Supply / Voltage Regulator Output Power
Input/Output 1.62V to 1.98V
VDDIO I/O Power Supply Power Input
1.62V to 3.6V. VDDIO should
always be equal to or lower than
VDDIN.
VDDANA Analog Power Supply Power Input 1.62V to 1.98V
ADVREFP Analog Reference Voltage Power Input 1.62V to 1.98V
VDDIN Voltage Regulator Input Power Input 1.62V to 3.6V(1)
GNDANA Analog Ground Ground
GND Ground Ground
Auxiliary Port - AUX
MCKO Trace Data Output Clock Output
MDO5 - MDO0 Trace Data Output Output
18
32142D–06/2013
ATUC64/128/256L3/4U
Note: 1. See Section 6. on page 39
3.4 I/O Line Considerations
3.4.1 JTAG Pins
The JTAG is enabled if TCK is low while the RESET_N pin is released. The TCK, TMS, and TDI
pins have pull-up resistors when JTAG is enabled. The TCK pin always has pull-up enabled during
reset. The TDO pin is an output, driven at VDDIO, and has no pull-up resistor. The JTAG
pins can be used as GPIO pins and multiplexed with peripherals when the JTAG is disabled.
Please refer to Section 3.2.3 on page 13 for the JTAG port connections.
3.4.2 PA00
Note that PA00 is multiplexed with TCK. PA00 GPIO function must only be used as output in the
application.
3.4.3 RESET_N Pin
The RESET_N pin is a schmitt input and integrates a permanent pull-up resistor to VDDIN. As
the product integrates a power-on reset detector, the RESET_N pin can be left unconnected in
case no reset from the system needs to be applied to the product.
The RESET_N pin is also used for the aWire debug protocol. When the pin is used for debugging,
it must not be driven by external circuitry.
3.4.4 TWI Pins PA21/PB04/PB05
When these pins are used for TWI, the pins are open-drain outputs with slew-rate limitation and
inputs with spike filtering. When used as GPIO pins or used for other peripherals, the pins have
the same characteristics as other GPIO pins. Selected pins are also SMBus compliant (refer to
Section on page 10). As required by the SMBus specification, these pins provide no leakage
path to ground when the ATUC64/128/256L3/4U is powered down. This allows other devices on
the SMBus to continue communicating even though the ATUC64/128/256L3/4U is not powered.
After reset a TWI function is selected on these pins instead of the GPIO. Please refer to the
GPIO Module Configuration chapter for details.
MSEO1 - MSEO0 Trace Frame Control Output
EVTI_N Event In Input Low
EVTO_N Event Out Output Low
General Purpose I/O pin
PA22 - PA00 Parallel I/O Controller I/O Port 0 I/O
PB27 - PB00 Parallel I/O Controller I/O Port 1 I/O
Table 3-8. Signal Description List, Continued
Signal Name Function Type
Active
Level Comments
19
32142D–06/2013
ATUC64/128/256L3/4U
3.4.5 TWI Pins PA05/PA07/PA17
When these pins are used for TWI, the pins are open-drain outputs with slew-rate limitation and
inputs with spike filtering. When used as GPIO pins or used for other peripherals, the pins have
the same characteristics as other GPIO pins.
After reset a TWI function is selected on these pins instead of the GPIO. Please refer to the
GPIO Module Configuration chapter for details.
3.4.6 GPIO Pins
All the I/O lines integrate a pull-up resistor Programming of this pull-up resistor is performed
independently for each I/O line through the GPIO Controllers. After reset, I/O lines default as
inputs with pull-up resistors disabled, except PA00 which has the pull-up resistor enabled. PA20
selects SCIF-RC32OUT (GPIO Function F) as default enabled after reset.
3.4.7 High-drive Pins
The six pins PA02, PA06, PA08, PA09, PB01, and PB15 have high-drive output capabilities.
Refer to Section 35. on page 897 for electrical characteristics.
3.4.8 USB Pins PB13/PB14
When these pins are used for USB, the pins are behaving according to the USB specification.
When used as GPIO pins or used for other peripherals, the pins have the same behaviour as
other normal I/O pins, but the characteristics are different. Refer to Section 35. on page 897 for
electrical characteristics.
To be able to use the USB I/O the VDDIN power supply must be 3.3V nominal.
3.4.9 RC32OUT Pin
3.4.9.1 Clock output at startup
After power-up, the clock generated by the 32kHz RC oscillator (RC32K) will be output on PA20,
even when the device is still reset by the Power-On Reset Circuitry. This clock can be used by
the system to start other devices or to clock a switching regulator to rise the power supply voltage
up to an acceptable value.
The clock will be available on PA20, but will be disabled if one of the following conditions are
true:
• PA20 is configured to use a GPIO function other than F (SCIF-RC32OUT)
• PA20 is configured as a General Purpose Input/Output (GPIO)
• The bit FRC32 in the Power Manager PPCR register is written to zero (refer to the Power
Manager chapter)
The maximum amplitude of the clock signal will be defined by VDDIN.
Once the RC32K output on PA20 is disabled it can never be enabled again.
3.4.9.2 XOUT32_2 function
PA20 selects RC32OUT as default enabled after reset. This function is not automatically disabled
when the user enables the XOUT32_2 function on PA20. This disturbs the oscillator and
may result in the wrong frequency. To avoid this, RC32OUT must be disabled when XOUT32_2
is enabled.
20
32142D–06/2013
ATUC64/128/256L3/4U
3.4.10 ADC Input Pins
These pins are regular I/O pins powered from the VDDIO. However, when these pins are used
for ADC inputs, the voltage applied to the pin must not exceed 1.98V. Internal circuitry ensures
that the pin cannot be used as an analog input pin when the I/O drives to VDD. When the pins
are not used for ADC inputs, the pins may be driven to the full I/O voltage range.
21
32142D–06/2013
ATUC64/128/256L3/4U
4. Processor and Architecture
Rev: 2.1.2.0
This chapter gives an overview of the AVR32UC CPU. AVR32UC is an implementation of the
AVR32 architecture. A summary of the programming model, instruction set, and MPU is presented.
For further details, see the AVR32 Architecture Manual and the AVR32UC Technical
Reference Manual.
4.1 Features
• 32-bit load/store AVR32A RISC architecture
– 15 general-purpose 32-bit registers
– 32-bit Stack Pointer, Program Counter and Link Register reside in register file
– Fully orthogonal instruction set
– Privileged and unprivileged modes enabling efficient and secure operating systems
– Innovative instruction set together with variable instruction length ensuring industry leading
code density
– DSP extension with saturating arithmetic, and a wide variety of multiply instructions
• 3-stage pipeline allowing one instruction per clock cycle for most instructions
– Byte, halfword, word, and double word memory access
– Multiple interrupt priority levels
• MPU allows for operating systems with memory protection
• Secure State for supporting FlashVault technology
4.2 AVR32 Architecture
AVR32 is a new, high-performance 32-bit RISC microprocessor architecture, designed for costsensitive
embedded applications, with particular emphasis on low power consumption and high
code density. In addition, the instruction set architecture has been tuned to allow a variety of
microarchitectures, enabling the AVR32 to be implemented as low-, mid-, or high-performance
processors. AVR32 extends the AVR family into the world of 32- and 64-bit applications.
Through a quantitative approach, a large set of industry recognized benchmarks has been compiled
and analyzed to achieve the best code density in its class. In addition to lowering the
memory requirements, a compact code size also contributes to the core’s low power characteristics.
The processor supports byte and halfword data types without penalty in code size and
performance.
Memory load and store operations are provided for byte, halfword, word, and double word data
with automatic sign- or zero extension of halfword and byte data. The C-compiler is closely
linked to the architecture and is able to exploit code optimization features, both for size and
speed.
In order to reduce code size to a minimum, some instructions have multiple addressing modes.
As an example, instructions with immediates often have a compact format with a smaller immediate,
and an extended format with a larger immediate. In this way, the compiler is able to use
the format giving the smallest code size.
Another feature of the instruction set is that frequently used instructions, like add, have a compact
format with two operands as well as an extended format with three operands. The larger
format increases performance, allowing an addition and a data move in the same instruction in a
22
32142D–06/2013
ATUC64/128/256L3/4U
single cycle. Load and store instructions have several different formats in order to reduce code
size and speed up execution.
The register file is organized as sixteen 32-bit registers and includes the Program Counter, the
Link Register, and the Stack Pointer. In addition, register R12 is designed to hold return values
from function calls and is used implicitly by some instructions.
4.3 The AVR32UC CPU
The AVR32UC CPU targets low- and medium-performance applications, and provides an
advanced On-Chip Debug (OCD) system, no caches, and a Memory Protection Unit (MPU).
Java acceleration hardware is not implemented.
AVR32UC provides three memory interfaces, one High Speed Bus master for instruction fetch,
one High Speed Bus master for data access, and one High Speed Bus slave interface allowing
other bus masters to access data RAMs internal to the CPU. Keeping data RAMs internal to the
CPU allows fast access to the RAMs, reduces latency, and guarantees deterministic timing.
Also, power consumption is reduced by not needing a full High Speed Bus access for memory
accesses. A dedicated data RAM interface is provided for communicating with the internal data
RAMs.
A local bus interface is provided for connecting the CPU to device-specific high-speed systems,
such as floating-point units and I/O controller ports. This local bus has to be enabled by writing a
one to the LOCEN bit in the CPUCR system register. The local bus is able to transfer data
between the CPU and the local bus slave in a single clock cycle. The local bus has a dedicated
memory range allocated to it, and data transfers are performed using regular load and store
instructions. Details on which devices that are mapped into the local bus space is given in the
CPU Local Bus section in the Memories chapter.
Figure 4-1 on page 23 displays the contents of AVR32UC.
23
32142D–06/2013
ATUC64/128/256L3/4U
Figure 4-1. Overview of the AVR32UC CPU
4.3.1 Pipeline Overview
AVR32UC has three pipeline stages, Instruction Fetch (IF), Instruction Decode (ID), and Instruction
Execute (EX). The EX stage is split into three parallel subsections, one arithmetic/logic
(ALU) section, one multiply (MUL) section, and one load/store (LS) section.
Instructions are issued and complete in order. Certain operations require several clock cycles to
complete, and in this case, the instruction resides in the ID and EX stages for the required number
of clock cycles. Since there is only three pipeline stages, no internal data forwarding is
required, and no data dependencies can arise in the pipeline.
Figure 4-2 on page 24 shows an overview of the AVR32UC pipeline stages.
AVR32UC CPU pipeline
Instruction memory controller
MPU
High Speed Bus
High Speed Bus
OCD
systemOCD interface
Interrupt controller interface
High
Speed
Bus slave High Speed Bus
High Speed Bus master
Power/
Reset
control Reset interface
CPU Local
Bus
master CPU Local Bus
Data memory controller
CPU RAM High Speed
Bus master
24
32142D–06/2013
ATUC64/128/256L3/4U
Figure 4-2. The AVR32UC Pipeline
4.3.2 AVR32A Microarchitecture Compliance
AVR32UC implements an AVR32A microarchitecture. The AVR32A microarchitecture is targeted
at cost-sensitive, lower-end applications like smaller microcontrollers. This
microarchitecture does not provide dedicated hardware registers for shadowing of register file
registers in interrupt contexts. Additionally, it does not provide hardware registers for the return
address registers and return status registers. Instead, all this information is stored on the system
stack. This saves chip area at the expense of slower interrupt handling.
4.3.2.1 Interrupt Handling
Upon interrupt initiation, registers R8-R12 are automatically pushed to the system stack. These
registers are pushed regardless of the priority level of the pending interrupt. The return address
and status register are also automatically pushed to stack. The interrupt handler can therefore
use R8-R12 freely. Upon interrupt completion, the old R8-R12 registers and status register are
restored, and execution continues at the return address stored popped from stack.
The stack is also used to store the status register and return address for exceptions and scall.
Executing the rete or rets instruction at the completion of an exception or system call will pop
this status register and continue execution at the popped return address.
4.3.2.2 Java Support
AVR32UC does not provide Java hardware acceleration.
4.3.2.3 Memory Protection
The MPU allows the user to check all memory accesses for privilege violations. If an access is
attempted to an illegal memory address, the access is aborted and an exception is taken. The
MPU in AVR32UC is specified in the AVR32UC Technical Reference manual.
4.3.2.4 Unaligned Reference Handling
AVR32UC does not support unaligned accesses, except for doubleword accesses. AVR32UC is
able to perform word-aligned st.d and ld.d. Any other unaligned memory access will cause an
IF ID ALU
MUL
Regfile
write
Prefetch unit Decode unit
ALU unit
Multiply unit
Load-store
unit LS
Regfile
Read
25
32142D–06/2013
ATUC64/128/256L3/4U
address exception. Doubleword-sized accesses with word-aligned pointers will automatically be
performed as two word-sized accesses.
The following table shows the instructions with support for unaligned addresses. All other
instructions require aligned addresses.
4.3.2.5 Unimplemented Instructions
The following instructions are unimplemented in AVR32UC, and will cause an Unimplemented
Instruction Exception if executed:
• All SIMD instructions
• All coprocessor instructions if no coprocessors are present
• retj, incjosp, popjc, pushjc
• tlbr, tlbs, tlbw
• cache
4.3.2.6 CPU and Architecture Revision
Three major revisions of the AVR32UC CPU currently exist. The device described in this
datasheet uses CPU revision 3.
The Architecture Revision field in the CONFIG0 system register identifies which architecture
revision is implemented in a specific device.
AVR32UC CPU revision 3 is fully backward-compatible with revisions 1 and 2, ie. code compiled
for revision 1 or 2 is binary-compatible with revision 3 CPUs.
Table 4-1. Instructions with Unaligned Reference Support
Instruction Supported Alignment
ld.d Word
st.d Word
26
32142D–06/2013
ATUC64/128/256L3/4U
4.4 Programming Model
4.4.1 Register File Configuration
The AVR32UC register file is shown below.
Figure 4-3. The AVR32UC Register File
4.4.2 Status Register Configuration
The Status Register (SR) is split into two halfwords, one upper and one lower, see Figure 4-4
and Figure 4-5. The lower word contains the C, Z, N, V, and Q condition code flags and the R, T,
and L bits, while the upper halfword contains information about the mode and state the processor
executes in. Refer to the AVR32 Architecture Manual for details.
Figure 4-4. The Status Register High Halfword
Application
Bit 0
Supervisor
Bit 31
PC
SR
INT0PC
FINTPC
INT1PC
SMPC
R7
R5
R6
R4
R3
R1
R2
R0
Bit 31 Bit 0
PC
SR
R12
INT0PC
FINTPC
INT1PC
SMPC
R7
R5
R6
R4
R11
R9
R10
R8
R3
R1
R2
R0
INT0
SP_APP SP_SYS
R12
R11
R9
R10
R8
INT1 INT2 INT3 Exception NMI
LR LR
Bit 31 Bit 0
PC
SR
R12
INT0PC
FINTPC
INT1PC
SMPC
R7
R5
R6
R4
R11
R9
R10
R8
R3
R1
R2
R0
SP_SYS
LR
Bit 31 Bit 0
PC
SR
R12
INT0PC
FINTPC
INT1PC
SMPC
R7
R5
R6
R4
R11
R9
R10
R8
R3
R1
R2
R0
SP_SYS
LR
Bit 31 Bit 0
PC
SR
R12
INT0PC
FINTPC
INT1PC
SMPC
R7
R5
R6
R4
R11
R9
R10
R8
R3
R1
R2
R0
SP_SYS
LR
Bit 31 Bit 0
PC
SR
R12
INT0PC
FINTPC
INT1PC
SMPC
R7
R5
R6
R4
R11
R9
R10
R8
R3
R1
R2
R0
SP_SYS
LR
Bit 31 Bit 0
PC
SR
R12
INT0PC
FINTPC
INT1PC
SMPC
R7
R5
R6
R4
R11
R9
R10
R8
R3
R1
R2
R0
SP_SYS
LR
Bit 31 Bit 0
PC
SR
R12
INT0PC
FINTPC
INT1PC
SMPC
R7
R5
R6
R4
R11
R9
R10
R8
R3
R1
R2
R0
SP_SYS
LR
Secure
Bit 31 Bit 0
PC
SR
R12
INT0PC
FINTPC
INT1PC
SMPC
R7
R5
R6
R4
R11
R9
R10
R8
R3
R1
R2
R0
SP_SEC
LR
SS_STATUS
SS_ADRF
SS_ADRR
SS_ADR0
SS_ADR1
SS_SP_SYS
SS_SP_APP
SS_RAR
SS_RSR
Bit 31
0 0 0
Bit 16
Interrupt Level 0 Mask
Interrupt Level 1 Mask
Interrupt Level 3 Mask
Interrupt Level 2 Mask
0 0 0 0 0 0 1 1 0 0 0 0 1
- DM D - M2 M1 M0 EM I2MFE I0M GM LC
1 SS
Initial value
I1M Bit name
Mode Bit 0
Mode Bit 1
-
Mode Bit 2
Reserved
Debug State
- I3M
Reserved
Exception Mask
Global Interrupt Mask
Debug State Mask
Secure State
27
32142D–06/2013
ATUC64/128/256L3/4U
Figure 4-5. The Status Register Low Halfword
4.4.3 Processor States
4.4.3.1 Normal RISC State
The AVR32 processor supports several different execution contexts as shown in Table 4-2.
Mode changes can be made under software control, or can be caused by external interrupts or
exception processing. A mode can be interrupted by a higher priority mode, but never by one
with lower priority. Nested exceptions can be supported with a minimal software overhead.
When running an operating system on the AVR32, user processes will typically execute in the
application mode. The programs executed in this mode are restricted from executing certain
instructions. Furthermore, most system registers together with the upper halfword of the status
register cannot be accessed. Protected memory areas are also not available. All other operating
modes are privileged and are collectively called System Modes. They have full access to all privileged
and unprivileged resources. After a reset, the processor will be in supervisor mode.
4.4.3.2 Debug State
The AVR32 can be set in a debug state, which allows implementation of software monitor routines
that can read out and alter system information for use during application development. This
implies that all system and application registers, including the status registers and program
counters, are accessible in debug state. The privileged instructions are also available.
All interrupt levels are by default disabled when debug state is entered, but they can individually
be switched on by the monitor routine by clearing the respective mask bit in the status register.
Bit 15 Bit 0
Reserved
Carry
Zero
Sign
0 0 0 0 0 0 0 0 0 0 0 0 0 0
- T - - - - Bit name
0 0 Initial value
- L Q V N Z C
Overflow
Saturation
- - -
Lock
Reserved
Scratch
Table 4-2. Overview of Execution Modes, their Priorities and Privilege Levels.
Priority Mode Security Description
1 Non Maskable Interrupt Privileged Non Maskable high priority interrupt mode
2 Exception Privileged Execute exceptions
3 Interrupt 3 Privileged General purpose interrupt mode
4 Interrupt 2 Privileged General purpose interrupt mode
5 Interrupt 1 Privileged General purpose interrupt mode
6 Interrupt 0 Privileged General purpose interrupt mode
N/A Supervisor Privileged Runs supervisor calls
N/A Application Unprivileged Normal program execution mode
28
32142D–06/2013
ATUC64/128/256L3/4U
Debug state can be entered as described in the AVR32UC Technical Reference Manual.
Debug state is exited by the retd instruction.
4.4.3.3 Secure State
The AVR32 can be set in a secure state, that allows a part of the code to execute in a state with
higher security levels. The rest of the code can not access resources reserved for this secure
code. Secure State is used to implement FlashVault technology. Refer to the AVR32UC Technical
Reference Manual for details.
4.4.4 System Registers
The system registers are placed outside of the virtual memory space, and are only accessible
using the privileged mfsr and mtsr instructions. The table below lists the system registers specified
in the AVR32 architecture, some of which are unused in AVR32UC. The programmer is
responsible for maintaining correct sequencing of any instructions following a mtsr instruction.
For detail on the system registers, refer to the AVR32UC Technical Reference Manual.
Table 4-3. System Registers
Reg # Address Name Function
0 0 SR Status Register
1 4 EVBA Exception Vector Base Address
2 8 ACBA Application Call Base Address
3 12 CPUCR CPU Control Register
4 16 ECR Exception Cause Register
5 20 RSR_SUP Unused in AVR32UC
6 24 RSR_INT0 Unused in AVR32UC
7 28 RSR_INT1 Unused in AVR32UC
8 32 RSR_INT2 Unused in AVR32UC
9 36 RSR_INT3 Unused in AVR32UC
10 40 RSR_EX Unused in AVR32UC
11 44 RSR_NMI Unused in AVR32UC
12 48 RSR_DBG Return Status Register for Debug mode
13 52 RAR_SUP Unused in AVR32UC
14 56 RAR_INT0 Unused in AVR32UC
15 60 RAR_INT1 Unused in AVR32UC
16 64 RAR_INT2 Unused in AVR32UC
17 68 RAR_INT3 Unused in AVR32UC
18 72 RAR_EX Unused in AVR32UC
19 76 RAR_NMI Unused in AVR32UC
20 80 RAR_DBG Return Address Register for Debug mode
21 84 JECR Unused in AVR32UC
22 88 JOSP Unused in AVR32UC
23 92 JAVA_LV0 Unused in AVR32UC
29
32142D–06/2013
ATUC64/128/256L3/4U
24 96 JAVA_LV1 Unused in AVR32UC
25 100 JAVA_LV2 Unused in AVR32UC
26 104 JAVA_LV3 Unused in AVR32UC
27 108 JAVA_LV4 Unused in AVR32UC
28 112 JAVA_LV5 Unused in AVR32UC
29 116 JAVA_LV6 Unused in AVR32UC
30 120 JAVA_LV7 Unused in AVR32UC
31 124 JTBA Unused in AVR32UC
32 128 JBCR Unused in AVR32UC
33-63 132-252 Reserved Reserved for future use
64 256 CONFIG0 Configuration register 0
65 260 CONFIG1 Configuration register 1
66 264 COUNT Cycle Counter register
67 268 COMPARE Compare register
68 272 TLBEHI Unused in AVR32UC
69 276 TLBELO Unused in AVR32UC
70 280 PTBR Unused in AVR32UC
71 284 TLBEAR Unused in AVR32UC
72 288 MMUCR Unused in AVR32UC
73 292 TLBARLO Unused in AVR32UC
74 296 TLBARHI Unused in AVR32UC
75 300 PCCNT Unused in AVR32UC
76 304 PCNT0 Unused in AVR32UC
77 308 PCNT1 Unused in AVR32UC
78 312 PCCR Unused in AVR32UC
79 316 BEAR Bus Error Address Register
80 320 MPUAR0 MPU Address Register region 0
81 324 MPUAR1 MPU Address Register region 1
82 328 MPUAR2 MPU Address Register region 2
83 332 MPUAR3 MPU Address Register region 3
84 336 MPUAR4 MPU Address Register region 4
85 340 MPUAR5 MPU Address Register region 5
86 344 MPUAR6 MPU Address Register region 6
87 348 MPUAR7 MPU Address Register region 7
88 352 MPUPSR0 MPU Privilege Select Register region 0
89 356 MPUPSR1 MPU Privilege Select Register region 1
Table 4-3. System Registers (Continued)
Reg # Address Name Function
30
32142D–06/2013
ATUC64/128/256L3/4U
4.5 Exceptions and Interrupts
In the AVR32 architecture, events are used as a common term for exceptions and interrupts.
AVR32UC incorporates a powerful event handling scheme. The different event sources, like Illegal
Op-code and interrupt requests, have different priority levels, ensuring a well-defined
behavior when multiple events are received simultaneously. Additionally, pending events of a
higher priority class may preempt handling of ongoing events of a lower priority class.
When an event occurs, the execution of the instruction stream is halted, and execution is passed
to an event handler at an address specified in Table 4-4 on page 34. Most of the handlers are
placed sequentially in the code space starting at the address specified by EVBA, with four bytes
between each handler. This gives ample space for a jump instruction to be placed there, jumping
to the event routine itself. A few critical handlers have larger spacing between them, allowing
the entire event routine to be placed directly at the address specified by the EVBA-relative offset
generated by hardware. All interrupt sources have autovectored interrupt service routine (ISR)
addresses. This allows the interrupt controller to directly specify the ISR address as an address
90 360 MPUPSR2 MPU Privilege Select Register region 2
91 364 MPUPSR3 MPU Privilege Select Register region 3
92 368 MPUPSR4 MPU Privilege Select Register region 4
93 372 MPUPSR5 MPU Privilege Select Register region 5
94 376 MPUPSR6 MPU Privilege Select Register region 6
95 380 MPUPSR7 MPU Privilege Select Register region 7
96 384 MPUCRA Unused in this version of AVR32UC
97 388 MPUCRB Unused in this version of AVR32UC
98 392 MPUBRA Unused in this version of AVR32UC
99 396 MPUBRB Unused in this version of AVR32UC
100 400 MPUAPRA MPU Access Permission Register A
101 404 MPUAPRB MPU Access Permission Register B
102 408 MPUCR MPU Control Register
103 412 SS_STATUS Secure State Status Register
104 416 SS_ADRF Secure State Address Flash Register
105 420 SS_ADRR Secure State Address RAM Register
106 424 SS_ADR0 Secure State Address 0 Register
107 428 SS_ADR1 Secure State Address 1 Register
108 432 SS_SP_SYS Secure State Stack Pointer System Register
109 436 SS_SP_APP Secure State Stack Pointer Application Register
110 440 SS_RAR Secure State Return Address Register
111 444 SS_RSR Secure State Return Status Register
112-191 448-764 Reserved Reserved for future use
192-255 768-1020 IMPL IMPLEMENTATION DEFINED
Table 4-3. System Registers (Continued)
Reg # Address Name Function
31
32142D–06/2013
ATUC64/128/256L3/4U
relative to EVBA. The autovector offset has 14 address bits, giving an offset of maximum 16384
bytes. The target address of the event handler is calculated as (EVBA | event_handler_offset),
not (EVBA + event_handler_offset), so EVBA and exception code segments must be set up
appropriately. The same mechanisms are used to service all different types of events, including
interrupt requests, yielding a uniform event handling scheme.
An interrupt controller does the priority handling of the interrupts and provides the autovector offset
to the CPU.
4.5.1 System Stack Issues
Event handling in AVR32UC uses the system stack pointed to by the system stack pointer,
SP_SYS, for pushing and popping R8-R12, LR, status register, and return address. Since event
code may be timing-critical, SP_SYS should point to memory addresses in the IRAM section,
since the timing of accesses to this memory section is both fast and deterministic.
The user must also make sure that the system stack is large enough so that any event is able to
push the required registers to stack. If the system stack is full, and an event occurs, the system
will enter an UNDEFINED state.
4.5.2 Exceptions and Interrupt Requests
When an event other than scall or debug request is received by the core, the following actions
are performed atomically:
1. The pending event will not be accepted if it is masked. The I3M, I2M, I1M, I0M, EM, and
GM bits in the Status Register are used to mask different events. Not all events can be
masked. A few critical events (NMI, Unrecoverable Exception, TLB Multiple Hit, and
Bus Error) can not be masked. When an event is accepted, hardware automatically
sets the mask bits corresponding to all sources with equal or lower priority. This inhibits
acceptance of other events of the same or lower priority, except for the critical events
listed above. Software may choose to clear some or all of these bits after saving the
necessary state if other priority schemes are desired. It is the event source’s responsability
to ensure that their events are left pending until accepted by the CPU.
2. When a request is accepted, the Status Register and Program Counter of the current
context is stored to the system stack. If the event is an INT0, INT1, INT2, or INT3, registers
R8-R12 and LR are also automatically stored to stack. Storing the Status
Register ensures that the core is returned to the previous execution mode when the
current event handling is completed. When exceptions occur, both the EM and GM bits
are set, and the application may manually enable nested exceptions if desired by clearing
the appropriate bit. Each exception handler has a dedicated handler address, and
this address uniquely identifies the exception source.
3. The Mode bits are set to reflect the priority of the accepted event, and the correct register
file bank is selected. The address of the event handler, as shown in Table 4-4 on
page 34, is loaded into the Program Counter.
The execution of the event handler routine then continues from the effective address calculated.
The rete instruction signals the end of the event. When encountered, the Return Status Register
and Return Address Register are popped from the system stack and restored to the Status Register
and Program Counter. If the rete instruction returns from INT0, INT1, INT2, or INT3,
registers R8-R12 and LR are also popped from the system stack. The restored Status Register
contains information allowing the core to resume operation in the previous execution mode. This
concludes the event handling.
32
32142D–06/2013
ATUC64/128/256L3/4U
4.5.3 Supervisor Calls
The AVR32 instruction set provides a supervisor mode call instruction. The scall instruction is
designed so that privileged routines can be called from any context. This facilitates sharing of
code between different execution modes. The scall mechanism is designed so that a minimal
execution cycle overhead is experienced when performing supervisor routine calls from timecritical
event handlers.
The scall instruction behaves differently depending on which mode it is called from. The behaviour
is detailed in the instruction set reference. In order to allow the scall routine to return to the
correct context, a return from supervisor call instruction, rets, is implemented. In the AVR32UC
CPU, scall and rets uses the system stack to store the return address and the status register.
4.5.4 Debug Requests
The AVR32 architecture defines a dedicated Debug mode. When a debug request is received by
the core, Debug mode is entered. Entry into Debug mode can be masked by the DM bit in the
status register. Upon entry into Debug mode, hardware sets the SR.D bit and jumps to the
Debug Exception handler. By default, Debug mode executes in the exception context, but with
dedicated Return Address Register and Return Status Register. These dedicated registers
remove the need for storing this data to the system stack, thereby improving debuggability. The
Mode bits in the Status Register can freely be manipulated in Debug mode, to observe registers
in all contexts, while retaining full privileges.
Debug mode is exited by executing the retd instruction. This returns to the previous context.
4.5.5 Entry Points for Events
Several different event handler entry points exist. In AVR32UC, the reset address is
0x80000000. This places the reset address in the boot flash memory area.
TLB miss exceptions and scall have a dedicated space relative to EVBA where their event handler
can be placed. This speeds up execution by removing the need for a jump instruction placed
at the program address jumped to by the event hardware. All other exceptions have a dedicated
event routine entry point located relative to EVBA. The handler routine address identifies the
exception source directly.
AVR32UC uses the ITLB and DTLB protection exceptions to signal a MPU protection violation.
ITLB and DTLB miss exceptions are used to signal that an access address did not map to any of
the entries in the MPU. TLB multiple hit exception indicates that an access address did map to
multiple TLB entries, signalling an error.
All interrupt requests have entry points located at an offset relative to EVBA. This autovector offset
is specified by an interrupt controller. The programmer must make sure that none of the
autovector offsets interfere with the placement of other code. The autovector offset has 14
address bits, giving an offset of maximum 16384 bytes.
Special considerations should be made when loading EVBA with a pointer. Due to security considerations,
the event handlers should be located in non-writeable flash memory, or optionally in
a privileged memory protection region if an MPU is present.
If several events occur on the same instruction, they are handled in a prioritized way. The priority
ordering is presented in Table 4-4 on page 34. If events occur on several instructions at different
locations in the pipeline, the events on the oldest instruction are always handled before any
events on any younger instruction, even if the younger instruction has events of higher priority
33
32142D–06/2013
ATUC64/128/256L3/4U
than the oldest instruction. An instruction B is younger than an instruction A if it was sent down
the pipeline later than A.
The addresses and priority of simultaneous events are shown in Table 4-4 on page 34. Some of
the exceptions are unused in AVR32UC since it has no MMU, coprocessor interface, or floatingpoint
unit.
34
32142D–06/2013
ATUC64/128/256L3/4U
Table 4-4. Priority and Handler Addresses for Events
Priority Handler Address Name Event source Stored Return Address
1 0x80000000 Reset External input Undefined
2 Provided by OCD system OCD Stop CPU OCD system First non-completed instruction
3 EVBA+0x00 Unrecoverable exception Internal PC of offending instruction
4 EVBA+0x04 TLB multiple hit MPU PC of offending instruction
5 EVBA+0x08 Bus error data fetch Data bus First non-completed instruction
6 EVBA+0x0C Bus error instruction fetch Data bus First non-completed instruction
7 EVBA+0x10 NMI External input First non-completed instruction
8 Autovectored Interrupt 3 request External input First non-completed instruction
9 Autovectored Interrupt 2 request External input First non-completed instruction
10 Autovectored Interrupt 1 request External input First non-completed instruction
11 Autovectored Interrupt 0 request External input First non-completed instruction
12 EVBA+0x14 Instruction Address CPU PC of offending instruction
13 EVBA+0x50 ITLB Miss MPU PC of offending instruction
14 EVBA+0x18 ITLB Protection MPU PC of offending instruction
15 EVBA+0x1C Breakpoint OCD system First non-completed instruction
16 EVBA+0x20 Illegal Opcode Instruction PC of offending instruction
17 EVBA+0x24 Unimplemented instruction Instruction PC of offending instruction
18 EVBA+0x28 Privilege violation Instruction PC of offending instruction
19 EVBA+0x2C Floating-point UNUSED
20 EVBA+0x30 Coprocessor absent Instruction PC of offending instruction
21 EVBA+0x100 Supervisor call Instruction PC(Supervisor Call) +2
22 EVBA+0x34 Data Address (Read) CPU PC of offending instruction
23 EVBA+0x38 Data Address (Write) CPU PC of offending instruction
24 EVBA+0x60 DTLB Miss (Read) MPU PC of offending instruction
25 EVBA+0x70 DTLB Miss (Write) MPU PC of offending instruction
26 EVBA+0x3C DTLB Protection (Read) MPU PC of offending instruction
27 EVBA+0x40 DTLB Protection (Write) MPU PC of offending instruction
28 EVBA+0x44 DTLB Modified UNUSED
35
32142D–06/2013
ATUC64/128/256L3/4U
5. Memories
5.1 Embedded Memories
• Internal high-speed flash
– 256Kbytes (ATUC256L3U, ATUC256L4U)
– 128Kbytes (ATUC128L3U, ATUC128L4U)
– 64Kbytes (ATUC64L3U, ATUC64L4U)
• 0 wait state access at up to 25MHz in worst case conditions
• 1 wait state access at up to 50MHz in worst case conditions
• Pipelined flash architecture, allowing burst reads from sequential flash locations, hiding
penalty of 1 wait state access
• Pipelined flash architecture typically reduces the cycle penalty of 1 wait state operation
to only 8% compared to 0 wait state operation
• 100 000 write cycles, 15-year data retention capability
• Sector lock capabilities, bootloader protection, security bit
• 32 fuses, erased during chip erase
• User page for data to be preserved during chip erase
• Internal high-speed SRAM, single-cycle access at full speed
– 32Kbytes (ATUC256L3U, ATUC256L4U, ATUC128L3U, ATUC128L4U)
– 16Kbytes (ATUC64L3U, ATUC64L4U)
5.2 Physical Memory Map
The system bus is implemented as a bus matrix. All system bus addresses are fixed, and they
are never remapped in any way, not even during boot. Note that AVR32 UC CPU uses unsegmented
translation, as described in the AVR32 Architecture Manual. The 32-bit physical address
space is mapped as follows:
Table 5-1. ATUC64/128/256L3/4U Physical Memory Map
Memory Start Address
Size
ATUC256L3U, ATUC256L4U ATUC128L3U, ATUC128L4U ATUC64L3U, ATUC64L4U
Embedded SRAM 0x00000000 32Kbytes 32Kbytes 16Kbytes
Embedded Flash 0x80000000 256Kbytes 128Kbytes 64Kbytes
SAU Channels 0x90000000 256 bytes 256 bytes 256 bytes
HSB-PB Bridge B 0xFFFE0000 64Kbytes 64Kbytes 64Kbytes
HSB-PB Bridge A 0xFFFF0000 64Kbytes 64Kbytes 64Kbytes
Table 5-2. Flash Memory Parameters
Device Flash Size (FLASH_PW) Number of Pages (FLASH_P) Page Size (FLASH_W)
ATUC256L3U,
ATUC256L4U 256Kbytes 512 512 bytes
ATUC128L3U,
ATUC128L4U 128Kbytes 256 512 bytes
ATUC64L3U,
ATUC64L4U 64Kbytes 128 512 bytes
36
32142D–06/2013
ATUC64/128/256L3/4U
5.3 Peripheral Address Map
Table 5-3. Peripheral Address Mapping
Address Peripheral Name
0xFFFE0000
FLASHCDW Flash Controller - FLASHCDW
0xFFFE0400
HMATRIX HSB Matrix - HMATRIX
0xFFFE0800
SAU Secure Access Unit - SAU
0xFFFE1000
USBC USB 2.0 Interface - USBC
0xFFFF0000
PDCA Peripheral DMA Controller - PDCA
0xFFFF1000
INTC Interrupt controller - INTC
0xFFFF1400
PM Power Manager - PM
0xFFFF1800
SCIF System Control Interface - SCIF
0xFFFF1C00
AST Asynchronous Timer - AST
0xFFFF2000
WDT Watchdog Timer - WDT
0xFFFF2400
EIC External Interrupt Controller - EIC
0xFFFF2800
FREQM Frequency Meter - FREQM
0xFFFF2C00
GPIO General-Purpose Input/Output Controller - GPIO
0xFFFF3000
USART0 Universal Synchronous Asynchronous Receiver
Transmitter - USART0
0xFFFF3400
USART1 Universal Synchronous Asynchronous Receiver
Transmitter - USART1
0xFFFF3800
USART2 Universal Synchronous Asynchronous Receiver
Transmitter - USART2
0xFFFF3C00
USART3 Universal Synchronous Asynchronous Receiver
Transmitter - USART3
0xFFFF4000
SPI Serial Peripheral Interface - SPI
37
32142D–06/2013
ATUC64/128/256L3/4U
5.4 CPU Local Bus Mapping
Some of the registers in the GPIO module are mapped onto the CPU local bus, in addition to
being mapped on the Peripheral Bus. These registers can therefore be reached both by
accesses on the Peripheral Bus, and by accesses on the local bus.
Mapping these registers on the local bus allows cycle-deterministic toggling of GPIO pins since
the CPU and GPIO are the only modules connected to this bus. Also, since the local bus runs at
CPU speed, one write or read operation can be performed per clock cycle to the local busmapped
GPIO registers.
0xFFFF4400
TWIM0 Two-wire Master Interface - TWIM0
0xFFFF4800
TWIM1 Two-wire Master Interface - TWIM1
0xFFFF4C00
TWIS0 Two-wire Slave Interface - TWIS0
0xFFFF5000
TWIS1 Two-wire Slave Interface - TWIS1
0xFFFF5400
PWMA Pulse Width Modulation Controller - PWMA
0xFFFF5800
TC0 Timer/Counter - TC0
0xFFFF5C00
TC1 Timer/Counter - TC1
0xFFFF6000
ADCIFB ADC Interface - ADCIFB
0xFFFF6400
ACIFB Analog Comparator Interface - ACIFB
0xFFFF6800
CAT Capacitive Touch Module - CAT
0xFFFF6C00
GLOC Glue Logic Controller - GLOC
0xFFFF7000
AW aWire - AW
0xFFFF7400
ABDACB Audio Bitstream DAC - ABDACB
0xFFFF7800
IISC Inter-IC Sound (I2S) Controller - IISC
Table 5-3. Peripheral Address Mapping
38
32142D–06/2013
ATUC64/128/256L3/4U
The following GPIO registers are mapped on the local bus:
Table 5-4. Local Bus Mapped GPIO Registers
Port Register Mode
Local Bus
Address Access
0 Output Driver Enable Register (ODER) WRITE 0x40000040 Write-only
SET 0x40000044 Write-only
CLEAR 0x40000048 Write-only
TOGGLE 0x4000004C Write-only
Output Value Register (OVR) WRITE 0x40000050 Write-only
SET 0x40000054 Write-only
CLEAR 0x40000058 Write-only
TOGGLE 0x4000005C Write-only
Pin Value Register (PVR) - 0x40000060 Read-only
1 Output Driver Enable Register (ODER) WRITE 0x40000140 Write-only
SET 0x40000144 Write-only
CLEAR 0x40000148 Write-only
TOGGLE 0x4000014C Write-only
Output Value Register (OVR) WRITE 0x40000150 Write-only
SET 0x40000154 Write-only
CLEAR 0x40000158 Write-only
TOGGLE 0x4000015C Write-only
Pin Value Register (PVR) - 0x40000160 Read-only
39
32142D–06/2013
ATUC64/128/256L3/4U
6. Supply and Startup Considerations
6.1 Supply Considerations
6.1.1 Power Supplies
The ATUC64/128/256L3/4U has several types of power supply pins:
• VDDIO: Powers I/O lines. Voltage is 1.8 to 3.3V nominal.
• VDDIN: Powers I/O lines, the USB pins, and the internal regulator. Voltage is 1.8 to 3.3V
nominal if USB is not used, and 3.3V nominal when USB is used.
• VDDANA: Powers the ADC. Voltage is 1.8V nominal.
• VDDCORE: Powers the core, memories, and peripherals. Voltage is 1.8V nominal.
The ground pins GND are common to VDDCORE, VDDIO, and VDDIN. The ground pin for
VDDANA is GNDANA.
When VDDCORE is not connected to VDDIN, the VDDIN voltage must be higher than 1.98V.
Refer to Section 35. on page 897 for power consumption on the various supply pins.
For decoupling recommendations for the different power supplies, please refer to the schematic
checklist.
Refer to Section on page 10 for power supply connections for I/O pins.
6.1.2 Voltage Regulator
The ATUC64/128/256L3/4U embeds a voltage regulator that converts from 3.3V nominal to
1.8V with a load of up to 60 mA. The regulator supplies the output voltage on VDDCORE. The
regulator may only be used to drive internal circuitry in the device. VDDCORE should be externally
connected to the 1.8V domains. See Section 6.1.3 for regulator connection figures.
Adequate output supply decoupling is mandatory for VDDCORE to reduce ripple and avoid
oscillations. The best way to achieve this is to use two capacitors in parallel between VDDCORE
and GND as close to the device as possible. Please refer to Section 35.8 on page 911 for
decoupling capacitors values and regulator characteristics.
Figure 6-1. Supply Decoupling.
The voltage regulator can be turned off in the shutdown mode to power down the core logic and
keep a small part of the system powered in order to reduce power consumption. To enter this
mode the 3.3V supply mode, with 1.8V regulated I/O lines power supply configuration must be
used.
3.3V
1.8V
VDDIN
VDDCORE
1.8V
Regulator
CIN1
COUT1 COUT2
C IN3 IN2 C
40
32142D–06/2013
ATUC64/128/256L3/4U
6.1.3 Regulator Connection
The ATUC64/128/256L3/4U supports three power supply configurations:
• 3.3V single supply mode
– Shutdown mode is not available
• 1.8V single supply mode
– Shutdown mode is not available
• 3.3V supply mode, with 1.8V regulated I/O lines
– Shutdown mode is available
41
32142D–06/2013
ATUC64/128/256L3/4U
6.1.3.1 3.3V Single Supply Mode
In 3.3V single supply mode the internal regulator is connected to the 3.3V source (VDDIN pin)
and its output feeds VDDCORE. Figure 6-2 shows the power schematics to be used for 3.3V
single supply mode. All I/O lines will be powered by the same power (VDDIN=VDDIO).
Figure 6-2. 3.3V Single Supply Mode
VDDIO
VDDCORE
+
- 1.98-3.6V
VDDANA ADC
VDDIN GND
GNDANA
CPU,
Peripherals,
Memories,
SCIF, BOD,
RCSYS,
DFLL, PLL
OSC32K,
RC32K,
POR33,
SM33
I/O Pins I/O Pins
OSC32K_2,
AST, Wake,
Regulator
control
Linear
regulator
42
32142D–06/2013
ATUC64/128/256L3/4U
6.1.3.2 1.8V Single Supply Mode
In 1.8V single supply mode the internal regulator is not used, and VDDIO and VDDCORE are
powered by a single 1.8V supply as shown in Figure 6-3. All I/O lines will be powered by the
same power (VDDIN = VDDIO = VDDCORE).
Figure 6-3. 1.8V Single Supply Mode
VDDIO
VDDCORE
+
-
1.62-1.98V
VDDANA ADC
VDDIN GND
GNDANA
CPU,
Peripherals,
Memories,
SCIF, BOD,
RCSYS,
DFLL, PLL
OSC32K,
RC32K,
POR33,
SM33
I/O Pins I/O Pins
OSC32K_2,
AST, Wake,
Regulator
control
43
32142D–06/2013
ATUC64/128/256L3/4U
6.1.3.3 3.3V Supply Mode with 1.8V Regulated I/O Lines
In this mode, the internal regulator is connected to the 3.3V source and its output is connected
to both VDDCORE and VDDIO as shown in Figure 6-4. This configuration is required in order to
use Shutdown mode.
Figure 6-4. 3.3V Supply Mode with 1.8V Regulated I/O Lines
In this mode, some I/O lines are powered by VDDIN while other I/O lines are powered by VDDIO.
Refer to Section on page 10 for description of power supply for each I/O line.
Refer to the Power Manager chapter for a description of what parts of the system are powered in
Shutdown mode.
Important note: As the regulator has a maximum output current of 60 mA, this mode can only be
used in applications where the maximum I/O current is known and compatible with the core and
peripheral power consumption. Typically, great care must be used to ensure that only a few I/O
lines are toggling at the same time and drive very small loads.
VDDIO
VDDCORE
+
- 1.98-3.6V
VDDANA ADC
VDDIN GND
GNDANA
CPU,
Peripherals,
Memories,
SCIF, BOD,
RCSYS,
DFLL, PLL
OSC32K,
RC32K,
POR33,
SM33
I/O Pins I/O Pins
OSC32K_2,
AST, Wake,
Regulator
control
Linear
regulator
44
32142D–06/2013
ATUC64/128/256L3/4U
6.1.4 Power-up Sequence
6.1.4.1 Maximum Rise Rate
To avoid risk of latch-up, the rise rate of the power supplies must not exceed the values
described in Table 35-3 on page 898.
Recommended order for power supplies is also described in this chapter.
6.1.4.2 Minimum Rise Rate
The integrated Power-on Reset (POR33) circuitry monitoring the VDDIN powering supply
requires a minimum rise rate for the VDDIN power supply.
See Table 35-3 on page 898 for the minimum rise rate value.
If the application can not ensure that the minimum rise rate condition for the VDDIN power supply
is met, one of the following configurations can be used:
• A logic “0” value is applied during power-up on pin PA11 (WAKE_N) until VDDIN rises above
1.2V.
• A logic “0” value is applied during power-up on pin RESET_N until VDDIN rises above 1.2V.
6.2 Startup Considerations
This chapter summarizes the boot sequence of the ATUC64/128/256L3/4U. The behavior after
power-up is controlled by the Power Manager. For specific details, refer to the Power Manager
chapter.
6.2.1 Starting of Clocks
After power-up, the device will be held in a reset state by the Power-on Reset (POR18 and
POR33) circuitry for a short time to allow the power to stabilize throughout the device. After
reset, the device will use the System RC Oscillator (RCSYS) as clock source. Please refer to
Table 35-17 on page 910 for the frequency for this oscillator.
On system start-up, all high-speed clocks are disabled. All clocks to all modules are running. No
clocks have a divided frequency; all parts of the system receive a clock with the same frequency
as the System RC Oscillator.
When powering up the device, there may be a delay before the voltage has stabilized, depending
on the rise time of the supply used. The CPU can start executing code as soon as the supply
is above the POR18 and POR33 thresholds, and before the supply is stable. Before switching to
a high-speed clock source, the user should use the BOD to make sure the VDDCORE is above
the minimum level (1.62V).
6.2.2 Fetching of Initial Instructions
After reset has been released, the AVR32 UC CPU starts fetching instructions from the reset
address, which is 0x80000000. This address points to the first address in the internal Flash.
The code read from the internal flash is free to configure the clock system and clock sources.
Please refer to the PM and SCIF chapters for more details.
45
32142D–06/2013
ATUC64/128/256L3/4U
7. Peripheral DMA Controller (PDCA)
Rev: 1.2.3.1
7.1 Features
• Multiple channels
• Generates transfers between memories and peripherals such as USART and SPI
• Two address pointers/counters per channel allowing double buffering
• Performance monitors to measure average and maximum transfer latency
• Optional synchronizing of data transfers with extenal peripheral events
• Ring buffer functionality
7.2 Overview
The Peripheral DMA Controller (PDCA) transfers data between on-chip peripheral modules such
as USART, SPI and memories (those memories may be on- and off-chip memories). Using the
PDCA avoids CPU intervention for data transfers, improving the performance of the microcontroller.
The PDCA can transfer data from memory to a peripheral or from a peripheral to memory.
The PDCA consists of multiple DMA channels. Each channel has:
• A Peripheral Select Register
• A 32-bit memory pointer
• A 16-bit transfer counter
• A 32-bit memory pointer reload value
• A 16-bit transfer counter reload value
The PDCA communicates with the peripheral modules over a set of handshake interfaces. The
peripheral signals the PDCA when it is ready to receive or transmit data. The PDCA acknowledges
the request when the transmission has started.
When a transmit buffer is empty or a receive buffer is full, an optional interrupt request can be
generated.
46
32142D–06/2013
ATUC64/128/256L3/4U
7.3 Block Diagram
Figure 7-1. PDCA Block Diagram
7.4 Product Dependencies
In order to use this module, other parts of the system must be configured correctly, as described
below.
7.4.1 Power Management
If the CPU enters a sleep mode that disables the PDCA clocks, the PDCA will stop functioning
and resume operation after the system wakes up from sleep mode.
7.4.2 Clocks
The PDCA has two bus clocks connected: One High Speed Bus clock (CLK_PDCA_HSB) and
one Peripheral Bus clock (CLK_PDCA_PB). These clocks are generated by the Power Manager.
Both clocks are enabled at reset, and can be disabled in the Power Manager. It is
recommended to disable the PDCA before disabling the clocks, to avoid freezing the PDCA in
an undefined state.
7.4.3 Interrupts
The PDCA interrupt request lines are connected to the interrupt controller. Using the PDCA
interrupts requires the interrupt controller to be programmed first.
HSB to PB
Bridge
Peripheral DMA
Controller
(PDCA)
Peripheral
0
High Speed
Bus Matrix
Handshake Interfaces Peripheral Bus
IRQ
HSB
HSB
Interrupt
Controller
Peripheral
1
Peripheral
2
Peripheral
(n-1) ...
Memory
HSB
47
32142D–06/2013
ATUC64/128/256L3/4U
7.4.4 Peripheral Events
The PDCA peripheral events are connected via the Peripheral Event System. Refer to the
Peripheral Event System chapter for details.
7.5 Functional Description
7.5.1 Basic Operation
The PDCA consists of multiple independent PDCA channels, each capable of handling DMA
requests in parallel. Each PDCA channels contains a set of configuration registers which must
be configured to start a DMA transfer.
In this section the steps necessary to configure one PDCA channel is outlined.
The peripheral to transfer data to or from must be configured correctly in the Peripheral Select
Register (PSR). This is performed by writing the Peripheral Identity (PID) value for the corresponding
peripheral to the PID field in the PSR register. The PID also encodes the transfer
direction, i.e. memory to peripheral or peripheral to memory. See Section 7.5.6.
The transfer size must be written to the Transfer Size field in the Mode Register (MR.SIZE). The
size must match the data size produced or consumed by the selected peripheral. See Section
7.5.7.
The memory address to transfer to or from, depending on the PSR, must be written to the Memory
Address Register (MAR). For each transfer the memory address is increased by either a
one, two or four, depending on the size set in MR. See Section 7.5.2.
The number of data items to transfer is written to the TCR register. If the PDCA channel is
enabled, a transfer will start immediately after writing a non-zero value to TCR or the reload version
of TCR, TCRR. After each transfer the TCR value is decreased by one. Both MAR and TCR
can be read while the PDCA channel is active to monitor the DMA progress. See Section 7.5.3.
The channel must be enabled for a transfer to start. A channel is enable by writing a one to the
EN bit in the Control Register (CR).
7.5.2 Memory Pointer
Each channel has a 32-bit Memory Address Register (MAR). This register holds the memory
address for the next transfer to be performed. The register is automatically updated after each
transfer. The address will be increased by either one, two or four depending on the size of the
DMA transfer (byte, halfword or word). The MAR can be read at any time during transfer.
7.5.3 Transfer Counter
Each channel has a 16-bit Transfer Counter Register (TCR). This register must be written with
the number of transfers to be performed. The TCR register should contain the number of data
items to be transferred independently of the transfer size. The TCR can be read at any time during
transfer to see the number of remaining transfers.
7.5.4 Reload Registers
Both the MAR and the TCR have a reload register, respectively Memory Address Reload Register
(MARR) and Transfer Counter Reload Register (TCRR). These registers provide the
possibility for the PDCA to work on two memory buffers for each channel. When one buffer has
completed, MAR and TCR will be reloaded with the values in MARR and TCRR. The reload logic
is always enabled and will trigger if the TCR reaches zero while TCRR holds a non-zero value.
After reload, the MARR and TCRR registers are cleared.
48
32142D–06/2013
ATUC64/128/256L3/4U
If TCR is zero when writing to TCRR, the TCR and MAR are automatically updated with the
value written in TCRR and MARR.
7.5.5 Ring Buffer
When Ring Buffer mode is enabled the TCRR and MARR registers will not be cleared when
TCR and MAR registers reload. This allows the PDCA to read or write to the same memory
region over and over again until the transfer is actively stopped by the user. Ring Buffer mode is
enabled by writing a one to the Ring Buffer bit in the Mode Register (MR.RING).
7.5.6 Peripheral Selection
The Peripheral Select Register (PSR) decides which peripheral should be connected to the
PDCA channel. A peripheral is selected by writing the corresponding Peripheral Identity (PID) to
the PID field in the PSR register. Writing the PID will both select the direction of the transfer
(memory to peripheral or peripheral to memory), which handshake interface to use, and the
address of the peripheral holding register. Refer to the Peripheral Identity (PID) table in the Module
Configuration section for the peripheral PID values.
7.5.7 Transfer Size
The transfer size can be set individually for each channel to be either byte, halfword or word (8-
bit, 16-bit or 32-bit respectively). Transfer size is set by writing the desired value to the Transfer
Size field in the Mode Register (MR.SIZE).
When the PDCA moves data between peripherals and memory, data is automatically sized and
aligned. When memory is accessed, the size specified in MR.SIZE and system alignment is
used. When a peripheral register is accessed the data to be transferred is converted to a word
where bit n in the data corresponds to bit n in the peripheral register. If the transfer size is byte or
halfword, bits greater than 8 and16 respectively are set to zero.
Refer to the Module Configuration section for information regarding what peripheral registers are
used for the different peripherals and then to the peripheral specific chapter for information
about the size option available for the different registers.
7.5.8 Enabling and Disabling
Each DMA channel is enabled by writing a one to the Transfer Enable bit in the Control Register
(CR.TEN) and disabled by writing a one to the Transfer Disable bit (CR.TDIS). The current status
can be read from the Status Register (SR).
While the PDCA channel is enabled all DMA request will be handled as long the TCR and TCRR
is not zero.
7.5.9 Interrupts
Interrupts can be enabled by writing a one to the corresponding bit in the Interrupt Enable Register
(IER) and disabled by writing a one to the corresponding bit in the Interrupt Disable Register
(IDR). The Interrupt Mask Register (IMR) can be read to see whether an interrupt is enabled or
not. The current status of an interrupt source can be read through the Interrupt Status Register
(ISR).
The PDCA has three interrupt sources:
• Reload Counter Zero - The TCRR register is zero.
• Transfer Finished - Both the TCR and TCRR registers are zero.
• Transfer Error - An error has occurred in accessing memory.
49
32142D–06/2013
ATUC64/128/256L3/4U
7.5.10 Priority
If more than one PDCA channel is requesting transfer at a given time, the PDCA channels are
prioritized by their channel number. Channels with lower numbers have priority over channels
with higher numbers, giving channel zero the highest priority.
7.5.11 Error Handling
If the Memory Address Register (MAR) is set to point to an invalid location in memory, an error
will occur when the PDCA tries to perform a transfer. When an error occurs, the Transfer Error
bit in the Interrupt Status Register (ISR.TERR) will be set and the DMA channel that caused the
error will be stopped. In order to restart the channel, the user must program the Memory
Address Register to a valid address and then write a one to the Error Clear bit in the Control
Register (CR.ECLR). If the Transfer Error interrupt is enabled, an interrupt request will be generated
when a transfer error occurs.
7.5.12 Peripheral Event Trigger
Peripheral events can be used to trigger PDCA channel transfers. Peripheral Event synchronizations
are enabled by writing a one to the Event Trigger bit in the Mode Register (MR.ETRIG).
When set, all DMA requests will be blocked until a peripheral event is received. For each peripheral
event received, only one data item is transferred. If no DMA requests are pending when a
peripheral event is received, the PDCA will start a transfer as soon as a peripheral event is
detected. If multiple events are received while the PDCA channel is busy transferring data, an
overflow condition will be signaled in the Peripheral Event System. Refer to the Peripheral Event
System chapter for more information.
7.6 Performance Monitors
Up to two performance monitors allow the user to measure the activity and stall cycles for PDCA
transfers. To monitor a PDCA channel, the corresponding channel number must be written to
one of the MON0/1CH fields in the Performance Control Register (PCONTROL) and a one must
be written to the corresponding CH0/1EN bit in the same register.
Due to performance monitor hardware resource sharing, the two monitor channels should NOT
be programmed to monitor the same PDCA channel. This may result in UNDEFINED performance
monitor behavior.
7.6.1 Measuring mechanisms
Three different parameters can be measured by each channel:
• The number of data transfer cycles since last channel reset, both for read and write
• The number of stall cycles since last channel reset, both for read and write
• The maximum latency since last channel reset, both for read and write
These measurements can be extracted by software and used to generate indicators for bus
latency, bus load, and maximum bus latency.
Each of the counters has a fixed width, and may therefore overflow. When an overflow is
encountered in either the Performance Channel Data Read/Write Cycle registers (PRDATA0/1
and PWDATA0/1) or the Performance Channel Read/Write Stall Cycles registers (PRSTALL0/1
and PWSTALL0/1) of a channel, all registers in the channel are reset. This behavior is altered if
the Channel Overflow Freeze bit is one in the Performance Control register (PCONTROL.CH0/1OVF).
If this bit is one, the channel registers are frozen when either DATA or
STALL reaches its maximum value. This simplifies one-shot readout of the counter values.
50
32142D–06/2013
ATUC64/128/256L3/4U
The registers can also be manually reset by writing a one to the Channel Reset bit in the PCONTROL
register (PCONTROL.CH0/1RES). The Performance Channel Read/Write Latency
registers (PRLAT0/1 and PWLAT0/1) are saturating when their maximum count value is
reached. The PRLAT0/1 and PWLAT0/1 registers can only be reset by writing a one to the corresponding
reset bit in PCONTROL (PCONTROL.CH0/1RES).
A counter is enabled by writing a one to the Channel Enable bit in the Performance Control Register
(PCONTROL.CH0/1EN).
51
32142D–06/2013
ATUC64/128/256L3/4U
7.7 User Interface
7.7.1 Memory Map Overview
The channels are mapped as shown in Table 7-1. Each channel has a set of configuration registers,
shown in Table 7-2, where n is the channel number.
7.7.2 Channel Memory Map
Note: 1. The reset values are device specific. Please refer to the Module Configuration section at the
end of this chapter.
Table 7-1. PDCA Register Memory Map
Address Range Contents
0x000 - 0x03F DMA channel 0 configuration registers
0x040 - 0x07F DMA channel 1 configuration registers
... ...
(0x000 - 0x03F)+m*0x040 DMA channel m configuration registers
0x800-0x830 Performance Monitor registers
0x834 Version register
Table 7-2. PDCA Channel Configuration Registers
Offset Register Register Name Access Reset
0x000 + n*0x040 Memory Address Register MAR Read/Write 0x00000000
0x004 + n*0x040 Peripheral Select Register PSR Read/Write - (1)
0x008 + n*0x040 Transfer Counter Register TCR Read/Write 0x00000000
0x00C + n*0x040 Memory Address Reload Register MARR Read/Write 0x00000000
0x010 + n*0x040 Transfer Counter Reload Register TCRR Read/Write 0x00000000
0x014 + n*0x040 Control Register CR Write-only 0x00000000
0x018 + n*0x040 Mode Register MR Read/Write 0x00000000
0x01C + n*0x040 Status Register SR Read-only 0x00000000
0x020 + n*0x040 Interrupt Enable Register IER Write-only 0x00000000
0x024 + n*0x040 Interrupt Disable Register IDR Write-only 0x00000000
0x028 + n*0x040 Interrupt Mask Register IMR Read-only 0x00000000
0x02C + n*0x040 Interrupt Status Register ISR Read-only 0x00000000
52
32142D–06/2013
ATUC64/128/256L3/4U
7.7.3 Performance Monitor Memory Map
Note: 1. The number of performance monitors is device specific. If the device has only one performance
monitor, the Channel1 registers are not available. Please refer to the Module
Configuration section at the end of this chapter for the number of performance monitors on this
device.
7.7.4 Version Register Memory Map
Note: 1. The reset values are device specific. Please refer to the Module Configuration section at the end of this chapter.
Table 7-3. PDCA Performance Monitor Registers(1)
Offset Register Register Name Access Reset
0x800 Performance Control Register PCONTROL Read/Write 0x00000000
0x804 Channel0 Read Data Cycles PRDATA0 Read-only 0x00000000
0x808 Channel0 Read Stall Cycles PRSTALL0 Read-only 0x00000000
0x80C Channel0 Read Max Latency PRLAT0 Read-only 0x00000000
0x810 Channel0 Write Data Cycles PWDATA0 Read-only 0x00000000
0x814 Channel0 Write Stall Cycles PWSTALL0 Read-only 0x00000000
0x818 Channel0 Write Max Latency PWLAT0 Read-only 0x00000000
0x81C Channel1 Read Data Cycles PRDATA1 Read-only 0x00000000
0x820 Channel1 Read Stall Cycles PRSTALL1 Read-only 0x00000000
0x824 Channel1 Read Max Latency PRLAT1 Read-only 0x00000000
0x828 Channel1 Write Data Cycles PWDATA1 Read-only 0x00000000
0x82C Channel1 Write Stall Cycles PWSTALL1 Read-only 0x00000000
0x830 Channel1 Write Max Latency PWLAT1 Read-only 0x00000000
Table 7-4. PDCA Version Register Memory Map
Offset Register Register Name Access Reset
0x834 Version Register VERSION Read-only - (1)
53
32142D–06/2013
ATUC64/128/256L3/4U
7.7.5 Memory Address Register
Name: MAR
Access Type: Read/Write
Offset: 0x000 + n*0x040
Reset Value: 0x00000000
• MADDR: Memory Address
Address of memory buffer. MADDR should be programmed to point to the start of the memory buffer when configuring the
PDCA. During transfer, MADDR will point to the next memory location to be read/written.
31 30 29 28 27 26 25 24
MADDR[31:24]
23 22 21 20 19 18 17 16
MADDR[23:16]
15 14 13 12 11 10 9 8
MADDR[15:8]
76543210
MADDR[7:0]
54
32142D–06/2013
ATUC64/128/256L3/4U
7.7.6 Peripheral Select Register
Name: PSR
Access Type: Read/Write
Offset: 0x004 + n*0x040
Reset Value: -
• PID: Peripheral Identifier
The Peripheral Identifier selects which peripheral should be connected to the DMA channel. Writing a PID will select both which
handshake interface to use, the direction of the transfer and also the address of the Receive/Transfer Holding Register for the
peripheral. See the Module Configuration section of PDCA for details. The width of the PID field is device specific and
dependent on the number of peripheral modules in the device.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
PID
55
32142D–06/2013
ATUC64/128/256L3/4U
7.7.7 Transfer Counter Register
Name: TCR
Access Type: Read/Write
Offset: 0x008 + n*0x040
Reset Value: 0x00000000
• TCV: Transfer Counter Value
Number of data items to be transferred by the PDCA. TCV must be programmed with the total number of transfers to be made.
During transfer, TCV contains the number of remaining transfers to be done.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
TCV[15:8]
76543210
TCV[7:0]
56
32142D–06/2013
ATUC64/128/256L3/4U
7.7.8 Memory Address Reload Register
Name: MARR
Access Type: Read/Write
Offset: 0x00C + n*0x040
Reset Value: 0x00000000
• MARV: Memory Address Reload Value
Reload Value for the MAR register. This value will be loaded into MAR when TCR reaches zero if the TCRR register has a nonzero
value.
31 30 29 28 27 26 25 24
MARV[31:24]
23 22 21 20 19 18 17 16
MARV[23:16]
15 14 13 12 11 10 9 8
MARV[15:8]
76543210
MARV[7:0]
57
32142D–06/2013
ATUC64/128/256L3/4U
7.7.9 Transfer Counter Reload Register
Name: TCRR
Access Type: Read/Write
Offset: 0x010 + n*0x040
Reset Value: 0x00000000
• TCRV: Transfer Counter Reload Value
Reload value for the TCR register. When TCR reaches zero, it will be reloaded with TCRV if TCRV has a positive value. If TCRV
is zero, no more transfers will be performed for the channel. When TCR is reloaded, the TCRR register is cleared.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
TCRV[15:8]
76543210
TCRV[7:0]
58
32142D–06/2013
ATUC64/128/256L3/4U
7.7.10 Control Register
Name: CR
Access Type: Write-only
Offset: 0x014 + n*0x040
Reset Value: 0x00000000
• ECLR: Transfer Error Clear
Writing a zero to this bit has no effect.
Writing a one to this bit will clear the Transfer Error bit in the Status Register (SR.TERR). Clearing the SR.TERR bit will allow the
channel to transmit data. The memory address must first be set to point to a valid location.
• TDIS: Transfer Disable
Writing a zero to this bit has no effect.
Writing a one to this bit will disable transfer for the DMA channel.
• TEN: Transfer Enable
Writing a zero to this bit has no effect.
Writing a one to this bit will enable transfer for the DMA channel.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
- - - - - - - ECLR
76543210
- - - - - - TDIS TEN
59
32142D–06/2013
ATUC64/128/256L3/4U
7.7.11 Mode Register
Name: MR
Access Type: Read/Write
Offset: 0x018 + n*0x040
Reset Value: 0x00000000
• RING: Ring Buffer
0:The Ring buffer functionality is disabled.
1:The Ring buffer functionality is enabled. When enabled, the reload registers, MARR and TCRR will not be cleared after reload.
• ETRIG: Event Trigger
0:Start transfer when the peripheral selected in Peripheral Select Register (PSR) requests a transfer.
1:Start transfer only when or after a peripheral event is received.
• SIZE: Size of Transfer
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
- - - - RING ETRIG SIZE
Table 7-5. Size of Transfer
SIZE Size of Transfer
0 Byte
1 Halfword
2 Word
3 Reserved
60
32142D–06/2013
ATUC64/128/256L3/4U
7.7.12 Status Register
Name: SR
Access Type: Read-only
Offset: 0x01C + n*0x040
Reset Value: 0x00000000
• TEN: Transfer Enabled
This bit is cleared when the TDIS bit in CR is written to one.
This bit is set when the TEN bit in CR is written to one.
0: Transfer is disabled for the DMA channel.
1: Transfer is enabled for the DMA channel.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
- - - - - - - TEN
61
32142D–06/2013
ATUC64/128/256L3/4U
7.7.13 Interrupt Enable Register
Name: IER
Access Type: Write-only
Offset: 0x020 + n*0x040
Reset Value: 0x00000000
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will set the corresponding bit in IMR.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
- - - - - TERR TRC RCZ
62
32142D–06/2013
ATUC64/128/256L3/4U
7.7.14 Interrupt Disable Register
Name: IDR
Access Type: Write-only
Offset: 0x024 + n*0x040
Reset Value: 0x00000000
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will clear the corresponding bit in IMR.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
- - - - - TERR TRC RCZ
63
32142D–06/2013
ATUC64/128/256L3/4U
7.7.15 Interrupt Mask Register
Name: IMR
Access Type: Read-only
Offset: 0x028 + n*0x040
Reset Value: 0x00000000
0: The corresponding interrupt is disabled.
1: The corresponding interrupt is enabled.
A bit in this register is cleared when the corresponding bit in IDR is written to one.
A bit in this register is set when the corresponding bit in IER is written to one.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
- - - - - TERR TRC RCZ
64
32142D–06/2013
ATUC64/128/256L3/4U
7.7.16 Interrupt Status Register
Name: ISR
Access Type: Read-only
Offset: 0x02C + n*0x040
Reset Value: 0x00000000
• TERR: Transfer Error
This bit is cleared when no transfer errors have occurred since the last write to CR.ECLR.
This bit is set when one or more transfer errors has occurred since reset or the last write to CR.ECLR.
• TRC: Transfer Complete
This bit is cleared when the TCR and/or the TCRR holds a non-zero value.
This bit is set when both the TCR and the TCRR are zero.
• RCZ: Reload Counter Zero
This bit is cleared when the TCRR holds a non-zero value.
This bit is set when TCRR is zero.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
- - - - - TERR TRC RCZ
65
32142D–06/2013
ATUC64/128/256L3/4U
7.7.17 Performance Control Register
Name: PCONTROL
Access Type: Read/Write
Offset: 0x800
Reset Value: 0x00000000
• MON1CH: Performance Monitor Channel 1
• MON0CH: Performance Monitor Channel 0
The PDCA channel number to monitor with counter n
Due to performance monitor hardware resource sharing, the two performance monitor channels should NOT be programmed to
monitor the same PDCA channel. This may result in UNDEFINED monitor behavior.
• CH1RES: Performance Channel 1 Counter Reset
Writing a zero to this bit has no effect.
Writing a one to this bit will reset the counter in the channel specified in MON1CH.
This bit always reads as zero.
• CH0RES: Performance Channel 0 Counter Reset
Writing a zero to this bit has no effect.
Writing a one to this bit will reset the counter in the channel specified in MON0CH.
This bit always reads as zero.
• CH1OF: Channel 1 Overflow Freeze
0: The performance channel registers are reset if DATA or STALL overflows.
1: All performance channel registers are frozen just before DATA or STALL overflows.
• CH1OF: Channel 0 Overflow Freeze
0: The performance channel registers are reset if DATA or STALL overflows.
1: All performance channel registers are frozen just before DATA or STALL overflows.
• CH1EN: Performance Channel 1 Enable
0: Performance channel 1 is disabled.
1: Performance channel 1 is enabled.
• CH0EN: Performance Channel 0 Enable
0: Performance channel 0 is disabled.
1: Performance channel 0 is enabled.
31 30 29 28 27 26 25 24
- - MON1CH
23 22 21 20 19 18 17 16
- - MON0CH
15 14 13 12 11 10 9 8
- - - - - - CH1RES CH0RES
76543210
- - CH1OF CH0OF - - CH1EN CH0EN
66
32142D–06/2013
ATUC64/128/256L3/4U
7.7.18 Performance Channel 0 Read Data Cycles
Name: PRDATA0
Access Type: Read-only
Offset: 0x804
Reset Value: 0x00000000
• DATA: Data Cycles Counted Since Last Reset
Clock cycles are counted using the CLK_PDCA_HSB clock
31 30 29 28 27 26 25 24
DATA[31:24]
23 22 21 20 19 18 17 16
DATA[23:16]
15 14 13 12 11 10 9 8
DATA[15:8]
76543210
DATA[7:0]
67
32142D–06/2013
ATUC64/128/256L3/4U
7.7.19 Performance Channel 0 Read Stall Cycles
Name: PRSTALL0
Access Type: Read-only
Offset: 0x808
Reset Value: 0x00000000
• STALL: Stall Cycles Counted Since Last Reset
Clock cycles are counted using the CLK_PDCA_HSB clock
31 30 29 28 27 26 25 24
STALL[31:24]
23 22 21 20 19 18 17 16
STALL[23:16]
15 14 13 12 11 10 9 8
STALL[15:8]
76543210
STALL[7:0]
68
32142D–06/2013
ATUC64/128/256L3/4U
7.7.20 Performance Channel 0 Read Max Latency
Name: PRLAT0
Access Type: Read/Write
Offset: 0x80C
Reset Value: 0x00000000
• LAT: Maximum Transfer Initiation Cycles Counted Since Last Reset
Clock cycles are counted using the CLK_PDCA_HSB clock
This counter is saturating. The register is reset only when PCONTROL.CH0RES is written to one.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
LAT[15:8]
76543210
LAT[7:0]
69
32142D–06/2013
ATUC64/128/256L3/4U
7.7.21 Performance Channel 0 Write Data Cycles
Name: PWDATA0
Access Type: Read-only
Offset: 0x810
Reset Value: 0x00000000
• DATA: Data Cycles Counted Since Last Reset
Clock cycles are counted using the CLK_PDCA_HSB clock
31 30 29 28 27 26 25 24
DATA[31:24]
23 22 21 20 19 18 17 16
DATA[23:16]
15 14 13 12 11 10 9 8
DATA[15:8]
76543210
DATA[7:0]
70
32142D–06/2013
ATUC64/128/256L3/4U
7.7.22 Performance Channel 0 Write Stall Cycles
Name: PWSTALL0
Access Type: Read-only
Offset: 0x814
Reset Value: 0x00000000
• STALL: Stall Cycles Counted Since Last Reset
Clock cycles are counted using the CLK_PDCA_HSB clock
31 30 29 28 27 26 25 24
STALL[31:24]
23 22 21 20 19 18 17 16
STALL[23:16]
15 14 13 12 11 10 9 8
STALL[15:8]
76543210
STALL[7:0]
71
32142D–06/2013
ATUC64/128/256L3/4U
7.7.23 Performance Channel 0 Write Max Latency
Name: PWLAT0
Access Type: Read/Write
Offset: 0x818
Reset Value: 0x00000000
• LAT: Maximum Transfer Initiation Cycles Counted Since Last Reset
Clock cycles are counted using the CLK_PDCA_HSB clock
This counter is saturating. The register is reset only when PCONTROL.CH0RES is written to one.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
LAT[15:8]
76543210
LAT[7:0]
72
32142D–06/2013
ATUC64/128/256L3/4U
7.7.24 Performance Channel 1 Read Data Cycles
Name: PRDATA1
Access Type: Read-only
Offset: 0x81C
Reset Value: 0x00000000
• DATA: Data Cycles Counted Since Last Reset
Clock cycles are counted using the CLK_PDCA_HSB clock
31 30 29 28 27 26 25 24
DATA[31:24]
23 22 21 20 19 18 17 16
DATA[23:16]
15 14 13 12 11 10 9 8
DATA[15:8]
76543210
DATA[7:0]
73
32142D–06/2013
ATUC64/128/256L3/4U
7.7.25 Performance Channel 1 Read Stall Cycles
Name: PRSTALL1
Access Type: Read-only
Offset: 0x820
Reset Value: 0x00000000
• STALL: Stall Cycles Counted Since Last Reset
Clock cycles are counted using the CLK_PDCA_HSB clock
31 30 29 28 27 26 25 24
STALL[31:24]
23 22 21 20 19 18 17 16
STALL[23:16]
15 14 13 12 11 10 9 8
STALL[15:8]
76543210
STALL[7:0]
74
32142D–06/2013
ATUC64/128/256L3/4U
7.7.26 Performance Channel 1 Read Max Latency
Name: PRLAT1
Access Type: Read/Write
Offset: 0x824
Reset Value: 0x00000000
• LAT: Maximum Transfer Initiation Cycles Counted Since Last Reset
Clock cycles are counted using the CLK_PDCA_HSB clock
This counter is saturating. The register is reset only when PCONTROL.CH1RES is written to one.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
LAT[15:8]
76543210
LAT[7:0]
75
32142D–06/2013
ATUC64/128/256L3/4U
7.7.27 Performance Channel 1 Write Data Cycles
Name: PWDATA1
Access Type: Read-only
Offset: 0x828
Reset Value: 0x00000000
• DATA: Data Cycles Counted Since Last Reset
Clock cycles are counted using the CLK_PDCA_HSB clock
31 30 29 28 27 26 25 24
DATA[31:24]
23 22 21 20 19 18 17 16
DATA[23:16]
15 14 13 12 11 10 9 8
DATA[15:8]
76543210
DATA[7:0]
76
32142D–06/2013
ATUC64/128/256L3/4U
7.7.28 Performance Channel 1 Write Stall Cycles
Name: PWSTALL1
Access Type: Read-only
Offset: 0x82C
Reset Value: 0x00000000
• STALL: Stall Cycles Counted Since Last Reset
Clock cycles are counted using the CLK_PDCA_HSB clock
31 30 29 28 27 26 25 24
STALL[31:24]
23 22 21 20 19 18 17 16
STALL[23:16]
15 14 13 12 11 10 9 8
STALL[15:8]
76543210
STALL[7:0]
77
32142D–06/2013
ATUC64/128/256L3/4U
7.7.29 Performance Channel 1 Write Max Latency
Name: PWLAT1
Access Type: Read/Write
Offset: 0x830
Reset Value: 0x00000000
• LAT: Maximum Transfer Initiation Cycles Counted Since Last Reset
Clock cycles are counted using the CLK_PDCA_HSB clock
This counter is saturating. The register is reset only when PCONTROL.CH1RES is written to one.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
LAT[15:8]
76543210
LAT[7:0]
78
32142D–06/2013
ATUC64/128/256L3/4U
7.7.30 PDCA Version Register
Name: VERSION
Access Type: Read-only
Offset: 0x834
Reset Value: -
• VARIANT: Variant Number
Reserved. No functionality associated.
• VERSION: Version Number
Version number of the module. No functionality associated.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
- - - - VARIANT
15 14 13 12 11 10 9 8
- - - - VERSION[11:8]
76543210
VERSION[7:0]
79
32142D–06/2013
ATUC64/128/256L3/4U
7.8 Module Configuration
The specific configuration for each PDCA instance is listed in the following tables.The module
bus clocks listed here are connected to the system bus clocks. Please refer to the Power Manager
chapter for details.
The PDCA and the peripheral modules communicate through a set of handshake signals. The
following table defines the valid settings for the Peripheral Identifier (PID) in the PDCA Peripheral
Select Register (PSR). The direction is specified as observed from the memory, so RX
means transfers from peripheral to memory, and TX means from memory to peripheral.
Table 7-6. PDCA Configuration
Feature PDCA
Number of channels 12
Number of performance monitors 1
Table 7-7. PDCA Clocks
Clock Name Description
CLK_PDCA_HSB Clock for the PDCA HSB interface
CLK_PDCA_PB Clock for the PDCA PB interface
Table 7-8. Register Reset Values
Register Reset Value
PSR CH 0 0
PSR CH 1 1
PSR CH 2 2
PSR CH 3 3
PSR CH 4 4
PSR CH 5 5
PSR CH 6 6
PSR CH 7 7
PSR CH 8 8
PSR CH 9 9
PSR CH 10 10
PSR CH 11 11
VERSION 123
Table 7-9. Peripheral Identity Values
PID Direction Peripheral Instance Peripheral Register
0 RX USART0 RHR
1 RX USART1 RHR
2 RX USART2 RHR
80
32142D–06/2013
ATUC64/128/256L3/4U
3 RX USART3 RHR
4 RX SPI RDR
5 RX TWIM0 RHR
6 RX TWIM1 RHR
7 RX TWIS0 RHR
8 RX TWIS1 RHR
9 RX ADCIFB LCDR
10 RX AW RHR
11 RX CAT ACOUNT
12 TX USART0 THR
13 TX USART1 THR
14 TX USART2 THR
15 TX USART3 THR
16 TX SPI TDR
17 TX TWIM0 THR
18 TX TWIM1 THR
19 TX TWIS0 THR
20 TX TWIS1 THR
21 TX AW THR
22 TX CAT MBLEN
23 TX ABDACB SDR0
24 TX ABDACB SDR1
25 RX IISC RHR (CH0)
26 RX IISC RHR (CH1)
27 TX IISC THR (CH0)
28 TX IISC THR (CH1)
29 RX CAT DMATSR
30 TX CAT DMATSW
Table 7-9. Peripheral Identity Values
PID Direction Peripheral Instance Peripheral Register
81
32142D–06/2013
ATUC64/128/256L3/4U
8. USB Interface (USBC)
Rev: 2.0.0.15
8.1 Features
• Compatible with the USB 2.0 specification
• Supports full (12Mbit/s) and low (1.5Mbit/s) speed communication
• Seven physical pipes/endpoints in ping-pong mode
• Flexible pipe/endpoint configuration and reallocation of data buffers in embedded RAM
• Up to two memory banks per pipe/endpoint
• Built-in DMA with multi-packet support through ping-pong mode
• On-chip transceivers with built-in pull-ups and pull-downs
8.2 Overview
The Universal Serial Bus interface (USBC) module complies with the Universal Serial Bus (USB)
2.0 specification.
Each pipe/endpoint can be configured into one of several transfer types. It can be associated
with one or more memory banks (located inside the embedded system or CPU RAM) used to
store the current data payload. If two banks are used (“ping-pong” mode), then one bank is read
or written by the CPU (or any other HSB master) while the other is read or written by the USBC
core.
Table 8-1 describes the hardware configuration of the USBC module.
8.3 Block Diagram
The USBC interfaces a USB link with a data flow stored in the embedded ram (CPU or HSB).
The USBC requires a 48MHz ± 0.25% reference clock, which is the USB generic clock. For
more details see ”Clocks” on page 84. The 48MHz clock is used to generate either a 12MHz fullspeed
or a 1.5MHz low-speed bit clock from the received USB differential data, and to transmit
data according to full- or low-speed USB device tolerances. Clock recovery is achieved by a digital
phase-locked loop (a DPLL, not represented) in the USBC module, which complies with the
USB jitter specifications.
The USBC module consists of:
• HSB master interface
Table 8-1. Description of USB pipes/endpoints
pipe/endpoint Mnemonic Max. size
Number of
available banks Type
0 PEP0 1023 bytes 1 Control/Isochronous/Bulk/Interrupt
1 PEP1 1023 bytes 2 Control/Isochronous/Bulk/Interrupt
2 PEP2 1023 bytes 2 Control/Isochronous/Bulk/Interrupt
... ... ... ... ...
6 PEP6 1023 bytes 2 Control/Isochronous/Bulk/Interrupt
82
32142D–06/2013
ATUC64/128/256L3/4U
• User interface
• USB Core
• Transceiver pads
Figure 8-1. USBC Block Diagram
Note: in the block diagram is symbolic, it is mapped to a GPIO pin (See Section “8.5.1” on page 84.).
The VBUS detection (rising edge detection on the GPIO pin) should be handled by software.
Interrupt
Controller
USB interrupts
DM
USB_VBUS (1)
USB
DP
User interface
SCIF GCLK_USBC @ 48 MHz
PB
USB 2.0
Core
USB clock
domain
System clock
domain
HSB
HSB Master
83
32142D–06/2013
ATUC64/128/256L3/4U
8.4 I/O Lines Description
Table 8-2. I/O Lines Description
PIn Name Pin Description Type Active Level
DM Data -: Differential Data Line - Port Input/Output
DP Data +: Differential Data Line + Port Input/Output
84
32142D–06/2013
ATUC64/128/256L3/4U
8.5 Product Dependencies
In order to use this module, other parts of the system must be configured correctly, as described
below.
8.5.1 I/O Lines
The USBC pins may be multiplexed with the I/O Controller lines. The user must first configure
the I/O Controller to assign the desired USBC pins to their peripheral functions.
The USB VBUS line should be connected to a GPIO pin and the user should monitor this with
software.
8.5.2 Power Management
If the CPU enters a sleep mode that disables clocks used by the USBC, the USBC will stop functioning
and resume operation after the system wakes up from sleep mode.
8.5.3 Clocks
The USBC has two bus clocks connected: One High Speed Bus clock (CLK_USBC_HSB) and
one Peripheral Bus clock (CLK_USBC_PB). These clocks are generated by the Power Manager.
Both clocks are enabled at reset, and can be disabled by the Power Manager. It is
recommended to disable the USBC before disabling the clocks, to avoid freezing the USBC in
an undefined state.
The 48MHz USB clock is generated by a dedicated generic clock from the SCIF module. Before
using the USB, the user must ensure that the USB generic clock (GCLK_USBC) is enabled at
48MHz in the SCIF module.
8.5.4 Interrupts
The USBC interrupt request line is connected to the interrupt controller. Using the USBC interrupt
requires the interrupt controller to be programmed first.
The USBC asynchronous interrupt can wake the CPU from any sleep mode:
• The Wakeup Interrupt (WAKEUP)
85
32142D–06/2013
ATUC64/128/256L3/4U
8.6 Functional Description
8.6.1 USB General Operation
8.6.1.1 Initialization
After a hardware reset, the USBC is in the Reset state. In this state:
• The module is disabled. The USBC Enable bit in the General Control register
(USBCON.USBE) is reset.
• The module clock is stopped in order to minimize power consumption. The Freeze USB Clock
bit in USBCON (USBCON.FRZCLK) is set.
• The USB pad is in suspend mode.
• The internal states and registers of the device are reset.
• The Freeze USB Clock (FRZCLK), USBC Enable (USBE), in USBCON and the Low-Speed
mode bit in the Device General Control register (UDCON.LS) can be written to by software,
so that the user can configure pads and speed before enabling the module. These values are
only taken into account once the module has been enabled and unfrozen.
After writing a one to USBCON.USBE, the USBC enters device mode in idle state.
Refer to Section 8.6.2 for the basic operation of the device mode.
The USBC can be disabled at any time by writing a zero to USBCON.USBE, this acts as a hardware
reset, except that the FRZCLK,bit in USBCON, and the LS bits in UDCON are not reset.
8.6.1.2 Interrupts
One interrupt vector is assigned to the USBC.
See Section 8.6.2.18 for further details about device interrupts.
See Section 8.5.4 for asynchronous interrupts.
8.6.1.3 Frozen clock
When the USB clock is frozen, it is still possible to access the following bits: FRZCLK, and USBE
in the USBCON register, and LS in the UDCON register.
When FRZCLK is set, only the asynchronous interrupt can trigger a USB interrupt (see Section
8.5.4).
8.6.1.4 Speed control
• Device mode
When the USBC interface is in device mode, the speed selection is done by the UDCON.LS bit,
connecting an internal pull-up resistor to either DP (full-speed mode) or DM (low-speed mode).
The LS bit shall be written before attaching the device, which can be simulated by clearing the
UDCON.DETACH bit.
86
32142D–06/2013
ATUC64/128/256L3/4U
Figure 8-2. Speed Selection in device mode
8.6.1.5 Data management
Endpoints and pipe buffers can be allocated anywhere in the embedded memory (CPU RAM or
HSB RAM).
See ”RAM management” on page 90.
8.6.1.6 Pad Suspend
Figure 8-3 illustrates the behavior of the USB pad in device mode.
Figure 8-3. Pad Behavior
• In Idle state, the pad is in low power consumption mode.
• In Active state, the pad is working.
Figure 8-4 illustrates the pad events leading to a PAD state change.
RPU
UDCON.DETACH
DP
DM
UDCON.LS
VBUS
Idle
Active
USBE = 1
& DETACH = 0
& Suspend
USBE = 0
| DETACH = 1
| Suspend
87
32142D–06/2013
ATUC64/128/256L3/4U
Figure 8-4. Pad events
The Suspend Interrupt bit in the Device Global Interrupt register (UDINT.SUSP) is set and the
Wakeup Interrupt (UDINT.WAKEUP) bit is cleared when a USB Suspend state has been
detected on the USB bus. This event automatically puts the USB pad in the Idle state. The
detection of a non-idle event sets WAKEUP, clears SUSP, and wakes the USB pad.
The pad goes to the Idle state if the module is disabled or if UDCON.DETACH is written to one.
It returns to the Active state when USBCON.USBE is written to one and DETACH is written to
zero.
SUSP Suspend detected Cleared on Wakeup
WAKEUP Wakeup detected Cleared by software to acknowledge the interrupt
PAD state
Active Idle Active
88
32142D–06/2013
ATUC64/128/256L3/4U
8.6.2 USBC Device Mode Operation
8.6.2.1 Device Enabling
In device mode, the USBC supports full- and low-speed data transfers.
Including the default control endpoint, a total of seven endpoints are provided. They can be configured
as isochronous, bulk or interrupt types, as described in Table 8-1 on page 81
After a hardware reset, the USBC device mode is in the reset state (see Section 8.6.1.1). In this
state, the endpoint banks are disabled and neither DP nor DM are pulled up (DETACH is one).
DP or DM will be pulled up according to the selected speed as soon as the DETACH bit is written
to zero. See “Device mode” for further details.
When the USBC is enabled (USBE is one) in device mode, it enters the Idle state, minimizing
power consumption. Being in Idle state does not require the USB clocks to be activated.
The USBC device mode can be disabled or reset at any time by disabling the USBC (by writing
a zero to USBE).
8.6.2.2 USB reset
The USB bus reset is initiated by a connected host and managed by hardware.
When a USB reset state is detected on the USB bus, the following operations are performed by
the controller:
• UDCON register is reset except for the DETACH and SPDCONF bits.
• Device Frame Number Register (UDFNUM), Endpoint n Configuration Register (UECFGn),
and Endpoint n Control Register (UECONn) registers are cleared.
• The data toggle sequencing in all the endpoints are cleared.
• At the end of the reset process, the End of Reset (EORST) bit in the UDINT register is set.
8.6.2.3 Endpoint activation
When an endpoint is disabled (UERST.EPENn = 0) the data toggle sequence, Endpoint n Status
Set (UESTAn), and UECONn registers will be reset. The controller ignores all transactions to
this endpoint as long as it is inactive.
To complete an endpoint activation, the user should fill out the endpoint descriptor: see Figure 8-
5 on page 91.
8.6.2.4 Data toggle sequence
In order to respond to a CLEAR_FEATURE USB request without disabling the endpoint, the
user can clear the data toggle sequence by writing a one to the Reset Data Toggle Set bit in the
Endpoint n Control Set register (UECONnSET.RSTDTS)
8.6.2.5 Busy bank enable
In order to make an endpoint bank look busy regardless of its actual state, the user can write a
one to the Busy Bank Enable bit in the Endpoint n Control Register (UECONnSET.BUSY0/1ES).
If a BUSYnE bit is set, any transaction to this bank will be rejected with a NAK reply.
8.6.2.6 Address setup
The USB device address is set up according to the USB protocol.
89
32142D–06/2013
ATUC64/128/256L3/4U
• After all kinds of resets, the USB device address is 0.
• The host starts a SETUP transaction with a SET_ADDRESS(addr) request.
• The user writes this address to the USB Address field (UDCON.UADD), and writes a zero to
the Address Enable bit (UDCON.ADDEN), resulting in the address remaining zero.
• The user sends a zero-length IN packet from the control endpoint.
• The user enables the stored USB device address by writing a one to ADDEN.
Once the USB device address is configured, the controller filters the packets to only accept
those targeting the address stored in UADD.
UADD and ADDEN should not be written to simultaneously. They should be written sequentially,
UADD field first.
If UADD or ADDEN is cleared, the default device address 0 is used. UADD and ADDEN are
cleared:
• On a hardware reset.
• When the USBC is disabled (USBE written to zero).
• When a USB reset is detected.
8.6.2.7 Suspend and Wakeup
When an idle USB bus state has been detected for 3 ms, the controller sets the Suspend
(SUSP) interrupt bit in UDINT. In this case, the transceiver is suspended, reducing power
consumption.
To further reduce power consumption it is recommended to freeze the USB clock by writing a
one to the Freeze USB Clock (FRZCLK) bit in USBCON when the USB bus is in suspend mode.
The MCU can also enter the idle or frozen sleep mode to further lower power consumption.
To recover from the suspend mode, the user shall wait for the Wakeup (WAKEUP) interrupt bit,
which is set when a non-idle event is detected, and then write a zero to FRZCLK.
As the WAKEUP interrupt bit in UDINT is set when a non-idle event is detected, it can occur
regardless of whether the controller is in the suspend mode or not. The SUSP and WAKEUP
interrupts are thus independent of each other except for that one bit is cleared when the other is
set.
8.6.2.8 Detach
The reset value of the DETACH bit located in the UDCON register, is one.
It is possible to initiate a device re-enumeration simply by writing a one and then a zero to
DETACH.
DETACH acts on the pull-up connections of the DP and DM pads. See “Device mode” for further
details.
8.6.2.9 Remote wakeup
The remote wakeup request (also known as upstream resume) is the only request the device
may send on its own initiative. This should be preceded by a DEVICE_REMOTE_WAKEUP
request from the host.
• First, the USBC must have detected a “Suspend” state on the bus, i.e. the remote wakeup
request can only be sent after a SUSP interrupt has been set.
90
32142D–06/2013
ATUC64/128/256L3/4U
• The user may then write a one to the remote wakeup (RMWKUP) bit in UDCON to send an
Upstream Resume to the host initiating the wakeup. This will automatically be done by the
controller after 5ms of inactivity on the USB bus.
• When the controller sends the Upstream Resume, the Upstream Resume (UPRSM) interrupt
is set and SUSP is cleared.
• RMWKUP is cleared at the end of the transmitting Upstream Resume.
• In case of a rebroadcast resume initiated by the host, the End of Resume (EORSM) interrupt
is set when the rebroadcast resume is completed.
8.6.2.10 RAM management
Endpoint data can be physically allocated anywhere in the embedded RAM. The USBC controller
accesses these endpoints directly through the HSB master (built-in DMA).
The USBC controller reads the USBC descriptors to know where each endpoint is located. The
base address of the USBC descriptor (UDESC.UDESCA) needs to be written by the user. The
descriptors can also be allocated anywhere in the embedded RAM.
Before using an endpoint, the user should setup the endpoint address for each bank. Depending
on the direction, the type, and the packet-mode (single or multi-packet), the user should also initialize
the endpoint packet size, and the endpoint control and status fields, so that the USBC
controller does not compute random values from the RAM.
When using an endpoint the user should read the UESTAX.CURRBK field to know which bank
is currently being processed.
91
32142D–06/2013
ATUC64/128/256L3/4U
Figure 8-5. Memory organization
Each descriptor of an endpoint n consists of four words.
• The address of the endpoint and the bank used (EPn_ADDR_BK0/1).
• The packet size information for the endpoint and bank (EPn_PCKSIZE_BK0/1):
Table 8-3. EPn_PCKSIZE_BK0/1 structure
– AUTO_ZLP: Auto zero length packet, see ”Multi packet mode for IN endpoints” on
page 96.
– MULTI_PACKET_SIZE: see ”Multi packet mode and single packet mode.” on page
93.
– BYTE_COUNT: see ”Multi packet mode and single packet mode.” on page 93.
31 30:16 15 14:0
AUTO_ZLP MULTI_PACKET_SIZE - BYTE_COUNT
EPn BK0
EP0_CTR_STA_BK0
E P 0 _ P C K S IZ E _ B K 0
EP0_ADDR_BK0 UDESCA
Growing Memory Addresses
Descriptor EP0
R e se rve d
EP0_CTR _STA_BK1
E P 0 _ P C K S IZ E _ B K 1
EP0_ADDR_BK1
R e se rve d
Bank0
Bank1
+0x000
+0x004
+0x008
+0x00C
+0x010
+0x014
+0x018
+0x01C
EP1_CTR_STA_BK0
E P 1 _ P C K S IZ E _ B K 0
EP1_ADDR_BK0
Descriptor EP1
R e se rve d
EP1_CTR _STA_BK1
E P 1 _ P C K S IZ E _ B K 1
EP1_ADDR_BK1
R e se rve d
Bank0
Bank1
+0x020
+0x024
+0x028
+0x02C
+0x030
+0x034
+0x038
+0x03C
EPn_CTR_STA_BK0
E P n _ P C K S IZ E _ B K 0
EPn_ADDR_BK0
R e se rve d
EPn_CTR _STA_BK1
E P n _ P C K S IZ E _ B K 1
EPn_ADDR_BK1
R e se rve d
Bank0
Bank1
Descriptor EPn
EPn BK1
U S B d e s c rip to rs
U S B B u ffe rs
92
32142D–06/2013
ATUC64/128/256L3/4U
• The control and status fields for the endpoint and bank (EPn_CTR_STA_BK0/1):
Table 8-4. EPn_CTR_STA_BK0/1 structure
– UNDERF: Underflow status for isochronous IN transfer. See ”Data flow error” on
page 99.
– OVERF: Overflow status for isochronous OUT transfer. See ”Data flow error” on
page 99.
– CRCERR: CRC error status for isochronous OUT transfer. See ”CRC error” on page
99.
– STALLRQ_NEXT: Stall request for the next transfer. See ”STALL request” on page
92.
8.6.2.11 STALL request
For each endpoint, the STALL management is performed using:
• The STALL Request (STALLRQ) bit in UECONn is set to initiate a STALL request.
• The STALLed Interrupt (STALLEDI) bit in UESTAn is set when a STALL handshake has been
sent.
To answer requests with a STALL handshake, STALLRQ has to be set by writing a one to the
STALL Request Set (STALLRQS) bit. All following requests will be discarded (RXOUTI, etc. will
not be set) and handshaked with a STALL until the STALLRQ bit is cleared, by receiving a new
SETUP packet (for control endpoints) or by writing a one to the STALL Request Clear (STALLRQC)
bit.
Each time a STALL handshake is sent, the STALLEDI bit is set by the USBC and the EPnINT
interrupt is set.
The user can use the descriptor to manage STALL requests. The USBC controller reads the
EPn_CTR_STA_BK0/1.STALLRQ_NEXT bit after successful transactions and if it is one the
USBC controller will set UECON.STALLRQ. The STALL_NEXT bit will be cleared upon receiving
a SETUP transaction and the USBC controller will then clear the STALLRQ bit.
• Special considerations for control endpoints
If a SETUP packet is received at a control endpoint where a STALL request is active, the
Received SETUP Interrupt (RXSTPI) bit in UESTAn is set, and the STALLRQ and STALLEDI
bits are cleared. It allows the SETUP to be always ACKed as required by the USB standard.
This management simplifies the enumeration process management. If a command is not supported
or contains an error, the user requests a STALL and can return to the main task, waiting
for the next SETUP request.
• STALL handshake and retry mechanism
The retry mechanism has priority over the STALL handshake. A STALL handshake is sent if the
STALLRQ bit is set and if there is no retry required.
31:19 18 17 16 15:1 0
Status elements Control elements
- UNDERF OVERF CRCERR - STALLRQ_NEXT
93
32142D–06/2013
ATUC64/128/256L3/4U
8.6.2.12 Multi packet mode and single packet mode.
Single packet mode is the default mode where one USB packet is managed per bank.
The multi-packet mode allows the user to manage data exceeding the maximum endpoint size
(UECFGn.EPSIZE) for an endpoint bank across multiple packets without software intervention.
This mode can also be coupled with the ping-pong mode.
• For an OUT endpoint, the EPn_PCKSIZE_BK0/1.MULTI_PACKET_SIZE field should be
configured correctly to enable the multi-packet mode. See ”Multi packet mode for OUT
endpoints” on page 98. For single packet mode, the MULTI_PACKET_SIZE should be
initialized to 0.
• For an IN endpoint, the EPn_PCKSIZE_BK0/1.BYTE_COUNT field should be configured
correctly to enable the multi-packet mode. See”Multi packet mode for IN endpoints” on page
96. For single packet mode, the BYTE_COUNT should be less than EPSIZE.
8.6.2.13 Management of control endpoints
• Overview
A SETUP request is always ACKed. When a new SETUP packet is received, the RXSTPI is set,
but not the Received OUT Data Interrupt (RXOUTI) bit.
The FIFO Control (FIFOCON) bit in UECONn is irrelevant for control endpoints. The user should
therefore never use it for these endpoints. When read, this value is always zero.
Control endpoints are managed using:
• The RXSTPI bit: is set when a new SETUP packet is received. This has to be cleared by
firmware in order to acknowledge the packet and to free the bank.
• The RXOUTI bit: is set when a new OUT packet is received. This has to be cleared by
firmware in order to acknowledge the packet and to free the bank.
• The Transmitted IN Data Interrupt (TXINI) bit: is set when the current bank is ready to accept
a new IN packet. This has to be cleared by firmware in order to send the packet.
• Control write
Figure 8-6 on page 94 shows a control write transaction. During the status stage, the controller
will not necessarily send a NAK on the first IN token:
• If the user knows the exact number of descriptor bytes that will be read, the status stage can
be predicted, and a zero-length packet can be sent after the next IN token.
• Alternatively the bytes can be read until the NAKed IN Interrupt (NAKINI) is triggered,
notifying that all bytes are sent by the host and that the transaction is now in the status stage.
94
32142D–06/2013
ATUC64/128/256L3/4U
Figure 8-6. Control Write
• Control read
Figure 8-7 on page 94 shows a control read transaction. The USBC has to manage the simultaneous
write requests from the CPU and USB host.
Figure 8-7. Control Read
A NAK handshake is always generated as the first status stage command. The UESTAn.NAKINI
bit is set. It allows the user to know that the host aborts the IN data stage. As a consequence,
the user should stop processing the IN data stage and should prepare to receive the OUT status
stage by checking the UESTAn.RXOUTI bit.
The OUT retry is always ACKed. This OUT reception sets RXOUTI. Handle this with the following
software algorithm:
// process the IN data stage
set TXINI
wait for RXOUTI (rising) OR TXINI (falling)
if RXOUTI is high, then process the OUT status stage
if TXINI is low, then return to process the IN data stage
Once the OUT status stage has been received, the USBC waits for a SETUP request. The
SETUP request has priority over all other requests and will be ACKed.
SETUP
RXSTPI
RXOUTI
TXINI
USB Bus
HW SW
OUT
HW SW
OUT
HW SW
IN IN
NAK
SW
SETUP STATUS DATA
SETUP
RXSTPI
RXOUTI
TXINI
USB Bus
HW SW
IN
HW SW
IN OUT OUT
NAK
SW
SW
HW
Wr Enable
HOST
Wr Enable
CPU
SETUP STATUS DATA
95
32142D–06/2013
ATUC64/128/256L3/4U
8.6.2.14 Management of IN endpoints
• Overview
IN packets are sent by the USBC device controller upon IN requests from the host.
The endpoint and its descriptor in RAM must be pre configured (see section ”RAM management”
on page 90 for more details).
When the current bank is clear, the TXINI and FIFO Control (UECONn.FIFOCON) bits will be set
simultaneously. This triggers an EPnINT interrupt if the Transmitted IN Data Interrupt Enable
(TXINE) bit in UECONn is one.
TXINI shall be cleared by software (by writing a one to the Transmitted IN Data Interrupt Enable
Clear bit in the Endpoint n Control Clear register (UECONnCLR.TXINIC)) to acknowledge the
interrupt. This has no effect on the endpoint FIFO.
The user writes the IN data to the bank referenced by the EPn descriptor and allows the USBC
to send the data by writing a one to the FIFO Control Clear (UECONnCLR.FIFOCONC) bit. This
will also cause a switch to the next bank if the IN endpoint is composed of multiple banks. The
TXINI and FIFOCON bits will be updated accordingly.
TXINI should always be cleared before clearing FIFOCON to avoid missing an TXINI event.
Figure 8-8. Example of an IN endpoint with one data bank
Figure 8-9. Example of an IN endpoint with two data banks
IN DATA
(bank 0) ACK
TXINI
FIFOCON
HW
write data to CPU
BANK 0
SW
SW SW
SW
IN
NAK
write data to CPU
BANK 0
IN DATA
(bank 0) ACK
TXINI
FIFOCON write data to CPU
BANK 0
SW
SW SW
SW
IN DATA
(bank 1) ACK
write data to CPU
BANK 1
SW
HW
write data to CPU
BANK0
96
32142D–06/2013
ATUC64/128/256L3/4U
• Detailed description
The data is written according to this sequence:
• When the bank is empty, TXINI and FIFOCON are set, which triggers an EPnINT interrupt if
TXINE is one.
• The user acknowledges the interrupt by clearing TXINI.
• The user reads the UESTAX.CURRBK field to see which the current bank is.
• The user writes the data to the current bank, located in RAM as described by its descriptor:
EPn_ADDR_BK0/1.
• The user should write the size of the IN packet into the USB descriptor:
EPn_PCKSIZE_BK0/1.BYTE_COUNT.
• The user allows the controller to send the bank contents and switches to the next bank (if
any) by clearing FIFOCON.
If the endpoint uses several banks, the current one can be written while the previous one is
being read by the host. When the user clears FIFOCON, the next current bank may already be
clear and TXINI is set immediately.
An “Abort” stage can be produced when a zero-length OUT packet is received during an IN
stage of a control or isochronous IN transaction. The Kill IN Bank (KILLBK) bit in UECONn is
used to kill the last written bank. The best way to manage this abort is to apply the algorithm represented
on Figure 8-10 on page 96. See ”Endpoint n Control Register” on page 130 for more
details about the KILLBK bit.
Figure 8-10. Abort Algorithm
• Multi packet mode for IN endpoints
In multi packet mode, the user can prepare n USB packets in the bank to be sent on a multiple
IN transaction. The packet sizes will equal UECFGn.EPSIZE unless the AUTO_ZLP option is
Endpoint
Abort
Abort Done
Abort is based on the fact
that no bank is busy, i.e.,
that nothing has to be sent
Disable the TXINI interrupt.
EPRSTn = 1
NBUSYBK
== 0?
Yes
TXINEC = 1
No
KILLBKS = 1
KILLBK
Yes == 1?
Kill the last written bank.
Wait for the end of the
procedure
No
97
32142D–06/2013
ATUC64/128/256L3/4U
set, or if the total byte count is not an integral multiple of EPSIZE, whereby the last packet
should be short.
To enable the multi packet mode, the user should configure the endpoint descriptor
(EPn_PCKSIZE_BK0/1.BYTE_COUNT) to the total size of the multi packet, which should be
larger than the endpoint size (EPSIZE).
Since the EPn_PCKSIZE_BK0/1.MULTI_PACKET_SIZE is incremented (by the transmitted
packet size) after each successful transaction, it should be set to zero when setting up a new
multi packet transfer.
The EPn_PCKSIZE_BK0/1.MULTI_PACKET_SIZE is cleared by hardware when all the bank
contents have been sent. The bank is considered as ready and the TX_IN flag is set when:
• A short packet (smaller than EPSIZE) has been transmitted.
• A packet has been successfully transmitted, the updated MULTI_PACKET_SIZE equals the
BYTE_COUNT, and the AUTO_ZLP field is not set.
• An extra zero length packet has been automatically sent for the last transfer of the current
bank, if BYTE_COUNT is a multiple of EPSIZE and AUTO_ZLP is set.
8.6.2.15 Management of OUT endpoints
• Overview
The endpoint and its descriptor in RAM must be pre configured, see section ”RAM management”
on page 90 for more details.
When the current bank is full, the RXOUTI and FIFO Control (UECONn.FIFOCON) bits will be
set simultaneously. This triggers an EPnINT interrupt if the Received OUT Data Interrupt Enable
(RXOUTE) bit in UECONn is one.
RXOUTI shall be cleared by software (by writing a one to the Received OUT Data Interrupt Clear
(RXOUTIC) bit) to acknowledge the interrupt. This has no effect on the endpoint FIFO.
The user reads the OUT data from the RAM and clears the FIFOCON bit to free the bank. This
will also cause a switch to the next bank if the OUT endpoint is composed of multiple banks.
RXOUTI should always be cleared before clearing FIFOCON to avoid missing an RXOUTI
event.
Figure 8-11. Example of an OUT endpoint with one data bank
OUT DATA
(bank 0) ACK
RXOUTI
FIFOCON
HW
OUT DATA
(bank 0) ACK
HW
SW
SW
SW
read data from CPU
BANK 0
read data from CPU
BANK 0
NAK
98
32142D–06/2013
ATUC64/128/256L3/4U
Figure 8-12. Example of an OUT endpoint with two data banks
• Detailed description
Before using the OUT endpoint, one should properly initialize its descriptor for each bank. See
Figure 8-5 on page 91.
The data is read, according to this sequence:
• When the bank is full, RXOUTI and FIFOCON are set, which triggers an EPnINT interrupt if
RXOUTE is one.
• The user acknowledges the interrupt by writing a one to RXOUTIC in order to clear RXOUTI.
• The user reads the UESTAX.CURRBK field to know the current bank number.
• The user reads the byte count of the current bank from the descriptor in RAM
(EPn_PCKSIZE_BK0/1.BYTE_COUNT) to know how many bytes to read.
• The user reads the data in the current bank, located in RAM as described by its descriptor:
EPn_ADDR_BK0/1.
• The user frees the bank and switches to the next bank (if any) by clearing FIFOCON.
If the endpoint uses several banks, the current one can be read while the next is being written by
the host. When the user clears FIFOCON, the following bank may already be ready and RXOUTI
will be immediately set.
• Multi packet mode for OUT endpoints
In multi packet mode, the user can extend the size of the bank allowing the storage of n USB
packets in the bank.
To enable the multi packet mode, the user should configure the endpoint descriptor
(EPn_PCKSIZE_BK0/1.MULTI_PACKET_SIZE) to match the size of the multi packet.This value
should be a multiple of the endpoint size (UECFGn.EPSIZE).
Since the EPn_PCKSIZE_BK0/1.BYTE_COUNT is incremented (by the received packet size)
after each successful transaction, it should be set to zero when setting up a new multi packet
transfer.
As for single packet mode, the number of received data bytes is stored in the BYTE_CNT field.
The bank is considered as “valid” and the RX_OUT flag is set when:
OUT DATA
(bank 0)
ACK
RXOUTI
FIFOCON
HW
OUT DATA
(bank 1) ACK
SW
read data from CPU SW
BANK 0
HW
SW
read data from CPU
BANK 1
99
32142D–06/2013
ATUC64/128/256L3/4U
• A packet has been successfully received and the updated BYTE_COUNT equals the
MULTI_PACKET_SIZE.
• A short packet (smaller than EPSIZE) has been received.
8.6.2.16 Data flow error
This error exists only for isochronous IN/OUT endpoints. It sets the Errorflow Interrupt
(ERRORFI) bit in UESTAn, which triggers an EPnINT interrupt if the Errorflow Interrupt Enable
(ERRORFE) bit is one. The user can check the EPn_CTR_STA_BK0/1.UNDERF and OVERF
bits in the endpoint descriptor to see which current bank has been affected.
• An underflow can occur during IN stage if the host attempts to read from an empty bank. A
zero-length packet is then automatically sent by the USBC. The endpoint descriptor
EPn_CTR_STA_BK0/1.UNDERF points out the bank from which the IN data should have
originated. If a new successful transaction occurs, the UNDERF bit is overwritten to 0 only if
the UESTAn.ERRORFI is cleared.
• An overflow can occur during the OUT stage if the host tries to send a packet while the bank
is full. Typically this occurs when a CPU is not fast enough. The packet data is not written to
the bank and is lost. The endpoint descriptor EPn_CTR_STA_BK0/1.OVERF points out
which bank the OUT data was destined to. If the UESTAn.ERRORFI bit is cleared and a new
transaction is successful, the OVERF bit will be overwritten to zero.
8.6.2.17 CRC error
This error exists only for isochronous OUT endpoints. It sets the CRC Error Interrupt (CRCERRI)
bit in UESTAn, which triggers an EPnINT interrupt if the CRC Error Interrupt Enable
(CRCERRE) bit is one.
A CRC error can occur during an isochronous OUT stage if the USBC detects a corrupted
received packet. The OUT packet is stored in the bank as if no CRC error had occurred
(RXOUTI is set).
The user can also check the endpoint descriptor to see which current bank is impacted by the
CRC error by reading EPn_CTR_STA_BK0/1.CRCERR.
8.6.2.18 Interrupts
There are two kinds of device interrupts: processing, i.e. their generation is part of the normal
processing, and exception, i.e. errors not related to CPU exceptions.
• Global interrupts
The processing device global interrupts are:
• The Suspend (SUSP) interrupt
• The Start of Frame (SOF) interrupt with no frame number CRC error (the Frame Number
CRC Error (FNCERR) bit in the Device Frame Number (UDFNUM) register is zero)
• The End of Reset (EORST) interrupt
• The Wakeup (WAKEUP) interrupt
• The End of Resume (EORSM) interrupt
• The Upstream Resume (UPRSM) interrupt
• The Endpoint n (EPnINT) interrupt
The exception device global interrupts are:
100
32142D–06/2013
ATUC64/128/256L3/4U
• The Start of Frame (SOF) interrupt with a frame number CRC error (FNCERR is one)
• Endpoint interrupts
The processing device endpoint interrupts are:
• The Transmitted IN Data Interrupt (TXINI)
• The Received OUT Data Interrupt (RXOUTI)
• The Received SETUP Interrupt (RXSTPI)
• The Number of Busy Banks (NBUSYBK) interrupt
The exception device endpoint interrupts are:
• The Errorflow Interrupt (ERRORFI)
• The NAKed OUT Interrupt (NAKOUTI)
• The NAKed IN Interrupt (NAKINI)
• The STALLed Interrupt (STALLEDI)
• The CRC Error Interrupt (CRCERRI)
101
32142D–06/2013
ATUC64/128/256L3/4U
8.7 User Interface
Note: 1. The reset values are device specific. Please refer to the Module Configuration section at the end of this chapter.
Table 8-5. USBC Register Memory Map
Offset Register Name Access Reset Value
0x0000 Device General Control Register UDCON Read/Write 0x00000100
0x0004 Device Global Interrupt Register UDINT Read-Only 0x00000000
0x0008 Device Global Interrupt Clear Register UDINTCLR Write-Only 0x00000000
0x000C Device Global Interrupt Set Register UDINTSET Write-Only 0x00000000
0x0010 Device Global Interrupt Enable Register UDINTE Read-Only 0x00000000
0x0014 Device Global Interrupt Enable Clear Register UDINTECLR Write-Only 0x00000000
0x0018 Device Global Interrupt Enable Set Register UDINTESET Write-Only 0x00000000
0x001C Endpoint Enable/Reset Register UERST Read/Write 0x00000000
0x0020 Device Frame Number Register UDFNUM Read-Only 0x00000000
0x0100 + n*4 Endpoint n Configuration Register UECFGn Read/Write 0x00000000
0x0130 + n*4 Endpoint n Status Register UESTAn Read-Only 0x00000100
0x0160 + n*4 Endpoint n Status Clear Register UESTAnCLR Write-Only 0x00000000
0x0190 + n*4 Endpoint n Status Set Register UESTAnSET Write-Only 0x00000000
0x01C0 + n*4 Endpoint n Control Register UECONn Read-Only 0x00000000
0x01F0 + n*4 Endpoint n Control Set Register UECONnSET Write-Only 0x00000000
0x0220 + n*4 Endpoint n Control Clear Register UECONnCLR Write-Only 0x00000000
0x0800 General Control Register USBCON Read/Write 0x00004000
0x0804 General Status Register USBSTA Read-Only 0x00000000
0x0808 General Status Clear Register USBSTACLR Write-Only 0x00000000
0x080C General Status Set Register USBSTASET Write-Only 0x00000000
0x0818 IP Version Register UVERS Read-Only -(1)
0x081C IP Features Register UFEATURES Read-Only -(1)
0x0820 IP PB Address Size Register UADDRSIZE Read-Only -(1)
0x0824 IP Name Register 1 UNAME1 Read-Only -(1)
0x0828 IP Name Register 2 UNAME2 Read-Only -(1)
0x082C USB Finite State Machine Status Register USBFSM Read-Only 0x00000009
0x0830 USB Descriptor address UDESC Read/Write 0x00000000
102
32142D–06/2013
ATUC64/128/256L3/4U
8.7.1 USB General Registers
8.7.1.1 General Control Register
Name: USBCON
Access Type: Read/Write
Offset: 0x0800
Reset Value: 0x00004000
• USBE: USBC Enable
Writing a zero to this bit will disable the USBC, USB transceiver, and USB clock inputs. This will over-ride FRZCLK settings but
not affect the value. Unless explicitly stated, all registers will become reset and read-only.
Writing a one to this bit will enable the USBC.
0: The USBC is disabled.
1: The USBC is enabled.
This bit can be written to even if FRZCLK is one.
• FRZCLK: Freeze USB Clock
Writing a zero to this bit will enable USB clock inputs.
Writing a one to this bit will disable USB clock inputs. The resume detection will remain active. Unless explicitly stated, all
registers will become read-only.
0: The clock inputs are enabled.
1: The clock inputs are disabled.
This bit can be written to even if USBE is zero.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
-- - -- -
15 14 13 12 11 10 9 8
USBE FRZCLK - - - - - -
76543210
--------
103
32142D–06/2013
ATUC64/128/256L3/4U
8.7.1.2 General Status Register
Register Name: USBSTA
Access Type: Read-Only
Offset: 0x0804
Reset Value: 0x00000000
• CLKUSABLE: Generic Clock Usable
This bit is cleared when the USB generic clock is not usable.
This bit is set when the USB generic clock (that should be 48 Mhz) is usable.
• SPEED: Speed Status
This field is set according to the controller speed mode.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
- CLKUSABLE SPEED - - - -
76543210
--------
SPEED Speed Status
00 full-speed mode
01 Reserved
10 low-speed mode
11 Reserved
104
32142D–06/2013
ATUC64/128/256L3/4U
8.7.1.3 General Status Clear Register
Register Name: USBSTACLR
Access Type: Write-Only
Offset: 0x0808
Reset Value: 0x00000000
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will clear the corresponding bit in USBSTA.
These bits always read as zero.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
--------
105
32142D–06/2013
ATUC64/128/256L3/4U
8.7.1.4 General Status Set Register
Register Name: USBSTASET
Access Type: Write-Only
Offset: 0x080C
Reset Value: 0x00000000
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will set the corresponding bit in USBSTA.
These bits always read as zero.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
--------
106
32142D–06/2013
ATUC64/128/256L3/4U
8.7.1.5 Version Register
Register Name: UVERS
Access Type: Read-Only
Offset: 0x0818
Reset Value: -
• VARIANT: Variant Number
Reserved. No functionality associated.
• VERSION: Version Number
Version number of the module. No functionality associated.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
- - - - VARIANT
15 14 13 12 11 10 9 8
- - - - VERSION[11:8]
76543210
VERSION[7:0]
107
32142D–06/2013
ATUC64/128/256L3/4U
8.7.1.6 Features Register
Register Name: UFEATURES
Access Type: Read-Only
Offset: 0x081C
Reset Value: -
• EPTNBRMAX: Maximal Number of pipes/endpoints
This field indicates the number of hardware-implemented pipes/endpoints:
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
- - - - EPTNBRMAX
108
32142D–06/2013
ATUC64/128/256L3/4U
8.7.1.7 Address Size Register
Register Name: UADDRSIZE
Access Type: Read-Only
Offset: 0x0820
Reset Value: -
• UADDRSIZE: IP PB Address Size
This field indicates the size of the PB address space reserved for the USBC IP interface.
31 30 29 28 27 26 25 24
UADDRSIZE[31:24]
23 22 21 20 19 18 17 16
UADDRSIZE[23:16]
15 14 13 12 11 10 9 8
UADDRSIZE[15:8]
76543210
UADDRSIZE[7:0]
109
32142D–06/2013
ATUC64/128/256L3/4U
8.7.1.8 IP Name Register 1
Register Name: UNAME1
Access Type: Read-Only
Offset: 0x0824
Reset Value: -
• UNAME1: IP Name Part One
This field indicates the first part of the ASCII-encoded name of the USBC IP.
31 30 29 28 27 26 25 24
UNAME1[31:24]
23 22 21 20 19 18 17 16
UNAME1[23:16]
15 14 13 12 11 10 9 8
UNAME1[15:8]
76543210
UNAME1[7:0]
110
32142D–06/2013
ATUC64/128/256L3/4U
8.7.1.9 IP Name Register 2
Register Name: UNAME2
Access Type: Read-Only
Offset: 0x0828
Reset Value:
• UNAME2: IP Name Part Two
This field indicates the second part of the ASCII-encoded name of the USBC IP.
31 30 29 28 27 26 25 24
UNAME2[31:24]
23 22 21 20 19 18 17 16
UNAME2[23:16]
15 14 13 12 11 10 9 8
UNAME2[15:8]
76543210
UNAME2[7:0]
111
32142D–06/2013
ATUC64/128/256L3/4U
8.7.1.10 Finite State Machine Status Register
Register Name: USBFSM
Access Type: Read-Only
Offset: 0x082C
Reset Value: 0x00000009
• DRDSTATE: Dual Role Device State
This field indicates the state of the USBC.
For Device mode it should always read 9.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
- - - - DRDSTATE
112
32142D–06/2013
ATUC64/128/256L3/4U
8.7.1.11 USB Descriptor Address
Register Name: UDESC
Access Type: Read-Write
Offset: 0x0830
Reset Value: -
• UDESCA: USB Descriptor Address
This field contains the address of the USB descriptor. The three least significant bits are always zero.
31 30 29 28 27 26 25 24
UDESCA[31:24]
23 22 21 20 19 18 17 16
UDESCA[23:16]
15 14 13 12 11 10 9 8
UDESCA[15:8]
76543210
UDESCA[7:0]
113
32142D–06/2013
ATUC64/128/256L3/4U
8.7.2 USB Device Registers
8.7.2.1 Device General Control Register
Register Name: UDCON
Access Type: Read/Write
Offset: 0x0000
Reset Value: 0x00000100
• GNAK: Global NAK
0: Normal mode.
1: A NAK handshake is answered for each USB transaction regardless of the current endpoint memory bank status.
• LS: low-speed mode force
0: The full-speed mode is active.
1: The low-speed mode is active.
This bit can be written to even if USBE is zero or FRZCLK is one. Disabling the USBC (by writing a zero to the USBE bit) does
not reset this bit.
• RMWKUP: Remote wakeup
Writing a zero to this bit has no effect.
Writing a one to this bit will send an upstream resume to the host for a remote wakeup.
This bit is cleared when the USBC receives a USB reset or once the upstream resume has been sent.
• DETACH: Detach
Writing a zero to this bit will reconnect the device.
Writing a one to this bit will physically detach the device (disconnect internal pull-up resistor from DP and DM).
• ADDEN: Address Enable
Writing a zero to this bit has no effect.
Writing a one to this bit will activate the UADD field (USB address).
This bit is cleared when a USB reset is received.
• UADD: USB Address
This field contains the device address.
This field is cleared when a USB reset is received.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
- - - - - - GNAK -
15 14 13 12 11 10 9 8
- - - LS - - RMWKUP DETACH
76543210
ADDEN UADD
114
32142D–06/2013
ATUC64/128/256L3/4U
8.7.2.2 Device Global Interrupt Register
Register Name: UDINT
Access Type: Read-Only
Offset: 0x0004
Reset Value: 0x00000000
Note: 1. EPnINT bits are within the range from EP0INT to EP6INT.
• EPnINT: Endpoint n Interrupt
This bit is cleared when the interrupt source is serviced.
This bit is set when an interrupt is triggered by the endpoint n (UESTAn, UECONn). This triggers a USB interrupt if EPnINTE is
one.
• UPRSM: Upstream Resume Interrupt
This bit is cleared when the UDINTCLR.UPRSMC bit is written to one to acknowledge the interrupt (USB clock inputs must be
enabled before).
This bit is set when the USBC sends a resume signal called “Upstream Resume”. This triggers a USB interrupt if UPRSME is
one.
• EORSM: End of Resume Interrupt
This bit is cleared when the UDINTCLR.EORSMC bit is written to one to acknowledge the interrupt.
This bit is set when the USBC detects a valid “End of Resume” signal initiated by the host. This triggers a USB interrupt if
EORSME is one.
• WAKEUP: Wakeup Interrupt
This bit is cleared when the UDINTCLR.WAKEUPC bit is written to one to acknowledge the interrupt (USB clock inputs must be
enabled before) or when the Suspend (SUSP) interrupt bit is set.
This bit is set when the USBC is reactivated by a filtered non-idle signal from the lines (not by an upstream resume). This
triggers an interrupt if WAKEUPE is one.
This interrupt is generated even if the clock is frozen by the FRZCLK bit.
• EORST: End of Reset Interrupt
This bit is cleared when the UDINTCLR.EORSTC bit is written to one to acknowledge the interrupt.
This bit is set when a USB “End of Reset” has been detected. This triggers a USB interrupt if EORSTE is one.
• SOF: Start of Frame Interrupt
This bit is cleared when the UDINTCLR.SOFC bit is written to one to acknowledge the interrupt.
This bit is set when a USB “Start of Frame” PID (SOF) has been detected (every 1 ms). This triggers a USB interrupt if SOFE is
one. The FNUM field is updated.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
- - - EP8INT(1) EP7INT(1) EP6INT(1) EP5INT(1) EP4INT(1)
15 14 13 12 11 10 9 8
EP3INT(1) EP2INT(1) EP1INT(1) EP0INT - - - -
76543210
- UPRSM EORSM WAKEUP EORST SOF - SUSP
115
32142D–06/2013
ATUC64/128/256L3/4U
• SUSP: Suspend Interrupt
This bit is cleared when the UDINTCLR.SUSPC bit is written to one to acknowledge the interrupt or when the Wakeup
(WAKEUP) interrupt bit is set.
This bit is set when a USB “Suspend” idle bus state has been detected for 3 frame periods (J state for 3 ms). This triggers a
USB interrupt if SUSPE is one.
116
32142D–06/2013
ATUC64/128/256L3/4U
8.7.2.3 Device Global Interrupt Clear Register
Register Name: UDINTCLR
Access Type: Write-Only
Offset: 0x0008
Reset Value: 0x00000000
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will clear the corresponding bit in UDINT.
These bits always read as zero.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
- UPRSMC EORSMC WAKEUPC EORSTC SOFC - SUSPC
117
32142D–06/2013
ATUC64/128/256L3/4U
8.7.2.4 Device Global Interrupt Set Register
Register Name: UDINTSET
Access Type: Write-Only
Offset: 0x000C
Reset Value: 0x00000000
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will set the corresponding bit in UDINT, which may be useful for test or debug purposes.
These bits always read as zero.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
- UPRSMS EORSMS WAKEUPS EORSTS SOFS - SUSPS
118
32142D–06/2013
ATUC64/128/256L3/4U
8.7.2.5 Device Global Interrupt Enable Register
Register Name: UDINTE
Access Type: Read-Only
Offset: 0x0010
Reset Value: 0x00000000
Note: 1. EPnINTE bits are within the range from EP0INTE to EP6INTE.
0: The corresponding interrupt is disabled.
1: The corresponding interrupt is enabled.
A bit in this register is cleared when the corresponding bit in UDINTECLR is written to one.
A bit in this register is set when the corresponding bit in UDINTESET is written to one.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
- - - EP8INTE(1) EP7INTE(1) EP6INTE(1) EP5INTE(1) EP4INTE(1)
15 14 13 12 11 10 9 8
EP3INTE(1) EP2INTE(1) EP1INTE(1) EP0INTE - - - -
76543210
- UPRSME EORSME WAKEUPE EORSTE SOFE - SUSPE
119
32142D–06/2013
ATUC64/128/256L3/4U
8.7.2.6 Device Global Interrupt Enable Clear Register
Register Name: UDINTECLR
Access Type: Write-Only
Offset: 0x0014
Reset Value: 0x00000000
Note: 1. EPnINTEC bits are within the range from EP0INTEC to EP6INTEC.
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will clear the corresponding bit in UDINTE.
These bits always read as zero.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
- - - EP8INTEC(1) EP7INTEC(1) EP6INTEC(1) EP5INTEC(1) EP4INTEC(1)
15 14 13 12 11 10 9 8
EP3INTEC(1) EP2INTEC(1) EP1INTEC(1) EP0INTEC - - - -
76543210
- UPRSMEC EORSMEC WAKEUPEC EORSTEC SOFEC - SUSPEC
120
32142D–06/2013
ATUC64/128/256L3/4U
8.7.2.7 Device Global Interrupt Enable Set Register
Register Name: UDINTESET
Access Type: Write-Only
Offset: 0x0018
Reset Value: 0x00000000
Note: 1. EPnINTES bits are within the range from EP0INTES to EP6INTES.
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will set the corresponding bit in UDINTE.
These bits always read as zero.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
- - - EP8INTES(1) EP7INTES(1) EP6INTES(1) EP5INTES(1) EP4INTES(1)
15 14 13 12 11 10 9 8
EP3INTES(1) EP2INTES(1) EP1INTES(1) EP0INTES - - - -
76543210
- UPRSMES EORSMES WAKEUPES EORSTES SOFES - SUSPES
121
32142D–06/2013
ATUC64/128/256L3/4U
8.7.2.8 Endpoint Enable/Reset Register
Register Name: UERST
Access Type: Read/Write
Offset: 0x001C
Reset Value: 0x00000000
• EPENn: Endpoint n Enable
Note: 1. EPENn bits are within the range from EPEN0 to EPEN6.
Writing a zero to this bit will disable the endpoint n (USB requests will be ignored), and resets the endpoints registers (UECFGn,
UESTAn, UECONn), but not the endpoint configuration (EPBK, EPSIZE, EPDIR, EPTYPE).
Writing a one to this bit will enable the endpoint n.
0: The endpoint n is disabled.
1: The endpoint n is enabled.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
- - - - - - - EPEN8(1)
76543210
EPEN7(1) EPEN6(1) EPEN5(1) EPEN4(1) EPEN3(1) EPEN2(1) EPEN1(1) EPEN0
122
32142D–06/2013
ATUC64/128/256L3/4U
8.7.2.9 Device Frame Number Register
Register Name: UDFNUM
Access Type: Read-Only
Offset: 0x0020
Reset Value: 0x00000000
• FNCERR: Frame Number CRC Error
This bit is cleared upon receiving a USB reset.
This bit is set when a corrupted frame number is received. This bit and the SOF interrupt bit are updated at the same time.
• FNUM: Frame Number
This field is cleared upon receiving a USB reset.
This field contains the 11-bit frame number information, as provided from the last SOF packet.
FNUM is updated even if a corrupted SOF is received.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
FNCERR - FNUM[10:5]
76543210
FNUM[4:0] - - -
123
32142D–06/2013
ATUC64/128/256L3/4U
8.7.2.10 Endpoint n Configuration Register
Register Name: UECFGn, n in [0..6]
Access Type: Read/Write
Offset: 0x0100 + (n * 0x04)
Reset Value: 0x00000000
• EPTYPE: Endpoint Type
This field selects the endpoint type:
This field is cleared upon receiving a USB reset.
• EPDIR: Endpoint Direction
0: The endpoint direction is OUT.
1: The endpoint direction is IN (nor for control endpoints).
This bit is cleared upon receiving a USB reset.
• EPSIZE: Endpoint Size
This field determines the size of each endpoint bank:
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
- - - EPTYPE - - EPDIR
76543210
- EPSIZE - EPBK - -
EPTYPE Endpoint Type
0 0 Control
0 1 Isochronous
1 0 Bulk
1 1 Interrupt
EPSIZE Endpoint Size
0 0 0 8 bytes
0 0 1 16 bytes
0 1 0 32 bytes
0 1 1 64 bytes
1 0 0 128 bytes
124
32142D–06/2013
ATUC64/128/256L3/4U
This field is cleared upon receiving a USB reset (except for the endpoint 0).
• EPBK: Endpoint Banks
This bit selects the number of banks for the endpoint:
0: single-bank endpoint
1: double-bank endpoint
For control endpoints, a single-bank endpoint shall be selected.
This field is cleared upon receiving a USB reset (except for the endpoint 0).
1 0 1 256 bytes
1 1 0 512 bytes
1 1 1 1024 bytes
EPSIZE Endpoint Size
125
32142D–06/2013
ATUC64/128/256L3/4U
8.7.2.11 Endpoint n Status Register
Register Name: UESTAn, n in [0..6]
Access Type: Read-Only 0x0100
Offset: 0x0130 + (n * 0x04)
Reset Value: 0x00000000
• CTRLDIR: Control Direction
Writing a zero or a one to this bit has no effect.
This bit is cleared after a SETUP packet to indicate that the following packet is an OUT packet.
This bit is set after a SETUP packet to indicate that the following packet is an IN packet.
• CURRBK: Current Bank
This bit is set for non-control endpoints, indicating the current bank:
This field may be updated one clock cycle after the RWALL bit changes, so the user should not poll this field as an interrupt bit.
• NBUSYBK: Number of Busy Banks
This field is set to indicate the number of busy banks:
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
- - - - - - CTRLDIR -
15 14 13 12 11 10 9 8
CURRBK NBUSYBK RAMACERI - DTSEQ
76543210
- STALLEDI/
CRCERRI - NAKINI NAKOUTI RXSTPI/
ERRORFI RXOUTI TXINI
CURRBK Current Bank
0 0 Bank0
0 1 Bank1
1 0 Reserved
1 1 Reserved
NBUSYBK Number of Busy Banks
0 0 0 (all banks free)
0 11
1 02
1 1 Reserved
126
32142D–06/2013
ATUC64/128/256L3/4U
For IN endpoints, this indicates the number of banks filled by the user and ready for IN transfers. When all banks are free an
EPnINT interrupt will be triggered if NBUSYBKE is one.
For OUT endpoints, this indicates the number of banks filled by OUT transactions from the host. When all banks are busy an
EPnINT interrupt will be triggered if NBUSYBKE is one.
• RAMACERI: Ram Access Error Interrupt
This bit is cleared when the RAMACERIC bit is written to one, acknowledging the interrupt.
This bit is set when a RAM access underflow error occurs during an IN data stage.
• DTSEQ: Data Toggle Sequence
This field is set to indicate the PID of the current bank:
For IN transfers, this indicates the data toggle sequence that will be used for the next packet to be sent.
For OUT transfers, this value indicates the data toggle sequence of the data received in the current bank.
• STALLEDI: STALLed Interrupt
This bit is cleared when the STALLEDIC bit is written to one, acknowledging the interrupt.
This bit is set when a STALL handshake has been sent and triggers an EPnINT interrupt if STALLEDE is one.
• CRCERRI: CRC Error Interrupt
This bit is cleared when the CRCERRIC bit is written to one, acknowledging the interrupt.
This bit is set when a CRC error has been detected in an isochronous OUT endpoint bank, and triggers an EPnINT interrupt if
CRCERRE is one.
• NAKINI: NAKed IN Interrupt
This bit is cleared when the NAKINIC bit is written to one, acknowledging the interrupt.
This bit is set when a NAK handshake has been sent in response to an IN request from the host, and triggers an EPnINT
interrupt if NAKINE is one.
• NAKOUTI: NAKed OUT Interrupt
This bit is cleared when the NAKOUTIC bit is written to one, acknowledging the interrupt.
This bit is set when a NAK handshake has been sent in response to an OUT request from the host, and triggers an EPnINT
interrupt if NAKOUTE is one.
• ERRORFI: Isochronous Error flow Interrupt
This bit is cleared when the ERRORFIC bit is written to one, acknowledging the interrupt.
This bit is set, for isochronous IN/OUT endpoints, when an errorflow (underflow or overflow) error occurs, and triggers an
EPnINT interrupt if ERRORFE is one.
An underflow can occur during IN stage if the host attempts to read from an empty bank. A zero-length packet is then
automatically sent by the USBC.
An overflow can also occur during OUT stage if the host sends a packet while the bank is already full, resulting in the packet
being lost. This is typically due to a CPU not being fast enough.
This bit is inactive (cleared) for bulk and interrupt IN/OUT endpoints and it means RXSTPI for control endpoints.
• RXSTPI: Received SETUP Interrupt
This bit is cleared when the RXSTPIC bit is written to one, acknowledging the interrupt and freeing the bank.
This bit is set, for control endpoints, to signal that the current bank contains a new valid SETUP packet, and triggers an EPnINT
interrupt if RXSTPE is one.
This bit is inactive (cleared) for bulk and interrupt IN/OUT endpoints and it means UNDERFI for isochronous IN/OUT endpoints.
• RXOUTI: Received OUT Data Interrupt
This bit is cleared when the RXOUTIC bit is written to one, acknowledging the interrupt. For control endpoints, it releases the
bank. For other endpoint types, the user should clear the FIFOCON bit to free the bank. RXOUTI shall always be cleared before
clearing FIFOCON to avoid missing an interrupt.
DTSEQ Data Toggle Sequence
0 0 Data0
0 1 Data1
1 X Reserved
127
32142D–06/2013
ATUC64/128/256L3/4U
This bit is set, for control endpoints, when the current bank contains a bulk OUT packet (data or status stage). This triggers an
EPnINT interrupt if RXOUTE is one.
This bit is set for isochronous, bulk and, interrupt OUT endpoints, at the same time as FIFOCON when the current bank is full.
This triggers an EPnINT interrupt if RXOUTE is one.
This bit is inactive (cleared) for isochronous, bulk and interrupt IN endpoints.
• TXINI: Transmitted IN Data Interrupt
This bit is cleared when the TXINIC bit is written to one, acknowledging the interrupt. For control endpoints, this will send the
packet. For other endpoint types, the user should clear the FIFOCON to allow the USBC to send the data. TXINI shall always be
cleared before clearing FIFOCON to avoid missing an interrupt.
This bit is set for control endpoints, when the current bank is ready to accept a new IN packet. This triggers an EPnINT interrupt
if TXINE is one.
This bit is set for isochronous, bulk and interrupt IN endpoints, at the same time as FIFOCON when the current bank is free.
This triggers an EPnINT interrupt if TXINE is one.
This bit is inactive (cleared) for isochronous, bulk and interrupt OUT endpoints.
128
32142D–06/2013
ATUC64/128/256L3/4U
8.7.2.12 Endpoint n Status Clear Register
Register Name: UESTAnCLR, n in [0..6]
Access Type: Write-Only
Offset: 0x0160 + (n * 0x04)
Reset Value: 0x00000000
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will clear the corresponding bit in UESTA.
These bits always read as zero.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
- - - - RAMACERIC - - -
76543210
- STALLEDIC/
CRCERRIC - NAKINIC NAKOUTIC RXSTPIC/
ERRORFIC RXOUTIC TXINIC
129
32142D–06/2013
ATUC64/128/256L3/4U
8.7.2.13 Endpoint n Status Set Register
Register Name: UESTAnSET, n in [0..6]
Access Type: Write-Only
Offset: 0x0190 + (n * 0x04)
Reset Value: 0x00000000
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will set the corresponding bit in UESTA.
These bits always read as zero.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
- - - NBUSYBKS RAMACERIS - -
76543210
- STALLEDIS/
CRCERRIS - NAKINIS NAKOUTIS RXSTPIS/
ERRORFIS RXOUTIS TXINIS
130
32142D–06/2013
ATUC64/128/256L3/4U
8.7.2.14 Endpoint n Control Register
Register Name: UECONn, n in [0..6]
Access Type: Read-Only
Offset: 0x01C0 + (n * 0x04)
Reset Value: 0x00000000
• BUSY0E: Busy Bank0 Enable
This bit is cleared when the BUSY0C bit is written to one.
This bit is set when the BUSY0ES bit is written to one. This will set the bank 0 as “busy”. All transactions, except SETUP,
destined to this bank will be rejected (i.e: NAK token will be answered).
• BUSY1E: Busy Bank1 Enable
This bit is cleared when the BUSY1C bit is written to one.
This bit is set when the BUSY1ES bit is written to one. This will set the bank 1 as “busy”. All transactions, except SETUP,
destined to this bank will be rejected (i.e: NAK token will be answered).
• STALLRQ: STALL Request
This bit is cleared when a new SETUP packet is received or when the STALLRQC bit is written to zero.
This bit is set when the STALLRQS bit is written to one, requesting a STALL handshake to be sent to the host.
• RSTDT: Reset Data Toggle
The data toggle sequence is cleared when the RSTDTS bit is written to one (i.e., Data0 data toggle sequence will be selected
for the next sent (IN endpoints) or received (OUT endpoints) packet.
This bit is always read as zero.
• FIFOCON: FIFO Control
For control endpoints:
The FIFOCON and RWALL bits are irrelevant. The software shall therefore never use them for these endpoints. When read,
their value is always 0.
For IN endpoints:
This bit is cleared when the FIFOCONC bit is written to one, sending the FIFO data and switching to the next bank.
This bit is set simultaneously to TXINI, when the current bank is free.
For OUT endpoints:
This bit is cleared when the FIFOCONC bit is written to one, freeing the current bank and switching to the next.
This bit is set simultaneously to RXINI, when the current bank is full.
31 30 29 28 27 26 25 24
- - - - - - BUSY1E BUSY0E
23 22 21 20 19 18 17 16
- - - - STALLRQ RSTDT - -
15 14 13 12 11 10 9 8
- FIFOCON KILLBK NBUSYBKE RAMACERE - -
76543210
- STALLEDE/
CRCERRE - NAKINE NAKOUTE RXSTPE/
ERRORFE RXOUTE TXINE
131
32142D–06/2013
ATUC64/128/256L3/4U
• KILLBK: Kill IN Bank
This bit is cleared by hardware after the completion of the “kill packet procedure”.
This bit is set when the KILLBKS bit is written to one, killing the last written bank.
The user shall wait for this bit to be cleared before trying to process another IN packet.
Caution: The bank is cleared when the “kill packet” procedure is completed by the USBC core:
If the bank is really killed, the NBUSYBK field is decremented.
If the bank sent instead of killed (IN transfer), the NBUSYBK field is decremented and the TXINI flag is set. This specific case
can occur if an IN token comes while the user tries to kill the bank.
Note: If two banks are ready to be sent, the above specific case will not occur, since the first bank is sent (IN transfer) while the
last bank is killed.
• NBUSYBKE: Number of Busy Banks Interrupt Enable
This bit is cleared when the NBUSYBKEC bit is written to zero, disabling the Number of Busy Banks interrupt (NBUSYBK).
This bit is set when the NBUSYBKES bit is written to one, enabling the Number of Busy Banks interrupt (NBUSYBK).
• RAMACERE: RAMACER Interrupt Enable
This bit is cleared when the RAMACEREC bit is written to one, disabling the RAMACER interrupt (RAMACERI).
This bit is set when the RAMACERES bit is written to one, enabling the RAMACER interrupt (RAMACERI).
• STALLEDE: STALLed Interrupt Enable
This bit is cleared when the STALLEDEC bit is written to one, disabling the STALLed interrupt (STALLEDI).
This bit is set when the STALLEDES bit is written to one, enabling the STALLed interrupt (STALLEDI).
• CRCERRE: CRC Error Interrupt Enable
This bit is cleared when the CRCERREC bit is written to one, disabling the CRC Error interrupt (CRCERRI).
This bit is set when the CRCERRES bit is written to one, enabling the CRC Error interrupt (CRCERRI).
• NAKINE: NAKed IN Interrupt Enable
This bit is cleared when the NAKINEC bit is written to one, disabling the NAKed IN interrupt (NAKINI).
This bit is set when the NAKINES bit is written to one, enabling the NAKed IN interrupt (NAKINI).
• NAKOUTE: NAKed OUT Interrupt Enable
This bit is cleared when the NAKOUTEC bit is written to one, disabling the NAKed OUT interrupt (NAKOUTI).
This bit is set when the NAKOUTES bit is written to one, enabling the NAKed OUT interrupt (NAKOUTI).
• RXSTPE: Received SETUP Interrupt Enable
This bit is cleared when the RXSTPEC bit is written to one, disabling the Received SETUP interrupt (RXSTPI).
This bit is set when the RXSTPES bit is written to one, enabling the Received SETUP interrupt (RXSTPI).
• ERRORFE: Errorflow Interrupt Enable
This bit is cleared when the ERRORFEC bit is written to one, disabling the Underflow interrupt (ERRORFI).
This bit is set when the ERRORFES bit is written to one, enabling the Underflow interrupt (ERRORFI).
• RXOUTE: Received OUT Data Interrupt Enable
This bit is cleared when the RXOUTEC bit is written to one, disabling the Received OUT Data interrupt (RXOUT).
This bit is set when the RXOUTES bit is written to one, enabling the Received OUT Data interrupt (RXOUT).
• TXINE: Transmitted IN Data Interrupt Enable
This bit is cleared when the TXINEC bit is written to one, disabling the Transmitted IN Data interrupt (TXINI).
This bit is set when the TXINES bit is written to one, enabling the Transmitted IN Data interrupt (TXINI).
132
32142D–06/2013
ATUC64/128/256L3/4U
8.7.2.15 Endpoint n Control Clear Register
Register Name: UECONnCLR, n in [0..6]
Access Type: Write-Only
Offset: 0x0220 + (n * 0x04)
Reset Value: 0x00000000
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will clear the corresponding bit in UECONn.
These bits always read as zero.
31 30 29 28 27 26 25 24
- - - - - - BUSY1EC BUSY0EC
23 22 21 20 19 18 17 16
- - - - STALLRQC - - -
15 14 13 12 11 10 9 8
- FIFOCONC - NBUSYBKEC RAMACEREC - - -
76543210
- STALLEDEC/
CRCERREC - NAKINEC NAKOUTEC RXSTPEC/
ERRORFEC RXOUTEC TXINEC
133
32142D–06/2013
ATUC64/128/256L3/4U
8.7.2.16 Endpoint n Control Set Register
Register Name: UECONnSET, n in [0..6]
Access Type: Write-Only
Offset: 0x01F0 + (n * 0x04)
Reset Value: 0x00000000
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will set the corresponding bit in UECONn.
These bits always read as zero.
•
•
31 30 29 28 27 26 25 24
- - - - - - BUSY1ES BUSY0ES
23 22 21 20 19 18 17 16
- - - - STALLRQS RSTDTS - -
15 14 13 12 11 10 9 8
- - KILLBKS NBUSYBKES RAMACERES ---
76543210
- STALLEDES/
CRCERRES - NAKINES NAKOUTES RXSTPES/
ERRORFES RXOUTES TXINES
134
32142D–06/2013
ATUC64/128/256L3/4U
8.8 Module Configuration
The specific configuration for each USBC instance is listed in the following tables. The module
bus clocks listed here are connected to the system bus clocks. Please refer to the Power Manager
chapter for details.
Table 8-6. USBC Clocks
Clock Name Description
CLK_USBC_PB Clock for the USBC PB interface
CLK_USBC_HSB Clock for the USBC HSB interface
GCLK_USBC The generic clock used for the USBC is GCLK7
Table 8-7. Register Reset Values
Register Reset Value
UVERS 0x00000200
UFEATURES 0x00000007
UADDRSIZE 0x00001000
UNAME1 0x48555342
UNAME2 0x00000000
135
32142D–06/2013
ATUC64/128/256L3/4U
9. Flash Controller (FLASHCDW)
Rev: 1.2.0.0
9.1 Features
• Controls on-chip flash memory
• Supports 0 and 1 wait state bus access
• Buffers reducing penalty of wait state in sequential code or loops
• Allows interleaved burst reads for systems with one wait state, outputting one 32-bit word per
clock cycle for sequential reads
• Secure State for supporting FlashVault technology
• 32-bit HSB interface for reads from flash and writes to page buffer
• 32-bit PB interface for issuing commands to and configuration of the controller
• Flash memory is divided into 16 regions can be individually protected or unprotected
• Additional protection of the Boot Loader pages
• Supports reads and writes of general-purpose Non Volatile Memory (NVM) bits
• Supports reads and writes of additional NVM pages
• Supports device protection through a security bit
• Dedicated command for chip-erase, first erasing all on-chip volatile memories before erasing
flash and clearing security bit
9.2 Overview
The Flash Controller (FLASHCDW) interfaces the on-chip flash memory with the 32-bit internal
HSB bus. The controller manages the reading, writing, erasing, locking, and unlocking
sequences.
9.3 Product Dependencies
In order to use this module, other parts of the system must be configured correctly, as described
below.
9.3.1 Power Management
If the CPU enters a sleep mode that disables clocks used by the FLASHCDW, the FLASHCDW
will stop functioning and resume operation after the system wakes up from sleep mode.
9.3.2 Clocks
The FLASHCDW has two bus clocks connected: One High Speed Bus clock
(CLK_FLASHCDW_HSB) and one Peripheral Bus clock (CLK_FLASHCDW_PB). These clocks
are generated by the Power Manager. Both clocks are enabled at reset, and can be disabled by
writing to the Power Manager. The user has to ensure that CLK_FLASHCDW_HSB is not turned
off before reading the flash or writing the pagebuffer and that CLK_FLASHCDW_PB is not
turned off before accessing the FLASHCDW configuration and control registers. Failing to do so
may deadlock the bus.
9.3.3 Interrupts
The FLASHCDW interrupt request lines are connected to the interrupt controller. Using the
FLASHCDW interrupts requires the interrupt controller to be programmed first.
136
32142D–06/2013
ATUC64/128/256L3/4U
9.3.4 Debug Operation
When an external debugger forces the CPU into debug mode, the FLASHCDW continues normal
operation. If the FLASHCDW is configured in a way that requires it to be periodically
serviced by the CPU through interrupts or similar, improper operation or data loss may result
during debugging.
9.4 Functional Description
9.4.1 Bus Interfaces
The FLASHCDW has two bus interfaces, one High Speed Bus (HSB) interface for reads from the
flash memory and writes to the page buffer, and one Peripheral Bus (PB) interface for issuing
commands and reading status from the controller.
9.4.2 Memory Organization
The flash memory is divided into a set of pages. A page is the basic unit addressed when programming
the flash. A page consists of several words. The pages are grouped into 16 regions of
equal size. Each of these regions can be locked by a dedicated fuse bit, protecting it from accidental
modification.
• p pages (FLASH_P)
• w bytes in each page and in the page buffer (FLASH_W)
• pw bytes in total (FLASH_PW)
• f general-purpose fuse bits (FLASH_F), used as region lock bits and for other device-specific
purposes
• 1 security fuse bit
• 1 User page
9.4.3 User Page
The User page is an additional page, outside the regular flash array, that can be used to store
various data, such as calibration data and serial numbers. This page is not erased by regular
chip erase. The User page can only be written and erased by a special set of commands. Read
accesses to the User page are performed just as any other read accesses to the flash. The
address map of the User page is given in Figure 9-1 on page 138.
9.4.4 Read Operations
The on-chip flash memory is typically used for storing instructions to be executed by the CPU.
The CPU will address instructions using the HSB bus, and the FLASHCDW will access the flash
memory and return the addressed 32-bit word.
In systems where the HSB clock period is slower than the access time of the flash memory, the
FLASHCDW can operate in 0 wait state mode, and output one 32-bit word on the bus per clock
cycle. If the clock frequency allows, the user should use 0 wait state mode, because this gives
the highest performance as no stall cycles are encountered.
The FLASHCDW can also operate in systems where the HSB bus clock period is faster than the
access speed of the flash memory. Wait state support and a read granularity of 64 bits ensure
efficiency in such systems.
Performance for systems with high clock frequency is increased since the internal read word
width of the flash memory is 64 bits. When a 32-bit word is to be addressed, the word itself and
137
32142D–06/2013
ATUC64/128/256L3/4U
also the other word in the same 64-bit location is read. The first word is output on the bus, and
the other word is put into an internal buffer. If a read to a sequential address is to be performed
in the next cycle, the buffered word is output on the bus, while the next 64-bit location is read
from the flash memory. Thus, latency in 1 wait state mode is hidden for sequential fetches.
The programmer can select the wait states required by writing to the FWS field in the Flash Control
Register (FCR). It is the responsibility of the programmer to select a number of wait states
compatible with the clock frequency and timing characteristics of the flash memory.
In 0ws mode, no wait states are encountered on any flash read operations. In 1 ws mode, one
stall cycle is encountered on the first access in a single or burst transfer. In 1 ws mode, if the first
access in a burst access is to an address that is not 64-bit aligned, an additional stall cycle is
also encountered when reading the second word in the burst. All subsequent words in the burst
are accessed without any stall cycles.
The Flash Controller provides two sets of buffers that can be enabled in order to speed up
instruction fetching. These buffers can be enabled by writing a one to the FCR.SEQBUF and
FCR.BRBUF bits. The SEQBUF bit enables buffering hardware optimizing sequential instruction
fetches. The BRBUF bit enables buffering hardware optimizing tight inner loops. These buffers
are never used when the flash is in 0 wait state mode. Usually, both these buffers should be
enabled when operating in 1 wait state mode. Some users requiring absolute cycle determinism
may want to keep the buffers disabled.
The Flash Controller address space is displayed in Figure 9-1. The memory space between
address pw and the User page is reserved, and reading addresses in this space returns an
undefined result. The User page is permanently mapped to an offset of 0x00800000 from the
start address of the flash memory.
Table 9-1. User Page Addresses
Memory type Start address, byte sized Size
Main array 0 pw bytes
User 0x00800000 w bytes
138
32142D–06/2013
ATUC64/128/256L3/4U
Figure 9-1. Memory Map for the Flash Memories
9.4.5 High Speed Read Mode
The flash provides a High Speed Read Mode, offering slightly higher flash read speed at the
cost of higher power consumption. Two dedicated commands, High Speed Read Mode Enable
(HSEN) and High Speed Read Mode Disable (HSDIS) control the speed mode. The High Speed
Mode (HSMODE) bit in the Flash Status Register (FSR) shows which mode the flash is in. After
reset, the High Speed Mode is disabled, and must be manually enabled if the user wants to.
Refer to the Electrical Characteristics chapter at the end of this datasheet for details on the maximum
clock frequencies in Normal and High Speed Read Mode.
0
pw
Reserved Flash data array
Reserved User Page
Flash with User Page
0x0080 0000
All addresses are byte addresses
Flash base address
Offset from
base address
139
32142D–06/2013
ATUC64/128/256L3/4U
Figure 9-2. High Speed Mode
9.4.6 Quick Page Read
A dedicated command, Quick Page Read (QPR), is provided to read all words in an addressed
page. All bits in all words in this page are AND’ed together, returning a 1-bit result. This result is
placed in the Quick Page Read Result (QPRR) bit in Flash Status Register (FSR). The QPR
command is useful to check that a page is in an erased state. The QPR instruction is much
faster than performing the erased-page check using a regular software subroutine.
9.4.7 Quick User Page Read
A dedicated command, Quick User Page Read (QPRUP), is provided to read all words in the
user page. All bits in all words in this page are AND’ed together, returning a 1-bit result. This
result is placed in the Quick Page Read Result (QPRR) bit in Flash Status Register (FSR). The
QPRUP command is useful to check that a page is in an erased state. The QPRUP instruction is
much faster than performing the erased-page check using a regular software subroutine.
9.4.8 Page Buffer Operations
The flash memory has a write and erase granularity of one page; data is written and erased in
chunks of one page. When programming a page, the user must first write the new data into the
Page Buffer. The contents of the entire Page Buffer is copied into the desired page in flash
memory when the user issues the Write Page command, Refer to Section 9.5.1 on page 141.
In order to program data into flash page Y, write the desired data to locations Y0 to Y31 in the
regular flash memory map. Writing to an address A in the flash memory map will not update the
flash memory, but will instead update location A%32 in the page buffer. The PAGEN field in the
Flash Command (FCMD) register will at the same time be updated with the value A/32.
Frequency
Frequency limit
for 0 wait state
operation
Normal
High
Speed mode
1 wait state
0 wait state
140
32142D–06/2013
ATUC64/128/256L3/4U
Figure 9-3. Mapping from Page Buffer to Flash
Internally, the flash memory stores data in 64-bit doublewords. Therefore, the native data size of
the Page Buffer is also a 64-bit doubleword. All locations shown in Figure 9-3 are therefore doubleword
locations. Since the HSB bus only has a 32-bit data width, two 32-bit HSB transfers
must be performed to write a 64-bit doubleword into the Page Buffer. The FLASHCDW has logic
to combine two 32-bit HSB transfers into a 64-bit data before writing this 64-bit data into the
Page Buffer. This logic requires the word with the low address to be written to the HSB bus
before the word with the high address. To exemplify, to write a 64-bit value to doubleword X0
residing in page X, first write a 32-bit word to the byte address pointing to address X0, thereafter
write a word to the byte address pointing to address (X0+4).
The page buffer is word-addressable and should only be written with aligned word transfers,
never with byte or halfword transfers. The page buffer can not be read.
The page buffer is also used for writes to the User page.
Page buffer write operations are performed with 4 wait states. Any accesses attempted to the
FLASHCDW on the HSB bus during these cycles will be automatically stalled.
Writing to the page buffer can only change page buffer bits from one to zero, i.e. writing
0xAAAAAAAA to a page buffer location that has the value 0x00000000 will not change the page
buffer value. The only way to change a bit from zero to one is to erase the entire page buffer with
the Clear Page Buffer command.
Z3 Z2 Z1 Z0
Z7 Z6 Z5 Z4
Z11 Z10 Z9 Z8
Z15 Z14 Z13 Z12
Z19 Z18 Z17 Z16
Z23 Z22 Z21 Z20
Z27 Z26 Z25 Z24
Z31 Z30 Z29 Z28
Y3 Y2 Y1 Y0
Y7 Y6 Y5 Y4
Y11 Y10 Y9 Y8
Y15 Y14 Y13 Y12
Y19 Y18 Y17 Y16
Y23 Y22 Y21 Y20
Y27 Y26 Y25 Y24
Y31 Y30 Y29 Y28
X3 X2 X1 X0
X7 X6 X5 X4
X11 X10 X9 X8
X15 X14 X13 X12
X19 X18 X17 X16
X23 X22 X21 X20
X27 X26 X25 X24
X31 X30 X29 X28
3 2 1 0
7 6 5 4
11 10 9 8
15 14 13 12
19 18 17 16
23 22 21 20
27 26 25 24
31 30 29 28
Page X
Page Y
Page Z
Page Buffer
64-bit data
Flash
All locations are doubleword locations
141
32142D–06/2013
ATUC64/128/256L3/4U
The page buffer is not automatically reset after a page write. The programmer should do this
manually by issuing the Clear Page Buffer flash command. This can be done after a page write,
or before the page buffer is loaded with data to be stored to the flash page.
9.5 Flash Commands
The FLASHCDW offers a command set to manage programming of the flash memory, locking
and unlocking of regions, and full flash erasing. See Section 9.8.2 for a complete list of
commands.
To run a command, the CMD field in the Flash Command Register (FCMD) has to be written
with the command number. As soon as the FCMD register is written, the FRDY bit in the Flash
Status Register (FSR) is automatically cleared. Once the current command is complete, the
FSR.FRDY bit is automatically set. If an interrupt has been enabled by writing a one to
FCR.FRDY, the interrupt request line of the Flash Controller is activated. All flash commands
except for Quick Page Read (QPR) and Quick User Page Read (QPRUP) will generate an interrupt
request upon completion if FCR.FRDY is one.
Any HSB bus transfers attempting to read flash memory when the FLASHCDW is busy executing
a flash command will be stalled, and allowed to continue when the flash command is
complete.
After a command has been written to FCMD, the programming algorithm should wait until the
command has been executed before attempting to read instructions or data from the flash or
writing to the page buffer, as the flash will be busy. The waiting can be performed either by polling
the Flash Status Register (FSR) or by waiting for the flash ready interrupt. The command
written to FCMD is initiated on the first clock cycle where the HSB bus interface in FLASHCDW
is IDLE. The user must make sure that the access pattern to the FLASHCDW HSB interface
contains an IDLE cycle so that the command is allowed to start. Make sure that no bus masters
such as DMA controllers are performing endless burst transfers from the flash. Also, make sure
that the CPU does not perform endless burst transfers from flash. This is done by letting the
CPU enter sleep mode after writing to FCMD, or by polling FSR for command completion. This
polling will result in an access pattern with IDLE HSB cycles.
All the commands are protected by the same keyword, which has to be written in the eight highest
bits of the FCMD register. Writing FCMD with data that does not contain the correct key
and/or with an invalid command has no effect on the flash memory; however, the PROGE bit is
set in the Flash Status Register (FSR). This bit is automatically cleared by a read access to the
FSR register.
Writing a command to FCMD while another command is being executed has no effect on the
flash memory; however, the PROGE bit is set in the Flash Status Register (FSR). This bit is
automatically cleared by a read access to the FSR register.
If the current command writes or erases a page in a locked region, or a page protected by the
BOOTPROT fuses, the command has no effect on the flash memory; however, the LOCKE bit is
set in the FSR register. This bit is automatically cleared by a read access to the FSR register.
9.5.1 Write/Erase Page Operation
Flash technology requires that an erase must be done before programming. The entire flash can
be erased by an Erase All command. Alternatively, pages can be individually erased by the
Erase Page command.
The User page can be written and erased using the mechanisms described in this chapter.
142
32142D–06/2013
ATUC64/128/256L3/4U
After programming, the page can be locked to prevent miscellaneous write or erase sequences.
Locking is performed on a per-region basis, so locking a region locks all pages inside the region.
Additional protection is provided for the lowermost address space of the flash. This address
space is allocated for the Boot Loader, and is protected both by the lock bit(s) corresponding to
this address space, and the BOOTPROT[2:0] fuses.
Data to be written is stored in an internal buffer called the page buffer. The page buffer contains
w words. The page buffer wraps around within the internal memory area address space and
appears to be repeated by the number of pages in it. Writing of 8-bit and 16-bit data to the page
buffer is not allowed and may lead to unpredictable data corruption.
Data must be written to the page buffer before the programming command is written to the Flash
Command Register (FCMD). The sequence is as follows:
• Reset the page buffer with the Clear Page Buffer command.
• Fill the page buffer with the desired contents as described in Section 9.4.8 on page 139.
• Programming starts as soon as the programming key and the programming command are
written to the Flash Command Register. The PAGEN field in the Flash Command Register
(FCMD) must contain the address of the page to write. PAGEN is automatically updated
when writing to the page buffer, but can also be written to directly. The FRDY bit in the Flash
Status Register (FSR) is automatically cleared when the page write operation starts.
• When programming is completed, the FRDY bit in the Flash Status Register (FSR) is set. If
an interrupt was enabled by writing FCR.FRDY to one, an interrupt request is generated.
Two errors can be detected in the FSR register after a programming sequence:
• Programming Error: A bad keyword and/or an invalid command have been written in the
FCMD register.
• Lock Error: Can have two different causes:
– The page to be programmed belongs to a locked region. A command must be
executed to unlock the corresponding region before programming can start.
– A bus master without secure status attempted to program a page requiring secure
privileges.
9.5.2 Erase All Operation
The entire memory is erased if the Erase All command (EA) is written to the Flash Command
Register (FCMD). Erase All erases all bits in the flash array. The User page is not erased. All
flash memory locations, the general-purpose fuse bits, and the security bit are erased (reset to
0xFF) after an Erase All.
The EA command also ensures that all volatile memories, such as register file and RAMs, are
erased before the security bit is erased.
Erase All operation is allowed only if no regions are locked, and the BOOTPROT fuses are configured
with a BOOTPROT region size of 0. Thus, if at least one region is locked, the bit LOCKE
in FSR is set and the command is cancelled. If the LOCKE bit in FCR is one, an interrupt request
is set generated.
When the command is complete, the FRDY bit in the Flash Status Register (FSR) is set. If an
interrupt has been enabled by writing FCR.FRDY to one, an interrupt request is generated. Two
errors can be detected in the FSR register after issuing the command:
143
32142D–06/2013
ATUC64/128/256L3/4U
• Programming Error: A bad keyword and/or an invalid command have been written in the
FCMD register.
• Lock Error: At least one lock region is protected, or BOOTPROT is different from 0. The erase
command has been aborted and no page has been erased. A “Unlock region containing
given page” (UP) command must be executed to unlock any locked regions.
9.5.3 Region Lock Bits
The flash memory has p pages, and these pages are grouped into 16 lock regions, each region
containing p/16 pages. Each region has a dedicated lock bit preventing writing and erasing
pages in the region. After production, the device may have some regions locked. These locked
regions are reserved for a boot or default application. Locked regions can be unlocked to be
erased and then programmed with another application or other data.
To lock or unlock a region, the commands Lock Region Containing Page (LP) and Unlock
Region Containing Page (UP) are provided. Writing one of these commands, together with the
number of the page whose region should be locked/unlocked, performs the desired operation.
One error can be detected in the FSR register after issuing the command:
• Programming Error: A bad keyword and/or an invalid command have been written in the
FCMD register.
The lock bits are implemented using the lowest 16 general-purpose fuse bits. This means that
lock bits can also be set/cleared using the commands for writing/erasing general-purpose fuse
bits, see Section 9.6. The general-purpose bit being in an erased (1) state means that the region
is unlocked.
The lowermost pages in the flash can additionally be protected by the BOOTPROT fuses, see
Section 9.6.
9.6 General-purpose Fuse Bits
The flash memory has a number of general-purpose fuse bits that the application programmer
can use freely. The fuse bits can be written and erased using dedicated commands, and read
144
32142D–06/2013
ATUC64/128/256L3/4U
through a dedicated Peripheral Bus address. Some of the general-purpose fuse bits are
reserved for special purposes, and should not be used for other functions:
The BOOTPROT fuses protects the following address space for the Boot Loader:
Table 9-2. General-purpose Fuses with Special Functions
GeneralPurpose
fuse
number Name Usage
15:0 LOCK Region lock bits.
16 EPFL
External Privileged Fetch Lock. Used to prevent the CPU from
fetching instructions from external memories when in privileged
mode. This bit can only be changed when the security bit is
cleared. The address range corresponding to external
memories is device-specific, and not known to the Flash
Controller. This fuse bit is simply routed out of the CPU or bus
system, the Flash Controller does not treat this fuse in any
special way, except that it can not be altered when the security
bit is set.
If the security bit is set, only an external JTAG or aWire Chip
Erase can clear EPFL. No internal commands can alter EPFL if
the security bit is set.
When the fuse is erased (i.e. "1"), the CPU can execute
instructions fetched from external memories. When the fuse is
programmed (i.e. "0"), instructions can not be executed from
external memories.
This fuse has no effect in devices with no External Memory
Interface (EBI).
19:17 BOOTPROT
Used to select one of eight different bootloader sizes. Pages
included in the bootloader area can not be erased or
programmed except by a JTAG or aWire chip erase.
BOOTPROT can only be changed when the security bit is
cleared.
If the security bit is set, only an external JTAG or aWire Chip
Erase can clear BOOTPROT, and thereby allow the pages
protected by BOOTPROT to be programmed. No internal
commands can alter BOOTPROT or the pages protected by
BOOTPROT if the security bit is set.
21:20 SECURE
Used to configure secure state and secure state debug
capabilities. Decoded into SSE and SSDE signals as shown in
Table 9-5. Refer to the AVR32 Architecture Manual and the
AVR32UC Technical Reference Manual for more details on
SSE and SSDE.
22 UPROT
If programmed (i.e. “0”), the JTAG USER PROTECTION
feature is enabled. If this fuse is programmed some HSB
addresses will be accessible by JTAG access even if the flash
security fuse is programmed. Refer to the JTAG documentation
for more information on this functionality. This bit can only be
changed when the security bit is cleared.
145
32142D–06/2013
ATUC64/128/256L3/4U
The SECURE fuses have the following functionality:
To erase or write a general-purpose fuse bit, the commands Write General-Purpose Fuse Bit
(WGPB) and Erase General-Purpose Fuse Bit (EGPB) are provided. Writing one of these commands,
together with the number of the fuse to write/erase, performs the desired operation.
An entire General-Purpose Fuse byte can be written at a time by using the Program GP Fuse
Byte (PGPFB) instruction. A PGPFB to GP fuse byte 2 is not allowed if the flash is locked by the
security bit. The PFB command is issued with a parameter in the PAGEN field:
• PAGEN[2:0] - byte to write
• PAGEN[10:3] - Fuse value to write
All general-purpose fuses can be erased by the Erase All General-Purpose fuses (EAGP) command.
An EAGP command is not allowed if the flash is locked by the security bit.
Two errors can be detected in the FSR register after issuing these commands:
• Programming Error: A bad keyword and/or an invalid command have been written in the
FCMD register.
• Lock Error:
– A write or erase of the BOOTPROT or EPFL or UPROT fuse bits was attempted
while the flash is locked by the security bit.
– A write or erase of the SECURE fuse bits was attempted when SECURE mode was
enabled.
The lock bits are implemented using the lowest 16 general-purpose fuse bits. This means that
the 16 lowest general-purpose fuse bits can also be written/erased using the commands for
locking/unlocking regions, see Section 9.5.3.
Table 9-3. Boot Loader Area Specified by BOOTPROT
BOOTPROT
Pages protected by
BOOTPROT
Size of protected
memory
7 None 0
6 0-1 1Kbyte
5 0-3 2Kbyte
4 0-7 4Kbyte
3 0-15 8Kbyte
2 0-31 16Kbyte
1 0-63 32Kbyte
0 0-127 64Kbyte
Table 9-5. Secure State Configuration
SECURE Functionality SSE SSDE
00 Secure state disabled 0 0
01 Secure enabled, secure state debug enabled 1 1
10 Secure enabled, secure state debug disabled 1 0
11 Secure state disabled 0 0
146
32142D–06/2013
ATUC64/128/256L3/4U
9.7 Security Bit
The security bit allows the entire device to be locked from external JTAG, aWire, or other debug
access for code security. The security bit can be written by a dedicated command, Set Security
Bit (SSB). Once set, the only way to clear the security bit is through the JTAG or aWire Chip
Erase command.
Once the security bit is set, the following Flash Controller commands will be unavailable and
return a lock error if attempted:
• Write General-Purpose Fuse Bit (WGPB) to BOOTPROT or EPFL fuses
• Erase General-Purpose Fuse Bit (EGPB) to BOOTPROT or EPFL fuses
• Program General-Purpose Fuse Byte (PGPFB) of fuse byte 2
• Erase All General-Purpose Fuses (EAGPF)
One error can be detected in the FSR register after issuing the command:
• Programming Error: A bad keyword and/or an invalid command have been written in the
FCMD register.
147
32142D–06/2013
ATUC64/128/256L3/4U
9.8 User Interface
Note: 1. The value of the Lock bits depend on their programmed state. All other bits in FSR are 0.
2. All bits in FGPRHI/LO are dependent on the programmed state of the fuses they map to. Any bits in these registers not
mapped to a fuse read as 0.
3. The reset values for these registers are device specific. Please refer to the Module Configuration section at the end of this
chapter.
Table 9-6. FLASHCDW Register Memory Map
Offset Register Register Name Access Reset
0x00 Flash Control Register FCR Read/Write 0x00000000
0x04 Flash Command Register FCMD Read/Write 0x00000000
0x08 Flash Status Register FSR Read-only -(1)
0x0C Flash Parameter Register FPR Read-only -(3)
0x10 Flash Version Register FVR Read-only -(3)
0x14 Flash General Purpose Fuse Register Hi FGPFRHI Read-only -(2)
0x18 Flash General Purpose Fuse Register Lo FGPFRLO Read-only -(2)
148
32142D–06/2013
ATUC64/128/256L3/4U
9.8.1 Flash Control Register
Name: FCR
Access Type: Read/Write
Offset: 0x00
Reset Value: 0x00000000
• BRBUF: Branch Target Instruction Buffer Enable
0: The Branch Target Instruction Buffer is disabled.
1: The Branch Target Instruction Buffer is enabled.
• SEQBUF: Sequential Instruction Fetch Buffer Enable
0: The Sequential Instruction Fetch Buffer is disabled.
1: The Sequential Instruction Fetch Buffer is enabled.
• FWS: Flash Wait State
0: The flash is read with 0 wait states.
1: The flash is read with 1 wait state.
• PROGE: Programming Error Interrupt Enable
0: Programming Error does not generate an interrupt request.
1: Programming Error generates an interrupt request.
• LOCKE: Lock Error Interrupt Enable
0: Lock Error does not generate an interrupt request.
1: Lock Error generates an interrupt request.
• FRDY: Flash Ready Interrupt Enable
0: Flash Ready does not generate an interrupt request.
1: Flash Ready generates an interrupt request.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
- - - - - BRBUF SEQBUF -
76543210
- FWS - - PROGE LOCKE - FRDY
149
32142D–06/2013
ATUC64/128/256L3/4U
9.8.2 Flash Command Register
Name: FCMD
Access Type: Read/Write
Offset: 0x04
Reset Value: 0x00000000
The FCMD can not be written if the flash is in the process of performing a flash command. Doing
so will cause the FCR write to be ignored, and the PROGE bit in FSR to be set.
• KEY: Write protection key
This field should be written with the value 0xA5 to enable the command defined by the bits of the register. If the field is written
with a different value, the write is not performed and no action is started.
This field always reads as 0.
• PAGEN: Page number
The PAGEN field is used to address a page or fuse bit for certain operations. In order to simplify programming, the PAGEN field
is automatically updated every time the page buffer is written to. For every page buffer write, the PAGEN field is updated with the
page number of the address being written to. Hardware automatically masks writes to the PAGEN field so that only bits
representing valid page numbers can be written, all other bits in PAGEN are always 0. As an example, in a flash with 1024
pages (page 0 - page 1023), bits 15:10 will always be 0.
31 30 29 28 27 26 25 24
KEY
23 22 21 20 19 18 17 16
PAGEN [15:8]
15 14 13 12 11 10 9 8
PAGEN [7:0]
76543210
- - CMD
Table 9-7. Semantic of PAGEN field in different commands
Command PAGEN description
No operation Not used
Write Page The number of the page to write
Clear Page Buffer Not used
Lock region containing given Page Page number whose region should be locked
Unlock region containing given Page Page number whose region should be unlocked
Erase All Not used
Write General-Purpose Fuse Bit GPFUSE #
Erase General-Purpose Fuse Bit GPFUSE #
Set Security Bit Not used
150
32142D–06/2013
ATUC64/128/256L3/4U
• CMD: Command
This field defines the flash command. Issuing any unused command will cause the Programming Error bit in FSR to be set, and
the corresponding interrupt to be requested if the PROGE bit in FCR is one.
Program GP Fuse Byte WriteData[7:0], ByteAddress[2:0]
Erase All GP Fuses Not used
Quick Page Read Page number
Write User Page Not used
Erase User Page Not used
Quick Page Read User Page Not used
High Speed Mode Enable Not used
High Speed Mode Disable Not used
Table 9-8. Set of commands
Command Value Mnemonic
No operation 0 NOP
Write Page 1 WP
Erase Page 2 EP
Clear Page Buffer 3 CPB
Lock region containing given Page 4 LP
Unlock region containing given Page 5 UP
Erase All 6 EA
Write General-Purpose Fuse Bit 7 WGPB
Erase General-Purpose Fuse Bit 8 EGPB
Set Security Bit 9 SSB
Program GP Fuse Byte 10 PGPFB
Erase All GPFuses 11 EAGPF
Quick Page Read 12 QPR
Write User Page 13 WUP
Erase User Page 14 EUP
Quick Page Read User Page 15 QPRUP
High Speed Mode Enable 16 HSEN
High Speed Mode Disable 17 HSDIS
RESERVED 16-31
Table 9-7. Semantic of PAGEN field in different commands
Command PAGEN description
151
32142D–06/2013
ATUC64/128/256L3/4U
9.8.3 Flash Status Register
Name: FSR
Access Type: Read-only
Offset: 0x08
Reset Value: 0x00000000
• LOCKx: Lock Region x Lock Status
0: The corresponding lock region is not locked.
1: The corresponding lock region is locked.
• HSMODE: High-Speed Mode
0: High-speed mode disabled.
1: High-speed mode enabled.
• QPRR: Quick Page Read Result
0: The result is zero, i.e. the page is not erased.
1: The result is one, i.e. the page is erased.
• SECURITY: Security Bit Status
0: The security bit is inactive.
1: The security bit is active.
• PROGE: Programming Error Status
Automatically cleared when FSR is read.
0: No invalid commands and no bad keywords were written in the Flash Command Register FCMD.
1: An invalid command and/or a bad keyword was/were written in the Flash Command Register FCMD.
• LOCKE: Lock Error Status
Automatically cleared when FSR is read.
0: No programming of at least one locked lock region has happened since the last read of FSR.
1: Programming of at least one locked lock region has happened since the last read of FSR.
• FRDY: Flash Ready Status
0: The Flash Controller is busy and the application must wait before running a new command.
1: The Flash Controller is ready to run a new command.
31 30 29 28 27 26 25 24
LOCK15 LOCK14 LOCK13 LOCK12 LOCK11 LOCK10 LOCK9 LOCK8
23 22 21 20 19 18 17 16
LOCK7 LOCK6 LOCK5 LOCK4 LOCK3 LOCK2 LOCK1 LOCK0
15 14 13 12 11 10 9 8
--------
76543210
- HSMODE QPRR SECURITY PROGE LOCKE - FRDY
152
32142D–06/2013
ATUC64/128/256L3/4U
9.8.4 Flash Parameter Register
Name: FPR
Access Type: Read-only
Offset: 0x0C
Reset Value: -
• PSZ: Page Size
The size of each flash page.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
- - - - - PSZ
76543210
- - - - FSZ
Table 9-9. Flash Page Size
PSZ Page Size
0 32 Byte
1 64 Byte
2 128 Byte
3 256 Byte
4 512 Byte
5 1024 Byte
6 2048 Byte
7 4096 Byte
153
32142D–06/2013
ATUC64/128/256L3/4U
• FSZ: Flash Size
The size of the flash. Not all device families will provide all flash sizes indicated in the table.
Table 9-10. Flash Size
FSZ Flash Size FSZ Flash Size
0 4 Kbyte 8 192 Kbyte
1 8 Kbyte 9 256 Kbyte
2 16 Kbyte 10 384 Kbyte
3 32 Kbyte 11 512 Kbyte
4 48 Kbyte 12 768 Kbyte
5 64 Kbyte 13 1024 Kbyte
6 96 Kbyte 14 2048 Kbyte
7 128 Kbyte 15 Reserved
154
32142D–06/2013
ATUC64/128/256L3/4U
9.8.5 Flash Version Register
Name: FVR
Access Type: Read-only
Offset: 0x10
Reset Value: 0x00000000
• VARIANT: Variant Number
Reserved. No functionality associated.
• VERSION: Version Number
Version number of the module. No functionality associated.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
- - - - VARIANT
15 14 13 12 11 10 9 8
- - - - VERSION[11:8]
76543210
VERSION[7:0]
155
32142D–06/2013
ATUC64/128/256L3/4U
9.8.6 Flash General Purpose Fuse Register High
Name: FGPFRHI
Access Type: Read-only
Offset: 0x14
Reset Value: -
This register is only used in systems with more than 32 GP fuses.
• GPFxx: General Purpose Fuse xx
0: The fuse has a written/programmed state.
1: The fuse has an erased state.
31 30 29 28 27 26 25 24
GPF63 GPF62 GPF61 GPF60 GPF59 GPF58 GPF57 GPF56
23 22 21 20 19 18 17 16
GPF55 GPF54 GPF53 GPF52 GPF51 GPF50 GPF49 GPF48
15 14 13 12 11 10 9 8
GPF47 GPF46 GPF45 GPF44 GPF43 GPF42 GPF41 GPF40
76543210
GPF39 GPF38 GPF37 GPF36 GPF35 GPF34 GPF33 GPF32
156
32142D–06/2013
ATUC64/128/256L3/4U
9.8.7 Flash General Purpose Fuse Register Low
Name: FGPFRLO
Access Type: Read-only
Offset: 0x18
Reset Value: -
• GPFxx: General Purpose Fuse xx
0: The fuse has a written/programmed state.
1: The fuse has an erased state.
31 30 29 28 27 26 25 24
GPF31 GPF30 GPF29 GPF28 GPF27 GPF26 GPF25 GPF24
23 22 21 20 19 18 17 16
GPF23 GPF22 GPF21 GPF20 GPF19 GPF18 GPF17 GPF16
15 14 13 12 11 10 9 8
GPF15 GPF14 GPF13 GPF12 GPF11 GPF10 GPF09 GPF08
76543210
GPF07 GPF06 GPF05 GPF04 GPF03 GPF02 GPF01 GPF00
157
32142D–06/2013
ATUC64/128/256L3/4U
9.9 Fuse Settings
The flash contains 32 general purpose fuses. These 32 fuses can be found in the Flash General
Purpose Fuse Register Low (FGPFRLO). The Flash General Purpose Fuse Register High
(FGPFRHI) is not used. In addition to the general purpose fuses, parts of the flash user page
can have a defined meaning outside of the flash controller and will also be described in this
section.
Note that when writing to the user page the values do not get loaded by the other modules on
the device until a chip reset occurs.
The general purpose fuses are erased by a JTAG or aWire chip erase.
158
32142D–06/2013
ATUC64/128/256L3/4U
9.9.1 Flash General Purpose Fuse Register Low (FGPFRLO)
• BODEN: Brown Out Detector Enable
• BODHYST: Brown Out Detector Hysteresis
0: The Brown out detector hysteresis is disabled
1: The Brown out detector hysteresis is enabled
• BODLEVEL: Brown Out Detector Trigger Level
This controls the voltage trigger level for the Brown out detector. Refer to ”Electrical Characteristics” on page 897.
• UPROT, SECURE, BOOTPROT, EPFL, LOCK
These are Flash Controller fuses and are described in the FLASHCDW section.
9.9.1.1 Default Fuse Value
The devices are shipped with the FGPFRLO register value:0xE07FFFFF:
• BODEN fuses set to 11. BOD is disabled.
• BODHYST fuse set to 1. The BOD hysteresis is enabled.
• BODLEVEL fuses set to 000000. This is the minimum voltage trigger level for BOD. This level
is lower than the POR level, so when BOD is enabled, it will never trigger with this default
value.
• UPROT fuse set to 1.
• SECURE fuse set to 11.
• BOOTPROT fuses set to 111. The bootloader protection is disabled.
• EPFL fuse set to 1. External privileged fetch is not locked.
• LOCK fuses set to 1111111111111111. No region locked.
After the JTAG or aWire chip erase command, the FGPFR register value is 0xFFFFFFFF.
31 30 29 28 27 26 25 24
BODEN BODHYST BODLEVEL[5:1]
23 22 21 20 19 18 17 16
BODLEVEL[0] UPROT SECURE BOOTPROT EPFL
15 14 13 12 11 10 9 8
LOCK[15:8]
7 6543210
LOCK[7:0]
BODEN Description
00 BOD disabled
01 BOD enabled, BOD reset enabled
10 BOD enabled, BOD reset disabled
11 BOD disabled
159
32142D–06/2013
ATUC64/128/256L3/4U
9.9.2 First Word of the User Page (Address 0x80800000)
• WDTAUTO: WatchDog Timer Auto Enable at Startup
0: The WDT is automatically enabled at startup.
1: The WDT is not automatically enabled at startup.
Please refer to the WDT chapter for detail about timeout settings when the WDT is automatically enabled.
9.9.2.1 Default user page first word value
The devices are shipped with the user page erased (all bits 1):
• WDTAUTO set to 1, WDT disabled.
31 30 29 28 27 26 25 24
- -------
23 22 21 20 19 18 17 16
- -------
15 14 13 12 11 10 9 8
- -------
7 6543210
- - - - - - - WDTAUTO
160
32142D–06/2013
ATUC64/128/256L3/4U
9.9.3 Second Word of the User Page (Address 0x80800004)
• SSADRR: Secure State End Address for the RAM
• SSADRF: Secure State End Address for the Flash
9.9.3.1 Default user page second word value
The devices are shipped with the User page erased (all bits 1).
9.10 Serial Number
Each device has a unique 120 bits serial number readable from address 0x8080020C to
0x8080021A.
9.11 Module Configuration
The specific configuration for each FLASHCDW instance is listed in the following tables.The
module bus clocks listed here are connected to the system bus clocks. Please refer to the Power
Manager chapter for details.
31 30 29 28 27 26 25 24
SSADRR[15:8]
23 22 21 20 19 18 17 16
SSADRR[7:0]
15 14 13 12 11 10 9 8
SSADRF[15:8]
7 6543210
SSADRF[7:0]
Table 9-11. Module Configuration
Feature
ATUC256L3U,
ATUC256L4U
ATUC128L3U,
ATUC128L4U
ATUC64L3U,
ATUC64L4U
Flash size 256Kbytes 128Kbytes 64Kbytes
Number of pages 512 256 128
Page size 512 bytes 512 bytes 512 bytes
Table 9-12. Module Clock Name
Module Name Clock Name Description
FLASHCDW
CLK_FLASHCDW_HSB Clock for the FLASHCDW HSB interface
CLK_FLASHCDW_PB Clock for the FLASHCDW PB interface
161
32142D–06/2013
ATUC64/128/256L3/4U
Table 9-13. Register Reset Values
Register
ATUC256L3U,
ATUC256L4U
ATUC128L3U,
ATUC128L4U
ATUC64L3U,
ATUC64L4U
FVR 0x00000120 0x00000120 0x00000120
FPR 0x00000409 0x00000407 0x00000405
162
32142D–06/2013
ATUC64/128/256L3/4U
10. Secure Access Unit (SAU)
Rev: 1.1.1.3
10.1 Features
• Remaps registers in memory regions protected by the MPU to regions not protected by the MPU
• Programmable physical address for each channel
• Two modes of operation: Locked and Open
– In Locked Mode, access to a channel must be preceded by an unlock action
• An unlocked channel remains open only for a specific amount of time, if no access is
performed during this time, the channel is relocked
• Only one channel can be open at a time, opening a channel while another one is open
locks the first one
• Access to a locked channel is denied, a bus error and optionally an interrupt is returned
• If a channel is relocked due to an unlock timeout, an interrupt can optionally be
generated
– In Open Mode, all channels are permanently unlocked
10.2 Overview
In many systems, erroneous access to peripherals can lead to catastrophic failure. An example
of such a peripheral is the Pulse Width Modulator (PWM) used to control electric motors. The
PWM outputs a pulse train that controls the motor. If the control registers of the PWM module
are inadvertently updated with wrong values, the motor can start operating out of control, possibly
causing damage to the application and the surrounding environment. However, sometimes
the PWM control registers must be updated with new values, for example when modifying the
pulse train to accelerate the motor. A mechanism must be used to protect the PWM control registers
from inadvertent access caused by for example:
• Errors in the software code
• Transient errors in the CPU caused by for example electrical noise altering the execution path
of the program
To improve the security in a computer system, the AVR32UC implements a Memory Protection
Unit (MPU). The MPU can be set up to limit the accesses that can be performed to specific
memory addresses. The MPU divides the memory space into regions, and assigns a set of
access restrictions on each region. Access restrictions can for example be read/write if the CPU
is in supervisor mode, and read-only if the CPU is in application mode. The regions can be of different
size, but each region is usually quite large, e.g. protecting 1 kilobyte of address space or
more. Furthermore, access to each region is often controlled by the execution state of the CPU,
i.e. supervisor or application mode. Such a simple control mechanism is often too inflexible (too
coarse-grained chunks) and with too much overhead (often requiring system calls to access protected
memory locations) for simple or real-time systems such as embedded microcontrollers.
Usually, the Secure Access Unit (SAU) is used together with the MPU to provide the required
security and integrity. The MPU is set up to protect regions of memory, while the SAU is set up
to provide a secure channel into specific memory locations that are protected by the MPU.
These specific locations can be thought of as fine-grained overrides of the general coarsegrained
protection provided by the MPU.
163
32142D–06/2013
ATUC64/128/256L3/4U
10.3 Block Diagram
Figure 10-1 presents the SAU integrated in an example system with a CPU, some memories,
some peripherals, and a bus system. The SAU is connected to both the Peripheral Bus (PB) and
the High Speed Bus (HSB). Configuration of the SAU is done via the PB, while memory
accesses are done via the HSB. The SAU receives an access on its HSB slave interface,
remaps it, checks that the channel is unlocked, and if so, initiates a transfer on its HSB master
interface to the remapped address.
The thin arrows in Figure 10-1 exemplifies control flow when using the SAU. The CPU wants to
read the RX Buffer in the USART. The MPU has been configured to protect all registers in the
USART from user mode access, while the SAU has been configured to remap the RX Buffer into
a memory space that is not protected by the MPU. This unprotected memory space is mapped
into the SAU HSB slave space. When the CPU reads the appropriate address in the SAU, the
SAU will perform an access to the desired RX buffer register in the USART, and thereafter return
the read results to the CPU. The return data flow will follow the opposite direction of the control
flow arrows in Figure 10-1.
Figure 10-1. SAU Block Diagram
SAU Channel
Bus master
MPU
CPU
Bus slave
USART
PWM
Bus slave Bus master
Bus slave
Flash
Bus slave
RAM
Bus bridge
SAU Configuration
Interrupt
request
High Speed Bus
SAU
Peripheral Bus
164
32142D–06/2013
ATUC64/128/256L3/4U
10.4 Product Dependencies
In order to use this module, other parts of the system must be configured correctly, as described
below.
10.4.1 Power Management
If the CPU enters a sleep mode that disables clocks used by the SAU, the SAU will stop functioning
and resume operation after the system wakes up from sleep mode.
10.4.2 Clocks
The SAU has two bus clocks connected: One High Speed Bus clock (CLK_SAU_HSB) and one
Peripheral Bus clock (CLK_SAU_PB). These clocks are generated by the Power Manager. Both
clocks are enabled at reset, and can be disabled by writing to the Power Manager. The user has
to ensure that CLK_SAU_HSB is not turned off before accessing the SAU. Likewise, the user
must ensure that no bus access is pending in the SAU before disabling CLK_SAU_HSB. Failing
to do so may deadlock the High Speed Bus.
10.4.3 Interrupt
The SAU interrupt request line is connected to the interrupt controller. Using the SAU interrupt
requires the interrupt controller to be programmed first.
10.4.4 Debug Operation
When an external debugger forces the CPU into debug mode, the SAU continues normal operation.
If the SAU is configured in a way that requires it to be periodically serviced by the CPU
through interrupts or similar, improper operation or data loss may result during debugging.
10.5 Functional Description
10.5.1 Enabling the SAU
The SAU is enabled by writing a one to the Enable (EN) bit in the Control Register (CR). This will
set the SAU Enabled (EN) bit in the Status Register (SR).
10.5.2 Configuring the SAU Channels
The SAU has a set of channels, mapped in the HSB memory space. These channels can be
configured by a Remap Target Register (RTR), located at the same memory address. When the
SAU is in normal mode, the SAU channel is addressed, and when the SAU is in setup mode, the
RTR can be addressed.
Before the SAU can be used, the channels must be configured and enabled. To configure a
channel, the corresponding RTR must be programmed with the Remap Target Address. To do
this, make sure the SAU is in setup mode by writing a one to the Setup Mode Enable (SEN) bit
in CR. This makes sure that a write to the RTR address accesses the RTR, not the SAU channel.
Thereafter, the RTR is written with the address to remap to, typically the address of a
specific PB register. When all channels have been configured, return to normal mode by writing
a one to the Setup Mode Disable (SDIS) in CR. The channels can now be enabled by writing
ones to the corresponding bits in the Channel Enable Registers (CERH/L).
The SAU is only able to remap addresses above 0xFFFC0000.
165
32142D–06/2013
ATUC64/128/256L3/4U
10.5.2.1 Protecting SAU configuration registers
In order to prevent the SAU configuration registers to be changed by malicious or runaway code,
they should be protected by the MPU as soon as they have been configured. Maximum security
is provided in the system if program memory does not contain any code to unprotect the configuration
registers in the MPU. This guarantees that runaway code can not accidentally unprotect
and thereafter change the SAU configuration registers.
10.5.3 Lock Mechanism
The SAU can be configured to use two different access mechanisms: Open and Locked. In
Open Mode, SAU channels can be accessed freely after they have been configured and
enabled. In order to prevent accidental accesses to remapped addresses, it is possible to configure
the SAU in Locked Mode. Writing a one to the Open Mode bit in the CONFIG register
(CONFIG.OPEN) will enable Open Mode. Writing a zero to CONFIG.OPEN will enable Locked
Mode.
When using Locked Mode, the lock mechanism must be configured by writing a user defined key
value to the Unlock Key (UKEY) field in the Configuration Register (CONFIG). The number of
CLK_SAU_HSB cycles the channel remains unlocked must be written to the Unlock Number of
Clock Cycles (UCYC) field in CONFIG.
Access control to the SAU channels is enabled by means of the Unlock Register (UR), which
resides in the same address space as the SAU channels. Before a channel can be accessed,
the unlock register must be written with th correct key and channel number (single write access).
Access to the channel is then permitted for the next CONFIG.UCYC clock cycles, or until a successful
access to the unlocked channel has been made.
Only one channel can be unlocked at a time. If any other channel is unlocked at the time of writing
UR, this channel will be automatically locked before the channel addressed by the UR write
is unlocked.
An attempted access to a locked channel will be aborted, and the Channel Access Unsuccessful
bit (SR.CAU) will be set.
Any pending errors bits in SR must be cleared before it is possible to access UR. The following
SR bits are defined as error bits: EXP, CAU, URREAD, URKEY, URES, MBERROR, RTRADR.
If any of these bits are set while writing to UR, the write is aborted and the Unlock Register Error
Status (URES) bit in SR is set.
10.5.4 Normal Operation
The following sequence must be used in order to access a SAU channel in normal operation
(CR.SEN=0):
1. If not in Open Mode, write the unlock key to UR.KEY and the channel number to
UR.CHANNEL.
2. Perform the read or write operation to the SAU channel. If not in Open Mode, this must
be done within CONFIG.UCYC clock cycles of unlocking the channel. The SAU will use
its HSB master interface to remap the access to the target address pointed to by the
corresponding RTR.
3. To confirm that the access was successful, wait for the IDLE transfer status bit
(SR.IDLE) to indicate the operation is completed. Then check SR for possible error conditions.
The SAU can be configured to generate interrupt requests or a Bus Error
Exception if the access failed.
166
32142D–06/2013
ATUC64/128/256L3/4U
10.5.4.1 Operation example
Figure 10-2 shows a typical memory map, consisting of some memories, some simple peripherals,
and a SAU with multiple channels and an Unlock Register (UR). Imagine that the MPU has
been set up to disallow all accesses from the CPU to the grey modules. Thus the CPU has no
way of accessing for example the Transmit Holding register in the UART, present on address X
on the bus. Note that the SAU RTRs are not protected by the MPU, thus the RTRs can be
accessed. If for example RTR0 is configured to point to address X, an access to RTR0 will be
remapped by the SAU to address X according to the algorithm presented above. By programming
the SAU RTRs, specific addresses in modules that have generally been protected by the
MPU can be performed.
Figure 10-2. Example Memory Map for a System with SAU
10.5.5 Interrupts
The SAU can generate an interrupt request to signal different events. All events that can generate
an interrupt request have dedicated bits in the Status Register (SR). An interrupt request will
be generated if the corresponding bit in the Interrupt Mask Register (IMR) is set. Bits in IMR are
set by writing a one to the corresponding bit in the Interrupt Enable Register (IER), and cleared
by writing a one to the corresponding bit in the Interrupt Disable Register (IDR). The interrupt
request remains active until the corresponding bit in SR is cleared by writing a one to the corresponding
bit in the Interrupt Clear Register (ICR).
The following SR bits are used for signalling the result of SAU accesses:
• RTR Address Error (RTRADR) is set if an illegal address is written to the RTRs. Only
addresses in the range 0xFFFC0000-0xFFFFFFFF are allowed.
• Master Interface Bus Error (MBERROR) is set if any of the conditions listed in Section 10.5.7
occurred.
Transmit Holding
Baudrate
Control
Receive Holding
Channel 1
RTR0
RTR1
Address X
Address Z
UART
SAU
CONFIG
SAU
CHANNEL
UR
RTR62 ...
167
32142D–06/2013
ATUC64/128/256L3/4U
• Unlock Register Error Status (URES) is set if an attempt was made to unlock a channel by
writing to the Unlock Register while one or more error bits in SR were set (see Section
10.5.6). The unlock operation was aborted.
• Unlock Register Key Error (URKEY) is set if the Unlock Register was attempted written with
an invalid key.
• Unlock Register Read (URREAD) is set if the Unlock Register was attempted read.
• Channel Access Unsuccessful (CAU) is set if the channel access was unsuccessful.
• Channel Access Successful (CAS) is set if the channel access was successful.
• Channel Unlock Expired (EXP) is set if the channel lock expired, with no channel being
accessed after the channel was unlocked.
10.5.6 Error bits
If error bits are set when attempting to unlock a channel, SR.URES will be set. The following SR
bits are considered error bits:
• EXP
• CAU
• URREAD
• URKEY
• URES
• MBERROR
• RTRADR
10.5.7 Bus Error Responses
By writing a one to the Bus Error Response Enable bit (CR.BERREN), serious access errors will
be configured to return a bus error to the CPU. This will cause the CPU to execute its Bus Error
Data Fetch exception routine.
The conditions that can generate a bus error response are:
• Reading the Unlock Register
• Trying to access a locked channel
• The SAU HSB master receiving a bus error response from its addressed slave
10.5.8 Disabling the SAU
To disable the SAU, the user must first ensure that no SAU bus operations are pending. This
can be done by checking that the SR.IDLE bit is set.
The SAU may then be disabled by writing a one to the Disable (DIS) bit in CR.
168
32142D–06/2013
ATUC64/128/256L3/4U
10.6 User Interface
The following addresses are used by SAU channel configuration registers. All offsets are relative to the SAU’s PB base
address.
Note: 1. The reset values are device specific. Please refer to the Module Configuration section at the end of this chapter.
The following addresses are used by SAU channel registers. All offsets are relative to the SAU’s HSB base address. The
number of channels implemented is device specific, refer to the Module Configuration section at the end of this chapter.
Table 10-1. SAU Configuration Register Memory Map
Offset Register Register Name Access Reset
0x00 Control Register CR Write-only 0x00000000
0x04 Configuration Register CONFIG Write-only 0x00000000
0x08 Channel Enable Register High CERH Read/Write 0x00000000
0x0C Channel Enable Register Low CERL Read/Write 0x00000000
0x10 Status Register SR Read-only 0x00000400
0x14 Interrupt Enable Register IER Write-only 0x00000000
0x18 Interrupt Disable Register IDR Write-only 0x00000000
0x1C Interrupt Mask Register IMR Read-only 0x00000000
0x20 Interrupt Clear Register ICR Write-only 0x00000000
0x24 Parameter Register PARAMETER Read-only -(1)
0x28 Version Register VERSION Read-only -(1)
Table 10-2. SAU Channel Register Memory Map
Offset Register Register Name Access Reset
0x00 Remap Target Register 0 RTR0 Read/Write N/A
0x04 Remap Target Register 1 RTR1 Read/Write N/A
0x08 Remap Target Register 2 RTR2 Read/Write N/A
... ... ... ... ...
0x04*n Remap Target Register n RTRn Read/Write N/A
0xFC Unlock Register UR Write-only N/A
169
32142D–06/2013
ATUC64/128/256L3/4U
10.6.1 Control Register
Name: CR
Access Type: Write-only
Offset: 0x00
Reset Value: 0x00000000
• BERRDIS: Bus Error Response Disable
Writing a zero to this bit has no effect.
Writing a one to this bit disables Bus Error Response from the SAU.
• BERREN: Bus Error Response Enable
Writing a zero to this bit has no effect.
Writing a one to this bit enables Bus Error Response from the SAU.
• SDIS: Setup Mode Disable
Writing a zero to this bit has no effect.
Writing a one to this bit exits setup mode.
• SEN: Setup Mode Enable
Writing a zero to this bit has no effect.
Writing a one to this bit enters setup mode.
• DIS: SAU Disable
Writing a zero to this bit has no effect.
Writing a one to this bit disables the SAU.
• EN: SAU Enable
Writing a zero to this bit has no effect.
Writing a one to this bit enables the SAU.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
- - BERRDIS BERREN SDIS SEN DIS EN
170
32142D–06/2013
ATUC64/128/256L3/4U
10.6.2 Configuration Register
Name: CONFIG
Access Type: Write-only
Offset: 0x04
Reset Value: 0x00000000
• OPEN: Open Mode Enable
Writing a zero to this bit disables open mode.
Writing a one to this bit enables open mode.
• UCYC: Unlock Number of Clock Cycles
Once a channel has been unlocked, it remains unlocked for this amount of CLK_SAU_HSB clock cycles or until one access to a
channel has been made.
• UKEY: Unlock Key
The value in this field must be written to UR.KEY to unlock a channel.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
- - - - - - - OPEN
15 14 13 12 11 10 9 8
UCYC
76543210
UKEY
171
32142D–06/2013
ATUC64/128/256L3/4U
10.6.3 Channel Enable Register High
Name: CERH
Access Type: Read/Write
Offset: 0x08
Reset Value: 0x00000000
• CERH[n]: Channel Enable Register High
0: Channel (n+32) is not enabled.
1: Channel (n+32) is enabled.
31 30 29 28 27 26 25 24
- CERH[30:24]
23 22 21 20 19 18 17 16
CERH[23:16]
15 14 13 12 11 10 9 8
CERH[15:8]
76543210
CERH[7:0]
172
32142D–06/2013
ATUC64/128/256L3/4U
10.6.4 Channel Enable Register Low
Name: CERL
Access Type: Read/Write
Offset: 0x0C
Reset Value: 0x00000000
• CERL[n]: Channel Enable Register Low
0: Channel n is not enabled.
1: Channel n is enabled.
31 30 29 28 27 26 25 24
CERL[31:24]
23 22 21 20 19 18 17 16
CERL[23:16]
15 14 13 12 11 10 9 8
CERL[15:8]
76543210
CERL[7:0]
173
32142D–06/2013
ATUC64/128/256L3/4U
10.6.5 Status Register
Name: SR
Access Type: Read-only
Offset: 0x10
Reset Value: 0x00000400
• IDLE
This bit is cleared when a read or write operation to the SAU channel is started.
This bit is set when the operation is completed and no SAU bus operations are pending.
• SEN: SAU Setup Mode Enable
This bit is cleared when the SAU exits setup mode.
This bit is set when the SAU enters setup mode.
• EN: SAU Enabled
This bit is cleared when the SAU is disabled.
This bit is set when the SAU is enabled.
• RTRADR: RTR Address Error
This bit is cleared when the corresponding bit in ICR is written to one.
This bit is set if, in the configuration phase, an RTR was written with an illegal address, i.e. the upper 16 bits in the address were
different from 0xFFFC, 0xFFFD, 0xFFFE or 0xFFFF.
• MBERROR: Master Interface Bus Error
This bit is cleared when the corresponding bit in ICR is written to one.
This bit is set if a channel access generated a transfer on the master interface that received a bus error response from the
addressed slave.
• URES: Unlock Register Error Status
This bit is cleared when the corresponding bit in ICR is written to one.
This bit is set if an attempt was made to unlock a channel by writing to the Unlock Register while one or more error bits were set
in SR. The unlock operation was aborted.
• URKEY: Unlock Register Key Error
This bit is cleared when the corresponding bit in ICR is written to one.
This bit is set if the Unlock Register was attempted written with an invalid key.
• URREAD: Unlock Register Read
This bit is cleared when the corresponding bit in ICR is written to one.
This bit is set if the Unlock Register was read.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
- - - - - IDLE SEN EN
76543210
RTRADR MBERROR URES URKEY URREAD CAU CAS EXP
174
32142D–06/2013
ATUC64/128/256L3/4U
• CAU: Channel Access Unsuccessful
This bit is cleared when the corresponding bit in ICR is written to one.
This bit is set if channel access was unsuccessful, i.e. an access was attempted to a locked or disabled channel.
• CAS: Channel Access Successful
This bit is cleared when the corresponding bit in ICR is written to one.
This bit is set if channel access successful, i.e. one access was made after the channel was unlocked.
• EXP: Channel Unlock Expired
This bit is cleared when the corresponding bit in ICR is written to one.
This bit is set if channel unlock has expired, i.e. no access being made after the channel was unlocked.
175
32142D–06/2013
ATUC64/128/256L3/4U
10.6.6 Interrupt Enable Register
Name: IER
Access Type: Write-only
Offset: 0x14
Reset Value: 0x00000000
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will set the corresponding bit in IMR.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
RTRADR MBERROR URES URKEY URREAD CAU CAS EXP
176
32142D–06/2013
ATUC64/128/256L3/4U
10.6.7 Interrupt Disable Register
Name: IDR
Access Type: Write-only
Offset: 0x18
Reset Value: 0x00000000
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will clear the corresponding bit in IMR.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
RTRADR MBERROR URES URKEY URREAD CAU CAS EXP
177
32142D–06/2013
ATUC64/128/256L3/4U
10.6.8 Interrupt Mask Register
Name: IMR
Access Type: Read-only
Offset: 0x1C
Reset Value: 0x00000000
0: The corresponding interrupt is disabled.
1: The corresponding interrupt is enabled.
A bit in this register is cleared when the corresponding bit in IDR is written to one.
A bit in this register is set when the corresponding bit in IER is written to one.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
RTRADR MBERROR URES URKEY URREAD CAU CAS EXP
178
32142D–06/2013
ATUC64/128/256L3/4U
10.6.9 Interrupt Clear Register
Name: ICR
Access Type: Write-only
Offset: 0x20
Reset Value: 0x00000000
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will clear the corresponding bit in SR and any corresponding interrupt request.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
RTRADR MBERROR URES URKEY URREAD CAU CAS EXP
179
32142D–06/2013
ATUC64/128/256L3/4U
10.6.10 Parameter Register
Name: PARAMETER
Access Type: Read-only
Offset: 0x24
Reset Value: -
• CHANNELS:
Number of channels implemented.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
- - CHANNELS
180
32142D–06/2013
ATUC64/128/256L3/4U
10.6.11 Version Register
Name: VERSION
Access Type: Write-only
Offset: 0x28
Reset Value: -
• VARIANT: Variant Number
Reserved. No functionality associated.
• VERSION: Version Number
Version number of the module. No functionality associated.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
- - - - VARIANT
15 14 13 12 11 10 9 8
- - - - VERSION[11:8]
76543210
VERSION[7:0]
181
32142D–06/2013
ATUC64/128/256L3/4U
10.6.12 Remap Target Register n
Name: RTRn
Access Type: Read/Write
Offset: n*4
Reset Value: 0x00000000
• RTR: Remap Target Address for Channel n
RTR[31:16] must have one of the following values, any other value will result in UNDEFINED behavior:
0xFFFC
0xFFFD
0xFFFE
0xFFFF
RTR[1:0] must be written to 00, any other value will result in UNDEFINED behavior.
31 30 29 28 27 26 25 24
RTR[31:24]
23 22 21 20 19 18 17 16
RTR[23:16]
15 14 13 12 11 10 9 8
RTR[15:8]
76543210
RTR[7:0]
182
32142D–06/2013
ATUC64/128/256L3/4U
10.6.13 Unlock Register
Name: UR
Access Type : Write-only
Offset: 0xFC
Reset Value: 0x00000000
• KEY: Unlock Key
The correct key must be written in order to unlock a channel. The key value written must correspond to the key value defined in
CONFIG.UKEY.
• CHANNEL: Channel Number
Number of the channel to unlock.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
KEY
76543210
- - CHANNEL
183
32142D–06/2013
ATUC64/128/256L3/4U
10.7 Module Configuration
The specific configuration for each SAU instance is listed in the following tables.The module bus
clocks listed here are connected to the system bus clocks. Please refer to the Power Manager
chapter for details.
Table 10-3. SAU configuration
Feature SAU
SAU Channels 16
Table 10-4. SAU clock name
Module name Clock name Description
SAU CLK_SAU_HSB Clock for the SAU HSB interface
SAU CLK_SAU_PB Clock for the SAU PB interface
Table 10-5. Register Reset Values
Register Reset Value
VERSION 0x00000111
PARAMETER 0x00000010
184
32142D–06/2013
ATUC64/128/256L3/4U
11. HSB Bus Matrix (HMATRIXB)
Rev: 1.3.0.3
11.1 Features
• User Interface on peripheral bus
• Configurable number of masters (up to 16)
• Configurable number of slaves (up to 16)
• One decoder for each master
• Programmable arbitration for each slave
– Round-Robin
– Fixed priority
• Programmable default master for each slave
– No default master
– Last accessed default master
– Fixed default master
• One cycle latency for the first access of a burst
• Zero cycle latency for default master
• One special function register for each slave (not dedicated)
11.2 Overview
The Bus Matrix implements a multi-layer bus structure, that enables parallel access paths
between multiple High Speed Bus (HSB) masters and slaves in a system, thus increasing the
overall bandwidth. The Bus Matrix interconnects up to 16 HSB Masters to up to 16 HSB Slaves.
The normal latency to connect a master to a slave is one cycle except for the default master of
the accessed slave which is connected directly (zero cycle latency). The Bus Matrix provides 16
Special Function Registers (SFR) that allow the Bus Matrix to support application specific
features.
11.3 Product Dependencies
In order to configure this module by accessing the user registers, other parts of the system must
be configured correctly, as described below.
11.3.1 Clocks
The clock for the HMATRIX bus interface (CLK_HMATRIX) is generated by the Power Manager.
This clock is enabled at reset, and can be disabled in the Power Manager.
11.4 Functional Description
11.4.1 Special Bus Granting Mechanism
The Bus Matrix provides some speculative bus granting techniques in order to anticipate access
requests from some masters. This mechanism reduces latency at first access of a burst or single
transfer. This bus granting mechanism sets a different default master for every slave.
At the end of the current access, if no other request is pending, the slave remains connected to
its associated default master. A slave can be associated with three kinds of default masters: no
default master, last access master, and fixed default master.
185
32142D–06/2013
ATUC64/128/256L3/4U
To change from one kind of default master to another, the Bus Matrix user interface provides the
Slave Configuration Registers, one for each slave, that set a default master for each slave. The
Slave Configuration Register contains two fields: DEFMSTR_TYPE and FIXED_DEFMSTR. The
2-bit DEFMSTR_TYPE field selects the default master type (no default, last access master, fixed
default master), whereas the 4-bit FIXED_DEFMSTR field selects a fixed default master provided
that DEFMSTR_TYPE is set to fixed default master. Please refer to the Bus Matrix user
interface description.
11.4.1.1 No Default Master
At the end of the current access, if no other request is pending, the slave is disconnected from
all masters. No Default Master suits low-power mode.
11.4.1.2 Last Access Master
At the end of the current access, if no other request is pending, the slave remains connected to
the last master that performed an access request.
11.4.1.3 Fixed Default Master
At the end of the current access, if no other request is pending, the slave connects to its fixed
default master. Unlike last access master, the fixed master does not change unless the user
modifies it by a software action (field FIXED_DEFMSTR of the related SCFG).
11.4.2 Arbitration
The Bus Matrix provides an arbitration mechanism that reduces latency when conflict cases
occur, i.e. when two or more masters try to access the same slave at the same time. One arbiter
per HSB slave is provided, thus arbitrating each slave differently.
The Bus Matrix provides the user with the possibility of choosing between 2 arbitration types for
each slave:
1. Round-Robin Arbitration (default)
2. Fixed Priority Arbitration
This is selected by the ARBT field in the Slave Configuration Registers (SCFG).
Each algorithm may be complemented by selecting a default master configuration for each
slave.
When a re-arbitration must be done, specific conditions apply. This is described in “Arbitration
Rules” .
11.4.2.1 Arbitration Rules
Each arbiter has the ability to arbitrate between two or more different master requests. In order
to avoid burst breaking and also to provide the maximum throughput for slave interfaces, arbitration
may only take place during the following cycles:
1. Idle Cycles: When a slave is not connected to any master or is connected to a master
which is not currently accessing it.
2. Single Cycles: When a slave is currently doing a single access.
3. End of Burst Cycles: When the current cycle is the last cycle of a burst transfer. For
defined length burst, predicted end of burst matches the size of the transfer but is managed
differently for undefined length burst. This is described below.
4. Slot Cycle Limit: When the slot cycle counter has reached the limit value indicating that
the current master access is too long and must be broken. This is described below.
186
32142D–06/2013
ATUC64/128/256L3/4U
• Undefined Length Burst Arbitration
In order to avoid long slave handling during undefined length bursts (INCR), the Bus Matrix provides
specific logic in order to re-arbitrate before the end of the INCR transfer. A predicted end
of burst is used as a defined length burst transfer and can be selected among the following five
possibilities:
1. Infinite: No predicted end of burst is generated and therefore INCR burst transfer will
never be broken.
2. One beat bursts: Predicted end of burst is generated at each single transfer inside the
INCP transfer.
3. Four beat bursts: Predicted end of burst is generated at the end of each four beat
boundary inside INCR transfer.
4. Eight beat bursts: Predicted end of burst is generated at the end of each eight beat
boundary inside INCR transfer.
5. Sixteen beat bursts: Predicted end of burst is generated at the end of each sixteen beat
boundary inside INCR transfer.
This selection can be done through the ULBT field in the Master Configuration Registers
(MCFG).
• Slot Cycle Limit Arbitration
The Bus Matrix contains specific logic to break long accesses, such as very long bursts on a
very slow slave (e.g., an external low speed memory). At the beginning of the burst access, a
counter is loaded with the value previously written in the SLOT_CYCLE field of the related Slave
Configuration Register (SCFG) and decreased at each clock cycle. When the counter reaches
zero, the arbiter has the ability to re-arbitrate at the end of the current byte, halfword, or word
transfer.
11.4.2.2 Round-Robin Arbitration
This algorithm allows the Bus Matrix arbiters to dispatch the requests from different masters to
the same slave in a round-robin manner. If two or more master requests arise at the same time,
the master with the lowest number is first serviced, then the others are serviced in a round-robin
manner.
There are three round-robin algorithms implemented:
1. Round-Robin arbitration without default master
2. Round-Robin arbitration with last default master
3. Round-Robin arbitration with fixed default master
• Round-Robin Arbitration without Default Master
This is the main algorithm used by Bus Matrix arbiters. It allows the Bus Matrix to dispatch
requests from different masters to the same slave in a pure round-robin manner. At the end of
the current access, if no other request is pending, the slave is disconnected from all masters.
This configuration incurs one latency cycle for the first access of a burst. Arbitration without
default master can be used for masters that perform significant bursts.
• Round-Robin Arbitration with Last Default Master
This is a biased round-robin algorithm used by Bus Matrix arbiters. It allows the Bus Matrix to
remove the one latency cycle for the last master that accessed the slave. At the end of the cur-
187
32142D–06/2013
ATUC64/128/256L3/4U
rent transfer, if no other master request is pending, the slave remains connected to the last
master that performed the access. Other non privileged masters still get one latency cycle if they
want to access the same slave. This technique can be used for masters that mainly perform single
accesses.
• Round-Robin Arbitration with Fixed Default Master
This is another biased round-robin algorithm. It allows the Bus Matrix arbiters to remove the one
latency cycle for the fixed default master per slave. At the end of the current access, the slave
remains connected to its fixed default master. Every request attempted by this fixed default master
will not cause any latency whereas other non privileged masters will still get one latency
cycle. This technique can be used for masters that mainly perform single accesses.
11.4.2.3 Fixed Priority Arbitration
This algorithm allows the Bus Matrix arbiters to dispatch the requests from different masters to
the same slave by using the fixed priority defined by the user. If two or more master requests are
active at the same time, the master with the highest priority number is serviced first. If two or
more master requests with the same priority are active at the same time, the master with the
highest number is serviced first.
For each slave, the priority of each master may be defined through the Priority Registers for
Slaves (PRAS and PRBS).
11.4.3 Slave and Master assignation
The index number assigned to Bus Matrix slaves and masters are described in the Module Configuration
section at the end of this chapter.
188
32142D–06/2013
ATUC64/128/256L3/4U
11.5 User Interface
Table 11-1. HMATRIX Register Memory Map
Offset Register Name Access Reset Value
0x0000 Master Configuration Register 0 MCFG0 Read/Write 0x00000002
0x0004 Master Configuration Register 1 MCFG1 Read/Write 0x00000002
0x0008 Master Configuration Register 2 MCFG2 Read/Write 0x00000002
0x000C Master Configuration Register 3 MCFG3 Read/Write 0x00000002
0x0010 Master Configuration Register 4 MCFG4 Read/Write 0x00000002
0x0014 Master Configuration Register 5 MCFG5 Read/Write 0x00000002
0x0018 Master Configuration Register 6 MCFG6 Read/Write 0x00000002
0x001C Master Configuration Register 7 MCFG7 Read/Write 0x00000002
0x0020 Master Configuration Register 8 MCFG8 Read/Write 0x00000002
0x0024 Master Configuration Register 9 MCFG9 Read/Write 0x00000002
0x0028 Master Configuration Register 10 MCFG10 Read/Write 0x00000002
0x002C Master Configuration Register 11 MCFG11 Read/Write 0x00000002
0x0030 Master Configuration Register 12 MCFG12 Read/Write 0x00000002
0x0034 Master Configuration Register 13 MCFG13 Read/Write 0x00000002
0x0038 Master Configuration Register 14 MCFG14 Read/Write 0x00000002
0x003C Master Configuration Register 15 MCFG15 Read/Write 0x00000002
0x0040 Slave Configuration Register 0 SCFG0 Read/Write 0x00000010
0x0044 Slave Configuration Register 1 SCFG1 Read/Write 0x00000010
0x0048 Slave Configuration Register 2 SCFG2 Read/Write 0x00000010
0x004C Slave Configuration Register 3 SCFG3 Read/Write 0x00000010
0x0050 Slave Configuration Register 4 SCFG4 Read/Write 0x00000010
0x0054 Slave Configuration Register 5 SCFG5 Read/Write 0x00000010
0x0058 Slave Configuration Register 6 SCFG6 Read/Write 0x00000010
0x005C Slave Configuration Register 7 SCFG7 Read/Write 0x00000010
0x0060 Slave Configuration Register 8 SCFG8 Read/Write 0x00000010
0x0064 Slave Configuration Register 9 SCFG9 Read/Write 0x00000010
0x0068 Slave Configuration Register 10 SCFG10 Read/Write 0x00000010
0x006C Slave Configuration Register 11 SCFG11 Read/Write 0x00000010
0x0070 Slave Configuration Register 12 SCFG12 Read/Write 0x00000010
0x0074 Slave Configuration Register 13 SCFG13 Read/Write 0x00000010
0x0078 Slave Configuration Register 14 SCFG14 Read/Write 0x00000010
0x007C Slave Configuration Register 15 SCFG15 Read/Write 0x00000010
0x0080 Priority Register A for Slave 0 PRAS0 Read/Write 0x00000000
0x0084 Priority Register B for Slave 0 PRBS0 Read/Write 0x00000000
0x0088 Priority Register A for Slave 1 PRAS1 Read/Write 0x00000000
189
32142D–06/2013
ATUC64/128/256L3/4U
0x008C Priority Register B for Slave 1 PRBS1 Read/Write 0x00000000
0x0090 Priority Register A for Slave 2 PRAS2 Read/Write 0x00000000
0x0094 Priority Register B for Slave 2 PRBS2 Read/Write 0x00000000
0x0098 Priority Register A for Slave 3 PRAS3 Read/Write 0x00000000
0x009C Priority Register B for Slave 3 PRBS3 Read/Write 0x00000000
0x00A0 Priority Register A for Slave 4 PRAS4 Read/Write 0x00000000
0x00A4 Priority Register B for Slave 4 PRBS4 Read/Write 0x00000000
0x00A8 Priority Register A for Slave 5 PRAS5 Read/Write 0x00000000
0x00AC Priority Register B for Slave 5 PRBS5 Read/Write 0x00000000
0x00B0 Priority Register A for Slave 6 PRAS6 Read/Write 0x00000000
0x00B4 Priority Register B for Slave 6 PRBS6 Read/Write 0x00000000
0x00B8 Priority Register A for Slave 7 PRAS7 Read/Write 0x00000000
0x00BC Priority Register B for Slave 7 PRBS7 Read/Write 0x00000000
0x00C0 Priority Register A for Slave 8 PRAS8 Read/Write 0x00000000
0x00C4 Priority Register B for Slave 8 PRBS8 Read/Write 0x00000000
0x00C8 Priority Register A for Slave 9 PRAS9 Read/Write 0x00000000
0x00CC Priority Register B for Slave 9 PRBS9 Read/Write 0x00000000
0x00D0 Priority Register A for Slave 10 PRAS10 Read/Write 0x00000000
0x00D4 Priority Register B for Slave 10 PRBS10 Read/Write 0x00000000
0x00D8 Priority Register A for Slave 11 PRAS11 Read/Write 0x00000000
0x00DC Priority Register B for Slave 11 PRBS11 Read/Write 0x00000000
0x00E0 Priority Register A for Slave 12 PRAS12 Read/Write 0x00000000
0x00E4 Priority Register B for Slave 12 PRBS12 Read/Write 0x00000000
0x00E8 Priority Register A for Slave 13 PRAS13 Read/Write 0x00000000
0x00EC Priority Register B for Slave 13 PRBS13 Read/Write 0x00000000
0x00F0 Priority Register A for Slave 14 PRAS14 Read/Write 0x00000000
0x00F4 Priority Register B for Slave 14 PRBS14 Read/Write 0x00000000
0x00F8 Priority Register A for Slave 15 PRAS15 Read/Write 0x00000000
0x00FC Priority Register B for Slave 15 PRBS15 Read/Write 0x00000000
0x0110 Special Function Register 0 SFR0 Read/Write –
0x0114 Special Function Register 1 SFR1 Read/Write –
0x0118 Special Function Register 2 SFR2 Read/Write –
0x011C Special Function Register 3 SFR3 Read/Write –
0x0120 Special Function Register 4 SFR4 Read/Write –
0x0124 Special Function Register 5 SFR5 Read/Write –
0x0128 Special Function Register 6 SFR6 Read/Write –
Table 11-1. HMATRIX Register Memory Map (Continued)
Offset Register Name Access Reset Value
190
32142D–06/2013
ATUC64/128/256L3/4U
0x012C Special Function Register 7 SFR7 Read/Write –
0x0130 Special Function Register 8 SFR8 Read/Write –
0x0134 Special Function Register 9 SFR9 Read/Write –
0x0138 Special Function Register 10 SFR10 Read/Write –
0x013C Special Function Register 11 SFR11 Read/Write –
0x0140 Special Function Register 12 SFR12 Read/Write –
0x0144 Special Function Register 13 SFR13 Read/Write –
0x0148 Special Function Register 14 SFR14 Read/Write –
0x014C Special Function Register 15 SFR15 Read/Write –
Table 11-1. HMATRIX Register Memory Map (Continued)
Offset Register Name Access Reset Value
191
32142D–06/2013
ATUC64/128/256L3/4U
11.5.1 Master Configuration Registers
Name: MCFG0...MCFG15
Access Type: Read/Write
Offset: 0x00 - 0x3C
Reset Value: 0x00000002
• ULBT: Undefined Length Burst Type
31 30 29 28 27 26 25 24
––––––––
23 22 21 20 19 18 17 16
––––––––
15 14 13 12 11 10 9 8
––––––––
76543210
– – – – – ULBT
Table 11-2. Undefined Length Burst Type
ULBT Undefined Length Burst Type Description
000 Inifinite Length Burst No predicted end of burst is generated and therefore INCR bursts coming from this
master cannot be broken.
001 Single-Access The undefined length burst is treated as a succession of single accesses, allowing rearbitration
at each beat of the INCR burst.
010 4 Beat Burst The undefined length burst is split into a four-beat burst, allowing re-arbitration at each
four-beat burst end.
011 8 Beat Burst The undefined length burst is split into an eight-beat burst, allowing re-arbitration at
each eight-beat burst end.
100 16 Beat Burst The undefined length burst is split into a sixteen-beat burst, allowing re-arbitration at
each sixteen-beat burst end.
192
32142D–06/2013
ATUC64/128/256L3/4U
11.5.2 Slave Configuration Registers
Name: SCFG0...SCFG15
Access Type: Read/Write
Offset: 0x40 - 0x7C
Reset Value: 0x00000010
• ARBT: Arbitration Type
0: Round-Robin Arbitration
1: Fixed Priority Arbitration
• FIXED_DEFMSTR: Fixed Default Master
This is the number of the Default Master for this slave. Only used if DEFMSTR_TYPE is 2. Specifying the number of a master
which is not connected to the selected slave is equivalent to setting DEFMSTR_TYPE to 0.
• DEFMSTR_TYPE: Default Master Type
0: No Default Master
At the end of the current slave access, if no other master request is pending, the slave is disconnected from all masters.
This results in a one cycle latency for the first access of a burst transfer or for a single access.
1: Last Default Master
At the end of the current slave access, if no other master request is pending, the slave stays connected to the last master having
accessed it.
This results in not having one cycle latency when the last master tries to access the slave again.
2: Fixed Default Master
At the end of the current slave access, if no other master request is pending, the slave connects to the fixed master the number
that has been written in the FIXED_DEFMSTR field.
This results in not having one cycle latency when the fixed master tries to access the slave again.
• SLOT_CYCLE: Maximum Number of Allowed Cycles for a Burst
When the SLOT_CYCLE limit is reached for a burst, it may be broken by another master trying to access this slave.
This limit has been placed to avoid locking a very slow slave when very long bursts are used.
This limit must not be very small. Unreasonably small values break every burst and the Bus Matrix arbitrates without performing
any data transfer. 16 cycles is a reasonable value for SLOT_CYCLE.
31 30 29 28 27 26 25 24
– – – – – – – ARBT
23 22 21 20 19 18 17 16
– – FIXED_DEFMSTR DEFMSTR_TYPE
15 14 13 12 11 10 9 8
––––––––
76543210
SLOT_CYCLE
193
32142D–06/2013
ATUC64/128/256L3/4U
11.5.3 Bus Matrix Priority Registers A For Slaves
Register Name: PRAS0...PRAS15
Access Type: Read/Write
Offset: -
Reset Value: 0x00000000
• MxPR: Master x Priority
Fixed priority of Master x for accessing the selected slave. The higher the number, the higher the priority.
31 30 29 28 27 26 25 24
- - M7PR - - M6PR
23 22 21 20 19 18 17 16
- - M5PR - - M4PR
15 14 13 12 11 10 9 8
- - M3PR - - M2PR
76543210
- - M1PR - - M0PR
194
32142D–06/2013
ATUC64/128/256L3/4U
11.5.4 Priority Registers B For Slaves
Name: PRBS0...PRBS15
Access Type: Read/Write
Offset: -
Reset Value: 0x00000000
• MxPR: Master x Priority
Fixed priority of Master x for accessing the selected slave. The higher the number, the higher the priority.
31 30 29 28 27 26 25 24
- - M15PR - - M14PR
23 22 21 20 19 18 17 16
- - M13PR - - M12PR
15 14 13 12 11 10 9 8
- - M11PR - - M10PR
76543210
- - M9PR - - M8PR
195
32142D–06/2013
ATUC64/128/256L3/4U
11.5.5 Special Function Registers
Name: SFR0...SFR15
Access Type: Read/Write
Offset: 0x110 - 0x14C
Reset Value: -
• SFR: Special Function Register Fields
Those registers are not a HMATRIX specific register. The field of those will be defined where they are used.
31 30 29 28 27 26 25 24
SFR
23 22 21 20 19 18 17 16
SFR
15 14 13 12 11 10 9 8
SFR
76543210
SFR
196
32142D–06/2013
ATUC64/128/256L3/4U
11.6 Module Configuration
The specific configuration for each HMATRIX instance is listed in the following tables.The module
bus clocks listed here are connected to the system bus clocks. Please refer to the Power
Manager chapter for details.
11.6.1 Bus Matrix Connections
The bus matrix has the several masters and slaves. Each master has its own bus and its own
decoder, thus allowing a different memory mapping per master. The master number in the table
below can be used to index the HMATRIX control registers. For example, HMATRIX MCFG0
register is associated with the CPU Data master interface.
Each slave has its own arbiter, thus allowing a different arbitration per slave. The slave number
in the table below can be used to index the HMATRIX control registers. For example, SCFG3 is
associated with the Internal SRAM Slave Interface.
Accesses to unused areas returns an error result to the master requesting such an access.
Table 11-3. HMATRIX Clocks
Clock Name Description
CLK_HMATRIX Clock for the HMATRIX bus interface
Table 11-4. High Speed Bus Masters
Master 0 CPU Data
Master 1 CPU Instruction
Master 2 CPU SAB
Master 3 SAU
Master 4 PDCA
Master 5 USBC
Table 11-5. High Speed Bus Slaves
Slave 0 Internal Flash
Slave 1 HSB-PB Bridge A
Slave 2 HSB-PB Bridge B
Slave 3 Internal SRAM
Slave 4 SAU
197
32142D–06/2013
ATUC64/128/256L3/4U
Figure 11-1. HMatrix Master / Slave Connections
CPU Data 0
CPU
Instruction 1
CPU SAB 2
SAU 3
Internal Flash
0
HSB-PB
Bridge 0
1
HSB-PB
Bridge 1
2
Internal SRAM
3
HMATRIX SLAVES
HMATRIX MASTERS
SAU
4
PDCA 4
USBC 5
198
32142D–06/2013
ATUC64/128/256L3/4U
12. Interrupt Controller (INTC)
Rev: 1.0.2.5
12.1 Features
• Autovectored low latency interrupt service with programmable priority
– 4 priority levels for regular, maskable interrupts
– One Non-Maskable Interrupt
• Up to 64 groups of interrupts with up to 32 interrupt requests in each group
12.2 Overview
The INTC collects interrupt requests from the peripherals, prioritizes them, and delivers an interrupt
request and an autovector to the CPU. The AVR32 architecture supports 4 priority levels for
regular, maskable interrupts, and a Non-Maskable Interrupt (NMI).
The INTC supports up to 64 groups of interrupts. Each group can have up to 32 interrupt request
lines, these lines are connected to the peripherals. Each group has an Interrupt Priority Register
(IPR) and an Interrupt Request Register (IRR). The IPRs are used to assign a priority level and
an autovector to each group, and the IRRs are used to identify the active interrupt request within
each group. If a group has only one interrupt request line, an active interrupt group uniquely
identifies the active interrupt request line, and the corresponding IRR is not needed. The INTC
also provides one Interrupt Cause Register (ICR) per priority level. These registers identify the
group that has a pending interrupt of the corresponding priority level. If several groups have a
pending interrupt of the same level, the group with the lowest number takes priority.
12.3 Block Diagram
Figure 12-1 gives an overview of the INTC. The grey boxes represent registers that can be
accessed via the user interface. The interrupt requests from the peripherals (IREQn) and the
NMI are input on the left side of the figure. Signals to and from the CPU are on the right side of
the figure.
199
32142D–06/2013
ATUC64/128/256L3/4U
Figure 12-1. INTC Block Diagram
12.4 Product Dependencies
In order to use this module, other parts of the system must be configured correctly, as described
below.
12.4.1 Power Management
If the CPU enters a sleep mode that disables CLK_SYNC, the INTC will stop functioning and
resume operation after the system wakes up from sleep mode.
12.4.2 Clocks
The clock for the INTC bus interface (CLK_INTC) is generated by the Power Manager. This
clock is enabled at reset, and can be disabled in the Power Manager.
The INTC sampling logic runs on a clock which is stopped in any of the sleep modes where the
system RC oscillator is not running. This clock is referred to as CLK_SYNC. This clock is
enabled at reset, and only turned off in sleep modes where the system RC oscillator is stopped.
12.4.3 Debug Operation
When an external debugger forces the CPU into debug mode, the INTC continues normal
operation.
12.5 Functional Description
All of the incoming interrupt requests (IREQs) are sampled into the corresponding Interrupt
Request Register (IRR). The IRRs must be accessed to identify which IREQ within a group that
is active. If several IREQs within the same group are active, the interrupt service routine must
prioritize between them. All of the input lines in each group are logically ORed together to form
the GrpReqN lines, indicating if there is a pending interrupt in the corresponding group.
The Request Masking hardware maps each of the GrpReq lines to a priority level from INT0 to
INT3 by associating each group with the Interrupt Level (INTLEVEL) field in the corresponding
Request
Masking
OR
IREQ0
IREQ1
IREQ2
IREQ31
GrpReq0
Masks SREG
Masks
I[3-0]M
GM
INTLEVEL
AUTOVECTOR
Prioritizer
Interrupt Controller CPU
OR GrpReqN
NMIREQ
OR
IREQ32
IREQ33
IREQ34
IREQ63
GrpReq1
IRR Registers IPR Registers ICR Registers
INT_level,
offset
INT_level,
offset
INT_level,
offset
IPR0
IPR1
IPRn
IRR0
IRR1
IRRn
ValReq0
ValReq1
ValReqN
.
.
.
.
.
.
.
.
.
200
32142D–06/2013
ATUC64/128/256L3/4U
Interrupt Priority Register (IPR). The GrpReq inputs are then masked by the mask bits from the
CPU status register. Any interrupt group that has a pending interrupt of a priority level that is not
masked by the CPU status register, gets its corresponding ValReq line asserted.
Masking of the interrupt requests is done based on five interrupt mask bits of the CPU status
register, namely Interrupt Level 3 Mask (I3M) to Interrupt Level 0 Mask (I0M), and Global Interrupt
Mask (GM). An interrupt request is masked if either the GM or the corresponding interrupt
level mask bit is set.
The Prioritizer hardware uses the ValReq lines and the INTLEVEL field in the IPRs to select the
pending interrupt of the highest priority. If an NMI interrupt request is pending, it automatically
gets the highest priority of any pending interrupt. If several interrupt groups of the highest pending
interrupt level have pending interrupts, the interrupt group with the lowest number is
selected.
The INTLEVEL and handler autovector offset (AUTOVECTOR) of the selected interrupt are
transmitted to the CPU for interrupt handling and context switching. The CPU does not need to
know which interrupt is requesting handling, but only the level and the offset of the handler
address. The IRR registers contain the interrupt request lines of the groups and can be read via
user interface registers for checking which interrupts of the group are actually active.
The delay through the INTC from the peripheral interrupt request is set until the interrupt request
to the CPU is set is three cycles of CLK_SYNC.
12.5.1 Non-Maskable Interrupts
A NMI request has priority over all other interrupt requests. NMI has a dedicated exception vector
address defined by the AVR32 architecture, so AUTOVECTOR is undefined when
INTLEVEL indicates that an NMI is pending.
12.5.2 CPU Response
When the CPU receives an interrupt request it checks if any other exceptions are pending. If no
exceptions of higher priority are pending, interrupt handling is initiated. When initiating interrupt
handling, the corresponding interrupt mask bit is set automatically for this and lower levels in status
register. E.g, if an interrupt of level 3 is approved for handling, the interrupt mask bits I3M,
I2M, I1M, and I0M are set in status register. If an interrupt of level 1 is approved, the masking
bits I1M and I0M are set in status register. The handler address is calculated by logical OR of
the AUTOVECTOR to the CPU system register Exception Vector Base Address (EVBA). The
CPU will then jump to the calculated address and start executing the interrupt handler.
Setting the interrupt mask bits prevents the interrupts from the same and lower levels to be
passed through the interrupt controller. Setting of the same level mask bit prevents also multiple
requests of the same interrupt to happen.
It is the responsibility of the handler software to clear the interrupt request that caused the interrupt
before returning from the interrupt handler. If the conditions that caused the interrupt are not
cleared, the interrupt request remains active.
12.5.3 Clearing an Interrupt Request
Clearing of the interrupt request is done by writing to registers in the corresponding peripheral
module, which then clears the corresponding NMIREQ/IREQ signal.
The recommended way of clearing an interrupt request is a store operation to the controlling
peripheral register, followed by a dummy load operation from the same register. This causes a
201
32142D–06/2013
ATUC64/128/256L3/4U
pipeline stall, which prevents the interrupt from accidentally re-triggering in case the handler is
exited and the interrupt mask is cleared before the interrupt request is cleared.
202
32142D–06/2013
ATUC64/128/256L3/4U
12.6 User Interface
Table 12-1. INTC Register Memory Map
Offset Register Register Name Access Reset
0x000 Interrupt Priority Register 0 IPR0 Read/Write 0x00000000
0x004 Interrupt Priority Register 1 IPR1 Read/Write 0x00000000
... ... ... ... ...
0x0FC Interrupt Priority Register 63 IPR63 Read/Write 0x00000000
0x100 Interrupt Request Register 0 IRR0 Read-only N/A
0x104 Interrupt Request Register 1 IRR1 Read-only N/A
... ... ... ... ...
0x1FC Interrupt Request Register 63 IRR63 Read-only N/A
0x200 Interrupt Cause Register 3 ICR3 Read-only N/A
0x204 Interrupt Cause Register 2 ICR2 Read-only N/A
0x208 Interrupt Cause Register 1 ICR1 Read-only N/A
0x20C Interrupt Cause Register 0 ICR0 Read-only N/A
203
32142D–06/2013
ATUC64/128/256L3/4U
12.6.1 Interrupt Priority Registers
Name: IPR0...IPR63
Access Type: Read/Write
Offset: 0x000 - 0x0FC
Reset Value: 0x00000000
• INTLEVEL: Interrupt Level
Indicates the EVBA-relative offset of the interrupt handler of the corresponding group:
00: INT0: Lowest priority
01: INT1
10: INT2
11: INT3: Highest priority
• AUTOVECTOR: Autovector Address
Handler offset is used to give the address of the interrupt handler. The least significant bit should be written to zero to give
halfword alignment.
31 30 29 28 27 26 25 24
INTLEVEL - - - - - -
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
- - AUTOVECTOR[13:8]
76543210
AUTOVECTOR[7:0]
204
32142D–06/2013
ATUC64/128/256L3/4U
12.6.2 Interrupt Request Registers
Name: IRR0...IRR63
Access Type: Read-only
Offset: 0x0FF - 0x1FC
Reset Value: N/A
• IRR: Interrupt Request line
This bit is cleared when no interrupt request is pending on this input request line.
This bit is set when an interrupt request is pending on this input request line.
The are 64 IRRs, one for each group. Each IRR has 32 bits, one for each possible interrupt request, for a total of 2048 possible
input lines. The IRRs are read by the software interrupt handler in order to determine which interrupt request is pending. The
IRRs are sampled continuously, and are read-only.
31 30 29 28 27 26 25 24
IRR[32*x+31] IRR[32*x+30] IRR[32*x+29] IRR[32*x+28] IRR[32*x+27] IRR[32*x+26] IRR[32*x+25] IRR[32*x+24]
23 22 21 20 19 18 17 16
IRR[32*x+23] IRR[32*x+22] IRR[32*x+21] IRR[32*x+20] IRR[32*x+19] IRR[32*x+18] IRR[32*x+17] IRR[32*x+16]
15 14 13 12 11 10 9 8
IRR[32*x+15] IRR[32*x+14] IRR[32*x+13] IRR[32*x+12] IRR[32*x+11] IRR[32*x+10] IRR[32*x+9] IRR[32*x+8]
76543210
IRR[32*x+7] IRR[32*x+6] IRR[32*x+5] IRR[32*x+4] IRR[32*x+3] IRR[32*x+2] IRR[32*x+1] IRR[32*x+0]
205
32142D–06/2013
ATUC64/128/256L3/4U
12.6.3 Interrupt Cause Registers
Name: ICR0...ICR3
Access Type: Read-only
Offset: 0x200 - 0x20C
Reset Value: N/A
• CAUSE: Interrupt Group Causing Interrupt of Priority n
ICRn identifies the group with the highest priority that has a pending interrupt of level n. This value is only defined when at least
one interrupt of level n is pending.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
- - CAUSE
206
32142D–06/2013
ATUC64/128/256L3/4U
12.7 Module Configuration
The specific configuration for each INTC instance is listed in the following tables.The module
bus clocks listed here are connected to the system bus clocks. Please refer to the Power Manager
chapter for details.
12.7.1 Interrupt Request Signal Map
12.8 Interrupt Request Signal Map
The various modules may output Interrupt request signals. These signals are routed to the Interrupt
Controller (INTC), described in a later chapter. The Interrupt Controller supports up to 64
groups of interrupt requests. Each group can have up to 32 interrupt request signals. All interrupt
signals in the same group share the same autovector address and priority level. Refer to the
documentation for the individual submodules for a description of the semantics of the different
interrupt requests.
The interrupt request signals are connected to the INTC as follows.
Table 12-2. INTC Clock Name
Module Name Clock Name Description
INTC CLK_INTC Clock for the INTC bus interface
Table 12-3. Interrupt Request Signal Map
Group Line Module Signal
0 0 AVR32UC3 CPU SYSREG COMPARE
1
0 AVR32UC3 CPU OCD DCEMU_DIRTY
1 AVR32UC3 CPU OCD DCCPU_READ
2 0 Flash Controller FLASHCDW
3 0 Secure Access Unit SAU
4
0 Peripheral DMA Controller PDCA 0
1 Peripheral DMA Controller PDCA 1
2 Peripheral DMA Controller PDCA 2
3 Peripheral DMA Controller PDCA 3
5
0 Peripheral DMA Controller PDCA 4
1 Peripheral DMA Controller PDCA 5
2 Peripheral DMA Controller PDCA 6
3 Peripheral DMA Controller PDCA 7
6
0 Peripheral DMA Controller PDCA 8
1 Peripheral DMA Controller PDCA 9
2 Peripheral DMA Controller PDCA 10
3 Peripheral DMA Controller PDCA 11
7 0 Power Manager PM
207
32142D–06/2013
ATUC64/128/256L3/4U
8 0 System Control Interface SCIF
9 0 Asynchronous Timer AST ALARM
10
0 Asynchronous Timer AST PER
1 Asynchronous Timer AST OVF
2 Asynchronous Timer AST READY
3 Asynchronous Timer AST CLKREADY
11
0 External Interrupt Controller EIC 1
1 External Interrupt Controller EIC 2
2 External Interrupt Controller EIC 3
3 External Interrupt Controller EIC 4
12 0 External Interrupt Controller EIC 5
13 0 Frequency Meter FREQM
14
0 General-Purpose Input/Output Controller GPIO 0
1 General-Purpose Input/Output Controller GPIO 1
2 General-Purpose Input/Output Controller GPIO 2
3 General-Purpose Input/Output Controller GPIO 3
4 General-Purpose Input/Output Controller GPIO 4
5 General-Purpose Input/Output Controller GPIO 5
6 General-Purpose Input/Output Controller GPIO 6
7 General-Purpose Input/Output Controller GPIO 7
15 0 Universal Synchronous Asynchronous
Receiver Transmitter USART0
16 0 Universal Synchronous Asynchronous
Receiver Transmitter USART1
17 0 Universal Synchronous Asynchronous
Receiver Transmitter USART2
18 0 Universal Synchronous Asynchronous
Receiver Transmitter USART3
19 0 Serial Peripheral Interface SPI
20 0 Two-wire Master Interface TWIM0
21 0 Two-wire Master Interface TWIM1
22 0 Two-wire Slave Interface TWIS0
23 0 Two-wire Slave Interface TWIS1
24 0 Pulse Width Modulation Controller PWMA
25
0 Timer/Counter TC00
1 Timer/Counter TC01
2 Timer/Counter TC02
Table 12-3. Interrupt Request Signal Map
208
32142D–06/2013
ATUC64/128/256L3/4U
26
0 Timer/Counter TC10
1 Timer/Counter TC11
2 Timer/Counter TC12
27 0 ADC Interface ADCIFB
28 0 Analog Comparator Interface ACIFB
29 0 Capacitive Touch Module CAT
30 0 aWire AW
31 0 Audio Bitstream DAC ABDACB
32 0 USB 2.0 Interface USBC
33 0 Inter-IC Sound (I2S) Controller IISC
Table 12-3. Interrupt Request Signal Map
209
32142D–06/2013
ATUC64/128/256L3/4U
13. Power Manager (PM)
Rev: 4.2.0.4
13.1 Features
• Generates clocks and resets for digital logic
• On-the-fly frequency change of CPU, HSB and PBx clocks
• Sleep modes allow simple disabling of logic clocks and clock sources
• Module-level clock gating through maskable peripheral clocks
• Wake-up from internal or external interrupts
• Automatic identification of reset sources
• Supports advanced Shutdown sleep mode
13.2 Overview
The Power Manager (PM) provides synchronous clocks used to clock the main digital logic in the
device, namely the CPU, and the modules and peripherals connected to the High Speed Bus
(HSB) and the Peripheral Buses (PBx).
The PM contains advanced power-saving features, allowing the user to optimize the power consumption
for an application. The synchronous clocks are divided into a number of clock
domains, one for the CPU and HSB, and one for each PBx. The clocks can run at different
speeds, allowing the user to save power by running peripherals relatively slow, whilst maintaining
high CPU performance. The clocks can be independently changed on-the-fly, without halting
any peripherals. The user may adjust CPU and memory speeds according to the dynamic application
load, without disturbing or re-configuring active peripherals.
Each module has a separate clock, enabling the user to save power by switching off clocks to
inactive modules. Clocks and oscillators can be automatically switched off during idle periods by
the CPU sleep instruction. The system will return to normal operation when interrupts occur.
To achieve minimal power usage, a special sleep mode, called Shutdown is available, where
power on all internal logic (CPU, peripherals) and most of the I/O lines is removed, reducing current
leakage. Only a small amount of logic, including the 32KHz crystal oscillator (OSC32K) and
the AST remain powered.
The Power Manager also contains a Reset Controller, which collects all possible reset sources,
generates hard and soft resets, and allows the reset source to be identified by software.
210
32142D–06/2013
ATUC64/128/256L3/4U
13.3 Block Diagram
Figure 13-1. PM Block Diagram
13.4 I/O Lines Description
13.5 Product Dependencies
13.5.1 Interrupt
The PM interrupt line is connected to one of the interrupt controllers internal sources. Using the
PM interrupt requires the interrupt controller to be configured first.
13.5.2 Clock Implementation
In ATUC64/128/256L3/4U, the HSB shares source clock with the CPU. Write attempts to the
HSB Clock Select register (HSBSEL) will be ignored, and it will always read the same as the
CPU Clock Select register (CPUSEL).
The PM bus interface clock (CLK_PM) is generated by the Power Manager. This clock is
enabled at reset, and can be disabled in the Power Manager. If disabled it can only be reenabled
by a reset.
13.5.3 Power Considerations
The Shutdown mode is only available for the “3.3V supply mode, with 1.8V regulated I/O lines“
power configuration.
Table 13-1. I/O Lines Description
Name Description Type Active Level
RESET_N Reset Input Low
Sleep Controller
Synchronous
Clock Generator
Reset Controller
Main Clock Sources
Sleep
Instruction
Power-on Reset
Detector(s)
Resets
Synchronous
clocks
CPU, HSB,
PBx
Interrupts
External Reset Pin
Reset Sources
211
32142D–06/2013
ATUC64/128/256L3/4U
13.6 Functional Description
13.6.1 Synchronous Clocks
The System RC Oscillator (RCSYS) and a selection of other clock sources can provide the
source for the main clock, which is the origin for the synchronous CPU/HSB and PBx module
clocks. For details about the other main clock sources, please refer to the Main Clock Control
(MCCTRL) register description. The synchronous clocks can run of the main clock and all the 8-
bit prescaler settings as long as fCPU fPBx,. The synchronous clock source can be changed onthe
fly, according to variations in application load. The clock domains can be shut down in sleep
mode, as described in Section 13.6.3. The module clocks in every synchronous clock domain
can be individually masked to minimize power consumption in inactive modules.
Figure 13-2. Synchronous Clock Generation
13.6.1.1 Selecting the main clock source
The common main clock can be connected to RCSYS or a selection of other clock sources. For
details about the other main clock sources, please refer to the MCCTRL register description. By
default, the main clock will be connected to RCSYS. The user can connect the main clock to
another source by writing to the Main Clock Select (MCCTRL.MCSEL) field. The user must first
assure that the source is enabled and ready in order to avoid a deadlock. Care should also be
taken so that the new synchronous clock frequencies do not exceed the maximum frequency for
each clock domain.
13.6.1.2 Selecting synchronous clock division ratio
The main clock feeds an 8-bit prescaler, which can be used to generate the synchronous clocks.
By default, the synchronous clocks run on the undivided main clock. The user can select a prescaler
division for the CPU clock by writing a one to the CPU Division bit in the CPU Clock Select
register (CPUSEL.CPUDIV), and a value to the CPU Clock Select field (CPUSEL.CPUSEL),
resulting in a CPU clock frequency:
fCPU = fmain / 2(CPUSEL+1)
Mask
Prescaler Main Clock
Sources
MCSEL
0
1
CPUSEL
CPUDIV
Main Clock
Sleep
Controller
CPUMASK
CPU Clocks
HSB Clocks
PBx Clocks
Sleep
Instruction
212
32142D–06/2013
ATUC64/128/256L3/4U
Similarly, the PBx clocks can be divided by writing their respective Clock Select (PBxSEL) registers
to get the divided PBx frequency:
fPBx = fmain / 2(PBSEL+1)
The PBx clock frequency can not exceed the CPU clock frequency. The user must select a PBxSEL.PBSEL
value greater than or equal to the CPUSEL.CPUSEL value, so that fCPU fPBx. If the
user selects division factors that will result in fCPU< fPBx, the Power Manager will automatically
change the PBxSEL.PBSEL/PBDIV values to ensure correct operation (fCPU fPBx).
The HSB clock will always be forced to the same division as the CPU clock.
To ensure correct operation, the frequencies must never exceed the specified maximum frequency
for each clock domain.
For modules connected to the HSB bus, the PB clock frequency must be the same as the CPU
clock frequency.
13.6.1.3 Clock Ready flag
There is a slight delay from CPUSEL and PBxSEL being written to the new clock setting taking
effect. During this interval, the Clock Ready bit in the Status Register (SR.CKRDY) will read as
zero. When the clock settings change is completed, the bit will read as one. The Clock Select
registers (CPUSEL, PBxSEL) must not be written to while SR.CKRDY is zero, or the system
may become unstable or hang.
The Clock Ready bit in the Interrupt Status Register (ISR.CKRDY) is set on a SR.CKRDY zeroto-one
transition. If the Clock Ready bit in the Interrupt Mask Register (IMR.CKRDY) is set, an
interrupt request is generated. IMR.CKRDY is set by writing a one to the corresponding bit in the
Interrupt Enable Register (IER.CKRDY).
13.6.2 Peripheral Clock Masking
By default, the clocks for all modules are enabled, regardless of which modules are actually
being used. It is possible to disable the clock for a module in the CPU, HSB, or PBx clock
domain by writing a zero to the corresponding bit in the corresponding Clock Mask (CPUMASK/HSBMASK/PBxMASK)
register. When a module is not clocked, it will cease operation,
and its registers cannot be read nor written. The module can be re-enabled later by writing a one
to the corresponding mask bit. A module may be connected to several clock domains, in which
case it will have several mask bits. The Maskable Module Clocks table in the Clock Mask register
description contains a list of implemented maskable clocks.
13.6.2.1 Cautionary note
Note that clocks should only be switched off if it is certain that the module will not be used.
Switching off the clock for the Flash Controller will cause a problem if the CPU needs to read
from the flash. Switching off the clock to the Power Manager, which contains the mask registers,
or the corresponding PBx bridge, will make it impossible to write to the mask registers again. In
this case, they can only be re-enabled by a system reset.
13.6.3 Sleep Modes
In normal operation, all clock domains are active, allowing software execution and peripheral
operation. When the CPU is idle, it is possible to switch it and other (optional) clock domains off
to save power. This is done by the sleep instruction, which takes the sleep mode index number
from Table 13-2 on page 213 as argument.
213
32142D–06/2013
ATUC64/128/256L3/4U
13.6.3.1 Entering and exiting sleep modes
The sleep instruction will halt the CPU and all modules belonging to the stopped clock domains.
The modules will be halted regardless of the bit settings in the mask registers.
Clock sources can also be switched off to save power. Some of these have a relatively long
start-up time, and are only switched off when very low power consumption is required.
The CPU and affected modules are restarted when the sleep mode is exited. This occurs when
an interrupt triggers. Note that even if an interrupt is enabled in sleep mode, it may not trigger if
the source module is not clocked.
13.6.3.2 Supported sleep modes
The following sleep modes are supported. These are detailed in Table 13-2 on page 213.
• Idle: The CPU is stopped, the rest of the device is operational.
• Frozen: The CPU and HSB modules are stopped, peripherals are operational.
• Standby: All synchronous clocks are stopped, and the clock sources are running, allowing for
a quick wake-up to normal mode.
• Stop: As Standby, but oscillators, and other clock sources are also stopped. 32KHz Oscillator
OSC32K(2), RCSYS, AST, and WDT will remain operational.
• DeepStop: All synchronous clocks and clock sources are stopped. Bandgap voltage
reference and BOD are turned off. OSC32K(2) and RCSYS remain operational.
• Static: All clock sources, including RCSYS are stopped. Bandgap voltage reference and BOD
are turned off. OSC32K(2) remains operational.
• Shutdown: All clock sources, including RCSYS are stopped. Bandgap voltage reference,
BOD detector, and Voltage regulator are turned off. OSC32K(2) remains operational. This
mode can only be used in the “3.3V supply mode, with 1.8V regulated I/O lines“
configuration (described in Power Considerations chapter). Refer to Section 13.6.4 for more
details.
Notes: 1. The sleep mode index is used as argument for the sleep instruction.
2. OSC32K will only remain operational if pre-enabled.
3. Clock sources other than those specifically listed in the table.
4. SYSTIMER is the clock for the CPU COUNT and COMPARE registers.
The internal voltage regulator is also adjusted according to the sleep mode in order to reduce its
power consumption.
Table 13-2. Sleep Modes
Index(1) Sleep Mode CPU HSB
PBx,
GCLK
Clock Sources(3),
SYSTIMER(4) OSC32K(2) RCSYS
BOD &
Bandgap
Voltage
Regulator
0 Idle Stop Run Run Run Run Run On Normal mode
1 Frozen Stop Stop Run Run Run Run On Normal mode
2 Standby Stop Stop Stop Run Run Run On Normal mode
3 Stop Stop Stop Stop Stop Run Run On Low power mode
4 DeepStop Stop Stop Stop Stop Run Run Off Low power mode
5 Static Stop Stop Stop Stop Run Stop Off Low power mode
6 Shutdown Stop Stop Stop Stop Run Stop Off Off
214
32142D–06/2013
ATUC64/128/256L3/4U
13.6.3.3 Waking from sleep modes
There are two types of wake-up sources from sleep mode, synchronous and asynchronous.
Synchronous wake-up sources are all non-masked interrupts. Asynchronous wake-up sources
are AST, WDT, external interrupts from EIC, external reset, external wake pin (WAKE_N), and
all asynchronous wake-ups enabled in the Asynchronous Wake Up Enable (AWEN) register. The
valid wake-up sources for each sleep mode are detailed in Table 13-3 on page 214.
In Shutdown the only wake-up sources are external reset, external wake-up pin or AST. See
Section 13.6.4.3 on page 216.
Notes: 1. The sleep mode index is used as argument for the sleep instruction.
2. Only PB modules operational, as HSB module clocks are stopped.
3. WDT only available if clocked from pre-enabled OSC32K.
13.6.3.4 SleepWalking
In all sleep modes where the PBx clocks are stopped, except for Shutdown mode, the device
can partially wake up if a PBx module asynchronously discovers that it needs its clock. Only the
requested clocks and clock sources needed will be started, all other clocks will remain masked
to zero. E.g. if the main clock source is OSC0, only OSC0 will be started even if other clock
sources were enabled in normal mode. Generic clocks can also be started in a similar way. The
state where only requested clocks are running is referred to as SleepWalking.
The time spent to start the requested clock is mostly limited by the startup time of the given clock
source. This allows PBx modules to handle incoming requests, while still keeping the power consumption
at a minimum.
When the device is SleepWalking any asynchronous wake-up can wake the device up at any
time without stopping the requested PBx clock.
All requests to start clocks can be masked by writing to the Peripheral Power Control Register
(PPCR), all requests are enabled at reset.
During SleepWalking the interrupt controller clock will be running. If an interrupt is pending when
entering SleepWalking, it will wake the whole device up.
13.6.3.5 Precautions when entering sleep mode
Modules communicating with external circuits should normally be disabled before entering a
sleep mode that will stop the module operation. This will prevent erratic behavior caused by
entering or exiting sleep modes. Please refer to the relevant module documentation for recommended
actions.
Table 13-3. Wake-up Sources
Index(1) Sleep Mode Wake-up Sources
0 Idle Synchronous, Asynchronous
1 Frozen Synchronous(2), Asynchronous
2 Standby Asynchronous
3 Stop Asynchronous
4 DeepStop Asynchronous
5 Static Asynchronous(3)
6 Shutdown External reset, External wake-up pin
215
32142D–06/2013
ATUC64/128/256L3/4U
Communication between the synchronous clock domains is disturbed when entering and exiting
sleep modes. Bus transactions over clock domains affected by the sleep mode are therefore not
recommended. The system may hang if the bus clocks are stopped during a bus transaction.
The CPU is automatically stopped in a safe state to ensure that all CPU bus operations are complete
when the sleep mode goes into effect. Thus, when entering Idle mode, no further action is
necessary.
When entering a sleep mode (except Idle mode), all HSB masters must be stopped before
entering the sleep mode. In order to let potential PBx write operations complete, the user should
let the CPU perform a PBx register read operation before issuing the sleep instruction. This will
stall the CPU until pending PBx operations have completed.
The Shutdown sleep mode requires extra care. Please refer to Section 13.6.4.
13.6.4 Shutdown Sleep Mode
13.6.4.1 Description
The Shutdown sleep mode is available only when the device is used in the “3.3V supply mode,
with 1.8V regulated I/O lines“ configuration (refer to the Power Considerations chapter). In this
configuration, the voltage regulator supplies both VDDCORE and VDDIO power supplies.
When the device enters Shutdown mode, the regulator is turned off and only the following logic
is kept powered by VDDIN:
– OSC32K using alternate pinout PA13/PA20
– AST core logic (internal counter and alarm detection logic)
– Backup Registers
– I/O lines PA11, PA13, PA20, PA21, PB04, PB05, and PB10
– RESET_N line
The table below lists I/O line functionality that remains operational during Shutdown sleep mode.
If no special function is used the I/O line will keep its setting when entering the sleep mode
13.6.4.2 Entering Shutdown sleep mode
Before entering the Shutdown sleep mode, a few actions are required:
– All modules should normally be disabled before entering Shutdown sleep mode (see
Section 13.6.3.5)
Table 13-4. I/O Lines Usage During Shutdown Mode
Pin Possible Usage During Shutdown Sleep Mode
PA11 WAKE_N signal (active low wake-up)
PA13 XIN32_2 (OSC32K using alternate pinout)
PA20 XOUT32_2 (OSC32K using alternate pinout)
PA21
PB04
PB05
PB10
RESET_N Reset pin
216
32142D–06/2013
ATUC64/128/256L3/4U
– The POR33 must be masked to avoid spurious resets when the power is back. This
must also be done when POR33 is disabled, as POR33 will be enabled
automatically when the device wakes up from Shutdown mode. Disable the POR33
by writing a one to the POR33MASK bit in the SCIF.VREGCR register. Due to
internal synchronisation, this bit must be read as a one before the sleep instruction is
executed by the CPU. Refer to the System Control Interface (SCIF) chapter for more
details.
– The 32KHz RC oscillator (RC32K) must be running and stable. This is done by
writing a one to the EN bit in the SCIF.RC32KCR register. Due to internal
synchronisation, this bit must be read as a one to ensure that the oscillator is stable
before the sleep instruction is executed by the CPU.
As soon as the Shutdown sleep mode is entered, all CPU and peripherals are reset to ensure a
consistent state. POR33 and RC32K are automatically disabled to save extra power.
13.6.4.3 Leaving Shutdown sleep mode
Exiting Shutdown sleep mode can be done by the events described in Table 13-5.
When a wake-up event occurs, the regulator is turned on and the device will wait for VDDCORE
to be valid before starting. The Sleep Reset bit in the Reset Cause register (RCAUSE.SLEEP) is
then set, allowing software running on the device to distinguish between the first power-up and a
wake-up from Shutdown mode.
13.6.4.4 Special consideration regarding waking up from Shutdown sleep mode using the WAKE_N pin
By default, the WAKE_N pin will only wake the device up if it is pulled low after entering Shutdown
mode. If the WAKE_N is pulled low before the Shutdown mode is entered, it will not wake
the device from the Shutdown sleep mode. In order to wake the device by pulling WAKE_N low
before entering Shutdown mode, the user has to write a one to the bit corresponding to the
WAKEN wake-up source in the AWEN register. In this scenario, the CPU execution will proceed
with the next instruction, and the RCAUSE register content will not be altered.
13.6.5 Divided PB Clocks
The clock generator in the Power Manager provides divided PBx clocks for use by peripherals
that require a prescaled PBx clock. This is described in the documentation for the relevant modules.
The divided clocks are directly maskable, and are stopped in sleep modes where the PBx
clocks are stopped.
Table 13-5. Events That Can Wake up the Device from Shutdown Mode
Source How
PA11 (WAKE_N) Pulling-down PA11 will wake up the device
RESET_N
Pulling-down RESET_N pin will wake up the device
The device is kept under reset until RESET_N is tied high
again
AST
OSC32K must be set-up to use alternate pinout (XIN32_2
and XOUT32_2) Refer to the SCIF Chapter
AST must be configured to use the clock from OSC32K
AST must be configured to allow alarm, periodic, or
overflow wake-up
217
32142D–06/2013
ATUC64/128/256L3/4U
13.6.6 Reset Controller
The Reset Controller collects the various reset sources in the system and generates hard and
soft resets for the digital logic.
The device contains a Power-on Reset (POR) detector, which keeps the system reset until
power is stable. This eliminates the need for external reset circuitry to guarantee stable operation
when powering up the device.
It is also possible to reset the device by pulling the RESET_N pin low. This pin has an internal
pull-up, and does not need to be driven externally during normal operation. Table 13-6 on page
217 lists these and other reset sources supported by the Reset Controller.
Figure 13-3. Reset Controller Block Diagram
In addition to the listed reset types, the JTAG & aWire can keep parts of the device statically
reset. See JTAG and aWire documentation for details.
Table 13-6. Reset Description
Reset Source Description
Power-on Reset Supply voltage below the Power-on Reset detector threshold
voltage VPOT
External Reset RESET_N pin asserted
Brown-out Reset VDDCORE supply voltage below the Brown-out detector
threshold voltage
JTAG
Reset
Controller
RESET_N
Power-on Reset
Detector(s)
OCD
Watchdog Reset
RCAUSE
CPU, HSB, PBx
OCD, AST, WDT,
Clock Generator
Brown-out
Detector
AWIRE
SM33 Detector
218
32142D–06/2013
ATUC64/128/256L3/4U
Depending on the reset source, when a reset occurs, some parts of the device are not always
reset. Only the Power-on Reset (POR) will force a whole device reset. Refer to the table in the
Module Configuration section at the end of this chapter for further details. The latest reset cause
can be read in the RCAUSE register, and can be read during the applications boot sequence in
order to determine proper action.
13.6.6.1 Power-on Reset Detector
The Power-on Reset 1.8V (POR18) detector monitors the VDDCORE supply pin and generates
a Power-on Reset (POR) when the device is powered on. The POR is active until the
VDDCORE voltage is above the power-on threshold level (VPOT). The POR will be re-generated
if the voltage drops below the power-on threshold level. See Electrical Characteristics for parametric
details.
The Power-on Reset 3.3V (POR33) detector monitors the internal regulator supply pin and generates
a Power-on Reset (POR) when the device is powered on. The POR is active until the
internal regulator supply voltage is above the regulator power-on threshold level (VPOT). The
POR will be re-generated if the voltage drops below the regulator power-on threshold level. See
Electrical Characteristics for parametric details.
13.6.6.2 External Reset
The external reset detector monitors the RESET_N pin state. By default, a low level on this pin
will generate a reset.
13.6.7 Clock Failure Detector
This mechanism automatically switches the main clock source to the safe RCSYS clock when
the main clock source fails. This may happen when an external crystal is selected as a source
for the main clock and the crystal is not mounted on the board. The main clock is compared with
RCSYS, and if no rising edge of the main clock is detected during one RCSYS period, the clock
is considered to have failed.
The detector is enabled by writing a one to the Clock Failure Detection Enable bit in the Clock
Failure Detector Control Register (CFDCTRL.CFDEN). As soon as the detector is enabled, the
clock failure detector will monitor the divided main clock. Note that the detector does not monitor
the main clock if RCSYS is the source of the main clock, or if the main clock is temporarily not
available (startup-time after a wake-up, switching timing etc.), or in sleep mode where the main
clock is driven by the RCSYS (Stop and DeepStop mode). When a clock failure is detected, the
main clock automatically switches to the RCSYS clock and the Clock Failure Detected (CFD)
interrupt is generated if enabled. The MCCTRL register is also changed by hardware to indicate
that the main clock comes from RCSYS.
13.6.8 Interrupts
The PM has a number of interrupt sources:
• AE - Access Error,
SM33 Reset Internal regulator supply voltage below the SM33 threshold
voltage. This generates a Power-on Reset.
Watchdog Timer See Watchdog Timer documentation
OCD See On-Chip Debug documentation
Reset Source Description
219
32142D–06/2013
ATUC64/128/256L3/4U
– A lock protected register is written to without first being unlocked.
• CKRDY - Clock Ready:
– New Clock Select settings in the CPUSEL/PBxSEL registers have taken effect. (A
zero-to-one transition on SR.CKRDY is detected).
• CFD - Clock Failure Detected:
– The system detects that the main clock is not running.
The Interrupt Status Register contains one bit for each interrupt source. A bit in this register is
set on a zero-to-one transition of the corresponding bit in the Status Register (SR), and cleared
by writing a one to the corresponding bit in the Interrupt Clear Register (ICR). The interrupt
sources will generate an interrupt request if the corresponding bit in the Interrupt Mask Register
is set. The interrupt sources are ORed together to form one interrupt request. The Power Manager
will generate an interrupt request if at least one of the bits in the Interrupt Mask Register
(IMR) is set. Bits in IMR are set by writing a one to the corresponding bit in the Interrupt Enable
Register (IER), and cleared by writing a one to the corresponding bit in the Interrupt Disable
Register (IDR). The interrupt request remains active until the corresponding bit in the Interrupt
Status Register (ISR) is cleared by writing a one to the corresponding bit in the Interrupt Clear
Register (ICR). Because all the interrupt sources are ORed together, the interrupt request from
the Power Manager will remain active until all the bits in ISR are cleared.
220
32142D–06/2013
ATUC64/128/256L3/4U
13.7 User Interface
Note: 1. The reset value is device specific. Please refer to the Module Configuration section at the end of this chapter.
2. Latest Reset Source.
3. Latest Wake Source.
Table 13-7. PM Register Memory Map
Offset Register Register Name Access Reset
0x000 Main Clock Control MCCTRL Read/Write 0x00000000
0x004 CPU Clock Select CPUSEL Read/Write 0x00000000
0x008 HSB Clock Select HSBSEL Read-only 0x00000000
0x00C PBA Clock Select PBASEL Read/Write 0x00000000
0x010 PBB Clock Select PBBSEL Read/Write 0x00000000
0x014 - 0x01C Reserved
0x020 CPU Mask CPUMASK Read/Write 0x00010001
0x024 HSB Mask HSBMASK Read/Write 0x0000007F
0x028 PBA Mask PBAMASK Read/Write 0x0FFFFFFF
0x02C PBB Mask PBBMASK Read/Write 0x0000000F
0x030- 0x03C Reserved
0x040 PBA Divided Mask PBADIVMASK Read/Write 0x0000007F
0x044 - 0x050 Reserved
0x054 Clock Failure Detector Control CFDCTRL Read/Write 0x00000000
0x058 Unlock Register UNLOCK Write-only 0x00000000
0x05C - 0x0BC Reserved
0x0C0 Interrupt Enable Register IER Write-only 0x00000000
0x0C4 Interrupt Disable Register IDR Write-only 0x00000000
0x0C8 Interrupt Mask Register IMR Read-only 0x00000000
0x0CC Interrupt Status Register ISR Read-only 0x00000000
0x0D0 Interrupt Clear Register ICR Write-only 0x00000000
0x0D4 Status Register SR Read-only 0x00000020
0x0D8 - 0x15C Reserved
0x160 Peripheral Power Control Register PPCR Read/Write 0x000001FA
0x164 - 0x17C Reserved
0x180 Reset Cause Register RCAUSE Read-only -(2)
0x184 Wake Cause Register WCAUSE Read-only -(3)
0x188 Asynchronous Wake Up Enable Register AWEN Read/Write 0x00000000
0x18C - 0x3F4 Reserved
0x3F8 Configuration Register CONFIG Read-only 0x00000043
0x3FC Version Register VERSION Read-only -(1)
221
32142D–06/2013
ATUC64/128/256L3/4U
13.7.1 Main Clock Control
Name: MCCTRL
Access Type: Read/Write
Offset: 0x000
Reset Value: 0x00000000
• MCSEL: Main Clock Select
Note: 1. If the 120MHz RC oscillator is selected as main clock source, it must be divided by at least 4 before being used as clock
source for the CPU. This division is selected by writing to the CPUSEL and CPUDIV bits in the CPUSEL register, before
switching to RC120M as main clock source.
Note that this register is protected by a lock. To write to this register the UNLOCK register has to be written first. Please
refer to the UNLOCK register description for details.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
- - - - - MCSEL
Table 13-8. Main clocks in ATUC64/128/256L3/4U.
MCSEL[2:0] Main clock source
0 System RC oscillator (RCSYS)
1 Oscillator0 (OSC0)
2 DFLL
3 120MHz RC oscillator
(RC120M)(1)
222
32142D–06/2013
ATUC64/128/256L3/4U
13.7.2 CPU Clock Select
Name: CPUSEL
Access Type: Read/Write
Offset: 0x004
Reset Value: 0x00000000
• CPUDIV, CPUSEL: CPU Division and Clock Select
CPUDIV = 0: CPU clock equals main clock.
CPUDIV = 1: CPU clock equals main clock divided by 2(CPUSEL+1).
Note that if CPUDIV is written to 0, CPUSEL should also be written to 0 to ensure correct operation.
Also note that writing this register clears POSCSR.CKRDY. The register must not be re-written until CKRDY goes high.
Note that this register is protected by a lock. To write to this register the UNLOCK register has to be written first. Please
refer to the UNLOCK register description for details.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
CPUDIV - - - - CPUSEL
223
32142D–06/2013
ATUC64/128/256L3/4U
13.7.3 HSB Clock Select
Name: HSBSEL
Access Type: Read
Offset: 0x008
Reset Value: 0x00000000
This register is read-only and its content is always equal to CPUSEL.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
HSBDIV - - - - HSBSEL
224
32142D–06/2013
ATUC64/128/256L3/4U
13.7.4 PBx Clock Select
Name: PBxSEL
Access Type: Read/Write
Offset: 0x00C-0x010
Reset Value: 0x00000000
• PBDIV, PBSEL: PBx Division and Clock Select
PBDIV = 0: PBx clock equals main clock.
PBDIV = 1: PBx clock equals main clock divided by 2(PBSEL+1).
Note that if PBDIV is written to 0, PBSEL should also be written to 0 to ensure correct operation.
Also note that writing this register clears SR.CKRDY. The register must not be re-written until SR.CKRDY is set.
Note that this register is protected by a lock. To write to this register the UNLOCK register has to be written first. Please
refer to the UNLOCK register description for details.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
PBDIV - - - - PBSEL
225
32142D–06/2013
ATUC64/128/256L3/4U
13.7.5 Clock Mask
Name: CPUMASK/HSBMASK/PBAMASK/PBBMASK
Access Type: Read/Write
Offset: 0x020-0x02C
Reset Value: -
• MASK: Clock Mask
If bit n is cleared, the clock for module n is stopped. If bit n is set, the clock for module n is enabled according to the current
power mode. The number of implemented bits in each mask register, as well as which module clock is controlled by each bit, is
shown in Table 13-9.
31 30 29 28 27 26 25 24
MASK[31:24]
23 22 21 20 19 18 17 16
MASK[23:16]
15 14 13 12 11 10 9 8
MASK[15:8]
76543210
MASK[7:0]
Table 13-9. Maskable Module Clocks in ATUC64/128/256L3/4U.
Bit CPUMASK HSBMASK PBAMASK PBBMASK
0 OCD PDCA PDCA FLASHCDW
1 - FLASHCDW INTC HMATRIX
2 - SAU PM SAU
3 - PBB bridge SCIF USBC
4 - PBA bridge AST -
5 - Peripheral Event System WDT -
6 - USBC EIC -
7 - - FREQM -
8 - - GPIO -
9 - - USART0 -
10 - - USART1 -
11 - - USART2 -
226
32142D–06/2013
ATUC64/128/256L3/4U
Note that this register is protected by a lock. To write to this register the UNLOCK register has to be written first. Please
refer to the UNLOCK register description for details.
12 - - USART3 -
13 - - SPI -
14 - - TWIM0 -
15 - - TWIM1 -
16 SYSTIMER - TWIS0 -
17 - - TWIS1 -
18 - - PWMA -
19 - - TC0 -
20 - - TC1 -
21 - - ADCIFB -
22 - - ACIFB -
23 - - CAT -
24 - - GLOC -
25 - - AW -
26 - - ABDACB -
27 - - IISC -
31:28 - - - -
Table 13-9. Maskable Module Clocks in ATUC64/128/256L3/4U.
Bit CPUMASK HSBMASK PBAMASK PBBMASK
227
32142D–06/2013
ATUC64/128/256L3/4U
13.7.6 PBA Divided Mask
Name: PBADIVMASK
Access Type: Read/Write
Offset: 0x040
Reset Value: 0x0000007F
• MASK: Clock Mask
If bit n is written to zero, the clock divided by 2(n+1) is stopped. If bit n is written to one, the clock divided by 2(n+1) is enabled
according to the current power mode. Table 13-10 shows what clocks are affected by the different MASK bits.
Note that this register is protected by a lock. To write to this register the UNLOCK register has to be written first. Please
refer to the UNLOCK register description for details.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
- ------
15 14 13 12 11 10 9 8
--------
76543210
- MASK[6:0]
Table 13-10. Divided Clock Mask
Bit USART0 USART1 USART2 USART3 TC0 TC1
0 - - - - TIMER_CLOCK2 TIMER_CLOCK2
1- - - - - -
2 CLK_USART/
DIV
CLK_USART/
DIV
CLK_USART/
DIV
CLK_USART/
DIV TIMER_CLOCK3 TIMER_CLOCK3
3- - - - - -
4 - - - - TIMER_CLOCK4 TIMER_CLOCK4
5- - - - - -
6 - - - - TIMER_CLOCK5 TIMER_CLOCK5
228
32142D–06/2013
ATUC64/128/256L3/4U
13.7.7 Clock Failure Detector Control Register
Name: CFDCTRL
Access Type: Read/Write
Offset: 0x054
Reset Value: 0x00000000
• SFV: Store Final Value
0: The register is read/write
1: The register is read-only, to protect against further accidental writes.
• CFDEN: Clock Failure Detection Enable
0: Clock Failure Detector is disabled
1: Clock Failure Detector is enabled
Note that this register is protected by a lock. To write to this register the UNLOCK register has to be written first. Please
refer to the UNLOCK register description for details.
31 30 29 28 27 26 25 24
SFV - - - - - - -
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
- - - - - - - CFDEN
229
32142D–06/2013
ATUC64/128/256L3/4U
13.7.8 Unlock Register
Name: UNLOCK
Access Type: Write-only
Offset: 0x058
Reset Value: 0x00000000
To unlock a write protected register, first write to the UNLOCK register with the address of the register to unlock in the
ADDR field and 0xAA in the KEY field. Then, in the next PB access write to the register specified in the ADDR field.
• KEY: Unlock Key
Write this bit field to 0xAA to enable unlock.
• ADDR: Unlock Address
Write the address of the register to unlock to this field.
31 30 29 28 27 26 25 24
KEY
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
- - - - - - ADDR[9:8]
76543210
ADDR[7:0]
230
32142D–06/2013
ATUC64/128/256L3/4U
13.7.9 Interrupt Enable Register
Name: IER
Access Type: Write-only
Offset: 0x0C0
Reset Value: 0x00000000
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will set the corresponding bit in IMR.
31 30 29 28 27 26 25 24
AE - - - - - - -
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
- - CKRDY - - - - CFD
231
32142D–06/2013
ATUC64/128/256L3/4U
13.7.10 Interrupt Disable Register
Name: IDR
Access Type: Write-only
Offset: 0x0C4
Reset Value: 0x00000000
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will clear the corresponding bit in IMR.
31 30 29 28 27 26 25 24
AE - - - - - - -
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
- - CKRDY - - - - CFD
232
32142D–06/2013
ATUC64/128/256L3/4U
13.7.11 Interrupt Mask Register
Name: IMR
Access Type: Read-only
Offset: 0x0C8
Reset Value: 0x00000000
0: The corresponding interrupt is disabled.
1: The corresponding interrupt is enabled.
This bit is cleared when the corresponding bit in IDR is written to one.
This bit is set when the corresponding bit in IER is written to one.
31 30 29 28 27 26 25 24
AE - - - - - - -
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
- - CKRDY - - - - CFD
233
32142D–06/2013
ATUC64/128/256L3/4U
13.7.12 Interrupt Status Register
Name: ISR
Access Type: Read-only
Offset: 0x0CC
Reset Value: 0x00000000
0: The corresponding interrupt is cleared.
1: The corresponding interrupt is pending.
This bit is cleared when the corresponding bit in ICR is written to one.
This bit is set on a zero-to-one transition of the corresponding bit in the Status Register (SR).
31 30 29 28 27 26 25 24
AE - - - - - - -
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
- - CKRDY - - - - CFD
234
32142D–06/2013
ATUC64/128/256L3/4U
13.7.13 Interrupt Clear Register
Name: ICR
Access Type: Write-only
Offset: 0x0D0
Reset Value: 0x00000000
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will clear the corresponding bit in ISR.
31 30 29 28 27 26 25 24
AE - - - - - - -
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
- - CKRDY - - - - CFD
235
32142D–06/2013
ATUC64/128/256L3/4U
13.7.14 Status Register
Name: SR
Access Type: Read-only
Offset: 0x0D4
Reset Value: 0x00000020
• AE: Access Error
0: No access error has occurred.
1: A write to lock protected register without unlocking it has occurred.
• CKRDY: Clock Ready
0: One of the CPUSEL/PBxSEL registers has been written, and the new clock setting is not yet effective.
1: The synchronous clocks have frequencies as indicated in the CPUSEL/PBxSEL registers.
• CFD: Clock Failure Detected
0: Main clock is running correctly.
1: Failure on main clock detected. Main clock is now running on RCSYS.
31 30 29 28 27 26 25 24
AE - - - - - - -
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
- - CKRDY - - - - CFD
236
32142D–06/2013
ATUC64/128/256L3/4U
13.7.15 Peripheral Power Control Register
Name: PPCR
Access Type: Read/Write
Offset: 0x004
Reset Value: 0x000001FA
• RSTTM: Reset test mode
0: External reset not in test mode
1: External reset in test mode
• FRC32: Force RC32 out
0: RC32 signal is not forced as output
1: RC32 signal is forced as output
• RSTPUN: Reset Pull-up, active low
0: Pull-up for external reset on
1: Pull-up for external reset off
31 30 29 28 27 26 25 24
PPC[31:24]
23 22 21 20 19 18 17 16
PPC[23:16]
15 14 13 12 11 10 9 8
PPC[15:8]
76543210
PPC[7:0]
Table 13-11. Peripheral Power Control
Bit Name
0 RSTPUN
1 FRC32
2 RSTTM
3 CATRCMASK
4 ACIFBCRCMASK
5 ADCIFBRCMASK
6 ASTRCMASK
7 TWIS0RCMASK
8 TWIS1RCMASK
31:9 -
237
32142D–06/2013
ATUC64/128/256L3/4U
• CATRCMASK: CAT Request Clock Mask
0: CAT Request Clock is disabled
1: CAT Request Clock is enabled
• ACIFBRCMASK: ACIFB Request Clock Mask
0: ACIFB Request Clock is disabled
1: ACIFB Request Clock is enabled
• ADCIFBRCMASK: ADCIFB Request Clock Mask
0: ADCIFB Request Clock is disabled
1: ADCIFB Request Clock is enabled
• ASTRCMASK: AST Request Clock Mask
0: AST Request Clock is disabled
1: AST Request Clock is enabled
• TWIS0RCMASK: TWIS0 Request Clock Mask
0: TWIS0 Request Clock is disabled
1: TWIS0 Request Clock is enabled
• TWIS1RCMASK: TWIS1 Request Clock Mask
0: TWIS1 Request Clock is disabled
1: TWIS1 Request Clock is enabled
Note that this register is protected by a lock. To write to this register the UNLOCK register has to be written first. Please
refer to the UNLOCK register description for details.
238
32142D–06/2013
ATUC64/128/256L3/4U
13.7.16 Reset Cause Register
Name: RCAUSE
Access Type: Read-only
Offset: 0x180
Reset Value: Latest Reset Source
• AWIRE: aWire Reset
This bit is set when the last reset was caused by the aWire.
• JTAG: JTAG Reset
This bit is set when the last reset was caused by the JTAG.
• OCDRST: OCD Reset
This bit is set when the last reset was due to the RES bit in the OCD Development Control register having been written to one.
• SLEEP: Sleep Reset
This bit is set when the last reset was due to the device waking up from the Shutdown sleep mode.
• WDT: Watchdog Reset
This bit is set when the last reset was due to a watchdog time-out.
• EXT: External Reset Pin
This bit is set when the last reset was due to the RESET_N pin being pulled low.
• BOD: Brown-out Reset
This bit is set when the last reset was due to the core supply voltage being lower than the brown-out threshold level.
• POR: Power-on Reset
This bit is set when the last reset was due to the core supply voltage VDDCORE being lower than the power-on threshold level
(the reset is generated by the POR18 detector), or the internal regulator supply voltage being lower than the regulator power-on
threshold level (generated by the POR33 detector), or the internal regulator supply voltage being lower than the minimum
required input voltage (generated by the 3.3V supply monitor SM33).
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
- - - AWIRE - JTAG OCDRST
76543210
- SLEEP - - WDT EXT BOD POR
239
32142D–06/2013
ATUC64/128/256L3/4U
13.7.17 Wake Cause Register
Name: WCAUSE
Access Type: Read-only
Offset: 0x184
Reset Value: Latest Wake Source
A bit in this register is set on wake up caused by the peripheral referred to in Table 13-12 on page 239.
31 30 29 28 27 26 25 24
WCAUSE[31:24]
23 22 21 20 19 18 17 16
WCAUSE[23:16]
15 14 13 12 11 10 9 8
WCAUSE[15:8]
76543210
WCAUSE[7:0]
Table 13-12. Wake Cause
Bit Wake Cause
0 CAT
1 ACIFB
2 ADCIFB
3 TWI Slave 0
4 TWI Slave 1
5 WAKE_N
6 ADCIFB Pen Detect
7 USBC
15:8 -
16 EIC
17 AST
31:18 -
240
32142D–06/2013
ATUC64/128/256L3/4U
13.7.18 Asynchronous Wake Up Enable Register
Name: AWEN
Access Type: Read/Write
Offset: 0x188
Reset Value: 0x00000000
Each bit in this register corresponds to an asynchronous wake-up source, according to Table 13-13 on page 240.
0: The corresponding wake up is disabled.
1: The corresponding wake up is enabled
31 30 29 28 27 26 25 24
AWEN[31:24]
23 22 21 20 19 18 17 16
AWEN[23:16]
15 14 13 12 11 10 9 8
AWEN[15:8]
76543210
AWEN[7:0]
Table 13-13. Asynchronous Wake-up Sources
Bit Asynchronous Wake-up Source
0 CAT
1 ACIFB
2 ADCIFB
3 TWIS0
4 TWIS1
5 WAKEN
6 ADCIFBPD
7 USBC
31:8 -
241
32142D–06/2013
ATUC64/128/256L3/4U
13.7.19 Configuration Register
Name: CONFIG
Access Type: Read-Only
Offset: 0x3F8
Reset Value: -
This register shows the configuration of the PM.
• HSBPEVC:HSB PEVC Clock Implemented
0: HSBPEVC not implemented.
1: HSBPEVC implemented.
• PBD: PBD Implemented
0: PBD not implemented.
1: PBD implemented.
• PBC: PBC Implemented
0: PBC not implemented.
1: PBC implemented.
• PBB: PBB Implemented
0: PBB not implemented.
1: PBB implemented.
• PBA: PBA Implemented
0: PBA not implemented.
1: PBA implemented.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
HSBPEVC - - - PBD PBC PBB PBA
242
32142D–06/2013
ATUC64/128/256L3/4U
13.7.20 Version Register
Name: VERSION
Access Type: Read-Only
Offset: 0x3FC
Reset Value: -
• VARIANT: Variant Number
Reserved. No functionality associated.
• VERSION: Version Number
Version number of the module. No functionality associated.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
- - - - VARIANT
15 14 13 12 11 10 9 8
- - - - VERSION[11:8]
76543210
VERSION[7:0]
243
32142D–06/2013
ATUC64/128/256L3/4U
13.8 Module Configuration
The specific configuration for each PM instance is listed in the following tables. The module bus
clocks listed here are connected to the system bus clocks. Please refer to the “Synchronous
Clocks”, “Peripheral Clock Masking” and “Sleep Modes” sections for details.
Table 13-14. Power Manager Clocks
Clock Name Description
CLK_PM Clock for the PM bus interface
Table 13-15. Register Reset Values
Register Reset Value
VERSION 0x00000420
Table 13-16. Effect of the Different Reset Events
Power-on
Reset
External
Reset
Watchdog
Reset
BOD
Reset
SM33
Reset
CPU Error
Reset
OCD
Reset
JTAG
Reset
CPU/HSB/PBx
(excluding Power Manager)
Y Y Y YY Y YY
32KHz oscillator Y N N N N N N N
RC Oscillator Calibration register Y N N N N N N N
Other oscillator control registers Y Y Y Y Y Y Y Y
AST registers, except interrupt
registers
Y N N NN N NN
Watchdog control register Y Y N Y Y Y Y Y
Voltage Calibration register Y N N N N N N N
SM33 control register Y Y Y Y Y Y Y Y
BOD control register Y Y Y N Y Y Y Y
Clock control registers Y Y Y Y Y Y Y Y
OCD system and OCD registers Y Y N Y Y Y N Y
244
32142D–06/2013
ATUC64/128/256L3/4U
14. System Control Interface (SCIF)
Rev: 1.1.0.0
14.1 Features
• Supports crystal oscillator 0.45-16MHz (OSC0)
• Supports Digital Frequency Locked Loop 20-150MHz (DFLL)
• Supports Phase Locked Loop 80-240MHz (PLL)
• Supports 32KHz ultra-low-power oscillator (OSC32K)
• Supports 32kHz RC oscillator (RC32K)
• Integrated low-power RC oscillator (RCSYS)
• Generic clocks (GCLK) with wide frequency range provided
• Generic Clock Prescaler
• Controls Bandgap
• Controls Brown-out detectors (BOD) and supply monitors
• Controls Voltage Regulator (VREG) behavior and calibration
• Controls Temperature Sensor
• Controls Supply Monitor 33 (SM33) operating modes and calibration
• Controls 120MHz integrated RC Oscillator (RC120M)
• Four 32-bit general-purpose backup registers
14.2 Overview
The System Control Interface (SCIF) controls the oscillators, Generic Clocks, BODs, Bandgap,
VREG, Temperature Sensor, and Backup Registers.
14.3 I/O Lines Description
14.4 Product Dependencies
In order to use this module, other parts of the system must be configured correctly, as described
below.
Table 14-1. I/O Lines Description
Pin Name Pin Description Type
RC32OUT RC32 output at startup Output
XIN0 Crystal 0 Input Analog/Digital
XIN32 Crystal 32 Input (primary location) Analog/Digital
XIN32_2 Crystal 32 Input (secondary location) Analog/Digital
XOUT0 Crystal 0 Output Analog
XOUT32 Crystal 32 Output (primary location) Analog
XOUT32_2 Crystal 32 Output (secondary location) Analog
GCLK9-GCLK0 Generic Clock Output Output
GCLK_IN2-GCLK_IN0 Generic Clock Input Input
245
32142D–06/2013
ATUC64/128/256L3/4U
14.4.1 I/O Lines
The SCIF provides a number of generic clock outputs, which can be connected to output pins,
multiplexed with GPIO lines. The programmer must first program the GPIO controller to assign
these pins to their peripheral function. If the I/O pins of the SCIF are not used by the application,
they can be used for other purposes by the GPIO controller. Oscillator pins are also multiplexed
with GPIO. When oscillators are used, the related pins are controlled directly by the SCIF, overriding
GPIO settings.
RC32OUT will be output after reset, and the GPIO controller can assign this pin to other peripheral
function after start-up.
14.4.2 Power Management
The BODs and all the oscillators, except the 32KHz oscillator (OSC32K) are turned off in some
sleep modes and turned automatically on when the device wakes up. The Voltage Regulator is
set in low power mode in some sleep modes and automatically set back in normal mode when
the device wakes up. Please refer to the Power Manager chapter for details.
The BOD control registers will not be reset by the Power Manager on a BOD reset.
14.4.3 Clocks
The SCIF controls all oscillators in the device. The oscillators can be used as source for the CPU
and peripherals. Selection of source is done in the Power Manager. The oscillators can also be
used as source for generic clocks.
14.4.4 Interrupts
The SCIF interrupt request line is connected to the interrupt controller. Using the SCIF interrupt
requires the interrupt controller to be programmed first.
14.4.5 Debug Operation
The SCIF does not interact with debug operations.
14.5 Functional Description
14.5.1 Oscillator (OSC) Operation
Rev: 1.1.1.0
The main oscillator (OSCn) is designed to be used with an external 0.450 to 16MHz crystal and
two biasing capacitors, as shown in the Electrical Characteristics chapter, or with an external
clock connected to the XIN. The oscillator can be used as source for the main clock in the
device, as described in the Power Manager chapter. The oscillator can be used as source for the
generic clocks, as described in the Generic Clocks section.
The oscillator is disabled by default after reset. When the oscillator is disabled, the XIN and
XOUT pins can be used as general purpose I/Os. When the oscillator is enabled, the XIN and
XOUT pins are controlled directly by the SCIF, overriding GPIO settings. When the oscillator is
configured to use an external clock, the clock must be applied to the XIN pin while the XOUT pin
can be used as general purpose I/O.
The oscillator is enabled by writing a one to the Oscillator Enable bit in the Oscillator Control register
(OSCCTRLn.OSCEN). Operation mode (external clock or crystal) is selected by writing to
the Oscillator Mode bit in OSCCTRLn (OSCCTRLn.MODE). The oscillator is automatically dis-
246
32142D–06/2013
ATUC64/128/256L3/4U
abled in certain sleep modes to reduce power consumption, as described in the Power Manager
chapter.
After a hard reset, or when waking up from a sleep mode where the oscillators were disabled,
the oscillator will need a certain amount of time to stabilize on the correct frequency. This startup
time can be set in the OSCCTRLn register.
The SCIF masks the oscillator outputs during the start-up time, to ensure that no unstable clocks
propagate to the digital logic.
The OSCn Ready bit in the Power and Clock Status Register (PCLKSR.OSCnRDY) is set when
the oscillator is stable and ready to be used as clock source. An interrupt can be generated on a
zero-to-one transition on OSCnRDY if the OSCnRDY bit in the Interrupt Mask Register
(IMR.OSCnRDY) is set. This bit is set by writing a one to the corresponding bit in the Interrupt
Enable Register (IER.OSCnRDY).
14.5.2 32KHz Oscillator (OSC32K) Operation
Rev: 1.1.0.1
The 32KHz oscillator operates as described for the oscillator above. The 32KHz oscillator can
be used as source clock for the Asynchronous Timer (AST) and the Watchdog Timer (WDT).
The 32KHz oscillator can also be used as source for the generic clocks.
The oscillator is disabled by default after reset. When the oscillator is disabled, the XIN32 and
XOUT32 pins can be used as general-purpose I/Os. When the oscillator is enabled, the XIN32
and XOUT32 pins are controlled directly by the SCIF, overriding GPIO settings. When the oscillator
is configured to use an external clock, the clock must be applied to the XIN32 pin while the
XOUT32 pin can be used as general-purpose I/O.
The oscillator is enabled writing a one to the OSC32 Enable bit in the 32KHz Oscillator Control
Register (OSCCTRL32OSC32EN). The oscillator is disabled by writing a zero to the OSC32EN
bit, while keeping the other bits unchanged. Writing to OSC32EN while also writing to other bits
may result in unpredictable behavior. Operation mode (external clock or crystal) is selected by
writing to the Oscillator Mode bit in OSCCTRL32 (OSCCTRL32.MODE). The oscillator is an
ultra-low-power design and remains enabled in all sleep modes.
The start-up time of the 32KHz oscillator is selected by writing to the Oscillator Start-up Time
field in the OSCCTRL32 register (OSCCTRL32.STARTUP). The SCIF masks the oscillator output
during the start-up time, to ensure that no unstable clock cycles propagate to the digital logic.
The OSC32 Ready bit in the Power and Clock Status Register (PCLKSR.OSC32RDY) is set
when the oscillator is stable and ready to be used as clock source. An interrupt can be generated
on a zero-to-one transition on PCLKSR.OSC32RDY if the OSC32RDY bit in the Interrupt
Mask Register (IMR.OSC32RDY) is set. This bit is set by writing a one to the corresponding bit
in the Interrupt Enable Register (IER.OSC32RDY).
.As a crystal oscillator usually requires a very long start-up time (up to 1 second), the 32KHz
oscillator will keep running across resets, except a Power-on Reset (POR).
The 32KHz oscillator also has a 1KHz output. This is enabled by writing a one to the Enable
1KHz output bit in OSCCTRL32 register (OSCCTRL32.EN1K). If the 32KHz output clock is not
needed when 1K is enabled, this can be disabled by writing a zero to the Enable 32KHz output
bit in the OSCCTRL32 register (OSCCTRL32.EN32K). OSCCTRL32.EN32K is set after a POR.
The 32KHz oscillator has two possible sets of pins. To select between them write to the Pin
Select bit in the OSCCTRL32 register (OSCCTRL32.PINSEL). If the 32KHz oscillator is to be
247
32142D–06/2013
ATUC64/128/256L3/4U
used in Shutdown mode, PINSEL must be written to one, and XIN32_2 and XOUT32_2 must be
used.
14.5.3 PLL Operation
Rev: 1.1.0.0
The device contains one Phase Locked Loop (PLL), which is controlled by the Phase Locked
Loop Interface (PLLIF). The PLL is disabled by default, but can be enabled to provide high frequency
source clocks for synchronous or generic clocks. The PLL can use different clock
sources as reference clock, please refer to the “PLL Clock Sources” table in the SCIF Module
Configuration section for details. The PLL output is divided by a multiplication factor, and the
PLL compares the phase of the resulting clock to the reference clock. The PLL will adjust its output
frequency until the two compared clocks phases are equal, thus locking the output frequency
to a multiple of the reference clock frequency.
When the PLL is switched on, or when changing the clock source or multiplication factor for the
PLL, the PLL is unlocked and the output frequency is undefined. The PLL clock for the digital
logic is automatically masked when the PLL is unlocked, to prevent the connected digital logic
from receiving a too high frequency and thus become unstable.
The PLL can be configured by writing the PLL Control Register (PLLn). To prevent unexpected
writes due to software bugs, write access to the PLLn register is protected by a locking mechanism,
for details please refer to the UNLOCK register description.
Figure 14-1. PLL with Control Logic and Filters
14.5.3.1 Enabling the PLL
Before the PLL is enabled it must be set up correctly. The PLL Oscillator Select field (PLLOSC)
selects a source for the reference clock. The PLL Multiply Factor (PLLMUL) and PLL Division
Phase
Detector
Output
Divider
Source
clocks
PLLOSC PLLOPT[0]
PLLMUL
Lock bit
Mask PLL clock
Input
Divider
PLLDIV
1/2
PLLOPT[1]
0
1
VCO
fvco fPLL
Lock
Counter
fREF
248
32142D–06/2013
ATUC64/128/256L3/4U
Factor (PLLDIV) fields must be written with the multiplication and division factors, respectively.
The PLLMUL must always be greater than 1, creating the PLL frequency:
fvco = (PLLMUL+1)/PLLDIV • fREF, if PLLDIV >0
fvco = 2•(PLLMUL+1) • fREF, if PLLDIV = 0
The PLL Options (PLLOPT) field should be configured to proper values according to the PLL
operating frequency. The PLLOPT field can also be configured to divide the output frequency of
the PLL by 2 and Wide-Bandwidth mode, which allows faster startup time and out-of-lock time.
It is not possible to change any of the PLL configuration bits when the PLL is enabled, Any write
to PLLn while the PLL is enabled will be discarded.
After setting up the PLL, the PLL is enabled by writing a one to the PLL Enable (PLLEN) bit in
the PLLn register.
14.5.3.2 Disabling the PLL
The PLL is disabled by writing a zero to the PLL Enable (PLLEN) bit in the PLLn register. After
disabling the PLL, the PLL configuration fields becomes writable.
14.5.3.3 PLL Lock
The lock signal for each PLL is available as a PLLLOCKn flag in the PCLKSR register. If the lock
for some reason is lost, the PLLLOCKLOSTn flag in PCLKSR register will be set. An interrupt
can be generated on a 0 to 1 transition of these bits.
14.5.4 Digital Frequency Locked Loop (DFLL) Operation
Rev: 2.1.0.1
The DFLL is controlled by the Digital Frequency Locked Loop Interface (DFLLIF). The DFLL is
disabled by default, but can be enabled to provide a high-frequency source clock for synchronous
and generic clocks.
Features:
• Internal oscillator with no external components
• 20-150MHz frequency in closed loop mode
• Can operate standalone as a high-frequency programmable oscillator in open loop mode
• Can operate as an accurate frequency multiplier against a known frequency in closed loop
mode
• Optional spread-spectrum clock generation
• Very high-frequency multiplication supported - can generate all frequencies from a 32KHz
clock
The DFLL can operate in both open loop mode and closed loop mode. In closed loop mode a
low frequency clock with high accuracy can be used as reference clock to get high accuracy on
the output clock (CLK_DFLL).
To prevent unexpected writes due to software bugs, write access to the configuration registers is
protected by a locking mechanism. For details please refer to the UNLOCK register description.
249
32142D–06/2013
ATUC64/128/256L3/4U
Figure 14-2. DFLLIF Block Diagram
14.5.4.1 Enabling the DFLL
The DFLL is enabled by writing a one to the Enable bit (EN) in the DFLLn Configuration Register
(DFLLnCONF). No other bits or fields in DFLLnCONF must be changed simultaneously, or
before the DFLL is enabled.
14.5.4.2 Internal synchronization
Due to multiple clock domains in the DFLLIF, values in the DFLLIF configuration registers need
to be synchronized to other clock domains. The status of this synchronization can be read from
the Power and Clocks Status Register (PCLKSR). Before writing to a DFLLIF configuration register,
the user must check that the DFLLn Synchronization Ready bit (DFLLnRDY) in PCLKSR is
set. When this bit is set, the DFLL can be configured, and CLK_DFLL is ready to be used. Any
write to a DFLLIF configuration register while DFLLnRDY is cleared will be ignored.
Before reading the value in any of the DFLL configuration registers a one must be written to the
Synchronization bit (SYNC) in the DFLLn Synchronization Register (DFLLnSYNC). The DFLL
configuration registers are ready to be read when PCLKSR.DFLLnRDY is set.
14.5.4.3 Disabling the DFLL
The DFLL is disabled by writing a zero to DFLLnCONF.EN. No other bits or fields in DFLLnCONF
must be changed simultaneously.
After disabling the DFLL, PCLKSR.DFLLnRDY will not be set. It is not required to wait for
PCLKSR.DFLLnRDY to be set before re-enabling the DFLL.
14.5.4.4 Open loop operation
After enabling the DFLL, open loop mode is selected by writing a zero to the Mode Selection bit
(MODE) in DFLLnCONF. When operating in open loop mode the output frequency of the DFLL
will be determined by the values written to the Coarse Calibration Value field (COARSE) and the
Fine Calibration Value field (FINE) in the DFLLnCONF register. When writing to COARSE and
DFLL
COARSE
FINE
8
9
CLK_DFLL
IMUL
FMUL 32
CLK_DFLLIF_REF
FREQUENCY
TUNER
DFLLLOCKC
DFLLLOCKLOSTC
DFLLLOCKF
DFLLLOCKLOSTF
DFLLLOCKA
DFLLLOCKLOSTA
CSTEP
FSTEP 8+9 CLK_DFLLIF_DITHER
250
32142D–06/2013
ATUC64/128/256L3/4U
FINE, be aware that the output frequency must not exceed the maximum frequency of the
device after the division in the clock generator. It is possible to change the value of COARSE
and FINE, and thereby the output frequency of the DFLL, while the DFLL is enabled and in use.
The DFLL clock is ready to be used when PCLKSR.DFLLnRDY is cleared after enabling the
DFLL.
The frequency range in open loop mode is 20-150MHz, but maximum frequency can be higher,
and the minimum frequency can be lower. The best way to start the DFLL at a specific frequency
in open loop mode is to first configure it for closed loop mode, see Section 14.5.4.5. When a lock
is achieved, read back the COARSE and FINE values and switch to open loop mode using these
values. An alternative approach is to use the Frequency Meter (FREQM) to monitor the DFLL
frequency and adjust the COARSE and FINE values based on measurement results form the
FREQM. Please refer to the FREQM chapter for more information on how to use it. Note that the
output frequency of the DFLL will drift when in open loop mode due to temperature and voltage
changes. Please refer to the Electrical Characteristics chapter for details.
14.5.4.5 Closed loop operation
The DFLL must be correctly configured before closed loop operation can be enabled. After
enabling the DFLL, enable and select a reference clock (CLK_DFLLIF_REF).
CLK_DFLLIF_REF is a generic clock, please refer to Generic Clocks section for details. Then
set the maximum step size allowed in finding the COARSE and FINE values by setting the
Coarse Maximum Step field (CSTEP) and Fine Maximum Step field (FSTEP) in the DFLLn Maximum
Step Register (DFLLnSTEP). A small step size will ensure low overshoot on the output
frequency, but can typically result in longer lock times. A high value might give a big overshoot,
but can typically give faster locking. DFLLnSTEP.CSTEP and DFLLnSTEP.FSTEP must be
lower than 50% of the maximum value of DFLLnCONF.COARSE and DFLLnCONF.FINE
respectively. Then select the multiplication factor in the Integer Multiply Factor field (IMUL) and
the Fractional Multiply field (FMUL) in the DFLLn Multiplier Register (DFLLnMUL). Care must be
taken when choosing IMUL and FMUL so the output frequency does not exceed the maximum
frequency of the device. Start the closed loop mode by writing a one to DFLLnCONF.MODE bit.
The frequency of CLK_DFLL (fDFLL) is given by:
where fREF is the frequency of CLK_DFLLIF_REF. COARSE and FINE in DFLLnCONF are readonly
in closed loop mode, and are controlled by the DFLLIF to meet user specified frequency.
The values in COARSE when the closed loop mode is enabled is used by the frequency tuner as
a starting point for COARSE. Setting COARSE to a value close to the final value will reduce the
time needed to get a lock on COARSE.
Frequency locking
The locking of the frequency in closed loop mode is divided into three stages. In the COARSE
stage the control logic quickly finds the correct value for DFLLnCONF.COARSE and thereby
sets the output frequency to a value close to the correct frequency. The DFLLn Locked on
Coarse Value bit (DFLLnLOCKC) in PCLKSR will be set when this is done. In the FINE stage the
control logic tunes the value in DFLLnCONF.FINE so the output frequency will be very close to
the desired frequency. DFLLn Locked on Fine Value bit (DFLLnLOCKF) in PCLKSR will be set
when this is done. In the ACCURATE stage the DFLL frequency tuning mechanism uses dithering
on the FINE bits to obtain an accurate average output frequency. DFLLn Locked on Accurate
Value bit (DFLLnLOCKA) in PCLKSR will be set when this is done. The ACCURATE stage will
f
DFLL IMUL FMUL
216
+ ----------------- f
REF =
251
32142D–06/2013
ATUC64/128/256L3/4U
only be executed if the Dithering Enable bit (DITHER) in DFLLnCONF has been written to a one.
If DITHER is written to a zero DFLLnLOCKA will never occur. If dithering is enabled, the frequency
of the dithering is decided by a generic clock (CLK_DFLLIF_DITHER). This clock has to
be set up correctly before enabling dithering. Please refer to the Generic Clocks section for
details.
Figure 14-3. DFLL Closed loop State Diagram
When dithering is enabled the accuracy of the average output frequency of the DFLL will be
higher. However, the actual frequency will be alternating between two frequencies. If a fixed frequency
is required, the dithering should not be enabled.
Figure 14-4. DFLL Locking in Closed loop
CLK_DFLL is ready to be used when the DFLLn Synchronization Ready bit (DFLLnRDY) in
PCLKSR is set after enabling the DFLL. However, the accuracy of the output frequency depends
on which locks are set.
For lock times, please refer to the Electrical Characteristics chapter.
Measure
fDFLLn
Calculate
new
COARSE
value
DFLLnLOCKC
0
Calculate
new FINE
value
DFLLnLOCKF
0
1 1 DFLLnLOCKA
Calculate
new
dithering
dutycycle
0
Compensate
for
drift
1 DITHER 1
Compensate
for
drift
0
Initial
frequency
Target
frequency
DFLLnLOCKC DFLLnLOCKF DFLLnLOCKA
252
32142D–06/2013
ATUC64/128/256L3/4U
Drift compensation
The frequency tuner will automatically compensate for drift in the fDFLL without losing either of the
locks. If the FINE value overflows or underflows, which should normally not happen, but could
occur due to large drift in temperature and voltage, all locks will be lost, and the COARSE and
FINE values will be recalibrated as described earlier. If any lock is lost the corresponding bit in
PCLKSR will be set, DFLLn Lock Lost on Coarse Value bit (DFLLnLOCKLOSTC) for lock lost on
COARSE value, DFLLn Lock Lost on Fine Value bit (DFLLnLOCKLOSTF) for lock lost on FINE
value and DFLLn Lock Lost on Accurate Value bit (DFLLnLOCKLOSTA) for lock lost on ACCURATE
value. The corresponding lock status bit will be cleared when the lock lost bit is set, and
vice versa.
Reference clock stop detection
If CLK_DFLLIF_REF stops or is running at a very slow frequency, the DFLLn Reference Clock
Stopped bit (DFLLnRCS) in PCLKSR will be set. Note that the detection of the clock stop will
take a long time. The DFLLIF operate as if it was in open loop mode if it detects that the reference
clock has stopped. This means that the COARSE and FINE values will be kept constant
while PCLKSR.DFLLnRCS is set. Closed loop mode operation will automatically resume if the
CLK_DFLLIF_REF is restarted, and compensate for any drift during the time CLK_DFLLIF_REF
was stopped. No locks will be lost.
Frequency error measurement
The ratio between CLK_DFLLIF_REF and CLK_DFLL is measured automatically by the DFLLIF.
The difference between this ratio and DFLLnMUL is stored in the Multiplication Ratio Difference
field (RATIODIFF) in the DFLLn Ratio Register (DFLLnRATIO). The relative error on CLK_DFLL
compared to the target frequency can be calculated as follows:
where is the number of reference clock cycles the DFLLIF is using for calculating the
ratio.
14.5.4.6 Dealing with delay in the DFLL
The time from selecting a new frequency until this frequency is output by the DFLL, can be up to
several micro seconds. If the difference between the desired output frequency (CLK_DFLL) and
the frequency of CLK_DFLLIF_REF is small this can lead to an instability in the DFLLIF locking
mechanism, which can prevent the DFLLIF from achieving locks. To avoid this, a chill cycle
where the CLK_DFLL frequency is not measured can be enabled. The chill cycle is enabled by
writing a one to the Chill Cycle Enable (CCEN) bit in the DFLLnCONF register. Enabling chill
cycles might double the lock time,
Another solution to the same problem can be to use less strict lock requirements. This is called
Quick Lock (QL), which is enabled by writing a one to the Quick Lock Enable (QLEN) bit in the
DFLLnCONF register. The QL might lead to bigger spread in the outputted frequency than chill
cycles, but the average output frequency is the same.
If the target frequency is below 40MHz, one of these methods should always be used.
14.5.4.7 Spread Spectrum Generator (SSG)
When the DFLL is used as the main clock source for the device, the EMI radiated from the
device will be synchronous to fDFLL. To provide better Electromagnetic Compatibility (EMC) the
error RATIODIFF fREF
2NUMREF f
DFLL = ------------------------------------------------
2NUMREF
253
32142D–06/2013
ATUC64/128/256L3/4U
DFLLIF can provide a clock with the energy spread in the frequency domain. This is done by
adding or subtracting values from the FINE value. SSG is enabled by writing a one to the Enable
bit (EN) in the DFLLn Spread Spectrum Generator Control Register (DFLLnSSG).
A generic clock sets the rate at which the SSG changes the frequency of the DFLL clock to generate
a spread spectrum (CLK_DFLLIF_DITHER). This is the same clock used by the dithering
mechanism. The frequency of this clock should be higher than fREF to ensure that the DFLLIF
can lock. Please refer to the Generic clocks section for details.
Optionally, the clock ticks can be qualified by a Pseudo Random Binary Sequence (PRBS) if the
PRBS bit in DFLLnSSG is one. This reduces the modulation effect of CLK_DFLLIF_DITHER frequency
onto fDFLL.
The amplitude of the frequency variation can be selected by setting the SSG Amplitude field
(AMPLITUDE) in DFLLnSSG. If AMPLITUDE is zero the SSG will toggle on the LSB of the FINE
value. If AMPLITUDE is one the SSG will add the sequence {1,-1, 0} to FINE.
The step size of the SSG is selected by writing to the SSG Step Size field (STEPSIZE) in
DFLLnSSG. STEPSIZE equal to zero or one will result in a step size equal to one. If the step
size is set to n, the output value from the SSG will be incremented/decremented by n on every
tick of the source clock.
The Spread Spectrum Generator is available in both open and closed loop mode.
When spread spectrum is enabled in closed loop mode, and the AMPLITUDE is high, an overflow/underflow
in FINE is more likely to occur.
Figure 14-5. Spread Spectrum Generator Block Diagram.
14.5.4.8 Wake from sleep modes
The DFLLIF may optionally reset its lock bits when waking from a sleep mode which disables the
DFLL. This is configured by the Lose Lock After Wake (LLAW) bit in DFLLnCONF register. If
DFLLnCONF.LLAW is written to zero the DFLL will be re-enabled and start running with the
same configuration as before going to sleep even if the reference clock is not available. The
locks will not be lost. When the reference clock has restarted, the FINE tracking will quickly compensate
for any frequency drift during sleep. If a one is written to DFLLnCONF.LLAW before
going to a sleep mode where the DFLL is turned off, the DFLLIF will lose all its locks when waking
up, and needs to regain these through the full lock sequence.
14.5.4.9 Accuracy
There are mainly three factors that decide the accuracy of the fDFLL. These can be tuned to
obtain maximum accuracy when fine lock is achieved.
Pseudorandom
Binary Sequence Spread Spectrum
Generator
FINE
9
To DFLL CLK_DFLLIF_DITHER
AMPLITUDE,
STEPSIZE PRBS
1
0
254
32142D–06/2013
ATUC64/128/256L3/4U
• FINE resolution: The frequency step between two FINE values. This is relatively smaller for
high output frequencies.
• Resolution of the measurement: If the resolution of the measured fDFLL is low, i.e. the ratio
between CLK_DFLL frequency and CLK_DFLLIF_REF is small, then the DFLLIF might lock
at a frequency that is lower than the targeted frequency. It is recommended to use a
reference clock frequency of 32 KHz or lower to avoid this issue for low target frequencies.
• The accuracy of the reference clock.
14.5.4.10 Interrupts
A interrupt can be generated on a zero-to-one transaction on DFLLnLOCKC, DFLLnLOCKF,
DFLLnLOCKA, DFLLnLOCKLOSTC, DFLLnLOCKLOSTF, DFLLnLOCKLOSTA, DFLLnRDY or
DFLLnRCS.
14.5.5 Brown-Out Detection (BOD)
Rev: 1.2.0.0
The Brown-Out Detector monitors the VDDCORE supply pin and compares the supply voltage
to the brown-out detection level.
The BOD is disabled by default, and is enabled by writing to the BOD Control field in the BOD
Control Register (BOD.CTRL). This field can also be updated by flash fuses.
The BOD is powered by VDDIO and will not be powered during Shutdown sleep mode.
To prevent unexpected writes to the BOD register due to software bugs, write access to this register
is protected by a locking mechanism. For details please refer to the UNLOCK register
description.
To prevent further modifications by software, the content of the BOD register can be set as readonly
by writing a one to the Store Final Value bit (BOD.SFV). When this bit is one, software can
not change the BOD register content. This bit is cleared after flash calibration and after a reset
except after a BOD reset.
The brown-out detection level is selected by writing to the BOD Level field in BOD
(BOD.LEVEL). Please refer to the Electrical Characteristics chapter for parametric details.
If the BOD is enabled (BOD.CTRL is one or two) and the supply voltage goes below the detection
level, the Brown-Out Detection bit in the Power and Clocks Status Register
(PCLKSR.BODDET) is set. This bit is cleared when the supply voltage goes above the detection
level. An interrupt request will be generated on a zero-to-one transition on PCLKSR.BODDET if
the Brown-Out Detection bit in the Interrupt Mask Register (IMR.BODDET) is set. This bit is set
by writing a one to the corresponding bit in the Interrupt Enable Register (IER.BODDET).
If BOD.CTRL is one, a BOD reset will be generated when the supply voltage goes below the
detection level. If BOD.CTRL is two, the device will not be reset.
Writing a one to the BOD Hysteresis bit in BOD (BOD.HYST) will add a hysteresis on the BOD
detection level.
Note that the BOD must be disabled before changing BOD.LEVEL, to avoid spurious reset or
interrupt. After enabling the BOD, the BOD output will be masked during one half of a RCSYS
clock cycle and two main clocks cycles to avoid false results.
When the JTAG or aWire is enabled, the BOD reset and interrupt are masked.
255
32142D–06/2013
ATUC64/128/256L3/4U
The CTRL, HYST, and LEVEL fields in the BOD Control Register are loaded factory defined calibration
values from flash fuses after a reset. If the Flash Calibration Done bit in the BOD Control
Register (BOD.FCD) is zero, the flash calibration will be redone after any reset, and the
BOD.FCD bit will be set before program execution starts in the CPU. If BOD.FCD is one, the
flash calibration is redone after any reset except for a BOD reset. The BOD.FCD bit is cleared
after a reset, except for a BOD reset. BOD.FCD is set when these fields have been updated after
a flash calibration. It is possible to override the values in the BOD.CTRL, BOD.HYST, and
BOD.LEVEL fields after reset by writing to the BOD Control Register. Please refer to the Fuse
Settings chapter for more details about BOD fuses and how to program the fuses.
Figure 14-6. BOD Block Diagram
14.5.6 Bandgap
Rev: 1.2.0.0
The flash memory, the BOD, and the Temperature Sensor need a stable voltage reference to
operate. This reference voltage is provided by an internal Bandgap voltage reference. This reference
is automatically turned on at start-up and turned off during some sleep modes to save
power. The Bandgap reference is powered by the internal regulator supply voltage and will not
be powered during Shutdown sleep mode. Please refer to the Power Manager chapter for
details.
VDDCORE
POR18 BOD
SCIF
POWER MANAGER(PM) INTC
Reset
Bod
Detected
Enable
BO
D Hyst
BOD
Level
Reset
In et rrupt
256
32142D–06/2013
ATUC64/128/256L3/4U
14.5.7 System RC Oscillator (RCSYS)
Rev: 1.1.1.0
The system RC oscillator has a startup time of three cycles, and is always available except in
some sleep modes. Please refer to the Power Manager chapter for details. The system RC oscillator
operates at a nominal frequency of 115kHz, and is calibrated using the Calibration Value
field (CALIB) in the RC Oscillator Calibration Register (RCCR). After a Power-on Reset (POR),
the RCCR.CALIB field is loaded with a factory defined value stored in the Flash fuses. Please
refer to the Fuse setting chapter for more details about RCCR fuses and how to program the
fuses.
If the Flash Calibration Done (FCD) bit in the RCCR is zero at any reset, the flash calibration will
be redone and the RCCR.FCD bit will be set before program execution starts in the CPU. If the
RCCR.FCD is one, the flash calibration will only be redone after a Power-on Reset.
To prevent unexpected writes to RCCR due to software bugs, write access to this register is protected
by a locking mechanism. For details please refer to the UNLOCK register description.
Although it is not recommended to override default factory settings, it is still possible to override
the default values by writing to RCCR.CALIB.
14.5.8 Voltage Regulator (VREG)
Rev: 1.1.0.0
The embedded voltage regulator can be used to provide the VDDCORE voltage from the internal
regulator supply voltage. It is controlled by the Voltage Regulator Calibration Register
(VREGCR). The voltage regulator is enabled by default at start-up but can be disabled by software
if an external voltage is provided on the VDDCORE pin. The VREGCR also contains bits to
control the POR18 detector and the POR33 detector.
14.5.8.1 Register protection
To prevent unexpected writes to VREGCR due to software bugs, write access to this register is
protected by a locking mechanism. For details please refer to the UNLOCK register description.
To prevent further modifications by software, the content of the VREGCR register can be set as
read-only by writing a one to the Store Final Value bit (VREGCR.SFV). Once this bit is set, software
can not change the VREGCR content until a Power-on Reset (POR) is applied.
14.5.8.2 Controlling voltage regulator output
The voltage regulator is always enabled at start-up, i.e. after a POR or when waking up from
Shutdown mode. It can be disabled by software by writing a zero to the Enable bit
(VREGCR.EN). This bit is set after a POR. Because of internal synchronization, the voltage regulator
is not immediately enabled or disabled. The actual state of the voltage regulator can be
read from the ON bit (VREGCR.ON).
The voltage regulator output level is controlled by the Select VDD field (SELVDD) in VREGCR.
The default value of this field corresponds to a regulator output voltage of 1.8V. Other values of
this field are not defined, and it is not recommended to change the value of this field.
The Voltage Regulator OK bit (VREGCR.VREGOK) bit indicates when the voltage regulator output
has reached the voltage threshold level.
257
32142D–06/2013
ATUC64/128/256L3/4U
14.5.8.3 Factory calibration
After a Power-on Reset (POR) the VREGCR.CALIB field is loaded with a factory defined calibration
value. This value is chosen so that the normal output voltage of the regulator after a powerup
is 1.8V.
Although it is not recommended to override default factory settings, it is still possible to override
these default values by writing to VREGCR.CALIB.
If the Flash Calibration Done bit in VREGCR (VREGCR.FCD) is zero, the flash calibration will be
redone after any reset, and the VREGCR.FCD bit will be set before program execution starts in
the CPU. If VREGCR.FCD is one, the flash calibration will only be redone after a POR.
14.5.8.4 POR33 control
VREGCR includes control bits for the Power-on Reset 3.3V (POR33) detector that monitors the
internal regulator supply voltage. The POR33 detector is enabled by default but can be disabled
by software to reduce power consumption. The 3.3V Supply Monitor (SM33) can then be used to
monitor the regulator power supply.
The POR33 detector is disabled by writing a zero to the POR33 Enable bit
(VREGCR.POR33EN). Because of internal synchronisation, the POR33 detector is not immediately
enabled or disabled. The actual state of the POR33 detector can be read from the POR33
Status bit (VREGCR.POR33STATUS).
The 32kHz RC oscillator (RC32K) must be enabled before disabling the POR33 detector. Once
the POR33 detector has been disabled, the RC32K oscillator can be disabled again.
To avoid spurious resets, it is mandatory to mask the Power-on Reset when enabling or disabling
the POR33 detector. The Power-on Reset generated by the POR33 detector can be
ignored by writing a one to the POR33 Mask bit (VREGCR.POR33MASK). Because of internal
synchronization, the masking is not immediately effective, so software should wait for the
VREGCR.POR33MASK to read as a one before assuming the masking is effective.
The output of the POR33 detector is zero if the internal regulator supply voltage is below the
POR33 power-on threshold level, and one if the internal regulator supply voltage is above the
POR33 power-on threshold level. This output (before masking) can be read from the POR33
Value bit (VREGCR.POR33VALUE).
14.5.8.5 POR18 control
VREGCR includes control bits for the Power-on Reset 1.8V (POR18) detector that monitors the
VDDCORE voltage. The POR18 detector is enabled by default but can be disabled by software
to reduce power consumption.
The POR18 detector is disabled by writing a zero to the POR18 Enable bit
(VREGCR.POR18EN). Because of internal synchronization, the POR18 detector is not immediately
enabled or disabled. The actual state of the POR18 detector can be read from the POR18
Status bit (VREGCR.POR18STATUS).
Please note that the POR18 detector cannot be disabled while the JTAG or aWire debug interface
is used. Writing a zero to VREGCR.POR18EN bit will have no effect.
To avoid spurious resets, it is mandatory to mask the Power-on Reset when enabling or disabling
the POR18 detector. The Power-on Reset generated by the POR18 detector can be
ignored by writing a one to the POR18 Mask bit (VREGCR.POR18MASK). Because of internal
258
32142D–06/2013
ATUC64/128/256L3/4U
synchronisation, the masking is not immediately effective, so software should wait for the
VREGCR.POR18MASK to read as one before assuming the masking is effective.
The output of the POR18 detector is zero if the VDDCORE voltage is below the POR18 poweron
threshold level, and one if the VDDCORE voltage is above the POR18 power-on threshold
level. The output of the POR18 detector (before masking) can be read from the POR18 Value bit
(VREGCR.POR18VALUE).
14.5.9 3.3 V Supply Monitor (SM33)
Rev: 1.1.0.0
The 3.3V supply monitor is a specific voltage detector for the internal regulator supply voltage. It
will indicate if the internal regulator supply voltage is above the minimum required input voltage
threshold. The user can choose to generate either a Power-on Reset (POR) and an interrupt
request, or only an interrupt request, when the internal regulator supply voltage drops below this
threshold.
Please refer to the Electrical Characteristics chapter for parametric details.
14.5.9.1 Register protection
To prevent unexpected writes to SM33 register due to software bugs, write access to this register
is protected by a locking mechanism. For details please refer to the UNLOCK register
description.
To prevent further modifications by software, the content of the register can be set as read-only
by writing a one to the Store Final Value bit (SM33.SFV). When this bit is one, software can not
change the SM33 register content until the device is reset.
14.5.9.2 Operating modes
The SM33 is disabled by default and is enabled by writing to the Supply Monitor Control field in
the SM33 control register (SM33.CTRL). The current state of the SM33 can be read from the
Supply Monitor On Indicator bit in SM33 (SM33.ONSM). Enabling the SM33 will disable the
POR33 detector.
The SM33 can operate in continuous mode or in sampling mode. In sampling mode, the SM33 is
periodically enabled for a short period of time, just enough to make a a measurement, and then
disabled for a longer time to reduce power consumption.
By default, the SM33 operates in sampling mode during DeepStop and Static mode and in continuous
mode for other sleep modes. Sampling mode can also be forced during sleep modes
other than DeepStop and Static, and during normal operation, by writing a one to the Force
Sampling Mode bit in the SM33 register (SM33.FS).
The user can select the sampling frequency by writing to the Sampling Frequency field in SM33
(SM33.SAMPFREQ). The sampling mode uses the 32kHz RC oscillator (RC32K) as clock
source. The 32kHz RC oscillator is automatically enabled when the SM33 operates in sampling
mode.
14.5.9.3 Interrupt and reset generation
If the SM33 is enabled (SM33.CTRL is one or two) and the regulator supply voltage drops below
the SM33 threshold, the SM33DET bit in the Power and Clocks Status Register
(PCLKSR.SM33DET) is set. This bit is cleared when the supply voltage goes above the threshold.
An interrupt request is generated on a zer-to-one transition of PCLKSR.SM33DET if the
259
32142D–06/2013
ATUC64/128/256L3/4U
Supply Monitor 3.3V Detection bit in the Interrupt Mask Register (IMR.SM33DET) is set. This bit
is set by writing a one to the corresponding bit in the Interrupt Enable Register (IER.SM33DET).
If SM33.CTRL is one, a POR will be generated when the voltage drops below the threshold. If
SM33.CTRL is two, the device will not be reset.
14.5.9.4 Factory calibration
After a reset the SM33.CALIB field is loaded with a factory defined value. This value is chosen
so that the nominal threshold value is 1.75V. The flash calibration is redone after any reset, and
the Flash Calibration Done bit in SM33 (SM33.FCD) is set before program execution starts in the
CPU.
Although it is not recommended to override default factory settings, it is still possible to override
the default value by writing to SM33.CALIB
14.5.10 Temperature Sensor
Rev: 1.0.0.0
The Temperature Sensor is connected to an ADC channel, please refer to the ADC chapter for
details. It is enabled by writing one to the Enable bit (EN) in the Temperature Sensor Configuration
Register (TSENS). The Temperature Sensor can not be calibrated.
Please refer to the Electrical Characteristics chapter for more details.
14.5.11 120MHz RC Oscillator (RC120M)
Rev: 1.1.0.0
The 120MHz RC Oscillator can be used as source for the main clock in the device, as described
in the Power Manager chapter. The oscillator can also be used as source for the generic clocks,
as described in Generic Clock section. The RC120M must be enabled before it is used as a
source clock. To enable the clock, the user must write a one to the Enable bit in the 120MHz RC
Oscillator Control Register (RC120MCR.EN), and read back the RC120MCR register until the
EN bit reads one. The clock is disabled by writing a zero to RC120MCR.EN. The EN bit must be
read back as zero before the RC120M is re-enabled. If not, undefined behavior may occur.
The oscillator is automatically disabled in certain sleep modes to reduce power consumption, as
described in the Power Manager chapter.
14.5.12 Backup Registers (BR)
Rev: 1.0.0.1
Four 32-bit backup registers are available to store values when the device is in Shutdown
mode. These registers will keep their content even when the VDDCORE supply and the internal
regulator supply voltage supplies are removed. The backup registers can be accessed by reading
from and writing to the BR0, BR1, BR2, and BR3 registers.
After writing to one of the backup registers the user must wait until the Backup Register Interface
Ready bit in tne Power and Clocks Status Register (PCLKSR.BRIFARDY) is set before writing to
another backup register. Writes to the backup register while PCLKSR.BRIFARDY is zero will be
discarded. An interrupt can be generated on a zero-to-one transition on PCLKSR.BRIFARDY if
260
32142D–06/2013
ATUC64/128/256L3/4U
the BRIFARDY bit in the Interrupt Mask Register (IMR.BRIFARDY) is set. This bit is set by writing
a one to the corresponding bit in the Interrupt Enable Register (IER.BRIFARDY).
After powering up the device the Backup Register Interface Valid bit in PCLKSR (PCLKSR.BRIFAVALID)
is cleared, indicating that the content of the backup registers has not been written and
contains the reset value. After writing to one of the backup registers the PCLKSR.BRIFAVALID
bit is set. During writes to the backup registers (when BRIFARDY is zero) BRIFAVALID will be
zero. If a reset occurs when BRIFARDY is zero, BRIFAVALID will be cleared after the reset, indicating
that the content of the backup registers is not valid. If BRIFARDY is one when a reset
occurs, BRIFAVALID will be one and the content is the same as before the reset.
The user must ensure that BRIFAVALID and BRIFARDY are both set before reading the backup
register values.
14.5.13 32kHz RC Oscillator (RC32K)
Rev: 1.1.0.0
The RC32K can be used as source for the generic clocks, as described in The Generic Clocks
section.
The 32kHz RC oscillator (RC32K) is forced on after reset, and output on PA20. The clock is
available on the pad until the PPCR.FRC32 bit in the Power Manager has been cleared or a different
peripheral function has been chosen on PA20 (PA20 will start with peripheral function F
by default). Note that the forcing will only enable the clock output. To be able to use the RC32K
normally the oscillator must be enabled as described below.
The oscillator is enabled by writing a one to the Enable bit in the 32kHz RC Oscillator Configuration
Register (RC32KCR.EN) and disabled by writing a zero to RC32KCR.EN. The oscillator is
also automatically enabled when the sampling mode is requested for the SM33. In this case,
writing a zero to RC32KCR.EN will not disable the RC32K until the sampling mode is no longer
requested.
14.5.14 Generic Clock Prescalers
Rev: 1.0.0.0
The generic clocks can be sourced by two special prescalers to increase the generic clock frequency
precision.
These prescalers are named the High Resolution Prescaler (HRP) and the Fractional Prescaler
(FP).
14.5.14.1 High resolution prescaler
The HRP is a 24-bit counter that can generate a very accurate clock waveform. The clock
obtained has 50% duty cycle.
261
32142D–06/2013
ATUC64/128/256L3/4U
Figure 14-7. High Resolution Prescaler Generation
The HRP is enabled by writing a one to the High Resolution Prescaler Enable (HRPEN) bit in the
High Resolution Prescaler Control Register (HRPCR).
The user can select a clock source for the HRP by writing to the Clock Selection (CKSEL) field of
the HRPCR register.
The user must configure the High Resolution Prescaler Clock (HRPCLK) frequency by writing to
the High Resolution Count (HRCOUNT) field of the High Resolution Counter (HRPCR) register.
This results in the output frequency:
fHRPCLK = fSRC / (2*(HRCOUNT+1))
The CKSEL field can not be changed dynamically but the HRCOUNT field can be changed onthe-fly.
14.5.14.2 Fractional prescaler
The FP generates a clock whose average frequency is more precise than the HRP. However,
this clock frequency is subject to jitter around the target clock frequency. This jitter influence can
be decreased by dividing this clock with the GCLK divider. Moreover the duty cycle of this clock
is not precisely 50%.
Figure 14-8. Fractional Prescaler Generation
The FP is enabled by writing a one to the FPEN bit in the Fractional Prescaler Control Register
(FPCR).
The user can select a clock source for the FP by writing to the CKSEL field of the FPCR register.
Divider
CKSEL
HRPCLK
HRCOUNT
Mask
HRPEN
Divider
CKSEL
FPCLK
FPDIV
Mask
FPMUL FPEN
262
32142D–06/2013
ATUC64/128/256L3/4U
The user must configure the FP frequency by writing to the FPMUL and FPDIV fields of the
FPMUL and FPDIV registers. FPMUL and FPDIV must not be equal to zero and FPDIV must be
greater or equal to FPMUL. This results in the output frequency:
fFPCLK = fSRC * FPMUL/ (2*FPDIV)
The CKSEL field can not be changed dynamically but the FPMUL and FPDIV fields can be
changed on-the-fly.
• Jitter description
As described in Figure 14-9, the CLKFP half period lengths are integer multiples of the source
clock period but are not always equals. However the difference between the low level half period
length and the high level half period length is at the most one source clock period.
This induces when FPDIV is not an integer multiple of FPMUL a jitter on the FPCLK. The more
the FPCLK frequency is low, the more the jitter incidence is reduced.
Figure 14-9. Fractional Prescaler Jitter Examples
14.5.15 Generic Clocks
Rev: 1.1.0.0
Timers, communication modules, and other modules connected to external circuitry may require
specific clock frequencies to operate correctly. The SCIF defines a number of generic clocks that
can provide a wide range of accurate clock frequencies.
Each generic clock runs from either clock source listed in the “Generic Clock Sources” table in
the SCIF Module Configuration section. The selected source can optionally be divided by any
even integer up to 512. Each clock can be independently enabled and disabled, and is also
automatically disabled along with peripheral clocks by the Sleep Controller in the Power
Manager.
SRC clock
FPCLK
FMUL= 5
FDIV=5
FMUL=3
FDIV=10
FMUL=7
FDIV=9
263
32142D–06/2013
ATUC64/128/256L3/4U
Figure 14-10. Generic Clock Generation
14.5.15.1 Enabling a generic clock
A generic clock is enabled by writing a one to the Clock Enable bit (CEN) in the Generic Clock
Control Register (GCCTRL). Each generic clock can individually select a clock source by writing
to the Oscillator Select field (OSCSEL). The source clock can optionally be divided by writing a
one to the Divide Enable bit (DIVEN) and the Division Factor field (DIV), resulting in the output
frequency:
where fSRC is the frequency of the selected source clock, and fGCLK is the output frequency of the
generic clock.
14.5.15.2 Disabling a generic clock
A generic clock is disabled by writing a zero to CEN or entering a sleep mode that disables the
PB clocks. In either case, the generic clock will be switched off on the first falling edge after the
disabling event, to ensure that no glitches occur. After CEN has been written to zero, the bit will
still read as one until the next falling edge occurs, and the clock is actually switched off. When
writing a zero to CEN the other bits in GCCTRL should not be changed until CEN reads as zero,
to avoid glitches on the generic clock. The generic clocks will be automatically re-enabled when
waking from sleep.
14.5.15.3 Changing clock frequency
When changing the generic clock frequency by changing OSCSEL or DIV, the clock should be
disabled before being re-enabled with the new clock source or division setting. This prevents
glitches during the transition.
14.5.15.4 Generic clock allocation
The generic clocks are allocated to different functions as shown in the “Generic Clock Allocation”
table in the SCIF Module Configuration section.
14.5.16 Interrupts
The SCIF has the following interrupt sources:
• AE - Access Error:
– A protected SCIF register was accessed without first being correctly unlocked.
Divider
OSCSEL
Generic Clock
DIV
0
1
DIVEN
Mask
CEN
Sleep Controller
fSRC fGCLK
Generic
Clock
Sources
f
GCLK
f
SRC
2 DIV + 1 = ----------------------------
264
32142D–06/2013
ATUC64/128/256L3/4U
• PLLLOCK - PLL Lock
– A 0 to 1 transition on the PCLKSR.PLLLOCK bit is detected.
• PLLLOCKLOST - PLL Lock Lost
– A to 1 transition on the PCLKSR.PLLLOCKLOST bit is detected.
• BRIFARDY - Backup Register Interface Ready.
– A 0 to 1 transition on the PCLKSR.BRIFARDY bit is detected.
• DFLL0RCS - DFLL Reference Clock Stopped:
– A 0 to 1 transition on the PCLKSR.DFLLRCS bit is detected.
• DFLL0RDY - DFLL Ready:
– A 0 to 1 transition on the PCLKSR.DFLLRDY bit is detected.
• DFLL0LOCKLOSTA - DFLL lock lost on Accurate value:
– A 0 to 1 transition on the PCLKSR.DFLLLOCKLOSTA bit is detected.
• DFLL0LOCKLOSTF - DFLL lock lost on Fine value:
– A 0 to 1 transition on the PCLKSR.DFLLLOCKLOSTF bit is detected.
• DFLL0LOCKLOSTC - DFLL lock lost on Coarse value:
– A 0 to 1 transition on the PCLKSR.DFLLLOCKLOSTC bit is detected.
• DFLL0LOCKA - DFLL Locked on Accurate value:
– A 0 to 1 transition on the PCLKSR.DFLLLOCKA bit is detected.
• DFLL0LOCKF - DFLL Locked on Fine value:
– A 0 to 1 transition on the PCLKSR.DFLLLOCKF bit is detected.
• DFLL0LOCKC - DFLL Locked on Coarse value:
– A 0 to 1 transition on the PCLKSR.DFLLLOCKC bit is detected.
• BODDET - Brown out detection:
– A 0 to 1 transition on the PCLKSR.BODDET bit is detected.
• SM33DET - Supply Monitor 3.3V Detector:
– A 0 to 1 transition on the PCLKSR.SM33DET bit is detected.
• VREGOK - Voltage Regulator OK:
– A 0 to 1 transition on the PCLKSR.VREGOK bit is detected.
• OSC0RDY - Oscillator Ready:
– A 0 to 1 transition on the PCLKSR.OSC0RDY bit is detected.
• OSC32RDY - 32KHz Oscillator Ready:
– A 0 to 1 transition on the PCLKSR.OSC32RDY bit is detected.
The interrupt sources will generate an interrupt request if the corresponding bit in the Interrupt
Mask Register is set. The interrupt sources are ORed together to form one interrupt request. The
SCIF will generate an interrupt request if at least one of the bits in the Interrupt Mask Register
(IMR) is set. Bits in IMR are set by writing a one to the corresponding bit in the Interrupt Enable
Register (IER), and cleared by writing a one to the corresponding bit in the Interrupt Disable
Register (IDR). The interrupt request remains active until the corresponding bit in the Interrupt
Status Register (ISR) is cleared by writing a one to the corresponding bit in the Interrupt Clear
Register (ICR). Because all the interrupt sources are ORed together, the interrupt request from
the SCIF will remain active until all the bits in ISR are cleared.
265
32142D–06/2013
ATUC64/128/256L3/4U
14.6 User Interface
Table 14-2. SCIF Register Memory Map
Offset Register Register Name Access Reset
0x0000 Interrupt Enable Register IER Write-only 0x00000000
0x0004 Interrupt Disable Register IDR Write-only 0x00000000
0x0008 Interrupt Mask Register IMR Read-only 0x00000000
0x000C Interrupt Status Register ISR Read-only 0x00000000
0x0010 Interrupt Clear Register ICR Write-only 0x00000000
0x0014 Power and Clocks Status Register PCLKSR Read-only 0x00000000
0x0018 Unlock Register UNLOCK Write-only 0x00000000
0x001C Oscillator 0 Control Register OSCCTRL0 Read/Write 0x00000000
0x0020 Oscillator 32 Control Register OSCCTRL32 Read/Write 0x00000004
0x0024 DFLL Config Register DFLL0CONF Read/Write 0x00000000
0x0028 DFLL Multiplier Register DFLL0MUL Write-only 0x00000000
0x002C DFLL Step Register DFLL0STEP Write-only 0x00000000
0x0030 DFLL Spread Spectrum Generator Control
Register DFLL0SSG Write-only 0x00000000
0x0034 DFLL Ratio Register DFLL0RATIO Read-only 0x00000000
0x0038 DFLL Synchronization Register DFLL0SYNC Write-only 0x00000000
0x003C BOD Level Register BOD Read/Write -(2)
0x0044 Voltage Regulator Calibration Register VREGCR Read/Write -(2)
0x0048 System RC Oscillator Calibration Register RCCR Read/Write -(2)
0x004C Supply Monitor 33 Calibration Register SM33 Read/Write -(2)
0x0050 Temperature Sensor Calibration Register TSENS Read/Write 0x00000000
0x0058 120MHz RC Oscillator Control Register RC120MCR Read/Write 0x00000000
0x005C-0x0068 Backup Registers BR Read/Write 0x00000000
0x006C 32kHz RC Oscillator Control Register RC32KCR Read/Write 0x00000000
0x0070 Generic Clock Control0 GCCTRL0 Read/Write 0x00000000
0x0074 Generic Clock Control1 GCCTRL1 Read/Write 0x00000000
0x0078 Generic Clock Control2 GCCTRL2 Read/Write 0x00000000
0x007C Generic Clock Control3 GCCTRL3 Read/Write 0x00000000
0x0080 Generic Clock Control4 GCCTRL4 Read/Write 0x00000000
0x0084 Generic Clock Control5 GCCTRL5 Read/Write 0x00000000
0x0088 Generic Clock Control6 GCCTRL6 Read/Write 0x00000000
0x008C Generic Clock Control7 GCCTRL7 Read/Write 0x00000000
0x0090 Generic Clock Control8 GCCTRL8 Read/Write 0x00000000
0x0094 Generic Clock Control9 GCCTRL9 Read/Write 0x00000000
266
32142D–06/2013
ATUC64/128/256L3/4U
Note: 1. The reset value is device specific. Please refer to the Module Configuration section at the end of this chapter.
2. The reset value of this register depends on factory calibration.
0x0098 PLL0 Control Register PLL0 Read/Write 0x00000000
0x009C High Resolution Prescaler Control Register HRPCR Read/Write 0x00000000
0x00A0 Fractional Prescaler Control Register FPCR Read/Write 0x00000000
0x00A4 Fractional Prescaler Multiplier Register FPMUL Read/Write 0x00000000
0x00A8 Fractional Prescaler DIVIDER Register FPDIV Read/Write 0x00000000
0x03BC Commonly used Modules Version Register CMVERSION Read-only -(1)
0x03C0 Generic Clock Prescaler Version Register GCLKPRESCVERSION Read-only -(1)
0x03C4 PLL Version Register PLLVERSION Read-only -(1)
0x03C8 Oscillator0 Version Register OSC0VERSION Read-only -(1)
0x03CC 32 KHz Oscillator Version Register OSC32VERSION Read-only -(1)
0x03D0 DFLL Version Register DFLLIFVERSION Read-only -(1)
0x03D4 BOD Version Register BODIFAVERSION Read-only -(1)
0x03D8 Voltage Regulator Version Register VREGIFBVERSION Read-only -(1)
0x03DC System RC Oscillator Version Register RCOSCIFAVERSION Read-only -(1)
0x03E0 3.3V Supply Monitor Version Register SM33IFAVERSION Read-only -(1)
0x03E4 Temperature Sensor Version Register TSENSIFAVERSION Read-only -(1)
0x03EC 120MHz RC Oscillator Version Register RC120MIFAVERSION Read-only -(1)
0x03F0 Backup Register Interface Version Register BRIFAVERSION Read-only -(1)
0x03F4 32kHz RC Oscillator Version Register RC32KIFAVERSION Read-only -(1)
0x03F8 Generic Clock Version Register GCLKVERSION Read-only -(1)
0x03FC SCIF Version Register VERSION Read-only -(1)
Table 14-2. SCIF Register Memory Map
Offset Register Register Name Access Reset
267
32142D–06/2013
ATUC64/128/256L3/4U
14.6.1 Interrupt Enable Register
Name: IER
Access Type: Write-only
Offset: 0x0000
Reset Value: 0x00000000
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will set the corresponding bit in IMR.
31 30 29 28 27 26 25 24
AE - - - - - - -
23 22 21 20 19 18 17 16
----- PLLLOCKLO
ST0 PLLLOCK0 BRIFARDY
15 14 13 12 11 10 9 8
DFLL0RCS DFLL0RDY DFLL0LOCK
LOSTA
DFLL0LOCK
LOSTF
DFLL0LOCK
LOSTC
DFLL0LOCK
A
DFLL0LOCK
F
DFLL0LOCK
C
76543210
BODDET SM33DET VREGOK - - - OSC0RDY OSC32RDY
268
32142D–06/2013
ATUC64/128/256L3/4U
14.6.2 Interrupt Disable Register
Name: IDR
Access Type: Write-only
Offset: 0x0004
Reset Value: 0x00000000
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will clear the corresponding bit in IMR.
31 30 29 28 27 26 25 24
AE - - - - - - -
23 22 21 20 19 18 17 16
----- PLLLOCKLO
ST0 PLLLOCK0 BRIFARDY
15 14 13 12 11 10 9 8
DFLL0RCS DFLL0RDY DFLL0LOCK
LOSTA
DFLL0LOCK
LOSTF
DFLL0LOCK
LOSTC
DFLL0LOCK
A
DFLL0LOCK
F
DFLL0LOCK
C
76543210
BODDET SM33DET VREGOK - - - OSC0RDY OSC32RDY
269
32142D–06/2013
ATUC64/128/256L3/4U
14.6.3 Interrupt Mask Register
Name: IMR
Access Type: Read-only
Offset: 0x0008
Reset Value: 0x00000000
0: The corresponding interrupt is disabled.
1: The corresponding interrupt is enabled.
A bit in this register is cleared when the corresponding bit in IDR is written to one.
A bit in this register is set when the corresponding bit in IER is written to one.
31 30 29 28 27 26 25 24
AE - - - - - - -
23 22 21 20 19 18 17 16
----- PLLLOCKLO
ST0 PLLLOCK0 BRIFARDY
15 14 13 12 11 10 9 8
DFLL0RCS DFLL0RDY DFLL0LOCK
LOSTA
DFLL0LOCK
LOSTF
DFLL0LOCK
LOSTC
DFLL0LOCK
A
DFLL0LOCK
F
DFLL0LOCK
C
76543210
BODDET SM33DET VREGOK - - - OSC0RDY OSC32RDY
270
32142D–06/2013
ATUC64/128/256L3/4U
14.6.4 Interrupt Status Register
Name: ISR
Access Type: Read-only
Offset: 0x000C
Reset Value: 0x00000000
0: The corresponding interrupt is cleared.
1: The corresponding interrupt is pending.
A bit in this register is cleared when the corresponding bit in ICR is written to one.
A bit in this register is set when the corresponding interrupt occurs.
31 30 29 28 27 26 25 24
AE - - - - - - -
23 22 21 20 19 18 17 16
----- PLLLOCKLO
ST0 PLLLOCK0 BRIFARDY
15 14 13 12 11 10 9 8
DFLL0RCS DFLL0RDY DFLL0LOCK
LOSTA
DFLL0LOCK
LOSTF
DFLL0LOCK
LOSTC
DFLL0LOCK
A
DFLL0LOCK
F
DFLL0LOCK
C
76543210
BODDET SM33DET VREGOK - - - OSC0RDY OSC32RDY
271
32142D–06/2013
ATUC64/128/256L3/4U
14.6.5 Interrupt Clear Register
Name: ICR
Access Type: Write-only
Offset: 0x0010
Reset Value: 0x00000000
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will clear the corresponding bit in ISR.
31 30 29 28 27 26 25 24
AE - - - - - - -
23 22 21 20 19 18 17 16
----- PLLLOCKLO
ST0 PLLLOCK0 BRIFARDY
15 14 13 12 11 10 9 8
DFLL0RCS DFLL0RDY DFLL0LOCK
LOSTA
DFLL0LOCK
LOSTF
DFLL0LOCK
LOSTC
DFLL0LOCK
A
DFLL0LOCK
F
DFLL0LOCK
C
76543210
BODDET SM33DET VREGOK - - - OSC0RDY OSC32RDY
272
32142D–06/2013
ATUC64/128/256L3/4U
14.6.6 Power and Clocks Status Register
Name: PCLKSR
Access Type: Read-only
Offset: 0x0014
Reset Value: 0x00000000
• BRIFAVALID: Backup Register Interface Valid
0: The values in the backup registers are not valid.
1: The values in the backup registers are valid.
• PLLL0LOCKLOST: PLL0 lock lost value
0: PLL0 has not lost it’s lock or has never been enabled.
1: PLL0 has lost it’s lock, either by disabling the PLL0 or due to faulty operation.
• PLL0LOCK: PLL0 Locked on Accurate value
0: PLL0 is unlocked on accurate value.
1: PLL0 is locked on accurate value, and is ready to be selected as clock source with an accurate output clock.
• BRIFARDY: Backup Register Interface Ready
0: The backup register interface is busy updating the backup registers. Writes to BRn will be discarded.
1: The backup register interface is ready to accept new writes to the backup registers.
• DFLL0RCS: DFLL0 Reference Clock Stopped
0: The DFLL reference clock is running, or has never been enabled.
1: The DFLL reference clock has stopped or is too slow.
• DFLL0RDY: DFLL0 Synchronization Ready
0: Read or write to DFLL registers is invalid
1: Read or write to DFLL registers is valid
• DFLL0LOCKLOSTA: DFLL0 Lock Lost on Accurate Value
0: DFLL has not lost its Accurate lock or has never been enabled.
1: DFLL has lost its Accurate lock, either by disabling the DFLL or due to faulty operation.
• DFLL0LOCKLOSTF: DFLL0 Lock Lost on Fine Value
0: DFLL has not lost its Fine lock or has never been enabled.
1: DFLL has lost its Fine lock, either by disabling the DFLL or due to faulty operation.
31 30 29 28 27 26 25 24
- BRIFAVALID - - - - - -
23 22 21 20 19 18 17 16
----- PLLLOCKLO
ST0 PLLLOCK0 BRIFARDY
15 14 13 12 11 10 9 8
DFLL0RCS DFLL0RDY DFLL0LOCK
LOSTA
DFLL0LOCK
LOSTF
DFLL0LOCK
LOSTC
DFLL0LOCK
A
DFLL0LOCK
F
DFLL0LOCK
C
76543210
BODDET SM33DET VREGOK - - - OSC0RDY OSC32RDY
273
32142D–06/2013
ATUC64/128/256L3/4U
• DFLL0LOCKLOSTC: DFLL0 Lock Lost on Coarse Value
0: DFLL has not lost its Coarse lock or has never been enabled.
1: DFLL has lost its Coarse lock, either by disabling the DFLL or due to faulty operation.
• DFLL0LOCKA: DFLL0 Locked on Accurate Value
0: DFLL is unlocked on Accurate value.
1: DFLL is locked on Accurate value, and is ready to be selected as clock source with an accurate output clock.
• DFLL0LOCKF: DFLL0 Locked on Fine Value
0: DFLL is unlocked on Fine value.
1: DFLL is locked on Fine value, and is ready to be selected as clock source with a high accuracy on the output clock.
• DFLL0LOCKC: DFLL0 Locked on Coarse Value
0: DFLL is unlocked on Coarse value.
1: DFLL is locked on Coarse value, and is ready to be selected as clock source with medium accuracy on the output clock.
• BODDET: Brown-Out Detection
0: No BOD Event.
1: BOD has detected that the supply voltage is below the BOD reference value.
• SM33DET: Supply Monitor 3.3V Detector
0: SM33 not enabled or the supply voltage is above the SM33 threshold.
1: SM33 enabled and the supply voltage is below the SM33 threshold.
• VREGOK: Voltage Regulator OK
0: Voltage regulator not enabled or not ready.
1: Voltage regulator has reached its output threshold value after being enabled.
• OSC0RDY: OSC0 Ready
0: Oscillator not enabled or not ready.
1: Oscillator is stable and ready to be used as clock source.
• OSC32RDY: 32 KHz oscillator Ready
0: OSC32K not enabled or not ready.
1: OSC32K is stable and ready to be used as clock source.
274
32142D–06/2013
ATUC64/128/256L3/4U
14.6.7 Unlock Register
Name: UNLOCK
Access Type: Write-only
Offset: 0x0018
Reset Value: 0x00000000
To unlock a write protected register, first write to the UNLOCK register with the address of the register to unlock in the ADDR
field and 0xAA in the KEY field. Then, in the next PB access write to the register specified in the ADDR field.
The LOCK is by default off. To turn on the LOCK, first write 0xAA to the KEY field and UNLOCK address offset to the ADDR field
in the UNLOCK register, followed by writing 0x5A5A5A5A to the UNLOCK register. To turn off the LOCK, first write 0xAA to the
KEY field and UNLOCK address offset to the ADDR field in the UNLOCK register, followed by writing 0xA5AA5A55 to the
UNLOCK register.
• KEY: Unlock Key
Write this bit field to 0xAA to enable unlock.
• ADDR: Unlock Address
Write the address offset of the register to unlock to this field.
31 30 29 28 27 26 25 24
KEY
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
- - - - - - ADDR[9:8]
76543210
ADDR[7:0]
275
32142D–06/2013
ATUC64/128/256L3/4U
14.6.8 Oscillator Control Register
Name: OSCCTRLn
Access Type: Read/Write
Reset Value: 0x00000000
• OSCEN: Oscillator Enable
0: The oscillator is disabled.
1: The oscillator is enabled.
• STARTUP: Oscillator Start-up Time
Select start-up time for the oscillator. Please refer to the “Oscillator Startup Time” table in the SCIF Module Configuration
section for details.
• AGC: Automatic Gain Control
For test purposes.
• GAIN: Gain
Selects the gain for the oscillator. Please refer to the “Oscillator Gain Settings” table in the SCIF Module Configuration section
for details.
• MODE: Oscillator Mode
0: External clock connected on XIN. XOUT can be used as general-purpose I/O (no crystal).
1: Crystal is connected to XIN/XOUT.
Note that this register is protected by a lock. To write to this register the UNLOCK register has to be written first. Please
refer to the UNLOCK register description for details.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
- - - - - - - OSCEN
15 14 13 12 11 10 9 8
- - - - STARTUP[3:0]
76543210
- - - - AGC GAIN[1:0] MODE
276
32142D–06/2013
ATUC64/128/256L3/4U
14.6.9 32KHz Oscillator Control Register
Name: OSCCTRL32
Access Type: Read/Write
Reset Value: 0x00000004
Note: This register is only reset by Power-On Reset
• RESERVED
This bit must always be written to zero.
• STARTUP: Oscillator Start-up Time
Select start-up time for 32 KHz oscillator
31 30 29 28 27 26 25 24
RESERVED -------
23 22 21 20 19 18 17 16
- - - - - STARTUP[2:0]
15 14 13 12 11 10 9 8
- - - - - MODE[2:0]
76543210
- - - - EN1K EN32K PINSEL OSC32EN
Table 14-3. Start-up Time for 32 KHz Oscillator
STARTUP
Number of RCSYS Clock
Cycle
Approximative Equivalent Time
(RCOSC = 115 kHz)
00 0
1 128 1.1 ms
2 8192 72.3 ms
3 16384 143 ms
4 65536 570 ms
5 131072 1.1 s
6 262144 2.3 s
7 524288 4.6 s
277
32142D–06/2013
ATUC64/128/256L3/4U
• MODE: Oscillator Mode
• EN1K: 1 KHz output Enable
0: The 1 KHz output is disabled.
1: The 1 KHz output is enabled.
• EN32K: 32 KHz output Enable
0: The 32 KHz output is disabled.
1: The 32 KHz output is enabled.
• PINSEL: Pins Select
0: Default pins used.
1: Alternate pins: XIN32_2 pin is used instead of XIN32 pin, XOUT32_2 pin is used instead of XOUT32.
• OSC32EN: 32 KHz Oscillator Enable
0: The 32 KHz Oscillator is disabled
1: The 32 KHz Oscillator is enabled
Table 14-4. Operation Mode for 32 KHz Oscillator
MODE Description
0 External clock connected to XIN32, XOUT32 can be used as general-purpose I/O (no crystal)
1 Crystal mode. Crystal is connected to XIN32/XOUT32.
2 Reserved
3 Reserved
4 Crystal and high current mode. Crystal is connected to XIN32/XOUT32.
5 Reserved
6 Reserved
7 Reserved
278
32142D–06/2013
ATUC64/128/256L3/4U
14.6.10 DFLLn Configuration Register
Name: DFLLnCONF
Access Type: Read/Write
Reset Value: 0x00000000
• COARSE: Coarse Calibration Value
Set the value of the coarse calibration register. If in closed loop mode, this field is Read-only.
• FINE: FINE Calibration Value
Set the value of the fine calibration register. If in closed loop mode, this field is Read-only.
• QLEN: Quick Lock Enable
0: Quick Lock is disabled.
1: Quick Lock is enabled.
• CCEN: Chill Cycle Enable
0: Chill Cycle is disabled.
1: Chill Cycle is enabled.
• LLAW: Lose Lock After Wake
0: Locks will not be lost after waking up from sleep modes.
1: Locks will be lost after waking up from sleep modes where the DFLL clock has been stopped.
• DITHER: Enable Dithering
0: The fine LSB input to the VCO is constant.
1: The fine LSB input to the VCO is dithered to achieve sub-LSB approximation to the correct multiplication ratio.
• MODE: Mode Selection
0: The DFLL is in open loop operation.
1: The DFLL is in closed loop operation.
• EN: Enable
0: The DFLL is disabled.
1: The DFLL is enabled.
Note that this register is protected by a lock. To write to this register the UNLOCK register has to be written first. Please
refer to the UNLOCK register description for details.
31 30 29 28 27 26 25 24
COARSE[7:0]
23 22 21 20 19 18 17 16
- - - - - - - FINE[8]
15 14 13 12 11 10 9 8
FINE[7:0]
76543210
- QLEN CCEN - LLAW DITHER MODE EN
279
32142D–06/2013
ATUC64/128/256L3/4U
14.6.11 DFLLn Multiplier Register
Name: DFLLnMUL
Access Type: Read/Write
Reset Value: 0x00000000
• IMUL: Integer Multiply Factor
This field, together with FMUL, determines the ratio between fDFLL and fREFthe DFLL. IMUL is the integer part, while the FMUL is
the fractional part.
In open loop mode, writing to this register has no effect.
• FMUL: Fractional Multiply Factor
This field, together with IMUL, determines the ratio between fDFLL and fREFthe DFLL. IMUL is the integer part, while the FMUL is
the fractional part.
In open loop mode, writing to this register has no effect.
Note that this register is protected by a lock. To write to this register the UNLOCK register has to be written first. Please
refer to the UNLOCK register description for details.
31 30 29 28 27 26 25 24
IMUL[15:8]
23 22 21 20 19 18 17 16
IMUL[7:0]
15 14 13 12 11 10 9 8
FMUL[15:8]
76543210
FMUL[7:0]
280
32142D–06/2013
ATUC64/128/256L3/4U
14.6.12 DFLLn Maximum Step Register
Name: DFLLnSTEP
Access Type: Read/Write
Reset Value: 0x00000000
• FSTEP: Fine Maximum Step
This indicates the maximum step size during fine adjustment in closed-loop mode. When adjusting to a new frequency, the
expected overshoot of that frequency depends on this step size.
• CSTEP: Coarse Maximum Step
This indicates the maximum step size during coarse adjustment in closed-loop mode. When adjusting to a new frequency, the
expected overshoot of that frequency depends on this step size.
Note that this register is protected by a lock. To write to this register the UNLOCK register has to be written first. Please
refer to the UNLOCK register description for details.
31 30 29 28 27 26 25 24
- - - - - - - FSTEP[8]
23 22 21 20 19 18 17 16
FSTEP[7:0]
15 14 13 12 11 10 9 8
--------
76543210
CSTEP[7:0]
281
32142D–06/2013
ATUC64/128/256L3/4U
14.6.13 DFLLn Spread Spectrum Generator Control Register
Name: DFLLnSSG
Access Type: Read/Write
Reset Value: 0x00000000
• STEPSIZE: SSG Step Size
Sets the step size of the spread spectrum.
• AMPLITUDE: SSG Amplitude
Sets the amplitude of the spread spectrum.
• PRBS: Pseudo Random Bit Sequence
0: Each spread spectrum frequency is applied at constant intervals
1: Each spread spectrum frequency is applied at pseudo-random intervals
• EN: Enable
0: SSG is disabled.
1: SSG is enabled.
Note that this register is protected by a lock. To write to this register the UNLOCK register has to be written first. Please
refer to the UNLOCK register description for details.
31 30 29 28 27 26 25 24
- -------
23 22 21 20 19 18 17 16
- - - STEPSIZE[4:0]
15 14 13 12 11 10 9 8
- - - AMPLITUDE[4:0]
76543210
- - - - - - PRBS EN
282
32142D–06/2013
ATUC64/128/256L3/4U
14.6.14 DFLLn Ratio Register
Name: DFLLnRATIO
Access Type: Read-only
Reset Value: 0x00000000
• RATIODIFF: Multiplication Ratio Difference
In closed-loop mode, this field indicates the error in the ratio between the VCO frequency and the target frequency.
• NUMREF: Numerical Reference
The number of reference clock cycles used to measure the VCO frequency equals 2^NUMREF.
31 30 29 28 27 26 25 24
RATIODIFF[15:8]
23 22 21 20 19 18 17 16
RATIODIFF[7:0]
15 14 13 12 11 10 9 8
- -------
76543210
- - - NUMREF[4:0]
283
32142D–06/2013
ATUC64/128/256L3/4U
14.6.15 DFLLn Synchronization Register
Name: DFLLnSYNC
Access Type: Write-only
Reset Value: 0x00000000
• SYNC: Synchronization
To be able to read the current value of DFLLnCONF or DFLLnRATIO in closed-loop mode, this bit should be written to one. The
updated value is available in DFLLnCONF and DFLLnRATIO when PCLKSR.DFLLnRDY is set.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
- - - - - - - SYNC
284
32142D–06/2013
ATUC64/128/256L3/4U
14.6.16 BOD Control Register
Name: BOD
Access Type: Read/Write
Reset Value: -
• SFV: Store Final Value
0: The register is read/write
1: The register is read-only, to protect against further accidental writes.
This bit is cleared after any reset except for a BOD reset, and during flash calibration.
• FCD: Fuse Calibration Done
0: The flash calibration will be redone after any reset.
1: The flash calibration will be redone after any reset except for a BOD reset.
This bit is cleared after any reset, except for a BOD reset.
This bit is set when the CTRL, HYST and LEVEL fields have been updated by the flash fuses after a reset.
• CTRL: BOD Control
• HYST: BOD Hysteresis
0: No hysteresis.
1: Hysteresis on.
• LEVEL: BOD Level
This field sets the triggering threshold of the BOD. See Electrical Characteristics for actual voltage levels.
Note that any change to the LEVEL field of the BOD register should be done with the BOD deactivated to avoid spurious reset
or interrupt.
31 30 29 28 27 26 25 24
SFV - - - - - - -
23 22 21 20 19 18 17 16
- - - - - - - FCD
15 14 13 12 11 10 9 8
- - - - - - CTRL
76543210
- HYST LEVEL
Table 14-5. Operation Mode for BOD
CTRL Description
0 BOD is disabled.
1 BOD is enabled and can reset the device. An interrupt request will be generated, if enabled in the IMR
register.
2 BOD is enabled but cannot reset the device. An interrupt request will be generated, if enabled in the IMR
register.
3 Reserved.
285
32142D–06/2013
ATUC64/128/256L3/4U
Note that this register is protected by a lock. To write to this register the UNLOCK register has to be written first. Please
refer to the UNLOCK register description for details.
286
32142D–06/2013
ATUC64/128/256L3/4U
14.6.17 Voltage Regulator Calibration Register
Name: VREGCR
Access Type: Read/Write
Reset Value: -
• SFV: Store Final Value
0: The register is read/write.
1: The register is read-only, to protect against further accidental writes.
This bit is cleared by a Power-on Reset.
• INTPD: Internal Pull-down
This bit is used for test purposes only.
0: The voltage regulator output is not pulled to ground.
1: The voltage regulator output has a pull-down to ground.
• POR18VALUE: Power-on Reset 1.8V Output Value
0: VDDCORE voltage is below the POR18 power-on threshold level.
1: VDDCORE voltage is above the POR18 power-on threshold level.
This bit is read-only. Writing to this bit has no effect.
• POR33VALUE: Power-on Reset 3.3V Output Value
0: Internal regulator supply voltage is below the POR33 power-on threshold level.
1: Internal regulator supply voltage is above the POR33 power-on threshold level.
This bit is read-only. Writing to this bit has no effect.
• POR18MASK: Power-on Reset 1.8V Output Mask
0: Power-on Reset is not masked.
1: Power-on Reset is masked.
• POR18STATUS: Power-on Reset 1.8V Status
0: Power-on Reset is disabled.
1: Power-on Reset is enabled.
This bit is read-only. Writing to this bit has no effect.
• POR18EN: Power-on Reset 1.8V Enable
Writing a zero to this bit disables the POR18 detector.
Writing a one to this bit enables the POR18 detector.
• POR33MASK: Power-on Reset 3.3V Output Mask
0: Power-on Reset 3.3V is not masked.
31 30 29 28 27 26 25 24
SFV INTPD - - - DBG- POR18VALUE POR33VALUE
23 22 21 20 19 18 17 16
POR18MASK POR18STAT
US POR18EN POR33MASK POR33STAT
US POR33EN DEEPDIS FCD
15 14 13 12 11 10 9 8
- - - - CALIB
76543210
ON VREGOK EN - - SELVDD
287
32142D–06/2013
ATUC64/128/256L3/4U
1: Power-on Reset 3.3V is masked.
• POR33STATUS: Power-on Reset 3.3V Status
0: Power-on Reset is disabled.
1: Power-on Reset is enabled.
This bit is read-only. Writing to this bit has no effect.
• POR33EN: Power-on Reset 3.3V Enable
0: Writing a zero to this bit disables the POR33 detector.
1: Writing a one to this bit enables the POR33 detector.
• DEEPDIS: Disable Regulator Deep Mode
0: Regulator will enter deep mode in low-power sleep modes for lower power consumption.
1: Regulator will stay in full-power mode in all sleep modes for shorter start-up time.
• FCD: Flash Calibration Done
0: The flash calibration will be redone after any reset.
1: The flash calibration will only be redone after a Power-on Reset.
This bit is cleared after a Power-on Reset.
This bit is set when the CALIB field has been updated by flash calibration after a reset.
• CALIB: Calibration Value
Calibration value for Voltage Regulator. This is calibrated during production and should not be changed.
• ON: Voltage Regulator On Status
0: The voltage regulator is currently disabled.
1: The voltage regulator is currently enabled.
This bit is read-only. Writing to this bit has no effect.
• VREGOK: Voltage Regulator OK Status
0: The voltage regulator is disabled or has not yet reached a stable output voltage.
1: The voltage regulator has reached the output voltage threshold level after being enabled.
This bit is read-only. Writing to this bit has no effect.
• EN: Enable
0: The voltage regulator is disabled.
1: The voltage regulator is enabled.
Note: This bit is set after a Power-on Reset (POR).
• SELVDD: Select VDD
Output voltage of the Voltage Regulator. The default value of this bit corresponds to an output voltage of 1.8V.
Note that this register is protected by a lock. To write to this register the UNLOCK register has to be written first. Please
refer to the UNLOCK register description for details.
288
32142D–06/2013
ATUC64/128/256L3/4U
14.6.18 System RC Oscillator Calibration Register
Name: RCCR
Access Type: Read/Write
Reset Value: -
• FCD: Flash Calibration Done
0: The flash calibration will be redone after any reset.
1: The flash calibration will only be redone after a Power-on Reset.
This bit is cleared after a POR.
This bit is set when the CALIB field has been updated by the flash fuses after a reset.
• CALIB: Calibration Value
Calibration Value for the System RC oscillator (RCSYS).
Note that this register is protected by a lock. To write to this register the UNLOCK register has to be written first. Please
refer to the UNLOCK register description for details.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
- - - - - - - FCD
15 14 13 12 11 10 9 8
- - - - - - CALIB[9:8]
76543210
CALIB[7:0]
289
32142D–06/2013
ATUC64/128/256L3/4U
14.6.19 Supply Monitor 33 Calibration Register
Name: SM33
Access Type: Read/Write
Reset Value: -
• SAMPFREQ: Sampling Frequency
Selects the sampling mode frequency of the 3.3V supply monitor. In sampling mode, the SM33 performs a measurement every
2(SAMPFREQ+5) cycles of the internal 32kHz RC oscillator.
• ONSM: Supply Monitor On Indicator
0: The supply monitor is disabled.
1: The supply monitor is enabled.
This bit is read-only. Writing to this bit has no effect.
• SFV: Store Final Value
0: The register is read/write
1: The register is read-only, to protect against further accidental writes.
This bit is cleared after a reset.
• FCD: Flash Calibration Done
This bit is cleared after a reset.
This bit is set when CALIB field has been updated after a reset.
• CALIB: Calibration Value
Calibration Value for the SM33.
• FS: Force Sampling Mode
0: Sampling mode is enabled in DeepStop and Static mode only.
1: Sampling mode is always enabled.
• CTRL: Supply Monitor Control
31 30 29 28 27 26 25 24
- - - - SAMPFREQ
23 22 21 20 19 18 17 16
- - - - - ONSM SFV FCD
15 14 13 12 11 10 9 8
- - - - CALIB
76543210
FS - - - CTRL
290
32142D–06/2013
ATUC64/128/256L3/4U
Selects the operating mode for the SM33.
Note that this register is protected by a lock. To write to this register the UNLOCK register has to be written first. Please
refer to the UNLOCK register description for details.
Table 14-6. Operation Mode for SM33
CTRL Description
0 SM33 is disabled.
1 SM33 is enabled and can reset the device. An interrupt request will be generated if the corresponding
interrupt is enabled in the IMR register.
2 SM33 is enabled and cannot reset the device. An interrupt request will be generated if the corresponding
interrupt is enabled in the IMR register.
3 SM33 is disabled
4-7 Reserved
291
32142D–06/2013
ATUC64/128/256L3/4U
14.6.20 Temperature Sensor Configuration Register
Name: TSENS
Access Type: Read/Write
Reset Value: 0x00000000
• EN: Temperature Sensor Enable
0: The Temperature Sensor is disabled.
1: The Temperature Sensor is enabled.
Note that this register is protected by a lock. To write to this register the UNLOCK register has to be written first. Please
refer to the UNLOCK register description for details.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
- - - - - EN
292
32142D–06/2013
ATUC64/128/256L3/4U
14.6.21 120MHz RC Oscillator Configuration Register
Name: RC120MCR
Access Type: Read/Write
Reset Value: 0x00000000
• EN: RC120M Enable
0: The 120 MHz RC oscillator is disabled.
1: The 120 MHz RC oscillator is enabled.
Note that this register is protected by a lock. To write to this register the UNLOCK register has to be written first. Please
refer to the UNLOCK register description for details.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
- - - - - - - EN
293
32142D–06/2013
ATUC64/128/256L3/4U
14.6.22 Backup Register n
Name: BRn
Access Type: Read/Write
Reset Value: 0x00000000
This is a set of general-purpose read/write registers. Data stored in these registers is retained when the device is in Shutdown.
Before writing to these registers the user must ensure that PCLKSR.BRIFARDY is not set.
Note that this registers are protected by a lock. To write to these registers the UNLOCK register has to be written first.
Please refer to the UNLOCK register description for details.
31 30 29 28 27 26 25 24
DATA[31:24]
23 22 21 20 19 18 17 16
DATA[23:16]
15 14 13 12 11 10 9 8
DATA[15:8]
76543210
DATA[7:0]
294
32142D–06/2013
ATUC64/128/256L3/4U
14.6.23 32kHz RC Oscillator Configuration Register
Name: RC32KCR
Access Type: Read/Write
Reset Value: 0x00000000
• EN: RC32K Enable
0: The 32 kHz RC oscillator is disabled.
1: The 32 kHz RC oscillator is enabled.
Note that this register is protected by a lock. To write to this register the UNLOCK register has to be written first. Please
refer to the UNLOCK register description for details.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
- - - - - - - EN
295
32142D–06/2013
ATUC64/128/256L3/4U
14.6.24 Generic Clock Control
Name: GCCTRL
Access Type: Read/Write
Reset Value: 0x00000000
There is one GCCTRL register per generic clock in the design.
• DIV: Division Factor
The number of DIV bits for each generic clock is as shown in the “Generic Clock number of DIV bits” table in the SCIF Module
Configuration section.
• OSCSEL: Oscillator Select
Selects the source clock for the generic clock. Please refer to the “Generic Clock Sources” table in the SCIF Module
Configuration section.
• DIVEN: Divide Enable
0: The generic clock equals the undivided source clock.
1: The generic clock equals the source clock divided by 2*(DIV+1).
• CEN: Clock Enable
0: The generic clock is disabled.
1: The generic clock is enabled.
31 30 29 28 27 26 25 24
DIV[15:8]
23 22 21 20 19 18 17 16
DIV[7:0]
15 14 13 12 11 10 9 8
- - - OSCSEL[4:0]
76543210
- - - - - - DIVEN CEN
296
32142D–06/2013
ATUC64/128/256L3/4U
14.6.25 PLL Control Register
Name: PLLn
Access Type: Read/Write
Reset Value: 0x00000000
• PLLCOUNT: PLL Count
Specifies the number of RCSYS clock cycles before ISR.PLLLOCKn will be set after PLLn has been written, or after PLLn has
been automatically re-enabled after exiting a sleep mode.
• PLLMUL: PLL Multiply Factor
• PLLDIV: PLL Division Factor
These fields determine the ratio of the PLL output frequency to the source oscillator frequency:
fvco = (PLLMUL+1)/PLLDIV • fREF if PLLDIV >0
fvco = 2•(PLLMUL+1) • fREF if PLLDIV = 0
Note that the PLLMUL field should always be greater than 1 or the behavior of the PLL will be undefined.
• PLLOPT: PLL Option
PLLOPT[0]: Selects the VCO frequency range (fvco).
0: 80MHz1
1
1
0
0
BaudRate SelectedClock
8 2 – OVER CD = -----------------------------------------------
438
32142D–06/2013
ATUC64/128/256L3/4U
The baud rate is calculated with the following formula (OVER=0):
The baud rate error is calculated with the following formula. It is not recommended to work with
an error higher than 5%.
20.6.1.3 Fractional Baud Rate in Asynchronous Mode
The baud rate generator has a limitation: the source frequency is always a multiple of the baud
rate. An approach to this problem is to integrate a high resolution fractional N clock generator,
outputting fractional multiples of the reference source clock. This fractional part is selected with
the Fractional Part field (BRGR.FP), and is activated by giving it a non-zero value. The resolution
is one eighth of CD. The resulting baud rate is calculated using the following formula:
The modified architecture is presented below:
Table 20-3. Baud Rate Example (OVER=0)
Source Clock (Hz)
Expected Baud
Rate (bit/s) Calculation Result CD Actual Baud Rate (bit/s) Error
3 686 400 38 400 6.00 6 38 400.00 0.00%
4 915 200 38 400 8.00 8 38 400.00 0.00%
5 000 000 38 400 8.14 8 39 062.50 1.70%
7 372 800 38 400 12.00 12 38 400.00 0.00%
8 000 000 38 400 13.02 13 38 461.54 0.16%
12 000 000 38 400 19.53 20 37 500.00 2.40%
12 288 000 38 400 20.00 20 38 400.00 0.00%
14 318 180 38 400 23.30 23 38 908.10 1.31%
14 745 600 38 400 24.00 24 38 400.00 0.00%
18 432 000 38 400 30.00 30 38 400.00 0.00%
24 000 000 38 400 39.06 39 38 461.54 0.16%
24 576 000 38 400 40.00 40 38 400.00 0.00%
25 000 000 38 400 40.69 40 38 109.76 0.76%
32 000 000 38 400 52.08 52 38 461.54 0.16%
32 768 000 38 400 53.33 53 38 641.51 0.63%
33 000 000 38 400 53.71 54 38 194.44 0.54%
40 000 000 38 400 65.10 65 38 461.54 0.16%
50 000 000 38 400 81.38 81 38 580.25 0.47%
60 000 000 38 400 97.66 98 38 265.31 0.35%
BaudRate CLKUSART = CD 16
Error 1 ExpectedBaudRate
ActualBaudRate
-------------------------------------------------- = –
BaudRate SelectedClock
8 2 – OVER CD FP
8
+ -------
= --------------------------------------------------------------------
439
32142D–06/2013
ATUC64/128/256L3/4U
Figure 20-3. Fractional Baud Rate Generator
20.6.1.4 Baud Rate in Synchronous and SPI Mode
If the USART is configured to operate in synchronous mode, the selected clock is divided by the
BRGR.CD field. This does not apply when CLK is selected.
When CLK is selected the external frequency must be at least 4.5 times lower than the system
clock, and when either CLK or CLK_USART/DIV are selected, CD must be even to ensure a
50/50 duty cycle. If CLK_USART is selected, the generator ensures this regardless of value.
20.6.2 Receiver and Transmitter Control
After a reset, the transceiver is disabled. The receiver/transmitter is enabled by writing a one to
either the Receiver Enable, or Transmitter Enable bit in the Control Register (CR.RXEN, or
CR.TXEN). They may be enabled together and can be configured both before and after they
have been enabled. The user can reset the USART receiver/transmitter at any time by writing a
one to either the Reset Receiver (CR.RSTRX), or Reset Transmitter (CR.RSTTX) bit. This software
reset clears status bits and resets internal state machines, immediately halting any
communication. The user interface configuration registers will retain their values.
The user can disable the receiver/transmitter by writing a one to either the Receiver Disable, or
Transmitter Disable bit (CR.RXDIS, or CR.TXDIS). If the receiver is disabled during a character
reception, the USART will wait for the current character to be received before disabling. If the
transmitter is disabled during transmission, the USART will wait until both the current character
and the character stored in the Transmitter Holding Register (THR) are transmitted before disabling.
If a timeguard has been implemented it will remain functional during the transaction.
USCLKS CD Modulus
Control
FP
FP
CD
glitch-free
logic
16-bit Counter
OVER
FIDI
SYNC
Sampling
Divider
CLK_USART
CLK_USART/DIV
Reserved CLK
CLK
BaudRate
Clock
Sampling
Clock
SYNC
USCLKS = 3
>1
1
2
3
0
0
1
0
1
1
0
0
BaudRate SelectedClock
CD = -------------------------------------
440
32142D–06/2013
ATUC64/128/256L3/4U
20.6.3 Synchronous and Asynchronous Modes
20.6.3.1 Transmitter Operations
The transmitter performs equally in both synchronous and asynchronous operating modes
(MR.SYNC). One start bit, up to 9 data bits, an optional parity bit, and up to two stop bits are
successively shifted out on the TXD pin at each falling edge of the serial clock. The number of
data bits is selected by the Character Length field (MR.CHRL) and the MR.MODE9 bit. Nine bits
are selected by writing a one to MODE9, overriding any value in CHRL. The parity bit configuration
is selected in the MR.PAR field. The Most Significant Bit First bit (MR.MSBF) selects which
data bit to send first. The number of stop bits is selected by the MR.NBSTOP field. The 1.5 stop
bit configuration is only supported in asynchronous mode.
Figure 20-4. Character Transmit
The characters are sent by writing to the Character to be Transmitted field (THR.TXCHR). The
transmitter reports status with the Transmitter Ready (TXRDY) and Transmitter Empty
(TXEMPTY) bits in the Channel Status Register (CSR). TXRDY is set when THR is empty.
TXEMPTY is set when both THR and the transmit shift register are empty (transmission complete).
Both TXRDY and TXEMPTY are cleared when the transmitter is disabled. Writing a
character to THR while TXRDY is zero has no effect and the written character will be lost.
Figure 20-5. Transmitter Status
20.6.3.2 Asynchronous Receiver
If the USART is configured in an asynchronous operating mode (MR.SYNC = 0), the receiver will
oversample the RXD input line by either 8 or 16 times the baud rate clock, as selected by the
Oversampling Mode bit (MR.OVER). If the line is zero for half a bit period (four or eight consecutive
samples, respectively), a start bit will be assumed, and the following 8th or 16th sample will
determine the logical value on the line, in effect resulting in bit values being determined at the
middle of the bit period.
D0 D1 D2 D3 D4 D5 D6 D7
TXD
Start
Bit
Parity
Bit
Stop
Bit
Example: 8-bit, Parity Enabled One Stop
Baud Rate
Clock
D0 D1 D2 D3 D4 D5 D6 D7
TXD
Start
Bit
Parity
Bit
Stop
Bit
Baud Rate
Clock
Start
Bit
Write
THR
D0 D1 D2 D3 D4 D5 D6 D7 Parity
Bit
Stop
Bit
TXRDY
TXEMPTY
441
32142D–06/2013
ATUC64/128/256L3/4U
The number of data bits, endianess, parity mode, and stop bits are selected by the same bits
and fields as for the transmitter (MR.CHRL, MODE9, MSBF, PAR, and NBSTOP). The synchronization
mechanism will only consider one stop bit, regardless of the used protocol, and when
the first stop bit has been sampled, the receiver will automatically begin looking for a new start
bit, enabling resynchronization even if there is a protocol miss-match. Figure 20-6 and Figure
20-7 illustrate start bit detection and character reception in asynchronous mode.
Figure 20-6. Asynchronous Start Bit Detection
Figure 20-7. Asynchronous Character Reception
20.6.3.3 Synchronous Receiver
In synchronous mode (SYNC=1), the receiver samples the RXD signal on each rising edge of
the Baud Rate Clock. If a low level is detected, it is considered as a start bit. Configuration bits
and fields are the same as in asynchronous mode.
Sampling
Clock (x16)
RXD
Start
Detection
Sampling
Baud Rate
Clock
RXD
Start
Rejection
Sampling
12345678
12345670 1234
12345678 9 10 11 12 13 14 15 16 D0
Sampling
D0 D1 D2 D3 D4 D5 D6 D7
RXD
Parity
Bit
Stop
Bit
Example: 8-bit, Parity Enabled
Baud Rate
Clock
Start
Detection
16
samples
16
samples
16
samples
16
samples
16
samples
16
samples
16
samples
16
samples
16
samples
16
samples
442
32142D–06/2013
ATUC64/128/256L3/4U
Figure 20-8. Synchronous Mode Character Reception
20.6.3.4 Receiver Operations
When a character reception is completed, it is transferred to the Received Character field in the
Receive Holding Register (RHR.RXCHR), and the Receiver Ready bit in the Channel Status
Register (CSR.RXRDY) is set. If RXRDY is already set, RHR will be overwritten and the Overrun
Error bit (CSR.OVRE) is set. Reading RHR will clear RXRDY, and writing a one to the Reset
Status bit in the Control Register (CR.RSTSTA) will clear OVRE.
Figure 20-9. Receiver Status
20.6.3.5 Parity
The USART supports five parity modes selected by MR.PAR. The PAR field also enables the
Multidrop mode, see ”Multidrop Mode” on page 443. If even parity is selected, the parity bit will
be a zero if there is an even number of ones in the data character, and if there is an odd number
it will be a one. For odd parity the reverse applies. If space or mark parity is chosen, the parity bit
will always be a zero or one, respectively. See Table 20-4.
D0 D1 D2 D3 D4 D5 D6 D7
RXD
Start Sampling
Parity Bit
Stop Bit
Example: 8-bit, Parity Enabled 1 Stop
Baud Rate
Clock
D0 D1 D2 D3 D4 D5 D6 D7
RXD
Start
Bit
Parity
Bit
Stop
Bit
Baud Rate
Clock
Write
CR
RXRDY
OVRE
D0 D1 D2 D3 D4 D5 D6 D7 Start
Bit
Parity
Bit
Stop
Bit
RSTSTA = 1
Read
RHR
Table 20-4. Parity Bit Examples
Alphanum
Character Hex Bin
Parity Mode
Odd Even Mark Space None
A 0x41 0100 0001 1 0 1 0 -
V 0x56 0101 0110 1 0 1 0 -
R 0x52 0101 0010 0 1 1 0 -
443
32142D–06/2013
ATUC64/128/256L3/4U
The receiver will report parity errors in CSR.PARE, unless parity is disabled. Writing a one to
CR.RSTSTA will clear PARE. See Figure 20-10
Figure 20-10. Parity Error
20.6.3.6 Multidrop Mode
If PAR is either 0x6 or 0x7, the USART runs in Multidrop mode. This mode differentiates data
and address characters. Data has the parity bit zero and addresses have a one. By writing a one
to the Send Address bit (CR.SENDA) the user will cause the next character written to THR to be
transmitted as an address. Receiving a character with a one as parity bit will set PARE.
20.6.3.7 Transmitter Timeguard
The timeguard feature enables the USART to interface slow devices by inserting an idle state on
the TXD line in between two characters. This idle state corresponds to a long stop bit, whose
duration is selected by the Timeguard Value field in the Transmitter Timeguard Register
(TTGR.TG). The transmitter will hold the TXD line high for TG bit periods, in addition to the number
of stop bits. As illustrated in Figure 20-11, the behavior of TXRDY and TXEMPTY is modified
when TG has a non-zero value. If a pending character has been written to THR, the TXRDY bit
will not be set until this characters start bit has been sent. TXEMPTY will remain low until the
timeguard transmission has completed.
Figure 20-11. Timeguard Operation
D0 D1 D2 D3 D4 D5 D6 D7
RXD
Start
Bit
Bad
Parity
Bit
Stop
Bit
Baud Rate
Clock
Write
CR
PARE
RXRDY
RSTSTA = 1
D0 D1 D2 D3 D4 D5 D6 D7
TXD
Start
Bit
Parity
Bit
Stop
Bit
Baud Rate
Clock
Start
Bit
TG = 4
Write
THR
D0 D1 D2 D3 D4 D5 D6 D7 Parity
Bit
Stop
Bit
TXRDY
TXEMPTY
TG = 4
444
32142D–06/2013
ATUC64/128/256L3/4U
Table 20-5. Maximum Baud Rate Dependent Timeguard Durations
20.6.3.8 Receiver Time-out
The Time-out Value field in the Receiver Time-out Register (RTOR.TO) enables handling of variable-length
frames by detection of selectable idle durations on the RXD line. The value written to
TO is loaded to a decremental counter, and unless it is zero, a time-out will occur when the
amount of inactive bit periods match the initial counter value. If a time-out has not occurred, the
counter will reload and restart every time a new character arrives. A time-out sets the TIMEOUT
bit in CSR. Clearing TIMEOUT can be done in two ways:
• Writing a one to the Start Time-out bit (CR.STTTO). This also aborts count down until the
next character has been received.
• Writing a one to the Reload and Start Time-out bit (CR.RETTO). This also reloads the
counter and restarts count down immediately.
Figure 20-12. Receiver Time-out Block Diagram
Table 20-6. Maximum Time-out Period
Baud Rate (bit/sec) Bit time (µs) Timeguard (ms)
1 200 833 212.50
9 600 104 26.56
14400 69.4 17.71
19200 52.1 13.28
28800 34.7 8.85
33400 29.9 7.63
56000 17.9 4.55
57600 17.4 4.43
115200 8.7 2.21
Baud Rate (bit/sec) Bit Time (µs) Time-out (ms)
600 1 667 109 225
1 200 833 54 613
2 400 417 27 306
4 800 208 13 653
16-bit Time-out
Counter
0
TO
TIMEOUT
Baud Rate
Clock
=
Character
Received
RETTO
Load
Clock
16-bit
Value
STTTO
1 D Q
Clear
445
32142D–06/2013
ATUC64/128/256L3/4U
20.6.3.9 Framing Error
The receiver is capable of detecting framing errors. A framing error has occurred if a stop bit
reads as zero. This can occur if the transmitter and receiver are not synchronized. A framing
error is reported by CSR.FRAME as soon as the error is detected, at the middle of the stop bit.
Figure 20-13. Framing Error Status
20.6.3.10 Transmit Break
When TXRDY is set, the user can request the transmitter to generate a break condition on the
TXD line by writing a one to The Start Break bit (CR.STTBRK). The break is treated as a normal
0x00 character transmission, clearing TXRDY and TXEMPTY, but with zeroes for preambles,
start, parity, stop, and time guard bits. Writing a one to the Stop Break bit (CR.STBRK) will stop
the generation of new break characters, and send ones for TG duration or at least 12 bit periods,
ensuring that the receiver detects end of break, before resuming normal operation. Figure 20-14
illustrates STTBRK and STPBRK effect on the TXD line.
Writing to STTBRK and STPBRK simultaneously can lead to unpredictable results. Writes to
THR before a pending break has started will be ignored.
9 600 104 6 827
14400 69 4 551
19200 52 3 413
28800 35 2 276
33400 30 1 962
56000 18 1 170
57600 17 1 138
200000 5 328
Baud Rate (bit/sec) Bit Time (µs) Time-out (ms)
D0 D1 D2 D3 D4 D5 D6 D7
RXD
Start
Bit
Parity
Bit
Stop
Bit
Baud Rate
Clock
Write
CR
FRAME
RXRDY
RSTSTA = 1
446
32142D–06/2013
ATUC64/128/256L3/4U
Figure 20-14. Break Transmission
20.6.3.11 Receive Break
A break condition is assumed when incoming data, parity, and stop bits are zero. This corresponds
to a framing error, but FRAME will remain zero while the Break Received/End Of Break
bit (CSR.RXBRK) is set. Writing a one to CR.RSTSTA will clear RXBRK. An end of break will
also set RXBRK, and is assumed when TX is high for at least 2/16 of a bit period in asynchronous
mode, or when a high level is sampled in synchronous mode.
20.6.3.12 Hardware Handshaking
The USART features an out-of-band hardware handshaking flow control mechanism, implementable
by connecting the RTS and CTS pins with the remote device, as shown in Figure 20-
15.
Figure 20-15. Connection with a Remote Device for Hardware Handshaking
Writing 0x2 to the MR.MODE field configures the USART to operate in this mode. The receiver
will drive its RTS pin high when disabled or when the Reception Buffer Full bit (CSR.RXBUFF) is
set by the Buffer Full signal from the Peripheral DMA controller. If the receivers RTS pin is high,
the transmitters CTS pin will also be high and only the active character transactions will be completed.
Allocating a new buffer to the DMA controller by clearing RXBUFF, will drive the RTS pin
low, allowing the transmitter to resume transmission. Detected level changes on the CTS pin
can trigger interrupts, and are reported by the CTS Input Change bit in the Channel Status Register
(CSR.CTSIC).
Figure 20-16 illustrates receiver functionality, and Figure 20-17 illustrates transmitter
functionality.
D0 D1 D2 D3 D4 D5 D6 D7
TXD
Start
Bit
Parity
Bit
Stop
Bit
Baud Rate
Clock
Write
CR
TXRDY
TXEMPTY
STTBRK = 1 STPBRK = 1
Break Transmission End of Break
USART
TXD
CTS
Remote
Device
RXD
RXD TXD
RTS
RTS
CTS
447
32142D–06/2013
ATUC64/128/256L3/4U
Figure 20-16. Receiver Behavior when Operating with Hardware Handshaking
Figure 20-17. Transmitter Behavior when Operating with Hardware Handshaking
Figure 20-18.
20.6.4 SPI Mode
The USART features a Serial Peripheral Interface (SPI) link compliant mode, supporting synchronous,
full-duplex communication, in both master and slave mode. Writing 0xE (master) or
0xF (slave) to MR.MODE will enable this mode. A SPI in master mode controls the data flow to
and from the other SPI devices, who are in slave mode. It is possible to let devices take turns
being masters (aka multi-master protocol), and one master may shift data simultaneously into
several slaves, but only one slave may respond at a time. A slave is selected when its slave
select (NSS) signal has been raised by the master. The USART can only generate one NSS signal,
and it is possible to use standard I/O lines to address more than one slave.
20.6.4.1 Modes of Operation
The SPI system consists of two data lines and two control lines:
• Master Out Slave In (MOSI): This line supplies the data shifted from master to slave. In
master mode this is connected to TXD, and in slave mode to RXD.
• Master In Slave Out (MISO): This line supplies the data shifted from slave to master. In
master mode this is connected to RXD, and in slave mode to TXD.
• Serial Clock (CLK): This is controlled by the master. One period per bit transmission. In both
modes this is connected to CLK.
• Slave Select (NSS): This control line allows the master to select or deselect a slave. In
master mode this is connected to RTS, and in slave mode to CTS.
Changing SPI mode after initial configuration has to be followed by a transceiver software reset
in order to avoid unpredictable behavior.
20.6.4.2 Baud Rate
The baud rate generator operates as described in ”Baud Rate in Synchronous and SPI Mode”
on page 439, with the following requirements:
In SPI Master Mode:
RTS
RXBUFF
Write
CR
RXEN = 1
RXD
RXDIS = 1
CTS
TXD
448
32142D–06/2013
ATUC64/128/256L3/4U
• The Clock Selection field (MR.USCLKS) must not equal 0x3 (external clock, CLK).
• The Clock Output Select bit (MR.CLKO) must be one.
• The BRGR.CD field must be at least 0x4.
• If USCLKS is one (internal divided clock, CLK_USART/DIV), the value in CD has to be even,
ensuring a 50:50 duty cycle. CD can be odd if USCLKS is zero (internal clock, CLK_USART).
In SPI Slave Mode:
• CLK frequency must be at least four times lower than the system clock.
20.6.4.3 Data Transfer
• Up to nine data bits are successively shifted out on the TXD pin at each edge. There are no
start, parity, or stop bits, and MSB is always sent first. The SPI Clock Polarity (MR.CPOL),
and SPI Clock Phase (MR.CPHA) bits configure CLK by selecting the edges upon which bits
are shifted and sampled, resulting in four non-interoperable protocol modes see Table 20-7.
A master/slave pair must use the same configuration, and the master must be reconfigured if
it is to communicate with slaves using different configurations. See Figures 20-19 and 20-20.
Figure 20-19. SPI Transfer Format (CPHA=1, 8 bits per transfer)
Table 20-7. SPI Bus Protocol Modes
SPI Bus Protocol Mode CPOL CPHA
0 01
1 00
2 11
3 10
CLK cycle (for reference)
CLK
(CPOL= 1)
MOSI
SPI Master ->TXD
SPI Slave ->RXD
MISO
SPI Master ->RXD
SPI Slave ->TXD
NSS
SPI Master ->RTS
SPI Slave ->CTS
MSB
MSB
1
CLK
(CPOL= 0)
3 5 6 7 8
4 3 2 1 LSB
6
6 5
5 4 3 2 1 LSB
2 4
449
32142D–06/2013
ATUC64/128/256L3/4U
Figure 20-20. SPI Transfer Format (CPHA=0, 8 bits per transfer)
20.6.4.4 Receiver and Transmitter Control
See ”Transmitter Operations” on page 440, and ”Receiver Operations” on page 442.
20.6.4.5 Character Transmission and Reception
In SPI master mode, the slave select line (NSS) is asserted low one bit period before the start of
transmission, and released high one bit period after every character transmission. A delay for at
least three bit periods is always inserted in between characters. In order to address slave
devices supporting the Chip Select Active After Transfer (CSAAT) mode, NSS can be forced low
by writing a one to the Force SPI Chip Select bit (CR.RTSEN/FCS). Releasing NSS when FCS
is one, is only possible by writing a one to the Release SPI Chip Select bit (CR.RTSDIS/RCS).
In SPI slave mode, a low level on NSS for at least one bit period will allow the slave to initiate a
transmission or reception. The Underrun Error bit (CSR.UNRE) is set if a character must be sent
while THR is empty, and TXD will be high during character transmission, as if 0xFF was being
sent. If a new character is written to THR it will be sent correctly during the next transmission
slot. Writing a one to CR.RSTSTA will clear UNRE. To ensure correct behavior of the receiver in
SPI slave mode, the master device sending the frame must ensure a minimum delay of one bit
period in between each character transmission.
20.6.4.6 Receiver Time-out
Receiver Time-out’s are not possible in SPI mode as the baud rate clock is only active during
data transfers.
20.6.5 LIN Mode
The USART features a LIN (Local Interconnect Network) 1.3 and 2.0 compliant mode, embedding
full error checking and reporting, automatic frame processing with up to 256 data bytes,
CLK cycle (for reference)
CLK
(CPOL= 0)
CLK
(CPOL= 1)
MOSI
SPI Master -> TXD
SPI Slave -> RXD
MISO
SPI Master -> RXD
SPI Slave -> TXD
NSS
SPI Master -> RTS
SPI Slave -> CTS
MSB 6 5
MSB 6 5
4
4 3
3 2
2 1
1 LSB
LSB
1 2 3 4 5 6 7 8
450
32142D–06/2013
ATUC64/128/256L3/4U
customizable response data lengths, and requires minimal CPU resources. Writing 0xA (master)
or 0xB (slave) to MR.MODE enables this mode.
20.6.5.1 Modes of operation
Changing LIN mode after initial configuration has to be followed by a transceiver software reset
in order to avoid unpredictable behavior.
20.6.5.2 Receiver and Transmitter Control
See Section “20.6.2” on page 439.
20.6.5.3 Baud Rate Configuration
The LIN nodes baud rate is configured in the Baud Rate Generator Register (BRGR), See Section
“20.6.1.1” on page 437.
20.6.5.4 Character Transmission and Reception
See ”Transmitter Operations” on page 440, and ”Receiver Operations” on page 442.
20.6.5.5 Header Transmission (Master Node Configuration)
All LIN frames start with a header sent by the master. As soon as the identifier has been written
to the Identifier Character field in the LIN Identifier Register (LINIR.IDCHR), TXRDY is cleared
and the header is sent. The header consists of a Break, Sync, and Identifier field. TXRDY is set
when the identifier has been transferred into the transmitters shift register.
The Break field consists of 13 dominant bits, the break, and one recessive bit, the break delimiter.
The Sync field is the character 0x55. The Identifier field contains the Identifier as written to
IDCHR. The identifier parity bits can be generated automatically (see Section 20.6.5.8).
Figure 20-21. Header Transmission
20.6.5.6 Header Reception (Slave Node Configuration)
The USART stays idle until it detects a break field, consisting of at least 11 consecutive dominant
bits (zeroes) on the bus. A received break will set the Lin Break bit (CSR.LINBK). The Sync
field is used to synchronize the baud rate (see Section 20.6.5.7). IDCHR is updated and the LIN
Identifier bit (CSR.LINID) is set when the Identifier has been received. The Identifier parity bits
can be automatically checked (see Section 20.6.5.8). Writing a one to RSTSTA will clear LINBK
and LINID.
TXD
Baud Rate
Clock
Start
Bit
Write
LINIR
10101010
TXRDY
Stop
Bit
Start
Bit Break Field ID0 ID1 ID2 ID3 ID4 ID5 ID6 ID7
13 dominant bits (at 0)
Stop
Bit
Break
Delimiter
1 recessive bit
(at 1)
Synch Byte = 0x55
LINIR ID
451
32142D–06/2013
ATUC64/128/256L3/4U
Figure 20-22. Header Reception
20.6.5.7 Slave Node Synchronization
Synchronization is only done by the slave. If the Sync field is not 0x55, an Inconsistent Sync
Field error (CSR.LINISFE) is generated. The time between falling edges is measured by a 19-bit
counter, driven by the sampling clock (see Section 20.6.1).
Figure 20-23. Sync Field
The counter starts when the Sync field start bit is detected, and continues for eight bit periods.
The 16 most significant bits (counter value divided by 8) becomes the new clock divider
(BRGR.CD), and the three least significant bits (the remainder) becomes the new fractional part
(BRGR.FP).
Figure 20-24. Slave Node Synchronization
The synchronization accuracy depends on:
• The theoretical slave node clock frequency; nominal clock frequency (FNom)
• The baud rate
Break Field
13 dominant bits (at 0)
Break
Delimiter
1 recessive bit
(at 1)
Start
Bit 10101010 Stop
Bit
Start
Bit ID0 ID1 ID2 ID4 ID3 ID6 ID5 ID7 Stop
Bit
Synch Byte = 0x55
Baud Rate
Clock
RXD
Write US_CR
With RSTSTA=1
US_LINIR
LINID
Start
bit
Stop
bit
Synch Field
8 Tbit
2 Tbit 2 Tbit 2 Tbit 2 Tbit
RXD
Baud Rate
Clock
LINIDRX
Synchro Counter 000_0011_0001_0110_1101
BRGR
Clcok Divider (CD)
0000_0110_0010_1101
BRGR
Fractional Part (FP)
101
Initial CD
Initial FP
Reset
Start
Bit 10101010 Stop
Bit
Start
Bit Break Field ID0 ID1 ID2 ID3 ID4 ID5 ID6 ID7
13 dominant bits (at 0)
Stop
Bit
Break
Delimiter
1 recessive bit
(at 1)
Synch Byte = 0x55
452
32142D–06/2013
ATUC64/128/256L3/4U
• The oversampling mode (OVER=0 => 16x, or OVER=1 => 8x)
The following formula is used to calculate synchronization deviation, where FSLAVE is the real
slave node clock frequency, and FTOL_UNSYNC is the difference between FNom and FSLAVE According
to the LIN specification, FTOL_UNSYNCH may not exceed ±15%, and the bit rates between two
nodes must be within ±2% of each other, resulting in a maximal BaudRate_deviation of ±1%.
Minimum nominal clock frequency with a fractional part:
Examples:
• Baud rate = 20 kbit/s, OVER=0 (Oversampling 16x) => FNom(min) = 2.64 MHz
• Baud rate = 20 kbit/s, OVER=1 (Oversampling 8x) => FNom(min) = 1.47 MHz
• Baud rate = 1 kbit/s, OVER=0 (Oversampling 16x) => FNom(min) = 132 kHz
• Baud rate = 1 kbit/s, OVER=1 (Oversampling 8x) => FNom(min) = 74 kHz
If the fractional part is not used, the synchronization accuracy is much lower. The 16 most significant
bits, added with the first least significant bit, becomes the new clock divider (CD). The
equation of the baud rate deviation is the same as above, but the constants are:
Minimum nominal clock frequency without a fractional part:
Examples:
• Baud rate = 20 kbit/s, OVER=0 (Oversampling 16x) => FNom(min) = 19.12 MHz
• Baud rate = 20 kbit/s, OVER=1 (Oversampling 8x) => FNom(min) = 9.71 MHz
• Baud rate = 1 kbit/s, OVER=0 (Oversampling 16x) => FNom(min) = 956 kHz
• Baud rate = 1 kbit/s, OVER=1 (Oversampling 8x) => FNom(min) = 485 kHz
20.6.5.8 Identifier Parity
An identifier field consists of two sub-fields; the identifier and its parity. Bits 0 to 5 are assigned
to the identifier, while bits 6 and 7 are assigned to parity. Automatic parity management is disabled
by writing a one to the Parity Disable bit in the LIN Mode register (LINMR.PARDIS).
BaudRate_deviation 100 8 2 OVER – + BaudRate
8 FSLAVE -------------------------------------------------------------------------------------------------- = %
BaudRate_deviation 100 8 2 OVER – + BaudRate
8
FTOL_UNSYNC
100 ----------------------------------- xFNom
--------------------------------------------------------------------------------------------------
= %
–0.5 +0.5 -1 +1
FNom min 100 0.5 8 2 OVER – + 1 BaudRate
8 –15
100
--------- + 1 1%
------------------------------------------------------------------------------------------------------
= Hz
–4 +4 -1 +1
FNom min 100 4 8 2 OVER – + 1 Baudrate
8 –15
100
--------- + 1 1%
-----------------------------------------------------------------------------------------------
= Hz
453
32142D–06/2013
ATUC64/128/256L3/4U
• PARDIS=0: During header transmission, the parity bits are computed and in the shift register
they replace bits six and seven from IDCHR. During header reception, the parity bits are
checked and can generate a LIN Identifier Parity Error (see Section 20.6.6). Bits six and
seven in IDCHR read as zero when receiving.
• PARDIS=1: During header transmission, all the bits in IDCHR are sent on the bus. During
header reception, all the bits in IDCHR are updated with the received Identifier.
20.6.5.9 Node Action
After an identifier transaction, a LIN response mode has to be selected. This is done in the Node
Action field (LINMR.NACT). Below are some response modes exemplified in a small LIN cluster:
• Response, from master to slave1:
Master: NACT=PUBLISH
Slave1: NACT=SUBSCRIBE
Slave2: NACT=IGNORE
• Response, from slave1 to master:
Master: NACT=SUBSCRIBE
Slave1: NACT=PUBLISH
Slave2: NACT=IGNORE
• Response, from slave1 to slave2:
Master: NACT=IGNORE
Slave1: NACT=PUBLISH
Slave2: NACT=SUBSCRIBE
20.6.5.10 LIN Response Data Length
The response data length is the number of data fields (bytes), excluding the checksum.
Figure 20-25. Response Data Length
The response data length can be configured, either by the user, or automatically by bits 4 and 5
in the Identifier (IDCHR), in accordance to LIN 1.1. The user selects mode by writing to the Data
Length Mode bit (LINMR.DML):
• DLM=0: the response data length is configured by the user by writing to the 8-bit Data Length
Control field (LINMR.DLC). The response data length equals DLC + 1 bytes.
User configuration: 1 - 256 data fields (DLC+1)
Identifier configuration: 2/4/8 data fields
Sync
Break
Sync
Field
Identifier
Field
Checksum
Field
Data
Field
Data
Field
Data
Field
Data
Field
454
32142D–06/2013
ATUC64/128/256L3/4U
• DLM=1: the response data length is defined by the Identifier bits according to the table below.
20.6.5.11 Checksum
The last frame field is the checksum. It is configured by the Checksum Type (LINMR.CHKTYP),
and the Checksum Disable (LINMR.CHKDIS) bits. TXRDY will not be set after the last THR data
write if enabled. Writing a one to CHKDIS will disable the automatic checksum generation/checking,
and the user may send/check this last byte manually, disguised as a normal data.
The checksum is an inverted 8-bit sum with carry, either:
• over all data bytes, called a classic checksum. This is used for LIN 1.3 compliant slaves, and
automatically managed when CHKDIS=0, and CHKTYP=1.
• over all data bytes and the protected identifier, called an enhanced checksum. This is used
for LIN 2.0 compliant slaves, and automatically managed when CHKDIS=0, and CHKTYP=0.
20.6.5.12 Frame Slot Mode
A LIN master can be configured to use frame slots with a pre-defined minimum length. Writing a
one to the Frame Slot Mode Disable bit (LINMR.FSDIS) disables this mode. This mode will not
allow TXRDY to be set after a frame transfer until the entire frame slot duration has elapsed, in
effect preventing the master from sending a new header. The LIN Transfer Complete bit
(CSR.LINTC) will still be set after the checksum has been sent. Writing a one to CR.RSTST
clears LINTC.
Figure 20-26. Frame Slot Mode with Automatic Checksum
The minimum frame slot size is determined by TFrame_Maximum, and calculated below (all values
in bit periods):
• THeader_Nominal = 34
Table 20-8. Response Data Length if DLM = 1
IDCHR[5] IDCHR[4] Response Data Length [bytes]
00 2
01 2
10 4
11 8
Break Synch Protected
Identifier
Data N Checksum
Header
Interframe
space Response
space
Frame
Frame slot = TFrame_Maximum
Response
TXRDY
Write
THR
Write
LINID
Data 1 Data 2 Data 3
Data3
Data N-1
Data N
Frame Slot Mode
Disabled
Frame Slot Mode
Enabled
LINTC
Data 1
455
32142D–06/2013
ATUC64/128/256L3/4U
• TFrame_Maximum = 1.4 x (THeader_Nominal + TResponse_Nominal + 1)(Note:)
Note: The term “+1” leads to an integer result for TFrame_Max (LIN Specification 1.3)
If the Checksum is sent (CHKDIS=0):
• TResponse_Nominal = 10 x (NData + 1)
• TFrame_Maximum = 1.4 x (34 + 10 x (DLC + 1 + 1) + 1)
• TFrame_Maximum = 77 + 14 x DLC
If the Checksum is not sent (CHKDIS=1):
• TResponse_Nominal = 10 x NData
• TFrame_Maximum = 1.4 x (34 + 10 x (DLC + 1) + 1)
• TFrame_Maximum = 63 + 14 x DLC
20.6.6 LIN Errors
These error bits are cleared by writing a one to CSR.RSTSTA.
20.6.6.1 Slave Not Responding Error (CSR.LINSNRE)
This error is generated if no valid message appears within the TFrame_Maximum time frame
slot, while the USART is expecting a response from another node (NACT=SUBSCRIBE).
20.6.6.2 Checksum Error (CSR.LINCE)
This error is generated if the received checksum is wrong. This error can only be generated if the
checksum feature is enabled (CHKDIS=0).
20.6.6.3 Identifier Parity Error (CSR.LINIPE)
This error is generated if the identifier parity is wrong. This error can only be generated if parity is
enabled (PARDIS=0).
20.6.6.4 Inconsistent Sync Field Error (CSR.LINISFE)
This error is generated in slave mode if the Sync Field character received is not 0x55. Synchronization
procedure is aborted.
20.6.6.5 Bit Error (CSR.LINBE)
This error is generated if the value transmitted by the USART on Tx differs from the value sampled
on Rx. If a bit error is detected, the transmission is aborted at the next byte border.
20.6.7 LIN Frame Handling
20.6.7.1 Master Node Configuration
• Write a one to CR.TXEN and CR.RXEN to enable both transmitter and receiver
• Select LIN mode and master node by writing to MR.MODE
• Configure the baud rate by writing to CD and FP in BRGR
• Configure the frame transfer by writing to NACT, PARDIS, CHKDIS, CHKTYPE, DLCM,
FSDIS, and DLC in LINMR
• Check that CSR.TXRDY is one
• Send the header by writing to LINIR.IDCHR
The following procedure depends on the NACT setting:
456
32142D–06/2013
ATUC64/128/256L3/4U
• Case 1: NACT=PUBLISH, the USART sends a response
– Wait until TXRDY is a one
– Send a byte by writing to THR.TXCHR
– Repeat the two previous steps until there is no more data to send
– Wait until CSR.LINTC is a one
– Check for LIN errors
• Case 2: NACT=SUBSCRIBE, the USART receives a response
– Wait until RXRDY is a one
– Read RHR.RXCHR
– Repeat the two previous steps until there is no more data to read
– Wait until LINTC is a one
– Check for LIN errors
• Case 3: NACT=IGNORE, the USART is not concerned by a response
– Wait until LINTC is a one
– Check for LIN errors
Figure 20-27. Master Node Configuration, NACT=PUBLISH
Frame
Break Synch Protected
Identifier
Data 1 Data N Checksum
TXRDY
Write
THR
Write
LINIR
Data 1 Data 2 Data 3
Data N-1
Data N
RXRDY
Header
Interframe
space Response
space
Frame slot = TFrame_Maximum
Data3 Response
LINTC
FSDIS=1 FSDIS=0
457
32142D–06/2013
ATUC64/128/256L3/4U
Figure 20-28. Master Node Configuration, NACT=SUBSCRIBE
Figure 20-29. Master Node Configuration, NACT=IGNORE
20.6.7.2 Slave Node Configuration
This is identical to the master node configuration above, except for:
• LIN mode selected in MR.MODE is slave
• When the baud rate is configured, wait until CSR.LINID is a one, then;
• Check for LINISFE and LINPE errors, clear errors and LINIDby writing a one to RSTSTA
• Read IDCHR
• Configure the frame transfer by writing to NACT, PARDIS, CHKDIS, CHKTYPE, DLCM, and
DLC in LINMR
IMPORTANT: if NACT=PUBLISH, and this field is already correct, the LINMR register must still
be written with this value in order to set TXRDY, and to request the corresponding Peripheral
DMA Controller write transfer.
The different NACT settings result in the same procedure as for the master node, see page 455.
Break Synch Protected
Identifier
Data 1 Data N Checksum
TXRDY
Read
RHR
Write
LINIR
Data 1
Data N-1
Data N-1
RXRDY
Data N-2 Data N
Header
Interframe
Response space
space
Frame
Frame slot = TFrame_Maximum
Data3 Response
LINTC
FSDIS=1 FSDIS=0
TXRDY
Write
LINIR
RXRDY
LINTC
Break Synch Protected
Identifier
Data 1 Data N-1 Data N Checksum
Header
Interframe
Response space
space
Frame
Frame slot = TFrame_Maximum
Data3 Response
FSDIS=1 FSDIS=0
458
32142D–06/2013
ATUC64/128/256L3/4U
Figure 20-30. Slave Node Configuration, NACT=PUBLISH
Figure 20-31. Slave Node Configuration, NACT=SUBSCRIBE
Figure 20-32. Slave Node Configuration, NACT=IGNORE
20.6.8 LIN Frame Handling With The Peripheral DMA Controller
The USART can be used together with the Peripheral DMA Controller in order to transfer data
without processor intervention. The DMA Controller uses the TXRDY and RXRDY bits, to trigger
one byte writes or reads. It always writes to THR, and it always reads RHR.
Break Synch Protected
Identifier
Data 1 Data N Checksum
TXRDY
Write
THR
Read
LINID
Data 1 Data 3
Data N-1
Data N
RXRDY
LINIDRX
Data 2
LINTC
TXRDY
Read
RHR
Read
LINID
RXRDY
LINIDRX
LINTC
Break Synch Protected
Identifier
Data 1 Data N Checksum
Data 1
Data N-1
Data N-2 Data N-1 Data N
TXRDY
Read
RHR
Read
LINID
RXRDY
LINIDRX
LINTC
Break Synch Protected
Identifier
Data 1 Data N Checksum Data N-1
459
32142D–06/2013
ATUC64/128/256L3/4U
20.6.8.1 Master Node Configuration
The Peripheral DMA Controller Mode bit (LINMR.PDCM) allows the user to select configuration:
• PDCM=0: LIN configuration must be written to LINMR, it is not stored in the write buffer.
• PDCM=1: LIN configuration is written by the DMA Controller to THR, and is stored in the
write buffer. Since data transfer size is a byte, the transfer is split into two accesses. The first
writes the NACT, PARDIS, CHKDIS, CHKTYP, DLM and FSDIS bits, while the second writes
the DLC field. If NACT=PUBLISH, the write buffer will also contain the Identifier.
When NACT=SUBSCRIBE, the read buffer contains the data.
Figure 20-33. Master Node with Peripheral DMA Controller (PDCM=0)
Figure 20-34. Master Node with Peripheral DMA Controller (PDCM=1)
|
|
|
|
RXRDY
TXRDY
Peripheral
bus
USART LIN
CONTROLLER
DATA 0
DATA N
|
|
|
|
READ BUFFER
NODE ACTION = PUBLISH NODE ACTION = SUBSCRIBE
Peripheral DMA
Controller
RXRDY
Peripheral
bus
DATA 0
DATA 1
DATA N
WRITE BUFFER
Peripheral DMA
Controller
USART LIN
CONTROLLER
|
|
|
|
|
|
|
|
NACT
PARDIS
CHKDIS
CHKTYP DLM
FSDIS
DLC
IDENTIFIER
DATA 0
DATA N
WRITE BUFFER
RXRDY
Peripheral
bus
DLC
IDENTIFIER
DATA 0
DATA N
WRITE BUFFER
RXRDY READ BUFFER
NODE ACTION = PUBLISH NODE ACTION = SUBSCRIBE
Peripheral DMA
Controller
Peripheral DMA
Controller
USART LIN
CONTROLLER
NACT
PARDIS
CHKDIS
CHKTYP DLM
FSDIS
USART LIN
CONTROLLER
TXRDY
Peripheral
bus
460
32142D–06/2013
ATUC64/128/256L3/4U
20.6.8.2 Slave Node Configuration
In this mode, the Peripheral DMA Controller transfers only data. The user reads the Identifier
from LINIR, and selects LIN mode by writing to LINMR. When NACT=PUBLISH the data is in the
write buffer, while the read buffer contains the data when NACT=SUBSCRIBE.
IMPORTANT: if in slave mode, NACT is already configured correctly as PUBLISH, the LINMR
register must still be written with this value in order to set TXRDY, and to request the corresponding
Peripheral DMA Controller write transfer.
Figure 20-35. Slave Node with Peripheral DMA Controller
20.6.9 Wake-up Request
Any node in a sleeping LIN cluster may request a wake-up. By writing to the Wakeup Signal
Type bit (LINMR.WKUPTYP), the user can choose to send either a LIN 1.3 (WKUPTYP=1), or a
LIN 2.0 (WKUPTYP=0) compliant wakeup request. Writing a one to the Send LIN Wakeup Signal
bit (CR.LINWKUP), transmits a wakeup, and when completed sets LINTC.
According to LIN 1.3, the wakeup request should be generated with the character 0x80 in order
to impose eight successive dominant bits.
According to LIN 2.0, the wakeup request is issued by forcing the bus into the dominant state for
250µs to 5ms. Sending the character 0xF0 does this, regardless of baud rate.
• Baud rate max = 20 kbit/s -> one bit period = 50µs -> five bit periods = 250µs
• Baud rate min = 1 kbit/s -> one bit period = 1ms -> five bit periods = 5ms
20.6.10 Bus Idle Time-out
LIN bus inactivity should eventually cause slaves to time-out and enter sleep mode. LIN 1.3
specifies this to 25000 bit periods, whilst LIN 2.0 specifies 4seconds. For the time-out counter
operation see Section 20.6.3.8 ”Receiver Time-out” on page 444.
|
|
|
|
|
|
|
|
DATA 0
DATA N
RXRDY
Peripheral
Bus
READ BUFFER
NACT = SUBSCRIBE DATA 0
DATA N
TXRDY
Peripheral
bus
WRITE BUFFER
USART LIN
CONTROLLER
USART LIN
CONTROLLER
Peripheral DMA
Controller
Peripheral DMA
Controller
Table 20-9. Receiver Time-out Values (RTOR.TO)
LIN Specification Baud Rate Time-out period TO
2.0
1 000 bit/s
4s
4 000
2 400 bit/s 9 600
9 600 bit/s 38 400
19 200 bit/s 76 800
20 000 bit/s 80 000
1.3 - 25 000 bit periods 25 000
461
32142D–06/2013
ATUC64/128/256L3/4U
20.6.11 Test Modes
The internal loopback feature enables on-board diagnostics, and allows the USART to operate
in three different test modes, with reconfigured pin functionality, as shown below.
20.6.11.1 Normal Mode
During normal operation, a receivers RXD pin is connected to a transmitters TXD pin.
Figure 20-36. Normal Mode Configuration
20.6.11.2 Automatic Echo Mode
Automatic echo mode allows bit-by-bit retransmission. When a bit is received on the RXD pin, it
is also sent to the TXD pin, as shown in Figure 20-37. Transmitter configuration has no effect.
Figure 20-37. Automatic Echo Mode Configuration
20.6.11.3 Local Loopback Mode
Local loopback mode connects the output of the transmitter directly to the input of the receiver,
as shown in Figure 20-38. The TXD and RXD pins are not used. The RXD pin has no effect on
the receiver and the TXD pin is continuously driven high, as in idle state.
Figure 20-38. Local Loopback Mode Configuration
20.6.11.4 Remote Loopback Mode
Remote loopback mode connects the RXD pin to the TXD pin, as shown in Figure 20-39. The
transmitter and the receiver are disabled and have no effect. This mode allows bit-by-bit
retransmission.
Receiver
Transmitter
RXD
TXD
Receiver
Transmitter
RXD
TXD
Receiver
Transmitter
RXD
TXD
1
462
32142D–06/2013
ATUC64/128/256L3/4U
Figure 20-39. Remote Loopback Mode Configuration
20.6.12 Write Protection Registers
To prevent single software errors from corrupting USART behavior, certain address spaces can
be write-protected by writing the correct Write Protect KEY and a one to the Write Protect
Enable bit in the Write Protect Mode Register (WPMR.WPKEY, and WPMR.WPEN). Disabling
the write protection is done by writing the correct key, and a zero to WPEN.
Write attempts to a write protected register are detected and the Write Protect Violation Status
bit in the Write Protect Status Register (WPSR.WPVS) is set, while the Write Protect Violation
Source field (WPSR.WPVSRC) indicates the targeted register. Writing the correct key to the
Write Protect KEY bit (WPMR.WPKEY) clears WPVSRC and WPVS.
The protected registers are:
• ”Mode Register” on page 466
• ”Baud Rate Generator Register” on page 476
• ”Receiver Time-out Register” on page 477
• ”Transmitter Timeguard Register” on page 478
Receiver
Transmitter
RXD
TXD
1
463
32142D–06/2013
ATUC64/128/256L3/4U
20.7 User Interface
Note: 1. Values in the Version Register vary with the version of the IP block implementation.
Table 20-10. USART Register Memory Map
Offset Register Name Access Reset
0x0000 Control Register CR Write-only 0x00000000
0x0004 Mode Register MR Read-write 0x00000000
0x0008 Interrupt Enable Register IER Write-only 0x00000000
0x000C Interrupt Disable Register IDR Write-only 0x00000000
0x0010 Interrupt Mask Register IMR Read-only 0x00000000
0x0014 Channel Status Register CSR Read-only 0x00000000
0x0018 Receiver Holding Register RHR Read-only 0x00000000
0x001C Transmitter Holding Register THR Write-only 0x00000000
0x0020 Baud Rate Generator Register BRGR Read-write 0x00000000
0x0024 Receiver Time-out Register RTOR Read-write 0x00000000
0x0028 Transmitter Timeguard Register TTGR Read-write 0x00000000
0x0054 LIN Mode Register LINMR Read-write 0x00000000
0x0058 LIN Identifier Register LINIR Read-write 0x00000000
0x00E4 Write Protect Mode Register WPMR Read-write 0x00000000
0x00E8 Write Protect Status Register WPSR Read-only 0x00000000
0x00FC Version Register VERSION Read-only 0x–(1)
464
32142D–06/2013
ATUC64/128/256L3/4U
20.7.1 Control Register
Name: CR
Access Type: Write-only
Offset: 0x0
Reset Value: 0x00000000
• LINWKUP: Send LIN Wakeup Signal
Writing a zero to this bit has no effect.
Writing a one to this bit will sends a wakeup signal on the LIN bus.
• LINABT: Abort LIN Transmission
Writing a zero to this bit has no effect.
Writing a one to this bit will abort the current LIN transmission.
• RTSDIS/RCS: Request to Send Disable/Release SPI Chip Select
Writing a zero to this bit has no effect.
Writing a one to this bit when USART is not in SPI master mode drives RTS pin high.
Writing a one to this bit when USART is in SPI master mode releases NSS (RTS pin).
• RTSEN/FCS: Request to Send Enable/Force SPI Chip Select
Writing a zero to this bit has no effect.
Writing a one to this bit when USART is not in SPI master mode drives RTS low.
Writing a one to this bit when USART is in SPI master mode when;
FCS=0: has no effect.
FCS=1: forces NSS (RTS pin) low, even if USART is not transmitting, in order to address SPI slave devices supporting the
CSAAT Mode (Chip Select Active After Transfer).
• RETTO: Rearm Time-out
Writing a zero to this bit has no effect.
Writing a one to this bit reloads the time-out counter and clears CSR.TIMEOUT.
• RSTNACK: Reset Non Acknowledge
Writing a zero to this bit has no effect.
Writing a one to this bit clears CSR.NACK.
• SENDA: Send Address
Writing a zero to this bit has no effect.
Writing a one to this bit will in multidrop mode send the next character written to THR as an address.
• STTTO: Start Time-out
Writing a zero to this bit has no effect.
Writing a one to this bit will abort any current time-out count down, and trigger a new count down when the next character has
been received. CSR.TIMEOUT is also cleared.
31 30 29 28 27 26 25 24
––––––––
23 22 21 20 19 18 17 16
– – LINWKUP LINABT RTSDIS/RCS RTSEN/FCS – –
15 14 13 12 11 10 9 8
RETTO RSTNACK – SENDA STTTO STPBRK STTBRK RSTSTA
76543210
TXDIS TXEN RXDIS RXEN RSTTX RSTRX – –
465
32142D–06/2013
ATUC64/128/256L3/4U
• STPBRK: Stop Break
Writing a zero to this bit has no effect.
Writing a one to this bit will stop the generation of break signal characters, and then send ones for TTGR.TG duration, or at least
12 bit periods. No effect if no break is being transmitted.
• STTBRK: Start Break
Writing a zero to this bit has no effect.
Writing a one to this bit will start transmission of break characters when current characters present in THR and the transmit shift
register have been sent. No effect if a break signal is already being generated.
• RSTSTA: Reset Status Bits
Writing a zero to this bit has no effect.
Writing a one to this bit will clear the following bits in CSR: PARE, FRAME, OVRE, LINBE, LINSFE, LINIPE, LINCE, LINSNRE,
and RXBRK.
• TXDIS: Transmitter Disable
Writing a zero to this bit has no effect.
Writing a one to this bit disables the transmitter.
• TXEN: Transmitter Enable
Writing a zero to this bit has no effect.
Writing a one to this bit enables the transmitter if TXDIS is zero.
• RXDIS: Receiver Disable
Writing a zero to this bit has no effect.
Writing a one to this bit disables the receiver.
• RXEN: Receiver Enable
Writing a zero to this bit has no effect.
Writing a one to this bit enables the receiver if RXDIS is zero.
• RSTTX: Reset Transmitter
Writing a zero to this bit has no effect.
Writing a one to this bit will reset the transmitter.
• RSTRX: Reset Receiver
Writing a zero to this bit has no effect.
Writing a one to this bit will reset the receiver.
466
32142D–06/2013
ATUC64/128/256L3/4U
20.7.2 Mode Register
Name: MR
Access Type: Read-write
Offset: 0x4
Reset Value: 0x00000000
This register can only be written if the WPEN bit is cleared in the Write Protect Mode Register.
• INACK: Inhibit Non Acknowledge
0: The NACK is generated.
1: The NACK is not generated.
• OVER: Oversampling Mode
0: Oversampling at 16 times the baud rate.
1: Oversampling at 8 times the baud rate.
• CLKO: Clock Output Select
0: The USART does not drive the CLK pin.
1: The USART drives the CLK pin unless USCLKS selects the external clock.
• MODE9: 9-bit Character Length
0: CHRL defines character length.
1: 9-bit character length.
• MSBF/CPOL: Bit Order or SPI Clock Polarity
If USART does not operate in SPI Mode:
MSBF=0: Least Significant Bit is sent/received first.
MSBF=1: Most Significant Bit is sent/received first.
If USART operates in SPI Mode, CPOL is used with CPHA to produce the required clock/data relationship between devices.
CPOL=0: The inactive state value of CLK is logic level zero.
CPOL=1: The inactive state value of CLK is logic level one.
31 30 29 28 27 26 25 24
––––– –
23 22 21 20 19 18 17 16
– – – INACK OVER CLKO MODE9 MSBF/CPOL
15 14 13 12 11 10 9 8
CHMODE NBSTOP PAR SYNC/CPHA
76543210
CHRL USCLKS MODE
467
32142D–06/2013
ATUC64/128/256L3/4U
• CHMODE: Channel Mode
• NBSTOP: Number of Stop Bits
• PAR: Parity Type
• SYNC/CPHA: Synchronous Mode Select or SPI Clock Phase
If USART does not operate in SPI Mode (MODE is 0xE and 0xF):
SYNC = 0: USART operates in Asynchronous Mode.
SYNC = 1: USART operates in Synchronous Mode.
If USART operates in SPI Mode, CPHA determines which edge of CLK causes data to change and which edge causes data to
be captured. CPHA is used with CPOL to produce the required clock/data relationship between master and slave devices.
CPHA = 0: Data is changed on the leading edge of CLK and captured on the following edge of CLK.
CPHA = 1: Data is captured on the leading edge of CLK and changed on the following edge of CLK.
Table 20-11.
CHMODE Mode Description
0 0 Normal Mode
0 1 Automatic Echo. Receiver input is connected to the TXD pin.
1 0 Local Loopback. Transmitter output is connected to the Receiver input.
1 1 Remote Loopback. RXD pin is internally connected to the TXD pin.
Table 20-12.
NBSTOP Asynchronous (SYNC=0) Synchronous (SYNC=1)
0 0 1 stop bit 1 stop bit
0 1 1.5 stop bits Reserved
1 0 2 stop bits 2 stop bits
1 1 Reserved Reserved
Table 20-13.
PAR Parity Type
0 0 0 Even parity
0 0 1 Odd parity
0 1 0 Parity forced to 0 (Space)
0 1 1 Parity forced to 1 (Mark)
1 0 x No parity
1 1 x Multidrop mode
468
32142D–06/2013
ATUC64/128/256L3/4U
• CHRL: Character Length.
• USCLKS: Clock Selection
Note: 1. The value of DIV is device dependent. Please refer to the Module Configuration section at the end of this chapter.
• MODE
Table 20-14.
CHRL Character Length
0 0 5 bits
0 1 6 bits
1 0 7 bits
1 1 8 bits
Table 20-15.
USCLKS Selected Clock
0 0 CLK_USART
0 1 CLK_USART/DIV(1)
1 0 Reserved
1 1 CLK
Table 20-16.
MODE Mode of the USART
0 0 0 0 Normal
0 0 1 0 Hardware Handshaking
1 0 1 0 LIN Master
1 0 1 1 LIN Slave
1 1 1 0 SPI Master
1 1 1 1 SPI Slave
Others Reserved
469
32142D–06/2013
ATUC64/128/256L3/4U
20.7.3 Interrupt Enable Register
Name: IER
Access Type: Write-only
Offset: 0x8
Reset Value: 0x00000000
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will set the corresponding bit in IMR.
31 30 29 28 27 26 25 24
– – LINSNRE LINCE LINIPE LINISFE LINBE –
23 22 21 20 19 18 17 16
– – – – CTSIC – – –
15 14 13 12 11 10 9 8
LINTC LINID NACK/LINBK RXBUFF – ITER/UNRE TXEMPTY TIMEOUT
76543210
PARE FRAME OVRE – – RXBRK TXRDY RXRDY
470
32142D–06/2013
ATUC64/128/256L3/4U
20.7.4 Interrupt Disable Register
Name: IDR
Access Type: Write-only
Offset: 0xC
Reset Value: 0x00000000
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will clear the corresponding bit in IMR.
31 30 29 28 27 26 25 24
– – LINSNRE LINCE LINIPE LINISFE LINBE –
23 22 21 20 19 18 17 16
– – – – CTSIC – – –
15 14 13 12 11 10 9 8
LINTC LINID NACK/LINBK RXBUFF – ITER/UNRE TXEMPTY TIMEOUT
76543210
PARE FRAME OVRE – – RXBRK TXRDY RXRDY
471
32142D–06/2013
ATUC64/128/256L3/4U
20.7.5 Interrupt Mask Register
Name: IMR
Access Type: Read-only
Offset: 0x10
Reset Value: 0x00000000
0: The corresponding interrupt is disabled.
1: The corresponding interrupt is enabled.
A bit in this register is cleared when the corresponding bit in IDR is written to one.
A bit in this register is set when the corresponding bit in IER is written to one.
31 30 29 28 27 26 25 24
– – LINSNRE LINCE LINIPE LINISFE LINBE –
23 22 21 20 19 18 17 16
– – – – CTSIC – – –
15 14 13 12 11 10 9 8
LINTC LINID NACK/LINBK RXBUFF – ITER/UNRE TXEMPTY TIMEOUT
76543210
PARE FRAME OVRE – – RXBRK TXRDY RXRDY
472
32142D–06/2013
ATUC64/128/256L3/4U
20.7.6 Channel Status Register
Name: CSR
Access Type: Read-only
Offset: 0x14
Reset Value: 0x00000000
• LINSNRE: LIN Slave Not Responding Error
0: No LIN Slave Not Responding Error has been detected since the last RSTSTA.
1: A LIN Slave Not Responding Error has been detected since the last RSTSTA.
• LINCE: LIN Checksum Error
0: No LIN Checksum Error has been detected since the last RSTSTA.
1: A LIN Checksum Error has been detected since the last RSTSTA.
• LINIPE: LIN Identifier Parity Error
0: No LIN Identifier Parity Error has been detected since the last RSTSTA.
1: A LIN Identifier Parity Error has been detected since the last RSTSTA.
• LINISFE: LIN Inconsistent Sync Field Error
0: No LIN Inconsistent Sync Field Error has been detected since the last RSTSTA
1: The USART is configured as a Slave node and a LIN Inconsistent Sync Field Error has been detected since the last RSTSTA.
• LINBE: LIN Bit Error
0: No Bit Error has been detected since the last RSTSTA.
1: A Bit Error has been detected since the last RSTSTA.
• CTS: Image of CTS Input
0: CTS is low.
1: CTS is high.
• CTSIC: Clear to Send Input Change Flag
0: No change has been detected on the CTS pin since the last CSR read.
1: At least one change has been detected on the CTS pin since the last CSR read.
• LINTC: LIN Transfer Completed
0: The USART is either idle or a LIN transfer is ongoing.
1: A LIN transfer has been completed since the last RSTSTA.
• LINID: LIN Identifier
0: No LIN Identifier has been sent or received.
1: A LIN Identifier has been sent (master) or received (slave), since the last RSTSTA.
• NACK: Non Acknowledge
0: No Non Acknowledge has been detected since the last RSTNACK.
1: At least one Non Acknowledge has been detected since the last RSTNACK.
• RXBUFF: Reception Buffer Full
0: The Buffer Full signal from the Peripheral DMA Controller channel is inactive.
31 30 29 28 27 26 25 24
– – LINSNRE LINCE LINIPE LINISFE LINBE –
23 22 21 20 19 18 17 16
CTS – – – CTSIC – – –
15 14 13 12 11 10 9 8
LINTC LINID NACK/LINBK RXBUFF – ITER/UNRE TXEMPTY TIMEOUT
76543210
PARE FRAME OVRE – – RXBRK TXRDY RXRDY
473
32142D–06/2013
ATUC64/128/256L3/4U
1: The Buffer Full signal from the Peripheral DMA Controller channel is active.
• ITER/UNRE: Max number of Repetitions Reached or SPI Underrun Error
If USART does not operate in SPI Slave Mode:
ITER=0: Maximum number of repetitions has not been reached since the last RSTSTA.
ITER=1: Maximum number of repetitions has been reached since the last RSTSTA.
If USART operates in SPI Slave Mode:
UNRE=0: No SPI underrun error has occurred since the last RSTSTA.
UNRE=1: At least one SPI underrun error has occurred since the last RSTSTA.
• TXEMPTY: Transmitter Empty
0: The transmitter is either disabled or there are characters in THR, or in the transmit shift register.
1: There are no characters in neither THR, nor in the transmit shift register.
• TIMEOUT: Receiver Time-out
0: There has not been a time-out since the last Start Time-out command (CR.STTTO), or RTOR.TO is zero.
1: There has been a time-out since the last Start Time-out command.
• PARE: Parity Error
0: Either no parity error has been detected, or the parity bit is a zero in multidrop mode, since the last RSTSTA.
1: Either at least one parity error has been detected, or the parity bit is a one in multidrop mode, since the last RSTSTA.
• FRAME: Framing Error
0: No stop bit has been found as low since the last RSTSTA.
1: At least one stop bit has been found as low since the last RSTSTA.
• OVRE: Overrun Error
0: No overrun error has occurred since the last RSTSTA.
1: At least one overrun error has occurred since the last RSTSTA.
• RXBRK: Break Received/End of Break
0: No Break received or End of Break detected since the last RSTSTA.
1: Break received or End of Break detected since the last RSTSTA.
• TXRDY: Transmitter Ready
0: The transmitter is either disabled, or a character in THR is waiting to be transferred to the transmit shift register, or an
STTBRK command has been requested. As soon as the transmitter is enabled, TXRDY becomes one.
1: There is no character in the THR.
• RXRDY: Receiver Ready
0: The receiver is either disabled, or no complete character has been received since the last read of RHR. If characters were
being received when the receiver was disabled, RXRDY changes to 1 when the receiver is enabled.
1: At least one complete character has been received and RHR has not yet been read.
474
32142D–06/2013
ATUC64/128/256L3/4U
20.7.7 Receiver Holding Register
Name: RHR
Access Type: Read-only
Offset: 0x18
Reset Value: 0x00000000
• RXCHR: Received Character
Last received character.
31 30 29 28 27 26 25 24
––––––––
23 22 21 20 19 18 17 16
––––––––
15 14 13 12 11 10 9 8
– – – – – – – RXCHR[8]
76543210
RXCHR[7:0]
475
32142D–06/2013
ATUC64/128/256L3/4U
20.7.8 Transmitter Holding Register
Name: THR
Access Type: Write-only
Offset: 0x1C
Reset Value: 0x00000000
• TXCHR: Character to be Transmitted
If TXRDY is zero this field contains the next character to be transmitted.
31 30 29 28 27 26 25 24
––––––––
23 22 21 20 19 18 17 16
––––––––
15 14 13 12 11 10 9 8
– – – – – – – TXCHR[8]
76543210
TXCHR[7:0]
476
32142D–06/2013
ATUC64/128/256L3/4U
20.7.9 Baud Rate Generator Register
Name: BRGR
Access Type: Read-write
Offset: 0x20
Reset Value: 0x00000000
This register can only be written to if write protection is disabled, see ”Write Protect Mode Register” on page 482.
• FP: Fractional Part
0: Fractional divider is disabled.
1 - 7: Baud rate resolution, defined by FP x 1/8.
• CD: Clock Divider
31 30 29 28 27 26 25 24
––––––––
23 22 21 20 19 18 17 16
– – – – – FP
15 14 13 12 11 10 9 8
CD[15:8]
76543210
CD[7:0]
Table 20-17.
CD
SYNC = 0
SYNC = 1
or
MODE = SPI
(Master or Slave)
OVER = 0 OVER = 1
0 Baud Rate Clock Disabled
1 to 65535
Baud Rate =
Selected Clock/16/CD
Baud Rate =
Selected Clock/8/CD
Baud Rate =
Selected Clock /CD
477
32142D–06/2013
ATUC64/128/256L3/4U
20.7.10 Receiver Time-out Register
Name: RTOR
Access Type: Read-write
Offset: 0x24
Reset Value: 0x00000000
This register can only be written to if write protection is disabled, see ”Write Protect Mode Register” on page 482.
• TO: Time-out Value
0: The receiver Time-out is disabled.
1 - 131071: The receiver Time-out is enabled and the time-out delay is TO x bit period.
Note that the size of the TO counter is device dependent, see the Module Configuration section.
31 30 29 28 27 26 25 24
––––––––
23 22 21 20 19 18 17 16
– – – – – – – TO[16]
15 14 13 12 11 10 9 8
TO[15:8]
76543210
TO[7:0]
478
32142D–06/2013
ATUC64/128/256L3/4U
20.7.11 Transmitter Timeguard Register
Name: TTGR
Access Type: Read-write
Offset: 0x28
Reset Value: 0x00000000
This register can only be written to if write protection is disabled, see ”Write Protect Mode Register” on page 482.
• TG: Timeguard Value
0: The transmitter Timeguard is disabled.
1 - 255: The transmitter timeguard is enabled and the timeguard delay is TG x bit period.
31 30 29 28 27 26 25 24
––––––––
23 22 21 20 19 18 17 16
––––––––
15 14 13 12 11 10 9 8
––––––––
76543210
TG
479
32142D–06/2013
ATUC64/128/256L3/4U
20.7.12 LIN Mode Register
Name: LINMR
Access Type: Read-write
Offset: 0x54
Reset Value: 0x00000000
• PDCM: Peripheral DMA Controller Mode
0: The LIN mode register is not written by the Peripheral DMA Controller.
1: The LIN mode register is, except for this bit, written by the Peripheral DMA Controller.
• DLC: Data Length Control
0 - 255: If DLM=0 this field defines the response data length to DLC+1 bytes.
• WKUPTYP: Wakeup Signal Type
0: Writing a one to CR.LINWKUP will send a LIN 2.0 wakeup signal.
1: Writing a one to CR.LINWKUP will send a LIN 1.3 wakeup signal.
• FSDIS: Frame Slot Mode Disable
0: The Frame Slot mode is enabled.
1: The Frame Slot mode is disabled.
• DLM: Data Length Mode
0: The response data length is defined by DLC.
1: The response data length is defined by bits 4 and 5 of the Identifier (LINIR.IDCHR).
• CHKTYP: Checksum Type
0: LIN 2.0 “Enhanced” checksum
1: LIN 1.3 “Classic” checksum
• CHKDIS: Checksum Disable
0: Checksum is automatically computed and sent when master, and checked when slave.
1: Checksum is not computed and sent, nor checked.
• PARDIS: Parity Disable
0: Identifier parity is automatically computed and sent when master, and checked when slave.
1: Identifier parity is not computed and sent, nor checked.
• NACT: LIN Node Action
31 30 29 28 27 26 25 24
––––––––
23 22 21 20 19 18 17 16
– – – – – – – PDCM
15 14 13 12 11 10 9 8
DLC
76543210
WKUPTYP FSDIS DLM CHKTYP CHKDIS PARDIS NACT
Table 20-18.
NACT Mode Description
0 0 PUBLISH: The USART transmits the response.
480
32142D–06/2013
ATUC64/128/256L3/4U
0 1 SUBSCRIBE: The USART receives the response.
1 0 IGNORE: The USART does not transmit and does not receive the response.
1 1 Reserved
Table 20-18.
481
32142D–06/2013
ATUC64/128/256L3/4U
20.7.13 LIN Identifier Register
Name: LINIR
Access Type: Read-write or Read-only
Offset: 0x58
Reset Value: 0x00000000
• IDCHR: Identifier Character
If USART is in LIN master mode, the IDCHR field is read-write, and its value is the Identifier character to be transmitted.
If USART is in LIN slave mode, the IDCHR field is read-only, and its value is the last received Identifier character.
31 30 29 28 27 26 25 24
––––––––
23 22 21 20 19 18 17 16
––––––––
15 14 13 12 11 10 9 8
––––––––
76543210
IDCHR
482
32142D–06/2013
ATUC64/128/256L3/4U
20.7.14 Write Protect Mode Register
Register Name: WPMR
Access Type: Read-write
Offset: 0xE4
Reset Value: See Table 20-10
• WPKEY: Write Protect KEY
Has to be written to 0x555341 (“USA” in ASCII) in order to successfully write WPEN. Always reads as zero.
• WPEN: Write Protect Enable
0 = Write protection disabled.
1 = Write protection enabled.
Protects the registers:
• ”Mode Register” on page 466
• ”Baud Rate Generator Register” on page 476
• ”Receiver Time-out Register” on page 477
• ”Transmitter Timeguard Register” on page 478
31 30 29 28 27 26 25 24
WPKEY[23:16]
23 22 21 20 19 18 17 16
WPKEY[15:8]
15 14 13 12 11 10 9 8
WPKEY[7:0]
76543210
— — — — — — — WPEN
483
32142D–06/2013
ATUC64/128/256L3/4U
20.7.15 Write Protect Status Register
Register Name: WPSR
Access Type: Read-only
Offset: 0xE8
Reset Value: See Table 20-10
• WPVSRC: Write Protect Violation Source
If WPVS=1 this field indicates which write-protected register was unsuccessfully written to, either by address offset or code.
• WPVS: Write Protect Violation Status
0= No write protect violation has occurred since the last WPSR read.
1= A write protect violation has occurred since the last WPSR read.
Note: Reading WPSR automatically clears all fields.
31 30 29 28 27 26 25 24
————————
23 22 21 20 19 18 17 16
WPVSRC[15:8]
15 14 13 12 11 10 9 8
WPVSRC[7:0]
76543210
— — — — — — — WPVS
484
32142D–06/2013
ATUC64/128/256L3/4U
20.7.16 Version Register
Name: VERSION
Access Type: Read-only
Offset: 0xFC
Reset Value: -
• MFN
Reserved. No functionality associated.
• VERSION
Version of the module. No functionality associated.
31 30 29 28 27 26 25 24
––––––––
23 22 21 20 19 18 17 16
– – – – MFN
15 14 13 12 11 10 9 8
– – – – VERSION[11:8]
76543210
VERSION[7:0]
485
32142D–06/2013
ATUC64/128/256L3/4U
20.8 Module Configuration
The specific configuration for each USART instance is listed in the following tables.The module
bus clocks listed here are connected to the system bus clocks. Please refer to the Power Manager
chapter for details.
Table 20-19. USART Configuration
Feature USART0 USART1 USART2 USART3
Receiver Time-out Counter Size
(Size of the RTOR.TO field) 17 bit 17 bit 17 bit 17 bit
DIV Value for divided CLK_USART 8 8 8 8
Table 20-20. USART Clocks
Module Name Clock Name Description
USART0 CLK_USART0 Clock for the USART0 bus interface
USART1 CLK_USART1 Clock for the USART1 bus interface
USART2 CLK_USART2 Clock for the USART2 bus interface
USART3 CLK_USART3 Clock for the USART3 bus interface
Table 20-21. Register Reset Values
Register Reset Value
VERSION 0x00000440
486
32142D–06/2013
ATUC64/128/256L3/4U
21. Serial Peripheral Interface (SPI)
Rev: 2.1.1.3
21.1 Features
• Compatible with an embedded 32-bit microcontroller
• Supports communication with serial external devices
– Four chip selects with external decoder support allow communication with up to 15
peripherals
– Serial memories, such as DataFlash and 3-wire EEPROMs
– Serial peripherals, such as ADCs, DACs, LCD controllers, CAN controllers and Sensors
– External co-processors
• Master or Slave Serial Peripheral Bus Interface
– 4 - to 16-bit programmable data length per chip select
– Programmable phase and polarity per chip select
– Programmable transfer delays between consecutive transfers and between clock and data
per chip select
– Programmable delay between consecutive transfers
– Selectable mode fault detection
• Connection to Peripheral DMA Controller channel capabilities optimizes data transfers
– One channel for the receiver, one channel for the transmitter
– Next buffer support
– Four character FIFO in reception
21.2 Overview
The Serial Peripheral Interface (SPI) circuit is a synchronous serial data link that provides communication
with external devices in Master or Slave mode. It also enables communication
between processors if an external processor is connected to the system.
The Serial Peripheral Interface is essentially a shift register that serially transmits data bits to
other SPIs. During a data transfer, one SPI system acts as the “master”' which controls the data
flow, while the other devices act as “slaves'' which have data shifted into and out by the master.
Different CPUs can take turn being masters (Multiple Master Protocol opposite to Single Master
Protocol where one CPU is always the master while all of the others are always slaves) and one
master may simultaneously shift data into multiple slaves. However, only one slave may drive its
output to write data back to the master at any given time.
A slave device is selected when the master asserts its NSS signal. If multiple slave devices
exist, the master generates a separate slave select signal for each slave (NPCS).
The SPI system consists of two data lines and two control lines:
• Master Out Slave In (MOSI): this data line supplies the output data from the master shifted
into the input(s) of the slave(s).
• Master In Slave Out (MISO): this data line supplies the output data from a slave to the input of
the master. There may be no more than one slave transmitting data during any particular
transfer.
• Serial Clock (SPCK): this control line is driven by the master and regulates the flow of the
data bits. The master may transmit data at a variety of baud rates; the SPCK line cycles once
for each bit that is transmitted.
• Slave Select (NSS): this control line allows slaves to be turned on and off by hardware.
487
32142D–06/2013
ATUC64/128/256L3/4U
21.3 Block Diagram
Figure 21-1. SPI Block Diagram
21.4 Application Block Diagram
Figure 21-2. Application Block Diagram: Single Master/Multiple Slave Implementation
Spi Interface
Interrupt Control
Peripheral DMA
Controller
I/O
Controller
CLK_SPI
Peripheral Bus
SPI Interrupt
SPCK
NPCS3
NPCS2
NPCS1
NPCS0/NSS
MOSI
MISO
Slave 0
Slave 2
Slave 1
SPCK
NPCS3
NPCS2
NPCS1
NPCS0
MOSI
MISO
Spi Master
SPCK
NSS
MOSI
MISO
SPCK
NSS
MOSI
MISO
SPCK
NSS
MOSI
MISO
NC
488
32142D–06/2013
ATUC64/128/256L3/4U
21.5 I/O Lines Description
21.6 Product Dependencies
In order to use this module, other parts of the system must be configured correctly, as described
below.
21.6.1 I/O Lines
The pins used for interfacing the compliant external devices may be multiplexed with I/O lines.
The user must first configure the I/O Controller to assign the SPI pins to their peripheral
functions.
21.6.2 Clocks
The clock for the SPI bus interface (CLK_SPI) is generated by the Power Manager. This clock is
enabled at reset, and can be disabled in the Power Manager. It is recommended to disable the
SPI before disabling the clock, to avoid freezing the SPI in an undefined state.
21.6.3 Interrupts
The SPI interrupt request line is connected to the interrupt controller. Using the SPI interrupt
requires the interrupt controller to be programmed first.
21.7 Functional Description
21.7.1 Modes of Operation
The SPI operates in master mode or in slave mode.
Operation in master mode is configured by writing a one to the Master/Slave Mode bit in the
Mode Register (MR.MSTR). The pins NPCS0 to NPCS3 are all configured as outputs, the SPCK
pin is driven, the MISO line is wired on the receiver input and the MOSI line driven as an output
by the transmitter.
If the MR.MSTR bit is written to zero, the SPI operates in slave mode. The MISO line is driven by
the transmitter output, the MOSI line is wired on the receiver input, the SPCK pin is driven by the
transmitter to synchronize the receiver. The NPCS0 pin becomes an input, and is used as a
Slave Select signal (NSS). The pins NPCS1 to NPCS3 are not driven and can be used for other
purposes.
The data transfers are identically programmable for both modes of operations. The baud rate
generator is activated only in master mode.
Table 21-1. I/O Lines Description
Pin Name Pin Description
Type
Master Slave
MISO Master In Slave Out Input Output
MOSI Master Out Slave In Output Input
SPCK Serial Clock Output Input
NPCS1-NPCS3 Peripheral Chip Selects Output Unused
NPCS0/NSS Peripheral Chip Select/Slave Select Output Input
489
32142D–06/2013
ATUC64/128/256L3/4U
21.7.2 Data Transfer
Four combinations of polarity and phase are available for data transfers. The clock polarity is
configured with the Clock Polarity bit in the Chip Select Registers (CSRn.CPOL). The clock
phase is configured with the Clock Phase bit in the CSRn registers (CSRn.NCPHA). These two
bits determine the edges of the clock signal on which data is driven and sampled. Each of the
two bits has two possible states, resulting in four possible combinations that are incompatible
with one another. Thus, a master/slave pair must use the same parameter pair values to communicate.
If multiple slaves are used and fixed in different configurations, the master must
reconfigure itself each time it needs to communicate with a different slave.
Table 21-2 on page 489 shows the four modes and corresponding parameter settings.
Figure 21-3 on page 489 and Figure 21-4 on page 490 show examples of data transfers.
Figure 21-3. SPI Transfer Format (NCPHA = 1, 8 bits per transfer)
Table 21-2. SPI modes
SPI Mode CPOL NCPHA
0 01
1 00
2 11
3 10
SPCK cycle (for reference) 1 4 2 3 5 8 6 7
SPCK
(CPOL = 0)
NSS
(to slave)
MISO
(from slave)
MOSI
(from master)
SPCK
(CPOL = 1)
MSB 6 4 5 LSB 3 2 1
MSB 6 5 4 3 2 1 LSB ***
*** Not Defined, but normaly MSB of previous character received
490
32142D–06/2013
ATUC64/128/256L3/4U
Figure 21-4. SPI Transfer Format (NCPHA = 0, 8 bits per transfer)
21.7.3 Master Mode Operations
When configured in master mode, the SPI uses the internal programmable baud rate generator
as clock source. It fully controls the data transfers to and from the slave(s) connected to the SPI
bus. The SPI drives the chip select line to the slave and the serial clock signal (SPCK).
The SPI features two holding registers, the Transmit Data Register (TDR) and the Receive Data
Register (RDR), and a single Shift Register. The holding registers maintain the data flow at a
constant rate.
After enabling the SPI, a data transfer begins when the processor writes to the TDR register.
The written data is immediately transferred in the Shift Register and transfer on the SPI bus
starts. While the data in the Shift Register is shifted on the MOSI line, the MISO line is sampled
and shifted in the Shift Register. Transmission cannot occur without reception.
Before writing to the TDR, the Peripheral Chip Select field in TDR (TDR.PCS) must be written in
order to select a slave.
If new data is written to TDR during the transfer, it stays in it until the current transfer is completed.
Then, the received data is transferred from the Shift Register to RDR, the data in TDR is
loaded in the Shift Register and a new transfer starts.
The transfer of a data written in TDR in the Shift Register is indicated by the Transmit Data Register
Empty bit in the Status Register (SR.TDRE). When new data is written in TDR, this bit is
cleared. The SR.TDRE bit is used to trigger the Transmit Peripheral DMA Controller channel.
The end of transfer is indicated by the Transmission Registers Empty bit in the SR register
(SR.TXEMPTY). If a transfer delay (CSRn.DLYBCT) is greater than zero for the last transfer,
SR.TXEMPTY is set after the completion of said delay. The CLK_SPI can be switched off at this
time.
During reception, received data are transferred from the Shift Register to the reception FIFO.
The FIFO can contain up to 4 characters (both Receive Data and Peripheral Chip Select fields).
While a character of the FIFO is unread, the Receive Data Register Full bit in SR remains high
(SR.RDRF). Characters are read through the RDR register. If the four characters stored in the
FIFO are not read and if a new character is stored, this sets the Overrun Error Status bit in the
SR register (SR.OVRES). The procedure to follow in such a case is described in Section
21.7.3.8.
SPCK cycle (for reference) 1 4 2 3 5 8 6 7
SPCK
(CPOL = 0)
NSS
(to slave)
MISO
(from slave)
MOSI
(from master)
SPCK
(CPOL = 1)
MSB 6 4 5 LSB 3 2 1
6 5 4 3 2 1 LSB
*** Not Defined, but normaly LSB of previous character transmitted
*** MSB
491
32142D–06/2013
ATUC64/128/256L3/4U
Figure 21-5 on page 491shows a block diagram of the SPI when operating in master mode. Figure
21-6 on page 492 shows a flow chart describing how transfers are handled.
21.7.3.1 Master mode block diagram
Figure 21-5. Master Mode Block Diagram
Baud Rate Generator
RXFIFOEN
4 – Character FIFO
Shift Register
TDRE
RXFIFOEN
4 – Character FIFO
PS
PCSDEC
Current
Peripheral
MODF
MODFDIS
MSTR
SCBR
CSR0..3
CSR0..3
CPOL
NCPHA
BITS
RDR
RD
RDRF
OVRES
TD
TDR
RDR
CSAAT
CSNAAT
CSR0..3
PCS
MR
PCS
TDR
SPCK CLK_SPI
MISO MOSI LSB MSB
NPCS1
NPCS2
NPCS3
NPCS0
SPI
Clock
0
1
0
1
0
1
NPCS0
492
32142D–06/2013
ATUC64/128/256L3/4U
21.7.3.2 Master mode flow diagram
Figure 21-6. Master Mode Flow Diagram
SPI Enable
CSAAT ?
PS ?
1
0
0
1
1
NPCS = TDR(PCS) NPCS = MR(PCS)
Delay DLYBS
Serializer = TDR(TD)
TDRE = 1
Data Transfer
RDR(RD) = Serializer
RDRF = 1
TDRE ?
NPCS = 0xF
Delay DLYBCS
Fixed
peripheral
Variable
peripheral
Delay DLYBCT
0
1 CSAAT ?
0
TDRE ?
1
0
PS ?
0
1
TDR(PCS)
= NPCS ?
no
yes MR(PCS)
= NPCS ?
no
NPCS = 0xF
Delay DLYBCS
NPCS = TDR(PCS)
NPCS = 0xF
Delay DLYBCS
NPCS = MR(PCS),
TDR(PCS)
Fixed
peripheral
Variable
peripheral
- NPCS defines the current Chip Select
- CSAAT, DLYBS, DLYBCT refer to the fields of the
Chip Select Register corresponding to the Current Chip Select
- When NPCS is 0xF, CSAAT is 0.
493
32142D–06/2013
ATUC64/128/256L3/4U
21.7.3.3 Clock generation
The SPI Baud rate clock is generated by dividing the CLK_SPI , by a value between 1 and 255.
This allows a maximum operating baud rate at up to CLK_SPI and a minimum operating baud
rate of CLK_SPI divided by 255.
Writing the Serial Clock Baud Rate field in the CSRn registers (CSRn.SCBR) to zero is forbidden.
Triggering a transfer while CSRn.SCBR is zero can lead to unpredictable results.
At reset, CSRn.SCBR is zero and the user has to configure it at a valid value before performing
the first transfer.
The divisor can be defined independently for each chip select, as it has to be configured in the
CSRn.SCBR field. This allows the SPI to automatically adapt the baud rate for each interfaced
peripheral without reprogramming.
21.7.3.4 Transfer delays
Figure 21-7 on page 493 shows a chip select transfer change and consecutive transfers on the
same chip select. Three delays can be configured to modify the transfer waveforms:
• The delay between chip selects, programmable only once for all the chip selects by writing to
the Delay Between Chip Selects field in the MR register (MR.DLYBCS). Allows insertion of a
delay between release of one chip select and before assertion of a new one.
• The delay before SPCK, independently programmable for each chip select by writing the
Delay Before SPCK field in the CSRn registers (CSRn.DLYBS). Allows the start of SPCK to
be delayed after the chip select has been asserted.
• The delay between consecutive transfers, independently programmable for each chip select
by writing the Delay Between Consecutive Transfers field in the CSRn registers
(CSRn.DLYBCT). Allows insertion of a delay between two transfers occurring on the same
chip select
These delays allow the SPI to be adapted to the interfaced peripherals and their speed and bus
release time.
Figure 21-7. Programmable Delays
DLYBCS DLYBS DLYBCT DLYBCT
Chip Select 1
Chip Select 2
SPCK
494
32142D–06/2013
ATUC64/128/256L3/4U
21.7.3.5 Peripheral selection
The serial peripherals are selected through the assertion of the NPCS0 to NPCS3 signals. By
default, all the NPCS signals are high before and after each transfer.
The peripheral selection can be performed in two different ways:
• Fixed Peripheral Select: SPI exchanges data with only one peripheral
• Variable Peripheral Select: Data can be exchanged with more than one peripheral
Fixed Peripheral Select is activated by writing a zero to the Peripheral Select bit in MR (MR.PS).
In this case, the current peripheral is defined by the MR.PCS field and the TDR.PCS field has no
effect.
Variable Peripheral Select is activated by writing a one to the MR.PS bit . The TDR.PCS field is
used to select the current peripheral. This means that the peripheral selection can be defined for
each new data.
The Fixed Peripheral Selection allows buffer transfers with a single peripheral. Using the Peripheral
DMA Controller is an optimal means, as the size of the data transfer between the memory
and the SPI is either 4 bits or 16 bits. However, changing the peripheral selection requires the
Mode Register to be reprogrammed.
The Variable Peripheral Selection allows buffer transfers with multiple peripherals without reprogramming
the MR register. Data written to TDR is 32-bits wide and defines the real data to be
transmitted and the peripheral it is destined to. Using the Peripheral DMA Controller in this mode
requires 32-bit wide buffers, with the data in the LSBs and the PCS and LASTXFER fields in the
MSBs, however the SPI still controls the number of bits (8 to16) to be transferred through MISO
and MOSI lines with the CSRn registers. This is not the optimal means in term of memory size
for the buffers, but it provides a very effective means to exchange data with several peripherals
without any intervention of the processor.
21.7.3.6 Peripheral chip select decoding
The user can configure the SPI to operate with up to 15 peripherals by decoding the four Chip
Select lines, NPCS0 to NPCS3 with an external logic. This can be enabled by writing a one to
the Chip Select Decode bit in the MR register (MR.PCSDEC).
When operating without decoding, the SPI makes sure that in any case only one chip select line
is activated, i.e. driven low at a time. If two bits are defined low in a PCS field, only the lowest
numbered chip select is driven low.
When operating with decoding, the SPI directly outputs the value defined by the PCS field of
either the MR register or the TDR register (depending on PS).
As the SPI sets a default value of 0xF on the chip select lines (i.e. all chip select lines at one)
when not processing any transfer, only 15 peripherals can be decoded.
The SPI has only four Chip Select Registers, not 15. As a result, when decoding is activated,
each chip select defines the characteristics of up to four peripherals. As an example, the CRS0
register defines the characteristics of the externally decoded peripherals 0 to 3, corresponding to
the PCS values 0x0 to 0x3. Thus, the user has to make sure to connect compatible peripherals
on the decoded chip select lines 0 to 3, 4 to 7, 8 to 11 and 12 to 14.
21.7.3.7 Peripheral deselection
When operating normally, as soon as the transfer of the last data written in TDR is completed,
the NPCS lines all rise. This might lead to runtime error if the processor is too long in responding
495
32142D–06/2013
ATUC64/128/256L3/4U
to an interrupt, and thus might lead to difficulties for interfacing with some serial peripherals
requiring the chip select line to remain active during a full set of transfers.
To facilitate interfacing with such devices, the CSRn registers can be configured with the Chip
Select Active After Transfer bit written to one (CSRn.CSAAT) . This allows the chip select lines
to remain in their current state (low = active) until transfer to another peripheral is required.
When the CSRn.CSAAT bit is written to qero, the NPCS does not rise in all cases between two
transfers on the same peripheral. During a transfer on a Chip Select, the SR.TDRE bit rises as
soon as the content of the TDR is transferred into the internal shifter. When this bit is detected
the TDR can be reloaded. If this reload occurs before the end of the current transfer and if the
next transfer is performed on the same chip select as the current transfer, the Chip Select is not
de-asserted between the two transfers. This might lead to difficulties for interfacing with some
serial peripherals requiring the chip select to be de-asserted after each transfer. To facilitate
interfacing with such devices, the CSRn registers can be configured with the Chip Select Not
Active After Transfer bit (CSRn.CSNAAT) written to one. This allows to de-assert systematically
the chip select lines during a time DLYBCS. (The value of the CSRn.CSNAAT bit is taken into
account only if the CSRn.CSAAT bit is written to zero for the same Chip Select).
Figure 21-8 on page 496 shows different peripheral deselection cases and the effect of the
CSRn.CSAAT and CSRn.CSNAAT bits.
21.7.3.8 FIFO management
A FIFO has been implemented in Reception FIFO (both in master and in slave mode), in order to
be able to store up to 4 characters without causing an overrun error. If an attempt is made to
store a fifth character, an overrun error rises. If such an event occurs, the FIFO must be flushed.
There are two ways to Flush the FIFO:
• By performing four read accesses of the RDR (the data read must be ignored)
• By writing a one to the Flush Fifo Command bit in the CR register (CR.FLUSHFIFO).
After that, the SPI is able to receive new data.
496
32142D–06/2013
ATUC64/128/256L3/4U
Figure 21-8. Peripheral Deselection
Figure 21-8 on page 496 shows different peripheral deselection cases and the effect of the
CSRn.CSAAT and CSRn.CSNAAT bits.
21.7.3.9 Mode fault detection
The SPI is capable of detecting a mode fault when it is configured in master mode and NPCS0,
MOSI, MISO, and SPCK are configured as open drain through the I/O Controller with either
internal or external pullup resistors. If the I/O Controller does not have open-drain capability,
mode fault detection must be disabled by writing a one to the Mode Fault Detection bit in the MR
A
NPCS[0..3]
Write TDR
TDRE
NPCS[0..3]
Write TDR
TDRE
NPCS[0..3]
Write TDR
TDRE
DLYBCS
PCS = A
DLYBCS
DLYBCT
A
PCS = B
B
DLYBCS
PCS = A
DLYBCS
DLYBCT
A
PCS = B
B
DLYBCS
DLYBCT
PCS=A
A
DLYBCS
DLYBCT
A
PCS = A
A A
DLYBCT
A A
CSAAT = 0 and CSNAAT = 0
DLYBCT
A A
CSAAT = 1 and CSNAAT= 0 / 1
A
DLYBCS
PCS = A
DLYBCT
A A
CSAAT = 0 and CSNAAT = 1
NPCS[0..3]
Write TDR
TDRE
PCS = A
DLYBCT
A A
CSAAT = 0 and CSNAAT = 0
497
32142D–06/2013
ATUC64/128/256L3/4U
register (MR.MODFDIS). In systems with open-drain I/O lines, a mode fault is detected when a
low level is driven by an external master on the NPCS0/NSS signal.
When a mode fault is detected, the Mode Fault Error bit in the SR (SR.MODF) is set until the SR
is read and the SPI is automatically disabled until re-enabled by writing a one to the SPI Enable
bit in the CR register (CR.SPIEN).
By default, the mode fault detection circuitry is enabled. The user can disable mode fault detection
by writing a one to the Mode Fault Detection bit in the MR register (MR.MODFDIS).
21.7.4 SPI Slave Mode
When operating in slave mode, the SPI processes data bits on the clock provided on the SPI
clock pin (SPCK).
The SPI waits for NSS to go active before receiving the serial clock from an external master.
When NSS falls, the clock is validated on the serializer, which processes the number of bits
defined by the Bits Per Transfer field of the Chip Select Register 0 (CSR0.BITS). These bits are
processed following a phase and a polarity defined respectively by the CSR0.NCPHA and
CSR0.CPOL bits. Note that the BITS, CPOL, and NCPHA bits of the other Chip Select Registers
have no effect when the SPI is configured in Slave Mode.
The bits are shifted out on the MISO line and sampled on the MOSI line.
When all the bits are processed, the received data is transferred in the Receive Data Register
and the SR.RDRF bit rises. If the RDR register has not been read before new data is received,
the SR.OVRES bit is set. Data is loaded in RDR even if this flag is set. The user has to read the
SR register to clear the SR.OVRES bit.
When a transfer starts, the data shifted out is the data present in the Shift Register. If no data
has been written in the TDR register, the last data received is transferred. If no data has been
received since the last reset, all bits are transmitted low, as the Shift Register resets to zero.
When a first data is written in TDR, it is transferred immediately in the Shift Register and the
SR.TDRE bit rises. If new data is written, it remains in TDR until a transfer occurs, i.e. NSS falls
and there is a valid clock on the SPCK pin. When the transfer occurs, the last data written in
TDR is transferred in the Shift Register and the SR.TDRE bit rises. This enables frequent
updates of critical variables with single transfers.
Then, a new data is loaded in the Shift Register from the TDR. In case no character is ready to
be transmitted, i.e. no character has been written in TDR since the last load from TDR to the
Shift Register, the Shift Register is not modified and the last received character is retransmitted.
In this case the Underrun Error Status bit is set in SR (SR.UNDES).
Figure 21-9 on page 498 shows a block diagram of the SPI when operating in slave mode.
498
32142D–06/2013
ATUC64/128/256L3/4U
Figure 21-9. Slave Mode Functional Block Diagram
Shift Register
SPCK
SPIENS
LSB MSB
NSS
MOSI
SPI
Clock
TDRE
TDR
TD
RDRF
OVRES
CSR0
CPOL
NCPHA
BITS
SPIEN
SPIDIS
MISO
UNDES
RDR
RD
4 - Character FIFO
0
1
RXFIFOEN
499
32142D–06/2013
ATUC64/128/256L3/4U
21.8 User Interface
Note: 1. The reset values are device specific. Please refer to the Module Configuration section at the end of this chapter.
Table 21-3. SPI Register Memory Map
Offset Register Register Name Access Reset
0x00 Control Register CR Write-only 0x00000000
0x04 Mode Register MR Read/Write 0x00000000
0x08 Receive Data Register RDR Read-only 0x00000000
0x0C Transmit Data Register TDR Write-only 0x00000000
0x10 Status Register SR Read-only 0x00000000
0x14 Interrupt Enable Register IER Write-only 0x00000000
0x18 Interrupt Disable Register IDR Write-only 0x00000000
0x1C Interrupt Mask Register IMR Read-only 0x00000000
0x30 Chip Select Register 0 CSR0 Read/Write 0x00000000
0x34 Chip Select Register 1 CSR1 Read/Write 0x00000000
0x38 Chip Select Register 2 CSR2 Read/Write 0x00000000
0x3C Chip Select Register 3 CSR3 Read/Write 0x00000000
0x E4 Write Protection Control Register WPCR Read/Write 0X00000000
0xE8 Write Protection Status Register WPSR Read-only 0x00000000
0xF8 Features Register FEATURES Read-only - (1)
0xFC Version Register VERSION Read-only - (1)
500
32142D–06/2013
ATUC64/128/256L3/4U
21.8.1 Control Register
Name: CR
Access Type: Write-only
Offset: 0x00
Reset Value: 0x00000000
• LASTXFER: Last Transfer
1: The current NPCS will be deasserted after the character written in TD has been transferred. When CSRn.CSAAT is one, this
allows to close the communication with the current serial peripheral by raising the corresponding NPCS line as soon as TD
transfer has completed.
0: Writing a zero to this bit has no effect.
• FLUSHFIFO: Flush Fifo Command
1: If The FIFO Mode is enabled (MR.FIFOEN written to one) and if an overrun error has been detected, this command allows to
empty the FIFO.
0: Writing a zero to this bit has no effect.
• SWRST: SPI Software Reset
1: Writing a one to this bit will reset the SPI. A software-triggered hardware reset of the SPI interface is performed. The SPI is in
slave mode after software reset. Peripheral DMA Controller channels are not affected by software reset.
0: Writing a zero to this bit has no effect.
• SPIDIS: SPI Disable
1: Writing a one to this bit will disable the SPI. As soon as SPIDIS is written to one, the SPI finishes its transfer, all pins are set
in input mode and no data is received or transmitted. If a transfer is in progress, the transfer is finished before the SPI is
disabled. If both SPIEN and SPIDIS are equal to one when the CR register is written, the SPI is disabled.
0: Writing a zero to this bit has no effect.
• SPIEN: SPI Enable
1: Writing a one to this bit will enable the SPI to transfer and receive data.
0: Writing a zero to this bit has no effect.
31 30 29 28 27 26 25 24
- - - - - - - LASTXFER
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
- - - - - - - FLUSHFIFO
76543210
SWRST - - - - - SPIDIS SPIEN
501
32142D–06/2013
ATUC64/128/256L3/4U
21.8.2 Mode Register
Name: MR
Access Type: Read/Write
Offset: 0x04
Reset Value: 0x00000000
• DLYBCS: Delay Between Chip Selects
This field defines the delay from NPCS inactive to the activation of another NPCS. The DLYBCS time guarantees nonoverlapping
chip selects and solves bus contentions in case of peripherals having long data float times.
If DLYBCS is less than or equal to six, six CLK_SPI periods will be inserted by default.
Otherwise, the following equation determines the delay:
• PCS: Peripheral Chip Select
This field is only used if Fixed Peripheral Select is active (PS = 0).
If PCSDEC = 0:
PCS = xxx0NPCS[3:0] = 1110
PCS = xx01NPCS[3:0] = 1101
PCS = x011NPCS[3:0] = 1011
PCS = 0111NPCS[3:0] = 0111
PCS = 1111forbidden (no peripheral is selected)
(x = don’t care)
If PCSDEC = 1:
NPCS[3:0] output signals = PCS.
• LLB: Local Loopback Enable
1: Local loopback path enabled. LLB controls the local loopback on the data serializer for testing in master mode only (MISO is
internally connected on MOSI).
0: Local loopback path disabled.
• RXFIFOEN: FIFO in Reception Enable
1: The FIFO is used in reception (four characters can be stored in the SPI).
31 30 29 28 27 26 25 24
DLYBCS
23 22 21 20 19 18 17 16
- - - - PCS
15 14 13 12 11 10 9 8
--------
76543210
LLB RXFIFOEN - MODFDIS - PCSDEC PS MSTR
Delay Between Chip Selects DLYBCS
CLKSPI = -----------------------
502
32142D–06/2013
ATUC64/128/256L3/4U
0: The FIFO is not used in reception (only one character can be stored in the SPI).
• MODFDIS: Mode Fault Detection
1: Mode fault detection is disabled. If the I/O controller does not have open-drain capability, mode fault detection must be
disabled for proper operation of the SPI.
0: Mode fault detection is enabled.
• PCSDEC: Chip Select Decode
0: The chip selects are directly connected to a peripheral device.
1: The four chip select lines are connected to a 4- to 16-bit decoder.
When PCSDEC equals one, up to 15 Chip Select signals can be generated with the four lines using an external 4- to 16-bit
decoder. The CSRn registers define the characteristics of the 15 chip selects according to the following rules:
CSR0 defines peripheral chip select signals 0 to 3.
CSR1 defines peripheral chip select signals 4 to 7.
CSR2 defines peripheral chip select signals 8 to 11.
CSR3 defines peripheral chip select signals 12 to 14.
• PS: Peripheral Select
1: Variable Peripheral Select.
0: Fixed Peripheral Select.
• MSTR: Master/Slave Mode
1: SPI is in master mode.
0: SPI is in slave mode.
503
32142D–06/2013
ATUC64/128/256L3/4U
21.8.3 Receive Data Register
Name: RDR
Access Type: Read-only
Offset: 0x08
Reset Value: 0x00000000
• RD: Receive Data
Data received by the SPI Interface is stored in this register right-justified. Unused bits read zero.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
RD[15:8]
76543210
RD[7:0]
504
32142D–06/2013
ATUC64/128/256L3/4U
21.8.4 Transmit Data Register
Name: TDR
Access Type: Write-only
Offset: 0x0C
Reset Value: 0x00000000
• LASTXFER: Last Transfer
1: The current NPCS will be deasserted after the character written in TD has been transferred. When CSRn.CSAAT is one, this
allows to close the communication with the current serial peripheral by raising the corresponding NPCS line as soon as TD
transfer has completed.
0: Writing a zero to this bit has no effect.
This field is only used if Variable Peripheral Select is active (MR.PS = 1).
• PCS: Peripheral Chip Select
If PCSDEC = 0:
PCS = xxx0NPCS[3:0] = 1110
PCS = xx01NPCS[3:0] = 1101
PCS = x011NPCS[3:0] = 1011
PCS = 0111NPCS[3:0] = 0111
PCS = 1111forbidden (no peripheral is selected)
(x = don’t care)
If PCSDEC = 1:
NPCS[3:0] output signals = PCS
This field is only used if Variable Peripheral Select is active (MR.PS = 1).
• TD: Transmit Data
Data to be transmitted by the SPI Interface is stored in this register. Information to be transmitted must be written to the TDR
register in a right-justified format.
31 30 29 28 27 26 25 24
- - - - - - - LASTXFER
23 22 21 20 19 18 17 16
- - - - PCS
15 14 13 12 11 10 9 8
TD[15:8]
76543210
TD[7:0]
505
32142D–06/2013
ATUC64/128/256L3/4U
21.8.5 Status Register
Name: SR
Access Type: Read-only
Offset: 0x10
Reset Value: 0x00000000
• SPIENS: SPI Enable Status
1: This bit is set when the SPI is enabled.
0: This bit is cleared when the SPI is disabled.
• UNDES: Underrun Error Status (Slave Mode Only)
1: This bit is set when a transfer begins whereas no data has been loaded in the TDR register.
0: This bit is cleared when the SR register is read.
• TXEMPTY: Transmission Registers Empty
1: This bit is set when TDR and internal shifter are empty. If a transfer delay has been defined, TXEMPTY is set after the
completion of such delay.
0: This bit is cleared as soon as data is written in TDR.
• NSSR: NSS Rising
1: A rising edge occurred on NSS pin since last read.
0: This bit is cleared when the SR register is read.
• OVRES: Overrun Error Status
1: This bit is set when an overrun has occurred. An overrun occurs when RDR is loaded at least twice from the serializer since
the last read of the RDR.
0: This bit is cleared when the SR register is read.
• MODF: Mode Fault Error
1: This bit is set when a Mode Fault occurred.
0: This bit is cleared when the SR register is read.
• TDRE: Transmit Data Register Empty
1: This bit is set when the last data written in the TDR register has been transferred to the serializer.
0: This bit is cleared when data has been written to TDR and not yet transferred to the serializer.
TDRE equals zero when the SPI is disabled or at reset. The SPI enable command sets this bit to one.
• RDRF: Receive Data Register Full
1: Data has been received and the received data has been transferred from the serializer to RDR since the last read of RDR.
0: No data has been received since the last read of RDR
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
- - - - - - - SPIENS
15 14 13 12 11 10 9 8
- - - - - UNDES TXEMPTY NSSR
76543210
- - - - OVRES MODF TDRE RDRF
506
32142D–06/2013
ATUC64/128/256L3/4U
21.8.6 Interrupt Enable Register
Name: IER
Access Type: Write-only
Offset: 0x14
Reset Value: 0x00000000
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will set the corresponding bit in IMR.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
- - - - - UNDES TXEMPTY NSSR
76543210
- - - - OVRES MODF TDRE RDRF
507
32142D–06/2013
ATUC64/128/256L3/4U
21.8.7 Interrupt Disable Register
Name: IDR
Access Type: Write-only
Offset: 0x18
Reset Value: 0x00000000
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will clear the corresponding bit in IMR.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
- - - - - UNDES TXEMPTY NSSR
76543210
- - - - OVRES MODF TDRE RDRF
508
32142D–06/2013
ATUC64/128/256L3/4U
21.8.8 Interrupt Mask Register
Name: IMR
Access Type: Read-only
Offset: 0x1C
Reset Value: 0x00000000
0: The corresponding interrupt is disabled.
1: The corresponding interrupt is enabled.
A bit in this register is cleared when the corresponding bit in IDR is written to one.
A bit in this register is set when the corresponding bit in IER is written to one.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
- - - - - UNDES TXEMPTY NSSR
76543210
- - - - OVRES MODF TDRE RDRF
509
32142D–06/2013
ATUC64/128/256L3/4U
21.8.9 Chip Select Register 0
Name: CSR0
Access Type: Read/Write
Offset: 0x30
Reset Value: 0x00000000
• DLYBCT: Delay Between Consecutive Transfers
This field defines the delay between two consecutive transfers with the same peripheral without removing the chip select. The
delay is always inserted after each transfer and before removing the chip select if needed.
When DLYBCT equals zero, no delay between consecutive transfers is inserted and the clock keeps its duty cycle over the
character transfers.
Otherwise, the following equation determines the delay:
• DLYBS: Delay Before SPCK
This field defines the delay from NPCS valid to the first valid SPCK transition.
When DLYBS equals zero, the NPCS valid to SPCK transition is 1/2 the SPCK clock period.
Otherwise, the following equations determine the delay:
• SCBR: Serial Clock Baud Rate
In Master Mode, the SPI Interface uses a modulus counter to derive the SPCK baud rate from the CLK_SPI. The Baud rate is
selected by writing a value from 1 to 255 in the SCBR field. The following equations determine the SPCK baud rate:
Writing the SCBR field to zero is forbidden. Triggering a transfer while SCBR is zero can lead to unpredictable results.
At reset, SCBR is zero and the user has to write it to a valid value before performing the first transfer.
If a clock divider (SCBRn) field is set to one and the other SCBR fields differ from one, access on CSn is correct but no correct
access will be possible on other CS.
31 30 29 28 27 26 25 24
DLYBCT
23 22 21 20 19 18 17 16
DLYBS
15 14 13 12 11 10 9 8
SCBR
76543210
BITS CSAAT CSNAAT NCPHA CPOL
Delay Between Consecutive Transfers 32 DLYBCT
CLKSPI = ------------------------------------
Delay Before SPCK DLYBS
CLKSPI = ---------------------
SPCK Baudrate CLKSPI
SCBR = ---------------------
510
32142D–06/2013
ATUC64/128/256L3/4U
• BITS: Bits Per Transfer
The BITS field determines the number of data bits transferred. Reserved values should not be used.
• CSAAT: Chip Select Active After Transfer
1: The Peripheral Chip Select does not rise after the last transfer is achieved. It remains active until a new transfer is requested
on a different chip select.
0: The Peripheral Chip Select Line rises as soon as the last transfer is achieved.
• CSNAAT: Chip Select Not Active After Transfer (Ignored if CSAAT = 1)
0: The Peripheral Chip Select does not rise between two transfers if the TDR is reloaded before the end of the first transfer and
if the two transfers occur on the same Chip Select.
1: The Peripheral Chip Select rises systematically between each transfer performed on the same slave for a minimal duration of:
(if DLYBCT field is different from 0)
(if DLYBCT field equals 0)
• NCPHA: Clock Phase
1: Data is captured after the leading (inactive-to-active) edge of SPCK and changed on the trailing (active-to-inactive) edge of
SPCK.
0: Data is changed on the leading (inactive-to-active) edge of SPCK and captured after the trailing (active-to-inactive) edge of
SPCK.
NCPHA determines which edge of SPCK causes data to change and which edge causes data to be captured. NCPHA is used
with CPOL to produce the required clock/data relationship between master and slave devices.
• CPOL: Clock Polarity
1: The inactive state value of SPCK is logic level one.
0: The inactive state value of SPCK is logic level zero.
BITS Bits Per Transfer
0000 8
0001 9
0010 10
0011 11
0100 12
0101 13
0110 14
0111 15
1000 16
1001 4
1010 5
1011 6
1100 7
1101 Reserved
1110 Reserved
1111 Reserved
DLYBCS
CLKSPI
-----------------------
DLYBCS + 1
CLKSPI
--------------------------------
511
32142D–06/2013
ATUC64/128/256L3/4U
CPOL is used to determine the inactive state value of the serial clock (SPCK). It is used with NCPHA to produce the required
clock/data relationship between master and slave devices.
512
32142D–06/2013
ATUC64/128/256L3/4U
21.8.10 Chip Select Register 1
Name: CSR1
Access Type: Read/Write
Offset: 0x34
Reset Value: 0x00000000
• DLYBCT: Delay Between Consecutive Transfers
This field defines the delay between two consecutive transfers with the same peripheral without removing the chip select. The
delay is always inserted after each transfer and before removing the chip select if needed.
When DLYBCT equals zero, no delay between consecutive transfers is inserted and the clock keeps its duty cycle over the
character transfers.
Otherwise, the following equation determines the delay:
• DLYBS: Delay Before SPCK
This field defines the delay from NPCS valid to the first valid SPCK transition.
When DLYBS equals zero, the NPCS valid to SPCK transition is 1/2 the SPCK clock period.
Otherwise, the following equations determine the delay:
• SCBR: Serial Clock Baud Rate
In Master Mode, the SPI Interface uses a modulus counter to derive the SPCK baud rate from the CLK_SPI. The Baud rate is
selected by writing a value from 1 to 255 in the SCBR field. The following equations determine the SPCK baud rate:
Writing the SCBR field to zero is forbidden. Triggering a transfer while SCBR is zero can lead to unpredictable results.
At reset, SCBR is zero and the user has to write it to a valid value before performing the first transfer.
If a clock divider (SCBRn) field is set to one and the other SCBR fields differ from one, access on CSn is correct but no correct
access will be possible on other CS.
31 30 29 28 27 26 25 24
DLYBCT
23 22 21 20 19 18 17 16
DLYBS
15 14 13 12 11 10 9 8
SCBR
76543210
BITS CSAAT CSNAAT NCPHA CPOL
Delay Between Consecutive Transfers 32 DLYBCT
CLKSPI = ------------------------------------
Delay Before SPCK DLYBS
CLKSPI = ---------------------
SPCK Baudrate CLKSPI
SCBR = ---------------------
513
32142D–06/2013
ATUC64/128/256L3/4U
• BITS: Bits Per Transfer
The BITS field determines the number of data bits transferred. Reserved values should not be used.
• CSAAT: Chip Select Active After Transfer
1: The Peripheral Chip Select does not rise after the last transfer is achieved. It remains active until a new transfer is requested
on a different chip select.
0: The Peripheral Chip Select Line rises as soon as the last transfer is achieved.
• CSNAAT: Chip Select Not Active After Transfer (Ignored if CSAAT = 1)
0: The Peripheral Chip Select does not rise between two transfers if the TDR is reloaded before the end of the first transfer and
if the two transfers occur on the same Chip Select.
1: The Peripheral Chip Select rises systematically between each transfer performed on the same slave for a minimal duration of:
(if DLYBCT field is different from 0)
(if DLYBCT field equals 0)
• NCPHA: Clock Phase
1: Data is captured after the leading (inactive-to-active) edge of SPCK and changed on the trailing (active-to-inactive) edge of
SPCK.
0: Data is changed on the leading (inactive-to-active) edge of SPCK and captured after the trailing (active-to-inactive) edge of
SPCK.
NCPHA determines which edge of SPCK causes data to change and which edge causes data to be captured. NCPHA is used
with CPOL to produce the required clock/data relationship between master and slave devices.
• CPOL: Clock Polarity
1: The inactive state value of SPCK is logic level one.
0: The inactive state value of SPCK is logic level zero.
BITS Bits Per Transfer
0000 8
0001 9
0010 10
0011 11
0100 12
0101 13
0110 14
0111 15
1000 16
1001 4
1010 5
1011 6
1100 7
1101 Reserved
1110 Reserved
1111 Reserved
DLYBCS
CLKSPI
-----------------------
DLYBCS + 1
CLKSPI
--------------------------------
514
32142D–06/2013
ATUC64/128/256L3/4U
CPOL is used to determine the inactive state value of the serial clock (SPCK). It is used with NCPHA to produce the required
clock/data relationship between master and slave devices.
515
32142D–06/2013
ATUC64/128/256L3/4U
21.8.11 Chip Select Register 2
Name: CSR2
Access Type: Read/Write
Offset: 0x38
Reset Value: 0x00000000
• DLYBCT: Delay Between Consecutive Transfers
This field defines the delay between two consecutive transfers with the same peripheral without removing the chip select. The
delay is always inserted after each transfer and before removing the chip select if needed.
When DLYBCT equals zero, no delay between consecutive transfers is inserted and the clock keeps its duty cycle over the
character transfers.
Otherwise, the following equation determines the delay:
• DLYBS: Delay Before SPCK
This field defines the delay from NPCS valid to the first valid SPCK transition.
When DLYBS equals zero, the NPCS valid to SPCK transition is 1/2 the SPCK clock period.
Otherwise, the following equations determine the delay:
• SCBR: Serial Clock Baud Rate
In Master Mode, the SPI Interface uses a modulus counter to derive the SPCK baud rate from the CLK_SPI. The Baud rate is
selected by writing a value from 1 to 255 in the SCBR field. The following equations determine the SPCK baud rate:
Writing the SCBR field to zero is forbidden. Triggering a transfer while SCBR is zero can lead to unpredictable results.
At reset, SCBR is zero and the user has to write it to a valid value before performing the first transfer.
If a clock divider (SCBRn) field is set to one and the other SCBR fields differ from one, access on CSn is correct but no correct
access will be possible on other CS.
31 30 29 28 27 26 25 24
DLYBCT
23 22 21 20 19 18 17 16
DLYBS
15 14 13 12 11 10 9 8
SCBR
76543210
BITS CSAAT CSNAAT NCPHA CPOL
Delay Between Consecutive Transfers 32 DLYBCT
CLKSPI = ------------------------------------
Delay Before SPCK DLYBS
CLKSPI = ---------------------
SPCK Baudrate CLKSPI
SCBR = ---------------------
516
32142D–06/2013
ATUC64/128/256L3/4U
• BITS: Bits Per Transfer
The BITS field determines the number of data bits transferred. Reserved values should not be used.
• CSAAT: Chip Select Active After Transfer
1: The Peripheral Chip Select does not rise after the last transfer is achieved. It remains active until a new transfer is requested
on a different chip select.
0: The Peripheral Chip Select Line rises as soon as the last transfer is achieved.
• CSNAAT: Chip Select Not Active After Transfer (Ignored if CSAAT = 1)
0: The Peripheral Chip Select does not rise between two transfers if the TDR is reloaded before the end of the first transfer and
if the two transfers occur on the same Chip Select.
1: The Peripheral Chip Select rises systematically between each transfer performed on the same slave for a minimal duration of:
(if DLYBCT field is different from 0)
(if DLYBCT field equals 0)
• NCPHA: Clock Phase
1: Data is captured after the leading (inactive-to-active) edge of SPCK and changed on the trailing (active-to-inactive) edge of
SPCK.
0: Data is changed on the leading (inactive-to-active) edge of SPCK and captured after the trailing (active-to-inactive) edge of
SPCK.
NCPHA determines which edge of SPCK causes data to change and which edge causes data to be captured. NCPHA is used
with CPOL to produce the required clock/data relationship between master and slave devices.
• CPOL: Clock Polarity
1: The inactive state value of SPCK is logic level one.
0: The inactive state value of SPCK is logic level zero.
BITS Bits Per Transfer
0000 8
0001 9
0010 10
0011 11
0100 12
0101 13
0110 14
0111 15
1000 16
1001 4
1010 5
1011 6
1100 7
1101 Reserved
1110 Reserved
1111 Reserved
DLYBCS
CLKSPI
-----------------------
DLYBCS + 1
CLKSPI
--------------------------------
517
32142D–06/2013
ATUC64/128/256L3/4U
CPOL is used to determine the inactive state value of the serial clock (SPCK). It is used with NCPHA to produce the required
clock/data relationship between master and slave devices.
518
32142D–06/2013
ATUC64/128/256L3/4U
21.8.12 Chip Select Register 3
Name: CSR3
Access Type: Read/Write
Offset: 0x3C
Reset Value: 0x00000000
• DLYBCT: Delay Between Consecutive Transfers
This field defines the delay between two consecutive transfers with the same peripheral without removing the chip select. The
delay is always inserted after each transfer and before removing the chip select if needed.
When DLYBCT equals zero, no delay between consecutive transfers is inserted and the clock keeps its duty cycle over the
character transfers.
Otherwise, the following equation determines the delay:
• DLYBS: Delay Before SPCK
This field defines the delay from NPCS valid to the first valid SPCK transition.
When DLYBS equals zero, the NPCS valid to SPCK transition is 1/2 the SPCK clock period.
Otherwise, the following equations determine the delay:
• SCBR: Serial Clock Baud Rate
In Master Mode, the SPI Interface uses a modulus counter to derive the SPCK baud rate from the CLK_SPI. The Baud rate is
selected by writing a value from 1 to 255 in the SCBR field. The following equations determine the SPCK baud rate:
Writing the SCBR field to zero is forbidden. Triggering a transfer while SCBR is zero can lead to unpredictable results.
At reset, SCBR is zero and the user has to write it to a valid value before performing the first transfer.
If a clock divider (SCBRn) field is set to one and the other SCBR fields differ from one, access on CSn is correct but no correct
access will be possible on other CS.
31 30 29 28 27 26 25 24
DLYBCT
23 22 21 20 19 18 17 16
DLYBS
15 14 13 12 11 10 9 8
SCBR
76543210
BITS CSAAT CSNAAT NCPHA CPOL
Delay Between Consecutive Transfers 32 DLYBCT
CLKSPI = ------------------------------------
Delay Before SPCK DLYBS
CLKSPI = ---------------------
SPCK Baudrate CLKSPI
SCBR = ---------------------
519
32142D–06/2013
ATUC64/128/256L3/4U
• BITS: Bits Per Transfer
The BITS field determines the number of data bits transferred. Reserved values should not be used.
• CSAAT: Chip Select Active After Transfer
1: The Peripheral Chip Select does not rise after the last transfer is achieved. It remains active until a new transfer is requested
on a different chip select.
0: The Peripheral Chip Select Line rises as soon as the last transfer is achieved.
• CSNAAT: Chip Select Not Active After Transfer (Ignored if CSAAT = 1)
0: The Peripheral Chip Select does not rise between two transfers if the TDR is reloaded before the end of the first transfer and
if the two transfers occur on the same Chip Select.
1: The Peripheral Chip Select rises systematically between each transfer performed on the same slave for a minimal duration of:
(if DLYBCT field is different from 0)
(if DLYBCT field equals 0)
• NCPHA: Clock Phase
1: Data is captured after the leading (inactive-to-active) edge of SPCK and changed on the trailing (active-to-inactive) edge of
SPCK.
0: Data is changed on the leading (inactive-to-active) edge of SPCK and captured after the trailing (active-to-inactive) edge of
SPCK.
NCPHA determines which edge of SPCK causes data to change and which edge causes data to be captured. NCPHA is used
with CPOL to produce the required clock/data relationship between master and slave devices.
• CPOL: Clock Polarity
1: The inactive state value of SPCK is logic level one.
0: The inactive state value of SPCK is logic level zero.
BITS Bits Per Transfer
0000 8
0001 9
0010 10
0011 11
0100 12
0101 13
0110 14
0111 15
1000 16
1001 4
1010 5
1011 6
1100 7
1101 Reserved
1110 Reserved
1111 Reserved
DLYBCS
CLKSPI
-----------------------
DLYBCS + 1
CLKSPI
--------------------------------
520
32142D–06/2013
ATUC64/128/256L3/4U
CPOL is used to determine the inactive state value of the serial clock (SPCK). It is used with NCPHA to produce the required
clock/data relationship between master and slave devices.
521
32142D–06/2013
ATUC64/128/256L3/4U
21.8.13 Write Protection Control Register
Register Name: WPCR
Access Type: Read-write
Offset: 0xE4
Reset Value: 0x00000000
• SPIWPKEY: SPI Write Protection Key Password
If a value is written in SPIWPEN, the value is taken into account only if SPIWPKEY is written with “SPI” (SPI written in ASCII
Code, i.e. 0x535049 in hexadecimal).
• SPIWPEN: SPI Write Protection Enable
1: The Write Protection is Enabled
0: The Write Protection is Disabled
31 30 29 28 27 26 25 24
SPIWPKEY[23:16]
23 22 21 20 19 18 17 16
SPIWPKEY[15:8]
15 14 13 12 11 10 9 8
SPIWPKEY[7:0]
76543210
- - - - - - - SPIWPEN
522
32142D–06/2013
ATUC64/128/256L3/4U
21.8.14 Write Protection Status Register
Register Name: WPSR
Access Type: Read-only
Offset: 0xE8
Reset Value: 0x00000000
• SPIWPVSRC: SPI Write Protection Violation Source
This Field indicates the Peripheral Bus Offset of the register concerned by the violation (MR or CSRx)
• SPIWPVS: SPI Write Protection Violation Status
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
SPIWPVSRC
76543210
- - - - - SPIWPVS
SPIWPVS value Violation Type
1 The Write Protection has blocked a Write access to a protected register (since the last read).
2 Software Reset has been performed while Write Protection was enabled (since the last read
or since the last write access on MR, IER, IDR or CSRx).
3 Both Write Protection violation and software reset with Write Protection enabled have
occurred since the last read.
4 Write accesses have been detected on MR (while a chip select was active) or on CSRi (while
the Chip Select “i” was active) since the last read.
5
The Write Protection has blocked a Write access to a protected register and write accesses
have been detected on MR (while a chip select was active) or on CSRi (while the Chip Select
“i” was active) since the last read.
6
Software Reset has been performed while Write Protection was enabled (since the last read
or since the last write access on MR, IER, IDR or CSRx) and some write accesses have been
detected on MR (while a chip select was active) or on CSRi (while the Chip Select “i” was
active) since the last read.
7
- The Write Protection has blocked a Write access to a protected register.
and
- Software Reset has been performed while Write Protection was enabled.
and
- Write accesses have been detected on MR (while a chip select was active) or on CSRi
(while the Chip Select “i” was active) since the last read.
523
32142D–06/2013
ATUC64/128/256L3/4U
21.8.15 Features Register
Register Name: FEATURES
Access Type: Read-only
Offset: 0xF8
Reset Value: –
• SWIMPL: Spurious Write Protection Implemented
0: Spurious write protection is not implemented.
1: Spurious write protection is implemented.
• FIFORIMPL: FIFO in Reception Implemented
0: FIFO in reception is not implemented.
1: FIFO in reception is implemented.
• BRPBHSB: Bridge Type is PB to HSB
0: Bridge type is not PB to HSB.
1: Bridge type is PB to HSB.
• CSNAATIMPL: CSNAAT Features Implemented
0: CSNAAT (Chip select not active after transfer) features are not implemented.
1: CSNAAT features are implemented.
• EXTDEC: External Decoder True
0: External decoder capability is not implemented.
1: External decoder capability is implemented.
• LENNCONF: Character Length if not Configurable
If the character length is not configurable, this field specifies the fixed character length.
• LENCONF: Character Length Configurable
0: The character length is not configurable.
1: The character length is configurable.
• PHZNCONF: Phase is Zero if Phase not Configurable
0: If phase is not configurable, phase is non-zero.
1: If phase is not configurable, phase is zero.
• PHCONF: Phase Configurable
0: Phase is not configurable.
1: Phase is configurable.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
- - - SWIMPL FIFORIMPL BRPBHSB CSNAATIMPL EXTDEC
15 14 13 12 11 10 9 8
LENNCONF LENCONF
76543210
PHZNCONF PHCONF PPNCONF PCONF NCS
524
32142D–06/2013
ATUC64/128/256L3/4U
• PPNCONF: Polarity Positive if Polarity not Configurable
0: If polarity is not configurable, polarity is negative.
1: If polarity is not configurable, polarity is positive.
• PCONF: Polarity Configurable
0: Polarity is not configurable.
1: Polarity is configurable.
• NCS: Number of Chip Selects
This field indicates the number of chip selects implemented.
525
32142D–06/2013
ATUC64/128/256L3/4U
21.8.16 Version Register
Register Name: VERSION
Access Type: Read-only
Offset: 0xFC
Reset Value: –
• MFN
Reserved. No functionality associated.
• VERSION
Version number of the module. No functionality associated.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
- - - - MFN
15 14 13 12 11 10 9 8
VERSION[11:8]
76543210
VERSION[7:0]
526
32142D–06/2013
ATUC64/128/256L3/4U
21.9 Module Configuration
The specific configuration for each SPI instance is listed in the following tables.The module bus
clocks listed here are connected to the system bus clocks. Please refer to the Power Manager
chapter for details.
Table 21-4. SPI Clock Name
Module Name Clock Name Description
SPI CLK_SPI Clock for the SPI bus interface
Table 21-5.
Register Reset Value
FEATURES 0x001F0154
VERSION 0x00000211
527
32142D–06/2013
ATUC64/128/256L3/4U
22. Two-wire Master Interface (TWIM)
Rev.: 1.1.0.1
22.1 Features
• Compatible with I²C standard
– Multi-master support
– Transfer speeds of 100 and 400 kbit/s
– 7- and 10-bit and General Call addressing
• Compatible with SMBus standard
– Hardware Packet Error Checking (CRC) generation and verification with ACK control
– SMBus ALERT interface
– 25 ms clock low timeout delay
– 10 ms master cumulative clock low extend time
– 25 ms slave cumulative clock low extend time
• Compatible with PMBus
• Compatible with Atmel Two-wire Interface Serial Memories
• DMA interface for reducing CPU load
• Arbitrary transfer lengths, including 0 data bytes
• Optional clock stretching if transmit or receive buffers not ready for data transfer
22.2 Overview
The Atmel Two-wire Master Interface (TWIM) interconnects components on a unique two-wire
bus, made up of one clock line and one data line with speeds of up to 400 kbit/s, based on a
byte-oriented transfer format. It can be used with any Atmel Two-wire Interface bus serial
EEPROM and I²C compatible device such as a real time clock (RTC), dot matrix/graphic LCD
controller, and temperature sensor, to name a few. The TWIM is always a bus master and can
transfer sequential or single bytes. Multiple master capability is supported. Arbitration of the bus
is performed internally and relinquishes the bus automatically if the bus arbitration is lost.
A configurable baud rate generator permits the output data rate to be adapted to a wide range of
core clock frequencies.Table 22-1 lists the compatibility level of the Atmel Two-wire Interface in
Master Mode and a full I²C compatible device.
Note: 1. START + b000000001 + Ack + Sr
Table 22-1. Atmel TWIM Compatibility with I²C Standard
I²C Standard Atmel TWIM
Standard-mode (100 kbit/s) Supported
Fast-mode (400 kbit/s) Supported
Fast-mode Plus (1 Mbit/s) Supported
7- or 10-bits Slave Addressing Supported
START BYTE(1) Not Supported
Repeated Start (Sr) Condition Supported
ACK and NACK Management Supported
Slope Control and Input Filtering (Fast mode) Supported
Clock Stretching Supported
528
32142D–06/2013
ATUC64/128/256L3/4U
Table 22-2 lists the compatibility level of the Atmel Two-wire Master Interface and a full SMBus
compatible master.
22.3 List of Abbreviations
22.4 Block Diagram
Figure 22-1. Block Diagram
Table 22-2. Atmel TWIM Compatibility with SMBus Standard
SMBus Standard Atmel TWIM
Bus Timeouts Supported
Address Resolution Protocol Supported
Alert Supported
Host Functionality Supported
Packet Error Checking Supported
Table 22-3. Abbreviations
Abbreviation Description
TWI Two-wire Interface
A Acknowledge
NA Non Acknowledge
P Stop
S Start
Sr Repeated Start
SADR Slave Address
ADR Any address except SADR
R Read
W Write
Peripheral
Bus Bridge
Two-wire
Interface
I/O Controller
TWCK
TWD
INTC
TWI Interrupt
Power
Manager
CLK_TWIM
TWALM
529
32142D–06/2013
ATUC64/128/256L3/4U
22.5 Application Block Diagram
Figure 22-2. Application Block Diagram
22.6 I/O Lines Description
22.7 Product Dependencies
In order to use this module, other parts of the system must be configured correctly, as described
below.
22.7.1 I/O Lines
TWD and TWCK are bidirectional lines, connected to a positive supply voltage via a current
source or pull-up resistor (see Figure 22-4 on page 531). When the bus is free, both lines are
high. The output stages of devices connected to the bus must have an open-drain or open-collector
to perform the wired-AND function.
TWALM is used to implement the optional SMBus SMBALERT signal.
The TWALM, TWD, and TWCK pins may be multiplexed with I/O Controller lines. To enable the
TWIM, the user must perform the following steps:
• Program the I/O Controller to:
– Dedicate TWD, TWCK, and optionally TWALM as peripheral lines.
– Define TWD, TWCK, and optionally TWALM as open-drain.
22.7.2 Power Management
If the CPU enters a sleep mode that disables clocks used by the TWIM, the TWIM will stop functioning
and resume operation after the system wakes up from sleep mode.
TWI
Master
TWD
TWCK
Atmel TWI
serial EEPROM I
2
C RTC I
2
C LCD
controller
I
2
C temp
sensor
Slave 2 Slave 3 Slave 4
VDD
Rp: pull-up value as given by the I2C Standard
TWALM
Slave 1
Rp Rp Rp
Table 22-4. I/O Lines Description
Pin Name Pin Description Type
TWD Two-wire Serial Data Input/Output
TWCK Two-wire Serial Clock Input/Output
TWALM SMBus SMBALERT Input/Output
530
32142D–06/2013
ATUC64/128/256L3/4U
22.7.3 Clocks
The clock for the TWIM bus interface (CLK_TWIM) is generated by the Power Manager. This
clock is enabled at reset, and can be disabled in the Power Manager. It is recommended to disable
the TWIM before disabling the clock, to avoid freezing the TWIM in an undefined state.
22.7.4 DMA
The TWIM DMA handshake interface is connected to the Peripheral DMA Controller. Using the
TWIM DMA functionality requires the Peripheral DMA Controller to be programmed after setting
up the TWIM.
22.7.5 Interrupts
The TWIM interrupt request lines are connected to the interrupt controller. Using the TWIM interrupts
requires the interrupt controller to be programmed first.
22.7.6 Debug Operation
When an external debugger forces the CPU into debug mode, the TWIM continues normal operation.
If the TWIM is configured in a way that requires it to be periodically serviced by the CPU
through interrupts or similar, improper operation or data loss may result during debugging.
531
32142D–06/2013
ATUC64/128/256L3/4U
22.8 Functional Description
22.8.1 Transfer Format
The data put on the TWD line must be 8 bits long. Data is transferred MSB first; each byte must
be followed by an acknowledgement. The number of bytes per transfer is unlimited (see Figure
22-4).
Each transfer begins with a START condition and terminates with a STOP condition (see Figure
22-4).
• A high-to-low transition on the TWD line while TWCK is high defines the START condition.
• A low-to-high transition on the TWD line while TWCK is high defines a STOP condition.
Figure 22-3. START and STOP Conditions
Figure 22-4. Transfer Format
22.8.2 Operation
The TWIM has two modes of operation:
• Master transmitter mode
• Master receiver mode
The master is the device which starts and stops a transfer and generates the TWCK clock.
These modes are described in the following chapters.
TWD
TWCK
Start Stop
TWD
TWCK
Start Address R/W Ack Data Ack Data Ack Stop
532
32142D–06/2013
ATUC64/128/256L3/4U
22.8.2.1 Clock Generation
The Clock Waveform Generator Register (CWGR) is used to control the waveform of the TWCK
clock. CWGR must be written so that the desired TWI bus timings are generated. CWGR
describes bus timings as a function of cycles of a prescaled clock. The clock prescaling can be
selected through the Clock Prescaler field in CWGR (CWGR.EXP).
CWGR has the following fields:
LOW: Prescaled clock cycles in clock low count. Used to time TLOW and TBUF.
HIGH: Prescaled clock cycles in clock high count. Used to time THIGH.
STASTO: Prescaled clock cycles in clock high count. Used to time THD_STA, TSU_STA, TSU_STO.
DATA: Prescaled clock cycles for data setup and hold count. Used to time THD_DAT, TSU_DAT.
EXP: Specifies the clock prescaler setting.
Note that the total clock low time generated is the sum of THD_DAT + TSU_DAT + TLOW.
Any slave or other bus master taking part in the transfer may extend the TWCK low period at any
time.
The TWIM hardware monitors the state of the TWCK line as required by the I²C specification.
The clock generation counters are started when a high/low level is detected on the TWCK line,
not when the TWIM hardware releases/drives the TWCK line. This means that the CWGR settings
alone do not determine the TWCK frequency. The CWGR settings determine the clock low
time and the clock high time, but the TWCK rise and fall times are determined by the external circuitry
(capacitive load, etc.).
Figure 22-5. Bus Timing Diagram
f
PRESCALER
f
CLK_TWIM
2 EXP 1 + = -------------------------
S t
HD:STA
t LOW
t
SU:DAT
t HIGH
t
HD:DAT
t LOW
P
t
SU:STO
Sr
t
SU:STA
t
SU:DAT
533
32142D–06/2013
ATUC64/128/256L3/4U
22.8.2.2 Setting up and Performing a Transfer
Operation of the TWIM is mainly controlled by the Control Register (CR) and the Command Register
(CMDR). TWIM status is provided in the Status Register (SR). The following list presents
the main steps in a typical communication:
1. Before any transfers can be performed, bus timings must be configured by writing to the
Clock Waveform Generator Register (CWGR). If operating in SMBus mode, the SMBus
Timing Register (SMBTR) register must also be configured.
2. If the Peripheral DMA Controller is to be used for the transfers, it must be set up.
3. CMDR or NCMDR must be written with a value describing the transfer to be performed.
The interrupt system can be set up to give interrupt requests on specific events or error conditions
in the SR, for example when the transfer is complete or if arbitration is lost. The Interrupt
Enable Register (IER) and Interrupt Disable Register (IDR) can be written to specify which bits in
the SR will generate interrupt requests.
The SR.BUSFREE bit is set when activity is completed on the two-wire bus. The SR.CRDY bit is
set when CMDR and/or NCMDR is ready to receive one or more commands.
The controller will refuse to start a new transfer while ANAK, DNAK, or ARBLST in the Status
Register (SR) is one. This is necessary to avoid a race when the software issues a continuation
of the current transfer at the same time as one of these errors happen. Also, if ANAK or DNAK
occurs, a STOP condition is sent automatically. The user will have to restart the transmission by
clearing the error bits in SR after resolving the cause for the NACK.
After a data or address NACK from the slave, a STOP will be transmitted automatically. Note
that the VALID bit in CMDR is NOT cleared in this case. If this transfer is to be discarded, the
VALID bit can be cleared manually allowing any command in NCMDR to be copied into CMDR.
When a data or address NACK is returned by the slave while the master is transmitting, it is possible
that new data has already been written to the THR register. This data will be transferred out
as the first data byte of the next transfer. If this behavior is to be avoided, the safest approach is
to perform a software reset of the TWIM.
22.8.3 Master Transmitter Mode
A START condition is transmitted and master transmitter mode is initiated when the bus is free
and CMDR has been written with START=1 and READ=0. START and SADR+W will then be
transmitted. During the address acknowledge clock pulse (9th pulse), the master releases the
data line (HIGH), enabling the slave to pull it down in order to acknowledge the address. The
master polls the data line during this clock pulse and sets the Address Not Acknowledged bit
(ANAK) in the Status Register if no slave acknowledges the address.
After the address phase, the following is repeated:
while (NBYTES>0)
1. Wait until THR contains a valid data byte, stretching low period of TWCK. SR.TXRDY
indicates the state of THR. Software or the Peripheral DMA Controller must write the
data byte to THR.
2. Transmit this data byte
3. Decrement NBYTES
4. If (NBYTES==0) and STOP=1, transmit STOP condition
Writing CMDR with START=STOP=1 and NBYTES=0 will generate a transmission with no data
bytes, ie START, SADR+W, STOP.
534
32142D–06/2013
ATUC64/128/256L3/4U
TWI transfers require the slave to acknowledge each received data byte. During the acknowledge
clock pulse (9th pulse), the master releases the data line (HIGH), enabling the slave to pull
it down in order to generate the acknowledge. The master polls the data line during this clock
pulse and sets the Data Acknowledge bit (DNACK) in the Status Register if the slave does not
acknowledge the data byte. As with the other status bits, an interrupt can be generated if
enabled in the Interrupt Enable Register (IER).
TXRDY is used as Transmit Ready for the Peripheral DMA Controller transmit channel.
The end of a command is marked when the TWIM sets the SR.CCOMP bit. See Figure 22-6 and
Figure 22-7.
Figure 22-6. Master Write with One Data Byte
Figure 22-7. Master Write with Multiple Data Bytes
22.8.4 Master Receiver Mode
A START condition is transmitted and master receiver mode is initiated when the bus is free and
CMDR has been written with START=1 and READ=1. START and SADR+R will then be transmitted.
During the address acknowledge clock pulse (9th pulse), the master releases the data
line (HIGH), enabling the slave to pull it down in order to acknowledge the address. The master
polls the data line during this clock pulse and sets the Address Not Acknowledged bit (ANAK) in
the Status Register if no slave acknowledges the address.
After the address phase, the following is repeated:
while (NBYTES>0)
TWD
SR.IDLE
TXRDY
Write THR (DATA)
NBYTES set to 1
STOP sent automatically
(ACK received and NBYTES=0)
S DADR W A DATA A P
TWD
SR.IDLE
TXRDY
Write THR
(DATAn)
NBYTES set to n
STOP sent automatically
(ACK received and NBYTES=0)
S DADR W A DATAn A DATAn+5 A A DATAn+m P
Write THR
(DATAn+1)
Write THR
(DATAn+m)
Last data sent
535
32142D–06/2013
ATUC64/128/256L3/4U
1. Wait until RHR is empty, stretching low period of TWCK. SR.RXRDY indicates the state
of RHR. Software or the Peripheral DMA Controller must read any data byte present in
RHR.
2. Release TWCK generating a clock that the slave uses to transmit a data byte.
3. Place the received data byte in RHR, set RXRDY.
4. If NBYTES=0, generate a NAK after the data byte, otherwise generate an ACK.
5. Decrement NBYTES
6. If (NBYTES==0) and STOP=1, transmit STOP condition.
Writing CMDR with START=STOP=1 and NBYTES=0 will generate a transmission with no data
bytes, ie START, DADR+R, STOP
The TWI transfers require the master to acknowledge each received data byte. During the
acknowledge clock pulse (9th pulse), the slave releases the data line (HIGH), enabling the master
to pull it down in order to generate the acknowledge. All data bytes except the last are
acknowledged by the master. Not acknowledging the last byte informs the slave that the transfer
is finished.
RXRDY is used as Receive Ready for the Peripheral DMA Controller receive channel.
Figure 22-8. Master Read with One Data Byte
Figure 22-9. Master Read with Multiple Data Bytes
TWD
SR.IDLE
RXRDY
Write START &
STOP bit
NBYTES set to 1
Read RHR
S DADR R A DATA N P
TWD
SR.IDLE
RXRDY
Write START +
STOP bit
NBYTES set to m
S DADR R A DATAn A DATAn+m-1 A N DATAn+m P
Read RHR
DATAn
DATAn+1
Read RHR
DATAn+m-2
Read RHR
DATAn+m-1
Read RHR
DATAn+m
Send STOP
When NBYTES=0
536
32142D–06/2013
ATUC64/128/256L3/4U
22.8.5 Using the Peripheral DMA Controller
The use of the Peripheral DMA Controller significantly reduces the CPU load. The user can set
up ring buffers for the Peripheral DMA Controller, containing data to transmit or free buffer space
to place received data.
To assure correct behavior, respect the following programming sequences:
22.8.5.1 Data Transmit with the Peripheral DMA Controller
1. Initialize the transmit Peripheral DMA Controller (memory pointers, size, etc.).
2. Configure the TWIM (ADR, NBYTES, etc.).
3. Start the transfer by enabling the Peripheral DMA Controller to transmit.
4. Wait for the Peripheral DMA Controller end-of-transmit flag.
5. Disable the Peripheral DMA Controller.
22.8.5.2 Data Receive with the Peripheral DMA Controller
1. Initialize the receive Peripheral DMA Controller (memory pointers, size, etc.).
2. Configure the TWIM (ADR, NBYTES, etc.).
3. Start the transfer by enabling the Peripheral DMA Controller to receive.
4. Wait for the Peripheral DMA Controller end-of-receive flag.
5. Disable the Peripheral DMA Controller.
22.8.6 Multi-master Mode
More than one master may access the bus at the same time without data corruption by using
arbitration.
Arbitration starts as soon as two or more masters place information on the bus at the same time,
and stops (arbitration is lost) for the master that intends to send a logical one while the other
master sends a logical zero.
As soon as arbitration is lost by a master, it stops sending data and listens to the bus in order to
detect a STOP. The SR.ARBLST flag will be set. When the STOP is detected, the master who
lost arbitration may reinitiate the data transfer.
Arbitration is illustrated in Figure 22-11.
If the user starts a transfer and if the bus is busy, the TWIM automatically waits for a STOP condition
on the bus before initiating the transfer (see Figure 22-10).
Note: The state of the bus (busy or free) is not indicated in the user interface.
537
32142D–06/2013
ATUC64/128/256L3/4U
Figure 22-10. User Sends Data While the Bus is Busy
Figure 22-11. Arbitration Cases
22.8.7 Combined Transfers
CMDR and NCMDR may be used to generate longer sequences of connected transfers, since
generation of START and/or STOP conditions is programmable on a per-command basis.
Writing NCMDR with START=1 when the previous transfer was written with STOP=0 will cause
a REPEATED START on the bus. The ability to generate such connected transfers allows arbitrary
transfer lengths, since it is legal to write CMDR with both START=0 and STOP=0. If this is
done in master receiver mode, the CMDR.ACKLAST bit must also be controlled.
TWCK
TWD DATA sent by a master
STOP sent by the master START sent by the TWI
DATA sent by the TWI
Bus is busy
Bus is free
A transfer is programmed
(DADR + W + START + Write THR) Transfer is initiated
TWI DATA transfer Transfer is kept
Bus is considered as free
TWCK
Bus is busy Bus is free
A transfer is programmed
(DADR + W + START + Write THR) Transfer is initiated
TWI DATA transfer Transfer is kept
Bus is considered as free
Data from a Master
Data from TWI S 0
S 0 0
1
1
1
ARBLST
S 0
S 0 0
1
1
1
TWD S 1 0 0
1 1
1 1
Arbitration is lost
TWI stops sending data
P
P S 1 0 0
1 1
Data from the master 1 1 Data from the TWI
Arbitration is lost
The master stops sending data
Transfer is stopped
Transfer is programmed again
(DADR + W + START + Write THR)
TWCK
TWD
538
32142D–06/2013
ATUC64/128/256L3/4U
As for single data transfers, the TXRDY and RXRDY bits in the Status Register indicates when
data to transmit can be written to THR, or when received data can be read from RHR. Transfer
of data to THR and from RHR can also be done automatically by DMA, see Section 22.8.5
22.8.7.1 Write Followed by Write
Consider the following transfer:
START, DADR+W, DATA+A, DATA+A, REPSTART, DADR+W, DATA+A, DATA+A, STOP.
To generate this transfer:
1. Write CMDR with START=1, STOP=0, DADR, NBYTES=2 and READ=0.
2. Write NCMDR with START=1, STOP=1, DADR, NBYTES=2 and READ=0.
3. Wait until SR.TXRDY==1, then write first data byte to transfer to THR.
4. Wait until SR.TXRDY==1, then write second data byte to transfer to THR.
5. Wait until SR.TXRDY==1, then write third data byte to transfer to THR.
6. Wait until SR.TXRDY==1, then write fourth data byte to transfer to THR.
22.8.7.2 Read Followed by Read
Consider the following transfer:
START, DADR+R, DATA+A, DATA+NA, REPSTART, DADR+R, DATA+A, DATA+NA, STOP.
To generate this transfer:
1. Write CMDR with START=1, STOP=0, DADR, NBYTES=2 and READ=1.
2. Write NCMDR with START=1, STOP=1, DADR, NBYTES=2 and READ=1.
3. Wait until SR.RXRDY==1, then read first data byte received from RHR.
4. Wait until SR.RXRDY==1, then read second data byte received from RHR.
5. Wait until SR.RXRDY==1, then read third data byte received from RHR.
6. Wait until SR.RXRDY==1, then read fourth data byte received from RHR.
If combining several transfers, without any STOP or REPEATED START between them, remember
to write a one to the ACKLAST bit in CMDR to keep from ending each of the partial transfers
with a NACK.
22.8.7.3 Write Followed by Read
Consider the following transfer:
START, DADR+W, DATA+A, DATA+A, REPSTART, DADR+R, DATA+A, DATA+NA, STOP.
539
32142D–06/2013
ATUC64/128/256L3/4U
Figure 22-12. Combining a Write and Read Transfer
To generate this transfer:
1. Write CMDR with START=1, STOP=0, DADR, NBYTES=2 and READ=0.
2. Write NCMDR with START=1, STOP=1, DADR, NBYTES=2 and READ=1.
3. Wait until SR.TXRDY==1, then write first data byte to transfer to THR.
4. Wait until SR.TXRDY==1, then write second data byte to transfer to THR.
5. Wait until SR.RXRDY==1, then read first data byte received from RHR.
6. Wait until SR.RXRDY==1, then read second data byte received from RHR.
22.8.7.4 Read Followed by Write
Consider the following transfer:
START, DADR+R, DATA+A, DATA+NA, REPSTART, DADR+W, DATA+A, DATA+A, STOP.
Figure 22-13. Combining a Read and Write Transfer
To generate this transfer:
1. Write CMDR with START=1, STOP=0, DADR, NBYTES=2 and READ=1.
2. Write NCMDR with START=1, STOP=1, DADR, NBYTES=2 and READ=0.
3. Wait until SR.RXRDY==1, then read first data byte received from RHR.
4. Wait until SR.RXRDY==1, then read second data byte received from RHR.
5. Wait until SR.TXRDY==1, then write first data byte to transfer to THR.
6. Wait until SR.TXRDY==1, then write second data byte to transfer to THR.
TWD
SR.IDLE
TXRDY
S DADR W A DATA0 A DATA1 NA Sr DADR R A DATA2 A DATA3 A P
THR DATA0 DATA1
RXRDY
1
RHR DATA2 DATA3
TWD
SR.IDLE
TXRDY
S SADR R A DATA0 A DATA1 Sr DADR W A DATA2 A DATA3 NA P
THR DATA2
RXRDY
RHR DATA0 DATA3
A
1
2
DATA3
Read
TWI_RHR
540
32142D–06/2013
ATUC64/128/256L3/4U
22.8.8 Ten Bit Addressing
Writing a one to CMDR.TENBIT enables 10-bit addressing in hardware. Performing transfers
with 10-bit addressing is similar to transfers with 7-bit addresses, except that bits 9:7 of
CMDR.SADR must be written appropriately.
In Figure 22-14 and Figure 22-15, the grey boxes represent signals driven by the master, the
white boxes are driven by the slave.
22.8.8.1 Master Transmitter
To perform a master transmitter transfer:
1. Write CMDR with TENBIT=1, REPSAME=0, READ=0, START=1, STOP=1 and the
desired address and NBYTES value.
Figure 22-14. A Write Transfer with 10-bit Addressing
22.8.8.2 Master Receiver
When using master receiver mode with 10-bit addressing, CMDR.REPSAME must also be controlled.
CMDR.REPSAME must be written to one when the address phase of the transfer should
consist of only 1 address byte (the 11110xx byte) and not 2 address bytes. The I²C standard
specifies that such addressing is required when addressing a slave for reads using 10-bit
addressing.
To perform a master receiver transfer:
1. Write CMDR with TENBIT=1, REPSAME=0, READ=0, START=1, STOP=0,
NBYTES=0 and the desired address.
2. Write NCMDR with TENBIT=1, REPSAME=1, READ=1, START=1, STOP=1 and the
desired address and NBYTES value.
Figure 22-15. A Read Transfer with 10-bit Addressing
22.8.9 SMBus Mode
SMBus mode is enabled and disabled by writing to the SMEN and SMDIS bits in CR. SMBus
mode operation is similar to I²C operation with the following exceptions:
• Only 7-bit addressing can be used.
• The SMBus standard describes a set of timeout values to ensure progress and throughput on
the bus. These timeout values must be written into SMBTR.
• Transmissions can optionally include a CRC byte, called Packet Error Check (PEC).
• A dedicated bus line, SMBALERT, allows a slave to get a master’s attention.
• A set of addresses have been reserved for protocol handling, such as Alert Response
Address (ARA) and Host Header (HH) Address.
S SLAVE ADDRESS
1st 7 bits RW A1 A2 DATA A P SLAVE ADDRESS
2nd byte DATA AA
11110XX0
S SLAVE ADDRESS
1st 7 bits RW A1 A2 DATA A P SLAVE ADDRESS
2nd byte DATA A
11110XX0
Sr SLAVE ADDRESS
1st 7 bits RW A3
11110XX1
541
32142D–06/2013
ATUC64/128/256L3/4U
22.8.9.1 Packet Error Checking
Each SMBus transfer can optionally end with a CRC byte, called the PEC byte. Writing a one to
CMDR.PECEN enables automatic PEC handling in the current transfer. Transfers with and without
PEC can freely be intermixed in the same system, since some slaves may not support PEC.
The PEC LFSR is always updated on every bit transmitted or received, so that PEC handling on
combined transfers will be correct.
In master transmitter mode, the master calculates a PEC value and transmits it to the slave after
all data bytes have been transmitted. Upon reception of this PEC byte, the slave will compare it
to the PEC value it has computed itself. If the values match, the data was received correctly, and
the slave will return an ACK to the master. If the PEC values differ, data was corrupted, and the
slave will return a NACK value. The DNAK bit in SR reflects the state of the last received
ACK/NACK value. Some slaves may not be able to check the received PEC in time to return a
NACK if an error occurred. In this case, the slave should always return an ACK after the PEC
byte, and some other mechanism must be implemented to verify that the transmission was
received correctly.
In master receiver mode, the slave calculates a PEC value and transmits it to the master after all
data bytes have been transmitted. Upon reception of this PEC byte, the master will compare it to
the PEC value it has computed itself. If the values match, the data was received correctly. If the
PEC values differ, data was corrupted, and SR.PECERR is set. In master receiver mode, the
PEC byte is always followed by a NACK transmitted by the master, since it is the last byte in the
transfer.
The PEC byte is automatically inserted in a master transmitter transmission if PEC is enabled
when NBYTES reaches zero. The PEC byte is identified in a master receiver transmission if
PEC is enabled when NBYTES reaches zero. NBYTES must therefore be written with the total
number of data bytes in the transmission, including the PEC byte.
In combined transfers, the PECEN bit should only be written to one in the last of the combined
transfers. Consider the following transfer:
S, ADR+W, COMMAND_BYTE, ACK, SR, ADR+R, DATA_BYTE, ACK, PEC_BYTE, NACK, P
This transfer is generated by writing two commands to the command registers. The first command
is a write with NBYTES=1 and PECEN=0, and the second is a read with NBYTES=2 and
PECEN=1.
Writing a one to the STOP bit in CR will place a STOP condition on the bus after the current
byte. No PEC byte will be sent in this case.
22.8.9.2 Timeouts
The TLOWS and TLOWM fields in SMBTR configure the SMBus timeout values. If a timeout
occurs, the master will transmit a STOP condition and leave the bus. The SR.TOUT bit is set.
22.8.9.3 SMBus ALERT Signal
A slave can get the master’s attention by pulling the TWALM line low. The TWIM will then set the
SR.SMBALERT bit. This can be set up to trigger an interrupt, and software can then take the
appropriate action, as defined in the SMBus standard.
542
32142D–06/2013
ATUC64/128/256L3/4U
22.8.10 Identifying Bus Events
This chapter lists the different bus events, and how they affect bits in the TWIM registers. This is
intended to help writing drivers for the TWIM.
Table 22-5. Bus Events
Event Effect
Master transmitter has sent
a data byte SR.THR is cleared.
Master receiver has
received a data byte SR.RHR is set.
Start+Sadr sent, no ack
received from slave
SR.ANAK is set.
SR.CCOMP not set.
CMDR.VALID remains set.
STOP automatically transmitted on bus.
Data byte sent to slave, no
ack received from slave
SR.DNAK is set.
SR.CCOMP not set.
CMDR.VALID remains set.
STOP automatically transmitted on bus.
Arbitration lost
SR.ARBLST is set.
SR.CCOMP not set.
CMDR.VALID remains set.
TWCK and TWD immediately released to a pulled-up state.
SMBus Alert received SR.SMBALERT is set.
SMBus timeout received
SR.SMBTOUT is set.
SR.CCOMP not set.
CMDR.VALID remains set.
STOP automatically transmitted on bus.
Master transmitter receives
SMBus PEC Error
SR.DNAK is set.
SR.CCOMP not set.
CMDR.VALID remains set.
STOP automatically transmitted on bus.
Master receiver discovers
SMBus PEC Error
SR.PECERR is set.
SR.CCOMP not set.
CMDR.VALID remains set.
STOP automatically transmitted on bus.
CR.STOP is written by user
SR.STOP is set.
SR.CCOMP set.
CMDR.VALID remains set.
STOP transmitted on bus after current byte transfer has finished.
543
32142D–06/2013
ATUC64/128/256L3/4U
22.9 User Interface
Note: 1. The reset values for these registers are device specific. Please refer to the Module Configuration section at the end of this
chapter.
Table 22-6. TWIM Register Memory Map
Offset Register Register Name Access Reset
0x00 Control Register CR Write-only 0x00000000
0x04 Clock Waveform Generator Register CWGR Read/Write 0x00000000
0x08 SMBus Timing Register SMBTR Read/Write 0x00000000
0x0C Command Register CMDR Read/Write 0x00000000
0x10 Next Command Register NCMDR Read/Write 0x00000000
0x14 Receive Holding Register RHR Read-only 0x00000000
0x18 Transmit Holding Register THR Write-only 0x00000000
0x1C Status Register SR Read-only 0x00000002
0x20 Interrupt Enable Register IER Write-only 0x00000000
0x24 Interrupt Disable Register IDR Write-only 0x00000000
0x28 Interrupt Mask Register IMR Read-only 0x00000000
0x2C Status Clear Register SCR Write-only 0x00000000
0x30 Parameter Register PR Read-only -(1)
0x34 Version Register VR Read-only -(1)
544
32142D–06/2013
ATUC64/128/256L3/4U
22.9.1 Control Register
Name: CR
Access Type: Write-only
Offset: 0x00
Reset Value: 0x00000000
• STOP: Stop the Current Transfer
Writing a one to this bit terminates the current transfer, sending a STOP condition after the shifter has become idle. If there are
additional pending transfers, they will have to be explicitly restarted by software after the STOP condition has been successfully
sent.
Writing a zero to this bit has no effect.
• SWRST: Software Reset
If the TWIM master interface is enabled, writing a one to this bit resets the TWIM. All transfers are halted immediately, possibly
violating the bus semantics.
If the TWIM master interface is not enabled, it must first be enabled before writing a one to this bit.
Writing a zero to this bit has no effect.
• SMDIS: SMBus Disable
Writing a one to this bit disables SMBus mode.
Writing a zero to this bit has no effect.
• SMEN: SMBus Enable
Writing a one to this bit enables SMBus mode.
Writing a zero to this bit has no effect.
• MDIS: Master Disable
Writing a one to this bit disables the master interface.
Writing a zero to this bit has no effect.
• MEN: Master Enable
Writing a one to this bit enables the master interface.
Writing a zero to this bit has no effect.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
- - - - - - - STOP
76543210
SWRST - SMDIS SMEN - - MDIS MEN
545
32142D–06/2013
ATUC64/128/256L3/4U
22.9.2 Clock Waveform Generator Register
Name: CWGR
Access Type: Read/Write
Offset: 0x04
Reset Value: 0x00000000
• EXP: Clock Prescaler
Used to specify how to prescale the TWCK clock. Counters are prescaled according to the following formula
• DATA: Data Setup and Hold Cycles
Clock cycles for data setup and hold count. Prescaled by CWGR.EXP. Used to time THD_DAT, TSU_DAT.
• STASTO: START and STOP Cycles
Clock cycles in clock high count. Prescaled by CWGR.EXP. Used to time THD_STA, TSU_STA, TSU_STO
• HIGH: Clock High Cycles
Clock cycles in clock high count. Prescaled by CWGR.EXP. Used to time THIGH.
• LOW: Clock Low Cycles
Clock cycles in clock low count. Prescaled by CWGR.EXP. Used to time TLOW, TBUF.
31 30 29 28 27 26 25 24
- EXP DATA
23 22 21 20 19 18 17 16
STASTO
15 14 13 12 11 10 9 8
HIGH
76543210
LOW
f
PRESCALER
f
CLK_TWIM
2 EXP 1 + = -------------------------
546
32142D–06/2013
ATUC64/128/256L3/4U
22.9.3 SMBus Timing Register
Name: SMBTR
Access Type: Read/Write
Offset: 0x08
Reset Value: 0x00000000
• EXP: SMBus Timeout Clock Prescaler
Used to specify how to prescale the TIM and TLOWM counters in SMBTR. Counters are prescaled according to the following
formula
• THMAX: Clock High Maximum Cycles
Clock cycles in clock high maximum count. Prescaled by SMBTR.EXP. Used for bus free detection. Used to time THIGH:MAX.
NOTE: Uses the prescaler specified by CWGR, NOT the prescaler specified by SMBTR.
• TLOWM: Master Clock Stretch Maximum Cycles
Clock cycles in master maximum clock stretch count. Prescaled by SMBTR.EXP. Used to time TLOW:MEXT
• TLOWS: Slave Clock Stretch Maximum Cycles
Clock cycles in slave maximum clock stretch count. Prescaled by SMBTR.EXP. Used to time TLOW:SEXT.
31 30 29 28 27 26 25 24
EXP - - - -
23 22 21 20 19 18 17 16
THMAX
15 14 13 12 11 10 9 8
TLOWM
76543210
TLOWS
f
prescaled SMBus
f
CLKTWIM
2 EXP + 1 = ------------------------
547
32142D–06/2013
ATUC64/128/256L3/4U
22.9.4 Command Register
Name: CMDR
Access Type: Read/Write
Offset: 0x0C
Reset Value: 0x00000000
• ACKLAST: ACK Last Master RX Byte
0: Causes the last byte in master receive mode (when NBYTES has reached 0) to be NACKed. This is the standard way of
ending a master receiver transfer.
1: Causes the last byte in master receive mode (when NBYTES has reached 0) to be ACKed. Used for performing linked
transfers in master receiver mode with no STOP or REPEATED START between the subtransfers. This is needed when more
than 255 bytes are to be received in one single transmission.
• PECEN: Packet Error Checking Enable
0: Causes the transfer not to use PEC byte verification. The PEC LFSR is still updated for every bit transmitted or received. Must
be used if SMBus mode is disabled.
1: Causes the transfer to use PEC. PEC byte generation (if master transmitter) or PEC byte verification (if master receiver) will
be performed.
• NBYTES: Number of Data Bytes in Transfer
The number of data bytes in the transfer. After the specified number of bytes have been transferred, a STOP condition is
transmitted if CMDR.STOP is one. In SMBus mode, if PEC is used, NBYTES includes the PEC byte, i.e. there are NBYTES-1
data bytes and a PEC byte.
• VALID: CMDR Valid
0: Indicates that CMDR does not contain a valid command.
1: Indicates that CMDR contains a valid command. This bit is cleared when the command is finished.
• STOP: Send STOP Condition
0: Do not transmit a STOP condition after the data bytes have been transmitted.
1: Transmit a STOP condition after the data bytes have been transmitted.
• START: Send START Condition
0: The transfer in CMDR should not commence with a START or REPEATED START condition.
1: The transfer in CMDR should commence with a START or REPEATED START condition. If the bus is free when the command
is executed, a START condition is used. If the bus is busy, a REPEATED START is used.
• REPSAME: Transfer is to Same Address as Previous Address
Only used in 10-bit addressing mode, always write to 0 in 7-bit addressing mode.
31 30 29 28 27 26 25 24
- - - - ACKLAST PECEN
23 22 21 20 19 18 17 16
NBYTES
15 14 13 12 11 10 9 8
VALID STOP START REPSAME TENBIT SADR[9:7]
76543210
SADR[6:0] READ
548
32142D–06/2013
ATUC64/128/256L3/4U
Write this bit to one if the command in CMDR performs a repeated start to the same slave address as addressed in the previous
transfer in order to enter master receiver mode.
Write this bit to zero otherwise.
• TENBIT: Ten Bit Addressing Mode
0: Use 7-bit addressing mode.
1: Use 10-bit addressing mode. Must not be used when the TWIM is in SMBus mode.
• SADR: Slave Address
Address of the slave involved in the transfer. Bits 9-7 are don’t care if 7-bit addressing is used.
• READ: Transfer Direction
0: Allow the master to transmit data.
1: Allow the master to receive data.
549
32142D–06/2013
ATUC64/128/256L3/4U
22.9.5 Next Command Register
Name: NCMDR
Access Type: Read/Write
Offset: 0x10
Reset Value: 0x00000000
This register is identical to CMDR. When the VALID bit in CMDR becomes 0, the content of NCMDR is copied into CMDR,
clearing the VALID bit in NCMDR. If the VALID bit in CMDR is cleared when NCMDR is written, the content is copied
immediately.
31 30 29 28 27 26 25 24
- - - - ACKLAST PECEN
23 22 21 20 19 18 17 16
NBYTES
15 14 13 12 11 10 9 8
VALID STOP START REPSAME TENBIT SADR[9:7]
76543210
SADR[6:0] READ
550
32142D–06/2013
ATUC64/128/256L3/4U
22.9.6 Receive Holding Register
Name: RHR
Access Type: Read-only
Offset: 0x14
Reset Value: 0x00000000
• RXDATA: Received Data
When the RXRDY bit in the Status Register (SR) is one, this field contains a byte received from the TWI bus.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
RXDATA
551
32142D–06/2013
ATUC64/128/256L3/4U
22.9.7 Transmit Holding Register
Name: THR
Access Type: Write-only
Offset: 0x18
Reset Value: 0x00000000
• TXDATA: Data to Transmit
Write data to be transferred on the TWI bus here.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
TXDATA
552
32142D–06/2013
ATUC64/128/256L3/4U
22.9.8 Status Register
Name: SR
Access Type: Read-only
Offset: 0x1C
Reset Value: 0x00000002
• MENB: Master Interface Enable
0: Master interface is disabled.
1: Master interface is enabled.
• STOP: Stop Request Accepted
This bit is one when a STOP request caused by writing a one to CR.STOP has been accepted, and transfer has stopped.
This bit is cleared by writing 1 to the corresponding bit in the Status Clear Register (SCR).
• PECERR: PEC Error
This bit is one when a SMBus PEC error occurred.
This bit is cleared by writing 1 to the corresponding bit in the Status Clear Register (SCR).
• TOUT: Timeout
This bit is one when a SMBus timeout occurred.
This bit is cleared by writing 1 to the corresponding bit in the Status Clear Register (SCR).
• SMBALERT: SMBus Alert
This bit is one when an SMBus Alert was received.
This bit is cleared by writing 1 to the corresponding bit in the Status Clear Register (SCR).
• ARBLST: Arbitration Lost
This bit is one when the actual state of the SDA line did not correspond to the data driven onto it, indicating a higher-priority
transmission in progress by a different master.
This bit is cleared by writing 1 to the corresponding bit in the Status Clear Register (SCR).
• DNAK: NAK in Data Phase Received
This bit is one when no ACK was received form slave during data transmission.
This bit is cleared by writing 1 to the corresponding bit in the Status Clear Register (SCR).
• ANAK: NAK in Address Phase Received
This bit is one when no ACK was received from slave during address phase
This bit is cleared by writing 1 to the corresponding bit in the Status Clear Register (SCR).
• BUSFREE: Two-wire Bus is Free
This bit is one when activity has completed on the two-wire bus.
Otherwise, this bit is cleared.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
- - - - - - - MENB
15 14 13 12 11 10 9 8
- STOP PECERR TOUT SMBALERT ARBLST DNAK ANAK
76543210
- - BUSFREE IDLE CCOMP CRDY TXRDY RXRDY
553
32142D–06/2013
ATUC64/128/256L3/4U
• IDLE: Master Interface is Idle
This bit is one when no command is in progress, and no command waiting to be issued.
Otherwise, this bit is cleared.
• CCOMP: Command Complete
This bit is one when the current command has completed successfully.
This bit is zero if the command failed due to conditions such as a NAK receved from slave.
This bit is cleared by writing 1 to the corresponding bit in the Status Clear Register (SCR).
• CRDY: Ready for More Commands
This bit is one when CMDR and/or NCMDR is ready to receive one or more commands.
This bit is cleared when this is no longer true.
• TXRDY: THR Data Ready
This bit is one when THR is ready for one or more data bytes.
This bit is cleared when this is no longer true (i.e. THR is full or transmission has stopped).
• RXRDY: RHR Data Ready
This bit is one when RX data are ready to be read from RHR.
This bit is cleared when this is no longer true.
554
32142D–06/2013
ATUC64/128/256L3/4U
22.9.9 Interrupt Enable Register
Name: IER
Access Type: Write-only
Offset: 0x20
Reset Value: 0x00000000
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will set the corresponding bit in IMR
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
- STOP PECERR TOUT SMBALERT ARBLST DNAK ANAK
76543210
- - BUSFREE IDLE CCOMP CRDY TXRDY RXRDY
555
32142D–06/2013
ATUC64/128/256L3/4U
22.9.10 Interrupt Disable Register
Name: IDR
Access Type: Write-only
Offset: 0x24
Reset Value: 0x00000000
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will clear the corresponding bit in IMR
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
- STOP PECERR TOUT SMBALERT ARBLST DNAK ANAK
76543210
- - BUSFREE IDLE CCOMP CRDY TXRDY RXRDY
556
32142D–06/2013
ATUC64/128/256L3/4U
22.9.11 Interrupt Mask Register
Name: IMR
Access Type: Read-only
Offset: 0x28
Reset Value: 0x00000000
0: The corresponding interrupt is disabled.
1: The corresponding interrupt is enabled.
This bit is cleared when the corresponding bit in IDR is written to one.
This bit is set when the corresponding bit in IER is written to one.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
- STOP PECERR TOUT SMBALERT ARBLST DNAK ANAK
76543210
- - BUSFREE IDLE CCOMP CRDY TXRDY RXRDY
557
32142D–06/2013
ATUC64/128/256L3/4U
22.9.12 Status Clear Register
Name: SCR
Access Type : Write-only
Offset: 0x2C
Reset Value: 0x00000000
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will clear the corresponding bit in SR and the corresponding interrupt request.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
- STOP PECERR TOUT SMBALERT ARBLST DNAK ANAK
76543210
- - - - CCOMP - - -
558
32142D–06/2013
ATUC64/128/256L3/4U
22.9.13 Parameter Register (PR)
Name: PR
Access Type: Read-only
Offset: 0x30
Reset Value: -
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
--------
559
32142D–06/2013
ATUC64/128/256L3/4U
22.9.14 Version Register (VR)
Name: VR
Access Type: Read-only
Offset: 0x34
Reset Value: -
• VARIANT: Variant Number
Reserved. No functionality associated.
• VERSION: Version Number
Version number of the module. No functionality associated.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
- - - - VARIANT
15 14 13 12 11 10 9 8
- - - - VERSION [11:8]
76543210
VERSION [7:0]
560
32142D–06/2013
ATUC64/128/256L3/4U
22.10 Module Configuration
The specific configuration for each TWIM instance is listed in the following tables.The module
bus clocks listed here are connected to the system bus clocks. Please refer to the Power Manager
chapter for details.
Table 22-7. Module Clock Name
Module Name Clock Name Description
TWIM0 CLK_TWIM0 Clock for the TWIM0 bus interface
TWIM1 CLK_TWIM1 Clock for the TWIM1 bus interface
Table 22-8. Register Reset Values
Register Reset Value
VERSION 0x00000110
PARAMETER 0x00000000
561
32142D–06/2013
ATUC64/128/256L3/4U
23. Two-wire Slave Interface (TWIS)
Rev.: 1.2.0.1
23.1 Features
• Compatible with I²C standard
– Transfer speeds of 100 and 400 kbit/s
– 7 and 10-bit and General Call addressing
• Compatible with SMBus standard
– Hardware Packet Error Checking (CRC) generation and verification with ACK response
– SMBALERT interface
– 25 ms clock low timeout delay
– 25 ms slave cumulative clock low extend time
• Compatible with PMBus
• DMA interface for reducing CPU load
• Arbitrary transfer lengths, including 0 data bytes
• Optional clock stretching if transmit or receive buffers not ready for data transfer
• 32-bit Peripheral Bus interface for configuration of the interface
23.2 Overview
The Atmel Two-wire Slave Interface (TWIS) interconnects components on a unique two-wire
bus, made up of one clock line and one data line with speeds of up to 400 kbit/s, based on a
byte-oriented transfer format. It can be used with any Atmel Two-wire Interface bus, I²C, or
SMBus-compatible master. The TWIS is always a bus slave and can transfer sequential or single
bytes.
Below, Table 23-1 lists the compatibility level of the Atmel Two-wire Slave Interface and a full I²C
compatible device.
Note: 1. START + b000000001 + Ack + Sr
Table 23-1. Atmel TWIS Compatibility with I²C Standard
I²C Standard Atmel TWIS
Standard-mode (100 kbit/s) Supported
Fast-mode (400 kbit/s) Supported
7 or 10 bits Slave Addressing Supported
START BYTE(1) Not Supported
Repeated Start (Sr) Condition Supported
ACK and NAK Management Supported
Slope control and input filtering (Fast mode) Supported
Clock stretching Supported
562
32142D–06/2013
ATUC64/128/256L3/4U
Below, Table 23-2 lists the compatibility level of the Atmel Two-wire Slave Interface and a full
SMBus compatible device.
23.3 List of Abbreviations
23.4 Block Diagram
Figure 23-1. Block Diagram
Table 23-2. Atmel TWIS Compatibility with SMBus Standard
SMBus Standard Atmel TWIS
Bus Timeouts Supported
Address Resolution Protocol Supported
Alert Supported
Packet Error Checking Supported
Table 23-3. Abbreviations
Abbreviation Description
TWI Two-wire Interface
A Acknowledge
NA Non Acknowledge
P Stop
S Start
Sr Repeated Start
SADR Slave Address
ADR Any address except SADR
R Read
W Write
Peripheral
Bus Bridge
Two-wire
Interface
I/O Controller
TWCK
TWD
Interrupt
Controller
TWI Interrupt
Power
Manager
CLK_TWIS
TWALM
563
32142D–06/2013
ATUC64/128/256L3/4U
23.5 Application Block Diagram
Figure 23-2. Application Block Diagram
23.6 I/O Lines Description
23.7 Product Dependencies
In order to use this module, other parts of the system must be configured correctly, as described
below.
23.7.1 I/O Lines
TWDand TWCK are bidirectional lines, connected to a positive supply voltage via a current
source or pull-up resistor (see Figure 23-5 on page 565). When the bus is free, both lines are
high. The output stages of devices connected to the bus must have an open-drain or open-collector
to perform the wired-AND function.
TWALM is used to implement the optional SMBus SMBALERT signal.
TWALM, TWD, and TWCK pins may be multiplexed with I/O Controller lines. To enable the
TWIS, the user must perform the following steps:
• Program the I/O Controller to:
– Dedicate TWD, TWCK, and optionally TWALM as peripheral lines.
– Define TWD, TWCK, and optionally TWALM as open-drain.
Host with
TWI
Interface
TWD
TWCK
Atmel TWI
serial EEPROM I²C RTC I²C LCD
controller
Slave 1 Slave 2 Slave 3
VDD
I²C temp.
sensor
Slave 4
Rp: Pull up value as given by the I²C Standard
Rp Rp
Table 23-4. I/O Lines Description
Pin Name Pin Description Type
TWD Two-wire Serial Data Input/Output
TWCK Two-wire Serial Clock Input/Output
TWALM SMBus SMBALERT Input/Output
564
32142D–06/2013
ATUC64/128/256L3/4U
23.7.2 Power Management
If the CPU enters a sleep mode that disables clocks used by the TWIS, the TWIS will stop functioning
and resume operation after the system wakes up from sleep mode. The TWIS is able to
wake the system from sleep mode upon address match, see Section 23.8.8 on page 572.
23.7.3 Clocks
The clock for the TWIS bus interface (CLK_TWIS) is generated by the Power Manager. This
clock is enabled at reset, and can be disabled in the Power Manager. It is recommended to disable
the TWIS before disabling the clock, to avoid freezing the TWIS in an undefined state.
23.7.4 DMA
The TWIS DMA handshake interface is connected to the Peripheral DMA Controller. Using the
TWIS DMA functionality requires the Peripheral DMA Controller to be programmed after setting
up the TWIS.
23.7.5 Interrupts
The TWIS interrupt request lines are connected to the interrupt controller. Using the TWIS interrupts
requires the interrupt controller to be programmed first.
23.7.6 Debug Operation
When an external debugger forces the CPU into debug mode, the TWIS continues normal operation.
If the TWIS is configured in a way that requires it to be periodically serviced by the CPU
through interrupts or similar, improper operation or data loss may result during debugging.
23.8 Functional Description
23.8.1 Transfer Format
The data put on the TWD line must be 8 bits long. Data is transferred MSB first; each byte must
be followed by an acknowledgement. The number of bytes per transfer is unlimited (see Figure
23-4 on page 565).
Each transfer begins with a START condition and terminates with a STOP condition (see Figure
23-3).
• A high-to-low transition on the TWD line while TWCK is high defines the START condition.
• A low-to-high transition on the TWD line while TWCK is high defines a STOP condition.
Figure 23-3. START and STOP Conditions
TWD
TWCK
Start Stop
565
32142D–06/2013
ATUC64/128/256L3/4U
Figure 23-4. Transfer Format
23.8.2 Operation
The TWIS has two modes of operation:
• Slave transmitter mode
• Slave receiver mode
A master is a device which starts and stops a transfer and generates the TWCK clock. A slave is
assigned an address and responds to requests from the master. These modes are described in
the following chapters.
Figure 23-5. Typical Application Block Diagram
23.8.2.1 Bus Timing
The Timing Register (TR) is used to control the timing of bus signals driven by the TWIS. TR
describes bus timings as a function of cycles of the prescaled CLK_TWIS. The clock prescaling
can be selected through TR.EXP.
TR has the following fields:
TLOWS: Prescaled clock cycles used to time SMBUS timeout TLOW:SEXT.
TWD
TWCK
Start Address R/W Ack Data Ack Data Ack Stop
Host with
TWI
Interface
TWD
TWCK
Atmel TWI
Serial EEPROM I²C RTC I²C LCD
Controller
Slave 1 Slave 2 Slave 3
VDD
I²C Temp.
Sensor
Slave 4
Rp: Pull up value as given by the I²C Standard
Rp Rp
fPRESCALED
f
CLK_TWIS
2 EXP 1 + = ------------------------
566
32142D–06/2013
ATUC64/128/256L3/4U
TTOUT: Prescaled clock cycles used to time SMBUS timeout TTIMEOUT.
SUDAT: Non-prescaled clock cycles for data setup and hold count. Used to time TSU_DAT.
EXP: Specifies the clock prescaler setting used for the SMBUS timeouts.
Figure 23-6. Bus Timing Diagram
23.8.2.2 Setting Up and Performing a Transfer
Operation of the TWIS is mainly controlled by the Control Register (CR). The following list presents
the main steps in a typical communication:
3. Before any transfers can be performed, bus timings must be configured by writing to the
Timing Register (TR).If the Peripheral DMA Controller is to be used for the transfers, it
must be set up.
4. The Control Register (CR) must be configured with information such as the slave
address, SMBus mode, Packet Error Checking (PEC), number of bytes to transfer, and
which addresses to match.
The interrupt system can be set up to generate interrupt request on specific events or error conditions,
for example when a byte has been received.
The NBYTES register is only used in SMBus mode, when PEC is enabled. In I²C mode or in
SMBus mode when PEC is disabled, the NBYTES register is not used, and should be written to
zero. NBYTES is updated by hardware, so in order to avoid hazards, software updates of
NBYTES can only be done through writes to the NBYTES register.
23.8.2.3 Address Matching
The TWIS can be set up to match several different addresses. More than one address match
may be enabled simultaneously, allowing the TWIS to be assigned to several addresses. The
address matching phase is initiated after a START or REPEATED START condition. When the
TWIS receives an address that generates an address match, an ACK is automatically returned
to the master.
S t
HD:STA
t LOW
t
SU:DAT
t HIGH
t
HD:DAT
t LOW
P
t
SU:STO
Sr
t
SU:STA
t
SU:DAT
567
32142D–06/2013
ATUC64/128/256L3/4U
In I²C mode:
• The address in CR.ADR is checked for address match if CR.SMATCH is one.
• The General Call address is checked for address match if CR.GCMATCH is one.
In SMBus mode:
• The address in CR.ADR is checked for address match if CR.SMATCH is one.
• The Alert Response Address is checked for address match if CR.SMAL is one.
• The Default Address is checked for address match if CR.SMDA is one.
• The Host Header Address is checked for address match if CR.SMHH is one.
23.8.2.4 Clock Stretching
Any slave or bus master taking part in a transfer may extend the TWCK low period at any time.
The TWIS may extend the TWCK low period after each byte transfer if CR.STREN is one and:
• Module is in slave transmitter mode, data should be transmitted, but THR is empty, or
• Module is in slave receiver mode, a byte has been received and placed into the internal
shifter, but the Receive Holding Register (RHR) is full, or
• Stretch-on-address-match bit CR.SOAM=1 and slave was addressed. Bus clock remains
stretched until all address match bits in the Status Register (SR) have been cleared.
If CR.STREN is zero and:
• Module is in slave transmitter mode, data should be transmitted but THR is empty: Transmit
the value present in THR (the last transmitted byte or reset value), and set SR.URUN.
• Module is in slave receiver mode, a byte has been received and placed into the internal
shifter, but RHR is full: Discard the received byte and set SR.ORUN.
23.8.2.5 Bus Errors
If a bus error (misplaced START or STOP) condition is detected, the SR.BUSERR bit is set and
the TWIS waits for a new START condition.
23.8.3 Slave Transmitter Mode
If the TWIS matches an address in which the R/W bit in the TWI address phase transfer is set, it
will enter slave transmitter mode and set the SR.TRA bit (note that SR.TRA is set one
CLK_TWIS cycle after the relevant address match bit in the same register is set).
After the address phase, the following actions are performed:
1. If SMBus mode and PEC is used, NBYTES must be set up with the number of bytes to
transmit. This is necessary in order to know when to transmit the PEC byte. NBYTES
can also be used to count the number of bytes received if using DMA.
2. Byte to transmit depends on I²C/SMBus mode and CR.PEC:
– If in I²C mode or CR.PEC is zero or NBYTES is non-zero: The TWIS waits until THR
contains a valid data byte, possibly stretching the low period of TWCK. After THR
contains a valid data byte, the data byte is transferred to a shifter, and then
SR.TXRDY is changed to one because the THR is empty again.
– SMBus mode and CR.PEC is one: If NBYTES is zero, the generated PEC byte is
automatically transmitted instead of a data byte from THR. TWCK will not be
stretched by the TWIS.
3. The data byte in the shifter is transmitted.
568
32142D–06/2013
ATUC64/128/256L3/4U
4. NBYTES is updated. If CR.CUP is one, NBYTES is incremented, otherwise NBYTES is
decremented.
5. After each data byte has been transmitted, the master transmits an ACK (Acknowledge)
or NAK (Not Acknowledge) bit. If a NAK bit is received by the TWIS, the SR.NAK bit is
set. Note that this is done two CLK_TWIS cycles after TWCK has been sampled by the
TWIS to be HIGH (see Figure 23-9). The NAK indicates that the transfer is finished, and
the TWIS will wait for a STOP or REPEATED START. If an ACK bit is received, the
SR.NAK bit remains LOW. The ACK indicates that more data should be transmitted,
jump to step 2. At the end of the ACK/NAK clock cycle, the Byte Transfer Finished
(SR.BTF) bit is set. Note that this is done two CLK_TWIS cycles after TWCK has been
sampled by the TWIS to be LOW (see Figure 23-9). Also note that in the event that
SR.NAK bit is set, it must not be cleared before the SR.BTF bit is set to ensure correct
TWIS behavior.
6. If STOP is received, SR.TCOMP and SR.STO will be set.
7. If REPEATED START is received, SR.REP will be set.
The TWI transfers require the receiver to acknowledge each received data byte. During the
acknowledge clock pulse (9th pulse), the slave releases the data line (HIGH), enabling the master
to pull it down in order to generate the acknowledge. The slave polls the data line during this
clock pulse and sets the NAK bit in SR if the master does not acknowledge the data byte. A NAK
means that the master does not wish to receive additional data bytes. As with the other status
bits, an interrupt can be generated if enabled in the Interrupt Enable Register (IER).
SR.TXRDY is used as Transmit Ready for the Peripheral DMA Controller transmit channel.
The end of the complete transfer is marked by the SR.TCOMP bit changing from zero to one.
See Figure 23-7 and Figure 23-8.
Figure 23-7. Slave Transmitter with One Data Byte
TCOMP
TXRDY
Write THR (DATA) STOP sent by master
TWD S DADR R P A DATA N
NBYTES set to 1
569
32142D–06/2013
ATUC64/128/256L3/4U
Figure 23-8. Slave Transmitter with Multiple Data Bytes
Figure 23-9. Timing Relationship between TWCK, SR.NAK, and SR.BTF
23.8.4 Slave Receiver Mode
If the TWIS matches an address in which the R/W bit in the TWI address phase transfer is
cleared, it will enter slave receiver mode and clear SR.TRA (note that SR.TRA is cleared one
CLK_TWIS cycle after the relevant address match bit in the same register is set).
After the address phase, the following is repeated:
1. If SMBus mode and PEC is used, NBYTES must be set up with the number of bytes to
receive. This is necessary in order to know which of the received bytes is the PEC byte.
NBYTES can also be used to count the number of bytes received if using DMA.
2. Receive a byte. Set SR.BTF when done.
3. Update NBYTES. If CR.CUP is written to one, NBYTES is incremented, otherwise
NBYTES is decremented. NBYTES is usually configured to count downwards if PEC is
used.
4. After a data byte has been received, the slave transmits an ACK or NAK bit. For ordinary
data bytes, the CR.ACK field controls if an ACK or NAK should be returned. If PEC
is enabled and the last byte received was a PEC byte (indicated by NBYTES equal to
zero), The TWIS will automatically return an ACK if the PEC value was correct, otherwise
a NAK will be returned.
5. If STOP is received, SR.TCOMP will be set.
6. If REPEATED START is received, SR.REP will be set.
The TWI transfers require the receiver to acknowledge each received data byte. During the
acknowledge clock pulse (9th pulse), the master releases the data line (HIGH), enabling the
S DADR R DATA n+5 A P A DATA n A DATA n+m N
TCOMP
TXRDY
Write THR (Data n)
NBYTES set to m
STOP sent by master
TWD
Write THR (Data n+1) Write THR (Data n+m)
Last data sent
DATA (LSB) N P
TWCK
SR.NAK
SR.BTF
t1 t1
t1: (CLK_TWIS period) x 2
TWD
570
32142D–06/2013
ATUC64/128/256L3/4U
slave to pull it down in order to generate the acknowledge. The master polls the data line during
this clock pulse.
The SR.RXRDY bit indicates that a data byte is available in the RHR. The RXRDY bit is also
used as Receive Ready for the Peripheral DMA Controller receive channel.
Figure 23-10. Slave Receiver with One Data Byte
Figure 23-11. Slave Receiver with Multiple Data Bytes
23.8.5 Interactive ACKing Received Data Bytes
When implementing a register interface over TWI, it may sometimes be necessary or just useful
to report reads and writes to invalid register addresses by sending a NAK to the host. To be able
to do this, one must first receive the register address from the TWI bus, and then tell the TWIS
whether to ACK or NAK it. In normal operation of the TWIS, this is not possible because the controller
will automatically ACK the byte at about the same time as the RXRDY bit changes from
zero to one. Writing a one to the Stretch on Data Byte Received bit (CR.SODR) will stretch the
clock allowing the user to update CR.ACK bit before returning the desired value. After the last bit
in the data byte is received, the TWI bus clock is stretched, the received data byte is transferred
to the RHR register, and SR.BTF is set. At this time, the user can examine the received byte and
write the desired ACK or NACK value to CR.ACK. When the user clears SR.BTF, the desired
ACK value is transferred on the TWI bus. This makes it possible to look at the byte received,
determine if it is valid, and then decide to ACK or NAK it.
23.8.6 Using the Peripheral DMA Controller
The use of the Peripheral DMA Controller significantly reduces the CPU load. The user can set
up ring buffers for the Peripheral DMA Controller, containing data to transmit or free buffer space
to place received data. By initializing NBYTES to zero before a transfer, and writing a one to
CR.CUP, NBYTES is incremented by one each time a data has been transmitted or received.
This allows the user to detect how much data was actually transferred by the DMA system.
S DADR W DATA A P A
TCOMP
RXRDY
Read RHR
TWD
TWD S DADR W DATA n A A A DATA (n+1) A DATA (n+m) DATA (n+m)-1 P A
TCOMP
RXRDY
Read RHR
DATA n
Read RHR
DATA (n+1)
Read RHR
DATA (n+m)-1
Read RHR
DATA (n+m)
571
32142D–06/2013
ATUC64/128/256L3/4U
To assure correct behavior, respect the following programming sequences:
23.8.6.1 Data Transmit with the Peripheral DMA Controller
1. Initialize the transmit Peripheral DMA Controller (memory pointers, size, etc.).
2. Configure the TWIS (ADR, NBYTES, etc.).
3. Start the transfer by enabling the Peripheral DMA Controller to transmit.
4. Wait for the Peripheral DMA Controller end-of-transmit flag.
5. Disable the Peripheral DMA Controller.
23.8.6.2 Data Receive with the Peripheral DMA Controller
1. Initialize the receive Peripheral DMA Controller (memory pointers, size - 1, etc.).
2. Configure the TWIS (ADR, NBYTES, etc.).
3. Start the transfer by enabling the Peripheral DMA Controller to receive.
4. Wait for the Peripheral DMA Controller end-of-receive flag.
5. Disable the Peripheral DMA Controller.
23.8.7 SMBus Mode
SMBus mode is enabled by writing a one to the SMBus Mode Enable (SMEN) bit in CR. SMBus
mode operation is similar to I²C operation with the following exceptions:
• Only 7-bit addressing can be used.
• The SMBus standard describes a set of timeout values to ensure progress and throughput on
the bus. These timeout values must be written to TR.
• Transmissions can optionally include a CRC byte, called Packet Error Check (PEC).
• A dedicated bus line, SMBALERT, allows a slave to get a master’s attention.
• A set of addresses have been reserved for protocol handling, such as Alert Response
Address (ARA) and Host Header (HH) Address. Address matching on these addresses can
be enabled by configuring CR appropriately.
23.8.7.1 Packet Error Checking (PEC)
Each SMBus transfer can optionally end with a CRC byte, called the PEC byte. Writing a one to
the Packet Error Checking Enable (PECEN) bit in CR enables automatic PEC handling in the
current transfer. The PEC generator is always updated on every bit transmitted or received, so
that PEC handling on following linked transfers will be correct.
In slave receiver mode, the master calculates a PEC value and transmits it to the slave after all
data bytes have been transmitted. Upon reception of this PEC byte, the slave will compare it to
the PEC value it has computed itself. If the values match, the data was received correctly, and
the slave will return an ACK to the master. If the PEC values differ, data was corrupted, and the
slave will return a NAK value. The SR.SMBPECERR bit is set automatically if a PEC error
occurred.
In slave transmitter mode, the slave calculates a PEC value and transmits it to the master after
all data bytes have been transmitted. Upon reception of this PEC byte, the master will compare
it to the PEC value it has computed itself. If the values match, the data was received correctly. If
the PEC values differ, data was corrupted, and the master must take appropriate action.
The PEC byte is automatically inserted in a slave transmitter transmission if PEC enabled when
NBYTES reaches zero. The PEC byte is identified in a slave receiver transmission if PEC
572
32142D–06/2013
ATUC64/128/256L3/4U
enabled when NBYTES reaches zero. NBYTES must therefore be set to the total number of
data bytes in the transmission, including the PEC byte.
23.8.7.2 Timeouts
The Timing Register (TR) configures the SMBus timeout values. If a timeout occurs, the slave
will leave the bus. The SR.SMBTOUT bit is also set.
23.8.7.3 SMBALERT
A slave can get the master’s attention by pulling the SMBALERT line low. This is done by writing
a one to the SMBus Alert (SMBALERT) bit in CR. This will also enable address match on the
Alert Response Address (ARA).
23.8.8 Wakeup from Sleep Modes by TWI Address Match
The TWIS is able to wake the device up from a sleep mode upon an address match, including
sleep modes where CLK_TWIS is stopped. After detecting the START condition on the bus, The
TWIS will stretch TWCK until CLK_TWIS has started. The time required for starting CLK_TWIS
depends on which sleep mode the device is in. After CLK_TWIS has started, the TWIS releases
its TWCK stretching and receives one byte of data on the bus. At this time, only a limited part of
the device, including the TWIS, receives a clock, thus saving power. The TWIS goes on to
receive the slave address. If the address phase causes a TWIS address match, the entire
device is wakened and normal TWIS address matching actions are performed. Normal TWI
transfer then follows. If the TWIS is not addressed, CLK_TWIS is automatically stopped and the
device returns to its original sleep mode.
23.8.9 Identifying Bus Events
This chapter lists the different bus events, and how these affects the bits in the TWIS registers.
This is intended to help writing drivers for the TWIS.
Table 23-5. Bus Events
Event Effect
Slave transmitter has sent a
data byte
SR.THR is cleared.
SR.BTF is set.
The value of the ACK bit sent immediately after the data byte is given
by CR.ACK.
Slave receiver has received
a data byte
SR.RHR is set.
SR.BTF is set.
SR.NAK updated according to value of ACK bit received from master.
Start+Sadr on bus, but
address is to another slave None.
Start+Sadr on bus, current
slave is addressed, but
address match enable bit in
CR is not set
None.
Start+Sadr on bus, current
slave is addressed,
corresponding address
match enable bit in CR set
Correct address match bit in SR is set.
SR.TRA updated according to transfer direction (updating is done one
CLK_TWIS cycle after address match bit is set)
Slave enters appropriate transfer direction mode and data transfer
can commence.
573
32142D–06/2013
ATUC64/128/256L3/4U
Start+Sadr on bus, current
slave is addressed,
corresponding address
match enable bit in CR set,
SR.STREN and SR.SOAM
are set.
Correct address match bit in SR is set.
SR.TRA updated according to transfer direction (updating is done one
CLK_TWIS cycle after address match bit is set).
Slave stretches TWCK immediately after transmitting the address
ACK bit. TWCK remains stretched until all address match bits in SR
have been cleared.
Slave enters appropriate transfer direction mode and data transfer
can commence.
Repeated Start received
after being addressed
SR.REP set.
SR.TCOMP unchanged.
Stop received after being
addressed
SR.STO set.
SR.TCOMP set.
Start, Repeated Start, or
Stop received in illegal
position on bus
SR.BUSERR set.
SR.STO and SR.TCOMP may or may not be set depending on the
exact position of an illegal stop.
Data is to be received in
slave receiver mode,
SR.STREN is set, and RHR
is full
TWCK is stretched until RHR has been read.
Data is to be transmitted in
slave receiver mode,
SR.STREN is set, and THR
is empty
TWCK is stretched until THR has been written.
Data is to be received in
slave receiver mode,
SR.STREN is cleared, and
RHR is full
TWCK is not stretched, read data is discarded.
SR.ORUN is set.
Data is to be transmitted in
slave receiver mode,
SR.STREN is cleared, and
THR is empty
TWCK is not stretched, previous contents of THR is written to bus.
SR.URUN is set.
SMBus timeout received SR.SMBTOUT is set.
TWCK and TWD are immediately released.
Slave transmitter in SMBus
PEC mode has transmitted
a PEC byte, that was not
identical to the PEC
calculated by the master
receiver.
Master receiver will transmit a NAK as usual after the last byte of a
master receiver transfer.
Master receiver will retry the transfer at a later time.
Slave receiver discovers
SMBus PEC Error
SR.SMBPECERR is set.
NAK returned after the data byte.
Table 23-5. Bus Events
Event Effect
574
32142D–06/2013
ATUC64/128/256L3/4U
23.9 User Interface
Note: 1. The reset values for these registers are device specific. Please refer to the Module Configuration section at the end of this
chapter.
Table 23-6. TWIS Register Memory Map
Offset Register Register Name Access Reset
0x00 Control Register CR Read/Write 0x00000000
0x04 NBYTES Register NBYTES Read/Write 0x00000000
0x08 Timing Register TR Read/Write 0x00000000
0x0C Receive Holding Register RHR Read-only 0x00000000
0x10 Transmit Holding Register THR Write-only 0x00000000
0x14 Packet Error Check Register PECR Read-only 0x00000000
0x18 Status Register SR Read-only 0x00000002
0x1C Interrupt Enable Register IER Write-only 0x00000000
0x20 Interrupt Disable Register IDR Write-only 0x00000000
0x24 Interrupt Mask Register IMR Read-only 0x00000000
0x28 Status Clear Register SCR Write-only 0x00000000
0x2C Parameter Register PR Read-only -(1)
0x30 Version Register VR Read-only -(1)
575
32142D–06/2013
ATUC64/128/256L3/4U
23.9.1 Control Register
Name: CR
Access Type: Read/Write
Offset: 0x00
Reset Value: 0x00000000
• TENBIT: Ten Bit Address Match
0: Disables Ten Bit Address Match.
1: Enables Ten Bit Address Match.
• ADR: Slave Address
Slave address used in slave address match. Bits 9:0 are used if in 10-bit mode, bits 6:0 otherwise.
• SODR: Stretch Clock on Data Byte Reception
0: Does not stretch bus clock immediately before ACKing a received data byte.
1: Stretches bus clock immediately before ACKing a received data byte.
• SOAM: Stretch Clock on Address Match
0: Does not stretch bus clock after address match.
1: Stretches bus clock after address match.
• CUP: NBYTES Count Up
0: Causes NBYTES to count down (decrement) per byte transferred.
1: Causes NBYTES to count up (increment) per byte transferred.
• ACK: Slave Receiver Data Phase ACK Value
0: Causes a low value to be returned in the ACK cycle of the data phase in slave receiver mode.
1: Causes a high value to be returned in the ACK cycle of the data phase in slave receiver mode.
• PECEN: Packet Error Checking Enable
0: Disables SMBus PEC (CRC) generation and check.
1: Enables SMBus PEC (CRC) generation and check.
• SMHH: SMBus Host Header
0: Causes the TWIS not to acknowledge the SMBus Host Header.
1: Causes the TWIS to acknowledge the SMBus Host Header.
• SMDA: SMBus Default Address
0: Causes the TWIS not to acknowledge the SMBus Default Address.
1: Causes the TWIS to acknowledge the SMBus Default Address.
• SMBALERT: SMBus Alert
0: Causes the TWIS to release the SMBALERT line and not to acknowledge the SMBus Alert Response Address (ARA).
1: Causes the TWIS to pull down the SMBALERT line and to acknowledge the SMBus Alert Response Address (ARA).
31 30 29 28 27 26 25 24
- - - - - TENBIT ADR[9:8]
23 22 21 20 19 18 17 16
ADR[7:0]
15 14 13 12 11 10 9 8
SODR SOAM CUP ACK PECEN SMHH SMDA SMBALERT
76543210
SWRST - - STREN GCMATCH SMATCH SMEN SEN
576
32142D–06/2013
ATUC64/128/256L3/4U
• SWRST: Software Reset
This bit will always read as 0.
Writing a zero to this bit has no effect.
Writing a one to this bit resets the TWIS.
• STREN: Clock Stretch Enable
0: Disables clock stretching if RHR/THR buffer full/empty. May cause over/underrun.
1: Enables clock stretching if RHR/THR buffer full/empty.
• GCMATCH: General Call Address Match
0: Causes the TWIS not to acknowledge the General Call Address.
1: Causes the TWIS to acknowledge the General Call Address.
• SMATCH: Slave Address Match
0: Causes the TWIS not to acknowledge the Slave Address.
1: Causes the TWIS to acknowledge the Slave Address.
• SMEN: SMBus Mode Enable
0: Disables SMBus mode.
1: Enables SMBus mode.
• SEN: Slave Enable
0: Disables the slave interface.
1: Enables the slave interface.
577
32142D–06/2013
ATUC64/128/256L3/4U
23.9.2 NBYTES Register
Name: NBYTES
Access Type: Read/Write
Offset: 0x04
Reset Value: 0x00000000
• NBYTES: Number of Bytes to Transfer
Writing to this field updates the NBYTES counter. The field can also be read to learn the progress of the transfer. NBYTES can
be incremented or decremented automatically by hardware.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
NBYTES
578
32142D–06/2013
ATUC64/128/256L3/4U
23.9.3 Timing Register
Name: TR
Access Type: Read/Write
Offset: 0x08
Reset Value: 0x00000000
• EXP: Clock Prescaler
Used to specify how to prescale the SMBus TLOWS counter. The counter is prescaled according to the following formula:
• SUDAT: Data Setup Cycles
Non-prescaled clock cycles for data setup count. Used to time TSU_DAT. Data is driven SUDAT cycles after TWCK low detected.
This timing is used for timing the ACK/NAK bits, and any data bits driven in slave transmitter mode.
• TTOUT: SMBus TTIMEOUT Cycles
Prescaled clock cycles used to time SMBus TTIMEOUT.
• TLOWS: SMBus TLOW:SEXT Cycles
Prescaled clock cycles used to time SMBus TLOW:SEXT.
31 30 29 28 27 26 25 24
EXP - - - -
23 22 21 20 19 18 17 16
SUDAT
15 14 13 12 11 10 9 8
TTOUT
76543210
TLOWS
f
PRESCALED
f
CLK_TWIS
2 EXP 1 + = ------------------------
579
32142D–06/2013
ATUC64/128/256L3/4U
23.9.4 Receive Holding Register
Name: RHR
Access Type: Read-only
Offset: 0x0C
Reset Value: 0x00000000
• RXDATA: Received Data Byte
When the RXRDY bit in the Status Register (SR) is one, this field contains a byte received from the TWI bus.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
RXDATA
580
32142D–06/2013
ATUC64/128/256L3/4U
23.9.5 Transmit Holding Register
Name: THR
Access Type: Write-only
Offset: 0x10
Reset Value: 0x00000000
• TXDATA: Data Byte to Transmit
Write data to be transferred on the TWI bus here.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
TXDATA
581
32142D–06/2013
ATUC64/128/256L3/4U
23.9.6 Packet Error Check Register
Name: PECR
Access Type: Read-only
Offset: 0x14
Reset Value: 0x00000000
• PEC: Calculated PEC Value
The calculated PEC value. Updated automatically by hardware after each byte has been transferred. Reset by hardware after a
STOP condition. Provided if the user manually wishes to control when the PEC byte is transmitted, or wishes to access the PEC
value for other reasons. In ordinary operation, the PEC handling is done automatically by hardware.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
PEC
582
32142D–06/2013
ATUC64/128/256L3/4U
23.9.7 Status Register
Name: SR
Access Type: Read-only
Offset: 0x18
Reset Value: 0x000000002
• BTF: Byte Transfer Finished
This bit is cleared when the corresponding bit in SCR is written to one.
This bit is set when byte transfer has completed.
• REP: Repeated Start Received
This bit is cleared when the corresponding bit in SCR is written to one.
This bit is set when a REPEATED START condition is received.
• STO: Stop Received
This bit is cleared when the corresponding bit in SCR is written to one.
This bit is set when the STOP condition is received.
• SMBDAM: SMBus Default Address Match
This bit is cleared when the corresponding bit in SCR is written to one.
This bit is set when the received address matched the SMBus Default Address.
• SMBHHM: SMBus Host Header Address Match
This bit is cleared when the corresponding bit in SCR is written to one.
This bit is set when the received address matched the SMBus Host Header Address.
• SMBALERTM: SMBus Alert Response Address Match
This bit is cleared when the corresponding bit in SCR is written to one.
This bit is set when the received address matched the SMBus Alert Response Address.
• GCM: General Call Match
This bit is cleared when the corresponding bit in SCR is written to one.
This bit is set when the received address matched the General Call Address.
• SAM: Slave Address Match
This bit is cleared when the corresponding bit in SCR is written to one.
This bit is set when the received address matched the Slave Address.
• BUSERR: Bus Error
This bit is cleared when the corresponding bit in SCR is written to one.
This bit is set when a misplaced START or STOP condition has occurred.
31 30 29 28 27 26 25 24
-- - -----
23 22 21 20 19 18 17 16
BTF REP STO SMBDAM SMBHHM SMBALERTM GCM SAM
15 14 13 12 11 10 9 8
- BUSERR SMBPECERR SMBTOUT - - - NAK
76 5 43210
ORUN URUN TRA - TCOMP SEN TXRDY RXRDY
583
32142D–06/2013
ATUC64/128/256L3/4U
• SMBPECERR: SMBus PEC Error
This bit is cleared when the corresponding bit in SCR is written to one.
This bit is set when a SMBus PEC error has occurred.
• SMBTOUT: SMBus Timeout
This bit is cleared when the corresponding bit in SCR is written to one.
This bit is set when a SMBus timeout has occurred.
• NAK: NAK Received
This bit is cleared when the corresponding bit in SCR is written to one.
This bit is set when a NAK was received from the master during slave transmitter operation.
• ORUN: Overrun
This bit is cleared when the corresponding bit in SCR is written to one.
This bit is set when an overrun has occurred in slave receiver mode. Can only occur if CR.STREN is zero.
• URUN: Underrun
This bit is cleared when the corresponding bit in SCR is written to one.
This bit is set when an underrun has occurred in slave transmitter mode. Can only occur if CR.STREN is zero.
• TRA: Transmitter Mode
0: The slave is in slave receiver mode.
1: The slave is in slave transmitter mode.
• TCOMP: Transmission Complete
This bit is cleared when the corresponding bit in SCR is written to one.
This bit is set when transmission is complete. Set after receiving a STOP after being addressed.
• SEN: Slave Enabled
0: The slave interface is disabled.
1: The slave interface is enabled.
• TXRDY: TX Buffer Ready
0: The TX buffer is full and should not be written to.
1: The TX buffer is empty, and can accept new data.
• RXRDY: RX Buffer Ready
0: No RX data ready in RHR.
1: RX data is ready to be read from RHR.
584
32142D–06/2013
ATUC64/128/256L3/4U
23.9.8 Interrupt Enable Register
Name: IER
Access Type: Write-only
Offset: 0x1C
Reset Value: 0x00000000
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will write a one to the corresponding bit in IMR.
31 30 29 28 27 26 25 24
-- - -----
23 22 21 20 19 18 17 16
BTF REP STO SMBDAM SMBHHM SMBALERTM GCM SAM
15 14 13 12 11 10 9 8
- BUSERR SMBPECERR SMBTOUT - - - NAK
76 5 43210
ORUN URUN - - TCOMP - TXRDY RXRDY
585
32142D–06/2013
ATUC64/128/256L3/4U
23.9.9 Interrupt Disable Register
Name: IDR
Access Type: Write-only
Offset: 0x20
Reset Value: 0x00000000
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will clear the corresponding bit in IMR.
31 30 29 28 27 26 25 24
-- - -----
23 22 21 20 19 18 17 16
BTF REP STO SMBDAM SMBHHM SMBALERTM GCM SAM
15 14 13 12 11 10 9 8
- BUSERR SMBPECERR SMBTOUT - - - NAK
76 5 43210
ORUN URUN - - TCOMP - TXRDY RXRDY
586
32142D–06/2013
ATUC64/128/256L3/4U
23.9.10 Interrupt Mask Register
Name: IMR
Access Type: Read-only
Offset: 0x24
Reset Value: 0x00000000
0: The corresponding interrupt is disabled.
1: The corresponding interrupt is enabled.
This bit is cleared when the corresponding bit in IDR is written to one.
This bit is set when the corresponding bit in IER is written to one.
31 30 29 28 27 26 25 24
-- - -----
23 22 21 20 19 18 17 16
BTF REP STO SMBDAM SMBHHM SMBALERTM GCM SAM
15 14 13 12 11 10 9 8
- BUSERR SMBPECERR SMBTOUT - - - NAK
76 5 43210
ORUN URUN - - TCOMP - TXRDY RXRDY
587
32142D–06/2013
ATUC64/128/256L3/4U
23.9.11 Status Clear Register
Name: SCR
Access Type: Write-only
Offset: 0x28
Reset Value: 0x00000000
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will clear the corresponding bit in SR and the corresponding interrupt request.
31 30 29 28 27 26 25 24
-- - -----
23 22 21 20 19 18 17 16
BTF REP STO SMBDAM SMBHHM SMBALERTM GCM SAM
15 14 13 12 11 10 9 8
- BUSERR SMBPECERR SMBTOUT - - - NAK
76 5 43210
ORUN URUN - - TCOMP - - -
588
32142D–06/2013
ATUC64/128/256L3/4U
23.9.12 Parameter Register
Name: PR
Access Type: Read-only
Offset: 0x2C
Reset Value: -
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
--------
589
32142D–06/2013
ATUC64/128/256L3/4U
23.9.13 Version Register (VR)
Name: VR
Access Type: Read-only
Offset: 0x30
Reset Value: -
• VARIANT: Variant Number
Reserved. No functionality associated.
• VERSION: Version Number
Version number of the module. No functionality associated.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
- - - - VARIANT
15 14 13 12 11 10 9 8
- - - - VERSION [11:8]
76543210
VERSION [7:0]
590
32142D–06/2013
ATUC64/128/256L3/4U
23.10 Module Configuration
The specific configuration for each TWIS instance is listed in the following tables.The module
bus clocks listed here are connected to the system bus clocks. Please refer to the Power Manager
chapter for details.
Table 23-7. Module Clock Name
Module Name Clock Name Description
TWIS0 CLK_TWIS0 Clock for the TWIS0 bus interface
TWIS1 CLK_TWIS1 Clock for the TWIS1 bus interface
Table 23-8. Register Reset Values
Register Reset Value
VERSION 0x00000120
PARAMETER 0x00000000
591
32142D–06/2013
ATUC64/128/256L3/4U
24. Inter-IC Sound Controller (IISC)
Rev: 1.0.0.0
24.1 Features
• Compliant with Inter-IC Sound (I2
S) bus specification
• Master, slave, and controller modes:
– Slave: data received/transmitted
– Master: data received/transmitted and clocks generated
– Controller: clocks generated
• Individual enable and disable of receiver, transmitter, and clocks
• Configurable clock generator common to receiver and transmitter:
– Suitable for a wide range of sample frequencies (fs), including 32kHz, 44.1kHz, 48kHz,
88.2kHz, 96kHz, and 192kHz
– 16fs to 1024fs Master Clock generated for external oversampling ADCs
• Several data formats supported:
– 32-, 24-, 20-, 18-, 16-, and 8-bit mono or stereo format
– 16- and 8-bit compact stereo format, with left and right samples packed in the same word to
reduce data transfers
• DMA interfaces for receiver and transmitter to reduce processor overhead:
– Either one DMA channel for both audio channels, or
– One DMA channel per audio channel
• Smart holding registers management to avoid audio channels mix after overrun or underrun
24.2 Overview
The Inter-IC Sound Controller (IISC) provides a 5-wire, bidirectional, synchronous, digital audio
link with external audio devices: ISDI, ISDO, IWS, ISCK, and IMCK pins.
This controller is compliant with the Inter-IC Sound (I2
S) bus specification.
The IISC consists of a Receiver, a Transmitter, and a common Clock Generator, that can be
enabled separately, to provide Master, Slave, or Controller modes with Receiver, Transmitter, or
both active.
Peripheral DMA channels, separate for the Receiver and for the Transmitter, allow a continuous
high bitrate data transfer without processor intervention to the following:
• Audio CODECs in Master, Slave, or Controller mode
• Stereo DAC or ADC through dedicated I2
S serial interface
The IISC can use either a single DMA channel for both audio channels or one DMA channel per
audio channel.
The 8- and 16-bit compact stereo format allows reducing the required DMA bandwidth by transferring
the left and right samples within the same data word.
In Master Mode, the IISC allows outputting a 16 fs to 1024fs Master Clock, in order to provide an
oversampling clock to an external audio codec or digital signal processor (DSP).
592
32142D–06/2013
ATUC64/128/256L3/4U
24.3 Block Diagram
Figure 24-1. IISC Block Diagram
24.4 I/O Lines Description
24.5 Product Dependencies
In order to use this module, other parts of the system must be configured correctly, as described
below.
24.5.1 I/O lines
The IISC pins may be multiplexed with I/O Controller lines. The user must first program the I/O
Controller to assign the desired IISC pins to their peripheral function. If the IISC I/O lines are not
used by the application, they can be used for other purposes by the I/O Controller. It is required
to enable only the IISC inputs and outputs actually in use.
24.5.2 Power Management
If the CPU enters a sleep mode that disables clocks used by the IISC, the IISC will stop functioning
and resume operation after the system wakes up from sleep mode.I/O Controller
ISCK
IWS
ISDI
ISDO
IMCK
Receiver
Clocks
Transmitter
Peripheral Bus interface
Generic clock
PB Peripheral
Bus Bridge
Interrupt
Controller
SCIF
Power
Manager PB clock
IRQ
Peripheral
DMA
Controller
Rx
Tx
IISC
Table 24-1. I/O Lines Description
Pin Name Pin Description Type
IMCK Master Clock Output
ISCK Serial Clock Input/Output
IWS I2
S Word Select Input/Output
ISDI Serial Data Input Input
ISDO Serial Data Output Output
593
32142D–06/2013
ATUC64/128/256L3/4U
24.5.3 Clocks
The clock for the IISC bus interface (CLK_IISC) is generated by the Power Manager. This clock
is enabled at reset, and can be disabled in the Power Manager. It is recommended to disable the
IISC before disabling the clock, to avoid freezing the IISC in an undefined state.
One of the generic clocks is connected to the IISC. The generic clock (GCLK_IISC) can be set to
a wide range of frequencies and clock sources. The GCLK_IISC must be enabled and configured
before use. Refer to the module configuration section for details on the GCLK_IISC used
for the IISC. The frequency for this clock has to be set as described in Table.
24.5.4 DMA
The IISC DMA handshake interfaces are connected to the Peripheral DMA Controller. Using the
IISC DMA functionality requires the Peripheral DMA Controller to be programmed first.
24.5.5 Interrupts
The IISC interrupt line is connected to the Interrupt Controller. Using the IISC interrupt requires
the Interrupt Controller to be programmed first.
24.5.6 Debug Operation
When an external debugger forces the CPU into debug mode, the IISC continues normal operation.
If this module is configured in a way that requires it to be periodically serviced by the CPU
through interrupt requests or similar, improper operation or data loss may result during
debugging.
24.6 Functional Description
24.6.1 Initialization
The IISC features a Receiver, a Transmitter, and, for Master and Controller modes, a Clock
Generator. Receiver and Transmitter share the same Serial Clock and Word Select.
Before enabling the IISC, the chosen configuration must be written to the Mode Register (MR).
The IMCKMODE, MODE, and DATALENGTH fields in the MR register must be written. If the
IMCKMODE field is written as one, then the IMCKFS field should be written with the chosen
ratio, as described in Section 24.6.5 ”Serial Clock and Word Select Generation” on page 595.
Once the Mode Register has been written, the IISC Clock Generator, Receiver, and Transmitter
can be enabled by writing a one to the CKEN, RXEN, and TXEN bits in the Control Register
(CR). The Clock Generator can be enabled alone, in Controller Mode, to output clocks to the
IMCK, ISCK, and IWS pins. The Clock Generator must also be enabled if the Receiver or the
Transmitter is enabled.
The Clock Generator, Receiver, and Transmitter can be disabled independently by writing a one
to CR.CXDIS, CR.RXDIS and/or CR.TXDIS respectively. Once requested to stop, they will only
stop when the transmission of the pending frame transmission will be completed.
24.6.2 Basic Operation
The Receiver can be operated by reading the Receiver Holding Register (RHR), whenever the
Receive Ready (RXRDY) bit in the Status Register (SR) is set. Successive values read from
RHR will correspond to the samples from the left and right audio channels for the successive
frames.
594
32142D–06/2013
ATUC64/128/256L3/4U
The Transmitter can be operated by writing to the Transmitter Holding Register (RHR), whenever
the Transmit Ready (TXRDY) bit in the Status Register (SR) is set. Successive values
written to THR should correspond to the samples from the left and right audio channels for the
successive frames.
The Receive Ready and Transmit Ready bits can be polled by reading the Status Register.
The IISC processor load can be reduced by enabling interrupt-driven operation. The RXRDY
and/or TXRDY interrupt requests can be enabled by writing a one to the corresponding bit in the
Interrupt Enable Register (IER). The interrupt service routine associated to the IISC interrupt
request will then be executed whenever the Receive Ready or the Transmit Ready status bit is
set.
24.6.3 Master, Controller, and Slave Modes
In Master and Controller modes, the IISC provides the Master Clock, the Serial Clock and the
Word Select. IMCK, ISCK, and IWS pins are outputs.
In Controller mode, the IISC Receiver and Transmitter are disabled. Only the clocks are enabled
and used by an external receiver and/or transmitter.
In Slave mode, the IISC receives the Serial Clock and the Word Select from an external master.
ISCK and IWS pins are inputs.
The mode is selected by writing the MODE field of the Mode Register (MR). Since the MODE
field changes the direction of the IWS and ISCK pins, the Mode Register should only be written
when the IISC is stopped, in order to avoid unwanted glitches on the IWS and ISCK pins.
24.6.4 I2
S Reception and Transmission Sequence
As specified in the I2
S protocol, data bits are left-adjusted in the Word Select time slot, with the
MSB transmitted first, starting one clock period after the transition on the Word Select line.
Figure 24-2. I
2
S Reception and Transmission Sequence
Data bits are sent on the falling edge of the Serial Clock and sampled on the rising edge of the
Serial Clock. The Word Select line indicates the channel in transmission, a low level for the left
channel and a high level for the right channel.
The length of transmitted words can be chosen among 8, 16, 18, 20, 24, and 32 bits by writing
the MR.DATALENGTH field.
If the time slot allows for more data bits than written in the MR.DATALENGTH field, zeroes are
appended to the transmitted data word or extra received bits are discarded. If the time slot
allows for less data bits than written, the extra bits to be transmitted are not sent or the missing
bits are set to zero in the received data word.
Serial Clock ISCK
Word Select IWS
Data ISDI/ISDO MSB
Left Channel
LSB MSB
Right Channel
595
32142D–06/2013
ATUC64/128/256L3/4U
24.6.5 Serial Clock and Word Select Generation
The generation of clocks in the IISC is described in Figure 24-3 on page 596.
In Slave mode, the Serial Clock and Word Select Clock are driven by an external master. ISCK
and IWS pins are inputs and no generic clock is required by the IISC.
In Master mode, the user can configure the Master Clock, Serial Clock, and Word Select Clock
through the Mode Register (MR). IMCK, ISCK, and IWS pins are outputs and a generic clock is
used to derive the IISC clocks.
Audio codecs connected to the IISC pins may require a Master Clock signal with a frequency
multiple of the audio sample frequency (fs), such as 256fs. When the IISC is in Master mode,
writing a one to MR.IMCKMODE will output GCLK_IISC as Master Clock to the IMCK pin, and
will divide GCLK_IISC to create the internal bit clock, output on the ISCK pin. The clock division
factor is defined by writing to MR.IMCKFS and MR.DATALENGTH, as described ”IMCKFS:
Master Clock to fs Ratio” on page 602.
The Master Clock (IMCK) frequency is 16*(IMCKFS+1) times the sample frequency (fs), i.e. IWS
frequency. The Serial Clock (ISCK) frequency is 2*Slot Length times the sample frequency (fs),
where Slot Length is defined in Table 24-2 on page 595.
Warning: MR.IMCKMODE should only be written as one if the Master Clock frequency is strictly
higher than the Serial Clock.
If a Master Clock output is not required, the GCLK_IISC generic clock is used as ISCK, by writing
a zero to MR.IMCKMODE. Alternatively, if the frequency of the generic clock used is a
multiple of the required ISCK frequency, the IMCK to ISCK divider can be used with the ratio
defined by writing the MR.IMCKFS field.
The IWS pin is used as Word Select as described in Section 24.6.4.
Table 24-2. Slot Length
MR.DATALENGTH Word Length Slot Length
0 32 bits 32
1 24 bits
32 if MR.IWS24 is zero
24 if MR.IWS24 is one 2 20 bits
3 18 bits
4 16 bits
16
5 16 bits compact stereo
6 8 bits
8
7 8 bits compact stereo
596
32142D–06/2013
ATUC64/128/256L3/4U
Figure 24-3. IISC Clocks Generation
24.6.6 Mono
When the Transmit Mono (TXMONO) in the Mode Register is set, data written to the left channel
is duplicated to the right output channel.
When the Receive Mono (RXMONO) in the Mode Register is set, data received from the left
channel is duplicated to the right channel.
24.6.7 Holding Registers
The IISC user interface includes a Receive Holding Register (RHR) and a Transmit Holding
Register (THR). RHR and THR are used to access audio samples for both audio channels.
When a new data word is available in the RHR register, the Receive Ready bit (RXRDY) in the
Status Register (SR) is set. Reading the RHR register will clear this bit.
A receive overrun condition occurs if a new data word becomes available before the previous
data word has been read from the RHR register. Then, the Receive Overrun bit in the Status
Register will be set and bit i of the RXORCH field in the Status Register is set, where i is the current
receive channel number.
When the THR register is empty, the Transmit Ready bit (TXRDY) in the Status Register (SR) is
set. Writing into the THR register will clear this bit.
A transmit underrun condition occurs if a new data word needs to be transmitted before it has
been written to the THR register. Then, the Transmit Underrun bit in the Status Register will be
set and bit i of the TXORCH field in the Status Register is set, where i is the current transmit
channel number. If the TXSAME bit in the Mode Register is zero, then a zero data word is transmitted
in case of underrun. If MR.TXSAME is one, then the previous data word for the current
transmit channel number is transmitted.
MR.MODE = SLAVE Clock
divider MR.DATALENGTH
GCLK_IISC Clock
enable
Clock
divider
CR.CKEN/CKDIS MR.IMCKMODE
MR.DATALENGTH
MR.IMCKFS
MR.IMCKMODE 0 1
IMCK pin output
Clock
enable
CR.CKEN/CKDIS
Internal
bit clock ISCK pin input 1
0
ISCK pin output
Internal
word clock IWS pin input 1
0
IWS pin output
597
32142D–06/2013
ATUC64/128/256L3/4U
Data words are right-justified in the RHR and THR registers. For 16-bit compact stereo, the left
sample uses bits 15 through 0 and the right sample uses bits 31 through 16 of the same data
word. For 8-bit compact stereo, the left sample uses bits 7 through 0 and the right sample uses
bits 15 through 8 of the same data word.
24.6.8 DMA Operation
The Receiver and the Transmitter can each be connected either to one single Peripheral DMA
channel or to one Peripheral DMA channel per data channel. This is selected by writing to the
MR.RXDMA and MR.TXDMA bits. If a single Peripheral DMA channel is selected, all data samples
use IISC Receiver or Transmitter DMA channel 0.
The Peripheral DMA reads from the RHR register and writes to the RHR register for both audio
channels, successively.
The Peripheral DMA transfers may use 32-bit word, 16-bit halfword, or 8-bit byte according to
the value of the MR.DATALENGTH field.
24.6.9 Loop-back Mode
For debugging purposes, the IISC can be configured to loop back the Transmitter to the
Receiver. Writing a one to the MR.LOOP bit will internally connect ISDO to ISDI, so that the
transmitted data is also received. Writing a zero to MR.LOOP will restore the normal behavior
with independent Receiver and Transmitter. As for other changes to the Receiver or Transmitter
configuration, the IISC Receiver and Transmitter must be disabled before writing to the MR register
to update MR.LOOP.
24.6.10 Interrupts
An IISC interrupt request can be triggered whenever one or several of the following bits are set
in the Status Register (SR): Receive Ready (RXRDY), Receive Overrun (RXOR), Transmit
Ready (TXRDY), or Transmit Underrun (TXOR).
The interrupt request will be generated if the corresponding bit in the Interrupt Mask Register
(IMR) is set. Bits in IMR are set by writing a one to the corresponding bit in the Interrupt Enable
Register (IER), and cleared by writing a one to the corresponding bit in the Interrupt Disable
Register (IDR). The interrupt request remains active until the corresponding bit in SR is cleared
by writing a one the corresponding bit in the Status Clear Register (SCR).
For debugging purposes, interrupt requests can be simulated by writing a one to the corresponding
bit in the Status Set Register (SSR).
598
32142D–06/2013
ATUC64/128/256L3/4U
Figure 24-4. Interrupt Block Diagram
24.7 IISC Application Examples
The IISC can support several serial communication modes used in audio or high-speed serial
links. Some standard applications are shown in the following figures. All serial link applications
supported by the IISC are not listed here.
Figure 24-5. Audio Application Block Diagram
IER IDR IMR
Set Clear
Interrupt
Control
IISC Interrupt
Request
TXRDY
TXUR
Transmitter
Receiver
RXRDY
RXOR
Serial Clock
Word Select
Serial Data Out MSB LSB MSB
Serial Data Out
Word Select
Serial Clock
IISC
ISCK
IWS
ISDO
ISDI
EXTERNAL
I
2
S
RECEIVER
599
32142D–06/2013
ATUC64/128/256L3/4U
Figure 24-6. Codec Application Block Diagram
Figure 24-7. Time Slot Application Block Diagram
IISC Word Select
Serial Data Out
Serial Data In
EXTERNAL
AUDIO
CODEC
IMCK
IWS
ISDO
ISDI
Serial Clock
Master Clock
ISCK
Right Time Slot
Serial Clock
Word Select
Serial Data Out
Serial Data In
Dstart Dend
Left Time Slot
EXTERNAL
AUDIO
CODEC
for Left
Time Slot
EXTERNAL
AUDIO
CODEC
for Right
Time Slot
Serial Data In
Serial Data Out
Word Select
Serial Clock
Serial Clock
Word Select
Serial Data Out
Serial Data In
Dstart
Left Time Slot Right Time Slot
Dend
IISC
ISCK
IWS
ISDO
ISDI
Master Clock IMCK
600
32142D–06/2013
ATUC64/128/256L3/4U
24.8 User Interface
Note: 1. The reset values for these registers are device specific. Please refer to the Module Configuration section at the end of this
chapter.
Table 24-3. IISC Register Memory Map
Offset Register Register Name Access Reset
0x00 Control Register CR Write-only 0x00000000
0x04 Mode Register MR Read/Write 0x00000000
0x08 Status Register SR Read-only 0x00000000
0x0C Status Clear Register SCR Write-only 0x00000000
0x10 Status Set Register SSR Write-only 0x00000000
0x14 Interrupt Enable Register IER Write-only 0x00000000
0x18 Interrupt Disable Register IDR Write-only 0x00000000
0x1C Interrupt Mask Register IMR Read-only 0x00000000
0x20 Receiver Holding Register RHR Read-only 0x00000000
0x24 Transmitter Holding Register THR Write-only 0x00000000
0x28 Version Register VERSION Read-only -
(1)
0x2C Parameter Register PARAMETER Read-only -
(1)
601
32142D–06/2013
ATUC64/128/256L3/4U
24.8.1 Control Register
Name: CR
Access Type: Write-only
Offset: 0x00
Reset Value: 0x00000000
The Control Register should only be written to enable the IISC after the chosen configuration has been written to the Mode
Register, in order to avoid unwanted glitches on the IWS, ISCK, and ISDO outputs. The proper sequence is to write the MR
register, then write the CR register to enable the IISC, or to disable the IISC before writing a new value into MR.
• SWRST: Software Reset
Writing a zero to this bit has no effect.
Writing a one to this bit resets all the registers in the module. The module will be disabled after the reset.
This bit always reads as zero.
• TXDIS: Transmitter Disable
Writing a zero to this bit has no effect.
Writing a one to this bit disables the IISC Transmitter. SR.TXEN will be cleared when the Transmitter is effectively stopped.
• TXEN: Transmitter Enable
Writing a zero to this bit has no effect.
Writing a one to this bit enables the IISC Transmitter, if TXDIS is not one. SR.TXEN will be set when the Transmitter is effectively
started.
• CKDIS: Clocks Disable
Writing a zero to this bit has no effect.
Writing a one to this bit disables the IISC clocks generation.
• CKEN: Clocks Enable
Writing a zero to this bit has no effect.
Writing a one to this bit enables the IISC clocks generation, if CKDIS is not one.
• RXDIS: Receiver Disable
Writing a zero to this bit has no effect.
Writing a one to this bit disables the IISC Receiver. SR.TXEN will be cleared when the Transmitter is effectively stopped.
• RXEN: Receiver Enable
Writing a zero to this bit has no effect.
Writing a one to this bit enables the IISC Receiver, if RXDIS is not one. SR.RXEN will be set when the Receiver is effectively
started.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
SWRST - TXDIS TXEN CKDIS CKEN RXDIS RXEN
602
32142D–06/2013
ATUC64/128/256L3/4U
24.8.2 Mode Register
Name: MR
Access Type: Read/Write
Offset: 0x04
Reset Value: 0x00000000
The Mode Register should only be written when the IISC is stopped, in order to avoid unwanted glitches on the IWS, ISCK,
and ISDO outputs. The proper sequence is to write the MR register, then write the CR register to enable the IISC, or to disable
the IISC before writing a new value into MR.
• IWS24: IWS TDM Slot Width
0: IWS slot is 32-bit wide for DATALENGTH=18/20/24-bit
1: IWS slot is 24-bit wide for DATALENGTH=18/20/24-bit
Refer to Table 24-2, “Slot Length,” on page 595.
• IMCKMODE: Master Clock Mode
0: No Master Clock generated (generic clock is used as ISCK output)
1: Master Clock generated (generic clock is used as IMCK output)
Warning: if IMCK frequency is the same as ISCK, IMCKMODE should not be written as one. Refer to Section 24.6.5 ”Serial
Clock and Word Select Generation” on page 595 and Table 24-2, “Slot Length,” on page 595.
• IMCKFS: Master Clock to fs Ratio
Master Clock frequency is 16*(IMCKFS+1) times the sample rate, i.e. IWS frequency:
31 30 29 28 27 26 25 24
IWS24 IMCKMODE IMCKFS
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
- TXSAME TXDMA TXMONO RXLOOP RXDMA RXMONO
76543210
- - - DATALENGTH - MODE
Table 24-4. Master Clock to Sample Frequency (fs) Ratio
fs Ratio IMCKFS
16 fs 0
32 fs 1
48fs 2
64 fs 3
96fs 5
128 fs 7
192fs 11
256 fs 15
603
32142D–06/2013
ATUC64/128/256L3/4U
• TXSAME: Transmit Data when Underrun
0: Zero sample transmitted when underrun
1: Previous sample transmitted when underrun
• TXDMA: Single or multiple DMA Channels for Transmitter
0: Transmitter uses a single DMA channel for both audio channels
1: Transmitter uses one DMA channel per audio channel
• TXMONO: Transmit Mono
0: Stereo
1: Mono, with left audio samples duplicated to right audio channel by the IISC
• RXLOOP: Loop-back Test Mode
0: Normal mode
1: ISDO output of IISC is internally connected to ISDI input
• RXMONO: Receive Mono
0: Stereo
1: Mono, with left audio samples duplicated to right audio channel by the IISC
• RXDMA: Single or multiple DMA Channels for Receiver
0: Receiver uses a single DMA channel for both audio channels
1: Receiver uses one DMA channel per audio channel-
• DATALENGTH: Data Word Length
• MODE: Mode
384 fs 23
512 fs 31
768 fs 47
1024 fs 63
Table 24-5. Data Word Length
DATALENGTH Word Length Comments
0 32 bits
1 24 bits
2 20 bits
3 18 bits
4 16 bits
5 16 bits compact stereo Left sample in bits 15 through 0 and right sample in bits 31 through 16 of the same word
6 8 bits
7 8 bits compact stereo Left sample in bits 7 through 0 and right sample in bits 15 through 8 of the same word
Table 24-6. Mode
MODE Comments
0 SLAVE ISCK and IWS pin inputs used as Bit Clock and Word Select/Frame Sync.
1 MASTER Bit Clock and Word Select/Frame Sync generated by IISC from GCLK_IISC and output to ISCK and IWS pins.
GCLK_IISC is output as Master Clock on IMCK if MR.IMCKMODE is one.
Table 24-4. Master Clock to Sample Frequency (fs) Ratio
fs Ratio IMCKFS
604
32142D–06/2013
ATUC64/128/256L3/4U
24.8.3 Status Register
Name: SR
Access Type: Read-only
Offset: 0x08
Reset Value: 0x00000000
• TXURCH: Transmit Underrun Channel
This field is cleared when SCR.TXUR is written to one
Bit i of this field is set when a transmit underrun error occurred in channel i (i=0 for first channel of the frame)
• RXORCH: Receive Overrun Channel
This field is cleared when SCR.RXOR is written to one
Bit i of this field is set when a receive overrun error occurred in channel i (i=0 for first channel of the frame)
• TXUR: Transmit Underrun
This bit is cleared when the corresponding bit in SCR is written to one
This bit is set when an underrun error occurs on the THR register or when the corresponding bit in SSR is written to one
• TXRDY: Transmit Ready
This bit is cleared when data is written to THR
This bit is set when the THR register is empty and can be written with new data to be transmitted
• TXEN: Transmitter Enabled
This bit is cleared when the Transmitter is effectively disabled, following a CR.TXDIS or CR.SWRST request
This bit is set when the Transmitter is effectively enabled, following a CR.TXEN request
• RXOR: Receive Overrun
This bit is cleared when the corresponding bit in SCR is written to one
This bit is set when an overrun error occurs on the RHR register or when the corresponding bit in SSR is written to one
• RXRDY: Receive Ready
This bit is cleared when the RHR register is read
This bit is set when received data is present in the RHR register
• RXEN: Receiver Enabled
This bit is cleared when the Receiver is effectively disabled, following a CR.RXDIS or CR.SWRST request
This bit is set when the Receiver is effectively enabled, following a CR.RXEN request
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
- - TXURCH - - - -
15 14 13 12 11 10 9 8
- - - - - - RXORCH
76543210
- TXUR TXRDY TXEN - RXOR RXRDY RXEN
605
32142D–06/2013
ATUC64/128/256L3/4U
24.8.4 Status Clear Register
Name: SCR
Access Type: Write-only
Offset: 0x0C
Reset Value: 0x00000000
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will clear the corresponding bit in SR and the corresponding interrupt request.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
- - TXURCH - - - -
15 14 13 12 11 10 9 8
- - - - - - RXORCH
76543210
- TXUR - - - RXOR - -
606
32142D–06/2013
ATUC64/128/256L3/4U
24.8.5 Status Set Register
Name: SSR
Access Type: Write-only
Offset: 0x10
Reset Value: 0x00000000
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will set the corresponding bit in SR.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
- - TXURCH - - - -
15 14 13 12 11 10 9 8
- - - - - - RXORCH
76543210
- TXUR - - - RXOR - -
607
32142D–06/2013
ATUC64/128/256L3/4U
24.8.6 Interrupt Enable Register
Name: IER
Access Type: Write-only
Offset: 0x14
Reset Value: 0x00000000
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will set the corresponding bit in IMR.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
- TXUR TXRDY - - RXOR RXRDY -
608
32142D–06/2013
ATUC64/128/256L3/4U
24.8.7 Interrupt Disable Register
Name: IDR
Access Type: Write-only
Offset: 0x18
Reset Value: 0x00000000
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will clear the corresponding bit in IMR.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
- TXUR TXRDY - - RXOR RXRDY -
609
32142D–06/2013
ATUC64/128/256L3/4U
24.8.8 Interrupt Mask Register
Name: IMR
Access Type: Read-only
Offset: 0x1C
Reset Value: 0x00000000
0: The corresponding interrupt is disabled.
1: The corresponding interrupt is enabled.
A bit in this register is cleared when the corresponding bit in IDR is written to one.
A bit in this register is set when the corresponding bit in IER is written to one.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
- TXUR TXRDY - - RXOR RXRDY -
610
32142D–06/2013
ATUC64/128/256L3/4U
24.8.9 Receive Holding Register
Name: RHR
Access Type: Read-only
Offset: 0x20
Reset Value: 0x00000000
• RHR: Received Word
This field is set by hardware to the last received data word. If MR.DATALENGTH specifies less than 32 bits, data shall be rightjustified
into the RHR field.
31 30 29 28 27 26 25 24
RHR[31:24]
23 22 21 20 19 18 17 16
RHR[23:16]
15 14 13 12 11 10 9 8
RHR[15:8]
76543210
RHR[7:0]
611
32142D–06/2013
ATUC64/128/256L3/4U
24.8.10 Transmit Holding Register
Name: THR
Access Type: Write-only
Offset: 0x24
Reset Value: 0x00000000
• THR: Data Word to Be Transmitted
Next data word to be transmitted after the current word if TXRDY is not set. If MR.DATALENGTH specifies less than 32 bits, data
shall be right-justified into the THR field.
31 30 29 28 27 26 25 24
THR[31:24]
23 22 21 20 19 18 17 16
THR[23:16]
15 14 13 12 11 10 9 8
THR[15:8]
76543210
THR[7:0]
612
32142D–06/2013
ATUC64/128/256L3/4U
24.8.11 Module Version
Name: VERSION
Access Type: Read-only
Offset: 0x28
Reset Value: -
• VARIANT: Variant Number
Reserved. No functionality associated.
• VERSION: Version Number
Version number of the module. No functionality associated.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
- - - - VARIANT
15 14 13 12 11 10 9 8
- - - - VERSION[11:8]
76543210
VERSION[7:0]
613
32142D–06/2013
ATUC64/128/256L3/4U
24.8.12 Module Parameters
Name: PARAMETER
Access Type: Read-only
Offset: 0x2C
Reset Value: -
Reserved. No functionality associated.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
--------
614
32142D–06/2013
ATUC64/128/256L3/4U
24.9 Module configuration
The specific configuration for each IISC instance is listed in the following tables. The module bus
clocks listed here are connected to the system bus clocks. Please refer to the Power Manager
chapter for details.
Table 24-7. IISC Clocks
Clock Name Description
CLK_IISC Clock for the IISC bus interface
GCLK The generic clock used for the IISC is GCLK6
Table 24-8. Register Reset Values
Register Reset Value
VERSION 0x00000100
615
32142D–06/2013
ATUC64/128/256L3/4U
25. Pulse Width Modulation Controller (PWMA)
Rev: 2.0.1.0
25.1 Features
• Left-aligned non-inverted 12-bit PWM
• Common 12-bit timebase counter
– Asynchronous clock source supported
– Spread-spectrum counter to allow a constantly varying duty cycle
• Separate 12-bit duty cycle register per channel
• Synchronized channel updates
– No glitches when changing the duty cycles
• Interlinked operation supported
– Up to 32 channels can be updated with the same duty cycle value at a time
– Up to 4 channels can be updated with different duty cycle values at a time
• Interrupt on PWM timebase overflow
• Incoming peripheral events supported
– Pre-defined channels support incoming (increase/decrease) peripheral events from the
Peripheral Event System
– Incoming increase/decrease event can either increase or decrease the duty cycle by one
• One output peripheral event supported
– Connected to channel 0 and asserted when the common timebase counter is equal to the
programmed duty cycle for channel 0
• Output PWM waveforms
– Support normal waveform output for each channel
– Support composite waveform generation (XOR’ed) for each pair channels
• Open drain driving on selected pins for 5V PWM operation
25.2 Overview
The Pulse Width Modulation Controller (PWMA) controls several pulse width modulation (PWM)
channels. The number of channels is specific to the device. Each channel controls one square
output PWM waveform. Characteristics of the output PWM waveforms such as period and duty
cycle are configured through the user interface. All user interface registers are mapped on the
peripheral bus.
The duty cycle value for each channel can be set independently, while the period is determined
by a common timebase counter (TC). The timebase for the counter is selected by using the allocated
asynchronous Generic Clock (GCLK). The user interface for the PWMA contains
handshake and synchronizing logic to ensure that no glitches occur on the output PWM waveforms
while changing the duty cycle values.
PWMA duty cycle values can be changed using two approaches, either an interlinked singlevalue
mode or an interlinked multi-value mode. In the interlinked single-value mode, any set of
channels, up to 32 channels, can be updated simultaneously with the same value while the other
channels remain unchanged. There is also an interlinked multi-value mode, where the 8 least
significant bits of up to 4 channels can be updated with 4 different values while the other channels
remain unchanged.
Some pins can be driven in open drain mode, allowing the PWMA to generate a 5V waveform
using an external pullup resistor.
616
32142D–06/2013
ATUC64/128/256L3/4U
25.3 Block Diagram
Figure 25-1. PWMA Block Diagram
25.4 I/O Lines Description
Each channel outputs one PWM waveform on one external I/O line.
25.5 Product Dependencies
In order to use this module, other parts of the system must be configured correctly, as described
below.
PWM Blocks
Channel m
Channel 1
Channel 0
Duty Cycle
Register
COMP
PWMA[m:0]
Interrupt
Handling
IRQ
PB
TOP
Timebase
Counter
SPREAD
Adjust
TOFL
READY
Channel_0
CLK_PWMA
GCLK Domain
PB Clock Domain
Spread
Spectrum
Counter
Sync
GCLK ETV
Control
Duty Cycle Channel
Select WAVEXOR
CWG
TCLR CHERR
Table 25-1. I/O Line Description
Pin Name Pin Description Type
PWMA[n] Output PWM waveform for one channel n Output
PWMMOD[n] Output PWM waveform for one channel n, open drain mode Output
617
32142D–06/2013
ATUC64/128/256L3/4U
25.5.1 I/O Lines
The pins used for interfacing the PWMA may be multiplexed with I/O Controller lines. The programmer
must first program the I/O Controller to assign the desired PWMA pins to their
peripheral function.
It is only required to enable the PWMA outputs actually in use.
25.5.2 Power Management
If the CPU enters a sleep mode that disables clocks used by the PWMA, the PWMA will stop
functioning and resume operation after the system wakes up from sleep mode.
25.5.3 Clocks
The clock for the PWMA bus interface (CLK_PWMA) is controlled by the Power Manager. This
clock is enabled at reset, and can be disabled in the Power Manager. It is recommended to disable
the PWMA before disabling the clock, to avoid freezing the PWMA in an undefined state.
Additionally, the PWMA depends on a dedicated Generic Clock (GCLK). The GCLK can be set
to a wide range of frequencies and clock sources and must be enabled in the System Control
Interface (SCIF) before the PWMA can be used.
25.5.4 Interrupts
The PWMA interrupt request lines are connected to the interrupt controller. Using the PWMA
interrupts requires the interrupt controller to be programmed first.
25.5.5 Peripheral Events
The PWMA peripheral events are connected via the Peripheral Event System. Refer to the
Peripheral Event System chapter for details.
25.5.6 Debug Operation
When an external debugger forces the CPU into debug mode, the PWMA continues normal
operation. If the PWMA is configured in a way that requires it to be periodically serviced by the
CPU through interrupts, improper operation or data loss may result during debugging.
25.6 Functional Description
The PWMA embeds a number of PWM channel submodules, each providing an output PWM
waveform. Each PWM channel contains a duty cycle register and a comparator. A common
timebase counter for all channels determines the frequency and the period for all the PWM
waveforms.
25.6.1 Enabling the PWMA
Once the GCLK has been enabled, the PWMA is enabled by writing a one to the EN bit in the
Control Register (CR).
25.6.2 Timebase Counter
The top value of the timebase counter defines the period of the PWMA output waveform. The
timebase counter starts at zero when the PWMA is enabled and counts upwards until it reaches
its effective top value (ETV). The effective top value is defined by specifying the desired number
of GCLK clock cycles in the TOP field of Top Value Register (TVR.TOP) in normal operation (the
618
32142D–06/2013
ATUC64/128/256L3/4U
SPREAD field of CR (CR.SPREAD) is zero). When the timebase counter reaches its effective
top value, it restarts counting from zero. The period of the PWMA output waveform is then:
The timebase counter can be reset by writing a one to the Timebase Clear bit in CR (CR.TCLR).
Note that this can cause a glitch to the output PWM waveforms in use.
25.6.3 Spread Spectrum Counter
The spread spectrum counter allows the generation of constantly varying duty cycles on the output
PWM waveforms. This is achieved by varying the effective top value of the timebase counter
in a range defined by the spread spectrum counter value.
When CR.SPREAD is not zero, the spread spectrum counter is enabled. Its range is defined by
CR.SPREAD. It starts to count from -CR.SPREAD when the PWMA is enabled or after reset
and counts upwards. When it reaches CR.SPREAD, it restarts to count from -CR.SPREAD
again. The spread spectrum counter will cause the effective top value to vary from TOPSPREAD
to TOP+SPREAD. Figure 25-2 on page 618 illustrates this. This leads to a constantly
varying duty cycle on the PWM output waveforms though the duty cycle values stored are
unchanged.
Figure 25-2. PWMA Adjusting Top Value for Timebase Counter
25.6.3.1 Special considerations
The maximum value of the timebase counter is 0x0FFF. If SPREAD is written to a value that will
cause the ETV to exceed this value, the spread spectrum counter’s range will be limited to prevent
the timebase counter to exceed its maximum value.
If SPREAD is written to a value causing (TOP-SPREAD) to be below zero, the spread spectrum
counter’s range will be limited to prevent the timebase counter to count below zero.
In both cases, the SPREAD value read from the Control Register will be the same value as written
to the SPREAD field.
TPWMA ETV + 1 TGCLK =
0x0
0x0FFF
Duty Cycle
-SPREAD
SPREAD
TOP Adjusting top value range
for the timerbase counter
619
32142D–06/2013
ATUC64/128/256L3/4U
When writing a one to CR.TCLR, the timebase counter and the spread spectrum counter are
reset at their lower limit values and the effective top value of the timebase counter will also be
reset.
25.6.4 Duty Cycle and Waveform Properties
Each PWM channel has its own duty cycle value (DCV) which is write-only and cannot be read
out. The duty cycle value can be changed in two approaches as described in Section25.6.6.
When the duty cycle value is zero, the PWM output is zero. Otherwise, the PWM output is set
when the timebase counter is zero, and cleared when the timebase counter reaches the duty
cycle value. This is summarized as:
Note that when increasing the duty cycle value for one channel from 0 to 1, the number of GCLK
cycles when the PWM waveform is high will jump from 0 to 2. When incrementing the duty cycle
value by one for any other values, the number of GCLK cycle when the waveform is high will
increase by one. This is summarized in Table 25-2.
25.6.5 Waveform Output
PWMA waveforms are output to I/O lines. The output waveform properties are controlled by
Composite Waveform Generation (CWG) register(s). If this register is cleared (by default), the
channel waveforms are out directly to the I/O lines. To avoid too many I/O toggling simultaneously
on the output I/O lines, every other output PWM waveform toggles on the negative edge of
the GCLK instead of the positive edge.
In CWG mode, all channels are paired and their outputs are XOR’ed together if the corresponding
bit of CWG register is set. The even number of output is the XOR’ed output and the odd
number of output is the inverse of its. Each bit of CWG register controls one pair channels and
the least significant bit refers to the lowest number of pair channels.
25.6.6 Updating Duty Cycle Values
25.6.6.1 Interlinked Single Value PWM Operation
The PWM channels can be interlinked to allow multiple channels to be updated simultaneously
with the same duty cycle value. This value must be written to the Interlinked Single Value Duty
Table 25-2. PMW Waveform Duty Cycles
Duty Cycle Value
#Clock Cycles
When Waveform is High
#Clock Cycles
When Waveform is Low
0 0 ETV+1
1 2 ETV-1
2 3 ETV-2
... ... ...
ETV-1 ETV 1
ETV ETV+1 0
PWM Waveform = low when DCV = 0 or TC DCV
high when TC DCV and DCV 0
620
32142D–06/2013
ATUC64/128/256L3/4U
(ISDUTY) register. Each channel has a corresponding enabling bit in the Interlinked Single
Value Channel Set (ISCHSET) register(s). When a bit is written to one in the ISCHSET register,
the duty cycle register for the corresponding channel will be updated with the value stored in the
ISDUTY register. It can only be updated when the READY bit in the Status Register
(SR.READY) is one, indicating that the PWMA is ready for writing. Figure 25-3 on page 620
shows the writing procedure. It is thus possible to update the duty cycle values for up to 32 PWM
channels within one ISCHSET register at a time.
Figure 25-3. Interlinked Single Value PWM Operation Flow
25.6.6.2 Interlinked Multiple Value PWM Operation
The interlinked multiple value PWM operation allows up to four channels to be updated simultaneously
with different duty cycle values. The four duty cycle values are required to be written to
the four registers, DUTY3, DUTY2, DUTY1 and DUTY0 , respectively. The index number of the
four channels to be updated is written to the four SEL fields in the Interlinked Multiple Value
Channel Select (IMCHSEL) register (IMCHSEL.SEL). When the IMCHSEL register is written,
the values stored in the DUTY0/1/2/3 registers are synchronized to the duty cycle registers for
the channels selected by the SEL fields. Figure 25-4 on page 620 shows the writing procedure.
Note that only writes to the implemented channels will be effective. If one of the IMCHSEL.SEL
fields points to a non-existing channel, the corresponding value in the DUTYx register will not be
written. If the same channel is specified multiple times in the IMCHSEL.SEL fields, the channel
will be updated with the value referred by the upper IMCHSEL.SEL field.
When only the least significant 8-bits duty cycle value are considered for updating, the four duty
cycle values can be written to the IMDUTY register once. This is equivalent to writing the four
duty cycle values to the four DUTY registers one by one.
Figure 25-4. Interlinked Multiple Value PWM Operation Flow
ISCHSETm
...
Write
Enable
Channeln
DUTY
Channel1
DUTY
Channel0
DUTY
ISDUTY
Channel2
DUTY
DUTY3/2/1/0
IMDUTY IMCHSEL
Channeln
DUTY
...
MUX
Channel1
DUTY
Channel0
DUTY
621
32142D–06/2013
ATUC64/128/256L3/4U
25.6.7 Open Drain Mode
Some pins can be used in open drain mode, allowing the PWMA waveform to toggle between
0V and up to 5V on these pins. In this mode the PWMA will drive the pin to zero or leave the output
open. An external pullup can be used to pull the pin up to the desired voltage.
To enable open drain mode on a pin the PWMAOD function must be selected instead of the
PWMA function in the I/O Controller. Please refer to the Module Configuration chapter for information
about which pins are available in open drain mode.
25.6.8 Synchronization
Both the timebase counter and the spread spectrum counter can be reset and the duty cycle
registers can be written through the user interface of the module. This requires a synchronization
between the PB and GCLK clock domains, which takes a few clock cycles of each clock
domain. The BUSY bit in SR indicates when the synchronization is ongoing. Writing to the module
while the BUSY bit is set will result in discarding the new value.
Note that the duty cycle registers will not be updated with the new values until the timebase
counter reaches its top value, in order to avoid glitches. The BUSY bit in SR will always be set
during this updating and synchronization period.
25.6.9 Interrupts
When the timebase counter overflows, the Timebase Overflow bit in the Status Register
(SR.TOFL) is set. If the corresponding bit in the Interrupt Mask Register (IMR) is set, an interrupt
request will be generated.
Since the user needs to wait until the user interface is available between each write due to synchronization,
a READY bit is provided in SR, which can be used to generate an interrupt
request.
The interrupt request will be generated if the corresponding bit in IMR is set. Bits in IMR are set
by writing a one to the corresponding bit in the Interrupt Enable Register (IER), and cleared by
writing a one to the corresponding bit in the Interrupt Disable Register (IDR). The interrupt
request remains active until the corresponding bit in SR is cleared by writing a one to the corresponding
bit in the Status Clear Register (SCR).
25.6.10 Peripheral Events
25.6.10.1 Input Peripheral Events
The pre-defined channels support input peripheral events from the Peripheral Event System.
Input peripheral events must be enabled by writing a one to the corresponding bit in the Channel
Event Enable Registers (CHEERs) before peripheral events can be used to control the duty
cycle value. Each bit in the register corresponds to one channel, where bit 0 corresponds to
channel 0 and so on. Both the increase and decrease events are enabled for the corresponding
channel when a bit in the CHEER register is set.
An increase or decrease event (event_incr/event_decr) can either increase or decrease the duty
cycle value by one in a PWM period. The events are taken into account when the common timebase
counter reaches its top. The behavior is defined by the Channel Event Response Register
(CHERR). Each bit in the register corresponds to one channel, where bit 0 corresponds to channel
0 and so on. If the bit in CHERR is set to 0 (default) for a channel, the increase event will
increase the duty cycle value and the decrease event will decrease the duty cycle value for that
channel. If the bit is set to 1, the increase and decrease event will have reverse function so that
622
32142D–06/2013
ATUC64/128/256L3/4U
the increase event will decrease the duty cycle value and decrease event will increase the duty
cycle value. If both the increase event and the decrease event occur at the same time for a
channel, the duty cycle value will not be changed.
The number of channels supporting input peripheral events is device specific. Please refer to the
Module Configuration section at the end of this chapter for details.
25.6.10.2 Output Peripheral Event
The PWMA also supports one output peripheral event (event_ch0) to the Peripheral Event System.
This output peripheral event is connected to channel 0 and will be asserted when the
timebase counter reaches the duty cycle value for channel 0. This output event is always
enabled.
623
32142D–06/2013
ATUC64/128/256L3/4U
25.7 User Interface
Note: 1. The reset values are device specific. Please refer to the Module Configuration section at the end of this chapter.
Table 25-3. PWMA Register Memory Map
Offset Register Register Name Access Reset
0x00 Control Register CR Read/Write 0x00000000
0x04 Interlinked Single Value Duty Register ISDUTY Write-only 0x00000000
0x08 Interlinked Multiple Value Duty Register IMDUTY Write-only 0x00000000
0x0C Interlinked Multiple Value Channel Select IMCHSEL Write-only 0x00000000
0x10 Interrupt Enable Register IER Write-only 0x00000000
0x14 Interrupt Disable Register IDR Write-only 0x00000000
0x18 Interrupt Mask Register IMR Read-only 0x00000000
0x1C Status Register SR Read-only 0x00000000
0x20 Status Clear Register SCR Write-only 0x00000000
0x24 Parameter Register PARAMETER Read-only - (1)
0x28 Version Register VERSION Read-only - (1)
0x2C Top Value Register TVR Read/Write 0x00000000
0x30+m*0x10 Interlinked Single Value Channel Set m ISCHSETm Write-only 0x00000000
0x34+m*0x10 Channel Event Response Register m CHERRm Read/Write 0x00000000
0x38+m*0x10 Channel Event Enable Register m CHEERm Read/Write 0x00000000
0x3C+k*0x10 CWG Register CWGk Read/Write 0x00000000
0x80 Interlinked Multiple Value Duty0 Register DUTY0 Write-only 0x00000000
0x84 Interlinked Multiple Value Duty1 Register DUTY1 Write-only 0x00000000
0x88 Interlinked Multiple Value Duty2 Register DUTY2 Write-only 0x00000000
0x8C Interlinked Multiple Value Duty3 Register DUTY3 Write-only 0x00000000
624
32142D–06/2013
ATUC64/128/256L3/4U
25.7.1 Control Register
Name: CR
Access Type: Read/Write
Offset: 0x00
Reset Value: 0x00000000
• SPREAD: Spread Spectrum Limit Value
The spread spectrum limit value, together with the TOP field, defines the range for the spread spectrum counter. It is introduced
in order to achieve constant varying duty cycles on the output PWM waveforms. Refer to Section25.6.3 for more information.
• TOP: Timebase Counter Top Value
The top value for the timebase counter. The value written to this field will update the least significant 8 bits of the TVR.TOP field
in case only 8-bits resolution is required. The 4 most significant bits of TVR.TOP will be written to 0. When the TVR.TOP field is
written, this CR.TOP field will also be updated with only the least significant 8 bits of TVR.TOP field.
• TCLR: Timebase Clear
Writing a zero to this bit has no effect.
Writing a one to this bit will clear the timebase counter.
This bit is always read as zero.
• EN: Module Enable
0: The PWMA is disabled
1: The PWMA is enabled
31 30 29 28 27 26 25 24
- - - - - - - SPREAD[8]
23 22 21 20 19 18 17 16
SPREAD[7:0]
15 14 13 12 11 10 9 8
TOP
76543210
- - - - - - TCLR EN
625
32142D–06/2013
ATUC64/128/256L3/4U
25.7.2 Interlinked Single Value Duty Register
Name: ISDUTY
Access Type: Write-only
Offset: 0x04
Reset Value: 0x00000000
• DUTY: Duty Cycle Value
The duty cycle value written to this field is written simultaneously to all channels selected in the ISCHSETm register.
If the value zero is written to DUTY all affected channels will be disabled. In this state the output waveform will be zero all the
time.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
- - - - DUTY[11:8]
76543210
DUTY[7:0]
626
32142D–06/2013
ATUC64/128/256L3/4U
25.7.3 Interlinked Multiple Value Duty Register
Name: IMDUTY
Access Type: Write-only
Offset: 0x08
Reset Value: 0x00000000
• DUTYn: Duty Cycle
The value written to DUTY field n will be automatically written to the least significant 8 bits of the DUTYn register for a PWMA
channel while the most significant 4bits of the DUTYn register are unchanged. Which channel is selected for updating is defined
by the corresponding SEL field in the IMCHSEL register.
To write mulitple channels at a time with more than 8 bits of the duty cycle value, refer to DUTY3/2/1/0 registers.
If the value zero is written to DUTY all affected channels will be disabled. In this state the output waveform will be zero all the
time.
31 30 29 28 27 26 25 24
DUTY3
23 22 21 20 19 18 17 16
DUTY2
15 14 13 12 11 10 9 8
DUTY1
76543210
DUTY0
627
32142D–06/2013
ATUC64/128/256L3/4U
25.7.4 Interlinked Multiple Value Channel Select
Name: IMCHSEL
Access Type: Write-only
Offset: 0x0C
Reset Value: 0x00000000
• SELn: Channel Select
The duty cycle of the PWMA channel SELn will be updated with the value stored in the DUTYn register when IMCHSEL is
written. If SELn points to a non-implemented channel, the write will be discarded.
Note: The duty registers will be updated with the value stored in the DUTY3, DUTY2, DUTY1 and DUTY0 registers when the IMCHSEL
register is written. Synchronization takes place immediately when an IMCHSEL register is written. The duty cycle registers
will, however, not be updated until the synchronization is completed and the timebase counter reaches its top value in order to
avoid glitches. When only 8 bits duty cycle value are considered for updating, the four duty cycle values can be written to the
IMDUTY register once. This is equivalent to writing the 8 bits four duty cycle values to the four DUTY registers one by one while
the upper 4 bits remain unchanged.
31 30 29 28 27 26 25 24
SEL3
23 22 21 20 19 18 17 16
SEL2
15 14 13 12 11 10 9 8
SEL1
76543210
SEL0
628
32142D–06/2013
ATUC64/128/256L3/4U
25.7.5 Interrupt Enable Register
Name: IER
Access Type: Write-only
Offset: 0x10
Reset Value: 0x00000000
Writing a zero to a bit in this register has no effect
Writing a one to a bit in this register will set the corresponding bit in IMR.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
- - - - - READY - TOFL
629
32142D–06/2013
ATUC64/128/256L3/4U
25.7.6 Interrupt Disable Register
Name: IDR
Access Type: Write-only
Offset: 0x14
Reset Value: 0x00000000
Writing a zero to a bit in this register has no effect
Writing a one to a bit in this register will clear the corresponding bit in IMR.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
- - - - - READY - TOFL
630
32142D–06/2013
ATUC64/128/256L3/4U
25.7.7 Interrupt Mask Register
Name: IMR
Access Type: Read-only
Offset: 0x18
Reset Value: 0x00000000
0: The corresponding interrupt is disabled.
1: The corresponding interrupt is enabled.
A bit in this register is cleared when the corresponding bit in IDR is written to one.
A bit in this register is set when the corresponding bit in IER is written to one.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
- - - - - READY - TOFL
631
32142D–06/2013
ATUC64/128/256L3/4U
25.7.8 Status Register
Name: SR
Access Type: Read-only
Offset: 0x1C
Reset Value: 0x00000000
• BUSY: Interface Busy
This bit is automatically cleared when the interface is no longer busy.
This bit is set when the user interface is busy and will not respond to new write operations.
• READY: Interface Ready
This bit is cleared by writing a one to the corresponding bit in the SCR register.
This bit is set when the BUSY bit has a 1-to-0 transition.
• TOFL: Timebase Overflow
This bit is cleared by writing a one to corresponding bit in the SCR register.
This bit is set when the timebase counter has wrapped at its top value.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
- - - - BUSY READY - TOFL
632
32142D–06/2013
ATUC64/128/256L3/4U
25.7.9 Status Clear Register
Name: SCR
Access Type: Write-only
Offset: 0x20
Reset Value: 0x00000000
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will clear the corresponding bit in SR and the corresponding interrupt request.
This register always reads as zero.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 1 10 9 8
--------
76543210
- - - - - READY - TOFL
633
32142D–06/2013
ATUC64/128/256L3/4U
25.7.10 Parameter Register
Name: PARAMETER
Access Type: Read-only
Offset: 0x24
Reset Value: -
• CHANNELS: Channels Implemented
This field contains the number of channels implemented on the device.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
CHANNELS
634
32142D–06/2013
ATUC64/128/256L3/4U
25.7.11 Version Register
Name: VERSION
Access Type: Read-only
Offset: 0x28
Reset Value: -
• VARIANT: Variant Number
Reserved. No functionality associated.
• VERSION: Version Number
Version number of the module. No functionality associated.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
- - - - VARIANT
15 14 13 12 11 10 9 8
- - - - VERSION[11:8]
76543210
VERSION[7:0]
635
32142D–06/2013
ATUC64/128/256L3/4U
25.7.12 Top Value Register
Name: TVR
Access Type: Read/Write
Offset: 0x2C
Reset Value: 0x00000000
• TOP: Timebase Counter Top Value
The top value for the timebase counter. The value written to the CR.TOP field will automatically be written to the 8 least
significant bits of this field while the 4 most significant bits will be 0. When this register is written, it will also automatically update
the CR.TOP field with the 8 least significant bits.
The effective top value of the timebase counter is defined by both TVR.TOP and the CR.SPREAD. Refer to Section25.6.2 for
more information.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
- - - - TOP[11:8]
76543210
TOP[7:0]
636
32142D–06/2013
ATUC64/128/256L3/4U
25.7.13 Interlinked Single Value Channel Set
Name: ISCHSETm
Access Type: Write-only
Offset: 0x30+m*0x10
Reset Value: 0x00000000
• SET: Single Value Channel Set
If the bit n in SET is one, the duty cycle of PWMA channel n will be updated with the value written to ISDUTY.
If more than one ISCHSET register is present, ISCHSET0 controls channels 31 to 0 and ISCHSET1 controls channels 63 to 32.
Note: The duty registers will be updated with the value stored in the ISDUTY register when any ISCHSETm register is written. Synchronization
takes place immediately when an ISCHSET register is written. The duty cycle registers will, however, not be
updated until the synchronization is completed and the timebase counter reaches its top value in order to avoid glitches.
31 30 29 28 27 26 25 24
SET
23 22 21 20 19 18 17 16
SET
15 14 13 12 11 10 9 8
SET
76543210
SET
637
32142D–06/2013
ATUC64/128/256L3/4U
25.7.14 Channel Event Response Register
Name: CHERRm
Access Type: Read/Write
Offset: 0x34+m*0x10
Reset Value: 0x00000000
• CHER: Channel Event Response
0: The increase event will increase the duty cycle value by one in a PWM period for the corresponding channel and the
decrease event will decrease the duty cycle value by one.
1: The increase event will decrease the duty cycle value by one in a PWM period for the corresponding channel and the
decrease event will increase the duty cycle value by one.
The events are taken into account when the common timebase counter reaches its top.
If more than one CHERR register is present, CHERR0 controls channels 31-0 and CHERR1 controls channels 64-32 and so on.
31 30 29 28 27 26 25 24
CHER
23 22 21 20 19 18 17 16
CHER
15 14 13 12 11 10 9 8
CHER
76543210
CHER
638
32142D–06/2013
ATUC64/128/256L3/4U
25.7.15 Channel Event Enable Register
Name: CHEERm
Access Type: Read/Write
Offset: 0x38+m*0x10
Reset Value: 0x00000000
• CHEE: Channel Event Enable
0: The input peripheral event for the corresponding channel is disabled.
1: The input peripheral event for the corresponding channel is enabled.
Both increase and decrease events for channel n are enabled if bit n is one.
If more than one CHEER register is present, CHEER0 controls channels 31-0 and CHEER1 controls channels 64-32 and so on.
31 30 29 28 27 26 25 24
CHEE
23 22 21 20 19 18 17 16
CHEE
15 14 13 12 11 10 9 8
CHEE
76543210
CHEE
639
32142D–06/2013
ATUC64/128/256L3/4U
25.7.16 Composite Waveform Generation
Name: CWG
Access Type: Read/Write
Offset: 0x3C+k*0x10
Reset Value: 0x00000000
• XOR: Pair Waveform XOR’ed
If the bit n in XOR field is one, the pair of PWMA output waveforms will be XORed before output. The even number output will be
the XOR’ed output and the odd number output will be reverse of it. For example, if bit 0 in XOR is one, the pair of PWMA output
waveforms for channel 0 and 1 will be XORed together.
If bit n in XOR is zero, normal waveforms are output for that pair. Note that
If more than one CWG register is present, CWG0 controls the first 32 pairs, corresponding to channels 63 downto 0, and CWG1
controls the second 32 pairs, corresponding to channels 127 downto 64.
31 30 29 28 27 26 25 24
XOR
23 22 21 20 19 18 17 16
XOR
15 14 13 12 11 10 9 8
XOR
76543210
XOR
640
32142D–06/2013
ATUC64/128/256L3/4U
25.7.17 Interlinked Multiple Value Duty0/1/2/3 Register
Name: DUTY0/1/2/3
Access Type: Write-only
Offset: 0x80-0x8C
Reset Value: 0x00000000
These registers allows up to 4 channels to be updated with a common 12-bits duty cycle value at a time. They are the
extension of the IMDUTY register which only supports updating the least significant 8 bits of the duty registers for up to 4
channels.
• DUTY: Duty Cycle Value
The duty cycle value written to this field will be updated to the channel specified by IMCHSEL.
DUTY0 is specified by IMCHSEL.SEL0, DUTY1 is specified by IMCHSEL.SEL1, and so on.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
- - - - DUTY[11:8]
76543210
DUTY[7:0]
641
32142D–06/2013
ATUC64/128/256L3/4U
25.8 Module Configuration
The specific configuration for each PWMA instance is listed in the following tables. The module
bus clocks listed here are connected to the system bus clocks. Please refer to the Power Manager
chapter for details.
Table 25-4. PWMA Configuration
Feature PWMA
Number of PWM channels 36
Channels supporting incoming peripheral events 0, 6, 8, 9, 11, 14, 19, and 20
PWMA channels with Open Drain mode 21, 27, and 28
Table 25-5. PWMA Clocks
Clock Name Descripton
CLK_PWMA Clock for the PWMA bus interface
GCLK The generic clock used for the PWMA is GCLK3
Table 25-6. Register Reset Values
Register Reset Value
VERSION 0x00000201
PARAMETER 0x00000024
642
32142D–06/2013
ATUC64/128/256L3/4U
26. Timer/Counter (TC)
Rev: 2.2.3.1.3
26.1 Features
• Three 16-bit Timer Counter channels
• A wide range of functions including:
– Frequency measurement
– Event counting
– Interval measurement
– Pulse generation
– Delay timing
– Pulse width modulation
– Up/down capabilities
• Each channel is user-configurable and contains:
– Three external clock inputs
– Five internal clock inputs
– Two multi-purpose input/output signals
• Internal interrupt signal
• Two global registers that act on all three TC channels
• Peripheral event input on all A lines in capture mode
26.2 Overview
The Timer Counter (TC) includes three identical 16-bit Timer Counter channels.
Each channel can be independently programmed to perform a wide range of functions including
frequency measurement, event counting, interval measurement, pulse generation, delay timing,
and pulse width modulation.
Each channel has three external clock inputs, five internal clock inputs, and two multi-purpose
input/output signals which can be configured by the user. Each channel drives an internal interrupt
signal which can be programmed to generate processor interrupts.
The TC block has two global registers which act upon all three TC channels.
The Block Control Register (BCR) allows the three channels to be started simultaneously with
the same instruction.
The Block Mode Register (BMR) defines the external clock inputs for each channel, allowing
them to be chained.
643
32142D–06/2013
ATUC64/128/256L3/4U
26.3 Block Diagram
Figure 26-1. TC Block Diagram
26.4 I/O Lines Description
26.5 Product Dependencies
In order to use this module, other parts of the system must be configured correctly, as described
below.
26.5.1 I/O Lines
The pins used for interfacing the compliant external devices may be multiplexed with I/O lines.
The user must first program the I/O Controller to assign the TC pins to their peripheral functions.
I/O
Controller
TC2XC2S
INT0
INT1
INT2
TIOA0
TIOA1
TIOA2
TIOB0
TIOB1
TIOB2
XC2
TCLK0
TCLK1
TCLK2
TCLK0
TCLK1
TCLK2
TCLK0
TCLK1
TCLK2
TIOA1
TIOA2
TIOA0
TIOA2
TIOA1
Interrupt
Controller
CLK0
CLK1
CLK2
A0
B0
A1
B1
A2
B2
Timer Count er
TIOB
TIOA
TIOB
SYNC
TIMER_CLOCK1
TIOA
SYNC
SYNC
TIOA
TIOB
TIMER_CLOCK2
TIMER_CLOCK3
TIMER_CLOCK4
TIMER_CLOCK5
XC1
XC0
XC0
XC2
XC1
XC0
XC1
XC2
Timer/Counter
Channel 2
Timer/Counter
Channel 1
Timer/Counter
Channel 0
TC1XC1S
TC0XC0S
TIOA0
Table 26-1. I/O Lines Description
Pin Name Description Type
CLK0-CLK2 External Clock Input Input
A0-A2 I/O Line A Input/Output
B0-B2 I/O Line B Input/Output
644
32142D–06/2013
ATUC64/128/256L3/4U
When using the TIOA lines as inputs the user must make sure that no peripheral events are generated
on the line. Refer to the Peripheral Event System chapter for details.
26.5.2 Power Management
If the CPU enters a sleep mode that disables clocks used by the TC, the TC will stop functioning
and resume operation after the system wakes up from sleep mode.
26.5.3 Clocks
The clock for the TC bus interface (CLK_TC) is generated by the Power Manager. This clock is
enabled at reset, and can be disabled in the Power Manager. It is recommended to disable the
TC before disabling the clock, to avoid freezing the TC in an undefined state.
26.5.4 Interrupts
The TC interrupt request line is connected to the interrupt controller. Using the TC interrupt
requires the interrupt controller to be programmed first.
26.5.5 Peripheral Events
The TC peripheral events are connected via the Peripheral Event System. Refer to the Peripheral
Event System chapter for details.
26.5.6 Debug Operation
The Timer Counter clocks are frozen during debug operation, unless the OCD system keeps
peripherals running in debug operation.
26.6 Functional Description
26.6.1 TC Description
The three channels of the Timer Counter are independent and identical in operation. The registers
for channel programming are listed in Figure 26-3 on page 659.
26.6.1.1 Channel I/O Signals
As described in Figure 26-1 on page 643, each Channel has the following I/O signals.
26.6.1.2 16-bit counter
Each channel is organized around a 16-bit counter. The value of the counter is incremented at
each positive edge of the selected clock. When the counter has reached the value 0xFFFF and
passes to 0x0000, an overflow occurs and the Counter Overflow Status bit in the Channel n Status
Register (SRn.COVFS) is set.
Table 26-2. Channel I/O Signals Description
Block/Channel Signal Name Description
Channel Signal
XC0, XC1, XC2 External Clock Inputs
TIOA Capture mode: Timer Counter Input
Waveform mode: Timer Counter Output
TIOB Capture mode: Timer Counter Input
Waveform mode: Timer Counter Input/Output
INT Interrupt Signal Output
SYNC Synchronization Input Signal
645
32142D–06/2013
ATUC64/128/256L3/4U
The current value of the counter is accessible in real time by reading the Channel n Counter
Value Register (CVn). The counter can be reset by a trigger. In this case, the counter value
passes to 0x0000 on the next valid edge of the selected clock.
26.6.1.3 Clock selection
At block level, input clock signals of each channel can either be connected to the external inputs
TCLK0, TCLK1 or TCLK2, or be connected to the configurable I/O signals A0, A1 or A2 for
chaining by writing to the BMR register. See Figure 26-2 on page 645.
Each channel can independently select an internal or external clock source for its counter:
• Internal clock signals: TIMER_CLOCK1, TIMER_CLOCK2, TIMER_CLOCK3,
TIMER_CLOCK4, TIMER_CLOCK5. See the Module Configuration Chapter for details about
the connection of these clock sources.
• External clock signals: XC0, XC1 or XC2. See the Module Configuration Chapter for details
about the connection of these clock sources.
This selection is made by the Clock Selection field in the Channel n Mode Register
(CMRn.TCCLKS).
The selected clock can be inverted with the Clock Invert bit in CMRn (CMRn.CLKI). This allows
counting on the opposite edges of the clock.
The burst function allows the clock to be validated when an external signal is high. The Burst
Signal Selection field in the CMRn register (CMRn.BURST) defines this signal.
Note: In all cases, if an external clock is used, the duration of each of its levels must be longer than the
CLK_TC period. The external clock frequency must be at least 2.5 times lower than the CLK_TC.
Figure 26-2. Clock Selection
TIMER_CLOCK5
XC2
TCCLKS
CLKI
BURST
1
Selected
Clock
XC1
XC0
TIMER_CLOCK4
TIMER_CLOCK3
TIMER_CLOCK2
TIMER_CLOCK1
646
32142D–06/2013
ATUC64/128/256L3/4U
26.6.1.4 Clock control
The clock of each counter can be controlled in two different ways: it can be enabled/disabled
and started/stopped. See Figure 26-3 on page 646.
• The clock can be enabled or disabled by the user by writing to the Counter Clock
Enable/Disable Command bits in the Channel n Clock Control Register (CCRn.CLKEN and
CCRn.CLKDIS). In Capture mode it can be disabled by an RB load event if the Counter Clock
Disable with RB Loading bit in CMRn is written to one (CMRn.LDBDIS). In Waveform mode,
it can be disabled by an RC Compare event if the Counter Clock Disable with RC Compare
bit in CMRn is written to one (CMRn.CPCDIS). When disabled, the start or the stop actions
have no effect: only a CLKEN command in CCRn can re-enable the clock. When the clock is
enabled, the Clock Enabling Status bit is set in SRn (SRn.CLKSTA).
• The clock can also be started or stopped: a trigger (software, synchro, external or compare)
always starts the clock. In Capture mode the clock can be stopped by an RB load event if the
Counter Clock Stopped with RB Loading bit in CMRn is written to one (CMRn.LDBSTOP). In
Waveform mode it can be stopped by an RC compare event if the Counter Clock Stopped
with RC Compare bit in CMRn is written to one (CMRn.CPCSTOP). The start and the stop
commands have effect only if the clock is enabled.
Figure 26-3. Clock Control
26.6.1.5 TC operating modes
Each channel can independently operate in two different modes:
• Capture mode provides measurement on signals.
• Waveform mode provides wave generation.
The TC operating mode selection is done by writing to the Wave bit in the CCRn register
(CCRn.WAVE).
In Capture mode, TIOA and TIOB are configured as inputs.
Q S
R
S
R
Q
CLKSTA CLKEN CLKDIS
Stop
Event
Disable
Counter
Clock
Selected
Clock Trigger
Event
647
32142D–06/2013
ATUC64/128/256L3/4U
In Waveform mode, TIOA is always configured to be an output and TIOB is an output if it is not
selected to be the external trigger.
26.6.1.6 Trigger
A trigger resets the counter and starts the counter clock. Three types of triggers are common to
both modes, and a fourth external trigger is available to each mode.
The following triggers are common to both modes:
• Software Trigger: each channel has a software trigger, available by writing a one to the
Software Trigger Command bit in CCRn (CCRn.SWTRG).
• SYNC: each channel has a synchronization signal SYNC. When asserted, this signal has the
same effect as a software trigger. The SYNC signals of all channels are asserted
simultaneously by writing a one to the Synchro Command bit in the BCR register
(BCR.SYNC).
• Compare RC Trigger: RC is implemented in each channel and can provide a trigger when the
counter value matches the RC value if the RC Compare Trigger Enable bit in CMRn
(CMRn.CPCTRG) is written to one.
The channel can also be configured to have an external trigger. In Capture mode, the external
trigger signal can be selected between TIOA and TIOB. In Waveform mode, an external event
can be programmed to be one of the following signals: TIOB, XC0, XC1, or XC2. This external
event can then be programmed to perform a trigger by writing a one to the External Event Trigger
Enable bit in CMRn (CMRn.ENETRG).
If an external trigger is used, the duration of the pulses must be longer than the CLK_TC period
in order to be detected.
Regardless of the trigger used, it will be taken into account at the following active edge of the
selected clock. This means that the counter value can be read differently from zero just after a
trigger, especially when a low frequency signal is selected as the clock.
26.6.1.7 Peripheral events on TIOA inputs
The TIOA input lines are ored internally with peripheral events from the Peripheral Event System.
To capture using events the user must ensure that the corresponding pin functions for the
TIOA line are disabled. When capturing on the external TIOA pin the user must ensure that no
peripheral events are generated on this pin.
26.6.2 Capture Operating Mode
This mode is entered by writing a zero to the CMRn.WAVE bit.
Capture mode allows the TC channel to perform measurements such as pulse timing, frequency,
period, duty cycle and phase on TIOA and TIOB signals which are considered as
inputs.
Figure 26-4 on page 649 shows the configuration of the TC channel when programmed in Capture
mode.
26.6.2.1 Capture registers A and B
Registers A and B (RA and RB) are used as capture registers. This means that they can be
loaded with the counter value when a programmable event occurs on the signal TIOA.
648
32142D–06/2013
ATUC64/128/256L3/4U
The RA Loading Selection field in CMRn (CMRn.LDRA) defines the TIOA edge for the loading of
the RA register, and the RB Loading Selection field in CMRn (CMRn.LDRB) defines the TIOA
edge for the loading of the RB register.
RA is loaded only if it has not been loaded since the last trigger or if RB has been loaded since
the last loading of RA.
RB is loaded only if RA has been loaded since the last trigger or the last loading of RB.
Loading RA or RB before the read of the last value loaded sets the Load Overrun Status bit in
SRn (SRn.LOVRS). In this case, the old value is overwritten.
26.6.2.2 Trigger conditions
In addition to the SYNC signal, the software trigger and the RC compare trigger, an external trigger
can be defined.
The TIOA or TIOB External Trigger Selection bit in CMRn (CMRn.ABETRG) selects TIOA or
TIOB input signal as an external trigger. The External Trigger Edge Selection bit in CMRn
(CMRn.ETREDG) defines the edge (rising, falling or both) detected to generate an external trigger.
If CMRn.ETRGEDG is zero (none), the external trigger is disabled.
649
32142D–06/2013
ATUC64/128/256L3/4U
Figure 26-4. Capture Mode TIMER_CLOCK1 XC0
XC1
XC2
TCCLKS
CLKI
Q S
R
S
R
Q
CLKSTA CLKEN CLKDIS
BURST
TIOB
Capture
Register A Compare RC =
16-bit
Counter
ABETRG
SWTRG
ETRGEDG CPCTRG
IMR
Trig
LDRBS
LDRAS
ETRGS
SR
LOVRS
COVFS
SYNC
1
MTIOB
TIOA
MTIOA
LDRA
LDBSTOP
If RA is not Loaded
or RB is Loaded If RA is Loaded
LDBDIS
CPCS
INT
Edge
Detector
LDRB
CLK OVF
RESET
Timer/Counter Channel
Edge
Detector
Edge
Detector
Capture
Register B
Register C
TIMER_CLOCK2
TIMER_CLOCK3
TIMER_CLOCK4
TIMER_CLOCK5
650
32142D–06/2013
ATUC64/128/256L3/4U
26.6.3 Waveform Operating Mode
Waveform operating mode is entered by writing a one to the CMRn.WAVE bit.
In Waveform operating mode the TC channel generates one or two PWM signals with the same
frequency and independently programmable duty cycles, or generates different types of oneshot
or repetitive pulses.
In this mode, TIOA is configured as an output and TIOB is defined as an output if it is not used
as an external event.
Figure 26-5 on page 651 shows the configuration of the TC channel when programmed in
Waveform operating mode.
26.6.3.1 Waveform selection
Depending on the Waveform Selection field in CMRn (CMRn.WAVSEL), the behavior of CVn
varies.
With any selection, RA, RB and RC can all be used as compare registers.
RA Compare is used to control the TIOA output, RB Compare is used to control the TIOB output
(if correctly configured) and RC Compare is used to control TIOA and/or TIOB outputs.
651
32142D–06/2013
ATUC64/128/256L3/4U
Figure 26-5. Waveform Mode TCCLKS CLKI Q S
R
S
R
Q
CLKSTA CLKEN CLKDIS
CPCDIS
BURST
TIOB
Register A
Compare RC =
CPCSTOP
16-bit
Counter
EEVT
EEVTEDG
SYNC
SWTRG
ENETRG
WAVSEL
IMR
Trig
ACPC
ACPA
AEEVT
ASWTRG
BCPC
BCPB
BEEVT
BSWTRG
TIOA
MTIOA
TIOB
MTIOB
CPAS
COVFS
ETRGS
SR
CPCS
CPBS
CLK
OVF
RESET
Output Contr oller O utput Cont r oller
INT
1
Edge
Detector
Timer/Counter Channel
TIMER_CLOCK1
XC0
XC1
XC2
WAVSEL
Register B Register C
Compare RB = Compare RA =
TIMER_CLOCK2
TIMER_CLOCK3
TIMER_CLOCK4
TIMER_CLOCK5
652
32142D–06/2013
ATUC64/128/256L3/4U
26.6.3.2 WAVSEL = 0
When CMRn.WAVSEL is zero, the value of CVn is incremented from 0 to 0xFFFF. Once
0xFFFF has been reached, the value of CVn is reset. Incrementation of CVn starts again and
the cycle continues. See Figure 26-6 on page 652.
An external event trigger or a software trigger can reset the value of CVn. It is important to note
that the trigger may occur at any time. See Figure 26-7 on page 653.
RC Compare cannot be programmed to generate a trigger in this configuration. At the same
time, RC Compare can stop the counter clock (CMRn.CPCSTOP = 1) and/or disable the counter
clock (CMRn.CPCDIS = 1).
Figure 26-6. WAVSEL= 0 Without Trigger
Time
Counter Value
RC
RB
RA
TIOB
TIOA
Counter cleared by compare match with
0xFFFF
0xFFFF
Waveform Examples
653
32142D–06/2013
ATUC64/128/256L3/4U
Figure 26-7. WAVSEL= 0 With Trigger
26.6.3.3 WAVSEL = 2
When CMRn.WAVSEL is two, the value of CVn is incremented from zero to the value of RC,
then automatically reset on a RC Compare. Once the value of CVn has been reset, it is then
incremented and so on. See Figure 26-8 on page 654.
It is important to note that CVn can be reset at any time by an external event or a software trigger
if both are programmed correctly. See Figure 26-9 on page 654.
In addition, RC Compare can stop the counter clock (CMRn.CPCSTOP) and/or disable the
counter clock (CMRn.CPCDIS = 1).
Time
Counter Value
RC
RB
RA
TIOB
TIOA
Counter cleared by compare match with 0xFFFF
0xFFFF
Waveform Examples
Counter cleared by trigger
654
32142D–06/2013
ATUC64/128/256L3/4U
Figure 26-8. WAVSEL = 2 Without Trigger
Figure 26-9. WAVSEL = 2 With Trigger
26.6.3.4 WAVSEL = 1
When CMRn.WAVSEL is one, the value of CVn is incremented from 0 to 0xFFFF. Once 0xFFFF
is reached, the value of CVn is decremented to 0, then re-incremented to 0xFFFF and so on.
See Figure 26-10 on page 655.
Time
Counter Value
RC
RB
RA
TIOB
TIOA
Counter cleared by compare match
with RC
0xFFFF
Waveform Examples
Time
Counter Value
RC
RB
RA
TIOB
TIOA
Counter cleared by compare match with RC
0xFFFF
Waveform Examples
Counter cleared by trigger
655
32142D–06/2013
ATUC64/128/256L3/4U
A trigger such as an external event or a software trigger can modify CVn at any time. If a trigger
occurs while CVn is incrementing, CVn then decrements. If a trigger is received while CVn is
decrementing, CVn then increments. See Figure 26-11 on page 655.
RC Compare cannot be programmed to generate a trigger in this configuration.
At the same time, RC Compare can stop the counter clock (CMRn.CPCSTOP = 1) and/or disable
the counter clock (CMRn.CPCDIS = 1).
Figure 26-10. WAVSEL = 1 Without Trigger
Figure 26-11. WAVSEL = 1 With Trigger
Time
Counter Value
RC
RB
RA
TIOB
TIOA
Counter decremented by compare match
with 0xFFFF
0xFFFF
Waveform Examples
Time
Counter Value
TIOB
TIOA
Counter decremented by compare match with 0xFFFF
0xFFFF
Waveform Examples
Counter decremented by trigger
RC
RB
RA
Counter incremented by trigger
656
32142D–06/2013
ATUC64/128/256L3/4U
26.6.3.5 WAVSEL = 3
When CMRn.WAVSEL is three, the value of CVn is incremented from zero to RC. Once RC is
reached, the value of CVn is decremented to zero, then re-incremented to RC and so on. See
Figure 26-12 on page 656.
A trigger such as an external event or a software trigger can modify CVn at any time. If a trigger
occurs while CVn is incrementing, CVn then decrements. If a trigger is received while CVn is
decrementing, CVn then increments. See Figure 26-13 on page 657.
RC Compare can stop the counter clock (CMRn.CPCSTOP = 1) and/or disable the counter clock
(CMRn.CPCDIS = 1).
Figure 26-12. WAVSEL = 3 Without Trigger
Time
Counter Value
RC
RB
RA
TIOB
TIOA
Counter cleared by compare match with RC
0xFFFF
Waveform Examples
657
32142D–06/2013
ATUC64/128/256L3/4U
Figure 26-13. WAVSEL = 3 With Trigger
26.6.3.6 External event/trigger conditions
An external event can be programmed to be detected on one of the clock sources (XC0, XC1,
XC2) or TIOB. The external event selected can then be used as a trigger.
The External Event Selection field in CMRn (CMRn.EEVT) selects the external trigger. The
External Event Edge Selection field in CMRn (CMRn.EEVTEDG) defines the trigger edge for
each of the possible external triggers (rising, falling or both). If CMRn.EEVTEDG is written to
zero, no external event is defined.
If TIOB is defined as an external event signal (CMRn.EEVT = 0), TIOB is no longer used as an
output and the compare register B is not used to generate waveforms and subsequently no
IRQs. In this case the TC channel can only generate a waveform on TIOA.
When an external event is defined, it can be used as a trigger by writing a one to the
CMRn.ENETRG bit.
As in Capture mode, the SYNC signal and the software trigger are also available as triggers. RC
Compare can also be used as a trigger depending on the CMRn.WAVSEL field.
26.6.3.7 Output controller
The output controller defines the output level changes on TIOA and TIOB following an event.
TIOB control is used only if TIOB is defined as output (not as an external event).
The following events control TIOA and TIOB:
• software trigger
• external event
• RC compare
RA compare controls TIOA and RB compare controls TIOB. Each of these events can be programmed
to set, clear or toggle the output as defined in the following fields in CMRn:
• RC Compare Effect on TIOB (CMRn.BCPC)
Time
Counter Value
TIOB
TIOA
Counter decremented by compare match
with RC
0xFFFF
Waveform Examples
RC
RB
RA
Counter decremented by trigger
Counter incremented by trigger
658
32142D–06/2013
ATUC64/128/256L3/4U
• RB Compare Effect on TIOB (CMRn.BCPB)
• RC Compare Effect on TIOA (CMRn.ACPC)
• RA Compare Effect on TIOA (CMRn.ACPA)
659
32142D–06/2013
ATUC64/128/256L3/4U
26.7 User Interface
Table 26-3. TC Register Memory Map
Offset Register Register Name Access Reset
0x00 Channel 0 Control Register CCR0 Write-only 0x00000000
0x04 Channel 0 Mode Register CMR0 Read/Write 0x00000000
0x10 Channel 0 Counter Value CV0 Read-only 0x00000000
0x14 Channel 0 Register A RA0 Read/Write(1) 0x00000000
0x18 Channel 0 Register B RB0 Read/Write(1) 0x00000000
0x1C Channel 0 Register C RC0 Read/Write 0x00000000
0x20 Channel 0 Status Register SR0 Read-only 0x00000000
0x24 Interrupt Enable Register IER0 Write-only 0x00000000
0x28 Channel 0 Interrupt Disable Register IDR0 Write-only 0x00000000
0x2C Channel 0 Interrupt Mask Register IMR0 Read-only 0x00000000
0x40 Channel 1 Control Register CCR1 Write-only 0x00000000
0x44 Channel 1 Mode Register CMR1 Read/Write 0x00000000
0x50 Channel 1 Counter Value CV1 Read-only 0x00000000
0x54 Channel 1 Register A RA1 Read/Write(1) 0x00000000
0x58 Channel 1 Register B RB1 Read/Write(1) 0x00000000
0x5C Channel 1 Register C RC1 Read/Write 0x00000000
0x60 Channel 1 Status Register SR1 Read-only 0x00000000
0x64 Channel 1 Interrupt Enable Register IER1 Write-only 0x00000000
0x68 Channel 1 Interrupt Disable Register IDR1 Write-only 0x00000000
0x6C Channel 1 Interrupt Mask Register IMR1 Read-only 0x00000000
0x80 Channel 2 Control Register CCR2 Write-only 0x00000000
0x84 Channel 2 Mode Register CMR2 Read/Write 0x00000000
0x90 Channel 2 Counter Value CV2 Read-only 0x00000000
0x94 Channel 2 Register A RA2 Read/Write(1) 0x00000000
0x98 Channel 2 Register B RB2 Read/Write(1) 0x00000000
0x9C Channel 2 Register C RC2 Read/Write 0x00000000
0xA0 Channel 2 Status Register SR2 Read-only 0x00000000
0xA4 Channel 2 Interrupt Enable Register IER2 Write-only 0x00000000
0xA8 Channel 2 Interrupt Disable Register IDR2 Write-only 0x00000000
0xAC Channel 2 Interrupt Mask Register IMR2 Read-only 0x00000000
0xC0 Block Control Register BCR Write-only 0x00000000
0xC4 Block Mode Register BMR Read/Write 0x00000000
0xF8 Features Register FEATURES Read-only -(2)
0xFC Version Register VERSION Read-only -(2)
660
32142D–06/2013
ATUC64/128/256L3/4U
Notes: 1. Read-only if CMRn.WAVE is zero.
2. The reset values are device specific. Please refer to the Module Configuration section at the
end of this chapter.
661
32142D–06/2013
ATUC64/128/256L3/4U
26.7.1 Channel Control Register
Name: CCR
Access Type: Write-only
Offset: 0x00 + n * 0x40
Reset Value: 0x00000000
• SWTRG: Software Trigger Command
1: Writing a one to this bit will perform a software trigger: the counter is reset and the clock is started.
0: Writing a zero to this bit has no effect.
• CLKDIS: Counter Clock Disable Command
1: Writing a one to this bit will disable the clock.
0: Writing a zero to this bit has no effect.
• CLKEN: Counter Clock Enable Command
1: Writing a one to this bit will enable the clock if CLKDIS is not one.
0: Writing a zero to this bit has no effect.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
- - - - - SWTRG CLKDIS CLKEN
662
32142D–06/2013
ATUC64/128/256L3/4U
26.7.2 Channel Mode Register: Capture Mode
Name: CMR
Access Type: Read/Write
Offset: 0x04 + n * 0x40
Reset Value: 0x00000000
• LDRB: RB Loading Selection
• LDRA: RA Loading Selection
• WAVE
1: Capture mode is disabled (Waveform mode is enabled).
0: Capture mode is enabled.
• CPCTRG: RC Compare Trigger Enable
1: RC Compare resets the counter and starts the counter clock.
0: RC Compare has no effect on the counter and its clock.
• ABETRG: TIOA or TIOB External Trigger Selection
1: TIOA is used as an external trigger.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
- - - - LDRB LDRA
15 14 13 12 11 10 9 8
WAVE CPCTRG - - - ABETRG ETRGEDG
76543210
LDBDIS LDBSTOP BURST CLKI TCCLKS
LDRB Edge
0 none
1 rising edge of TIOA
2 falling edge of TIOA
3 each edge of TIOA
LDRA Edge
0 none
1 rising edge of TIOA
2 falling edge of TIOA
3 each edge of TIOA
663
32142D–06/2013
ATUC64/128/256L3/4U
0: TIOB is used as an external trigger.
• ETRGEDG: External Trigger Edge Selection
• LDBDIS: Counter Clock Disable with RB Loading
1: Counter clock is disabled when RB loading occurs.
0: Counter clock is not disabled when RB loading occurs.
• LDBSTOP: Counter Clock Stopped with RB Loading
1: Counter clock is stopped when RB loading occurs.
0: Counter clock is not stopped when RB loading occurs.
• BURST: Burst Signal Selection
• CLKI: Clock Invert
1: The counter is incremented on falling edge of the clock.
0: The counter is incremented on rising edge of the clock.
• TCCLKS: Clock Selection
ETRGEDG Edge
0 none
1 rising edge
2 falling edge
3 each edge
BURST Burst Signal Selection
0 The clock is not gated by an external signal
1 XC0 is ANDed with the selected clock
2 XC1 is ANDed with the selected clock
3 XC2 is ANDed with the selected clock
TCCLKS Clock Selected
0 TIMER_CLOCK1
1 TIMER_CLOCK2
2 TIMER_CLOCK3
3 TIMER_CLOCK4
4 TIMER_CLOCK5
5 XC0
6 XC1
7 XC2
664
32142D–06/2013
ATUC64/128/256L3/4U
26.7.3 Channel Mode Register: Waveform Mode
Name: CMR
Access Type: Read/Write
Offset: 0x04 + n * 0x40
Reset Value: 0x00000000
• BSWTRG: Software Trigger Effect on TIOB
• BEEVT: External Event Effect on TIOB
31 30 29 28 27 26 25 24
BSWTRG BEEVT BCPC BCPB
23 22 21 20 19 18 17 16
ASWTRG AEEVT ACPC ACPA
15 14 13 12 11 10 9 8
WAVE WAVSEL ENETRG EEVT EEVTEDG
76543210
CPCDIS CPCSTOP BURST CLKI TCCLKS
BSWTRG Effect
0 none
1 set
2 clear
3 toggle
BEEVT Effect
0 none
1 set
2 clear
3 toggle
665
32142D–06/2013
ATUC64/128/256L3/4U
• BCPC: RC Compare Effect on TIOB
• BCPB: RB Compare Effect on TIOB
• ASWTRG: Software Trigger Effect on TIOA
• AEEVT: External Event Effect on TIOA
• ACPC: RC Compare Effect on TIOA
BCPC Effect
0 none
1 set
2 clear
3 toggle
BCPB Effect
0 none
1 set
2 clear
3 toggle
ASWTRG Effect
0 none
1 set
2 clear
3 toggle
AEEVT Effect
0 none
1 set
2 clear
3 toggle
ACPC Effect
0 none
1 set
2 clear
3 toggle
666
32142D–06/2013
ATUC64/128/256L3/4U
• ACPA: RA Compare Effect on TIOA
• WAVE
1: Waveform mode is enabled.
0: Waveform mode is disabled (Capture mode is enabled).
• WAVSEL: Waveform Selection
• ENETRG: External Event Trigger Enable
1: The external event resets the counter and starts the counter clock.
0: The external event has no effect on the counter and its clock. In this case, the selected external event only controls the TIOA
output.
• EEVT: External Event Selection
Note: 1. If TIOB is chosen as the external event signal, it is configured as an input and no longer generates waveforms and subsequently
no IRQs.
• EEVTEDG: External Event Edge Selection
• CPCDIS: Counter Clock Disable with RC Compare
1: Counter clock is disabled when counter reaches RC.
0: Counter clock is not disabled when counter reaches RC.
ACPA Effect
0 none
1 set
2 clear
3 toggle
WAVSEL Effect
0 UP mode without automatic trigger on RC Compare
1 UPDOWN mode without automatic trigger on RC Compare
2 UP mode with automatic trigger on RC Compare
3 UPDOWN mode with automatic trigger on RC Compare
EEVT Signal selected as external event TIOB Direction
0 TIOB input(1)
1 XC0 output
2 XC1 output
3 XC2 output
EEVTEDG Edge
0 none
1 rising edge
2 falling edge
3 each edge
667
32142D–06/2013
ATUC64/128/256L3/4U
• CPCSTOP: Counter Clock Stopped with RC Compare
1: Counter clock is stopped when counter reaches RC.
0: Counter clock is not stopped when counter reaches RC.
• BURST: Burst Signal Selection
• CLKI: Clock Invert
1: Counter is incremented on falling edge of the clock.
0: Counter is incremented on rising edge of the clock.
• TCCLKS: Clock Selection
BURST Burst Signal Selection
0 The clock is not gated by an external signal.
1 XC0 is ANDed with the selected clock.
2 XC1 is ANDed with the selected clock.
3 XC2 is ANDed with the selected clock.
TCCLKS Clock Selected
0 TIMER_CLOCK1
1 TIMER_CLOCK2
2 TIMER_CLOCK3
3 TIMER_CLOCK4
4 TIMER_CLOCK5
5 XC0
6 XC1
7 XC2
668
32142D–06/2013
ATUC64/128/256L3/4U
26.7.4 Channel Counter Value Register
Name: CV
Access Type: Read-only
Offset: 0x10 + n * 0x40
Reset Value: 0x00000000
• CV: Counter Value
CV contains the counter value in real time.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
CV[15:8]
76543210
CV[7:0]
669
32142D–06/2013
ATUC64/128/256L3/4U
26.7.5 Channel Register A
Name: RA
Access Type: Read-only if CMRn.WAVE = 0, Read/Write if CMRn.WAVE = 1
Offset: 0x14 + n * 0X40
Reset Value: 0x00000000
• RA: Register A
RA contains the Register A value in real time.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
RA[15:8]
76543210
RA[7:0]
670
32142D–06/2013
ATUC64/128/256L3/4U
26.7.6 Channel Register B
Name: RB
Access Type: Read-only if CMRn.WAVE = 0, Read/Write if CMRn.WAVE = 1
Offset: 0x18 + n * 0x40
Reset Value: 0x00000000
• RB: Register B
RB contains the Register B value in real time.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
RB[15:8]
76543210
RB[7:0]
671
32142D–06/2013
ATUC64/128/256L3/4U
26.7.7 Channel Register C
Name: RC
Access Type: Read/Write
Offset: 0x1C + n * 0x40
Reset Value: 0x00000000
• RC: Register C
RC contains the Register C value in real time.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
RC[15:8]
76543210
RC[7:0]
672
32142D–06/2013
ATUC64/128/256L3/4U
26.7.8 Channel Status Register
Name: SR
Access Type: Read-only
Offset: 0x20 + n * 0x40
Reset Value: 0x00000000
Note: Reading the Status Register will also clear the interrupt bit for the corresponding interrupts.
• MTIOB: TIOB Mirror
1: TIOB is high. If CMRn.WAVE is zero, this means that TIOB pin is high. If CMRn.WAVE is one, this means that TIOB is driven
high.
0: TIOB is low. If CMRn.WAVE is zero, this means that TIOB pin is low. If CMRn.WAVE is one, this means that TIOB is driven
low.
• MTIOA: TIOA Mirror
1: TIOA is high. If CMRn.WAVE is zero, this means that TIOA pin is high. If CMRn.WAVE is one, this means that TIOA is driven
high.
0: TIOA is low. If CMRn.WAVE is zero, this means that TIOA pin is low. If CMRn.WAVE is one, this means that TIOA is driven
low.
• CLKSTA: Clock Enabling Status
1: This bit is set when the clock is enabled.
0: This bit is cleared when the clock is disabled.
• ETRGS: External Trigger Status
1: This bit is set when an external trigger has occurred.
0: This bit is cleared when the SR register is read.
• LDRBS: RB Loading Status
1: This bit is set when an RB Load has occurred and CMRn.WAVE is zero.
0: This bit is cleared when the SR register is read.
• LDRAS: RA Loading Status
1: This bit is set when an RA Load has occurred and CMRn.WAVE is zero.
0: This bit is cleared when the SR register is read.
• CPCS: RC Compare Status
1: This bit is set when an RC Compare has occurred.
0: This bit is cleared when the SR register is read.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
- - - - - MTIOB MTIOA CLKSTA
15 14 13 12 11 10 9 8
--------
76543210
ETRGS LDRBS LDRAS CPCS CPBS CPAS LOVRS COVFS
673
32142D–06/2013
ATUC64/128/256L3/4U
• CPBS: RB Compare Status
1: This bit is set when an RB Compare has occurred and CMRn.WAVE is one.
0: This bit is cleared when the SR register is read.
• CPAS: RA Compare Status
1: This bit is set when an RA Compare has occurred and CMRn.WAVE is one.
0: This bit is cleared when the SR register is read.
• LOVRS: Load Overrun Status
1: This bit is set when RA or RB have been loaded at least twice without any read of the corresponding register and
CMRn.WAVE is zero.
0: This bit is cleared when the SR register is read.
• COVFS: Counter Overflow Status
1: This bit is set when a counter overflow has occurred.
0: This bit is cleared when the SR register is read.
674
32142D–06/2013
ATUC64/128/256L3/4U
26.7.9 Channel Interrupt Enable Register
Name: IER
Access Type: Write-only
Offset: 0x24 + n * 0x40
Reset Value: 0x00000000
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will set the corresponding bit in IMR.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
ETRGS LDRBS LDRAS CPCS CPBS CPAS LOVRS COVFS
675
32142D–06/2013
ATUC64/128/256L3/4U
26.7.10 Channel Interrupt Disable Register
Name: IDR
Access Type: Write-only
Offset: 0x28 + n * 0x40
Reset Value: 0x00000000
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will clear the corresponding bit in IMR.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
ETRGS LDRBS LDRAS CPCS CPBS CPAS LOVRS COVFS
676
32142D–06/2013
ATUC64/128/256L3/4U
26.7.11 Channel Interrupt Mask Register
Name: IMR
Access Type: Read-only
Offset: 0x2C + n * 0x40
Reset Value: 0x00000000
0: The corresponding interrupt is disabled.
1: The corresponding interrupt is enabled.
A bit in this register is cleared when the corresponding bit in IDR is written to one.
A bit in this register is set when the corresponding bit in IER is written to one.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
ETRGS LDRBS LDRAS CPCS CPBS CPAS LOVRS COVFS
677
32142D–06/2013
ATUC64/128/256L3/4U
26.7.12 Block Control Register
Name: BCR
Access Type: Write-only
Offset: 0xC0
Reset Value: 0x00000000
• SYNC: Synchro Command
1: Writing a one to this bit asserts the SYNC signal which generates a software trigger simultaneously for each of the channels.
0: Writing a zero to this bit has no effect.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
- - - - - - - SYNC
678
32142D–06/2013
ATUC64/128/256L3/4U
26.7.13 Block Mode Register
Name: BMR
Access Type: Read/Write
Offset: 0xC4
Reset Value: 0x00000000
• TC2XC2S: External Clock Signal 2 Selection
• TC1XC1S: External Clock Signal 1 Selection
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
- - TC2XC2S TC1XC1S TC0XC0S
TC2XC2S Signal Connected to XC2
0 TCLK2
1 none
2 TIOA0
3 TIOA1
TC1XC1S Signal Connected to XC1
0 TCLK1
1 none
2 TIOA0
3 TIOA2
679
32142D–06/2013
ATUC64/128/256L3/4U
• TC0XC0S: External Clock Signal 0 Selection
TC0XC0S Signal Connected to XC0
0 TCLK0
1 none
2 TIOA1
3 TIOA2
680
32142D–06/2013
ATUC64/128/256L3/4U
26.7.14 Features Register
Name: FEATURES
Access Type: Read-only
Offset: 0xF8
Reset Value: -
• BRPBHSB: Bridge type is PB to HSB
1: Bridge type is PB to HSB.
0: Bridge type is not PB to HSB.
• UPDNIMPL: Up/down is implemented
1: Up/down counter capability is implemented.
0: Up/down counter capability is not implemented.
• CTRSIZE: Counter size
This field indicates the size of the counter in bits.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
-------
15 14 13 12 11 10 9 8
- - - - - - BRPBHSB UPDNIMPL
76543210
CTRSIZE
681
32142D–06/2013
ATUC64/128/256L3/4U
26.7.15 Version Register
Name: VERSION
Access Type: Read-only
Offset: 0xFC
Reset Value: -
• VARIANT: Variant number
Reserved. No functionality associated.
• VERSION: Version number
Version number of the module. No functionality associated.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
- - - - VARIANT
15 14 13 12 11 10 9 8
- - - - VERSION[11:8]
76543210
VERSION[7:0]
682
32142D–06/2013
ATUC64/128/256L3/4U
26.8 Module Configuration
The specific configuration for each Timer/Counter instance is listed in the following tables.The
module bus clocks listed here are connected to the system bus clocks. Please refer to the Power
Manager chapter for details.
26.8.1 Clock Connections
There are two Timer/Counter modules, TC0 and TC1, with three channels each, giving a total of
six Timer/Counter channels. Each Timer/Counter channel can independently select an internal
or external clock source for its counter:
Table 26-4. TC Bus Interface Clocks
Module name Clock Name Description
TC0 CLK_TC0 Clock for the TC0 bus interface
TC1 CLK_TC1 Clock for the TC1 bus interface
Table 26-5. Timer/Counter Clock Connections
Module Source Name Connection
TC0 Internal TIMER_CLOCK1 32 KHz oscillator clock (CLK_32K)
TIMER_CLOCK2 PBA Clock / 2
TIMER_CLOCK3 PBA Clock / 8
TIMER_CLOCK4 PBA Clock / 32
TIMER_CLOCK5 PBA Clock / 128
External XC0 See Section on page 10
XC1
XC2
TC1 Internal TIMER_CLOCK1 32 KHz oscillator clock (CLK_32K)
TIMER_CLOCK2 PBA Clock / 2
TIMER_CLOCK3 PBA Clock / 8
TIMER_CLOCK4 PBA Clock / 32
TIMER_CLOCK5 PBA Clock / 128
External XC0 See Section on page 10
XC1
XC2
683
32142D–06/2013
ATUC64/128/256L3/4U
27. Peripheral Event System
Rev: 1.0.0.1
27.1 Features
• Direct peripheral to peripheral communication system
• Allows peripherals to receive, react to, and send peripheral events without CPU intervention
• Cycle deterministic event communication
• Asynchronous interrupts allow advanced peripheral operation in low power sleep modes
27.2 Overview
Several peripheral modules can be configured to emit or respond to signals known as peripheral
events. The exact condition to trigger a peripheral event, or the action taken upon receiving a
peripheral event, is specific to each module. Peripherals that respond to peripheral events are
called peripheral event users and peripherals that emit peripheral events are called peripheral
event generators. A single module can be both a peripheral event generator and user.
The peripheral event generators and users are interconnected by a network known as the
Peripheral Event System. This allows low latency peripheral-to-peripheral signaling without CPU
intervention, and without consuming system resources such as bus or RAM bandwidth. This
offloads the CPU and system resources compared to a traditional interrupt-based software
driven system.
27.3 Peripheral Event System Block Diagram
Figure 27-1. Peripheral Event System Block Diagram
27.4 Functional Description
27.4.1 Configuration
The Peripheral Event System in the ATUC64/128/256L3/4U has a fixed mapping of peripheral
events between generators and users, as described in Table 27-1 to Table 27-4. Thus, the user
does not need to configure the interconnection between the modules, although each peripheral
event can be enabled or disabled at the generator or user side as described in the peripheral
chapter for each module.
Peripheral
Event
System
Generator
Generator
User
Generator/
User
684
32142D–06/2013
ATUC64/128/256L3/4U
Table 27-1. Peripheral Event Mapping from ACIFB to PWMA
Generator Generated Event User Effect Asynchronous
ACIFB channel 0
AC0 VINP > AC0 VINN PWMA channel 0
PWMA duty cycle value increased by one
No
AC0 VINN > AC0 VINP PWMA duty cycle value decreased by one
ACIFB channel 1
AC1 VINP > AC1 VINN PWMA channel 6
PWMA duty cycle value increased by one
AC1 VINN > AC1 VINP PWMA duty cycle value decreased by one
ACIFB channel 2
AC2 VINP > AC2 VINN PWMA channel 8
PWMA duty cycle value increased by one
AC2 VINN > AC2 VINP PWMA duty cycle value decreased by one
ACIFB channel 3
AC3 VINP > AC3 VINN PWMA channel 9
PWMA duty cycle value increased by one
AC3 VINN > AC3 VINP PWMA duty cycle value decreased by one
ACIFB channel 4
AC4 VINP > AC4 VINN PWMA channel 11
PWMA duty cycle value increased by one
AC4 VINN > AC4 VINP PWMA duty cycle value decreased by one
ACIFB channel 5
AC5 VINP > AC5 VINN PWMA channel 14
PWMA duty cycle value increased by one
AC5 VINN > AC5 VINP PWMA duty cycle value decreased by one
ACIFB channel 6
AC6 VINP > AC6 VINN PWMA channel 19
PWMA duty cycle value increased by one
AC6 VINN > AC6 VINP PWMA duty cycle value decreased by one
ACIFB channel 7
AC7 VINP > AC7 VINN PWMA channel 20
PWMA duty cycle value increased by one
AC7 VINN > AC7 VINP PWMA duty cycle value decreased by one
ACIFB channel n ACn VINN > ACn VINP CAT Automatically used by the CAT when
performing QMatrix acquisition. No
Table 27-2. Peripheral Event Mapping from GPIO to TC
Generator Generated Event User Effect Asynchronous
GPIO
Pin change on PA00-PA07
TC0
A0 capture
No
Pin change on PA08-PA15 A1 capture
Pin change on PA16-PA23 A2 capture
Pin change on PB00-PB07 TC1
A1 capture
Pin change on PB08-PB15 A2 capture
685
32142D–06/2013
ATUC64/128/256L3/4U
27.4.2 Peripheral Event Connections
Each generated peripheral event is connected to one or more users. If a peripheral event is connected
to multiple users, the peripheral event can trigger actions in multiple modules.
A peripheral event user can likewise be connected to one or more peripheral event generators. If
a peripheral event user is connected to multiple generators, the peripheral events are OR’ed
together to a single peripheral event. This means that peripheral events from either one of the
generators will result in a peripheral event to the user.
To configure a peripheral event, the peripheral event must be enabled at both the generator and
user side. Even if a generator is connected to multiple users, only the users with the peripheral
event enabled will trigger on the peripheral event.
27.4.3 Low Power Operation
As the peripheral events do not require CPU intervention, they are available in Idle mode. They
are also available in deeper sleep modes if both the generator and user remain clocked in that
mode.
Certain events are known as asynchronous peripheral events, as identified in Table 27-1 to
Table 27-4. These can be issued even when the system clock is stopped, and revive unclocked
user peripherals. The clock will be restarted for this module only, without waking the system from
sleep mode. The clock remains active only as long as required by the triggered function, before
being switched off again, and the system remains in the original sleep mode. The CPU and sysTable
27-3. Peripheral Event Mapping from AST
Generator Generated Event User Effect Asynchronous
AST
Overflow event
ACIFB
Comparison is triggered if the ACIFB.CONFn
register is written to 11 (Event Triggered Single
Measurement Mode) and the EVENTEN bit in
the ACIFB.CTRL register is written to 1.
Yes
Periodic event
Alarm event
Overflow event
ADCIFB
Conversion is triggered if the TRGMOD bit in
the ADCIFB.TRGR register is written to 111
(Peripheral Event Trigger).
Periodic event
Alarm event
Overflow event
CAT Trigger one iteration of autonomous touch
detection. Periodic event
Alarm event
Table 27-4. Peripheral Event Mapping from PWMA
Generator Generated Event User Effect Asynchronous
PWMA channel 0
Timebase counter
reaches the duty cycle
value.
ACIFB
Comparison is triggered if the ACIFB.CONFn
register is written to 11 (Event Triggered Single
Measurement Mode) and the EVENTEN bit in
the ACIFB.CTRL register is written to 1. No
ADCIFB
Conversion is triggered if the TRGMOD bit in
the ADCIFB.TRGR register is written to 111
(Peripheral Event Trigger).
686
32142D–06/2013
ATUC64/128/256L3/4U
tem will only be woken up if the user peripheral generates an interrupt as a result of the
operation. This concept is known as SleepWalking and is described in further detail in the Power
Manager chapter. Note that asynchronous peripheral events may be associated with a delay
due to the need to restart the system clock source if this has been stopped in the sleep mode.
27.5 Application Example
This application example shows how the Peripheral Event System can be used to program the
ADC Interface to perform ADC conversions at selected intervals.
Conversions of the active analog channels are started with a software or a hardware trigger.
One of the possible hardware triggers is a peripheral event trigger, allowing the Peripheral Event
System to synchronize conversion with some configured peripheral event source. From Table
27-3 and Table 27-4, it can be read that this peripheral event source can be either an AST
peripheral event, or an event from the PWM Controller. The AST can generate periodic peripheral
events at selected intervals, among other types of peripheral events. The Peripheral Event
System can then be used to set up the ADC Interface to sample an analog signal at regular
intervals.
The user must enable peripheral events in the AST and in the ADC Interface to accomplish this.
The periodic peripheral event in the AST is enabled by writing a one to the corresponding bit in
the AST Event Enable Register (EVE). To select the peripheral event trigger for the ADC Interface,
the user must write the value 0x7 to the Trigger Mode (TRGMOD) field in the ADC
Interface Trigger Register (TRGR). When the peripheral events are enabled, the AST will generate
peripheral events at the selected intervals, and the Peripheral Event System will route the
peripheral events to the ADC Interface, which will perform ADC conversions at the selected
intervals.
Figure 27-2. Application Example
Since the AST peripheral event is asynchronous, the description above will also work in sleep
modes where the ADC clock is stopped. In this case, the ADC clock (and clock source, if
needed) will be restarted during the ADC conversion. After the conversion, the ADC clock and
clock source will return to the sleep state, unless the ADC generates an interrupt, which in turn
will wake up the system. Using asynchronous interrupts thus allows ADC operation in much
lower power states than would otherwise be possible.
Peripheral
Event
System
AST ADC
Interface
Trigger
conversion
Periodic peripheral
event
687
32142D–06/2013
ATUC64/128/256L3/4U
28. Audio Bit Stream DAC (ABDACB)
Rev.: 1.0.0.0
28.1 Features
• 16 bit digital stereo DAC
• Oversampling D/A conversion architecture
– Adjustable oversampling ratio
– 3rd order Sigma-Delta D/A converters
• Digital bitstream output
• Parallel interface
• Connects to DMA for background transfer without CPU intervention
• Supported sampling frequencies
– 8000Hz, 11025Hz, 12000Hz, 16000Hz, 22050Hz, 24000Hz, 32000Hz, 44100Hz, and 48000Hz
• Supported data formats
– 32-, 24-, 20-, 18-, 16-, and 8-bit stereo format
– 16- and 8-bit compact stereo format, with left and right sample packed in the same word to
reduce data transfers
• Common mode offset control
• Volume control
28.2 Overview
The Audio Bitstream DAC (ABDACB) converts a 16-bit sample value to a digital bitstream with
an average value proportional to the sample value. Two channels are supported making the
Audio Bitstream DAC particularly suitable for stereo audio. Each channel has a pair of complementary
digital outputs, DAC and DACN, which can be connected to an external high input
impedance amplifier.
The Audio Bitstream DAC is made up of several signal processing blocks and a 3rd order Sigma
Delta D/A converter for each channel. The Sigma Delta modulator converts the parallel data to a
bitstream, while the signal processing blocks perform volume control, offset control, upsampling,
and filtering to compensate for the upsampling process. The upsampling is performed by a Cascaded
Integrator-Comb (CIC) filter, and the compensation filter is a Finite Impulse Response
(FIR) CIC compensation filter.
28.3 Block Diagram
Figure 28-1. ABDACB Block Diagram
User Inter af ce
Synchronizer
Volume control
Offset control
CIC Compensation
filter (FIR)
CIC
Comb
Section
CIC Integrator
section
Clock
divider
Sigma Delta
Modulator
Sigma Delta
Modulator
clk_abdacb gclk
Signal processing
(before up-sampling)
CLK
DAC[0]
DACN[0]
DAC[1]
DACN[1]
PB
688
32142D–06/2013
ATUC64/128/256L3/4U
28.4 I/O Lines Description
28.5 Product Dependencies
In order to use this module, other parts of the system must be configured correctly, as described
below.
28.5.1 I/O lines
The output pins used for the output bitstream from the Audio Bitstream DAC may be multiplexed
with I/O Controller lines.
Before using the Audio Bitstream DAC, the I/O Controller must be configured in order for the
Audio Bitstream DAC I/O lines to be in Audio Bitstream DAC peripheral mode.
28.5.2 Clocks
The clock for the ABDACB bus interface (CLK_ABDACB) is generated by the Power Manager.
This clock is turned on by default, and can be enabled and disabled in the Power Manager. It is
recommended to disable the ABDACB before disabling the clock, to avoid freezing the ABDACB
in an undefined state. Before using the Audio Bitstream DAC, the user must ensure that the
Audio Bitstream DAC clock is enabled in the Power Manager.
The Audio Bitstream DAC requires a separate clock for the D/A conversion. This clock is provided
by a generic clock which has to be set up in the System Control Interface (SCIF). The
frequency for this clock has to be set as described in Table 28-3 on page 697. It is important that
this clock is accurate and has low jitter. Incorrect frequency will result in too fast or too slow playback
(frequency shift), and too high jitter will add noise to the D/A conversion. For best
performance one should trade frequency accuracy (within some limits) for low jitter to obtain the
best performance as jitter will have large impact on the quality of the converted signal.
28.5.3 DMA
The ABDACB is connected to the Peripheral DMA controller. Using DMA to transfer data samples
requires the Peripheral DMA controller to be programmed before enabling the ABDACB.
28.5.4 Interrupts
The ABDACB interrupt request line is connected to the interrupt controller. Using the ABDACB
interrupt requires the interrupt controller to be programmed first.
Table 28-1. I/O Lines Description
Pin Name Pin Description Type
DAC[0] Output for channel 0 Output
DACN[0] Inverted output for channel 0 Output
DAC[1] Output for channel 1 Output
DACN[1] Inverted output for channel 1 Output
CLK Clock output for DAC Output
689
32142D–06/2013
ATUC64/128/256L3/4U
28.6 Functional Description
28.6.1 Construction
The Audio Bitstream DAC is divided into several parts, the user interface, the signal processing
blocks, and the Sigma Delta modulator blocks. See Figure 28-1 on page 687. The user interface
is used to configure the signal processing blocks and to input new data samples to the converter.The
signal processing blocks manages volume control, offset control, and upsampling.
The Sigma Delta blocks converts the parallel data to1-bit bitstreams.
28.6.1.1 CIC Interpolation Filter
The interpolation filter in the system is a Cascaded Integrator-Comb (CIC) interpolation filter
which interpolates from Fs to {125, 128, 136}xFs depending on the control settings. This filter is a
4th order CIC filter, and the basic building blocks of the filter is a comb part and an integrator
part. Since the CIC interpolator has a sinc-function frequency response it is compensated by a
linear phase CIC compensation filter to make the passband response more flat in the range 0-
20kHz, see figure Figure 28-4 on page 693. The frequency response of this type of interpolator
has the first zero at the input sampling frequency. This means that the first repeated specters
created by the upsampling process will not be fully rejected and the output signal will contain signals
from these repeated specters. See Figure 28-6 on page 694.
Since the human ear can not hear frequencies above 20kHz, we should not be affected by this
when the sample rate is above 40kHz, but digital measurement equipment will be affected. This
need to be accounted for when doing measurements on the system to prevent aliasing and
incorrect measurement results.
28.6.1.2 Sigma Delta Modulator
The Sigma Delta modulator is a 3rd order modulator consisting of three differentiators (delta
blocks), three integrators (sigma blocks), and a one bit quantizer. The purpose of the integrators
is to shape the noise, so that the noise is reduced in the audio passband and increased at the
higher frequencies, where it can be filtered out by an analog low-pass filter. To be able to filter
out all the noise at high frequencies the analog low-pass filter must be one order larger than the
Sigma Delta modulator.
28.6.1.3 Recreating the Analog Signal
Since the DAC and DACN outputs from the ABDAC are digital square wave signals, they have
to be passed through a low pass filter to recreate the analog signal. This also means that noise
on the IO voltage will couple through to the analog signal. To remove some of the IO noise the
ABDAC can output a clock signal, CLK, which can be used to resample the DAC and DACN signals
on external Flip-Flops powered by a clean supply.
28.6.2 Initialization
Before enabling the ABDACB the correct configuration must be applied to the Control Register
(CR). Configuring the Alternative Upsampling Ratio bit (CR.ALTUPR), Common Mode Offset
Control bit (CR.CMOC), and the Sampling Frequency field (CR.FS) according to the sampling
rate of the data that is converted and the type of amplifier the outputs are connected to is
required to get the correct behavior of the system. When the correct configuration is applied the
ABDACB can be enabled by writing a one to the Enable bit in the Control Register (CR.EN). The
module is disabled by writing a zero to the Enable bit. The module should be disabled before
entering sleep modes to ensure that the outputs are not left in an undesired state.
690
32142D–06/2013
ATUC64/128/256L3/4U
28.6.3 Basic operation
To convert audio data to a digital bitstream the user must first initialize the ABDACB as
described in Section 28.6.2. When the ABDACB is initialized and enabled it will indicate that it is
ready to receive new data by setting the Transmit Ready bit in the Status Register (SR.TXRDY).
When the TXRDY bit is set in the Status Register the user has to write new samples to Sample
Data Register 0 (SDR0) and Sample Data Register 1 (SDR1). If the Mono Mode (MONO) bit in
the Control Register (CR) is set, or one of the compact stereo formats are used by configuring
the Data Word Format (DATAFORMAT) in the Control Register, only SDR0 has to be written.
Failing to write to the sample data registers will result in an underrun indicated by the Transmit
Underrun (TXUR) bit in the Status Register (SR.TXUR). When new samples are written to the
sample data registers the TXRDY bit will be cleared.
To increase performance of the system an interrupt handler or DMA transfer can be used to
write new samples to the sample data registers. See Section 28.6.10 for details on DMA, and
Section 28.6.11 for details on interrupt.
28.6.4 Data Format
The input data type is two’s complement. The Audio Bitstream DAC can be configured to accept
different audio formats. The format must be configured in the Data Word Format field in the Control
Register. In regular operation data for the two channels are written to the sample data
registers SDR0 and SDR1. If the data format field specifies a format using less than 32 bits, data
must be written right-justified in SDR0 and SDR1. Sign extension into the unused bits is not necessary.
Only the 16 most significant bits in the data will be used by the ABDACB. For data
formats larger than 16 bits the least significant bits are ignored. For 8-bit data formats the 8 bits
will be used as the most significant bits in the 16-bit samples, the additional bits will be zeros.
The ABDACB also supports compact data formats for 16- and 8-bit samples. For 16-bit samples
the sample for channel 0 must be written to bits 15 through 0 and the sample for channel 1 must
be written to bits 31 through 16 in SDR0. For 8-bit samples the sample for channel 0 must be
written to bits 7 through 0 and the sample for channel 1 must be written to bits 15 through 8 in
SDR0. SDR1 is not used in this mode. See Table 28-5 on page 699.
28.6.5 Data Swapping
When the Swap Channels (SWAP) bit in the Control Register (CR.SWAP) is one, writing to the
Sample Data Register 0 (SDR0) will put the data in Sample Data Register 1 (SDR1). Writing
SDR1 will put the data in SDR0. If one of the two compact stereo formats is used the lower and
upper halfword of SDR0 will be swapped when writing to SDR0.
28.6.6 Common Mode Offset Control
When the Common Mode Offset Control (CMOC) bit in the Control Register is one the input data
will get a DC value applied to it and the amplitude will be scaled. This will make the common
mode offset of the two corresponding outputs, DAC and DACN, to move away from each other
so that the output signals are not overlapping. The result is that the two signals can be applied to
a differential analog filter, and the difference will always be a positive value, removing the need
for a negative voltage supply for the filter. The cost of doing this a 3dB loss in dynamic range. On
the left side of Figure 28-2 one can see the filtered output from the DAC and DACN pins when a
sine wave is played when CR.CMOC is zero. The waveform on the right side shows the output
of the differential filter when the two outputs on the left side are used as inputs to the differential
filter. Figure 28-3 show the corresponding outputs when CR.CMOC is one.
691
32142D–06/2013
ATUC64/128/256L3/4U
Figure 28-2. Output signals with CMOC=0
Figure 28-3. Output signals with CMOC=1
28.6.7 Volume Control
The Audio Bitstream DAC have two volume control registers, Volume Control Register 0 (VCR0)
and Volume Control Register 1 (VCR1), that can be used to adjust the volume for the corresponding
channel. The volume control is linear and will only scale each sample according to the
value in the Volume Control (VOLUME) field in the volume control registers. The register also
has a Mute bit (MUTE) which can be used to mute the corresponding channel. The filtered out-
692
32142D–06/2013
ATUC64/128/256L3/4U
put of the DAC pins will have a voltage given by the following equation, given that it is configured
to run at the default upsampling ratio of 128:
If one want to get coherence between the sign of the input data and the output voltage one can
use the DATAN outputs or invert the sign of the input data by software.
28.6.8 Mono
When the Mono bit (MONO) in the Control Register is set, data written to SDR0 will be used for
both output channels. If one of the compact stereo formats are used only the data written to the
part of SDR0 that corresponds with channel 0 is used.
28.6.9 Alternative Upsampling Ratio
The digital filters and Sigma Delta modulators requires its own clock to perform the conversion at
the correct speed, and this clock is provided by a generic clock in the SCIF. The frequency of
this clock depends on the input sample rate and the upsampling ratio which is controlled by the
Alternative Upsampling Ratio bit (ALTUPR) in the Control Register.
The ABDACB supports three upsampling ratios, 125, 128, and 136. The default setting is a ratio
of 128, and is used when CR.ALTUPR is zero. Using this ratio gives a clock frequency requirement
that is common for audio products. In some cases one may want to use other clock
frequencies that already are available in the system. By writing a one to CR.ALTUPR a upsampling
ratio of 125 or 136 is used depending on the configuration of the Sampling Frequency field
in the Control Register. Refer to Table 28-3 for required clock frequency and settings.
The required clock frequency of the generic clock can be calculated from the following equation:
R is the upsampling ratio of the converter. If CR.ALTUPR is zero the upsampling ratio is 128. If
CR.ALTUPR is one, R will change to 125 when CR.FS is configured for 8kHz, 12kHz, 16kHz,
24kHz, 32kHz, and 48kHz. For the other configurations of CR.FS, 11.025kHz, 22.050kHz, and
44.100kHz, it will change to 136.
28.6.10 DMA operation
The Audio Bitstream DAC is connected to the Peripheral DMA Controller. The Peripheral DMA
Controller can be programmed to automatically transfer samples to the Sample Data Registers
(SDR0 and SDR1) when the Audio Bitstream DAC is ready for new samples. Two DMA channels
are used, one for each sample data register. If the Mono Mode bit in the Control Register
(CR.MONO) is one, or one of the compact stereo formats is used, only the DMA channel connected
to SDR0 will be used. When using DMA only the Control Register needs to be written in
the Audio Bitstream DAC. This enables the Audio Bitstream DAC to operate without any CPU
intervention such as polling the Status Register (SR) or using interrupts. See the Peripheral
DMA Controller documentation for details on how to setup Peripheral DMA transfers.
28.6.11 Interrupts
The ABDACB requires new data samples at a rate of FS. The interrupt status bits are used to
indicate when the system is ready to receive new samples. The Transmit Ready Interrupt Status
bit in the Status Register (SR.TXRDY) will be set whenever the ABDACB is ready to receive a
new sample. A new sample value must be written to the sample data registers (SDR0 and
VOUT
1
2
-- 33
128 – --------- SDR
215 ------------ VOLUME
215 – 1
------------------------ VVDDIO =
GCLK[Hz] F = S R 8
693
32142D–06/2013
ATUC64/128/256L3/4U
SDR1) before 1/FS second, or an underrun will occur, as indicated by the Underrun Interrupt bit
in SR (SR.TXUR). The interrupt bits in SR are cleared by writing a one to the corresponding bit
in the Status Clear Register (SCR).
28.6.12 Frequency Response
Figure Figure 28-4 to Figure 28-7 show the frequency response for the system. The sampling
frequency used is 48kHz, but the response will be the same for other sampling frequencies,
always having the first zero at FS.
Figure 28-4. Passband Frequency Response
694
32142D–06/2013
ATUC64/128/256L3/4U
Figure 28-5. Frequency Response up to Sampling Frequency
Figure 28-6. Frequency Response up to 3x Sampling Frequency
695
32142D–06/2013
ATUC64/128/256L3/4U
Figure 28-7. Frequency Response up to 128x Sampling Frequency
696
32142D–06/2013
ATUC64/128/256L3/4U
28.7 User Interface
Note: 1. The reset values are device specific. Please refer to the Module Configuration section at the end of this chapter.
Table 28-2. ABDACB Register Memory Map
Offset Register Register Name Access Reset
0x00 Control Register CR Read/Write 0x00000000
0x04 Sample Data Register 0 SDR0 Read/Write 0x00000000
0x08 Sample Data Register 1 SDR1 Read/Write 0x00000000
0x0C Volume Control Register 0 VCR0 Read/Write 0x00000000
0x10 Volume Control Register 1 VCR1 Read/Write 0x00000000
0x14 Interrupt Enable Register IER Write-only 0x00000000
0x18 Interrupt Disable Register IDR Write-only 0x00000000
0x1C Interrupt Mask Register IMR Read-only 0x00000000
0x20 Status Register SR Read-only 0x00000000
0x24 Status Clear Register SCR Write-only 0x00000000
0x28 Parameter Register PARAMETER Read-only -
(1)
0x2C Version Register VERSION Read-only -
(1)
697
32142D–06/2013
ATUC64/128/256L3/4U
28.7.1 Control Register
Name: CR
Access Type: Read/Write
Offset: 0x00
Reset Value: 0x00000000
• FS: Sampling Frequency
Must be set to the matching data sampling frequency, see Table 28-3.
Note: 1. The actual clock requirement are 11.9952MHz, 23.9904MHz, and 47.9808MHz, but this is
very close to the suggested clock frequencies, and will only result in a very small frequency
shift. This need to be accounted for during testing if comparing to a reference signal.
Notes: 1.
31 30 29 28 27 26 25 24
- - - - FS
23 22 21 20 19 18 17 16
- - - - - DATAFORMAT
15 14 13 12 11 10 9 8
--------
76543210
SWRST - MONO CMOC ALTUPR - SWAP EN
Table 28-3. Generic Clock Requirements
CR.FS Description GCLK (CR.ALTUPR=1) GCLK (CR.ALTUPR=0)
0 8000Hz sampling frequency 8.0MHz 8.1920MHz
1 11025Hz sampling frequency 12.0MHz(1) 11.2896MHz
2 12000Hz sampling frequency 12.0MHz 12.2880MHz
3 16000Hz sampling frequency 16.0MHz 16.3840MHz
4 22050Hz sampling frequency 24.0MHz(1) 22.5792MHz
5 24000Hz sampling frequency 24.0MHz 24.5760MHz
6 32000Hz sampling frequency 32.0MHz 32.7680MHz
7 44100Hz sampling frequency 48.0MHz(1) 45.1584MHz
8 48000Hz sampling frequency 48.0MHz 49.1520MHz
Other Reserved - -
698
32142D–06/2013
ATUC64/128/256L3/4U
• DATAFORMAT: Data Word Format
• SWRST: Software Reset
Writing a zero to this bit does not have any effect.
Writing a one to this bit will reset the ABDACB as if a hardware reset was done.
• MONO: Mono Mode
0: Mono mode is disabled.
1: Mono mode is enabled.
• CMOC: Common Mode Offset Control
0: Common mode adjustment is disabled.
1: Common mode adjustment is enabled.
• ALTUPR: Alternative Upsampling Ratio
0: Alternative upsampling is disabled.
1: Alternative upsampling is enabled.
• SWAP: Swap Channels
0: Channel swap is disabled.
1: Channel swap is enabled.
• EN: Enable
0: The ABDACB is disabled.
1: The ABDACB is enabled.
Table 28-4. Data Word Format
DATAFORMAT Word length Comment
0 32 bits
1 24 bits
2 20 bits
3 18 bits
4 16 bits
5 16 bits compact stereo Channel 1 sample in bits 31 through 16, channel 0 sample in bits 15 through 0 in SDR0
6 8 bits
7 8 bits compact stereo Channel 1 sample in bits 15 through 8, channel 0 sample in bits 7through 0 in SDR0
699
32142D–06/2013
ATUC64/128/256L3/4U
28.7.2 Sample Data Register 0
Name: SDR0
Access Type: Read/Write
Offset: 0x04
Reset Value: 0x00000000
• DATA: Sample Data
Sample Data for channel 0 in two’s complement format. Data must be right-justified, see Table 28-5.
31 30 29 28 27 26 25 24
DATA[31:24]
23 22 21 20 19 18 17 16
DATA[23:16]
15 14 13 12 11 10 9 8
DATA[15:8]
76543210
DATA[7:0]
Table 28-5. Sample Data Register Formats
Data Format SDR0 SDR1 Comment
32 bits CH0 sample in DATA[31:0] CH1 sample in DATA[31:0]
24 bits CH0 sample in DATA[23:0] CH1 sample in DATA[23:0] Remaining bits are ignored.
20 bits CH0 sample in DATA[19:0] CH1 sample in DATA[19:0] Remaining bits are ignored.
18 bits CH0 sample in DATA[17:0] CH1 sample in DATA[17:0] Remaining bits are ignored.
16 bits CH0 sample in DATA[15:0] CH1 sample in DATA[15:0] Remaining bits are ignored.
16 bits compact stereo CH0 sample in DATA[15:0]
CH1 sample in DATA[31:16] Not used
8 bits CH0 sample in DATA[7:0] CH1 sample in DATA[7:0] Remaining bits are ignored.
8 bits compact stereo CH0 sample in DATA[7:0]
CH1 sample in DATA[15:8] Not used Remaining bits are ignored.
700
32142D–06/2013
ATUC64/128/256L3/4U
28.7.3 Sample Data Register 1
Name: SDR1
Access Type: Read/Write
Offset: 0x08
Reset Value: 0x00000000
• DATA: Sample Data
Sample Data for channel 1 in two’s complement format. Data must be right-justified, see Table 28-5 on page 699.
31 30 29 28 27 26 25 24
DATA[31:24]
23 22 21 20 19 18 17 16
DATA[23:16]
15 14 13 12 11 10 9 8
DATA[15:8]
76543210
DATA[7:0]
701
32142D–06/2013
ATUC64/128/256L3/4U
28.7.4 Volume Control Register 0
Name: VCR0
Access Type: Read/Write
Offset: 0x0C
Reset Value: 0x00000000
• MUTE: Mute
0: Channel 0 is not muted.
1: Channel 0 is muted.
• VOLUME: Volume Control
15-bit value adjusting the volume for channel 0.
31 30 29 28 27 26 25 24
MUTE - - - - - - -
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
- VOLUME[14:8]
76543210
VOLUME[7:0]
702
32142D–06/2013
ATUC64/128/256L3/4U
28.7.5 Volume Control Register 1
Name: VCR1
Access Type: Read/Write
Offset: 0x10
Reset Value: 0x00000000
• MUTE: Mute
0: Channel 1 is not muted.
1: Channel 1 is muted.
• VOLUME: Volume Control
15-bit value adjusting the volume for channel 1.
31 30 29 28 27 26 25 24
MUTE - - - - - - -
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
- VOLUME[14:8]
76543210
VOLUME[7:0]
703
32142D–06/2013
ATUC64/128/256L3/4U
28.7.6 Interrupt Enable Register
Name: IER
Access Type: Write-only
Offset: 0x14
Reset Value: 0x00000000
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will set the corresponding bit in IMR.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
- - - - - TXUR TXRDY -
704
32142D–06/2013
ATUC64/128/256L3/4U
28.7.7 Interrupt Disable Register
Name: IDR
Access Type: Write-only
Offset: 0x18
Reset Value: 0x00000000
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will clear the corresponding bit in IMR.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
- - - - - TXUR TXRDY -
705
32142D–06/2013
ATUC64/128/256L3/4U
28.7.8 Interrupt Mask Register
Name: IMR
Access Type: Read-only
Offset: 0x1C
Reset Value: 0x00000000
0: The corresponding interrupt is disabled.
1: The corresponding interrupt is enabled.
A bit in this register is cleared when the corresponding bit in IDR is written to one.
A bit in this register is set when the corresponding bit in IER is written to one.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
- - - - - TXUR TXRDY -
706
32142D–06/2013
ATUC64/128/256L3/4U
28.7.9 Status Register
Name: SR
Access Type: Read-only
Offset: 0x20
Reset Value: 0x00000000
• TXUR: Transmit Underrun
This bit is cleared when no underrun has occurred since the last time this bit was cleared (by reset or by writing to SCR).
This bit is set when at least one underrun has occurred since the last time this bit was cleared (by reset or by writing to SCR).
• TXRDY: Transmit Ready
This bit is cleared when the ABDACB is not ready to receive a new data in SDR.
This bit is set when the ABDACB is ready to receive a new data in SDR.
• BUSY: ABDACB Busy
This bit is set when the ABDACB is busy doing a data transfer between clock domains. CR, SDR0, and SDR1 can not be written
during this time.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
- - - - - TXUR TXRDY BUSY
707
32142D–06/2013
ATUC64/128/256L3/4U
28.7.10 Status Clear Register
Name: SCR
Access Type: Write-only
Offset: 0x24
Reset Value: 0x00000000
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will clear the corresponding bit in SR and the corresponding interrupt request.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
- - - - - TXUR TXRDY -
708
32142D–06/2013
ATUC64/128/256L3/4U
28.7.11 Parameter Register
Name: PARAMETER
Access Type: Read-only
Offset: 0x28
Reset Value: 0x00000000
Reserved. No functionality associated.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
--------
709
32142D–06/2013
ATUC64/128/256L3/4U
28.7.12 Version Register
Name: VERSION
Access Type: Read-only
Offset: 0x2C
Reset Value: 0x00000000
• VARIANT: Variant Number
Reserved. No functionality associated.
• VERSION: Version Number
Version number of the module. No functionality associated.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
- - - - VARIANT
15 14 13 12 11 10 9 8
- - - - VERSION[11:8]
76543210
VERSION[7:0]
710
32142D–06/2013
ATUC64/128/256L3/4U
28.8 Module Configuration
The specific configuration for each ABDACB instance is listed in the following tables.The module
bus clocks listed here are connected to the system bus clocks. Please refer to the Power Manager
chapter for details.
Table 28-6. ABDACB Clocks
Clock Name Description
CLK_ABDACB Clock for the ABDACB bus interface
GCLK The generic clock used for the ABDACB is GCLK6
Table 28-7. Register Reset Values
Register Reset Value
VERSION 0x00000100
PARAMETER 0x00000000
711
32142D–06/2013
ATUC64/128/256L3/4U
29. ADC Interface (ADCIFB)
Rev:1.0.1.1
29.1 Features
• Multi-channel Analog-to-Digital Converter with up to 12-bit resolution
• Enhanced Resolution Mode
– 11-bit resolution obtained by interpolating 4 samples
– 12-bit resolution obtained by interpolating 16 samples
• Glueless interface with resistive touch screen panel, allowing
– Resistive Touch Screen position measurement
– Pen detection and pen loss detection
• Integrated enhanced sequencer
– ADC Mode
– Resistive Touch Screen Mode
• Numerous trigger sources
– Software
– Embedded 16-bit timer for periodic trigger
– Pen detect trigger
– Continuous trigger
– External trigger, rising, falling, or any-edge trigger
– Peripheral event trigger
• ADC Sleep Mode for low power ADC applications
• Programmable ADC timings
– Programmable ADC clock
– Programmable startup time
29.2 Overview
The ADC Interface (ADCIFB) converts analog input voltages to digital values. The ADCIFB is
based on a Successive Approximation Register (SAR) 10-bit Analog-to-Digital Converter (ADC).
The conversions extend from 0V to ADVREFP.
The ADCIFB supports 8-bit and 10-bit resolution mode, in addition to enhanced resolution mode
with 11-bit and 12-bit resolution. Conversion results are reported in a common register for all
channels.
The 11-bit and 12-bit resolution modes are obtained by interpolating multiple samples to acquire
better accuracy. For 11-bit mode 4 samples are used, which gives an effective sample rate of
1/4 of the actual sample frequency. For 12-bit mode 16 samples are used, giving a effective
sample rate of 1/16 of actual. This arrangement allows conversion speed to be traded for better
accuracy.
Conversions can be started for all enabled channels, either by a software trigger, by detection of
a level change on the external trigger pin (TRIGGER), or by an integrated programmable timer.
When the Resistive Touch Screen Mode is enabled, an integrated sequencer automatically configures
the pad control signals and performs resistive touch screen conversions.
The ADCIFB also integrates an ADC Sleep Mode, a Pen-Detect Mode, and an Analog Compare
Mode, and connects with one Peripheral DMA Controller channel. These features reduce both
power consumption and processor intervention.
712
32142D–06/2013
ATUC64/128/256L3/4U
29.3 Block Diagram
Figure 29-1. ADCIFB Block Diagram
ADVREFP
Analog Multiplexer
Successive
Approximation
Register
Analog-to-Digital
Converter
Trigger
ADC Control
Logic
Timer
User
Interface
AD0
AD1
AD3
ADn
AD2
Resisitve Touch
Screen
Sequencer
CLK_ADCIFB
....
ADCIFB
ADP0
ADP1
I/O Controller
TRIGGER
Peripheral
Bus
DMA
Request
Interrupt
Request
CLK_ADC
713
32142D–06/2013
ATUC64/128/256L3/4U
29.4 I/O Lines Description
29.5 Product Dependencies
In order to use this module, other parts of the system must be configured correctly, as described
below.
29.5.1 I/O Lines
The analog input pins can be multiplexed with I/O Controller lines. The user must make sure the
I/O Controller is configured correctly to allow the ADCIFB access to the AD pins before the
ADCIFB is instructed to start converting data. If the user fails to do this the converted data may
be wrong.
The number of analog inputs is device dependent, please refer to the ADCIFB Module Configuration
chapter for the number of available AD inputs on the current device.
The ADVREFP pin must be connected correctly prior to using the ADCIFB. Failing to do so will
result in invalid ADC operation. See the Electrical Characteristics chapter for details.
If the TRIGGER, ADP0, and ADP1 pins are to be used in the application, the user must configure
the I/O Controller to assign the needed pins to the ADCIFB function.
29.5.2 Power Management
If the CPU enters a sleep mode that disables clocks used by the ADCIFB, the ADCIFB will stop
functioning and resume operation after the system wakes up from sleep mode.
If the Peripheral Event System is configured to send asynchronous peripheral events to the
ADCIFB and the clock used by the ADCIFB is stopped, a local and temporary clock will automatically
be requested so the event can be processed. Refer to Section 29.6.13, Section 29.6.12,
and the Peripheral Event System chapter for details.
Before entering a sleep mode where the clock to the ADCIFB is stopped, make sure the Analogto-Digital
Converter cell is put in an inactive state. Refer to Section 29.6.13 for more information.
29.5.3 Clocks
The clock for the ADCIFB bus interface (CLK_ADCIFB) is generated by the Power Manager.
This clock is enabled at reset, and can be disabled in the Power Manager. It is recommended to
disable the ADCIFB before disabling the clock, to avoid freezing the ADCIFB in an undefined
state.
Table 29-1. I/O Lines Description
Pin Name Description Type
ADVREFP Reference voltage Analog
TRIGGER External trigger Digital
ADP0 Drive Pin 0 for Resistive Touch Screen top channel (Xp) Digital
ADP1 Drive Pin 1 for Resistive Touch Screen right channel (Yp) Digital
AD0-ADn Analog input channels 0 to n Analog
714
32142D–06/2013
ATUC64/128/256L3/4U
29.5.4 DMA
The ADCIFB DMA handshake interface is connected to the Peripheral DMA Controller. Using
the ADCIFB DMA functionality requires the Peripheral DMA Controller to be programmed first.
29.5.5 Interrupts
The ADCIFB interrupt request line is connected to the interrupt controller. Using the ADCIFB
interrupt request functionality requires the interrupt controller to be programmed first.
29.5.6 Peripheral Events
The ADCIFB peripheral events are connected via the Peripheral Event System. Refer to the
Peripheral Event System chapter for details
29.5.7 Debug Operation
When an external debugger forces the CPU into debug mode, this module continues normal
operation. If this module is configured in a way that requires it to be periodically serviced by the
CPU through interrupt requests or similar, improper operation or data loss may result during
debugging.
29.6 Functional Description
The ADCIFB embeds a Successive Approximation Register (SAR) Analog-to-Digital Converter
(ADC). The ADC supports 8-bit or 10-bit resolution, which can be extended to 11 or 12 bits by
the Enhanced Resolution Mode.
The conversion is performed on a full range between 0V and the reference voltage pin
ADVREFP. Analog inputs between these voltages converts to digital values (codes) based on a
linear conversion. This linear conversion is described in the expression below where M is the
number of bits used to represent the analog value, Vin is the voltage of the analog value to convert,
Vref is the maximum voltage, and Code is the converted digital value.
29.6.1 Initializing the ADCIFB
The ADC Interface is enabled by writing a one to the Enable bit in the Control Register (CR.EN).
After the ADC Interface is enabled, the ADC timings needs to be configured by writing the correct
values to the RES, PRESCAL, and STARTUP fields in the ADC Configuration Register
(ACR). See Section 29.6.5, and Section 29.6.7 for details. Before the ADCIFB can be used, the
I/O Controller must be configured correctly and the Reference Voltage (ADVREFP) signal must
be connected. Refer to Section 29.5.1 for details.
29.6.2 Basic Operation
To convert analog values to digital values the user must first initialize the ADCIFB as described
in Section 29.6.1. When the ADCIFB is initialized the channels to convert must be enabled by
writing a one the corresponding bits in the Channel Enable Register (CHER). Enabling channel
N instructs the ADCIFB to convert the analog voltage applied to AD pin N at each conversion
sequence. Multiple channels can be enabled resulting in multiple AD pins being converted at
each conversion sequence.
Code
2M Vin
Vref
= -------------------
715
32142D–06/2013
ATUC64/128/256L3/4U
To start converting data the user can either manually start a conversion sequence by writing a
one to the START bit in the Control Register (CR.START) or configure an automatic trigger to
initiate the conversions. The automatic trigger can be configured to trig on many different conditions.
Refer to Section 29.8.1 for details.
The result of the conversion is stored in the Last Converted Data Register (LCDR) as they
become available, overwriting the result from the previous conversion. To avoid data loss if more
than one channel is enabled, the user must read the conversion results as they become available
either by using an interrupt handler or by using a Peripheral DMA channel to copy the
results to memory. Failing to do so will result in an Overrun Error condition, indicated by the
OVRE bit in the Status Register (SR).
To use an interrupt handler the user must enable the Data Ready (DRDY) interrupt request by
writing a one to the corresponding bit in the Interrupt Enable Register (IER). To clear the interrupt
after the conversion result is read, the user must write a one to the corresponding bit in the
Interrupt Clear Register (ICR). See Section 29.6.11 for details.
To use a Peripheral DMA Controller channel the user must configure the Peripheral DMA Controller
appropriately. The Peripheral DMA Controller will, when configured, automatically read
converted data as they become available. There is no need to manually clear any bits in the
Interrupt Status Register as this is performed by the hardware. If an Overrun Error condition happens
during DMA operation, the OVRE bit in the SR will be set.
29.6.3 ADC Resolution
The Analog-to-Digital Converter cell supports 8-bit or 10-bit resolution, which can be extended to
11-bit and 12-bit with the Enhanced Resolution Mode. The resolution is selected by writing the
selected resolution value to the RES field in the ADC Configuration Register (ACR). See Section
29.9.3.
By writing a zero to the RES field, the ADC switches to the lowest resolution and the conversion
results can be read in the eight lowest significant bits of the Last Converted Data Register
(LCDR). The four highest bits of the Last Converted Data (LDATA) field in the LCDR register
reads as zero. Writing a one to the RES field enables 10-bit resolution, the optimal resolution for
both sampling speed and accuracy. Writing two or three automatically enables Enhanced Resolution
Mode with 11-bit or 12-bit resolution, see Section 29.6.4 for details.
When a Peripheral DMA Controller channel is connected to the ADCIFB in 10-bit, 11-bit, or 12-
bit resolution mode, a transfer size of 16 bits must be used. By writing a zero to the RES field,
the destination buffers can be optimized for 8-bit transfers.
29.6.4 Enhanced Resolution Mode
The Enhanced Resolution Mode is automatically enabled when 11-bit or 12-bit mode is selected
in the ADC Configuration Register (ACR). In this mode the ADCIFB will trade conversion performance
for accuracy by averaging multiple samples.
To be able to increase the accuracy by averaging multiple samples it is important that some
noise is present in the input signal. The noise level should be between one and two LSB peakto-peak
to get good averaging performance.
The performance cost of enabling 11-bit mode is 4 ADC samples, which reduces the effective
ADC performance by a factor 4. For 12-bit mode this factor is 16. For 12-bit mode the effective
sample rate is maximum ADC sample rate divided by 16.
716
32142D–06/2013
ATUC64/128/256L3/4U
29.6.5 ADC Clock
The ADCIFB generates an internal clock named CLK_ADC that is used by the Analog-to-Digital
Converter cell to perform conversions. The CLK_ADC frequency is selected by writing to the
PRESCAL field in the ADC Configuration Register (ACR). The CLK_ADC range is between
CLK_ADCIFB/2, if PRESCAL is 0, and CLK_ADCIFB/128, if PRESCAL is 63 (0x3F).
A sensible PRESCAL value must be used in order to provide an ADC clock frequency according
to the maximum sampling rate parameter given in the Electrical Characteristics section. Failing
to do so may result in incorrect Analog-to-Digital Converter operation.
29.6.6 ADC Sleep Mode
The ADC Sleep Mode maximizes power saving by automatically deactivating the Analog-to-Digital
Converter cell when it is not being used for conversions. The ADC Sleep Mode is enabled by
writing a one to the SLEEP bit in the ADC Configuration Register (ACR).
When a trigger occurs while the ADC Sleep Mode is enabled, the Analog-to-Digital Converter
cell is automatically activated. As the analog cell requires a startup time, the logic waits during
this time and then starts the conversion of the enabled channels. When conversions of all
enabled channels are complete, the ADC is deactivated until the next trigger.
29.6.7 Startup Time
The Analog-to-Digital Converter cell has a minimal startup time when the cell is activated. This
startup time is given in the Electrical Characteristics chapter and must be written to the
STARTUP field in the ADC Configuration Register (ACR) to get correct conversion results.
The STARTUP field expects the startup time to be represented as the number of CLK_ADC
cycles between 8 and 1024 and in steps of 8 that is needed to cover the ADC startup time as
specified in the Electrical Characteristics chapter.
The Analog-to-Digital Converter cell is activated at the first conversion after reset and remains
active if ACR.SLEEP is zero. If ACR.SLEEP is one, the Analog-to-Digital Converter cell is automatically
deactivated when idle and thus each conversion sequence will have a initial startup
time delay.
29.6.8 Sample and Hold Time
A minimal Sample and Hold Time is necessary for the ADCIFB to guarantee the best converted
final value when switching between ADC channels. This time depends on the input impedance
of the analog input, but also on the output impedance of the driver providing the signal to the
analog input, as there is no input buffer amplifier.
The Sample and Hold time has to be programmed through the SHTIM field in the ADC Configuration
Register (ACR). This field can define a Sample and Hold time between 1 and 16
CLK_ADC cycles.
29.6.9 ADC Conversion
ADC conversions are performed on all enabled channels when a trigger condition is detected.
For details regarding trigger conditions see Section 29.8.1. The term channel is used to identify
a specific analog input pin so it can be included or excluded in an Analog-to-Digital conversion
sequence and to identify which AD pin was used to convert the current value in the Last Converted
Data Register (LCDR). Channel number N corresponding to AD pin number N.
717
32142D–06/2013
ATUC64/128/256L3/4U
Channels are enabled by writing a one to the corresponding bit in the Channel Enable Register
(CHER), and disabled by writing a one to the corresponding bit in the Channel Disable Register
(CHDR). Active channels are listed in the Channel Status Register (CHSR).
When a conversion sequence is started, all enabled channels will be converted in one sequence
and the result will be placed in the Last Converted Data Register (LCDR) with the channel number
used to produce the result. It is important to read out the results while the conversion
sequence is ongoing, as new values will automatically overwrite any old value and the old value
will be lost if not previously read by the user.
If the Analog-to-Digital Converter cell is inactive when starting a conversion sequence, the conversion
logic will wait a configurable number of CLK_ADC cycles as defined in the startup time
field in the ADC Configuration Register (ACR). After the cell is activated all enabled channels is
converted one by one until no more enabled channels exist. The conversion sequence converts
each enabled channel in order starting with the channel with the lowest channel number. If the
ACR.SLEEP bit is one, the Analog-to-Digital Converter cell is deactivated after the conversion
sequence has finished.
For each channel converted, the ADCIFB waits a Sample and Hold number of CLK_ADC cycles
as defined in the SHTIM field in ACR, and then instructs the Analog-to-Digital Converter cell to
start converting the analog voltage. The ADC cell requires 10 CLK_ADC cycles to actually convert
the value, so the total time to convert a channel is Sample and Hold + 10 CLK_ADC cycles.
29.6.10 Analog Compare Mode
The ADCIFB can test if the converted values, as they become available, are below, above, or
inside a specified range and generate interrupt requests based on this information. This is useful
for applications where the user wants to monitor some external analog signal and only initiate
actions if the value is above, below, or inside some specified range.
The Analog Compare mode is enabled by writing a one to the Analog Compare Enable (ACE) bit
in the Mode Register (MR). The values to compare must be written to the Low Value (LV) field
and the High Value (HV) field in the Compare Value Register (CVR). The Analog Compare
mode will, when enabled, check all enabled channels against the pre-programmed high and low
values and set status bits.
To generate an interrupt request if a converted value is below a limit, write the limit to the
CVR.LV field and enable interrupt request on the Compare Lesser Than (CLT) bit by writing a
one to the corresponding bit in the Interrupt Enable Register (IER). To generate an interrupt
request if a converted value is above a limit, write the limit to the CVR.HV field and enable interrupt
for Compare Greater Than (CGT) bit. To generate an interrupt request if a converted value
is inside a range, write the low and high limit to the LV and HV fields and enable the Compare
Else (CELSE) interrupt. To generate an interrupt request if a value is outside a range, write the
LV and HV fields to the low and high limits of the range and enable CGT and CLT interrupts.
Note that the values written to LV and HV must match the resolution selected in the ADC Configuration
Register (ACR).
29.6.11 Interrupt Operation
Interrupt requests are enabled by writing a one to the corresponding bit in the Interrupt Enable
Register (IER) and disabled by writing a one to the corresponding bit in the Interrupt Disable
Register (IDR). Enabled interrupts can be read from the Interrupt Mask Register (IMR). Active
interrupt requests, but potentially masked, are visible in the Interrupt Status Register (ISR). To
718
32142D–06/2013
ATUC64/128/256L3/4U
clear an active interrupt request, write a one to the corresponding bit in the Interrupt Clear Register
(ICR).
The source for the interrupt requests are the status bits in the Status Register (SR). The SR
shows the ADCIFB status at the time the register is read. The Interrupt Status Register (ISR)
shows the status since the last write to the Interrupt Clear Register. The combination of ISR and
SR allows the user to react to status change conditions but also allows the user to read the current
status at any time.
29.6.12 Peripheral Events
The Peripheral Event System can be used together with the ADCIFB to allow any peripheral
event generator to be used as a trigger source. To enable peripheral events to trigger a conversion
sequence the user must write the Peripheral Event Trigger value (0x7) to the Trigger Mode
(TRGMOD) field in the Trigger Register (TRGR). Refer to Table 29-4 on page 730. The user
must also configure a peripheral event generator to emit peripheral events for the ADCIFB to
trigger on. Refer to the Peripheral Event System chapter for details.
29.6.13 Sleep Mode
Before entering sleep modes the user must make sure the ADCIFB is idle and that the Analogto-Digital
Converter cell is inactive. To deactivate the Analog-to-Digital Converter cell the SLEEP
bit in the ADC Configuration Register (ACR) must be written to one and the ADCIFB must be
idle. To make sure the ADCIFB is idle, write a zero the Trigger Mode (TRGMOD) field in the
Trigger Register (TRGR) and wait for the READY bit in the Status Register (SR) to be set.
Note that by deactivating the Analog-to-Digital Converter cell, a startup time penalty as defined
in the STARTUP field in the ADC Configuration Register (ACR) will apply on the next
conversion.
29.6.14 Conversion Performances
For performance and electrical characteristics of the ADCIFB, refer to the Electrical Characteristics
chapter.
29.7 Resistive Touch Screen
The ADCIFB embeds an integrated Resistive Touch Screen Sequencer that can be used to calculate
contact coordinates on a resistive touch screen film. When instructed to start, the
integrated Resistive Touch Screen Sequencer automatically applies a sequence of voltage patterns
to the resistive touch screen films and the Analog-to-Digital Conversion cell is used to
measure the effects. The resulting measurements can be used to calculate the horizontal and
vertical contact coordinates. It is recommended to use a high resistance touch screen for optimal
resolution.
The resistive touch screen film is connected to the ADCIFB using the AD and ADP pins. See
Section 29.7.3 for details.
Resistive Touch Screen Mode is enabled by writing a one to the Touch Screen ADC Mode field
in the Mode Register (MR.TSAMOD). In this mode, channels TSPO+0 though TSPO+3 are
automatically enabled where TSPO refers to the Touch Screen Pin Offset field in the Mode Register
(MR.TSPO). For each conversion sequence, all enabled channels before TSPO+0 and
after TSPO+3 are converted as ordinary ADC channels, producing 1 conversion result each.
When the sequencer enters the TSPO+0 channel the Resistive Touch Screen Sequencer will
take over control and convert the next 4 channels as described in Section 29.7.4.
719
32142D–06/2013
ATUC64/128/256L3/4U
29.7.1 Resistive Touch Screen Principles
A resistive touch screen is based on two resistive films, each one fitted with a pair of electrodes,
placed at the top and bottom on one film, and on the right and left on the other. Between the two,
there is a layer that acts as an insulator, but makes a connection when pressure is applied to the
screen. This is illustrated in Figure 29-2 on page 719.
Figure 29-2. Resistive Touch Screen Position Measurement
29.7.2 Position Measurement Method
As shown in Figure 29-2 on page 719, to detect the position of a contact, voltage is first applied
to XP (top) and Xm (bottom) leaving Yp and Ym tristated. Due to the linear resistance of the film,
there is a voltage gradient from top to bottom on the first film. When a contact is performed on
the screen, the voltage at the contact point propagates to the second film. If the input impedance
on the YP (right) and Ym (left) electrodes are high enough, no current will flow, allowing the voltage
at the contact point to be measured at Yp. The value measured represents the vertical
position component of the contact point.
For the horizontal direction, the same method is used, but by applying voltage from YP (right) to
Ym (left) and measuring at XP.
In an ideal world (linear, with no loss), the vertical position is equal to:
VYP / VDD
To compensate for some of the real world imperfections, VXP and VXm can be measured and
used to improve accuracy at the cost of two more conversions per axes. The new expression for
the vertical position then becomes:
(VYP - VXM) / (VXP - VXM)
XM
XP
YM YP
XP
XM
YP
VDD
GND
Volt
Horizontal Position Detection
YP
YM
XP
VDD
GND
Volt
Vertical Position Detection
Pen
Contact
720
32142D–06/2013
ATUC64/128/256L3/4U
29.7.3 Resistive Touch Screen Pin Connections
The resistive touch screen film signals connects to the ADCIFB using the AD and ADP pins. The
XP (top) and XM (bottom) film signals are connected to ADtspo+0 and ADtspo+1 pins, and the YP
(right) and YM (left) signals are connected to ADtspo+2 and ADtspo+3 pins. The tspo index is
configurable through the Touch Screen Pin Offset (TSPO) field in the Mode Register (MR) and
allows the user to configure which AD pins to use for resistive touch screen applications. Writing
a zero to the TSPO field instructs the ADCIFB to use AD0 through AD3, where AD0 is connected
to XP, AD1 is connected to XM and so on. Writing a one to the TSPO field instructs the
ADCIFB to use AD1 through AD4 for resistive touch screen sequencing, where AD1 is connected
to XP and AD0 is free to be used as an ordinary ADC channel.
When the Analog Pin Output Enable (APOE) bit in the Mode Register (MR) is zero, the AD pins
are used to measure input voltage and drive the GND sequences, while the ADP pins are used
to drive the VDD sequences. This arrangement allows the user to reduce the voltage seen at the
AD input pins by inserting external resistors between ADP0 and XP and ADP1 and YP signals
which are again directly connected to the AD pins. It is important that the voltages observed at
the AD pins are not higher than the maximum allowed ADC input voltage. See Figure 29-3 on
page 721 for details regarding how to connect the resistive touch screen films to the AD and
ADP pins.
By adding a resistor between ADP0 and XP, and ADP1 and YP, the maximum voltage observed
at the AD pins can be controlled by the following voltage divider expressions:
The Rfilmx parameter is the film resistance observed when measuring between XP and XM. The
Rresistorx parameter is the resistor size inserted between ADP0 and XP. The definition of Rfilmy
and Rresistory is the same but for ADP1, YP, and YM instead.
Table 29-2. Resistive Touch Screen Pin Connections
ADCIFB Pin TS Signal, APOE == 0 TS Signal, APOE == 1
ADP0 Xp through a resistor No Connect
ADP1 Yp through a resistor No Connect
ADtspo+0 Xp Xp
ADtspo+1 Xm Xm
ADtspo+2 Yp Yp
ADtspo+3 Ym Ym
V ADtspo + 0
Rfilmx
Rfilmx Rresistorx + -------------------------------------------- V DP0 =
721
32142D–06/2013
ATUC64/128/256L3/4U
The ADP pins are used by default, as the APOE bit is zero after reset. Writing a one to the
APOE bit instructs the ADCIFB Resistive Touch Screen Sequencer to use the already connected
ADtspo+0 and ADtspo+2 pins to drive VDD to XP and YP signals directly. In this mode the
ADP pins can be used as general purpose I/O pins.
Before writing a one to the APOE bit the user must make sure that the I/O voltage is compatible
with the ADC input voltage. If the I/O voltage is higher than the maximum input voltage of the
ADC, permanent damage may occur. Refer to the Electrical Characteristics chapter for details.
Figure 29-3. Resistive Touch Screen Pin Connections
V ADtspo + 2
Rfilmy
Rfilmy Rresistory + -------------------------------------------- V DP1 =
ADtspo+1
XM
XP
YM YP
ADtspo+0
DP1
DP0
ADtspo+3
ADtspo+2
Analog Pin Output Enable (MR.APOE) == 0
ADtspo+1
XM
XP
YM YP
ADtspo+0
DP1
DP0
ADtspo+3
ADtspo+2
Analog Pin Output Enable (MR.APOE) == 1
NC
NC
722
32142D–06/2013
ATUC64/128/256L3/4U
29.7.4 Resistive Touch Screen Sequencer
The Resistive Touch Screen Sequencer is responsible for applying voltage to the resistive touch
screen films as described in Section 29.7.2. This is done by controlling the output enable and the
output value of the ADP and AD pins. This allows the Resistive Touch Screen Sequencer to add
a voltage gradient on one film while keeping the other film floating so a touch can be measured.
The Resistive Touch Screen Sequencer will when measuring the vertical position, apply VDD
and GND to the pins connected to XP and XM. The YP and YM pins are put in tristate mode so the
measurement of YP can proceed without interference. To compensate for ADC offset errors and
non ideal pad drivers, the actual voltage of XP and XM is measured as well, so the real values for
VDD and GND can be used in the contact point calculation to increase accuracy. See second
formula in Section 29.7.2.
When the vertical values are converted the same setup is applies for the second axes, by setting
XP and XM in tristate mode and applying VDD and GND to YP and YM. Refer to Section 29.8.3 for
details.
29.7.5 Pen Detect
If no contact is applied to the resistive touch screen films, any resistive touch screen conversion
result will be undefined as the film being measured is floating. This can be avoided by enabling
Pen Detect and only trigger resistive touch screen conversions when the Pen Contact
(PENCNT) status bit in the Status Register (SR) is one. Pen Detect is enabled by writing a one
to the Pen Detect (PENDET) bit in the Mode Register (MR).
When Pen Detect is enabled, the ADCIFB grounds the vertical panel by applying GND to XP and
XM and polarizes the horizontal panel by enabling pull-up on the pin connected to YP. The YM pin
will in this mode be tristated. Since there is no contact, no current is flowing and there is no
related power consumption. As soon as a contact occurs, GND will propagate to YM by pulling
down YP, allowing the contact to be registered by the ADCIFB.
A programmable debouncing filter can be used to filter out false pen detects because of noise.
The debouncing filter is programmable from one CLK_ADC period and up to 215 CLK_ADC periods.
The debouncer length is set by writing to the PENDBC field in MR.
723
32142D–06/2013
ATUC64/128/256L3/4U
Figure 29-4. Resistive Touch Screen Pen Detect
The Resistive Touch Screen Pen Detect can be used to generate an ADCIFB interrupt request
or it can be used to trig a conversion, so that a position can be measured as soon as a contact is
detected.
The Pen Detect Mode generates two types of status signals, reported in the Status Register
(SR):
• The bit PENCNT is set when current flows and remains set until current stops.
• The bit NOCNT is set when no current flows and remains set until current flows.
Before a current change is reflected in the SR, the new status must be stable for the duration of
the debouncing time.
Both status conditions can generate an interrupt request if the corresponding bit in the Interrupt
Mask Register (IMR) is one. Refer to Section 29.6.11 on page 717.
XP
XM
YM
YP
Tristate
GND
Pullup T o the ADC
Debouncer Pen Interrupt
PENDBC
GND
Resistive
Touch Screen
Sequencer
724
32142D–06/2013
ATUC64/128/256L3/4U
29.8 Operating Modes
The ADCIFB features two operating modes, each defining a separate conversion sequence:
• ADC Mode: At each trigger, all the enabled channels are converted.
• Resistive Touch Screen Mode: At each trigger, all enabled channels plus the resistive touch
screen channels are converted as described in Section 29.8.3. If channels except the
dedicated resistive touch screen channels are enabled, they are converted normally before
and after the resistive touch screen channels are converted.
The operating mode is selected by the TSAMOD field in the Mode Register (MR).
29.8.1 Conversion Triggers
A conversion sequence is started either by a software or by a hardware trigger. When a conversion
sequence is started, all enabled channels will be converted and made available in the
shared Last Converted Register (LCDR).
The software trigger is asserted by writing a one to the START field in the Control Register (CR).
The hardware trigger can be selected by the TRGMOD field in the Trigger Register (TRGR). Different
hardware triggers exist:
• External trigger, either rising or falling or any, detected on the external trigger pin TRIGGER
• Pen detect trigger, depending the PENDET bit in the Mode Register (MR)
• Continuous trigger, meaning the ADCIFB restarts the next sequence as soon as it finishes
the current one
• Periodic trigger, which is defined by the TRGR.TRGPER field
• Peripheral event trigger, allowing the Peripheral Event System to synchronize conversion with
some configured peripheral event source.
Enabling a hardware trigger does not disable the software trigger functionality. Thus, if a hardware
trigger is selected, the start of a conversion can still be initiated by the software trigger.
29.8.2 ADC Mode
In the ADC Mode, the active channels are defined by the Channel Status Register (CHSR). A
channel is enabled by writing a one to the corresponding bit in the Channel Enable Register
(CHER), and disabled by writing a one to the corresponding bit in the Channel Disable Register
(CHDR). The conversion results are stored in the Last Converted Data Register (LCDR) as they
become available, overwriting old conversions.
At each trigger, the following sequence is performed:
1. If ACR.SLEEP is one, wake up the ADC and wait for the startup time.
2. If Channel 0 is enabled, convert Channel 0 and store result in LCDR.
3. If Channel 1 is enabled, convert Channel 1 and store result in LCDR.
4. If Channel N is enabled, convert Channel N and store result in LCDR.
5. If ACR.SLEEP is one, place the ADC cell in a low-power state.
If the Peripheral DMA Controller is enabled, all converted values are transferred continuously
into the memory buffer.
29.8.3 Resistive Touch Screen Mode
Writing a one to the TSAMOD field in the Mode Register (MR) enables Resistive Touch Screen
Mode. In this mode the channels TSPO+0 to TSPO+3, corresponding to the resistive touch
725
32142D–06/2013
ATUC64/128/256L3/4U
screen inputs, are automatically activated. In addition, if any other channels are enabled, they
will be converted before and after the resistive touch screen conversion.
At each trigger, the following sequence is performed:
1. If ACR.SLEEP is one, wake up the ADC cell and wait for the startup time.
2. Convert all enabled channels before TSPO and store the results in the LCDR.
3. Apply supply on the inputs XP and XM during the Sample and Hold Time.
4. Convert Channel XM and store the result in TMP.
5. Apply supply on the inputs XP and XM during the Sample and Hold Time.
6. Convert Channel XP, subtract TMP from the result and store the subtracted result in
LCDR.
7. Apply supply on the inputs XP and XM during the Sample and Hold Time.
8. Convert Channel YP, subtract TMP from the result and store the subtracted result in
LCDR.
9. Apply supply on the inputs YP and YM during the Sample and Hold Time.
10. Convert Channel YM and store the result in TMP.
11. Apply supply on the inputs YP and YM during the Sample and Hold Time.
12. Convert Channel YP, subtract TMP from the result and store the subtracted result in
LCDR.
13. Apply supply on the inputs YP and YM during the Sample and Hold Time.
14. Convert Channel XP, subtract TMP from the result and store the subtracted result in
LCDR.
15. Convert all enabled channels after TSPO + 3 and store results in the LCDR.
16. If ACR.SLEEP is one, place the ADC cell in a low-power state.
The resulting buffer structure stored in memory is:
1. XP - XM
2. YP - XM
3. YP - YM
4. XP - YM.
The vertical position can be easily calculated by dividing the data at offset 1(XP - XM) by the data
at offset 2(YP - XM).
The horizontal position can be easily calculated by dividing the data at offset 3(YP - YM) by the
data at offset 4(XP - YM).
726
32142D–06/2013
ATUC64/128/256L3/4U
29.9 User Interface
Note: 1. The reset values for these registers are device specific. Please refer to the Module Configuration section at the end of this
chapter.
Table 29-3. ADCIFB Register Memory Map
Offset Register Name Access Reset
0x00 Control Register CR Write-only -
0x04 Mode Register MR Read/Write 0x00000000
0x08 ADC Configuration Register ACR Read/Write 0x00000000
0x0C Trigger Register TRGR Read/Write 0x00000000
0x10 Compare Value Register CVR Read/Write 0x00000000
0x14 Status Register SR Read-only 0x00000000
0x18 Interrupt Status Register ISR Read-only 0x00000000
0x1C Interrupt Clear Register ICR Write-only -
0x20 Interrupt Enable Register IER Write-only -
0x24 Interrupt Disable Register IDR Write-only -
0x28 Interrupt Mask Register IMR Read-only 0x00000000
0x2C Last Converted Data Register LCDR Read-only 0x00000000
0x30 Parameter Register PARAMETER Read-only -(1)
0x34 Version Register VERSION Read-only -(1)
0x40 Channel Enable Register CHER Write-only -
0x44 Channel Disable Register CHDR Write-only -
0x48 Channel Status Register CHSR Read-only 0x00000000
727
32142D–06/2013
ATUC64/128/256L3/4U
29.9.1 Control Register
Register Name: CR
Access Type: Write-only
Offset: 0x00
Reset Value: 0x00000000
• DIS: ADCDIFB Disable
Writing a zero to this bit has no effect.
Writing a one to this bit disables the ADCIFB.
Note: Disabling the ADCIFB effectively stops all clocks in the module so the user must make sure the ADCIFB is idle before
disabling the ADCIFB.
• EN: ADCIFB Enable
Writing a zero to this bit has no effect.
Writing a one to this bit enables the ADCIFB.
Note: The ADCIFB must be enabled before use.
• START: Start Conversion
Writing a zero to this bit has no effect.
Writing a one to this bit starts an Analog-to-Digital conversion.
• SWRST: Software Reset
Writing a zero to this bit has no effect.
Writing a one to this bit resets the ADCIFB, simulating a hardware reset.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
- - - - - - DIS EN
76543210
- - - - - - START SWRST
728
32142D–06/2013
ATUC64/128/256L3/4U
29.9.2 Mode Register
Name: MR
Access Type: Read/Write
Offset: 0x04
Reset Value: 0x00000000
• PENDBC: Pen Detect Debouncing Period
Period = 2PENDBC*TCLK_ADC
• TSPO: Touch Screen Pin Offset
The Touch Screen Pin Offset field is used to indicate which AD pins are connected to the resistive touch screen film edges. Only
an offset is specified and it is assumed that the resistive touch screen films are connected sequentially from the specified offset
pin and up to and including offset + 3 (4 pins).
• APOE: Analog Pin Output Enable
0: AD pins are not used to drive VDD in resistive touch screen sequence.
1: AD pins are used to drive VDD in resistive touch screen sequence.
Note: If the selected I/O voltage configuration is incompatible with the Analog-to-Digital converter cell voltage specification, this
bit must stay cleared to avoid damaging the ADC. In this case the ADP pins must be used to drive VDD instead, as described in
Section 29.7.3. If the I/O and ADC voltages are compatible, the AD pins can be used directly by writing a one to this bit. In this
case the ADP pins can be ignored.
• ACE: Analog Compare Enable
0: The analog compare functionality is disabled.
1: The analog compare functionality is enabled.
• PENDET: Pen Detect
0: The pen detect functionality is disabled.
1: The pen detect functionality is enabled.
Note: Touch detection logic can only be enabled when the ADC sequencer is idle. For successful pen detection the user must
make sure there is enough idle time between consecutive scans for the touch detection logic to settle.
• TSAMOD: Touch Screen ADC Mode
0: Touch Screen Mode is disabled.
1: Touch Screen Mode is enabled.
31 30 29 28 27 26 25 24
PENDBC - - - -
23 22 21 20 19 18 17 16
TSPO
15 14 13 12 11 10 9 8
--------
76543210
- APOE ACE PENDET - - - TSAMOD
729
32142D–06/2013
ATUC64/128/256L3/4U
29.9.3 ADC Configuration Register
Name: ACR
Access Type: Read/Write
Offset: 0x08
Reset Value: 0x00000000
• SHTIM: Sample & Hold Time for ADC Channels
• STARTUP: Startup Time
• PRESCAL: Prescaler Rate Selection
• RES: Resolution Selection
0: 8-bit resolution.
1: 10-bit resolution.
2: 11-bit resolution, interpolated.
3: 12-bit resolution, interpolated.
• SLEEP: ADC Sleep Mode
0: ADC Sleep Mode is disabled.
1: ADC Sleep Mode is enabled.
31 30 29 28 27 26 25 24
- - - - SHTIM
23 22 21 20 19 18 17 16
- STARTUP
15 14 13 12 11 10 9 8
- - PRESCAL
76543210
- - RES - - - SLEEP
TSAMPLE&HOLD SHTIM + 2 TCLK_ADC =
TARTUP STARTUP + 1 8 TCLK_AD =
TCLK_ADC = PRESCAL + 1 2 TCLK_ADCIFB
730
32142D–06/2013
ATUC64/128/256L3/4U
29.9.4 Trigger Register
Name: TRGR
Access Type: Read/Write
Offset: 0x0C
Reset Value: 0x00000000
• TRGPER: Trigger Period
Effective only if TRGMOD defines a Periodic Trigger.
Defines the periodic trigger period, with the following equations:
Trigger Period = TRGPER *TCLK_ADC
• TRGMOD: Trigger Mode
31 30 29 28 27 26 25 24
TRGPER[15:8]
23 22 21 20 19 18 17 16
TRGPER[7:0]
15 14 13 12 11 10 9 8
--------
76543210
- - - - - TRGMOD
Table 29-4. Trigger Modes
TRGMOD Selected Trigger Mode
0 0 0 No trigger, only software trigger can start conversions
0 0 1 External Trigger Rising Edge
0 1 0 External Trigger Falling Edge
0 1 1 External Trigger Any Edge
100 Pen Detect Trigger (shall be selected only if PENDET is set and TSAMOD = Touch
Screen mode)
1 0 1 Periodic Trigger (TRGPER shall be initiated appropriately)
1 1 0 Continuous Mode
1 1 1 Peripheral Event Trigger
731
32142D–06/2013
ATUC64/128/256L3/4U
29.9.5 Compare Value Register
Name: CVR
Access Type: Read/Write
Offset: 0x10
Reset Value: 0x00000000
• HV: High Value
Defines the high value used when comparing analog input.
• LV: Low Value
Defines the low value used when comparing analog input.
31 30 29 28 27 26 25 24
- - - - HV[11:8]
23 22 21 20 19 18 17 16
HV[7:0]
15 14 13 12 11 10 9 8
- - - - LV[11:8]
76543210
LV[7:0]
732
32142D–06/2013
ATUC64/128/256L3/4U
29.9.6 Status Register
Name: SR
Access Type: Read-only
Offset: 0x14
Reset Value: 0x00000000
• EN: Enable Status
0: The ADCIFB is disabled.
1: The ADCIFB is enabled.
This bit is cleared when CR.DIS is written to one.
This bit is set when CR.EN is written to one.
• CELSE: Compare Else Status
This bit is cleared when either CLT or CGT are detected or when analog compare is disabled.
This bit is set when no CLT or CGT are detected on the last converted data and analog compare is enabled.
• CGT: Compare Greater Than Status
This bit is cleared when no compare greater than CVR.HV is detected on the last converted data or when analog compare is
disabled.
This bit is set when compare greater than CVR.HV is detected on the last converted data and analog compare is enabled.
• CLT: Compare Lesser Than Status
This bit is cleared when no compare lesser than CVR.LV is detected on the last converted data or when analog compare is
disabled.
This bit is set when compare lesser than CVR.LV is detected on the last converted data and analog compare is enabled.
• BUSY: Busy Status
This bit is cleared when the ADCIFB is ready to perform a conversion sequence.
This bit is set when the ADCIFB is busy performing a convention sequence.
• READY: Ready Status
This bit is cleared when the ADCIFB is busy performing a conversion sequence
This bit is set when the ADCIFB is ready to perform a conversion sequence.
• NOCNT: No Contact Status
This bit is cleared when no contact loss is detected or pen detect is disabled
This bit is set when contact loss is detected and pen detect is enabled.
• PENCNT: Pen Contact Status
This bit is cleared when no contact is detected or pen detect is disabled.
31 30 29 28 27 26 25 24
- - - - - - - EN
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
- CELSE CGT CLT - - BUSY READY
76543210
- - NOCNT PENCNT - - OVRE DRDY
733
32142D–06/2013
ATUC64/128/256L3/4U
This bit is set when pen contact is detected and pen detect is enabled.
• OVRE: Overrun Error Status
This bit is cleared when no Overrun Error has occurred since the start of a conversion sequence.
This bit is set when one or more Overrun Error has occurred since the start of a conversion sequence.
• DRDY: Data Ready Status
0: No data has been converted since the last reset.
1: One or more conversions have completed since the last reset and data is available in LCDR.
This bit is cleared when CR.SWRST is written to one.
This bit is set when one or more conversions have completed and data is available in LCDR.
734
32142D–06/2013
ATUC64/128/256L3/4U
29.9.7 Interrupt Status Register
Name: ISR
Access Type: Read-only
Offset: 0x18
Reset Value: 0x00000000
• CELSE: Compare Else Status
This bit is cleared when the corresponding bit in ICR is written to one.
This bit is set when the corresponding bit in SR has a zero-to-one transition.
• CGT: Compare Greater Than Status
This bit is cleared when the corresponding bit in ICR is written to one.
This bit is set when the corresponding bit in SR has a zero-to-one transition.
• CLT: Compare Lesser Than Status
This bit is cleared when the corresponding bit in ICR is written to one.
This bit is set when the corresponding bit in SR has a zero-to-one transition.
• BUSY: Busy Status
This bit is cleared when the corresponding bit in ICR is written to one.
This bit is set when the corresponding bit in SR has a zero-to-one transition.
• READY: Ready Status
This bit is cleared when the corresponding bit in ICR is written to one.
This bit is set when the corresponding bit in SR has a zero-to-one transition.
• NOCNT: No Contact Status
This bit is cleared when the corresponding bit in ICR is written to one.
This bit is set when the corresponding bit in SR has a zero-to-one transition.
• PENCNT: Pen Contact Status
This bit is cleared when the corresponding bit in ICR is written to one.
This bit is set when the corresponding bit in SR has a zero-to-one transition.
• OVRE: Overrun Error Status
This bit is cleared when the corresponding bit in ICR is written to one.
This bit is set when the corresponding bit in SR has a zero-to-one transition.
• DRDY: Data Ready Status
This bit is cleared when the corresponding bit in ICR is written to one.
This bit is set when a conversion has completed and new data is available in LCDR.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
- CELSE CGT CLT - - BUSY READY
76543210
- - NOCNT PENCNT - - OVRE DRDY
735
32142D–06/2013
ATUC64/128/256L3/4U
29.9.8 Interrupt Clear Register
Name: ICR
Access Type: Write-only
Offset: 0x1C
Reset Value: 0x00000000
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will clear the corresponding bit in ISR and the corresponding interrupt request.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
- CELSE CGT CLT - - BUSY READY
76543210
- - NOCNT PENCNT - - OVRE DRDY
736
32142D–06/2013
ATUC64/128/256L3/4U
29.9.9 Interrupt Enable Register
Name: IER
Access Type: Write-only
Offset: 0x20
Reset Value: 0x00000000
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will set the corresponding bit in IMR.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
- CELSE CGT CLT - - BUSY READY
76543210
- - NOCNT PENCNT - - OVRE DRDY
737
32142D–06/2013
ATUC64/128/256L3/4U
29.9.10 Interrupt Disable Register
Name: IDR
Access Type: Write-only
Offset: 0x24
Reset Value: 0x00000000
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will clear the corresponding bit in IMR.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
- CELSE CGT CLT - - BUSY READY
76543210
- - NOCNT PENCNT - - OVRE DRDY
738
32142D–06/2013
ATUC64/128/256L3/4U
29.9.11 Interrupt Mask Register
Name: IMR
Access Type: Read-only
Offset: 0x28
Reset Value: 0x00000000
0: The corresponding interrupt is disabled.
1: The corresponding interrupt is enabled.
A bit in this register is cleared by writing a one to the corresponding bit in Interrupt Disable Register (IDR).
A bit in this register is set by writing a one to the corresponding bit in Interrupt Enable Register (IER).
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
- CELSE CGT CLT - - BUSY READY
76543210
- - NOCNT PENCNT - - OVRE DRDY
739
32142D–06/2013
ATUC64/128/256L3/4U
29.9.12 Last Converted Data Register
Name: LCDR
Access Type: Read-only
Offset: 0x2C
Reset Value: 0x00000000
• LCCH: Last Converted Channel
This field indicates what channel was last converted, i.e. what channel the LDATA represents.
• LDATA: Last Data Converted
The analog-to-digital conversion data is placed in this register at the end of a conversion on any analog channel and remains
until a new conversion on any analog channel is completed.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
LCCH
15 14 13 12 11 10 9 8
- - - - LDATA[11:8]
76543210
LDATA[7:0]
740
32142D–06/2013
ATUC64/128/256L3/4U
29.9.13 Parameter Register
Name: PARAMETER
Access Type: Read-only
Offset: 0x30
Reset Value: 0x00000000
• CHn: Channel n Implemented
0: The corresponding channel is not implemented.
1: The corresponding channel is implemented.
31 30 29 28 27 26 25 24
CH31 CH30 CH29 CH28 CH27 CH26 CH25 CH24
23 22 21 20 19 18 17 16
CH23 CH22 CH21 CH20 CH19 CH18 CH17 CH16
15 14 13 12 11 10 9 8
CH15 CH14 CH13 CH12 CH11 CH10 CH9 CH8
76543210
CH7 CH6 CH5 CH4 CH3 CH2 CH1 CH0
741
32142D–06/2013
ATUC64/128/256L3/4U
29.9.14 Version Register
Name: VERSION
Access Type: Read-only
Offset: 0x34
Reset Value: 0x00000000
• VARIANT: Variant Number
Reserved. No functionality associated.
• VERSION: Version Number
Version number of the Module. No functionality associated.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
- - - - VARIANT
15 14 13 12 11 10 9 8
- - - - VERSION[11:8]
76543210
VERSION[7:0]
742
32142D–06/2013
ATUC64/128/256L3/4U
29.9.15 Channel Enable Register
Name: CHER
Access Type: Write-only
Offset: 0x40
Reset Value: 0x00000000
• CHn: Channel n Enable
Writing a zero to a bit in this register has no effect
Writing a one to a bit in this register enables the corresponding channel
The number of available channels is device dependent. Please refer to the Module Configuration section at the end of this
chapter for information regarding which channels are implemented.
31 30 29 28 27 26 25 24
CH31 CH30 CH29 CH28 CH27 CH26 CH25 CH24
23 22 21 20 19 18 17 16
CH23 CH22 CH21 CH20 CH19 CH18 CH17 CH16
15 14 13 12 11 10 9 8
CH15 CH14 CH13 CH12 CH11 CH10 CH9 CH8
76543210
CH7 CH6 CH5 CH4 CH3 CH2 CH1 CH0
743
32142D–06/2013
ATUC64/128/256L3/4U
29.9.16 Channel Disable Register
Name: CHDR
Access Type: Write-only
Offset: 0x44
Reset Value: 0x00000000
• CHn: Channel N Disable
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register disables the corresponding channel.
Warning: If the corresponding channel is disabled during a conversion, or if it is disabled and then re-enabled during a
conversion, its associated data and its corresponding DRDY and OVRE bits in SR are unpredictable.
The number of available channels is device dependent. Please refer to the Module Configuration section at the end of this
chapter for information regarding how many channels are implemented.
31 30 29 28 27 26 25 24
CH31 CH30 CH29 CH28 CH27 CH26 CH25 CH24
23 22 21 20 19 18 17 16
CH23 CH22 CH21 CH20 CH19 CH18 CH17 CH16
15 14 13 12 11 10 9 8
CH15 CH14 CH13 CH12 CH11 CH10 CH9 CH8
76543210
CH7 CH6 CH5 CH4 CH3 CH2 CH1 CH0
744
32142D–06/2013
ATUC64/128/256L3/4U
29.9.17 Channel Status Register
Name: CHSR
Access Type: Read-only
Offset: 0x48
Reset Value: 0x00000000
• CHn: Channel N Status
0: The corresponding channel is disabled.
1: The corresponding channel is enabled.
A bit in this register is cleared by writing a one to the corresponding bit in Channel Disable Register (CHDR).
A bit in this register is set by writing a one to the corresponding bit in Channel Enable Register (CHER).
The number of available channels is device dependent. Please refer to the Module Configuration section at the end of this
chapter for information regarding how many channels are implemented.
31 30 29 28 27 26 25 24
CH31 CH30 CH29 CH28 CH27 CH26 CH25 CH24
23 22 21 20 19 18 17 16
CH23 CH22 CH21 CH20 CH19 CH18 CH17 CH16
15 14 13 12 11 10 9 8
CH15 CH14 CH13 CH12 CH11 CH10 CH9 CH8
76543210
CH7 CH6 CH5 CH4 CH3 CH2 CH1 CH0
745
32142D–06/2013
ATUC64/128/256L3/4U
29.10 Module Configuration
The specific configuration for each ADCIFB instance is listed in the following tables.The module
bus clocks listed here are connected to the system bus clocks. Please refer to the Power Manager
chapter for details.
Note: 1. AD3 does not exist
Table 29-5. Module Configuration
Feature ADCIFB
Number of ADC channels 9 (8 + 1 internal temperature sensor channel)
Table 29-6. ADCIFB Clocks
Clock Name Description
CLK_ADCIFB Clock for the ADCIFB bus interface
Table 29-7. Register Reset Values
Register Reset Value
VERSION 0x00000110
PARAMETER 0x000003FF
Table 29-8. ADC Input Channels(1)
Channel Input
CH0 AD0
CH1 AD1
CH2 AD2
CH4 AD4
CH5 AD5
CH6 AD6
CH7 AD7
CH8 AD8
CH9 Temperature sensor
746
32142D–06/2013
ATUC64/128/256L3/4U
30. Analog Comparator Interface (ACIFB)
Rev: 2.0.2.2
30.1 Features
• Controls an array of Analog Comparators
• Low power option
– Single shot mode support
• Selectable settings for filter option
– Filter length and hysteresis
• Window Mode
– Detect inside/outside window
– Detect above/below window
• Interrupt
– On comparator result rising edge, falling edge, toggle
– Inside window, outside window, toggle
– When startup time has passed
• Can generate events to the peripheral event system
30.2 Overview
The Analog Comparator Interface (ACIFB) is able to control a number of Analog Comparators
(AC) with identical behavior. An Analog Comparator compares two voltages and gives a compare
output depending on this comparison.
The ACIFB can be configured in normal mode using each comparator independently or in window
mode using defined comparator pairs to observe a window.
The number of channels implemented is device specific. Refer to the Module Configuration section
at the end of this chapter for details.
747
32142D–06/2013
ATUC64/128/256L3/4U
30.3 Block Diagram
Figure 30-1. ACIFB Block Diagram
30.4 I/O Lines Description
There are two groups of analog comparators, A and B, as shown in Table 30-1. In normal mode,
this grouping does not have any meaning. In window mode, two analog comparators, one from
group A and the corresponding comparator from group B, are paired.
……………...
TRIGGER
EVENTS
IRQ
GCLK
Peripheral Bus ACIFB
Analog
Comparators
PERIPHERAL
EVENT
GENERATION
-
+
AC
INN
INP
CONF0.INSELN
-
+
AC
INN
INP
CONFn.INSELN
FILTER
FILTER
INTERRUPT
GENERATION
CLK_ACIFB
CTRL.ACTEST
TR.ACTESTn
TR.ACTEST0
ACOUT0
ACOUTn
ACP0
ACN0
ACREFN
ACPn
ACNn
Table 30-1. Analog Comparator Groups for Window Mode
Group A Group B Pair Number
AC0 AC1 0
AC2 AC3 1
AC4 AC5 2
AC6 AC7 3
Table 30-2. I/O Line Description
Pin Name Pin Description Type
ACAPn Positive reference pin for Analog Comparator A n Analog
ACANn Negative reference pin for Analog Comparator A n Analog
748
32142D–06/2013
ATUC64/128/256L3/4U
The signal names corresponds to the groups A and B of analog comparators. For normal mode,
the mapping from input signal names in the block diagram to the signal names is given in Table
30-3.
30.5 Product Dependencies
In order to use this module, other parts of the system must be configured correctly, as described
below.
30.5.1 I/O Lines
The ACIFB pins are multiplexed with other peripherals. The user must first program the I/O Controller
to give control of the pins to the ACIFB.
30.5.2 Power Management
If the CPU enters a sleep mode that disables clocks used by the ACIFB, the ACIFB will stop
functioning and resume operation after the system wakes up from sleep mode.
30.5.3 Clocks
The clock for the ACIFB bus interface (CLK_ACIFB) is generated by the Power Manager. This
clock is enabled at reset, and can be disabled in the Power Manager. It is recommended to disable
the ACIFB before disabling the clock, to avoid freezing the ACIFB in an undefined state.
The ACIFB uses a GCLK as clock source for the Analog Comparators. The user must set up this
GCLK at the right frequency. The CLK_ACIFB clock of the interface must be at least 4x the
GCLK frequency used in the comparators. The GCLK is used both for measuring the startup
time of a comparator, and to give a frequency for the comparisons done in Continuous Measurement
Mode, see Section 30.6.
Refer to the Electrical Characteristics chapter for GCLK frequency limitations.
ACBPn Positive reference pin for Analog Comparator B n Analog
ACBNn Negative reference pin for Analog Comparator B n Analog
ACREFN Reference Voltage for all comparators selectable for INN Analog
Table 30-3. Signal Name Mapping
Pin Name Channel Number Normal Mode
ACAP0/ACAN0 0 ACP0/ACN0
ACBP0/ACBN0 1 ACP1/ACN1
ACAP1/ACAN1 2 ACP2/ACN2
ACBP1/ACBN1 3 ACP3/ACN3
ACAP2/ACAN2 4 ACP4/ACN4
ACBP2/ACBN2 5 ACP5/ACN5
ACAP3/ACAN3 6 ACP6/ACN6
ACBP3/ACBN3 7 ACP7/ACN7
Table 30-2. I/O Line Description
Pin Name Pin Description Type
749
32142D–06/2013
ATUC64/128/256L3/4U
30.5.4 Interrupts
The ACIFB interrupt request line is connected to the interrupt controller. Using the ACIFB interrupt
requires the interrupt controller to be programmed first.
30.5.5 Peripheral Events
The ACIFB peripheral events are connected via the Peripheral Event System. Refer to the
Peripheral Event System chapter for details.
30.5.6 Debug Operation
When an external debugger forces the CPU into debug mode, the ACIFB continues normal
operation. If the ACIFB is configured in a way that requires it to be periodically serviced by the
CPU through interrupts or similar, improper operation or data loss may result during debugging.
30.6 Functional Description
The ACIFB is enabled by writing a one to the Control Register Enable bit (CTRL.EN). Additionally,
the comparators must be individually enabled by programming the MODE field in the AC
Configuration Register (CONFn.MODE).
The results from the individual comparators can either be used directly (normal mode), or the
results from two comparators can be grouped to generate a comparison window (window mode).
All comparators need not be in the same mode, some comparators may be in normal mode,
while others are in window mode. There are restrictions on which AC channels that can be
grouped together in a window pair, see Section 30.6.5.
30.6.1 Analog Comparator Operation
Each AC channel can be in one of four different modes, determined by CONFn.MODE:
• Off
• Continuous Measurement Mode (CM)
• User Triggered Single Measurement Mode (UT)
• Event Triggered Single Measurement Mode (ET)
After being enabled, a startup time defined in CTRL.SUT is required before the result of the
comparison is ready. The GCLK is used for measuring the startup time of a comparator,
During the startup time the AC output is not available. When the ACn Ready bit in the Status
Register (SR.ACRDYn) is one, the output of ACn is ready. In window mode the result is available
when both the comparator outputs are ready (SR.ACRDYn=1 and SR.ACRDYn+1=1).
30.6.1.1 Continuous Measurement Mode
In CM, the Analog Comparator is continuously enabled and performing comparisons. This
ensures that the result of the latest comparison is always available in the ACn Current Comparison
Status bit in the Status Register (SR.ACCSn). Comparisons are done on every positive
edge of GCLK.
CM is enabled by writing CONFn.MODE to 1. After the startup time has passed, a comparison is
done and SR is updated. Appropriate peripheral events and interrupts are also generated. New
comparisons are performed continuously until the CONFn.MODE field is written to 0.
750
32142D–06/2013
ATUC64/128/256L3/4U
30.6.1.2 User Triggered Single Measurement Mode
In the UT mode, the user starts a single comparison by writing a one to the User Start Single
Comparison bit (CTRL.USTART). This mode is enabled by writing CONFn.MODE to 2. After the
startup time has passed, a single comparison is done and SR is updated. Appropriate peripheral
events and interrupts are also generated. No new comparisons will be performed.
CTRL.USTART is cleared automatically by hardware when the single comparison has been
done.
30.6.1.3 Event Triggered Single Measurement Mode
This mode is enabled by writing CONFn.MODE to 3 and Peripheral Event Trigger Enable
(CTRL.EVENTEN) to one. The ET mode is similar to the UT mode, the difference is that a
peripheral event from another hardware module causes the hardware to automatically set the
Peripheral Event Start Single Comparison bit (CTRL.ESTART). After the startup time has
passed, a single comparison is done and SR is updated. Appropriate peripheral events and
interrupts are also generated. No new comparisons will be performed. CTRL.ESTART is cleared
automatically by hardware when the single comparison has been done.
30.6.1.4 Selecting Comparator Inputs
Each Analog Comparator has one positive (INP) and one negative (INN) input. The positive
input is fed from an external input pin (ACPn). The negative input can either be fed from an
external input pin (ACNn) or from a reference voltage common to all ACs (ACREFN).
The user selects the input source as follows:
• In normal mode with the Negative Input Select and Positive Input Select fields
(CONFn.INSELN and CONFn.INSELP).
• In window mode with CONFn.INSELN, CONFn.INSELP and CONFn+1.INSELN,
CONFn+1,INSELP. The user must configure CONFn.INSELN and CONFn+1.INSELP to the
same source.
30.6.2 Interrupt Generation
The interrupt request will be generated if the corresponding bit in the Interrupt Mask Register
(IMR) is set. Bits in IMR are set by writing a one to the corresponding bit in the Interrupt Enable
Register (IER), and cleared by writing a one to the corresponding bit in the Interrupt Disable
Register (IDR). The interrupt request remains active until the corresponding bit in ISR is cleared
by writing a one to the corresponding bit in the Interrupt Status Clear Register (ICR).
30.6.3 Peripheral Event Generation
The ACIFB can be set up so that certain comparison results notify other parts of the device via
the Peripheral Event system. Refer to Section 30.6.4.3 and Section 30.6.5.3 for information on
which comparison results can generate events, and how to configure the ACIFB to achieve this.
Zero or one event will be generated per comparison.
30.6.4 Normal Mode
In normal mode all Analog Comparators are operating independently.
30.6.4.1 Normal Mode Output
Each Analog Comparator generates one output ACOUT according to the input voltages on INP
(AC positive input) and INN (AC negative input):
751
32142D–06/2013
ATUC64/128/256L3/4U
• ACOUT = 1 if VINP > VINN
• ACOUT = 0 if VINP < VINN
• ACOUT = 0 if the AC output is not available (SR.ACRDY = 0)
The output can optionally be filtered, as described in Section 30.6.6.
30.6.4.2 Normal Mode Interrupt
The AC channels can generate interrupts. The Interrupt Settings field in the Configuration Register
(CONFn.IS) can be configured to select when the AC will generate an interrupt:
• When VINP > VINN
• When VINP < VINN
• On toggle of the AC output (ACOUT)
• When comparison has been done
30.6.4.3 Normal Mode Peripheral Events
The ACIFB can generate peripheral events according to the configuration of CONFn.EVENN
and CONFn.EVENP.
• When VINP > VINN or
• When VINP < VINN or
• On toggle of the AC output (ACOUT)
30.6.5 Window Mode
In window mode, two ACs (an even and the following odd build up a pair) are grouped.
The negative input of ACn (even) and the positive input of ACn+1 (odd) has to be connected
together externally to the device and are controlled by the Input Select fields in the AC Configuration
Registers (CONFn.INSELN and CONFn+1.INSELP). The positive input of ACn (even) and
the negative input of ACn+1 (odd) can still be configured independently by CONFn.INSELP and
CONFn+1.INSELN, respectively.
752
32142D–06/2013
ATUC64/128/256L3/4U
Figure 30-2. Analog Comparator Interface in Window Mode
30.6.5.1 Window Mode Output
When operating in window mode, each channel generates the same ACOUT outputs as in normal
mode, see Section 30.6.4.1.
Additionally, the ACIFB generates a window mode signal (acwout) according to the common
input voltage to be compared:
• ACWOUT = 1 if the common input voltage is inside the window, VACN(N+1) < Vcommon < VACP(N)
• ACWOUT = 0 if the common input voltage is outside the window, Vcommon < VACN(N+1) or
Vcommon > VACP(N)
• ACWOUT = 0 if the window mode output is not available (SR.ACRDYn=0 or
SR.ACRDYn+1=0)
30.6.5.2 Window Mode Interrupts
When operating in window mode, each channel can generate the same interrupts as in normal
mode, see Section 30.6.4.2.
Additionally, when channels operate in window mode, programming Window Mode Interrupt Settings
in the Window Mode Configuration Register (CONFWn.WIS) can cause interrupts to be
generated when:
• As soon as the common input voltage is inside the window.
• As soon as the common input voltage is outside the window.
• On toggle of the window compare output (ACWOUT).
• When the comparison in both channels in the window pair is ready.
Comparator pair 0
-
+
AC0
Interrupt
Generator
Window
Module
ACOUT0
Peripheral Event
Generator
Window
window event
-
+
AC1
Filter
Filter
SR.ACCS0
SR.WFCS0
ACAP0
ACAN0
ACBP0
COMMON ACWOUT
ACBN0
IRQ
ACOUT1
753
32142D–06/2013
ATUC64/128/256L3/4U
30.6.5.3 Window Mode Peripheral Events
When operating in window mode, each channel can generate the same peripheral events as in
normal mode, see Section 30.6.4.3.
Additionally, when channels operate in window mode, programming Window Mode Event Selection
Source (CONFWn.WEVSRC) can cause peripheral events to be generated when:
• As soon as the common input voltage is inside the window.
• As soon as the common input voltage is outside the window.
• On toggle of the window compare output (ACWOUT)
• Whenever a comparison is ready and the common input voltage is inside the window.
• Whenever a comparison is ready and the common input voltage is outside the window.
• When the comparison in both channels in the window pair is ready.
30.6.6 Filtering
The output of the comparator can be filtered to reduce noise. The filter length is determined by
the Filter Length field in the CONFn register (CONFn.FLEN). The filter samples the Analog
Comparator output at the GCLK frequency for 2CONFn.FLEN samples. A separate counter (CNT)
counts the number of cycles the AC output was one. This filter is deactivated if CONFn.FLEN
equals 0.
If the filter is enabled, the Hysteresis Value field HYS in the CONFn register (CONFn.HYS) can
be used to define a hysteresis value. The hysteresis value should be chosen so that:
The filter function is defined by:
The filtering algorithm is explained in Figure 30-3. 2FLEN measurements are sampled. If the number
of measurements that are zero is less than (2FLEN/2 - HYS), the filtered result is zero. If the
number of measurements that are one is more than (2FLEN/2 + HYS), the filtered result is one.
Otherwise, the result is unchanged.
2FLEN
2 ---------------- HYS
CNT 2FLEN
2 ---------------- + HYS comp = 1
2FLEN
2 ---------------- + HYS CNT 2FLEN
2 ----------------–HYS comp unchanged
CNT 2FLEN
2 ----------------–HYS comp = 0
754
32142D–06/2013
ATUC64/128/256L3/4U
Figure 30-3. The Filtering Algorithm
30.7 Peripheral Event Triggers
Peripheral events from other modules can trigger comparisons in the ACIFB. All channels that
are set up in Event Triggered Single Measurement Mode will be started simultaneously when a
peripheral event is received. Channels that are operating in Continuous Measurement Mode or
User Triggered Single Measurement Mode will be unaffected by the received event. The software
can still operate these channels independently of channels in Event Triggered Single
Measurement Mode.
A peripheral event will trigger one or more comparisons, in normal or window mode.
30.8 AC Test mode
By writing the Analog Comparator Test Mode (CR.ACTEST) bit to one, the outputs from the ACs
are overridden by the value in the Test Register (TR), see Figure 30-1. This is useful for software
development.
2
FLEN
2
FLEN
2
HYS HYS
”Result=0" ”Result=1"
Result =
UNCHANGED
0
755
32142D–06/2013
ATUC64/128/256L3/4U
30.9 User Interface
Note: 1. The reset values for these registers are device specific. Please refer to the Module Configuration section at the end of this
chapter.
Table 30-4. ACIFB Register Memory Map
Offset Register Register Name Access Reset
0x00 Control Register CTRL Read/Write 0x00000000
0x04 Status Register SR Read-only 0x00000000
0x10 Interrupt Enable Register IER Write-only 0x00000000
0x14 Interrupt Disable Register IDR Write-only 0x00000000
0x18 Interrupt Mask Register IMR Read-only 0x00000000
0x1C Interrupt Status Register ISR Read-only 0x00000000
0x20 Interrupt Status Clear Register ICR Write-only 0x00000000
0x24 Test Register TR Read/Write 0x00000000
0x30 Parameter Register PARAMETER Read-only -(1)
0x34 Version Register VERSION Read-only -(1)
0x80 Window0 Configuration Register CONFW0 Read/Write 0x00000000
0x84 Window1 Configuration Register CONFW1 Read/Write 0x00000000
0x88 Window2 Configuration Register CONFW2 Read/Write 0x00000000
0x8C Window3 Configuration Register CONFW3 Read/Write 0x00000000
0xD0 AC0 Configuration Register CONF0 Read/Write 0x00000000
0xD4 AC1 Configuration Register CONF1 Read/Write 0x00000000
0xD8 AC2 Configuration Register CONF2 Read/Write 0x00000000
0xDC AC3 Configuration Register CONF3 Read/Write 0x00000000
0xE0 AC4 Configuration Register CONF4 Read/Write 0x00000000
0xE4 AC5 Configuration Register CONF5 Read/Write 0x00000000
0xE8 AC6 Configuration Register CONF6 Read/Write 0x00000000
0xEC AC7 Configuration Register CONF7 Read/Write 0x00000000
756
32142D–06/2013
ATUC64/128/256L3/4U
30.9.1 Control Register
Name: CTRL
Access Type: Read/Write
Offset: 0x00
Reset Value: 0x00000000
• SUT: Startup Time
Analog Comparator startup time = .
Each time an AC is enabled, the AC comparison will be enabled after the startup time of the AC.
• ACTEST: Analog Comparator Test Mode
0: The Analog Comparator outputs feeds the channel logic in ACIFB.
1: The Analog Comparator outputs are bypassed with the AC Test Register.
• ESTART: Peripheral Event Start Single Comparison
Writing a zero to this bit has no effect.
Writing a one to this bit starts a comparison and can be used for test purposes.
This bit is cleared when comparison is done.
This bit is set when an enabled peripheral event is received.
• USTART: User Start Single Comparison
Writing a zero to this bit has no effect.
Writing a one to this bit starts a Single Measurement Mode comparison.
This bit is cleared when comparison is done.
• EVENTEN: Peripheral Event Trigger Enable
0: A peripheral event will not trigger a comparison.
1: Enable comparison triggered by a peripheral event.
• EN: ACIFB Enable
0: The ACIFB is disabled.
1: The ACIFB is enabled.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
- - - - - - SUT[9:8]
15 14 13 12 11 10 9 8
SUT[7:0]
76543210
ACTEST - ESTART USTART - - -EVENTEN EN
SUT
FGCLK
----------------
757
32142D–06/2013
ATUC64/128/256L3/4U
30.9.2 Status Register
Name: SR
Access Type: Read-only
Offset: 0x04
Reset Value: 0x00000000
• WFCSn: Window Mode Current Status
This bit is cleared when the common input voltage is outside the window.
This bit is set when the common input voltage is inside the window.
• ACRDYn: ACn Ready
This bit is cleared when the AC output (ACOUT) is not ready.
This bit is set when the AC output (ACOUT) is ready, AC is enabled and its startup time is over.
• ACCSn: ACn Current Comparison Status
This bit is cleared when VINP is currently lower than VINN
This bit is set when VINP is currently greater than VINN.
31 30 29 28 27 26 25 24
- - - - WFCS3 WFCS2 WFCS1 WFCS0
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
ACRDY7 ACCS7 ACRDY6 ACCS6 ACRDY5 ACCS5 ACRDY4 ACCS4
76543210
ACRDY3 ACCS3 ACRDY2 ACCS2 ACRDY1 ACCS1 ACRDY0 ACCS0
758
32142D–06/2013
ATUC64/128/256L3/4U
30.9.3 Interrupt Enable Register
Name: IER
Access Type: Write-only
Offset: 0x10
Reset Value: 0x00000000
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will set the corresponding bit in IMR.
31 30 29 28 27 26 25 24
- - - - WFINT3 WFINT2 WFINT1 WFINT0
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
SUTINT7 ACINT7 SUTINT6 ACINT6 SUTINT5 ACINT5 SUTINT4 ACINT4
76543210
SUTINT3 ACINT3 SUTINT2 ACINT2 SUTINT1 ACINT1 SUTINT0 ACINT0
759
32142D–06/2013
ATUC64/128/256L3/4U
30.9.4 Interrupt Disable Register
Name: IDR
Access Type: Write-only
Offset: 0x14
Reset Value: 0x00000000
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will clear the corresponding bit in IMR.
31 30 29 28 27 26 25 24
- - - - WFINT3 WFINT2 WFINT1 WFINT0
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
SUTINT7 ACINT7 SUTINT6 ACINT6 SUTINT5 ACINT5 SUTINT4 ACINT4
76543210
SUTINT3 ACINT3 SUTINT2 ACINT2 SUTINT1 ACINT1 SUTINT0 ACINT0
760
32142D–06/2013
ATUC64/128/256L3/4U
30.9.5 Interrupt Mask Register
Name: IMR
Access Type: Read-only
Offset: 0x18
Reset Value: 0x00000000
• WFINTn: Window Mode Interrupt Mask
0: The corresponding interrupt is disabled.
1: The corresponding interrupt is enabled.
This bit is cleared when the corresponding bit in IDR is written to one.
This bit is set when the corresponding bit in IER is written to one.
• SUTINTn: ACn Startup Time Interrupt Mask
0: The corresponding interrupt is disabled.
1: The corresponding interrupt is enabled.
This bit is cleared when the corresponding bit in IDR is written to one.
This bit is set when the corresponding bit in IER is written to one.
• ACINTn: ACn Interrupt Mask
0: The corresponding interrupt is disabled.
1: The corresponding interrupt is enabled.
This bit is cleared when the corresponding bit in IDR is written to one.
This bit is set when the corresponding bit in IER is written to one.
31 30 29 28 27 26 25 24
- - - - WFINT3 WFINT2 WFINT1 WFINT0
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
SUTINT7 ACINT7 SUTINT6 ACINT6 SUTINT5 ACINT5 SUTINT4 ACINT4
76543210
SUTINT3 ACINT3 SUTINT2 ACINT2 SUTINT1 ACINT1 SUTINT0 ACINT0
761
32142D–06/2013
ATUC64/128/256L3/4U
30.9.6 Interrupt Status Register
Name: ISR
Access Type: Read-only
Offset: 0x1C
Reset Value: 0x00000000
• WFINTn: Window Mode Interrupt Status
0: No Window Mode Interrupt is pending.
1: Window Mode Interrupt is pending.
This bit is cleared when the corresponding bit in ICR is written to one.
This bit is set when the corresponding channel pair operating in window mode generated an interrupt.
• SUTINTn: ACn Startup Time Interrupt Status
0: No Startup Time Interrupt is pending.
1: Startup Time Interrupt is pending.
This bit is cleared when the corresponding bit in ICR is written to one.
This bit is set when the startup time of the corresponding AC has passed.
• ACINTn: ACn Interrupt Status
0: No Normal Mode Interrupt is pending.
1: Normal Mode Interrupt is pending.
This bit is cleared when the corresponding bit in ICR is written to one.
This bit is set when the corresponding channel generated an interrupt.
31 30 29 28 27 26 25 24
- - - - WFINT3 WFINT2 WFINT1 WFINT0
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
SUTINT7 ACINT7 SUTINT6 ACINT6 SUTINT5 ACINT5 SUTINT4 ACINT4
76543210
SUTINT3 ACINT3 SUTINT2 ACINT2 SUTINT1 ACINT1 SUTINT0 ACINT0
762
32142D–06/2013
ATUC64/128/256L3/4U
30.9.7 Interrupt Status Clear Register
Name: ICR
Access Type: Write-only
Offset: 0x20
Reset Value: 0x00000000
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will clear the corresponding bit in ISR and the corresponding interrupt request.
31 30 29 28 27 26 25 24
- - - - WFINT3 WFINT2 WFINT1 WFINT0
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
SUTINT7 ACINT7 SUTINT6 ACINT6 SUTINT5 ACINT5 SUTINT4 ACINT4
76543210
SUTINT3 ACINT3 SUTINT2 ACINT2 SUTINT1 ACINT1 SUTINT0 ACINT0
763
32142D–06/2013
ATUC64/128/256L3/4U
30.9.8 Test Register
Name: TR
Access Type: Read/Write
Offset: 0x24
Reset Value: 0x00000000
• ACTESTn: AC Output Override Value
If CTRL.ACTEST is set, the ACn output is overridden with the value of ACTESTn.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
ACTEST7 ACTEST6 ACTEST5 ACTEST4 ACTEST3 ACTEST2 ACTEST1 ACTEST0
764
32142D–06/2013
ATUC64/128/256L3/4U
30.9.9 Parameter Register
Name: PARAMETER
Access Type: Read-only
Offset: 0x30
Reset Value: -
• WIMPLn: Window Pair n Implemented
0: Window Pair not implemented.
1: Window Pair implemented.
• ACIMPLn: Analog Comparator n Implemented
0: Analog Comparator not implemented.
1: Analog Comparator implemented.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
- - - - WIMPL3 WIMPL2 WIMPL1 WIMPL0
15 14 13 12 11 10 9 8
--------
76543210
ACIMPL7 ACIMPL6 ACIMPL5 ACIMPL4 ACIMPL3 ACIMPL2 ACIMPL1 ACIMPL0
765
32142D–06/2013
ATUC64/128/256L3/4U
30.9.10 Version Register
Name: VERSION
Access Type: Read-only
Offset: 0x34
Reset Value: -
• VARIANT: Variant Number
Reserved. No functionality associated.
• VERSION: Version Number
Version number of the module. No functionality associated.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
- - - - VARIANT
15 14 13 12 11 10 9 8
- - - - VERSION[11:8]
76543210
VERSION[7:0]
766
32142D–06/2013
ATUC64/128/256L3/4U
30.9.11 Window Configuration Register
Name: CONFWn
Access Type: Read/Write
Offset: 0x80,0x84,0x88,0x8C
Reset Value: 0x00000000
• WFEN: Window Mode Enable
0: The window mode is disabled.
1: The window mode is enabled.
• WEVEN: Window Event Enable
0: Event from awout is disabled.
1: Event from awout is enabled.
• WEVSRC: Event Source Selection for Window Mode
000: Event on acwout rising edge.
001: Event on acwout falling edge.
010: Event on awout rising or falling edge.
011: Inside window.
100: Outside window.
101: Measure done.
110-111: Reserved.
• WIS: Window Mode Interrupt Settings
00: Window interrupt as soon as the input voltage is inside the window.
01: Window interrupt as soon as the input voltage is outside the window.
10: Window interrupt on toggle of window compare output.
11: Window interrupt when evaluation of input voltage is done.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
- - - - - - - WFEN
15 14 13 12 11 10 9 8
- - - - WEVEN WEVSRC
7654321 0
- - - - - - WIS
767
32142D–06/2013
ATUC64/128/256L3/4U
30.9.12 AC Configuration Register
Name: CONFn
Access Type: Read/Write
Offset: 0xD0,0xD4,0xD8,0xDC,0xE0,0xE4,0xE8,0xEC
Reset Value: 0x00000000
• FLEN: Filter Length
000: Filter off.
n: Number of samples to be averaged =2n
.
• HYS: Hysteresis Value
0000: No hysteresis.
1111: Max hysteresis.
• EVENN: Event Enable Negative
0: Do not output event when ACOUT is zero.
1: Output event when ACOUT is zero.
• EVENP: Event Enable Positive
0: Do not output event when ACOUT is one.
1: Output event when ACOUT is one.
• INSELP: Positive Input Select
00: ACPn pin selected.
01: Reserved.
10: Reserved.
11: Reserved.
• INSELN: Negative Input Select
00: ACNn pin selected.
01: ACREFN pin selected.
10: Reserved.
11: Reserved.
• MODE: Mode
00: Off.
01: Continuous Measurement Mode.
10: User Triggered Single Measurement Mode.
11: Event Triggered Single Measurement Mode.
31 30 29 28 27 26 25 24
- FLEN HYS
23 22 21 20 19 18 17 16
- - - - - - EVENP EVENN
15 14 13 12 11 10 9 8
- - - - INSELP INSELN
7654321 0
- - MODE - - IS
768
32142D–06/2013
ATUC64/128/256L3/4U
• IS: Interrupt Settings
00: Comparator interrupt when as VINP > VINN.
01: Comparator interrupt when as VINP < VINN.
10: Comparator interrupt on toggle of Analog Comparator output.
11: Comparator interrupt when comparison of VINP and VINN is done.
769
32142D–06/2013
ATUC64/128/256L3/4U
30.10 Module Configuration
The specific configuration for each ACIFB instance is listed in the following tables.The module
bus clocks listed here are connected to the system bus clocks. Refer to the Power Manager
chapter for details.
Table 30-5. ACIFB Configuration
Feature ACIFB
Number of channels 8
Table 30-6. ACIFB Clocks
Clock Name Description
CLK_ACIFB Clock for the ACIFB bus interface
GCLK The generic clock used for the ACIFB is GCLK4
Table 30-7. Register Reset Values
Register Reset Value
VERSION 0x00000202
PARAMETER 0x000F00FF
770
32142D–06/2013
ATUC64/128/256L3/4U
31. Capacitive Touch Module (CAT)
Rev: 4.0.0.0
31.1 Features
• QTouch® method allows N touch sensors to be implemented using 2N physical pins
• QMatrix method allows X by Y matrix of sensors to be implemented using (X+2Y) physical pins
• One autonomous QTouch sensor operates without DMA or CPU intervention
• All QTouch sensors can operate in DMA-driven mode without CPU intervention
• External synchronization to reduce 50 or 60 Hz mains interference
• Spread spectrum sensor drive capability
31.2 Overview
The Capacitive Touch Module (CAT) senses touch on external capacitive touch sensors. Capacitive
touch sensors use no external mechanical components, and therefore demand less
maintenance in the user application.
The module implements the QTouch method of capturing signals from capacitive touch sensors.
The QTouch method is generally suitable for small numbers of sensors since it requires 2 physical
pins per sensor. The module also implements the QMatrix method, which is more
appropriate for large numbers of sensors since it allows an X by Y matrix of sensors to be implemented
using only (X+2Y) physical pins. The module allows methods to function together, so N
touch sensors and an X by Y matrix of sensors can be implemented using (2N+X+2Y) physical
pins.
In addition, the module allows sensors using the QTouch method to be divided into two groups.
Each QTouch group can be configured with different properties. This eases the implementation
of multiple kinds of controls such as push buttons, wheels, and sliders.
All of the QTouch sensors can operate in a DMA-driven mode, known as DMATouch, that allows
detection of touch without CPU intervention. The module also implements one autonomous
QTouch sensor that is capable of detecting touch without DMA or CPU intervention. This allows
proximity or activation detection in low-power sleep modes.
771
32142D–06/2013
ATUC64/128/256L3/4U
31.3 Block Diagram
Figure 31-1. CAT Block Diagram
31.4 I/O Lines Description
Interface
Registers Peripheral Bus
Finite State
Machine Capacitor
Charge and
Discharge
Sequence
Generator
Counters
CSAn
SMP
I/O
Controller Pins
Discharge
Current
Sources
DIS
Yn
Analog
Comparators
Peripheral
Event System
CLK_CAT
Analog
Comparator
Interface
SYNC
Capacitive Touch Module (CAT)
CSBn
GCLK_CAT VDIVEN
NOTE:
Italicized
signals and
blocks are
used only for
QMatrix
operation
Table 31-1. I/O Lines Description
Name Description Type
CSAn Capacitive sense A line n I/O
CSBn Capacitive sense B line n I/O
DIS Discharge current control (only used for QMatrix) Analog
772
32142D–06/2013
ATUC64/128/256L3/4U
31.5 Product Dependencies
In order to use the CAT module, other parts of the system must be configured correctly, as
described below.
31.5.1 I/O Lines
The CAT pins may be multiplexed with other peripherals. The user must first program the I/O
Controller to give control of the pins to the CAT module. In QMatrix mode, the Y lines must be
driven by the CAT and analog comparators sense the voltage on the Y lines. Thus, the CAT (not
the Analog Comparator Interface) must be the selected function for the Y lines in the I/O
Controller.
By writing ones and zeros to bits in the Pin Mode Registers (PINMODEx), most of the CAT pins
can be individually selected to implement the QTouch method or the QMatrix method. Each pin
has a different name and function depending on whether it is implementing the QTouch method
or the QMatrix method. The following table shows the pin names for each method and the bits in
the PINMODEx registers which control the selection of the QTouch or QMatrix method.
SMP SMP line (only used for QMatrix) Output
SYNC Synchronize signal Input
VDIVEN Voltage divider enable (only used for QMatrix) Output
Table 31-1. I/O Lines Description
Name Description Type
Table 31-2. Pin Selection Guide
CAT Module Pin
Name
QTouch Method
Pin Name
QMatrix Method Pin
Name
Selection Bit in
PINMODEx Register
CSA0 SNS0 X0 SP0
CSB0 SNSK0 X1 SP0
CSA1 SNS1 Y0 SP1
CSB1 SNSK1 YK0 SP1
CSA2 SNS2 X2 SP2
CSB2 SNSK2 X3 SP2
CSA3 SNS3 Y1 SP3
CSB3 SNSK3 YK1 SP3
CSA4 SNS4 X4 SP4
CSB4 SNSK4 X5 SP4
CSA5 SNS5 Y2 SP5
CSB5 SNSK5 YK2 SP5
CSA6 SNS6 X6 SP6
CSB6 SNSK6 X7 SP6
CSA7 SNS7 Y3 SP7
CSB7 SNSK7 YK3 SP7
CSA8 SNS8 X8 SP8
773
32142D–06/2013
ATUC64/128/256L3/4U
31.5.2 Clocks
The clock for the CAT module, CLK_CAT, is generated by the Power Manager (PM). This clock
is turned on by default, and can be enabled and disabled in the PM. The user must ensure that
CLK_CAT is enabled before using the CAT module.
QMatrix operations also require the CAT generic clock, GCLK_CAT. This generic clock is generated
by the System Control Interface (SCIF), and is shared between the CAT and the Analog
Comparator Interface. The user must ensure that the GCLK_CAT is enabled in the SCIF before
using QMatrix functionality in the CAT module. For proper QMatrix operation, the frequency of
GCLK_CAT must be less than half the frequency of CLK_CAT. If only QTouch functionality is
used, then GCLK_CAT is unnecessary.
31.5.3 Interrupts
The CAT interrupt request line is connected to the interrupt controller. Using CAT interrupts
requires the interrupt controller to be programmed first.
31.5.4 Peripheral Events
The CAT peripheral events are connected via the Peripheral Event System. Refer to the Peripheral
Event System chapter for details.
31.5.5 Peripheral Direct Memory Access
The CAT module provides handshake capability for a Peripheral DMA Controller. One handshake
controls transfers from the Acquired Count Register (ACOUNT) to memory. A second
handshake requests burst lengths for each (X,Y) pair to the Matrix Burst Length Register
CSB8 SNSK8 X9 SP8
CSA9 SNS9 Y4 SP9
CSB9 SNSK9 YK4 SP9
CSA10 SNS10 X10 SP10
CSB10 SNSK10 X11 SP10
CSA11 SNS11 Y5 SP11
CSB11 SNSK11 YK5 SP11
CSA12 SNS12 X12 SP12
CSB12 SNSK12 X13 SP12
CSA13 SNS13 Y6 SP13
CSB13 SNSK13 YK6 SP13
CSA14 SNS14 X14 SP14
CSB14 SNSK14 X15 SP14
CSA15 SNS15 Y7 SP15
CSB15 SNSK15 YK7 SP15
CSA16 SNS16 X16 SP16
CSB16 SNSK16 X17 SP16
Table 31-2. Pin Selection Guide
CAT Module Pin
Name
QTouch Method
Pin Name
QMatrix Method Pin
Name
Selection Bit in
PINMODEx Register
774
32142D–06/2013
ATUC64/128/256L3/4U
(MBLEN) when using the QMatrix acquisition method. Two additional handshakes support DMATouch
by regulating transfers from memory to the DMATouch State Write Register (DMATSW)
and from the DMATouch State Read Register (DMATSR) to memory. The Peripheral DMA Controller
must be configured properly and enabled in order to perform direct memory access
transfers to/from the CAT module.
31.5.6 Analog Comparators
When the CAT module is performing QMatrix acquisition, it requires that on-chip analog comparators
be used as part of the process. These analog comparators are not controlled directly by
the CAT module, but by a separate Analog Comparator (AC) Interface. This interface must be
configured properly and enabled before the CAT module is used. This includes configuring the
generic clock input for the analog comparators to the proper sampling frequency.
The CAT will automatically use the negative peripheral events from the AC Interface on every Y
pin in QMatrix mode. When QMatrix acquisition is used the analog comparator corresponding to
the selected Y pins must be enabled and converting continuously, using the Y pin as the positive
reference and the ACREFN as negative reference.
31.5.7 Debug Operation
When an external debugger forces the CPU into debug mode, the CAT continues normal operation.
If the CAT is configured in a way that requires it to be periodically serviced by the CPU
through interrupts or similar, improper operation or data loss may result during debugging.
31.6 Functional Description
31.6.1 Acquisition Types
The CAT module can perform several types of QTouch acquisition from capacitive touch sensors:
autonomous QTouch (one sensor only), DMATouch, QTouch group A, and QTouch group
B. The CAT module can also perform QMatrix acquisition. Each type of acquisition has an associated
set of pin selection and configuration registers that allow a large degree of flexibility.
The following schematic diagrams show typical hardware connections for QTouch and QMatrix
sensors, respectively:
Figure 31-2. CAT Touch Connections
AVR32 Chip
QTouch
Sensor
Cs (Sense Capacitor)
SNSKn
SNSn
775
32142D–06/2013
ATUC64/128/256L3/4U
Figure 31-3. CAT Matrix Connections
In order to use the autonomous QTouch detection capability, the user must first set up the
Autonomous Touch Pin Select Register (ATPINS) and Autonomous/DMA Touch Configuration
Registers (ATCFG0 through 3) with appropriate values. The module can then be enabled using
the Control Register (CTRL). After the module is enabled, the module will acquire data from the
autonomous QTouch sensor and use it to determine whether the sensor is activated. The
active/inactive status of the autonomous QTouch sensor is reported in the Status Register (SR),
and it is also possible to configure the CAT to generate an interrupt whenever the status
changes. The module will continue acquiring autonomous QTouch sensor data and updating
autonomous QTouch status until the module is disabled or reset.
In order to use the DMATouch capability, it is first necessary to set up the pin mode registers
(PINMODE0, PINMODE1, and PINMODE2) so that the desired pins are specified as DMATouch.
The Autonomous/DMA Touch Configuration Registers (ATCFG0 through 3) must also be
configured with appropriate values. One channel of the Peripheral DMA Controller must be set
up to transfer state words from a block of memory to the DMATSW register, and another channel
must be set up to transfer state words from the DMATSR register back to the same block of
memory. The module can then be enabled using the CTRL register. After the module is enabled,
the module will acquire count values from each DMATouch sensor. Once the module has
acquired a count value for a sensor, it will use a handshake interface to signal the Peripheral
DMA controller to transfer a state word to the DMATSW register. The module will use the count
value to update the state word, and then the updated state word will be transferred to the
DMATSR register. Another handshake interface will signal the Peripheral DMA controller to
transfer the contents of the DMATSR register back to memory. The status of the DMATouch
sensors can be determined at any time by reading the DMATouch Sensor Status Register
(DMATSS).
AVR32 Chip
Cs0 (Sense Capacitor)
X3
YK0
X6 QMatrix Sensor Array
X7
X2
Y0
YK1
Y1 Cs1 (Sense Capacitor)
SMP
Rsmp1 Rsmp0
VDIVEN
DIS
Rdis
ACREFN
Ra
Rb
NOTE: If the CAT internal
current sources will be enabled,
the SMP signal and Rsmp
resistors should NOT be included
in the design. If the CAT internal
current sources will NOT be
enabled, the DIS signal and Rdis
resistor should NOT be included
in the design.
776
32142D–06/2013
ATUC64/128/256L3/4U
In order to use the QMatrix, QTouch group A, or QTouch group B acquisition capabilities, it is
first necessary to set up the pin mode registers (PINMODE0, PINMODE1, and PINMODE2) and
configuration registers (MGCFG0, MGCFG1, TGACFG0, TGACFG1, TGBCFG0, and
TGBCFG1). The module must then be enabled using the CTRL register. In order to initiate
acquisition, it is necessary to perform a write to the Acquisition Initiation and Selection Register
(AISR). The specific value written to AISR determines which type of acquisition will be performed:
QMatrix, QTouch group A, or QTouch group B. The CPU can initiate acquisition by
writing to the AISR.
While QMatrix, QTouch group A, or QTouch group B acquisition is in progress, the module collects
count values from the sensors and buffers them. Availability of acquired count data is
indicated by the Acquisition Ready (ACREADY) bit in the Status Register (SR). The CPU or the
Peripheral DMA Controller can then read the acquired counts from the ACOUNT register.
Because the CAT module is configured with Peripheral DMA Controller capability that can transfer
data from memory to MBLEN and from ACOUNT to memory, the Peripheral DMA Controller
can perform long acquisition sequences and store results in memory without CPU intervention.
31.6.2 Prescaler and Charge Length
Each QTouch acquisition type (autonomous QTouch, QTouch group A, and QTouch group B)
has its own prescaler. Each QTouch prescaler divides down the CLK_CAT clock to an appropriate
sampling frequency for its particular acquisition type. Typical frequencies are 1MHz for
QTouch acquisition and 4MHz for QMatrix burst timing control.
Each QTouch prescaler is controlled by the DIV field in the appropriate Configuration Register 0
(ATCFG0, TGACFG0, or TGBCFG0). The QMatrix burst timing prescaler is controlled by the
DIV field in MGCFG0. Each prescaler uses the following formula to generate the sampling clock:
Sampling clock = CLK_CAT / (2(DIV+1))
The capacitive sensor charge length, discharge length, and settle length can be determined for
each acquisition type using the CHLEN, DILEN, and SELEN fields in Configuration Registers 0
and 1. The lengths are specified in terms of prescaler clocks. In addition, the QMatrix Cx discharge
length can be determined using the CXDILEN field in MGCFG2.
For QMatrix acquisition, the duration of CHLEN should not be set to the same value as the
period of any periodic signal on any other pin. If the duration of CHLEN is the same as the
period of a signal on another pin, it is likely that the other signal will significantly affect measurements
due to stray capacitive coupling. For example, if a 1 MHz signal is generated on another
pin of the chip, then CHLEN should not be 1 microsecond.
For the QMatrix method, burst and capture lengths are set for each (X,Y) pair by writing the
desired length values to the MBLEN register. The write must be done before each X line can
start its acquisition and is indicated by the status bit MBLREQ in the Status Register (SR). A
DMA handshake interface is also connected to this status bit to reduce CPU overhead during
QMatrix acquisitions.
Four burst lengths (BURST0..3) can be written at one time into the MBLEN register. If the current
configuration uses Y lines larger than Y3 the register has to be written a second time. The
first write to MBLEN specifies the burst length for Y lines 0 to 3 in the BURST0 to BURST3 fields,
respectively. The second write specifies the burst length for Y lines 4 to 7 in fields BURST0 to
BURST3, respectively, and so on.
777
32142D–06/2013
ATUC64/128/256L3/4U
The Y and YK pins remain clamped to ground apart from the specified number of burst pulses,
when charge is transferred and captured into the sampling capacitor.
31.6.3 Capacitive Count Acquisition
For the QMatrix, QTouch group A, and QTouch group B types of acquisition, the module
acquires count values from the sensors, buffers them, and makes them available for reading in
the ACOUNT register. Further processing of the count values must be performed by the CPU.
When the module performs QMatrix acquisition using multiple Y lines, it starts the capture for
each Y line at the appropriate time in the burst sequence so that all captures finish simultaneously.
For example, suppose that an acquisition is performed on Y0 and Y1 with BURST0=53
and BURST1=60. The module will first toggle the X line 7 times while capturing on Y1 while Y0
and YK0 are clamped to ground. The module will then toggle the X line 53 times while capturing
on both Y1 and Y0.
31.6.4 Autonomous QTouch and DMATouch
For autonomous QTouch and DMATouch, a complete detection algorithm is implemented within
the CAT module. The additional parameters needed to control the detection algorithm must be
specified by the user in the ATCFG2 and ATCFG3 registers.
Autonomous QTouch and DMATouch sensitivity and out-of-touch sensitivity can be adjusted
with the SENSE and OUTSENS fields, respectively, in ATCFG2. Each field accepts values from
one to 255 where 255 is the least sensitive setting. The value in the OUTSENS field should be
smaller than the value in the SENSE field.
To avoid false positives a detect integration filtering technique can be used. The number of successive
detects required is specified in the FILTER field of the ATCFG2 register.
To compensate for changes in capacitance the CAT can recalibrate the autonomous QTouch
sensor periodically. The timing of this calibration is done with the NDRIFT and PDRIFT fields in
the Configuration register, ATCFG3. It is recommended that the PDRIFT value is smaller than
the NDRIFT value.
The autonomous QTouch sensor and DMATouch sensors will also recalibrate if the count value
goes too far positive beyond a threshold. This positive recalibration threshold is specified by the
PTHR field in the ATCFG3 register.
The following block diagram shows the sequence of acquisition and processing operations used
by the CAT module. The AISR written bit is internal and not visible in the user interface.
778
32142D–06/2013
ATUC64/128/256L3/4U
Figure 31-4. CAT Acquisition and Processing Sequence
31.6.5 Spread Spectrum Sensor Drive
To reduce electromagnetic compatibility issues, the capacitive sensors can be driven with a
spread spectrum signal. To enable spread spectrum drive for a specific acquisition type, the
user must write a one to the SPREAD bit in the appropriate Configuration Register 1 (MGCFG1,
ATCFG1, TGACFG1, or TGBCFG1).
During spread spectrum operation, the length of each pulse within a burst is varied in a deterministic
pattern, so that the exact same burst pattern is used for a specific burst length. The
maximum spread is determined by the MAXDEV field in the Spread Spectrum Configuration
Register (SSCFG) register. The prescaler divisor is varied in a sawtooth pattern from
(2(DIV+1))-MAXDEV to (2(DIV+1))+MAXDEV and then back to (2(DIV+1))-MAXDEV. For example,
if DIV is 2 and MAXDEV is 3, the prescaler divisor will have the following sequence: 6, 7, 8,
Idle
Acquire
autonomous
touch count
Acquire counts
Update
autonomous
touch detection
algorithm
Wait for all
acquired counts
to be transferred
AISR written flag set?
No Yes
Clear AISR
written flag
No Yes
Autonomous touch
enabled (ATEN)?
779
32142D–06/2013
ATUC64/128/256L3/4U
9, 3, 4, 5, 6, 7, 8, 9, 3, 4, etc. MAXDEV must not exceed the value of (2(DIV+1)), or undefined
behavior will occur.
31.6.6 Synchronization
To prevent interference from the 50 or 60 Hz mains line the CAT can trigger acquisition on the
SYNC signal. The SYNC signal should be derived from the mains line. The acquisition will trigger
on a falling edge of this signal. To enable synchronization for a specific acquisition type, the
user must write a one to the SYNC bit in the appropriate Configuration Register 1 (MGCFG1,
ATCFG1, TGACFG1, or TGBCFG1).
For QMatrix acquisition, all X lines must be sampled at a specific phase of the noise signal for
the synchronization to be effective. This can be accomplished by the synchronization timer,
which is enabled by writing a non-zero value to the SYNCTIM field in the MGCFG2 register. This
ensures that the start of the acquisition of each X line is spaced at regular intervals, defined by
the SYNCTIM field.
31.6.7 Resistive Drive
By default, the CAT pins are driven with normal I/O drive properties. Some of the CSA and CSB
pins can optionally drive with a 1k output resistance for improved EMC. The pins that have this
capability are listed in the Module Configuration section.
31.6.8 Discharge Current Sources
The device integrates discharge current sources, which can be used to discharge the sampling
capacitors during the QMatrix measurement phase. The discharge current sources are enabled
by writing the GLEN bit in the Discharge Current Source (DICS) register to one. This enables an
internal reference voltage, which can be either the internal 1.1V band gap voltage or VDDIO/3,
as selected by the INTVREFSEL bit in the DICS register. If the DICS.INTREFSEL bit is one, the
reference voltage is applied across an internal resistor, Rint. Otherwise, the voltage is applied to
the DIS pin, and an external reference resistor must be connected between DIS and ground.
The nominal discharge current is given by the following formula, where Vref is the reference voltage,
Rref is the value of the reference resistor, trim is the value written to the DICS.TRIM field,
and k is a constant of proportionality:
I = (Vref/Rref)*(1+(k*trim))
The values for the internal reference resistor, Rint, and the constant, k, may be found in the Electrical
Characteristics section. The nominal discharge current may be programmed between 2
and 20 µA. The reference current can be fine-tuned by adjusting the trim value in the DICS.TRIM
field.
The reference current is mirrored to each Y-pin if the corresponding bit is written to one in the
DICS.SOURCES field.
31.6.9 Voltage Divider Enable (VDIVEN) Capability
In many QMatrix applications, the sense capacitors will be charged to 50 mV or more and the
negative reference pin (ACREFN) of the analog comparators can be tied directly to ground. In
that case, the relatively small input offset voltage of the comparators will not cause acquisition
problems. However, in certain specialized QMatrix applications such as interpolated touch
screens, it may be desirable for the sense capacitors to be charged to less than 25 mV. When
such small voltages are used on the sense capacitors, the input offset voltage of the comparators
becomes an issue and can cause QMatrix acquisition problems.
780
32142D–06/2013
ATUC64/128/256L3/4U
Problems with QMatrix acquisition of small sense capacitor voltages can be solved by connecting
the negative reference pin (ACREFN) to a voltage divider that produces a small positive
voltage (20 mV, typically) to cancel any negative input offset voltage. With a 3.3V supply, recommended
values for the voltage divider are Ra (resistor from positive supply to ACREFN) of 8200
ohm and Rb (resistor from ACREFN to ground) of 50 ohm. These recommended values will produce
20 mV on the ACREFN pin, which should generally be enough to compensate for the
worst-case negative input offset of the analog comparators.
Unfortunately, such a voltage divider constantly draws a small current from the power supply,
reducing battery life in portable applications. In order to prevent this constant power drain, the
CAT module provides a voltage divider enable pin (VDIVEN) that can be used for driving the
voltage divider. The VDIVEN pin provides power to the voltage divider only when the comparators
are actually performing QMatrix comparisons. When the comparators are inactive, the
VDIVEN output is zero. This minimizes the power consumed by the voltage divider.
781
32142D–06/2013
ATUC64/128/256L3/4U
31.7 User Interface
Table 31-3. CAT Register Memory Map
Offset Register Register Name Access Reset
0x00 Control Register CTRL Read/Write 0x00000000
0x04 Autonomous Touch Pin Selection Register ATPINS Read/Write 0x00000000
0x08 Pin Mode Register 0 PINMODE0 Read/Write 0x00000000
0x0C Pin Mode Register 1 PINMODE1 Read/Write 0x00000000
0x10 Autonomous/DMA Touch Configuration Register 0 ATCFG0 Read/Write 0x00000000
0x14 Autonomous/DMA Touch Configuration Register 1 ATCFG1 Read/Write 0x00000000
0x18 Autonomous/DMA Touch Configuration Register 2 ATCFG2 Read/Write 0x00000000
0x1C Autonomous/DMA Touch Configuration Register 3 ATCFG3 Read/Write 0x00000000
0x20 Touch Group A Configuration Register 0 TGACFG0 Read/Write 0x00000000
0x24 Touch Group A Configuration Register 1 TGACFG1 Read/Write 0x00000000
0x28 Touch Group B Configuration Register 0 TGBCFG0 Read/Write 0x00000000
0x2C Touch Group B Configuration Register 1 TGBCFG1 Read/Write 0x00000000
0x30 Matrix Group Configuration Register 0 MGCFG0 Read/Write 0x00000000
0x34 Matrix Group Configuration Register 1 MGCFG1 Read/Write 0x00000000
0x38 Matrix Group Configuration Register 2 MGCFG2 Read/Write 0x00000000
0x3C Status Register SR Read-only 0x00000000
0x40 Status Clear Register SCR Write-only -
0x44 Interrupt Enable Register IER Write-only -
0x48 Interrupt Disable Register IDR Write-only -
0x4C Interrupt Mask Register IMR Read-only 0x00000000
0x50 Acquisition Initiation and Selection Register AISR Read/Write 0x00000000
0x54 Acquired Count Register ACOUNT Read-only 0x00000000
0x58 Matrix Burst Length Register MBLEN Write-only -
0x5C Discharge Current Source Register DICS Read/Write 0x00000000
0x60 Spread Spectrum Configuration Register SSCFG Read/Write 0x00000000
0x64 CSA Resistor Control Register CSARES Read/Write 0x00000000
0x68 CSB Resistor Control Register CSBRES Read/Write 0x00000000
0x6C Autonomous Touch Base Count Register ATBASE Read-only 0x00000000
0x70 Autonomous Touch Current Count Register ATCURR Read-only 0x00000000
0x74 Pin Mode Register 2 PINMODE2 Read/Write 0x00000000
0x78 DMATouch State Write Register DMATSW Write-only 0x00000000
0x7C DMATouch State Read Register DMATSR Read-only 0x00000000
0x80 Analog Comparator Shift Offset Register 0 ACSHI0 Read/Write 0x00000000
0x84 Analog Comparator Shift Offset Register 1 ACSHI1 Read/Write 0x00000000
0x88 Analog Comparator Shift Offset Register 2 ACSHI2 Read/Write 0x00000000
782
32142D–06/2013
ATUC64/128/256L3/4U
Note: 1. The reset value for this register is device specific. Please refer to the Module Configuration section at the end of this chapter.
0x8C Analog Comparator Shift Offset Register 3 ACSHI3 Read/Write 0x00000000
0x90 Analog Comparator Shift Offset Register 4 ACSHI4 Read/Write 0x00000000
0x94 Analog Comparator Shift Offset Register 5 ACSHI5 Read/Write 0x00000000
0x98 Analog Comparator Shift Offset Register 6 ACSHI6 Read/Write 0x00000000
0x9C Analog Comparator Shift Offset Register 7 ACSHI7 Read/Write 0x00000000
0xA0 DMATouch Sensor Status Register DMATSS Read-only 0x00000000
0xF8 Parameter Register PARAMETER Read-only -(1)
0xFC Version Register VERSION Read-only -(1)
Table 31-3. CAT Register Memory Map
Offset Register Register Name Access Reset
783
32142D–06/2013
ATUC64/128/256L3/4U
31.7.1 Control Register
Name: CTRL
Access Type: Read/Write
Offset: 0x00
Reset Value: 0x00000000
• SWRST: Software reset
Writing a zero to this bit has no effect.
Writing a one to this bit resets the module. The module will be disabled after the reset.
This bit always reads as zero.
• EN: Module enable
0: Module is disabled.
1: Module is enabled.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
SWRST - - - - - - EN
784
32142D–06/2013
ATUC64/128/256L3/4U
31.7.2 Autonomous Touch Pin Selection Register
Name: ATPINS
Access Type: Read/Write
Offset: 0x04
Reset Value: 0x00000000
• ATEN: Autonomous Touch Enable
0: Autonomous QTouch acquisition and detection is disabled.
1: Autonomous QTouch acquisition and detection is enabled using the sense pair specified in ATSP.
• ATSP: Autonomous Touch Sense Pair
Selects the sense pair that will be used by the autonomous QTouch sensor. A value of n will select sense pair n (CSAn and
CSBn pins).
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
- - - - - - - ATEN
76543210
- - - ATSP
785
32142D–06/2013
ATUC64/128/256L3/4U
31.7.3 Pin Mode Registers 0, 1, and 2
Name: PINMODE0, PINMODE1, and PINMODE2
Access Type: Read/Write
Offset: 0x08, 0x0C, 0x74
Reset Value: 0x00000000
• SP: Sense Pair Mode Selection
Each SP[n] bit determines the operation mode of sense pair n (CSAn and CSBn pins). The (PINMODE2.SP[n]
PINMODE1.SP[n] PINMODE0.SP[n]) bits have the following definitions:
000: Sense pair n disabled.
001: Sense pair n is assigned to QTouch Group A.
010: Sense pair n is assigned to QTouch Group B.
011: Sense pair n is assigned to the QMatrix Group.
100: Sense pair n is assigned to the DMATouch Group.
101: Reserved.
110: Reserved.
111: Reserved.
31 30 29 28 27 26 25 24
-
23 22 21 20 19 18 17 16
- SP[16]
15 14 13 12 11 10 9 8
SP[15:8]
76543210
SP[7:0]
786
32142D–06/2013
ATUC64/128/256L3/4U
31.7.4 Autonomous/DMA Touch Configuration Register 0
Name: ATCFG0
Access Type: Read/Write
Offset: 0x10
Reset Value: 0x00000000
• DIV: Clock Divider
The prescaler is used to ensure that the CLK_CAT clock is divided to around 1 MHz to produce the sampling clock.The
prescaler uses the following formula to generate the sampling clock:
Sampling clock = CLK_CAT / (2(DIV+1))
• CHLEN: Charge Length
For the autonomous QTouch sensor and DMATouch sensors, specifies how many sample clock cycles should be used for
transferring charge to the sense capacitor.
• SELEN: Settle Length
For the autonomous QTouch sensor and DMATouch sensors, specifies how many sample clock cycles should be used for
settling after charge transfer.
31 30 29 28 27 26 25 24
DIV[15:8]
23 22 21 20 19 18 17 16
DIV[7:0]
15 14 13 12 11 10 9 8
CHLEN
76543210
SELEN
787
32142D–06/2013
ATUC64/128/256L3/4U
31.7.5 Autonomous/DMA Touch Configuration Register 1
Name: ATCFG1
Access Type: Read/Write
Offset: 0x14
Reset Value: 0x00000000
• DISHIFT: Discharge Shift
For the autonomous QTouch sensor and DMATouch sensors, specifies how many bits the DILEN field should be shifted before
using it to determine the discharge time.
• SYNC: Sync Pin
For the autonomous QTouch sensor and DMATouch sensors, specifies that acquisition shall begin when a falling edge is
received on the SYNC line.
• SPREAD: Spread Spectrum Sensor Drive
For the autonomous QTouch sensor and DMATouch sensors, specifies that spread spectrum sensor drive shall be used.
• DILEN: Discharge Length
For the autonomous QTouch sensor and DMATouch sensors, specifies how many sample clock cycles the CAT should use to
discharge the capacitors before charging them.
• MAX: Maximum Count
For the autonomous QTouch sensor and DMATouch sensors, specifies how many counts the maximum acquisition should be.
31 30 29 28 27 26 25 24
- DISHIFT - SYNC SPREAD
23 22 21 20 19 18 17 16
DILEN
15 14 13 12 11 10 9 8
MAX[15:8]
76543210
MAX[7:0]
788
32142D–06/2013
ATUC64/128/256L3/4U
31.7.6 Autonomous/DMA Touch Configuration Register 2
Name: ATCFG2
Access Type: Read/Write
Offset: 0x18
Reset Value: 0x00000000
• FILTER: Autonomous Touch Filter Setting
For the autonomous QTouch sensor and DMATouch sensors, specifies how many positive detects in a row the CAT needs to
have on the sensor before reporting it as a touch. A FILTER value of 0 is not allowed and will result in undefined behavior.
• OUTSENS: Out-of-Touch Sensitivity
For the autonomous QTouch sensor and DMATouch sensors, specifies how sensitive the out-of-touch detector should be.
• SENSE: Sensitivity
For the autonomous QTouch sensor and DMATouch sensors, specifies how sensitive the touch detector should be.
31 30 29 28 27 26 25 24
-
23 22 21 20 19 18 17 16
- FILTER
15 14 13 12 11 10 9 8
OUTSENS
76543210
SENSE
789
32142D–06/2013
ATUC64/128/256L3/4U
31.7.7 Autonomous/DMA Touch Configuration Register 3
Name: ATCFG3
Access Type: Read/Write
Offset: 0x1C
Reset Value: 0x00000000
• PTHR: Positive Recalibration Threshold
For the autonomous QTouch sensor and DMATouch sensors, specifies how far a sensor’s signal must move in a positive
direction from the reference in order to cause a recalibration.
• PDRIFT: Positive Drift Compensation
For the autonomous QTouch sensor and DMATouch sensors, specifies how often a positive drift compensation should be
performed. When this field is zero, positive drift compensation will never be performed. When this field is non-zero, the positive
drift compensation time interval is given by the following formula:
Tpdrift = PDRIFT * 65536 * (sample clock period)
• NDRIFT: Negative Drift Compensation
For the autonomous QTouch sensor and DMATouch sensors, specifies how often a negative drift compensation should be
performed. When this field is zero, negative drift compensation will never be performed. When this field is non-zero, the negative
drift compensation time interval is given by the following formula:
Tndrift = NDRIFT * 65536 * (sample clock period)
With the typical sample clock frequency of 1 MHz, PDRIFT and NDRIFT can be set from 0.066 seconds to 16.7 seconds
with 0.066 second resolution.
31 30 29 28 27 26 25 24
-
23 22 21 20 19 18 17 16
PTHR
15 14 13 12 11 10 9 8
PDRIFT
76543210
NDRIFT
790
32142D–06/2013
ATUC64/128/256L3/4U
31.7.8 Touch Group x Configuration Register 0
Name: TGxCFG0
Access Type: Read/Write
Offset: 0x20, 0x28
Reset Value: 0x00000000
• DIV: Clock Divider
The prescaler is used to ensure that the CLK_CAT clock is divided to around 1 MHz to produce the sampling clock.The
prescaler uses the following formula to generate the sampling clock:
Sampling clock = CLK_CAT / (2(DIV+1))
• CHLEN: Charge Length
For the QTouch method, specifies how many sample clock cycles should be used for transferring charge to the sense capacitor.
• SELEN: Settle Length
For the QTouch method, specifies how many sample clock cycles should be used for settling after charge transfer.
31 30 29 28 27 26 25 24
DIV[15:8]
23 22 21 20 19 18 17 16
DIV[7:0]
15 14 13 12 11 10 9 8
CHLEN
76543210
SELEN
791
32142D–06/2013
ATUC64/128/256L3/4U
31.7.9 Touch Group x Configuration Register 1
Name: TGxCFG1
Access Type: Read/Write
Offset: 0x24, 0x2C
Reset Value: 0x00000000
• DISHIFT: Discharge Shift
For the sensors in QTouch group x, specifies how many bits the DILEN field should be shifted before using it to determine the
discharge time.
• SYNC: Sync Pin
For sensors in QTouch group x, specifies that acquisition shall begin when a falling edge is received on the SYNC line.
• SPREAD: Spread Spectrum Sensor Drive
For sensors in QTouch group x, specifies that spread spectrum sensor drive shall be used.
• DILEN: Discharge Length
For sensors in QTouch group x, specifies how many clock cycles the CAT should use to discharge the capacitors before
charging them.
• MAX: Touch Maximum Count
For sensors in QTouch group x, specifies how many counts the maximum acquisition should be.
31 30 29 28 27 26 25 24
- - DISHIFT - - SYNC SPREAD
23 22 21 20 19 18 17 16
DILEN
15 14 13 12 11 10 9 8
MAX[15:8]
76543210
MAX[7:0]
792
32142D–06/2013
ATUC64/128/256L3/4U
31.7.10 Matrix Group Configuration Register 0
Name: MGCFG0
Access Type: Read/Write
Offset: 0x30
Reset Value: 0x00000000
• DIV: Clock Divider
The prescaler is used to ensure that the CLK_CAT clock is divided to around 4 MHz to produce the burst timing clock.The
prescaler uses the following formula to generate the burst timing clock:
Burst timing clock = CLK_CAT / (2(DIV+1))
• CHLEN: Charge Length
For QMatrix sensors, specifies how many burst prescaler clock cycles should be used for transferring charge to the sense
capacitor.
• SELEN: Settle Length
For QMatrix sensors, specifies how many burst prescaler clock cycles should be used for settling after charge transfer.
31 30 29 28 27 26 25 24
DIV[15:8]
23 22 21 20 19 18 17 16
DIV[7:0]
15 14 13 12 11 10 9 8
CHLEN
76543210
SELEN
793
32142D–06/2013
ATUC64/128/256L3/4U
31.7.11 Matrix Group Configuration Register 1
Name: MGCFG1
Access Type: Read/Write
Offset: 0x34
Reset Value: 0x00000000
• DISHIFT: Discharge Shift
For QMatrix sensors, specifies how many bits the DILEN field should be shifted before using it to determine the discharge time.
• SYNC: Sync Pin
For QMatrix sensors, specifies that acquisition shall begin when a falling edge is received on the SYNC line.
• SPREAD: Spread Spectrum Sensor Drive
For QMatrix sensors, specifies that spread spectrum sensor drive shall be used.
• DILEN: Discharge Length
For QMatrix sensors, specifies how many burst prescaler clock cycles the CAT should use to discharge the capacitors at the
beginning of a burst sequence.
• MAX: Maximum Count
For QMatrix sensors, specifies how many counts the maximum acquisition should be.
31 30 29 28 27 26 25 24
- DISHIFT - SYNC SPREAD
23 22 21 20 19 18 17 16
DILEN
15 14 13 12 11 10 9 8
MAX[15:8]
76543210
MAX[7:0]
794
32142D–06/2013
ATUC64/128/256L3/4U
31.7.12 Matrix Group Configuration Register 2
Name: MGCFG2
Access Type: Read/Write
Offset: 0x38
Reset Value: 0x00000000
• ACCTRL: Analog Comparator Control
When written to one, allows the CAT to disable the analog comparators when they are not needed. When written to zero, the
analog comparators are always enabled.
• CONSEN: Consensus Filter Length
For QMatrix sensors, specifies that discharge will be terminated when CONSEN out of the most recent 5 comparator samples
are positive. For example, a value of 3 in the CONSEN field will terminate discharge when 3 out of the most recent 5 comparator
samples are positive. When CONSEN has the default value of 0, discharge will be terminated immediately when the comparator
output goes positive.
• CXDILEN: Cx Capacitor Discharge Length
For QMatrix sensors, specifies how many burst prescaler clock cycles the CAT should use to discharge the Cx capacitor at the
end of each burst cycle.
• SYNCTIM: Sync Time Interval
When non-zero, determines the number of prescaled clock cycles between the start of the acquisition on each X line for QMatrix
acquisition.
31 30 29 28 27 26 25 24
ACCTRL CONSEN -
23 22 21 20 19 18 17 16
CXDILEN
15 14 13 12 11 10 9 8
- SYNCTIM[11:8]
76543210
SYNCTIM[7:0]
795
32142D–06/2013
ATUC64/128/256L3/4U
31.7.13 Status Register
Name: SR
Access Type: Read-only
Offset: 0x3C
Reset Value: 0x00000000
• DMATSC: DMATouch Sensor State Change
0: No change in the DMATSS register.
1: One or more bits have changed in the DMATSS register.
• DMATSR: DMATouch State Read Register Ready
0: A new state word is not available in the DMATSR register.
1: A new state word is available in the DMATSR register.
• DMATSW: DMATouch State Write Register Request
0: The DMATouch algorithm is not requesting that a state word be written to the DMATSW register.
1: The DMATouch algorithm is requesting that a state word be written to the DMATSW register.
• ACQDONE: Acquisition Done
0: Acquisition is not done (still in progress).
1: Acquisition is complete.
• ACREADY: Acquired Count Data is Ready
0: Acquired count data is not available in the ACOUNT register.
1: Acquired count data is available in the ACOUNT register.
• MBLREQ: Matrix Burst Length Required
0: The QMatrix acquisition does not require any burst lengths.
1: The QMatrix acquisition requires burst lengths for the current X line.
• ATSTATE: Autonomous Touch Sensor State
0: The autonomous QTouch sensor is not active.
1: The autonomous QTouch sensor is active.
• ATSC: Autonomous Touch Sensor Status Interrupt
0: No status change in the autonomous QTouch sensor.
1: Status change in the autonomous QTouch sensor.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
DMATSC - - - - - DMATSR DMATSW
15 14 13 12 11 10 9 8
- - - - - - ACQDONE ACREADY
76543210
- - - MBLREQ ATSTATE ATSC ATCAL ENABLED
796
32142D–06/2013
ATUC64/128/256L3/4U
• ATCAL: Autonomous Touch Calibration Ongoing
0: The autonomous QTouch sensor is not calibrating.
1: The autonomous QTouch sensor is calibrating.
• ENABLED: Module Enabled
0: The module is disabled.
1: The module is enabled.
797
32142D–06/2013
ATUC64/128/256L3/4U
31.7.14 Status Clear Register
Name: SCR
Access Type: Write-only
Offset: 0x40
Reset Value: -
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will clear the corresponding bit in SR and the corresponding interrupt request.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
DMATSC - - - - - - -
15 14 13 12 11 10 9 8
- - - - - - ACQDONE ACREADY
76543210
- - - - - ATSC ATCAL -
798
32142D–06/2013
ATUC64/128/256L3/4U
31.7.15 Interrupt Enable Register
Name: IER
Access Type: Write-only
Offset: 0x44
Reset Value: -
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will set the corresponding bit in IMR.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
DMATSC - - - - - - -
15 14 13 12 11 10 9 8
- - - - - - ACQDONE ACREADY
76543210
- - - - - ATSC ATCAL -
799
32142D–06/2013
ATUC64/128/256L3/4U
31.7.16 Interrupt Disable Register
Name: IDR
Access Type: Write-only
Offset: 0x48
Reset Value: -
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will clear the corresponding bit in IMR.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
DMATSC - - - - - - -
15 14 13 12 11 10 9 8
- - - - - - ACQDONE ACREADY
76543210
- - - - - ATSC ATCAL -
800
32142D–06/2013
ATUC64/128/256L3/4U
31.7.17 Interrupt Mask Register
Name: IMR
Access Type: Read-only
Offset: 0x4C
Reset Value: 0x00000000
0: The corresponding interrupt is disabled.
1: The corresponding interrupt is enabled.
A bit in this register is cleared when the corresponding bit in IDR is written to one.
A bit in this register is set when the corresponding bit in IER is written to one.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
DMATSC - - - - - - -
15 14 13 12 11 10 9 8
- - - - - - ACQDONE ACREADY
76543210
- - - - - ATSC ATCAL -
801
32142D–06/2013
ATUC64/128/256L3/4U
31.7.18 Acquisition Initiation and Selection Register
Name: AISR
Access Type: Read/Write
Offset: 0x50
Reset Value: 0x00000000
• ACQSEL: Acquisition Type Selection
A write to this register initiates an acquisition of the following type:
00: QTouch Group A.
01: QTouch Group B.
10: QMatrix Group.
11: Undefined behavior.
A read of this register will return the value that was previously written.
31 30 29 28 27 26 25 24
-
23 22 21 20 19 18 17 16
-
15 14 13 12 11 10 9 8
-
76543210
- ACQSEL
802
32142D–06/2013
ATUC64/128/256L3/4U
31.7.19 Acquired Count Register
Name: ACOUNT
Access Type: Read-only
Offset: 0x54
Reset Value: 0x00000000
• Y: Y index
The Y index (for QMatrix method) associated with this count value.
• SPORX: Sensor pair or X index
The sensor pair index (for QTouch method) or X index (for QMatrix method) associated with this count value.
• COUNT: Count value
The signal (number of counts) acquired on the channel specified in the SPORX and Y fields.
When multiple acquired count values are read from a QTouch acquisition, the Y field will always be 0 and the SPORX value will
increase monotonically. For example, suppose a QTouch acquisition is performed using sensor pairs SP1, SP4, and SP9. The
first count read will have SPORX=1, the second read will have SPORX=4, and the third read will have SPORX=9.
When multiple acquired count values are read from a QMatrix acquisition, the SPORX value will stay the same while Y
increases monotonically through all Y values in the group. Then SPORX will increase to the next X value in the group. For
example, a QMatrix acquisition with X=2,3 and Y=4,7 would provide count values in the following order: X=2 and Y=4, then X=2
and Y=7, then X=3 and Y=4, and finally X=3 and Y=7.
31 30 29 28 27 26 25 24
Y
23 22 21 20 19 18 17 16
SPORX
15 14 13 12 11 10 9 8
COUNT[15:8]
76543210
COUNT[7:0]
803
32142D–06/2013
ATUC64/128/256L3/4U
31.7.20 Matrix Burst Length Register
Name: MBLEN
Access Type: Write-only
Offset: 0x58
Reset Value: -
• BURSTx: Burst Length x
For QMatrix sensors, specifies how many times the switching sequence should be repeated before acquisition begins for each
channel. Each count in the BURSTx field specifies 1 repeat of the switching sequence, so the actual burst length will be BURST.
Before doing a QMatrix acquisition on one X line this register has to be written with the burst values for the current XY pairs. For
each X line this register needs to be programmed with all the Y values. If Y values larger than 3 are used the register has to be
written several times in order to specify all burst lengths.
The Status Register bit MBLREQ is set to 1 when the CAT is waiting for values to be written into this register.
31 30 29 28 27 26 25 24
BURST0
23 22 21 20 19 18 17 16
BURST1
15 14 13 12 11 10 9 8
BURST2
76543210
BURST3
804
32142D–06/2013
ATUC64/128/256L3/4U
31.7.21 Discharge Current Source Register
Name: DICS
Access Type: Read/Write
Offset: 0x5C
Reset Value: 0x00000000
• FSOURCES: Force Discharge Current Sources
When FSOURCES[n] is 0, the corresponding discharge current source behavior depends on SOURCES[n].
When FSOURCES[n] is 1, the corresponding discharge current source is forced to be enabled continuously. This is useful for
testing or debugging but should not be done during normal acquisition.
• GLEN: Global Enable
0: The current source module is globally disabled.
1: The current source module is globally enabled.
• INTVREFSEL: Internal Voltage Reference Select
0: The voltage for the reference resistor is generated from the internal band gap circuit.
1: The voltage for the reference resistor is VDDIO/3.
• INTREFSEL: Internal Reference Select
0: The reference current flows through an external resistor on the DIS pin.
1: The reference current flows through the internal reference resistor.
• TRIM: Reference Current Trimming
This field is used to trim the discharge current. 0x00 corresponds to the minimum current value, and 0x1F corresponds to the
maximum current value.
• SOURCES: Enable Discharge Current Sources
When SOURCES[n] is 0, the corresponding discharge current source is disabled.
When SOURCES[n] is 1, the corresponding discharge current source is enabled at appropriate times during acquisition.
31 30 29 28 27 26 25 24
FSOURCES[7:0]
23 22 21 20 19 18 17 16
GLEN - - - - - INTVREFSEL INTREFSEL
15 14 13 12 11 10 9 8
- - - TRIM
76543210
SOURCES[7:0]
805
32142D–06/2013
ATUC64/128/256L3/4U
31.7.22 Spread Spectrum Configuration Register
Name: SSCFG
Access Type: Read/Write
Offset: 0x60
Reset Value: 0x00000000
• MAXDEV: Maximum Deviation
When spread spectrum burst is enabled, MAXDEV indicates the maximum number of prescaled clock cycles the burst pulse will
be extended or shortened.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
MAXDEV
806
32142D–06/2013
ATUC64/128/256L3/4U
31.7.23 CSA Resistor Control Register
Name: CSARES
Access Type: Read/Write
Offset: 0x64
Reset Value: 0x00000000
• RES: Resistive Drive Enable
When RES[n] is 0, CSA[n] has the same drive properties as normal I/O pads.
When RES[n] is 1, CSA[n] has a nominal output resistance of 1kOhm during the burst phase.
31 30 29 28 27 26 25 24
-
23 22 21 20 19 18 17 16
- RES[16]
15 14 13 12 11 10 9 8
RES[15:8]
76543210
RES[7:0]
807
32142D–06/2013
ATUC64/128/256L3/4U
31.7.24 CSB Resistor Control Register
Name: CSBRES
Access Type: Read/Write
Offset: 0x68
Reset Value: 0x00000000
• RES: Resistive Drive Enable
When RES[n] is 0, CSB[n] has the same drive properties as normal I/O pads.
When RES[n] is 1, CSB[n] has a nominal output resistance of 1kOhm during the burst phase.
31 30 29 28 27 26 25 24
-
23 22 21 20 19 18 17 16
- RES[16]
15 14 13 12 11 10 9 8
RES[15:8]
76543210
RES[7:0]
808
32142D–06/2013
ATUC64/128/256L3/4U
31.7.25 Autonomous Touch Base Count Register
Name: ATBASE
Access Type: Read-only
Offset: 0x6C
Reset Value: 0x00000000
• COUNT: Count value
The base count currently stored by the autonomous touch sensor. This is useful for autonomous touch debugging purposes.
31 30 29 28 27 26 25 24
-
23 22 21 20 19 18 17 16
-
15 14 13 12 11 10 9 8
COUNT[15:8]
76543210
COUNT[7:0]
809
32142D–06/2013
ATUC64/128/256L3/4U
31.7.26 Autonomous Touch Current Count Register
Name: ATCURR
Access Type: Read-only
Offset: 0x70
Reset Value: 0x00000000
• COUNT: Count value
The current count acquired by the autonomous touch sensor. This is useful for autonomous touch debugging purposes.
31 30 29 28 27 26 25 24
-
23 22 21 20 19 18 17 16
-
15 14 13 12 11 10 9 8
COUNT[15:8]
76543210
COUNT[7:0]
810
32142D–06/2013
ATUC64/128/256L3/4U
31.7.27 DMATouch State Write Register
Name: DMATSW
Access Type: Write-only
Offset: 0x78
Reset Value: 0x00000000
• NOTINCAL: Not in Calibration Mode
0: Calibration should be performed on the next iteration of the DMATouch algorithm.
1: Calibration should not be performed on the next iteration of the DMATouch algorithm.
• DETCNT: Detection Count
This count value is updated and used by the DMATouch algorithm in order to detect when a button has been pushed.
• BASECNT: Base Count
This count value represents the average expected acquired count when the sensor/button is not pushed.
31 30 29 28 27 26 25 24
- - - - - - - NOTINCAL
23 22 21 20 19 18 17 16
DETCNT[23:16]
15 14 13 12 11 10 9 8
BASECNT[15:8]
76543210
BASECNT[7:0]
811
32142D–06/2013
ATUC64/128/256L3/4U
31.7.28 DMA Touch State Read Register
Name: DMATSR
Access Type: Read/Write
Offset: 0x7C
Reset Value: 0x00000000
• NOTINCAL: Not in Calibration Mode
0: Calibration should be performed on the next iteration of the DMATouch algorithm.
1: Calibration should not be performed on the next iteration of the DMATouch algorithm.
• DETCNT: Detection Count
This count value is updated and used by the DMATouch algorithm in order to detect when a button has been pushed.
• BASECNT: Base Count
This count value represents the average expected acquired count when the sensor/button is not pushed.
31 30 29 28 27 26 25 24
- - - - - - - NOTINCAL
23 22 21 20 19 18 17 16
DETCNT[23:16]
15 14 13 12 11 10 9 8
BASECNT[15:8]
76543210
BASECNT[7:0]
812
32142D–06/2013
ATUC64/128/256L3/4U
31.7.29 Analog Comparator Shift Offset Register x
Name: ACSHIx
Access Type: Read/Write
Offset: 0x80, 0x84, 0x88, 0x8C, 0x90, 0x94, 0x98, and 0x9C
Reset Value: 0x00000000
• SHIVAL: Shift Offset Value
Specifies the amount to shift the count value from each comparator. This allows the offset of each comparator to be
compensated.
31 30 29 28 27 26 25 24
-
23 22 21 20 19 18 17 16
-
15 14 13 12 11 10 9 8
- SHIVAL[11:8]
76543210
SHIVAL[7:0]
813
32142D–06/2013
ATUC64/128/256L3/4U
31.7.30 DMATouch Sensor Status Register
Name: DMATSS
Access Type: Read-only
Offset: 0xA0
Reset Value: 0x00000000
• SS: Sensor Status
0: The DMATouch sensor is not active, i.e. the button is currently not pushed.
1: The DMATouch sensor is active, i.e. the button is currently pushed.
31 30 29 28 27 26 25 24
SS[31:24]
23 22 21 20 19 18 17 16
SS[23:16]
15 14 13 12 11 10 9 8
SS[15:8]
76543210
SS[7:0]
814
32142D–06/2013
ATUC64/128/256L3/4U
31.7.31 Parameter Register
Name: PARAMETER
Access Type: Read-only
Offset: 0xF8
Reset Value: -
• SP[n]: Sensor pair implemented
0: The corresponding sensor pair is not implemented
1: The corresponding sensor pair is implemented.
31 30 29 28 27 26 25 24
SP[31:24]
23 22 21 20 19 18 17 16
SP[23:16]
15 14 13 12 11 10 9 8
SP[15:8]
76543210
SP[7:0]
815
32142D–06/2013
ATUC64/128/256L3/4U
31.7.32 Version Register
Name: VERSION
Access Type: Read-only
Offset: 0xFC
Reset Value: -
• VARIANT: Variant number
Reserved. No functionality associated.
• VERSION: Version number
Version number of the module. No functionality associated.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
- - - - VARIANT
15 14 13 12 11 10 9 8
- - - - VERSION[11:8]
76543210
VERSION[7:0]
816
32142D–06/2013
ATUC64/128/256L3/4U
31.8 Module Configuration
The specific configuration the CAT module is listed in the following tables.The module bus
clocks listed here are connected to the system bus clocks. Please refer to the Power Manager
chapter for details.
31.8.1 Resistive Drive
By default, the CAT pins are driven with normal I/O drive properties. Some of the CSA and CSB
pins can optionally drive with a 1k output resistance for improved EMC.
To enable resistive drive on a pin, the user must write a one to the corresponding bit in the CSA
Resistor Control Register (CSARES) or CSB Resistor Control Register (CSBRES) register.
Table 31-4. CAT Configuration
Feature CAT
Number of touch sensors/Size of matrix Allows up to 17 touch sensors, or up to 16 by 8
matrix sensors to be interfaced.
Table 31-5. CAT Clocks
Clock Name Description
CLK_CAT Clock for the CAT bus interface
GCLK The generic clock used for the CAT is GCLK4
Table 31-6. Register Reset Values
Register Reset Value
VERSION 0x00000400
PARAMETER 0x0001FFFF
817
32142D–06/2013
ATUC64/128/256L3/4U
32. Glue Logic Controller (GLOC)
Rev: 1.0.0.0
32.1 Features
• Glue logic for general purpose PCB design
• Programmable lookup table
• Up to four inputs supported per lookup table
• Optional filtering of output
32.2 Overview
The Glue Logic Controller (GLOC) contains programmable logic which can be connected to the
device pins. This allows the user to eliminate logic gates for simple glue logic functions on the
PCB.
The GLOC consists of a number of lookup table (LUT) units. Each LUT can generate an output
as a user programmable logic expression with four inputs. Inputs can be individually masked.
The output can be combinatorially generated from the inputs, or filtered to remove spikes.
32.3 Block Diagram
Figure 32-1. GLOC Block Diagram PERIPHERAL BUS TRUTH
FILTER
OUT[0]
...
OUT[n]
FILTEN
IN[3:0]
…
IN[(4n+3):4n]
AEN
CLK_GLOC
GCLK
818
32142D–06/2013
ATUC64/128/256L3/4U
32.4 I/O Lines Description
Each LUT have 4 inputs and one output. The inputs and outputs for the LUTs are mapped
sequentially to the inputs and outputs. This means that LUT0 is connected to IN0 to IN3 and
OUT0. LUT1 is connected to IN4 to IN7 and OUT1. In general, LUTn is connected to IN[4n] to
IN[4n+3] and OUTn.
32.5 Product Dependencies
In order to use this module, other parts of the system must be configured correctly, as described
below.
32.5.1 I/O Lines
The pins used for interfacing the GLOC may be multiplexed with I/O Controller lines. The programmer
must first program the I/O Controller to assign the desired GLOC pins to their
peripheral function. If I/O lines of the GLOC are not used by the application, they can be used for
other purposes by the I/O Controller.
It is only required to enable the GLOC inputs and outputs actually in use. Pullups for pins configured
to be used by the GLOC will be disabled.
32.5.2 Clocks
The clock for the GLOC bus interface (CLK_GLOC) is generated by the Power Manager. This
clock is enabled at reset, and can be disabled in the Power Manager. It is recommended to disable
the GLOC before disabling the clock, to avoid freezing the module in an undefined state.
Additionally, the GLOC depends on a dedicated Generic Clock (GCLK). The GCLK can be set to
a wide range of frequencies and clock sources, and must be enabled by the System Control
Interface (SCIF) before the GLOC filter can be used.
32.5.3 Debug Operation
When an external debugger forces the CPU into debug mode, the GLOC continues normal
operation.
32.6 Functional Description
32.6.1 Enabling the Lookup Table Inputs
Since the inputs to each lookup table (LUT) unit can be multiplexed with other peripherals, each
input must be explicitly enabled by writing a one to the corresponding enable bit (AEN) in the
corresponding Control Register (CR).
If no inputs are enabled, the output OUTn will be the least significant bit in the TRUTHn register.
Table 32-1. I/O Lines Description
Pin Name Pin Description Type
IN0-INm Inputs to lookup tables Input
OUT0-OUTn Output from lookup tables Output
819
32142D–06/2013
ATUC64/128/256L3/4U
32.6.2 Configuring the Lookup Table
The lookup table in each LUT unit can generate any logic expression OUT as a function of up to
four inputs, IN[3:0]. The truth table for the expression is written to the TRUTH register for the
LUT. Table 32-2 shows the truth table for LUT0. The truth table for LUTn is written to TRUTHn,
and the corresponding input and outputs will be IN[4n] to IN[4n+3] and OUTn.
32.6.3 Output Filter
By default, the output OUTn is a combinatorial function of the inputs IN[4n] to IN[4n+3]. This may
cause some short glitches to occur when the inputs change value.
It is also possible to clock the output through a filter to remove glitches. This requires that the
corresponding generic clock (GCLK) has been enabled before use. The filter can then be
enabled by writing a one to the Filter Enable (FILTEN) bit in CRn. The OUTn output will be
delayed by three to four GCLK cycles when the filter is enabled.
Table 32-2. Truth Table for the Lookup Table in LUT0
IN[3] IN[2] IN[1] IN[0] OUT[0]
0 0 0 0 TRUTH0[0]
0 0 0 1 TRUTH0[1]
0 0 1 0 TRUTH0[2]
0 0 1 1 TRUTH0[3]
0 1 0 0 TRUTH0[4]
0 1 0 1 TRUTH0[5]
0 1 1 0 TRUTH0[6]
0 1 1 1 TRUTH0[7]
1 0 0 0 TRUTH0[8]
1 0 0 1 TRUTH0[9]
1 0 1 0 TRUTH0[10]
1 0 1 1 TRUTH0[11]
1 1 0 0 TRUTH0[12]
1 1 0 1 TRUTH0[13]
1 1 1 0 TRUTH0[14]
1 1 1 1 TRUTH0[15]
820
32142D–06/2013
ATUC64/128/256L3/4U
32.7 User Interface
Note: 1. The reset values are device specific. Please refer to the Module Configuration section at the end of this chapter.
Table 32-3. GLOC Register Memory Map
Offset Register Register Name Access Reset
0x00+n*0x08 Control Register n CRn Read/Write 0x00000000
0x04+n*0x08 Truth Table Register n TRUTHn Read/Write 0x00000000
0x38 Parameter Register PARAMETER Read-only - (1)
0x3C Version Register VERSION Read-only - (1)
821
32142D–06/2013
ATUC64/128/256L3/4U
32.7.1 Control Register n
Name: CRn
Access Type: Read/Write
Offset: 0x00+n*0x08
Reset Value: 0x00000000
• FILTEN: Filter Enable
1: The output is glitch filtered
0: The output is not glitch filtered
• AEN: Enable IN Inputs
Input IN[n] is enabled when AEN[n] is one.
Input IN[n] is disabled when AEN[n] is zero, and will not affect the OUT value.
31 30 29 28 27 26 25 24
FILTEN - - - - - - -
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
- - - - AEN
822
32142D–06/2013
ATUC64/128/256L3/4U
32.7.2 Truth Table Register n
Name: TRUTHn
Access Type: Read/Write
Offset: 0x04+n*0x08
Reset Value: 0x00000000
• TRUTH: Truth Table Value
This value defines the output OUT as a function of inputs IN:
OUT = TRUTH[IN]
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
TRUTH[15:8]
76543210
TRUTH[7:0]
823
32142D–06/2013
ATUC64/128/256L3/4U
32.7.3 Parameter Register
Name: PARAMETER
Access Type: Read-only
Offset: 0x38
Reset Value: -
• LUTS: Lookup Table Units Implemented
This field contains the number of lookup table units implemented in this device.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
LUTS
824
32142D–06/2013
ATUC64/128/256L3/4U
32.7.4 VERSION Register
Name: VERSION
Access Type: Read-only
Offset: 0x3C
Reset Value: -
• VARIANT: Variant Number
Reserved. No functionality associated.
• VERSION: Version Number
Version number of the module. No functionality associated.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
- - - - VARIANT
15 14 13 12 11 10 9 8
- - - - VERSION[11:8]
76543210
VERSION[7:0]
825
32142D–06/2013
ATUC64/128/256L3/4U
32.8 Module Configuration
The specific configuration for each GLOC instance is listed in the following tables.The GLOC
bus clocks listed here are connected to the system bus clocks. Please refer to the Power Manager
chapter for details.
Table 32-4. GLOC Configuration
Feature GLOC
Number of LUT units 2
Table 32-5. GLOC Clocks
Clock Name Description
CLK_GLOC Clock for the GLOC bus interface
GCLK The generic clock used for the GLOC is GCLK5
Table 32-6. Register Reset Values
Register Reset Value
VERSION 0x00000100
PARAMETER 0x00000002
826
32142D–06/2013
ATUC64/128/256L3/4U
33. aWire UART (AW)
Rev: 2.3.0.0
33.1 Features
• Asynchronous receiver or transmitter when the aWire system is not used for debugging.
• One- or two-pin operation supported.
33.2 Overview
If the AW is not used for debugging, the aWire UART can be used by the user to send or receive
data with one start bit, eight data bits, no parity bits, and one stop bit. This can be controlled
through the aWire UART user interface.
This chapter only describes the aWire UART user interface. For a description of the aWire
Debug Interface, please see the Programming and Debugging chapter.
33.3 Block Diagram
Figure 33-1. aWire Debug Interface Block Diagram
UART
Reset
filter
External reset
AW_ENABLE
RESET_N
Baudrate Detector
RW SZ ADDR DATA
CRC
AW CONTROL
AW User Interface
SAB interface
RESET command
Power
Manager
HALT command CPU
Flash
Controller CHIP_ERASE command
aWire Debug Interface
PB
SAB
827
32142D–06/2013
ATUC64/128/256L3/4U
33.4 I/O Lines Description
33.5 Product Dependencies
In order to use this module, other parts of the system must be configured correctly, as described
below.
33.5.1 I/O Lines
The pin used by AW is multiplexed with the RESET_N pin. The reset functionality is the default
function of this pin. To enable the aWire functionality on the RESET_N pin the user must enable
the aWire UART user interface.
33.5.2 Power Management
If the CPU enters a sleep mode that disables clocks used by the aWire UART user interface, the
aWire UART user interface will stop functioning and resume operation after the system wakes
up from sleep mode.
33.5.3 Clocks
The aWire UART uses the internal 120 MHz RC oscillator (RC120M) as clock source for its
operation. When using the aWire UART user interface RC120M must enabled using the Clock
Request Register (see Section 33.6.1).
The clock for the aWire UART user interface (CLK_AW) is generated by the Power Manager.
This clock is enabled at reset, and can be disabled in the Power Manager. It is recommended to
disable the aWire UART user interface before disabling the clock, to avoid freezing the aWire
UART user interface in an undefined state.
33.5.4 Interrupts
The aWire UART user interface interrupt request line is connected to the interrupt controller.
Using the aWire UART user interface interrupt requires the interrupt controller to be programmed
first.
33.5.5 Debug Operation
If the AW is used for debugging the aWire UART user interface will not be usable.
When an external debugger forces the CPU into debug mode, the aWire UART user interface
continues normal operation. If the aWire UART user interface is configured in a way that
requires it to be periodically serviced by the CPU through interrupts or similar, improper operation
or data loss may result during debugging.
33.5.6 External Components
The AW needs an external pullup on the RESET_N pin to ensure that the pin is pulled up when
the bus is not driven.
33.6 Functional Description
The aWire UART user interface can be used as a spare Asynchronous Receiver or Transmitter
when AW is not used for debugging.
Table 33-1. I/O Lines Description
Name Description Type
DATA aWire data multiplexed with the RESET_N pin. Input/Output
828
32142D–06/2013
ATUC64/128/256L3/4U
33.6.1 How to Initialize The Module
To initialize the aWire UART user interface the user must first enable the clock by writing a one
to the Clock Enable bit in the Clock Request Register (CLKR.CLKEN) and wait for the Clock
Enable bit in the Status Register (SR.CENABLED) to be set. After doing this either receive,
transmit or receive with resync must be selected by writing the corresponding value into the
Mode field of the Control (CTRL.MODE) Register. Due to the RC120M being asynchronous with
the system clock values must be allowed to propagate in the system. During this time the aWire
master will set the Busy bit in the Status Register (SR.BUSY).
After the SR.BUSY bit is cleared the Baud Rate field in the Baud Rate Register (BRR.BR) can
be written with the wanted baudrate ( ) according to the following formula ( is the RC120M
clock frequency):
After this operation the user must wait until the SR.BUSY is cleared. The interface is now ready
to be used.
33.6.2 Basic Asynchronous Receiver Operation
The aWire UART user interface must be initialized according to the sequence above, but the
CTRL.MODE field must be written to one (Receive mode).
When a data byte arrives the aWire UART user interface will indicate this by setting the Data
Ready Interrupt bit in the Status Register (SR.DREADYINT). The user must read the Data in the
Receive Holding Register (RHR.RXDATA) and clear the Interrupt bit by writing a one to the Data
Ready Interrupt Clear bit in the Status Clear Register (SCR.DREADYINT). The interface is now
ready to receive another byte.
33.6.3 Basic Asynchronous Transmitter Operation
The aWire UART user interface must be initialized according to the sequence above, but the
CTRL.MODE field must be written to two (Transmit mode).
To transmit a data byte the user must write the data to the Transmit Holding Register
(THE.TXDATA). Before the next byte can be written the SR.BUSY must be cleared.
33.6.4 Basic Asynchronous Receiver with Resynchronization
By writing three into CTRL.MODE the aWire UART user interface will assume that the first byte
it receives is a sync byte (0x55) and set BRR.BR according to this. All subsequent transfers will
assume this baudrate, unless BRR.BR is rewritten by the user.
To make the aWire UART user interface accept a new sync resynchronization the aWire UART
user interface must be disabled by writing zero to CTRL.MODE and then reenable the interface.
33.6.5 Overrun
In Receive mode an overrun can occur if the user has not read the previous received data from
the RHR.RXDATA when the newest data should be placed there. Such a condition is flagged by
setting the Overrun bit in the Status Register (SR.OVERRUN). If SR.OVERRUN is set the newest
data received is placed in RHR.RXDATA and the data that was there before is overwritten.
f
br f
aw
f
br
8f
aw
BR = -----------
829
32142D–06/2013
ATUC64/128/256L3/4U
33.6.6 Interrupts
To make the CPU able to do other things while waiting for the aWire UART user interface to finish
its operations the aWire UART user interface supports generating interrupts. All status bits in
the Status Register can be used as interrupt sources, except the SR.BUSY and SR.CENABLED
bits.
To enable an interrupt the user must write a one to the corresponding bit in the Interrupt Enable
Register (IER). Upon the next zero to one transition of this SR bit the aWire UART user interface
will flag this interrupt to the CPU. To clear the interrupt the user must write a one to the corresponding
bit in the Status Clear Register (SCR).
Interrupts can be disabled by writing a one to the corresponding bit in the Interrupt Disable Register
(IDR). The interrupt Mask Register (IMR) can be read to check if an interrupt is enabled or
disabled.
33.6.7 Using the Peripheral DMA Controller
To relieve the CPU of data transfers the aWire UART user interface support using the Peripheral
DMA controller.
To transmit using the Peripheral DMA Controller do the following:
1. Setup the aWire UART user interface in transmit mode.
2. Setup the Peripheral DMA Controller with buffer address and length, use byte as transfer
size.
3. Enable the Peripheral DMA Controller.
4. Wait until the Peripheral DMA Controller is done.
To receive using the Peripheral DMA Controller do the following:
1. Setup the aWire UART user interface in receive mode
2. Setup the Peripheral DMA Controller with buffer address and length, use byte as transfer
size.
3. Enable the Peripheral DMA Controller.
4. Wait until the Peripheral DMA Controller is ready.
830
32142D–06/2013
ATUC64/128/256L3/4U
33.7 User Interface
Note: 1. The reset values are device specific. Please refer to the Module Configuration section at the end of this chapter.
Table 33-2. aWire UART user interface Register Memory Map
Offset Register Register Name Access Reset
0x00 Control Register CTRL Read/Write 0x00000000
0x04 Status Register SR Read-only 0x00000000
0x08 Status Clear Register SCR Write-only -
0x0C Interrupt Enable Register IER Write-only -
0x10 Interrupt Disable Register IDR Write-only -
0x14 Interrupt Mask Register IMR Read-only 0x00000000
0x18 Receive Holding Register RHR Read-only 0x00000000
0x1C Transmit Holding Register THR Read/Write 0x00000000
0x20 Baud Rate Register BRR Read/Write 0x00000000
0x24 Version Register VERSION Read-only -(1)
0x28 Clock Request Register CLKR Read/Write 0x00000000
831
32142D–06/2013
ATUC64/128/256L3/4U
33.7.1 Control Register
Name: CTRL
Access Type: Read/Write
Offset: 0x00
Reset Value: 0x00000000
• MODE: aWire UART user interface mode
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
- - - - - - MODE
Table 33-3. aWire UART user interface Modes
MODE Mode Description
0 Disabled
1 Receive
2 Transmit
3 Receive with resync.
832
32142D–06/2013
ATUC64/128/256L3/4U
33.7.2 Status Register
Name: SR
Access Type: Read-only
Offset: 0x04
Reset Value: 0x00000000
• TRMIS: Transmit Mismatch
0: No transfers mismatches.
1: The transceiver was active when receiving.
This bit is set when the transceiver is active when receiving.
This bit is cleared when corresponding bit in SCR is written to one.
• OVERRUN: Data Overrun
0: No data overwritten in RHR.
1: Data in RHR has been overwritten before it has been read.
This bit is set when data in RHR is overwritten before it has been read.
This bit is cleared when corresponding bit in SCR is written to one.
• DREADYINT: Data Ready Interrupt
0: No new data in the RHR.
1: New data received and placed in the RHR.
This bit is set when new data is received and placed in the RHR.
This bit is cleared when corresponding bit in SCR is written to one.
• READYINT: Ready Interrupt
0: The interface has not generated an ready interrupt.
1: The interface has had a transition from busy to not busy.
This bit is set when the interface has transition from busy to not busy.
This bit is cleared when corresponding bit in SCR is written to one.
• CENABLED: Clock Enabled
0: The aWire clock is not enabled.
1: The aWire clock is enabled.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
- - TRMIS - - OVERRUN DREADYINT READYINT
76543210
- - - - - CENABLED - BUSY
833
32142D–06/2013
ATUC64/128/256L3/4U
This bit is set when the clock is disabled.
This bit is cleared when the clock is enabled.
• BUSY: Synchronizer Busy
0: The asynchronous interface is ready to accept more data.
1: The asynchronous interface is busy and will block writes to CTRL, BRR, and THR.
This bit is set when the asynchronous interface becomes busy.
This bit is cleared when the asynchronous interface becomes ready.
834
32142D–06/2013
ATUC64/128/256L3/4U
33.7.3 Status Clear Register
Name: SCR
Access Type: Write-only
Offset: 0x08
Reset Value: 0x00000000
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will clear the corresponding bit in SR and the corresponding interrupt request.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
- - TRMIS - - OVERRUN DREADYINT READYINT
76543210
--------
835
32142D–06/2013
ATUC64/128/256L3/4U
33.7.4 Interrupt Enable Register
Name: IER
Access Type: Write-only
Offset: 0x0C
Reset Value: 0x00000000
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will set the corresponding bit in IMR.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
- - TRMIS - - OVERRUN DREADYINT READYINT
76543210
--------
836
32142D–06/2013
ATUC64/128/256L3/4U
33.7.5 Interrupt Disable Register
Name: IDR
Access Type: Write-only
Offset: 0x10
Reset Value: 0x00000000
Writing a zero to a bit in this register has no effect.
Writing a one to a bit in this register will clear the corresponding bit in IMR.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
- - TRMIS - - OVERRUN DREADYINT READYINT
76543210
--------
837
32142D–06/2013
ATUC64/128/256L3/4U
33.7.6 Interrupt Mask Register
Name: IMR
Access Type: Read-only
Offset: 0x14
Reset Value: 0x00000000
0: The corresponding interrupt is disabled.
1: The corresponding interrupt is enabled.
A bit in this register is cleared when the corresponding bit in IDR is written to one.
A bit in this register is set when the corresponding bit in IER is written to one.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
- - TRMIS - - OVERRUN DREADYINT READYINT
76543210
--------
838
32142D–06/2013
ATUC64/128/256L3/4U
33.7.7 Receive Holding Register
Name: RHR
Access Type: Read-only
Offset: 0x18
Reset Value: 0x00000000
• RXDATA: Received Data
The last byte received.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
RXDATA
839
32142D–06/2013
ATUC64/128/256L3/4U
33.7.8 Transmit Holding Register
Name: THR
Access Type: Read/Write
Offset: 0x1C
Reset Value: 0x00000000
• TXDATA: Transmit Data
The data to send.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
TXDATA
840
32142D–06/2013
ATUC64/128/256L3/4U
33.7.9 Baud Rate Register
Name: BRR
Access Type: Read/Write
Offset: 0x20
Reset Value: 0x00000000
• BR: Baud Rate
The baud rate ( ) of the transmission, calculated using the following formula ( is the RC120M frequency):
BR should not be set to a value smaller than 32.
Writing a value to this field will update the baud rate of the transmission.
Reading this field will give the current baud rate of the transmission.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
BR[15:8]
76543210
BR[7:0]
f
br f
aw
f
br
8f
aw
BR = -----------
841
32142D–06/2013
ATUC64/128/256L3/4U
33.7.10 Version Register
Name: VERSION
Access Type: Read-only
Offset: 0x24
Reset Value: 0x00000200
• VERSION: Version Number
Version number of the module. No functionality associated.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
- - - - VERSION[11:8]
76543210
VERSION[7:0]
842
32142D–06/2013
ATUC64/128/256L3/4U
33.7.11 Clock Request Register
Name: CLKR
Access Type: Read/Write
Offset: 0x28
Reset Value: 0x00000000
• CLKEN: Clock Enable
0: The aWire clock is disabled.
1: The aWire clock is enabled.
Writing a zero to this bit will disable the aWire clock.
Writing a one to this bit will enable the aWire clock.
31 30 29 28 27 26 25 24
--------
23 22 21 20 19 18 17 16
--------
15 14 13 12 11 10 9 8
--------
76543210
- - - - - - - CLKEN
843
32142D–06/2013
ATUC64/128/256L3/4U
33.8 Module Configuration
The specific configuration for each aWire instance is listed in the following tables.The module
bus clocks listed here are connected to the system bus clocks. Please refer to the Power Manager
chapter for details.
Table 33-4. AW Clocks
Clock Name Description
CLK_AW Clock for the AW bus interface
Table 33-5. Register Reset Values
Register Reset Value
VERSION 0x00000230
844
32142D–06/2013
ATUC64/128/256L3/4U
34. Programming and Debugging
34.1 Overview
The ATUC64/128/256L3/4U supports programming and debugging through two interfaces,
JTAG or aWire. JTAG is an industry standard interface and allows boundary scan for PCB testing,
as well as daisy-chaining of multiple devices on the PCB. aWire is an Atmel proprietary
protocol which offers higher throughput and robust communication, and does not require application
pins to be reserved. Either interface provides access to the internal Service Access Bus
(SAB), which offers a bridge to the High Speed Bus, giving access to memories and peripherals
in the device. By using this bridge to the bus system, the flash and fuses can thus be programmed
by accessing the Flash Controller in the same manner as the CPU.
The SAB also provides access to the Nexus-compliant On-chip Debug (OCD) system in the
device, which gives the user non-intrusive run-time control of the program execution. Additionally,
trace information can be output on the Auxiliary (AUX) debug port or buffered in internal
RAM for later retrieval by JTAG or aWire.
34.2 Service Access Bus
The AVR32 architecture offers a common interface for access to On-chip Debug, programming,
and test functions. These are mapped on a common bus called the Service Access Bus (SAB),
which is linked to the JTAG and aWire port through a bus master module, which also handles
synchronization between the debugger and SAB clocks.
When accessing the SAB through the debugger there are no limitations on debugger frequency
compared to chip frequency, although there must be an active system clock in order for the SAB
accesses to complete. If the system clock is switched off in sleep mode, activity on the debugger
will restart the system clock automatically, without waking the device from sleep. Debuggers
may optimize the transfer rate by adjusting the frequency in relation to the system clock. This
ratio can be measured with debug protocol specific instructions.
The Service Access Bus uses 36 address bits to address memory or registers in any of the
slaves on the bus. The bus supports sized accesses of bytes (8 bits), halfwords (16 bits), or
words (32 bits). All accesses must be aligned to the size of the access, i.e. halfword accesses
must have the lowest address bit cleared, and word accesses must have the two lowest address
bits cleared.
34.2.1 SAB Address Map
The SAB gives the user access to the internal address space and other features through a 36
bits address space. The 4 MSBs identify the slave number, while the 32 LSBs are decoded
within the slave’s address space. The SAB slaves are shown in Table 34-1.
Table 34-1. SAB Slaves, Addresses and Descriptions
Slave Address [35:32] Description
Unallocated 0x0 Intentionally unallocated
OCD 0x1 OCD registers
HSB 0x4 HSB memory space, as seen by the CPU
845
32142D–06/2013
ATUC64/128/256L3/4U
34.2.2 SAB Security Restrictions
The Service Access bus can be restricted by internal security measures. A short description of
the security measures are found in the table below.
34.2.2.1 Security measure and control location
A security measure is a mechanism to either block or allow SAB access to a certain address or
address range. A security measure is enabled or disabled by one or several control signals. This
is called the control location for the security measure.
These security measures can be used to prevent an end user from reading out the code programmed
in the flash, for instance.
Below follows a more in depth description of what locations are accessible when the security
measures are active.
Note: 1. Second Word of the User Page, refer to the Fuses Settings section for details.
HSB 0x5 Alternative mapping for HSB space, for compatibility with
other 32-bit AVR devices.
Memory Service
Unit 0x6 Memory Service Unit registers
Reserved Other Unused
Table 34-1. SAB Slaves, Addresses and Descriptions
Slave Address [35:32] Description
Table 34-2. SAB Security Measures
Security Measure Control Location Description
Secure mode FLASHCDW
SECURE bits set
Allocates a portion of the flash for secure code. This code
cannot be read or debugged. The User page is also locked.
Security bit FLASHCDW
security bit set
Programming and debugging not possible, very restricted
access.
User code
programming
FLASHCDW
UPROT + security
bit set
Restricts all access except parts of the flash and the flash
controller for programming user code. Debugging is not
possible unless an OS running from the secure part of the
flash supports it.
Table 34-3. Secure Mode SAB Restrictions
Name Address Start Address End Access
Secure flash area 0x580000000 0x580000000 +
(USERPAGE[15:0] << 10) Blocked
Secure RAM area 0x500000000 0x500000000 +
(USERPAGE[31:16] << 10) Blocked
User page 0x580800000 0x581000000 Read
Other accesses - - As normal
846
32142D–06/2013
ATUC64/128/256L3/4U
Table 34-4. Security Bit SAB Restrictions
Name Address start Address end Access
OCD DCCPU,
OCD DCEMU,
OCD DCSR
0x100000110 0x100000118 Read/Write
User page 0x580800000 0x581000000 Read
Other accesses - - Blocked
Table 34-5. User Code Programming SAB Restrictions
Name Address start Address end Access
OCD DCCPU,
OCD DCEMU,
OCD DCSR
0x100000110 0x100000118 Read/Write
User page 0x580800000 0x581000000 Read
FLASHCDW PB
interface 0x5FFFE0000 0x5FFFE0400 Read/Write
FLASH pages
outside
BOOTPROT
0x580000000 +
BOOTPROT size 0x580000000 + Flash size Read/Write
Other accesses - - Blocked
847
32142D–06/2013
ATUC64/128/256L3/4U
34.3 On-Chip Debug
Rev: 2.1.2.0
34.3.1 Features
• Debug interface in compliance with IEEE-ISTO 5001-2003 (Nexus 2.0) Class 2+
• JTAG or aWire access to all on-chip debug functions
• Advanced Program, Data, Ownership, and Watchpoint trace supported
• NanoTrace aWire- or JTAG-based trace access
• Auxiliary port for high-speed trace information
• Hardware support for 6 Program and 2 Data breakpoints
• Unlimited number of software breakpoints supported
• Automatic CRC check of memory regions
34.3.2 Overview
Debugging on the ATUC64/128/256L3/4U is facilitated by a powerful On-Chip Debug (OCD)
system. The user accesses this through an external debug tool which connects to the JTAG or
aWire port and the Auxiliary (AUX) port if implemented. The AUX port is primarily used for trace
functions, and an aWire- or JTAG-based debugger is sufficient for basic debugging.
The debug system is based on the Nexus 2.0 standard, class 2+, which includes:
• Basic run-time control
• Program breakpoints
• Data breakpoints
• Program trace
• Ownership trace
• Data trace
In addition to the mandatory Nexus debug features, the ATUC64/128/256L3/4U implements
several useful OCD features, such as:
• Debug Communication Channel between CPU and debugger
• Run-time PC monitoring
• CRC checking
• NanoTrace
• Software Quality Assurance (SQA) support
The OCD features are controlled by OCD registers, which can be accessed by the debugger, for
instance when the NEXUS_ACCESS JTAG instruction is loaded. The CPU can also access
OCD registers directly using mtdr/mfdr instructions in any privileged mode. The OCD registers
are implemented based on the recommendations in the Nexus 2.0 standard, and are detailed in
the AVR32UC Technical Reference Manual.
34.3.3 I/O Lines Description
The OCD AUX trace port contains a number of pins, as shown in Table 34-6 on page 848.
These are multiplexed with I/O Controller lines, and must explicitly be enabled by writing OCD
registers before the debug session starts. The AUX port is mapped to two different locations,
848
32142D–06/2013
ATUC64/128/256L3/4U
selectable by OCD Registers, minimizing the chance that the AUX port will need to be shared
with an application.
34.3.4 Product Dependencies
In order to use this module, other parts of the system must be configured correctly, as described
below.
34.3.4.1 Power Management
The OCD clock operates independently of the CPU clock. If enabled in the Power Manager, the
OCD clock (CLK_OCD) will continue running even if the CPU enters a sleep mode that disables
the CPU clock.
34.3.4.2 Clocks
The OCD has a clock (CLK_OCD) running synchronously with the CPU clock. This clock is generated
by the Power Manager. The clock is enabled at reset, and can be disabled by writing to
the Power Manager.
34.3.4.3 Interrupt
The OCD system interrupt request lines are connected to the interrupt controller. Using the OCD
interrupts requires the interrupt controller to be programmed first.
Table 34-6. Auxiliary Port Signals
Pin Name Pin Description Direction Active Level Type
MCKO Trace data output clock Output Digital
MDO[5:0] Trace data output Output Digital
MSEO[1:0] Trace frame control Output Digital
EVTI_N Event In Input Low Digital
EVTO_N Event Out Output Low Digital
849
32142D–06/2013
ATUC64/128/256L3/4U
34.3.5 Block Diagram
Figure 34-1. On-Chip Debug Block Diagram
34.3.6 SAB-based Debug Features
A debugger can control all OCD features by writing OCD registers over the SAB interface. Many
of these do not depend on output on the AUX port, allowing an aWire- or JTAG-based debugger
to be used.
A JTAG-based debugger should connect to the device through a standard 10-pin IDC connector
as described in the AVR32UC Technical Reference Manual.
An aWire-based debugger should connect to the device through the RESET_N pin.
On-Chip Debug
JTAG
Debug PC
Debug
Instruction
CPU
Breakpoints
Program
Trace Data Trace Ownership
Trace
Transmit Queue Watchpoints
AUX
JTAG
Internal
SRAM
Service Access Bus
Memory
Service
Unit
HSB Bus Matrix Memories and
peripherals
aWire
aWire
850
32142D–06/2013
ATUC64/128/256L3/4U
Figure 34-2. JTAG-based Debugger
Figure 34-3. aWire-based Debugger
34.3.6.1 Debug Communication Channel
The Debug Communication Channel (DCC) consists of a pair OCD registers with associated
handshake logic, accessible to both CPU and debugger. The registers can be used to exchange
data between the CPU and the debugmaster, both runtime as well as in debug mode.
32-bit AVR
JTAG-based
debug tool
PC
JTAG
10-pin IDC
32-bit AVR
aWire-based
debug tool
PC
aWire
851
32142D–06/2013
ATUC64/128/256L3/4U
The OCD system can generate an interrupt to the CPU when DCCPU is read and when DCEMU
is written. This enables the user to build a custum debug protocol using only these registers. The
DCCPU and DCEMU registers are available even when the security bit in the flash is active.
For more information refer to the AVR32UC Technical Reference Manual.
34.3.6.2 Breakpoints
One of the most fundamental debug features is the ability to halt the CPU, to examine registers
and the state of the system. This is accomplished by breakpoints, of which many types are
available:
• Unconditional breakpoints are set by writing OCD registers by the debugger, halting the CPU
immediately.
• Program breakpoints halt the CPU when a specific address in the program is executed.
• Data breakpoints halt the CPU when a specific memory address is read or written, allowing
variables to be watched.
• Software breakpoints halt the CPU when the breakpoint instruction is executed.
When a breakpoint triggers, the CPU enters debug mode, and the D bit in the status register is
set. This is a privileged mode with dedicated return address and return status registers. All privileged
instructions are permitted. Debug mode can be entered as either OCD Mode, running
instructions from the debugger, or Monitor Mode, running instructions from program memory.
34.3.6.3 OCD Mode
When a breakpoint triggers, the CPU enters OCD mode, and instructions are fetched from the
Debug Instruction OCD register. Each time this register is written by the debugger, the instruction
is executed, allowing the debugger to execute CPU instructions directly. The debug master
can e.g. read out the register file by issuing mtdr instructions to the CPU, writing each register to
the Debug Communication Channel OCD registers.
34.3.6.4 Monitor Mode
Since the OCD registers are directly accessible by the CPU, it is possible to build a softwarebased
debugger that runs on the CPU itself. Setting the Monitor Mode bit in the Development
Control register causes the CPU to enter Monitor Mode instead of OCD mode when a breakpoint
triggers. Monitor Mode is similar to OCD mode, except that instructions are fetched from the
debug exception vector in regular program memory, instead of issued by the debug master.
34.3.6.5 Program Counter Monitoring
Normally, the CPU would need to be halted for a debugger to examine the current PC value.
However, the ATUC64/128/256L3/4U also proves a Debug Program Counter OCD register,
where the debugger can continuously read the current PC without affecting the CPU. This allows
the debugger to generate a simple statistic of the time spent in various areas of the code, easing
code optimization.
34.3.7 Memory Service Unit
The Memory Service Unit (MSU) is a block dedicated to test and debug functionality. It is controlled
through a dedicated set of registers addressed through the Service Access Bus.
852
32142D–06/2013
ATUC64/128/256L3/4U
34.3.7.1 Cyclic Redundancy Check (CRC)
The MSU can be used to automatically calculate the CRC of a block of data in memory. The
MSU will then read out each word in the specified memory block and report the CRC32-value in
an MSU register.
34.3.7.2 NanoTrace
The MSU additionally supports NanoTrace. This is a 32-bit AVR-specific feature, in which trace
data is output to memory instead of the AUX port. This allows the trace data to be extracted by
the debugger through the SAB, enabling trace features for aWire- or JTAG-based debuggers.
The user must write MSU registers to configure the address and size of the memory block to be
used for NanoTrace. The NanoTrace buffer can be anywhere in the physical address range,
including internal and external RAM, through an EBI, if present. This area may not be used by
the application running on the CPU.
34.3.8 AUX-based Debug Features
Utilizing the Auxiliary (AUX) port gives access to a wide range of advanced debug features. Of
prime importance are the trace features, which allow an external debugger to receive continuous
information on the program execution in the CPU. Additionally, Event In and Event Out pins
allow external events to be correlated with the program flow.
Debug tools utilizing the AUX port should connect to the device through a Nexus-compliant Mictor-38
connector, as described in the AVR32UC Technical Reference manual. This connector
includes the JTAG signals and the RESET_N pin, giving full access to the programming and
debug features in the device.
853
32142D–06/2013
ATUC64/128/256L3/4U
Figure 34-4. AUX+JTAG Based Debugger
34.3.8.1 Trace Operation
Trace features are enabled by writing OCD registers by the debugger. The OCD extracts the
trace information from the CPU, compresses this information and formats it into variable-length
messages according to the Nexus standard. The messages are buffered in a 16-frame transmit
queue, and are output on the AUX port one frame at a time.
The trace features can be configured to be very selective, to reduce the bandwidth on the AUX
port. In case the transmit queue overflows, error messages are produced to indicate loss of
data. The transmit queue module can optionally be configured to halt the CPU when an overflow
occurs, to prevent the loss of messages, at the expense of longer run-time for the program.
34.3.8.2 Program Trace
Program trace allows the debugger to continuously monitor the program execution in the CPU.
Program trace messages are generated for every branch in the program, and contains compressed
information, which allows the debugger to correlate the message with the source code
to identify the branch instruction and target address.
34.3.8.3 Data Trace
Data trace outputs a message every time a specific location is read or written. The message
contains information about the type (read/write) and size of the access, as well as the address
and data of the accessed location. The ATUC64/128/256L3/4U contains two data trace chanAVR32
AUX+JTAG
debu g tool
JTAG AUX
h ig h s p e e d
M ic to r3 8
T ra ce b u ffe r
P C
854
32142D–06/2013
ATUC64/128/256L3/4U
nels, each of which are controlled by a pair of OCD registers which determine the range of
addresses (or single address) which should produce data trace messages.
34.3.8.4 Ownership Trace
Program and data trace operate on virtual addresses. In cases where an operating system runs
several processes in overlapping virtual memory segments, the Ownership Trace feature can be
used to identify the process switch. When the O/S activates a process, it will write the process ID
number to an OCD register, which produces an Ownership Trace Message, allowing the debugger
to switch context for the subsequent program and data trace messages. As the use of this
feature depends on the software running on the CPU, it can also be used to extract other types
of information from the system.
34.3.8.5 Watchpoint Messages
The breakpoint modules normally used to generate program and data breakpoints can also be
used to generate Watchpoint messages, allowing a debugger to monitor program and data
events without halting the CPU. Watchpoints can be enabled independently of breakpoints, so a
breakpoint module can optionally halt the CPU when the trigger condition occurs. Data trace
modules can also be configured to produce watchpoint messages instead of regular data trace
messages.
34.3.8.6 Event In and Event Out Pins
The AUX port also contains an Event In pin (EVTI_N) and an Event Out pin (EVTO_N). EVTI_N
can be used to trigger a breakpoint when an external event occurs. It can also be used to trigger
specific program and data trace synchronization messages, allowing an external event to be
correlated to the program flow.
When the CPU enters debug mode, a Debug Status message is transmitted on the trace port.
All trace messages can be timestamped when they are received by the debug tool. However,
due to the latency of the transmit queue buffering, the timestamp will not be 100% accurate. To
improve this, EVTO_N can toggle every time a message is inserted into the transmit queue,
allowing trace messages to be timestamped precisely. EVTO_N can also toggle when a breakpoint
module triggers, or when the CPU enters debug mode, for any reason. This can be used to
measure precisely when the respective internal event occurs.
34.3.8.7 Software Quality Analysis (SQA)
Software Quality Analysis (SQA) deals with two important issues regarding embedded software
development. Code coverage involves identifying untested parts of the embedded code, to
improve test procedures and thus the quality of the released software. Performance analysis
allows the developer to precisely quantify the time spent in various parts of the code, allowing
bottlenecks to be identified and optimized.
Program trace must be used to accomplish these tasks without instrumenting (altering) the code
to be examined. However, traditional program trace cannot reconstruct the current PC value
without correlating the trace information with the source code, which cannot be done on-the-fly.
This limits program trace to a relatively short time segment, determined by the size of the trace
buffer in the debug tool.
The OCD system in ATUC64/128/256L3/4U extends program trace with SQA capabilities, allowing
the debug tool to reconstruct the PC value on-the-fly. Code coverage and performance
analysis can thus be reported for an unlimited execution sequence.
855
32142D–06/2013
ATUC64/128/256L3/4U
34.4 JTAG and Boundary-scan (JTAG)
Rev: 2.2.2.4
34.4.1 Features
• IEEE1149.1 compliant JTAG Interface
• Boundary-scan Chain for board-level testing
• Direct memory access and programming capabilities through JTAG Interface
34.4.2 Overview
The JTAG Interface offers a four pin programming and debug solution, including boundary-scan
support for board-level testing.
Figure 34-5 on page 856 shows how the JTAG is connected in an 32-bit AVR device. The TAP
Controller is a state machine controlled by the TCK and TMS signals. The TAP Controller
selects either the JTAG Instruction Register or one of several Data Registers as the scan chain
(shift register) between the TDI-input and TDO-output.
The Instruction Register holds JTAG instructions controlling the behavior of a Data Register. The
Device Identification Register, Bypass Register, and the boundary-scan chain are the Data Registers
used for board-level testing. The Reset Register can be used to keep the device reset
during test or programming.
The Service Access Bus (SAB) interface contains address and data registers for the Service
Access Bus, which gives access to On-Chip Debug, programming, and other functions in the
device. The SAB offers several modes of access to the address and data registers, as described
in Section 34.4.11.
Section 34.5 lists the supported JTAG instructions, with references to the description in this
document.
856
32142D–06/2013
ATUC64/128/256L3/4U
34.4.3 Block Diagram
Figure 34-5. JTAG and Boundary-scan Access
34.4.4 I/O Lines Description
34.4.5 Product Dependencies
In order to use this module, other parts of the system must be configured correctly, as described
below.
Table 34-7. I/O Line Description
Pin Name Pin Description Type Active Level
RESET_N External reset pin. Used when enabling and disabling the JTAG. Input Low
TCK Test Clock Input. Fully asynchronous to system clock frequency. Input
TMS Test Mode Select, sampled on rising TCK. Input
TDI Test Data In, sampled on rising TCK. Input
TDO Test Data Out, driven on falling TCK. Output
32-bit AVR device
JTAG data registers
TAP
Controller
Instruction Register
Device Identification
Register
By-pass Register
Reset Register
Service Access Bus
interface
Boundary Scan Chain
Pins and analog blocks
Data register
scan enable
JTAG Pins
Boundary scan enable
2nd JTAG
device
JTAG master
TDO TDI
Part specific registers
...
TMS TDO TDI
TMS
TCK
TCK
Instruction register
scan enable
SAB Internal I/O
lines
JTAG
TMS
TDI
TDO
TCK
857
32142D–06/2013
ATUC64/128/256L3/4U
34.4.5.1 I/O Lines
The TMS, TDI, TDO, and TCK pins are multiplexed with I/O lines. When the JTAG is used the
associated pins must be enabled. To enable the JTAG pins, refer to Section 34.4.7.
While using the multiplexed JTAG lines all normal peripheral activity on these lines is disabled.
The user must make sure that no external peripheral is blocking the JTAG lines while
debugging.
34.4.5.2 Power Management
When an instruction that accesses the SAB is loaded in the instruction register, before entering
a sleep mode, the system clocks are not switched off to allow debugging in sleep modes. This
can lead to a program behaving differently when debugging.
34.4.5.3 Clocks
The JTAG Interface uses the external TCK pin as clock source. This clock must be provided by
the JTAG master.
Instructions that use the SAB bus requires the internal main clock to be running.
34.4.6 JTAG Interface
The JTAG Interface is accessed through the dedicated JTAG pins shown in Table 34-7 on page
856. The TMS control line navigates the TAP controller, as shown in Figure 34-6 on page 858.
The TAP controller manages the serial access to the JTAG Instruction and Data registers. Data
is scanned into the selected instruction or data register on TDI, and out of the register on TDO,
in the Shift-IR and Shift-DR states, respectively. The LSB is shifted in and out first. TDO is highZ
in other states than Shift-IR and Shift-DR.
The device implements a 5-bit Instruction Register (IR). A number of public JTAG instructions
defined by the JTAG standard are supported, as described in Section 34.5.2, as well as a number
of 32-bit AVR-specific private JTAG instructions described in Section 34.5.3. Each
instruction selects a specific data register for the Shift-DR path, as described for each
instruction.
858
32142D–06/2013
ATUC64/128/256L3/4U
Figure 34-6. TAP Controller State Diagram
Test-LogicReset
Run-Test/
Idle
Select-DR
Scan
Select-IR
Scan
Capture-DR Capture-IR
Shift-DR Shift-IR
Exit1-DR Exit1-IR
Pause-DR Pause-IR
Exit2-DR Exit2-IR
Update-DR Update-IR
0
1 1
1
0
0
1
0
1
1
0
0
1
0
1
1
1
0
1 1
0 0
1 1
0
1
0
0 0
0
0
1
859
32142D–06/2013
ATUC64/128/256L3/4U
34.4.7 How to Initialize the Module
To enable the JTAG pins the TCK pin must be held low while the RESET_N pin is released.
After enabling the JTAG interface the halt bit is set automatically to prevent the system from running
code after the interface is enabled. To make the CPU run again set halt to zero using the
HALT command..
JTAG operation when RESET_N is pulled low is not possible.
Independent of the initial state of the TAP Controller, the Test-Logic-Reset state can always be
entered by holding TMS high for 5 TCK clock periods. This sequence should always be applied
at the start of a JTAG session and after enabling the JTAG pins to bring the TAP Controller into
a defined state before applying JTAG commands. Applying a 0 on TMS for 1 TCK period brings
the TAP Controller to the Run-Test/Idle state, which is the starting point for JTAG operations.
34.4.8 How to disable the module
To disable the JTAG pins the TCK pin must be held high while RESET_N pin is released.
34.4.9 Typical Sequence
Assuming Run-Test/Idle is the present state, a typical scenario for using the JTAG Interface
follows.
34.4.9.1 Scanning in JTAG Instruction
At the TMS input, apply the sequence 1, 1, 0, 0 at the rising edges of TCK to enter the Shift
Instruction Register (Shift-IR) state. While in this state, shift the 5 bits of the JTAG instructions
into the JTAG instruction register from the TDI input at the rising edge of TCK. During shifting,
the JTAG outputs status bits on TDO, refer to Section 34.5 for a description of these. The TMS
input must be held low during input of the 4 LSBs in order to remain in the Shift-IR state. The
JTAG Instruction selects a particular Data Register as path between TDI and TDO and controls
the circuitry surrounding the selected Data Register.
Apply the TMS sequence 1, 1, 0 to re-enter the Run-Test/Idle state. The instruction is latched
onto the parallel output from the shift register path in the Update-IR state. The Exit-IR, Pause-IR,
and Exit2-IR states are only used for navigating the state machine.
Figure 34-7. Scanning in JTAG Instruction
34.4.9.2 Scanning in/out Data
At the TMS input, apply the sequence 1, 0, 0 at the rising edges of TCK to enter the Shift Data
Register (Shift-DR) state. While in this state, upload the selected Data Register (selected by the
present JTAG instruction in the JTAG Instruction Register) from the TDI input at the rising edge
TCK
TAP State TLR RTI SelDR SelIR CapIR ShIR Ex1IR UpdIR RTI
TMS
TDI Instruction
TDO ImplDefined
860
32142D–06/2013
ATUC64/128/256L3/4U
of TCK. In order to remain in the Shift-DR state, the TMS input must be held low. While the Data
Register is shifted in from the TDI pin, the parallel inputs to the Data Register captured in the
Capture-DR state is shifted out on the TDO pin.
Apply the TMS sequence 1, 1, 0 to re-enter the Run-Test/Idle state. If the selected Data Register
has a latched parallel-output, the latching takes place in the Update-DR state. The Exit-DR,
Pause-DR, and Exit2-DR states are only used for navigating the state machine.
As shown in the state diagram, the Run-Test/Idle state need not be entered between selecting
JTAG instruction and using Data Registers.
34.4.10 Boundary-scan
The boundary-scan chain has the capability of driving and observing the logic levels on the digital
I/O pins, as well as the boundary between digital and analog logic for analog circuitry having
off-chip connections. At system level, all ICs having JTAG capabilities are connected serially by
the TDI/TDO signals to form a long shift register. An external controller sets up the devices to
drive values at their output pins, and observe the input values received from other devices. The
controller compares the received data with the expected result. In this way, boundary-scan provides
a mechanism for testing interconnections and integrity of components on Printed Circuits
Boards by using the 4 TAP signals only.
The four IEEE 1149.1 defined mandatory JTAG instructions IDCODE, BYPASS, SAMPLE/PRELOAD,
and EXTEST can be used for testing the Printed Circuit Board. Initial scanning of the
data register path will show the ID-code of the device, since IDCODE is the default JTAG
instruction. It may be desirable to have the 32-bit AVR device in reset during test mode. If not
reset, inputs to the device may be determined by the scan operations, and the internal software
may be in an undetermined state when exiting the test mode. If needed, the BYPASS instruction
can be issued to make the shortest possible scan chain through the device. The device can be
set in the reset state either by pulling the external RESETn pin low, or issuing the AVR_RESET
instruction with appropriate setting of the Reset Data Register.
The EXTEST instruction is used for sampling external pins and loading output pins with data.
The data from the output latch will be driven out on the pins as soon as the EXTEST instruction
is loaded into the JTAG IR-register. Therefore, the SAMPLE/PRELOAD should also be used for
setting initial values to the scan ring, to avoid damaging the board when issuing the EXTEST
instruction for the first time. SAMPLE/PRELOAD can also be used for taking a snapshot of the
external pins during normal operation of the part.
When using the JTAG Interface for boundary-scan, the JTAG TCK clock is independent of the
internal chip clock. The internal chip clock is not required to run during boundary-scan
operations.
NOTE: For pins connected to 5V lines care should be taken to not drive the pins to a logic one
using boundary-scan, as this will create a current flowing from the 3,3V driver to the 5V pull-up
on the line. Optionally a series resistor can be added between the line and the pin to reduce the
current.
Details about the boundary-scan chain can be found in the BSDL file for the device. This can be
found on the Atmel website.
34.4.11 Service Access Bus
The AVR32 architecture offers a common interface for access to On-Chip Debug, programming,
and test functions. These are mapped on a common bus called the Service Access Bus (SAB),
861
32142D–06/2013
ATUC64/128/256L3/4U
which is linked to the JTAG through a bus master module, which also handles synchronization
between the TCK and SAB clocks.
For more information about the SAB and a list of SAB slaves see the Service Access Bus
chapter.
34.4.11.1 SAB Address Mode
The MEMORY_SIZED_ACCESS instruction allows a sized read or write to any 36-bit address
on the bus. MEMORY_WORD_ACCESS is a shorthand instruction for 32-bit accesses to any
36-bit address, while the NEXUS_ACCESS instruction is a Nexus-compliant shorthand instruction
for accessing the 32-bit OCD registers in the 7-bit address space reserved for these. These
instructions require two passes through the Shift-DR TAP state: one for the address and control
information, and one for data.
34.4.11.2 Block Transfer
To increase the transfer rate, consecutive memory accesses can be accomplished by the
MEMORY_BLOCK_ACCESS instruction, which only requires a single pass through Shift-DR for
data transfer only. The address is automatically incremented according to the size of the last
SAB transfer.
34.4.11.3 Canceling a SAB Access
It is possible to abort an ongoing SAB access by the CANCEL_ACCESS instruction, to avoid
hanging the bus due to an extremely slow slave.
34.4.11.4 Busy Reporting
As the time taken to perform an access may vary depending on system activity and current chip
frequency, all the SAB access JTAG instructions can return a busy indicator. This indicates
whether a delay needs to be inserted, or an operation needs to be repeated in order to be successful.
If a new access is requested while the SAB is busy, the request is ignored.
The SAB becomes busy when:
• Entering Update-DR in the address phase of any read operation, e.g., after scanning in a
NEXUS_ACCESS address with the read bit set.
• Entering Update-DR in the data phase of any write operation, e.g., after scanning in data for
a NEXUS_ACCESS write.
• Entering Update-DR during a MEMORY_BLOCK_ACCESS.
• Entering Update-DR after scanning in a counter value for SYNC.
• Entering Update-IR after scanning in a MEMORY_BLOCK_ACCESS if the previous access
was a read and data was scanned after scanning the address.
The SAB becomes ready again when:
• A read or write operation completes.
• A SYNC countdown completed.
• A operation is cancelled by the CANCEL_ACCESS instruction.
What to do if the busy bit is set:
• During Shift-IR: The new instruction is selected, but the previous operation has not yet
completed and will continue (unless the new instruction is CANCEL_ACCESS). You may
862
32142D–06/2013
ATUC64/128/256L3/4U
continue shifting the same instruction until the busy bit clears, or start shifting data. If shifting
data, you must be prepared that the data shift may also report busy.
• During Shift-DR of an address: The new address is ignored. The SAB stays in address mode,
so no data must be shifted. Repeat the address until the busy bit clears.
• During Shift-DR of read data: The read data is invalid. The SAB stays in data mode. Repeat
scanning until the busy bit clears.
• During Shift-DR of write data: The write data is ignored. The SAB stays in data mode. Repeat
scanning until the busy bit clears.
34.4.11.5 Error Reporting
The Service Access Bus may not be able to complete all accesses as requested. This may be
because the address is invalid, the addressed area is read-only or cannot handle byte/halfword
accesses, or because the chip is set in a protected mode where only limited accesses are
allowed.
The error bit is updated when an access completes, and is cleared when a new access starts.
What to do if the error bit is set:
• During Shift-IR: The new instruction is selected. The last operation performed using the old
instruction did not complete successfully.
• During Shift-DR of an address: The previous operation failed. The new address is accepted.
If the read bit is set, a read operation is started.
• During Shift-DR of read data: The read operation failed, and the read data is invalid.
• During Shift-DR of write data: The previous write operation failed. The new data is accepted
and a write operation started. This should only occur during block writes or stream writes. No
error can occur between scanning a write address and the following write data.
• While polling with CANCEL_ACCESS: The previous access was cancelled. It may or may not
have actually completed.
• After power-up: The error bit is set after power up, but there has been no previous SAB
instruction so this error can be discarded.
34.4.11.6 Protected Reporting
A protected status may be reported during Shift-IR or Shift-DR. This indicates that the security
bit in the Flash Controller is set and that the chip is locked for access, according to Section
34.5.1.
The protected state is reported when:
• The Flash Controller is under reset. This can be due to the AVR_RESET command or the
RESET_N line.
• The Flash Controller has not read the security bit from the flash yet (This will take a a few
ms). Happens after the Flash Controller reset has been released.
• The security bit in the Flash Controller is set.
What to do if the protected bit is set:
• Release all active AVR_RESET domains, if any.
• Release the RESET_N line.
• Wait a few ms for the security bit to clear. It can be set temporarily due to a reset.
863
32142D–06/2013
ATUC64/128/256L3/4U
• Perform a CHIP_ERASE to clear the security bit. NOTE: This will erase all the contents of the
non-volatile memory.
34.5 JTAG Instruction Summary
The implemented JTAG instructions in the 32-bit AVR are shown in the table below.
34.5.1 Security Restrictions
When the security fuse in the Flash is programmed, the following JTAG instructions are
restricted:
• NEXUS_ACCESS
• MEMORY_WORD_ACCESS
• MEMORY_BLOCK_ACCESS
• MEMORY_SIZED_ACCESS
For description of what memory locations remain accessible, please refer to the SAB address
map.
Full access to these instructions is re-enabled when the security fuse is erased by the
CHIP_ERASE JTAG instruction.
Table 34-8. JTAG Instruction Summary
Instruction
OPCODE Instruction Description
0x01 IDCODE Select the 32-bit Device Identification register as data register.
0x02 SAMPLE_PRELOAD Take a snapshot of external pin values without affecting system operation.
0x03 EXTEST Select boundary-scan chain as data register for testing circuitry external to
the device.
0x04 INTEST Select boundary-scan chain for internal testing of the device.
0x06 CLAMP Bypass device through Bypass register, while driving outputs from boundaryscan
register.
0x0C AVR_RESET Apply or remove a static reset to the device
0x0F CHIP_ERASE Erase the device
0x10 NEXUS_ACCESS Select the SAB Address and Data registers as data register for the TAP. The
registers are accessed in Nexus mode.
0x11 MEMORY_WORD_ACCESS Select the SAB Address and Data registers as data register for the TAP.
0x12 MEMORY_BLOCK_ACCESS Select the SAB Data register as data register for the TAP. The address is
auto-incremented.
0x13 CANCEL_ACCESS Cancel an ongoing Nexus or Memory access.
0x14 MEMORY_SERVICE Select the SAB Address and Data registers as data register for the TAP. The
registers are accessed in Memory Service mode.
0x15 MEMORY_SIZED_ACCESS Select the SAB Address and Data registers as data register for the TAP.
0x17 SYNC Synchronization counter
0x1C HALT Halt the CPU for safe programming.
0x1F BYPASS Bypass this device through the bypass register.
Others N/A Acts as BYPASS
864
32142D–06/2013
ATUC64/128/256L3/4U
Note that the security bit will read as programmed and block these instructions also if the Flash
Controller is statically reset.
Other security mechanisms can also restrict these functions. If such mechanisms are present
they are listed in the SAB address map section.
34.5.1.1 Notation
Table 34-10 on page 864 shows bit patterns to be shifted in a format like "peb01". Each character
corresponds to one bit, and eight bits are grouped together for readability. The least
significantbit is always shifted first, and the most significant bit shifted last. The symbols used
are shown in Table 34-9.
In many cases, it is not required to shift all bits through the data register. Bit patterns are shown
using the full width of the shift register, but the suggested or required bits are emphasized using
bold text. I.e. given the pattern "aaaaaaar xxxxxxxx xxxxxxxx xxxxxxxx xx", the shift register is
34 bits, but the test or debug unit may choose to shift only 8 bits "aaaaaaar".
The following describes how to interpret the fields in the instruction description tables:
Table 34-9. Symbol Description
Symbol Description
0 Constant low value - always reads as zero.
1 Constant high value - always reads as one.
a An address bit - always scanned with the least significant bit first
b A busy bit. Reads as one if the SAB was busy, or zero if it was not. See Section 34.4.11.4 for
details on how the busy reporting works.
d A data bit - always scanned with the least significant bit first.
e An error bit. Reads as one if an error occurred, or zero if not. See Section 34.4.11.5 for
details on how the error reporting works.
p
The chip protected bit. Some devices may be set in a protected state where access to chip
internals are severely restricted. See the documentation for the specific device for details.
On devices without this possibility, this bit always reads as zero.
r A direction bit. Set to one to request a read, set to zero to request a write.
s A size bit. The size encoding is described where used.
x A don’t care bit. Any value can be shifted in, and output data should be ignored.
Table 34-10. Instruction Description
Instruction Description
IR input value
Shows the bit pattern to shift into IR in the Shift-IR state in order to select this
instruction. The pattern is show both in binary and in hexadecimal form for
convenience.
Example: 10000 (0x10)
IR output value
Shows the bit pattern shifted out of IR in the Shift-IR state when this instruction is
active.
Example: peb01
865
32142D–06/2013
ATUC64/128/256L3/4U
34.5.2 Public JTAG Instructions
The JTAG standard defines a number of public JTAG instructions. These instructions are
described in the sections below.
34.5.2.1 IDCODE
This instruction selects the 32 bit Device Identification register (DID) as Data Register. The DID
register consists of a version number, a device number, and the manufacturer code chosen by
JEDEC. This is the default instruction after a JTAG reset. Details about the DID register can be
found in the module configuration section at the end of this chapter.
Starting in Run-Test/Idle, the Device Identification register is accessed in the following way:
1. Select the IR Scan path.
2. In Capture-IR: The IR output value is latched into the shift register.
3. In Shift-IR: The instruction register is shifted by the TCK input.
4. Return to Run-Test/Idle.
5. Select the DR Scan path.
6. In Capture-DR: The IDCODE value is latched into the shift register.
7. In Shift-DR: The IDCODE scan chain is shifted by the TCK input.
8. Return to Run-Test/Idle.
34.5.2.2 SAMPLE_PRELOAD
This instruction takes a snap-shot of the input/output pins without affecting the system operation,
and pre-loading the scan chain without updating the DR-latch. The boundary-scan chain is
selected as Data Register.
Starting in Run-Test/Idle, the Device Identification register is accessed in the following way:
DR Size Shows the number of bits in the data register chain when this instruction is active.
Example: 34 bits
DR input value
Shows which bit pattern to shift into the data register in the Shift-DR state when this
instruction is active. Multiple such lines may exist, e.g., to distinguish between
reads and writes.
Example: aaaaaaar xxxxxxxx xxxxxxxx xxxxxxxx xx
DR output value
Shows the bit pattern shifted out of the data register in the Shift-DR state when this
instruction is active. Multiple such lines may exist, e.g., to distinguish between
reads and writes.
Example: xx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxeb
Table 34-10. Instruction Description (Continued)
Instruction Description
Table 34-11. IDCODE Details
Instructions Details
IR input value 00001 (0x01)
IR output value p0001
DR Size 32
DR input value xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx
DR output value Device Identification Register
866
32142D–06/2013
ATUC64/128/256L3/4U
1. Select the IR Scan path.
2. In Capture-IR: The IR output value is latched into the shift register.
3. In Shift-IR: The instruction register is shifted by the TCK input.
4. Return to Run-Test/Idle.
5. Select the DR Scan path.
6. In Capture-DR: The Data on the external pins are sampled into the boundary-scan
chain.
7. In Shift-DR: The boundary-scan chain is shifted by the TCK input.
8. Return to Run-Test/Idle.
34.5.2.3 EXTEST
This instruction selects the boundary-scan chain as Data Register for testing circuitry external to
the 32-bit AVR package. The contents of the latched outputs of the boundary-scan chain is
driven out as soon as the JTAG IR-register is loaded with the EXTEST instruction.
Starting in Run-Test/Idle, the EXTEST instruction is accessed the following way:
1. Select the IR Scan path.
2. In Capture-IR: The IR output value is latched into the shift register.
3. In Shift-IR: The instruction register is shifted by the TCK input.
4. In Update-IR: The data from the boundary-scan chain is applied to the output pins.
5. Return to Run-Test/Idle.
6. Select the DR Scan path.
7. In Capture-DR: The data on the external pins is sampled into the boundary-scan chain.
8. In Shift-DR: The boundary-scan chain is shifted by the TCK input.
9. In Update-DR: The data from the scan chain is applied to the output pins.
10. Return to Run-Test/Idle.
Table 34-12. SAMPLE_PRELOAD Details
Instructions Details
IR input value 00010 (0x02)
IR output value p0001
DR Size Depending on boundary-scan chain, see BSDL-file.
DR input value Depending on boundary-scan chain, see BSDL-file.
DR output value Depending on boundary-scan chain, see BSDL-file.
Table 34-13. EXTEST Details
Instructions Details
IR input value 00011 (0x03)
IR output value p0001
DR Size Depending on boundary-scan chain, see BSDL-file.
DR input value Depending on boundary-scan chain, see BSDL-file.
DR output value Depending on boundary-scan chain, see BSDL-file.
867
32142D–06/2013
ATUC64/128/256L3/4U
34.5.2.4 INTEST
This instruction selects the boundary-scan chain as Data Register for testing internal logic in the
device. The logic inputs are determined by the boundary-scan chain, and the logic outputs are
captured by the boundary-scan chain. The device output pins are driven from the boundary-scan
chain.
Starting in Run-Test/Idle, the INTEST instruction is accessed the following way:
1. Select the IR Scan path.
2. In Capture-IR: The IR output value is latched into the shift register.
3. In Shift-IR: The instruction register is shifted by the TCK input.
4. In Update-IR: The data from the boundary-scan chain is applied to the internal logic
inputs.
5. Return to Run-Test/Idle.
6. Select the DR Scan path.
7. In Capture-DR: The data on the internal logic is sampled into the boundary-scan chain.
8. In Shift-DR: The boundary-scan chain is shifted by the TCK input.
9. In Update-DR: The data from the boundary-scan chain is applied to internal logic
inputs.
10. Return to Run-Test/Idle.
34.5.2.5 CLAMP
This instruction selects the Bypass register as Data Register. The device output pins are driven
from the boundary-scan chain.
Starting in Run-Test/Idle, the CLAMP instruction is accessed the following way:
1. Select the IR Scan path.
2. In Capture-IR: The IR output value is latched into the shift register.
3. In Shift-IR: The instruction register is shifted by the TCK input.
4. In Update-IR: The data from the boundary-scan chain is applied to the output pins.
5. Return to Run-Test/Idle.
6. Select the DR Scan path.
7. In Capture-DR: A logic ‘0’ is loaded into the Bypass Register.
8. In Shift-DR: Data is scanned from TDI to TDO through the Bypass register.
Table 34-14. INTEST Details
Instructions Details
IR input value 00100 (0x04)
IR output value p0001
DR Size Depending on boundary-scan chain, see BSDL-file.
DR input value Depending on boundary-scan chain, see BSDL-file.
DR output value Depending on boundary-scan chain, see BSDL-file.
868
32142D–06/2013
ATUC64/128/256L3/4U
9. Return to Run-Test/Idle.
34.5.2.6 BYPASS
This instruction selects the 1-bit Bypass Register as Data Register.
Starting in Run-Test/Idle, the CLAMP instruction is accessed the following way:
1. Select the IR Scan path.
2. In Capture-IR: The IR output value is latched into the shift register.
3. In Shift-IR: The instruction register is shifted by the TCK input.
4. Return to Run-Test/Idle.
5. Select the DR Scan path.
6. In Capture-DR: A logic ‘0’ is loaded into the Bypass Register.
7. In Shift-DR: Data is scanned from TDI to TDO through the Bypass register.
8. Return to Run-Test/Idle.
34.5.3 Private JTAG Instructions
The 32-bit AVR defines a number of private JTAG instructions, not defined by the JTAG standard.
Each instruction is briefly described in text, with details following in table form.
34.5.3.1 NEXUS_ACCESS
This instruction allows Nexus-compliant access to the On-Chip Debug registers through the
SAB. The 7-bit register index, a read/write control bit, and the 32-bit data is accessed through
the JTAG port.
The data register is alternately interpreted by the SAB as an address register and a data register.
The SAB starts in address mode after the NEXUS_ACCESS instruction is selected, and
toggles between address and data mode each time a data scan completes with the busy bit
cleared.
NOTE: The polarity of the direction bit is inverse of the Nexus standard.
Table 34-15. CLAMP Details
Instructions Details
IR input value 00110 (0x06)
IR output value p0001
DR Size 1
DR input value x
DR output value x
Table 34-16. BYPASS Details
Instructions Details
IR input value 11111 (0x1F)
IR output value p0001
DR Size 1
DR input value x
DR output value x
869
32142D–06/2013
ATUC64/128/256L3/4U
Starting in Run-Test/Idle, OCD registers are accessed in the following way:
1. Select the IR Scan path.
2. In Capture-IR: The IR output value is latched into the shift register.
3. In Shift-IR: The instruction register is shifted by the TCK input.
4. Return to Run-Test/Idle.
5. Select the DR Scan path.
6. In Shift-DR: Scan in the direction bit (1=read, 0=write) and the 7-bit address for the
OCD register.
7. Go to Update-DR and re-enter Select-DR Scan.
8. In Shift-DR: For a read operation, scan out the contents of the addressed register. For a
write operation, scan in the new contents of the register.
9. Return to Run-Test/Idle.
For any operation, the full 7 bits of the address must be provided. For write operations, 32 data
bits must be provided, or the result will be undefined. For read operations, shifting may be terminated
once the required number of bits have been acquired.
34.5.3.2 MEMORY_SERVICE
This instruction allows access to registers in an optional Memory Service Unit. The 7-bit register
index, a read/write control bit, and the 32-bit data is accessed through the JTAG port.
The data register is alternately interpreted by the SAB as an address register and a data register.
The SAB starts in address mode after the MEMORY_SERVICE instruction is selected, and
toggles between address and data mode each time a data scan completes with the busy bit
cleared.
Starting in Run-Test/Idle, Memory Service registers are accessed in the following way:
1. Select the IR Scan path.
2. In Capture-IR: The IR output value is latched into the shift register.
3. In Shift-IR: The instruction register is shifted by the TCK input.
4. Return to Run-Test/Idle.
5. Select the DR Scan path.
6. In Shift-DR: Scan in the direction bit (1=read, 0=write) and the 7-bit address for the
Memory Service register.
Table 34-17. NEXUS_ACCESS Details
Instructions Details
IR input value 10000 (0x10)
IR output value peb01
DR Size 34 bits
DR input value (Address phase) aaaaaaar xxxxxxxx xxxxxxxx xxxxxxxx xx
DR input value (Data read phase) xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xx
DR input value (Data write phase) dddddddd dddddddd dddddddd dddddddd xx
DR output value (Address phase) xx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxeb
DR output value (Data read phase) eb dddddddd dddddddd dddddddd dddddddd
DR output value (Data write phase) xx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxeb
870
32142D–06/2013
ATUC64/128/256L3/4U
7. Go to Update-DR and re-enter Select-DR Scan.
8. In Shift-DR: For a read operation, scan out the contents of the addressed register. For a
write operation, scan in the new contents of the register.
9. Return to Run-Test/Idle.
For any operation, the full 7 bits of the address must be provided. For write operations, 32 data
bits must be provided, or the result will be undefined. For read operations, shifting may be terminated
once the required number of bits have been acquired.
34.5.3.3 MEMORY_SIZED_ACCESS
This instruction allows access to the entire Service Access Bus data area. Data is accessed
through a 36-bit byte index, a 2-bit size, a direction bit, and 8, 16, or 32 bits of data. Not all units
mapped on the SAB bus may support all sizes of accesses, e.g., some may only support word
accesses.
The data register is alternately interpreted by the SAB as an address register and a data register.
The SAB starts in address mode after the MEMORY_SIZED_ACCESS instruction is
selected, and toggles between address and data mode each time a data scan completes with
the busy bit cleared.
Table 34-18. MEMORY_SERVICE Details
Instructions Details
IR input value 10100 (0x14)
IR output value peb01
DR Size 34 bits
DR input value (Address phase) aaaaaaar xxxxxxxx xxxxxxxx xxxxxxxx xx
DR input value (Data read phase) xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xx
DR input value (Data write phase) dddddddd dddddddd dddddddd dddddddd xx
DR output value (Address phase) xx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxeb
DR output value (Data read phase) eb dddddddd dddddddd dddddddd dddddddd
DR output value (Data write phase) xx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxeb
871
32142D–06/2013
ATUC64/128/256L3/4U
The size field is encoded as i Table 34-19.
Starting in Run-Test/Idle, SAB data is accessed in the following way:
1. Select the IR Scan path.
2. In Capture-IR: The IR output value is latched into the shift register.
3. In Shift-IR: The instruction register is shifted by the TCK input.
4. Return to Run-Test/Idle.
5. Select the DR Scan path.
6. In Shift-DR: Scan in the direction bit (1=read, 0=write), 2-bit access size, and the 36-bit
address of the data to access.
7. Go to Update-DR and re-enter Select-DR Scan.
8. In Shift-DR: For a read operation, scan out the contents of the addressed area. For a
write operation, scan in the new contents of the area.
9. Return to Run-Test/Idle.
For any operation, the full 36 bits of the address must be provided. For write operations, 32 data
bits must be provided, or the result will be undefined. For read operations, shifting may be terminated
once the required number of bits have been acquired.
Table 34-19. Size Field Semantics
Size field value Access size Data alignment
00 Byte (8 bits)
Address modulo 4 : data alignment
0: dddddddd xxxxxxxx xxxxxxxx xxxxxxxx
1: xxxxxxxx dddddddd xxxxxxxx xxxxxxxx
2: xxxxxxxx xxxxxxxx dddddddd xxxxxxxx
3: xxxxxxxx xxxxxxxx xxxxxxxx dddddddd
01 Halfword (16 bits)
Address modulo 4 : data alignment
0: dddddddd dddddddd xxxxxxxx xxxxxxxx
1: Not allowed
2: xxxxxxxx xxxxxxxx dddddddd dddddddd
3: Not allowed
10 Word (32 bits)
Address modulo 4 : data alignment
0: dddddddd dddddddd dddddddd dddddddd
1: Not allowed
2: Not allowed
3: Not allowed
11 Reserved N/A
Table 34-20. MEMORY_SIZED_ACCESS Details
Instructions Details
IR input value 10101 (0x15)
IR output value peb01
DR Size 39 bits
DR input value (Address phase) aaaaaaaa aaaaaaaa aaaaaaaa aaaaaaaa aaaassr
DR input value (Data read phase) xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxx
DR input value (Data write phase) dddddddd dddddddd dddddddd dddddddd xxxxxxx
872
32142D–06/2013
ATUC64/128/256L3/4U
34.5.3.4 MEMORY_WORD_ACCESS
This instruction allows access to the entire Service Access Bus data area. Data is accessed
through the 34 MSB of the SAB address, a direction bit, and 32 bits of data. This instruction is
identical to MEMORY_SIZED_ACCESS except that it always does word sized accesses. The
size field is implied, and the two lowest address bits are removed and not scanned in.
Note: This instruction was previously known as MEMORY_ACCESS, and is provided for backwards
compatibility.
The data register is alternately interpreted by the SAB as an address register and a data register.
The SAB starts in address mode after the MEMORY_WORD_ACCESS instruction is
selected, and toggles between address and data mode each time a data scan completes with
the busy bit cleared.
Starting in Run-Test/Idle, SAB data is accessed in the following way:
1. Select the IR Scan path.
2. In Capture-IR: The IR output value is latched into the shift register.
3. In Shift-IR: The instruction register is shifted by the TCK input.
4. Return to Run-Test/Idle.
5. Select the DR Scan path.
6. In Shift-DR: Scan in the direction bit (1=read, 0=write) and the 34-bit address of the
data to access.
7. Go to Update-DR and re-enter Select-DR Scan.
8. In Shift-DR: For a read operation, scan out the contents of the addressed area. For a
write operation, scan in the new contents of the area.
9. Return to Run-Test/Idle.
For any operation, the full 34 bits of the address must be provided. For write operations, 32 data
bits must be provided, or the result will be undefined. For read operations, shifting may be terminated
once the required number of bits have been acquired.
DR output value (Address phase) xxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxeb
DR output value (Data read phase) xxxxxeb dddddddd dddddddd dddddddd dddddddd
DR output value (Data write phase) xxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxeb
Table 34-20. MEMORY_SIZED_ACCESS Details (Continued)
Instructions Details
Table 34-21. MEMORY_WORD_ACCESS Details
Instructions Details
IR input value 10001 (0x11)
IR output value peb01
DR Size 35 bits
DR input value (Address phase) aaaaaaaa aaaaaaaa aaaaaaaa aaaaaaaa aar
DR input value (Data read phase) xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxx
DR input value (Data write phase) dddddddd dddddddd dddddddd dddddddd xxx
873
32142D–06/2013
ATUC64/128/256L3/4U
34.5.3.5 MEMORY_BLOCK_ACCESS
This instruction allows access to the entire SAB data area. Up to 32 bits of data is accessed at a
time, while the address is sequentially incremented from the previously used address.
In this mode, the SAB address, size, and access direction is not provided with each access.
Instead, the previous address is auto-incremented depending on the specified size and the previous
operation repeated. The address must be set up in advance with
MEMORY_SIZE_ACCESS or MEMORY_WORD_ACCESS. It is allowed, but not required, to
shift data after shifting the address.
This instruction is primarily intended to speed up large quantities of sequential word accesses. It
is possible to use it also for byte and halfword accesses, but the overhead in this is case much
larger as 32 bits must still be shifted for each access.
The following sequence should be used:
1. Use the MEMORY_SIZE_ACCESS or MEMORY_WORD_ACCESS to read or write the
first location.
2. Return to Run-Test/Idle.
3. Select the IR Scan path.
4. In Capture-IR: The IR output value is latched into the shift register.
5. In Shift-IR: The instruction register is shifted by the TCK input.
6. Return to Run-Test/Idle.
7. Select the DR Scan path. The address will now have incremented by 1, 2, or 4 (corresponding
to the next byte, halfword, or word location).
8. In Shift-DR: For a read operation, scan out the contents of the next addressed location.
For a write operation, scan in the new contents of the next addressed location.
9. Go to Update-DR.
10. If the block access is not complete, return to Select-DR Scan and repeat the access.
11. If the block access is complete, return to Run-Test/Idle.
For write operations, 32 data bits must be provided, or the result will be undefined. For read
operations, shifting may be terminated once the required number of bits have been acquired.
DR output value (Address phase) xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xeb
DR output value (Data read phase) xeb dddddddd dddddddd dddddddd dddddddd
DR output value (Data write phase) xxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxeb
Table 34-21. MEMORY_WORD_ACCESS Details (Continued)
Instructions Details
Table 34-22. MEMORY_BLOCK_ACCESS Details
Instructions Details
IR input value 10010 (0x12)
IR output value peb01
DR Size 34 bits
DR input value (Data read phase) xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xx
874
32142D–06/2013
ATUC64/128/256L3/4U
The overhead using block word access is 4 cycles per 32 bits of data, resulting in an 88% transfer
efficiency, or 2.1 MBytes per second with a 20 MHz TCK frequency.
34.5.3.6 CANCEL_ACCESS
If a very slow memory location is accessed during a SAB memory access, it could take a very
long time until the busy bit is cleared, and the SAB becomes ready for the next operation. The
CANCEL_ACCESS instruction provides a possibility to abort an ongoing transfer and report a
timeout to the JTAG master.
When the CANCEL_ACCESS instruction is selected, the current access will be terminated as
soon as possible. There are no guarantees about how long this will take, as the hardware may
not always be able to cancel the access immediately. The SAB is ready to respond to a new
command when the busy bit clears.
Starting in Run-Test/Idle, CANCEL_ACCESS is accessed in the following way:
1. Select the IR Scan path.
2. In Capture-IR: The IR output value is latched into the shift register.
3. In Shift-IR: The instruction register is shifted by the TCK input.
4. Return to Run-Test/Idle.
34.5.3.7 SYNC
This instruction allows external debuggers and testers to measure the ratio between the external
JTAG clock and the internal system clock. The SYNC data register is a 16-bit counter that
counts down to zero using the internal system clock. The busy bit stays high until the counter
reaches zero.
Starting in Run-Test/Idle, SYNC instruction is used in the following way:
1. Select the IR Scan path.
2. In Capture-IR: The IR output value is latched into the shift register.
3. In Shift-IR: The instruction register is shifted by the TCK input.
4. Return to Run-Test/Idle.
5. Select the DR Scan path.
DR input value (Data write phase) dddddddd dddddddd dddddddd dddddddd xx
DR output value (Data read phase) eb dddddddd dddddddd dddddddd dddddddd
DR output value (Data write phase) xx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxeb
Table 34-22. MEMORY_BLOCK_ACCESS Details (Continued)
Instructions Details
Table 34-23. CANCEL_ACCESS Details
Instructions Details
IR input value 10011 (0x13)
IR output value peb01
DR Size 1
DR input value x
DR output value 0
875
32142D–06/2013
ATUC64/128/256L3/4U
6. Scan in an 16-bit counter value.
7. Go to Update-DR and re-enter Select-DR Scan.
8. In Shift-DR: Scan out the busy bit, and until the busy bit clears goto 7.
9. Calculate an approximation to the internal clock speed using the elapsed time and the
counter value.
10. Return to Run-Test/Idle.
The full 16-bit counter value must be provided when starting the synch operation, or the result
will be undefined. When reading status, shifting may be terminated once the required number of
bits have been acquired.
34.5.3.8 AVR_RESET
This instruction allows a debugger or tester to directly control separate reset domains inside the
chip. The shift register contains one bit for each controllable reset domain. Setting a bit to one
resets that domain and holds it in reset. Setting a bit to zero releases the reset for that domain.
The AVR_RESET instruction can be used in the following way:
1. Select the IR Scan path.
2. In Capture-IR: The IR output value is latched into the shift register.
3. In Shift-IR: The instruction register is shifted by the TCK input.
4. Return to Run-Test/Idle.
5. Select the DR Scan path.
6. In Shift-DR: Scan in the value corresponding to the reset domains the JTAG master
wants to reset into the data register.
7. Return to Run-Test/Idle.
8. Stay in run test idle for at least 10 TCK clock cycles to let the reset propagate to the
system.
See the device specific documentation for the number of reset domains, and what these
domains are.
For any operation, all bits must be provided or the result will be undefined.
Table 34-24. SYNC_ACCESS Details
Instructions Details
IR input value 10111 (0x17)
IR output value peb01
DR Size 16 bits
DR input value dddddddd dddddddd
DR output value xxxxxxxx xxxxxxeb
Table 34-25. AVR_RESET Details
Instructions Details
IR input value 01100 (0x0C)
IR output value p0001
876
32142D–06/2013
ATUC64/128/256L3/4U
34.5.3.9 CHIP_ERASE
This instruction allows a programmer to completely erase all nonvolatile memories in a chip.
This will also clear any security bits that are set, so the device can be accessed normally. In
devices without non-volatile memories this instruction does nothing, and appears to complete
immediately.
The erasing of non-volatile memories starts as soon as the CHIP_ERASE instruction is selected.
The CHIP_ERASE instruction selects a 1 bit bypass data register.
A chip erase operation should be performed as:
1. Reset the system and stop the CPU from executing.
2. Select the IR Scan path.
3. In Capture-IR: The IR output value is latched into the shift register.
4. In Shift-IR: The instruction register is shifted by the TCK input.
5. Check the busy bit that was scanned out during Shift-IR. If the busy bit was set goto 2.
6. Return to Run-Test/Idle.
34.5.3.10 HALT
This instruction allows a programmer to easily stop the CPU to ensure that it does not execute
invalid code during programming.
This instruction selects a 1-bit halt register. Setting this bit to one halts the CPU. Setting this bit
to zero releases the CPU to run normally. The value shifted out from the data register is one if
the CPU is halted. Before releasing the halt command the CPU needs to be reset to ensure that
it will start at the reset startup address.
The HALT instruction can be used in the following way:
1. Select the IR Scan path.
2. In Capture-IR: The IR output value is latched into the shift register.
3. In Shift-IR: The instruction register is shifted by the TCK input.
4. Return to Run-Test/Idle.
5. Select the DR Scan path.
DR Size Device specific.
DR input value Device specific.
DR output value Device specific.
Table 34-25. AVR_RESET Details (Continued)
Instructions Details
Table 34-26. CHIP_ERASE Details
Instructions Details
IR input value 01111 (0x0F)
IR output value p0b01
Where b is the busy bit.
DR Size 1 bit
DR input value x
DR output value 0
877
32142D–06/2013
ATUC64/128/256L3/4U
6. In Shift-DR: Scan in the value 1 to halt the CPU, 0 to start CPU execution.
7. Return to Run-Test/Idle.
Table 34-27. HALT Details
Instructions Details
IR input value 11100 (0x1C)
IR output value p0001
DR Size 1 bit
DR input value d
DR output value d
878
32142D–06/2013
ATUC64/128/256L3/4U
34.5.4 JTAG Data Registers
The following device specific registers can be selected as JTAG scan chain depending on the
instruction loaded in the JTAG Instruction Register. Additional registers exist, but are implicitly
described in the functional description of the relevant instructions.
34.5.4.1 Device Identification Register
The Device Identification Register contains a unique identifier for each product. The register is
selected by the IDCODE instruction, which is the default instruction after a JTAG reset.
Device specific ID codes
The different device configurations have different JTAG ID codes, as shown in Table 34-28.
Note that if the flash controller is statically reset, the ID code will be undefined.
34.5.4.2 Reset Register
The reset register is selected by the AVR_RESET instruction and contains one bit for each reset
domain in the device. Setting each bit to one will keep that domain reset until the bit is cleared.
MSB LSB
Bit 31 28 27 12 11 1 0
Device ID Revision Part Number Manufacturer ID 1
4 bits 16 bits 11 bits 1 bit
Revision This is a 4 bit number identifying the revision of the component.
Rev A = 0x0, B = 0x1, etc.
Part Number The part number is a 16 bit code identifying the component.
Manufacturer ID The Manufacturer ID is a 11 bit code identifying the manufacturer.
The JTAG manufacturer ID for ATMEL is 0x01F.
Table 34-28. Device and JTAG ID
Device Name JTAG ID Code (R is the revision number)
ATUC256L3U 0xr21C303F
ATUC128L3U 0xr21C403F
ATUC64L3U 0xr21C503F
ATUC256L4U 0xr21C603F
ATUC128L4U 0xr21C703F
ATUC64L4U 0xr21C803F
Bit 0
Reset
domain System
879
32142D–06/2013
ATUC64/128/256L3/4U
34.5.4.3 Boundary--scan Chain
The boundary-scan chain has the capability of driving and observing the logic levels on the digital
I/O pins, as well as driving and observing the logic levels between the digital I/O pins and the
internal logic. Typically, output value, output enable, and input data are all available in the
boundary-scan chain.
The boundary-scan chain is described in the BSDL (Boundary Scan Description Language) file
available at the Atmel web site.
System Resets the whole chip, except the JTAG itself.
880
32142D–06/2013
ATUC64/128/256L3/4U
34.6 aWire Debug Interface (AW)
Rev.: 2.3.0.1
34.6.1 Features
• Single pin debug system.
• Half Duplex asynchronous communication (UART compatible).
• Full duplex mode for direct UART connection.
• Compatible with JTAG functionality, except boundary scan.
• Failsafe packet-oriented protocol.
• Read and write on-chip memory and program on-chip flash and fuses through SAB interface.
• On-Chip Debug access through SAB interface.
• Asynchronous receiver or transmitter when the aWire system is not used for debugging.
34.6.2 Overview
The aWire Debug Interface (AW) offers a single pin debug solution that is fully compatible with
the functionality offered by the JTAG interface, except boundary scan. This functionality includes
memory access, programming capabilities, and On-Chip Debug access.
Figure 34-8 on page 881 shows how the AW is connected in a 32-bit AVR device. The
RESET_N pin is used both as reset and debug pin. A special sequence on RESET_N is needed
to block the normal reset functionality and enable the AW.
The Service Access Bus (SAB) interface contains address and data registers for the Service
Access Bus, which gives access to On-Chip Debug, programming, and other functions in the
device. The SAB offers several modes of access to the address and data registers, as discussed
in Section 34.6.6.8.
Section 34.6.7 lists the supported aWire commands and responses, with references to the
description in this document.
If the AW is not used for debugging, the aWire UART can be used by the user to send or receive
data with one stop bit, eight data bits, no parity bits, and one stop bit. This can be controlled
through the aWire user interface.
881
32142D–06/2013
ATUC64/128/256L3/4U
34.6.3 Block Diagram
Figure 34-8. aWire Debug Interface Block Diagram
34.6.4 I/O Lines Description
34.6.5 Product Dependencies
In order to use this module, other parts of the system must be configured correctly, as described
below.
Table 34-29. I/O Lines Description
Name Description Type
DATA aWire data multiplexed with the RESET_N pin. Input/Output
DATAOUT aWire data output in 2-pin mode. Output
UART
Reset
filter
External reset
AW_ENABLE
RESET_N
Baudrate Detector
RW SZ ADDR DATA
CRC
AW CONTROL
AW User Interface
SAB interface
RESET command
Power
Manager
HALT command CPU
Flash
Controller CHIP_ERASE command
aWire Debug Interface
PB
SAB
882
32142D–06/2013
ATUC64/128/256L3/4U
34.6.5.1 I/O Lines
The pin used by AW is multiplexed with the RESET_N pin. The reset functionality is the default
function of this pin. To enable the aWire functionality on the RESET_N pin the user must enable
the AW either by sending the enable sequence over the RESET_N pin from an external aWire
master or by enabling the aWire user interface.
In 2-pin mode data is received on the RESET_N line, but transmitted on the DATAOUT line.
After sending the 2_PIN_MODE command the DATAOUT line is automatically enabled. All other
peripheral functions on this pin is disabled.
34.6.5.2 Power Management
When debugging through AW the system clocks are automatically turned on to allow debugging
in sleep modes.
34.6.5.3 Clocks
The aWire UART uses the internal 120 MHz RC oscillator (RC120M) as clock source for its
operation. When enabling the AW the RC120M is automatically started.
34.6.5.4 External Components
The AW needs an external pullup on the RESET_N pin to ensure that the pin is pulled up when
the bus is not driven.
34.6.6 Functional Description
34.6.6.1 aWire Communication Protocol
The AW is accessed through the RESET_N pin shown in Table 34-29 on page 881. The AW
communicates through a UART operating at variable baud rate (depending on a sync pattern)
with one start bit, 8 data bits (LSB first), one stop bit, and no parity bits. The aWire protocol is
based upon command packets from an externalmaster and response packets from the slave
(AW). The master always initiates communication and decides the baud rate.
The packet contains a sync byte (0x55), a command/response byte, two length bytes (optional),
a number of data bytes as defined in the length field (optional), and two CRC bytes. If the command/response
has the most significant bit set, the command/response also carries the optional
length and data fields. The CRC field is not checked if the CRC value transmitted is 0x0000.
Table 34-30. aWire Packet Format
Field Number of bytes Description Comment Optional
SYNC 1 Sync pattern (0x55). Used by the receiver to set the baud rate
clock. No
COMMAND/
RESPONSE 1 Command from the master or
response from the slave.
When the most significant bit is set the
command/response has a length field. A
response has the next most significant bit
set. A command does not have this bit set.
No
883
32142D–06/2013
ATUC64/128/256L3/4U
CRC calculation
The CRC is calculated from the command/response, length, and data fields. The polynomial
used is the FCS16 (or CRC-16-CCIT) in reverse mode (0x8408) and the starting value is
0x0000.
Example command
Below is an example command from the master with additional data.
Figure 34-9. Example Command
Example response
Below is an example response from the slave with additional data.
Figure 34-10. Example Response
LENGTH 2 The number of bytes in the DATA
field. Yes
DATA LENGTH Data according to command/
response.
Yes
CRC 2 CRC calculated with the FCS16
polynomial.
CRC value of 0x0000 makes the aWire
disregard the CRC if the master does not
support it.
No
Table 34-30. aWire Packet Format
Field Number of bytes Description Comment Optional
baud_rate_clk
data_pin ...
field sync(0x55) command(0x81) length(MSB) length(lsb)
...
data(MSB) data(LSB) CRC(MSB) CRC(lsb)
baud_rate_clk
data_pin ...
field sync(0x55) response(0xC1) length(MSB) length(lsb)
...
data(MSB) data(LSB) CRC(MSB) CRC(lsb)
884
32142D–06/2013
ATUC64/128/256L3/4U
Avoiding drive contention when changing direction
The aWire debug protocol uses one dataline in both directions. To avoid both the master and the
slave to drive this line when changing direction the AW has a built in guard time before it starts to
drive the line. At reset this guard time is set to maximum (128 bit cycles), but can be lowered by
the master upon command.
The AW will release the line immediately after the stop character has been transmitted.
During the direction change there can be a period when the line is not driven. An external pullup
has to be added to RESET_N to keep the signal stable when neither master or slave is actively
driving the line.
34.6.6.2 The RESET_N pin
Normal reset functionality on the RESET_N pin is disabled when using aWire. However, the
user can reset the system through the RESET aWire command. During aWire operation the
RESET_N pin should not be connected to an external reset circuitry, but disconnected via a
switch or a jumper to avoid drive contention and speed problems.
Figure 34-11. Reset Circuitry and aWire.
34.6.6.3 Initializing the AW
To enable AW, the user has to send a 0x55 pattern with a baudrate of 1 kHz on the RESET_N
pin. The AW is enabled after transmitting this pattern and the user can start transmitting commands.
This pattern is not the sync pattern for the first command.
After enabling the aWire debug interface the halt bit is set automatically to prevent the system
from running code after the interface is enabled. To make the CPU run again set halt to zero
using the HALT command.
34.6.6.4 Disabling the AW
To disable AW, the user can keep the RESET_N pin low for 100 ms. This will disable the AW,
return RESET_N to its normal function, and reset the device.
An aWire master can also disable aWire by sending the DISABLE command. After acking the
command the AW will be disabled and RESET_N returns to its normal function.
RESET_N
AW Debug
Interface
Jumper
MCU
Power Manager
aWire master connector
Board Reset
Circuitry
885
32142D–06/2013
ATUC64/128/256L3/4U
34.6.6.5 Resetting the AW
The aWire master can reset the AW slave by pulling the RESET_N pin low for 20 ms. This is
equivalent to disabling and then enabling AW.
34.6.6.6 2-pin Mode
To avoid using special hardware when using a normal UART device as aWire master, the aWire
slave has a 2-pin mode where one pin is used as input and on pin is used as output. To enable
this mode the 2_PIN_MODE command must be sent. After sending the command, all responses
will be sent on the DATAOUT pin instead of the RESET_N pin. Commands are still received on
the RESET_N pin.
34.6.6.7 Baud Rate Clock
The communication speed is set by the master in the sync field of the command. The AW will
use this to resynchronize its baud rate clock and reply on this frequency. The minimum frequency
of the communication is 1 kHz. The maximum frequency depends on the internal clock
source for the AW (RC120M). The baud rate clock is generated by AW with the following
formula:
Where is the baud rate frequency and is the frequency of the internal RC120M. TUNE is
the value returned by the BAUD_RATE response.
To find the max frequency the user can issue the TUNE command to the AW to make it return
the TUNE value. This value can be used to compute the . The maximum operational frequency
( ) is then:
34.6.6.8 Service Access Bus
The AVR32 architecture offers a common interface for access to On-Chip Debug, programming,
and test functions. These are mapped on a common bus called the Service Access Bus (SAB),
which is linked to the aWire through a bus master module, which also handles synchronization
between the aWire and SAB clocks.
For more information about the SAB and a list of SAB slaves see the Service Access Bus
chapter.
SAB Clock
When accessing the SAB through the aWire there are no limitations on baud rate frequency
compared to chip frequency, although there must be an active system clock in order for the SAB
accesses to complete. If the system clock (CLK_SYS) is switched off in sleep mode, activity on
the aWire pin will restart the CLK_SYS automatically, without waking the device from sleep.
aWire masters may optimize the transfer rate by adjusting the baud rate frequency in relation to
the CLK_SYS. This ratio can be measured with the MEMORY_SPEED_REQUEST command.
When issuing the MEMORY_SPEED_REQUEST command a counter value CV is returned. CV
can be used to calculate the SAB speed ( ) using this formula:
f
aw
TUNE f br
8 = ----------------------------
f
br f
aw
f
aw
f
brmax
f
brmax
f
aw
4 = -------
f
sab
886
32142D–06/2013
ATUC64/128/256L3/4U
SAB Address Mode
The Service Access Bus uses 36 address bits to address memory or registers in any of the
slaves on the bus. The bus supports sized accesses of bytes (8 bits), halfwords (16 bits), or
words (32 bits). All accesses must be aligned to the size of the access, i.e. halfword accesses
must have the lowest address bit cleared, and word accesses must have the two lowest address
bits cleared.
Two instructions exist to access the SAB: MEMORY_WRITE and MEMORY_READ. These two
instructions write and read words, halfwords, and bytes from the SAB.
Busy Reporting
If the aWire master, during a MEMORY_WRITE or a MEMORY_READ command, transmit
another byte when the aWire is still busy sending the previous byte to the SAB, the AW will
respond with a MEMORY_READ_WRITE_STATUS error. See chapter Section 34.6.8.5 for
more details.
The aWire master should adjust its baudrate or delay between bytes when doing SAB accesses
to ensure that the SAB is not overwhelmed with data.
Error Reporting
If a write is performed on a non-existing memory location the SAB interface will respond with an
error. If this happens, all further writes in this command will not be performed and the error and
number of bytes written is reported in the MEMORY_READWRITE_STATUS message from the
AW after the write.
If a read is performed on a non-existing memory location, the SAB interface will respond with an
error. If this happens, the data bytes read after this event are not valid. The AW will include three
extra bytes at the end of the transfer to indicate if the transfer was successful, or in the case of
an error, how many valid bytes were received.
34.6.6.9 CRC Errors/NACK Response
The AW will calculate a CRC value when receiving the command, length, and data fields of the
command packets. If this value differs from the value from the CRC field of the packet, the AW
will reply with a NACK response. Otherwise the command is carried out normally.
An unknown command will be replied with a NACK response.
In worst case a transmission error can happen in the length or command field of the packet. This
can lead to the aWire slave trying to receive a command with or without length (opposite of what
the master intended) or receive an incorrect number of bytes. The aWire slave will then either
wait for more data when the master has finished or already have transmitted the NACK
response in congestion with the master. The master can implement a timeout on every command
and reset the slave if no response is returned after the timeout period has ended.
f
sab
3f
aw
CV – 3 = ----------------
887
32142D–06/2013
ATUC64/128/256L3/4U
34.6.7 aWire Command Summary
The implemented aWire commands are shown in the table below. The responses from the AW
are listed in Section 34.6.8.
All aWire commands are described below, with a summary in table form.
34.6.7.1 AYA
This command asks the AW: “Are you alive”, where the AW should respond with an
acknowledge.
Table 34-31. aWire Command Summary
COMMAND Instruction Description
0x01 AYA “Are you alive”.
0x02 JTAG_ID Asks AW to return the JTAG IDCODE.
0x03 STATUS_REQUEST Request a status message from the AW.
0x04 TUNE Tell the AW to report the current baud rate.
0x05 MEMORY_SPEED_REQUEST Reports the speed difference between the aWire control and the SAB clock
domains.
0x06 CHIP_ERASE Erases the flash and all volatile memories.
0x07 DISABLE Disables the AW.
0x08 2_PIN_MODE Enables the DATAOUT pin and puts the aWire in 2-pin mode, where all
responses are sent on the DATAOUT pin.
0x80 MEMORY_WRITE Writes words, halfwords, or bytes to the SAB.
0x81 MEMORY_READ Reads words, halfwords, or bytes from the SAB.
0x82 HALT Issues a halt command to the device.
0x83 RESET Issues a reset to the Reset Controller.
0x84 SET_GUARD_TIME Sets the guard time for the AW.
Table 34-32. Command/Response Description Notation
Command/Response Description
Command/Response value Shows the command/response value to put into the command/response field of the packet.
Additional data Shows the format of the optional data field if applicable.
Possible responses Shows the possible responses for this command.
Table 34-33. AYA Details
Command Details
Command value 0x01
Additional data N/A
Possible responses 0x40: ACK (Section 34.6.8.1)
0x41: NACK (Section 34.6.8.2)
888
32142D–06/2013
ATUC64/128/256L3/4U
34.6.7.2 JTAG_ID
This command instructs the AW to output the JTAG idcode in the following response.
34.6.7.3 STATUS_REQUEST
Asks the AW for a status message.
34.6.7.4 TUNE
Asks the AW for the current baud rate counter value.
34.6.7.5 MEMORY_SPEED_REQUEST
Asks the AW for the relative speed between the aWire clock (RC120M) and the SAB interface.
34.6.7.6 CHIP_ERASE
This instruction allows a programmer to completely erase all nonvolatile memories in the chip.
This will also clear any security bits that are set, so the device can be accessed normally. The
command is acked immediately, but the status of the command can be monitored by checking
Table 34-34. JTAG_ID Details
Command Details
Command value 0x02
Additional data N/A
Possible responses 0xC0: IDCODE (Section 34.6.8.3)
0x41: NACK (Section 34.6.8.2)
Table 34-35. STATUS_REQUEST Details
Command Details
Command value 0x03
Additional data N/A
Possible responses 0xC4: STATUS_INFO (Section 34.6.8.7)
0x41: NACK (Section 34.6.8.2)
Table 34-36. TUNE Details
Command Details
Command value 0x04
Additional data N/A
Possible responses 0xC3: BAUD_RATE (Section 34.6.8.6)
0x41: NACK (Section 34.6.8.2)
Table 34-37. MEMORY_SPEED_REQUEST Details
Command Details
Command value 0x05
Additional data N/A
Possible responses 0xC5: MEMORY_SPEED (Section 34.6.8.8)
0x41: NACK (Section 34.6.8.2)
889
32142D–06/2013
ATUC64/128/256L3/4U
the Chip Erase ongoing bit in the status bytes received after the STATUS_REQUEST
command.
34.6.7.7 DISABLE
Disables the AW. The AW will respond with an ACK response and then disable itself.
34.6.7.8 2_PIN_MODE
Enables the DATAOUT pin as an output pin. All responses sent from the aWire slave will be sent
on this pin, instead of the RESET_N pin, starting with the ACK for the 2_PIN_MODE command.
34.6.7.9 MEMORY_WRITE
This command enables programming of memory/writing to registers on the SAB. The
MEMORY_WRITE command allows words, halfwords, and bytes to be programmed to a continuous
sequence of addresses in one operation. Before transferring the data, the user must
supply:
1. The number of data bytes to write + 5 (size and starting address) in the length field.
2. The size of the transfer: words, halfwords, or bytes.
3. The starting address of the transfer.
Table 34-38. CHIP_ERASE Details
Command Details
Command value 0x06
Additional data N/A
Possible responses 0x40: ACK (Section 34.6.8.1)
0x41: NACK (Section 34.6.8.2)
Table 34-39. DISABLE Details
Command Details
Command value 0x07
Additional data N/A
Possible responses 0x40: ACK (Section 34.6.8.1)
0x41: NACK (Section 34.6.8.2)
Table 34-40. DISABLE Details
Command Details
Command value 0x07
Additional data N/A
Possible responses 0x40: ACK (Section 34.6.8.1)
0x41: NACK (Section 34.6.8.2)
890
32142D–06/2013
ATUC64/128/256L3/4U
The 4 MSB of the 36 bit SAB address are submitted together with the size field (2 bits). Then follows
the 4 remaining address bytes and finally the data bytes. The size of the transfer is
specified using the values from the following table:
Below is an example write command:
1. 0x55 (sync)
2. 0x80 (command)
3. 0x00 (length MSB)
4. 0x09 (length LSB)
5. 0x25 (size and address MSB, the two MSB of this byte are unused and set to zero)
6. 0x00
7. 0x00
8. 0x00
9. 0x04 (address LSB)
10. 0xCA
11. 0xFE
12. 0xBA
13. 0xBE
14. 0xXX (CRC MSB)
15. 0xXX (CRC LSB)
The length field is set to 0x0009 because there are 9 bytes of additional data: 5 address and size
bytes and 4 bytes of data. The address and size field indicates that words should be written to
address 0x500000004. The data written to 0x500000004 is 0xCAFEBABE.
34.6.7.10 MEMORY_READ
This command enables reading of memory/registers on the Service Access Bus (SAB). The
MEMORY_READ command allows words, halfwords, and bytes to be read from a continuous
sequence of addresses in one operation. The user must supply:
Table 34-41. Size Field Decoding
Size field Description
00 Byte transfer
01 Halfword transfer
10 Word transfer
11 Reserved
Table 34-42. MEMORY_WRITE Details
Command Details
Command value 0x80
Additional data Size, Address and Data
Possible responses 0xC2: MEMORY_READWRITE_STATUS (Section 34.6.8.5)
0x41: NACK (Section 34.6.8.2)
891
32142D–06/2013
ATUC64/128/256L3/4U
1. The size of the data field: 7 (size and starting address + read length indicator) in the
length field.
2. The size of the transfer: Words, halfwords, or bytes.
3. The starting address of the transfer.
4. The number of bytes to read (max 65532).
The 4 MSB of the 36 bit SAB address are submitted together with the size field (2 bits). The 4
remaining address bytes are submitted before the number of bytes to read. The size of the
transfer is specified using the values from the following table:
Below is an example read command:
1. 0x55 (sync)
2. 0x81 (command)
3. 0x00 (length MSB)
4. 0x07 (length LSB)
5. 0x25 (size and address MSB, the two MSB of this byte are unused and set to zero)
6. 0x00
7. 0x00
8. 0x00
9. 0x04 (address LSB)
10. 0x00
11. 0x04
12. 0xXX (CRC MSB)
13. 0xXX (CRC LSB)
The length field is set to 0x0007 because there are 7 bytes of additional data: 5 bytes of address
and size and 2 bytes with the number of bytes to read. The address and size field indicates one
word (four bytes) should be read from address 0x500000004.
Table 34-43. Size Field Decoding
Size field Description
00 Byte transfer
01 Halfword transfer
10 Word transfer
11 Reserved
Table 34-44. MEMORY_READ Details
Command Details
Command value 0x81
Additional data Size, Address and Length
Possible responses
0xC1: MEMDATA (Section 34.6.8.4)
0xC2: MEMORY_READWRITE_STATUS (Section 34.6.8.5)
0x41: NACK (Section 34.6.8.2)
892
32142D–06/2013
ATUC64/128/256L3/4U
34.6.7.11 HALT
This command tells the CPU to halt code execution for safe programming. If the CPU is not
halted during programming it can start executing partially loaded programs. To halt the processor,
the aWire master should send 0x01 in the data field of the command. After programming the
halting can be released by sending 0x00 in the data field of the command.
34.6.7.12 RESET
This command resets different domains in the part. The aWire master sends a byte with the
reset value. Each bit in the reset value byte corresponds to a reset domain in the chip. If a bit is
set the reset is activated and if a bit is not set the reset is released. The number of reset domains
and their destinations are identical to the resets described in the JTAG data registers chapter
under reset register.
34.6.7.13 SET_GUARD_TIME
Sets the guard time value in the AW, i.e. how long the AW will wait before starting its transfer
after the master has finished.
The guard time can be either 0x00 (128 bit lengths), 0x01 (16 bit lengths), 0x2 (4 bit lengths) or
0x3 (1 bit length).
Table 34-45. HALT Details
Command Details
Command value 0x82
Additional data 0x01 to halt the CPU 0x00 to release the halt and reset the
device.
Possible responses 0x40: ACK (Section 34.6.8.1)
0x41: NACK (Section 34.6.8.2)
Table 34-46. RESET Details
Command Details
Command value 0x83
Additional data Reset value for each reset domain. The number of reset
domains is part specific.
Possible responses 0x40: ACK (Section 34.6.8.1)
0x41: NACK (Section 34.6.8.2)
Table 34-47. SET_GUARD_TIME Details
Command Details
Command value 0x84
Additional data Guard time
Possible responses 0x40: ACK (Section 34.6.8.1)
0x41: NACK (Section 34.6.8.2)
893
32142D–06/2013
ATUC64/128/256L3/4U
34.6.8 aWire Response Summary
The implemented aWire responses are shown in the table below.
34.6.8.1 ACK
The AW has received the command successfully and performed the operation.
34.6.8.2 NACK
The AW has received the command, but got a CRC mismatch.
34.6.8.3 IDCODE
The JTAG idcode for this device.
34.6.8.4 MEMDATA
The data read from the address specified by the MEMORY_READ command. The last 3 bytes
are status bytes from the read. The first status byte is the status of the command described in
the table below. The last 2 bytes are the number of remaining data bytes to be sent in the data
field of the packet when the error occurred. If the read was not successful all data bytes after the
failure are undefined. A successful word read (4 bytes) will look like this:
Table 34-48. aWire Response Summary
RESPONSE Instruction Description
0x40 ACK Acknowledge.
0x41 NACK Not acknowledge. Sent after CRC errors and after unknown commands.
0xC0 IDCODE The JTAG idcode.
0xC1 MEMDATA Values read from memory.
0xC2 MEMORY_READWRITE_STATUS Status after a MEMORY_WRITE or a MEMORY_READ command. OK, busy,
error.
0xC3 BAUD_RATE The current baudrate.
0xC4 STATUS_INFO Status information.
0xC5 MEMORY_SPEED SAB to aWire speed information.
Table 34-49. ACK Details
Response Details
Response value 0x40
Additional data N/A
Table 34-50. NACK Details
Response Details
Response value 0x41
Additional data N/A
Table 34-51. IDCODE Details
Response Details
Response value 0xC0
Additional data JTAG idcode
894
32142D–06/2013
ATUC64/128/256L3/4U
1. 0x55 (sync)
2. 0xC1 (command)
3. 0x00 (length MSB)
4. 0x07 (length LSB)
5. 0xCA (Data MSB)
6. 0xFE
7. 0xBA
8. 0xBE (Data LSB)
9. 0x00 (Status byte)
10. 0x00 (Bytes remaining MSB)
11. 0x00 (Bytes remaining LSB)
12. 0xXX (CRC MSB)
13. 0xXX (CRC LSB)
The status is 0x00 and all data read are valid. An unsuccessful four byte read can look like this:
1. 0x55 (sync)
2. 0xC1 (command)
3. 0x00 (length MSB)
4. 0x07 (length LSB)
5. 0xCA (Data MSB)
6. 0xFE
7. 0xXX (An error has occurred. Data read is undefined. 5 bytes remaining of the Data
field)
8. 0xXX (More undefined data)
9. 0x02 (Status byte)
10. 0x00 (Bytes remaining MSB)
11. 0x05 (Bytes remaining LSB)
12. 0xXX (CRC MSB)
13. 0xXX (CRC LSB)
The error occurred after reading 2 bytes on the SAB. The rest of the bytes read are undefined.
The status byte indicates the error and the bytes remaining indicates how many bytes were
remaining to be sent of the data field of the packet when the error occurred.
Table 34-52. MEMDATA Status Byte
status byte Description
0x00 Read successful
0x01 SAB busy
0x02 Bus error (wrong address)
Other Reserved
Table 34-53. MEMDATA Details
Response Details
Response value 0xC1
Additional data Data read, status byte, and byte count (2 bytes)
895
32142D–06/2013
ATUC64/128/256L3/4U
34.6.8.5 MEMORY_READWRITE_STATUS
After a MEMORY_WRITE command this response is sent by AW. The response can also be
sent after a MEMORY_READ command if AW encountered an error when receiving the
address. The response contains 3 bytes, where the first is the status of the command and the 2
next contains the byte count when the first error occurred. The first byte is encoded this way:
34.6.8.6 BAUD_RATE
The current baud rate in the AW. See Section 34.6.6.7 for more details.
34.6.8.7 STATUS_INFO
A status message from AW.
Table 34-54. MEMORY_READWRITE_STATUS Status Byte
status byte Description
0x00 Write successful
0x01 SAB busy
0x02 Bus error (wrong address)
Other Reserved
Table 34-55. MEMORY_READWRITE_STATUS Details
Response Details
Response value 0xC2
Additional data Status byte and byte count (2 bytes)
Table 34-56. BAUD_RATE Details
Response Details
Response value 0xC3
Additional data Baud rate
Table 34-57. STATUS_INFO Contents
Bit number Name Description
15-9 Reserved
8 Protected The protection bit in the internal flash is set. SAB access is restricted. This bit
will read as one during reset.
7 SAB busy
The SAB bus is busy with a previous transfer. This could indicate that the CPU
is running on a very slow clock, the CPU clock has stopped for some reason
or that the part is in constant reset.
6 Chip erase ongoing The Chip erase operation has not finished.
5 CPU halted This bit will be set if the CPU is halted. This bit will read as zero during reset.
4-1 Reserved
0 Reset status This bit will be set if AW has reset the CPU using the RESET command.
896
32142D–06/2013
ATUC64/128/256L3/4U
34.6.8.8 MEMORY_SPEED
Counts the number of RC120M clock cycles it takes to sync one message to the SAB interface
and back again. The SAB clock speed ( ) can be calculated using the following formula:
34.6.9 Security Restrictions
When the security fuse in the Flash is programmed, the following aWire commands are limited:
• MEMORY_WRITE
• MEMORY_READ
Unlimited access to these instructions is restored when the security fuse is erased by the
CHIP_ERASE aWire command.
Note that the security bit will read as programmed and block these instructions also if the Flash
Controller is statically reset.
Table 34-58. STATUS_INFO Details
Response Details
Response value 0xC4
Additional data 2 status bytes
Table 34-59. MEMORY_SPEED Details
Response Details
Response value 0xC5
Additional data Clock cycle count (MS)
f
sab
f
sab
3f
aw
CV – 3 = ----------------
897
32142D–06/2013
ATUC64/128/256L3/4U
35. Electrical Characteristics
35.1 Absolute Maximum Ratings*
Notes: 1. 5V tolerant pins, see Section ”Peripheral Multiplexing on I/O lines” on page 10
2. VVDD corresponds to either VVDDIN or VVDDIO, depending on the supply for the pin. Refer to Section on page 10 for details.
35.2 Supply Characteristics
The following characteristics are applicable to the operating temperature range: TA = -40°C to
85°C, unless otherwise specified and are valid for a junction temperature up to TJ = 100°C.
Please refer to Section 6. ”Supply and Startup Considerations” on page 39.
Table 35-1. Absolute Maximum Ratings
Operating temperature..................................... -40C to +85C *NOTICE: Stresses beyond those listed under
“Absolute Maximum Ratings” may cause
permanent damage to the device. This is
a stress rating only and functional operation
of the device at these or other conditions
beyond those indicated in the
operational sections of this specification is
not implied. Exposure to absolute maximum
rating conditions for extended periods
may affect device reliability.
Storage temperature...................................... -60°C to +150°C
Voltage on input pins (except for 5V pins) with respect to ground
.................................................................-0.3V to VVDD(2)+0.3V
Voltage on 5V tolerant(1) pins with respect to ground ...............
.............................................................................-0.3V to 5.5V
Total DC output current on all I/O pins - VDDIO, 64-pin package
............... ......................................................................141 mA
Total DC output current on all I/O pins - VDDIN, 64-pin package
....................................................................................... 42 mA
Total DC output current on all I/O pins - VDDIO, 48-pin package
........... ...........................................................................120mA
Total DC output current on all I/O pins - VDDIN, 48-pin package
....................................................................................... 39 mA
Maximum operating voltage VDDCORE......................... 1.98V
Maximum operating voltage VDDIO, VDDIN .................... 3.6V
Table 35-2. Supply Characteristics
Symbol Parameter
Voltage
Min Max Unit
VVDDIO DC supply peripheral I/Os 1.62 3.6 V
VVDDIN
DC supply peripheral I/Os, 1.8V
single supply mode 1.62 1.98 V
DC supply peripheral I/Os and
internal regulator, 3.3V supply
mode
1.98 3.6 V
VVDDCORE DC supply core 1.62 1.98 V
VVDDANA Analog supply voltage 1.62 1.98 V
898
32142D–06/2013
ATUC64/128/256L3/4U
Note: 1. These values are based on simulation and characterization of other AVR microcontrollers
manufactured in the same process technology. These values are not covered by test limits in
production.
35.3 Maximum Clock Frequencies
These parameters are given in the following conditions:
• VVDDCORE = 1.62V to 1.98V
• Temperature = -40°C to 85°C
35.4 Power Consumption
The values in Table 35-5 are measured values of power consumption under the following conditions,
except where noted:
• Operating conditions, internal core supply (Figure 35-1) - this is the default configuration
– VVDDIN = 3.0V
Table 35-3. Supply Rise Rates and Order(1)
Symbol Parameter
Rise Rate
Min Max Unit Comment
VVDDIO DC supply peripheral I/Os 0 2.5 V/µs
VVDDIN
DC supply peripheral I/Os
and internal regulator 0.002 2.5 V/µs
Slower rise time requires
external power-on reset
circuit.
VVDDCORE DC supply core 0 2.5 V/µs Rise before or at the same
time as VDDIO
VVDDANA Analog supply voltage 0 2.5 V/µs Rise together with
VDDCORE
Table 35-4. Clock Frequencies
Symbol Parameter Description Min Max Units
fCPU CPU clock frequency 50
MHz
fPBA PBA clock frequency 50
fPBB PBB clock frequency 50
fGCLK0 GCLK0 clock frequency DFLLIF main reference, GCLK0 pin 50
fGCLK1 GCLK1 clock frequency DFLLIF dithering and SSG reference, GCLK1 pin 50
fGCLK2 GCLK2 clock frequency AST, GCLK2 pin 20
fGCLK3 GCLK3 clock frequency PWMA, GCLK3 pin 140
fGCLK4 GCLK4 clock frequency CAT, ACIFB, GCLK4 pin 50
fGCLK5 GCLK5 clock frequency GLOC and GCLK5 pin 80
fGCLK6 GCLK6 clock frequency ABDACB, IISC, and GCLK6 pin 50
fGCLK7 GCLK7 clock frequency USBC and GCLK7 pin 50
fGCLK8 GCLK8 clock frequency PLL0 source clock and GCLK8 pin 50
fGCLK9 GCLK9 clock frequency FREQM, GCLK0-8, GCLK9 pin 150
899
32142D–06/2013
ATUC64/128/256L3/4U
– VVDDCORE = 1.62V, supplied by the internal regulator
– Corresponds to the 3.3V supply mode with 1.8V regulated I/O lines, please refer to
the Supply and Startup Considerations section for more details
• Equivalent to the 3.3V single supply mode
• Consumption in 1.8V single supply mode can be estimated by subtracting the regulator
static current
• Operating conditions, external core supply (Figure 35-2) - used only when noted
– VVDDIN = VVDDCORE = 1.8V
– Corresponds to the 1.8V single supply mode, please refer to the Supply and Startup
Considerations section for more details
• TA = 25C
• Oscillators
– OSC0 (crystal oscillator) stopped
– OSC32K (32KHz crystal oscillator) running with external 32KHz crystal
– DFLL running at 50MHz with OSC32K as reference
• Clocks
– DFLL used as main clock source
– CPU, HSB, and PBB clocks undivided
– PBA clock divided by 4
– The following peripheral clocks running
• PM, SCIF, AST, FLASHCDW, PBA bridge
– All other peripheral clocks stopped
• I/Os are inactive with internal pull-up
• Flash enabled in high speed mode
• POR18 enabled
• POR33 disabled
900
32142D–06/2013
ATUC64/128/256L3/4U
Note: 1. These numbers are valid for the measured condition only and must not be extrapolated to other frequencies.
Figure 35-1. Measurement Schematic, Internal Core Supply
Table 35-5. Power Consumption for Different Operating Modes
Mode Conditions Measured on Consumption Typ Unit
Active(1) CPU running a recursive Fibonacci algorithm
Amp0
300
µA/MHz
CPU running a division algorithm 174
Idle(1) 96
Frozen(1) 57
Standby(1) 46
Stop 38
µA
DeepStop 25
Static
-OSC32K and AST stopped
-Internal core supply
14
-OSC32K running
-AST running at 1KHz
-External core supply (Figure 35-2)
7.3
-OSC32K and AST stopped
-External core supply (Figure 35-2) 6.7
Shutdown
-OSC32K running
-AST running at 1KHz 800
nA
AST and OSC32K stopped 220
Amp0 VDDIN
VDDCORE
VDDANA
VDDIO
901
32142D–06/2013
ATUC64/128/256L3/4U
Figure 35-2. Measurement Schematic, External Core Supply
Amp0 VDDIN
VDDCORE
VDDANA
VDDIO
902
32142D–06/2013
ATUC64/128/256L3/4U
35.5 I/O Pin Characteristics
Notes: 1. VVDD corresponds to either VVDDIN or VVDDIO, depending on the supply for the pin. Refer to Section on page 10 for details.
2. These values are based on simulation and characterization of other AVR microcontrollers manufactured in the same process
technology. These values are not covered by test limits in production.
Table 35-6. Normal I/O Pin Characteristics(1)
Symbol Parameter Condition Min Typ Max Units
RPULLUP Pull-up resistance 75 100 145 kOhm
VIL Input low-level voltage
VVDD = 3.0V -0.3 0.3 * VVDD V
VVDD = 1.62V -0.3 0.3 * VVDD
VIH Input high-level voltage
VVDD = 3.6V 0.7 * VVDD VVDD + 0.3
V
VVDD = 1.98V 0.7 * VVDD VVDD + 0.3
VOL Output low-level voltage
VVDD = 3.0V, IOL = 3mA 0.4
V
VVDD = 1.62V, IOL = 2mA 0.4
VOH Output high-level voltage
VVDD = 3.0V, IOH = 3mA VVDD - 0.4
V
VVDD = 1.62V, IOH = 2mA VVDD - 0.4
fMAX Output frequency(2)
VVDD = 3.0V, load = 10pF 45
MHz
VVDD = 3.0V, load = 30pF 23
tRISE Rise time(2)
VVDD = 3.0V, load = 10pF 4.7
ns
VVDD = 3.0V, load = 30pF 11.5
tFALL Fall time(2)
VVDD = 3.0V, load = 10pF 4.8
VVDD = 3.0V, load = 30pF 12
ILEAK Input leakage current Pull-up resistors disabled 1 µA
CIN
Input capacitance, all
normal I/O pins except
PA05, PA07, PA17, PA20,
PA21, PB04, PB05
TQFP48 package 1.4
pF
QFN48 package 1.1
TLLGA48 package 1.1
TQFP64 package 1.5
QFN64 package 1.1
CIN Input capacitance, PA20
TQFP48 package 2.7
QFN48 package 2.4
TLLGA48 package 2.4
TQFP64 package 2.8
QFN64 package 2.4
CIN
Input capacitance, PA05,
PA07, PA17, PA21, PB04,
PB05
TQFP48 package 3.8
QFN48 package 3.5
TLLGA48 package 3.5
TQFP64 package 3.9
QFN64 package 3.5
903
32142D–06/2013
ATUC64/128/256L3/4U
Notes: 1. VVDD corresponds to either VVDDIN or VVDDIO, depending on the supply for the pin. Refer to Section on page 10 for details.
Table 35-7. High-drive I/O Pin Characteristics(1)
Symbol Parameter Condition Min Typ Max Units
RPULLUP Pull-up resistance
PA06 30 50 110
PA02, PB01, RESET 75 100 145 kOhm
PA08, PA09 10 20 45
VIL Input low-level voltage
VVDD = 3.0V -0.3 0.3 * VVDD V
VVDD = 1.62V -0.3 0.3 * VVDD
VIH Input high-level voltage
VVDD = 3.6V 0.7 * VVDD VVDD + 0.3
V
VVDD = 1.98V 0.7 * VVDD VVDD + 0.3
VOL Output low-level voltage
VVDD = 3.0V, IOL = 6mA 0.4
V
VVDD = 1.62V, IOL = 4mA 0.4
VOH Output high-level voltage
VVDD = 3.0V, IOH = 6mA VVDD - 0.4
V
VVDD = 1.62V, IOH = 4mA VVDD - 0.4
fMAX
Output frequency, all High-drive I/O
pins, except PA08 and PA09(2)
VVDD = 3.0V, load = 10pF 45
MHz
VVDD = 3.0V, load = 30pF 23
tRISE
Rise time, all High-drive I/O pins, except
PA08 and PA09(2)
VVDD = 3.0V, load = 10pF 4.7
ns
VVDD = 3.0V, load = 30pF 11.5
tFALL
Fall time, all High-drive I/O pins, except
PA08 and PA09(2)
VVDD = 3.0V, load = 10pF 4.8
VVDD = 3.0V, load = 30pF 12
fMAX Output frequency, PA08 and PA09(2)
VVDD = 3.0V, load = 10pF 54
MHz
VVDD = 3.0V, load = 30pF 40
tRISE Rise time, PA08 and PA09(2)
VVDD = 3.0V, load = 10pF 2.8
ns
VVDD = 3.0V, load = 30pF 4.9
tFALL Fall time, PA08 and PA09(2)
VVDD = 3.0V, load = 10pF 2.4
VVDD = 3.0V, load = 30pF 4.6
ILEAK Input leakage current Pull-up resistors disabled 1 µA
CIN
Input capacitance, all High-drive I/O
pins, except PA08 and PA09
TQFP48 package 2.2
pF
QFN48 package 2.0
TLLGA48 package 2.0
TQFP64 package 2.3
QFN64 package 2.0
CIN Input capacitance, PA08 and PA09
TQFP48 package 7.0
QFN48 package 6.7
TLLGA48 package 6.7
TQFP64 package 7.1
QFN64 package 6.7
904
32142D–06/2013
ATUC64/128/256L3/4U
2. These values are based on simulation and characterization of other AVR microcontrollers manufactured in the same process
technology. These values are not covered by test limits in production.
Notes: 1. VVDD corresponds to either VVDDIN or VVDDIO, depending on the supply for the pin. Refer to Section on page 10 for details.
2. These values are based on simulation and characterization of other AVR microcontrollers manufactured in the same process
technology. These values are not covered by test limits in production.
Table 35-8. High-drive I/O, 5V Tolerant, Pin Characteristics(1)
Symbol Parameter Condition Min Typ Max Units
RPULLUP Pull-up resistance 30 50 110 kOhm
VIL Input low-level voltage
VVDD = 3.0V -0.3 0.3 * VVDD V
VVDD = 1.62V -0.3 0.3 * VVDD
VIH Input high-level voltage
VVDD = 3.6V 0.7 * VVDD 5.5
V
VVDD = 1.98V 0.7 * VVDD 5.5
VOL Output low-level voltage
VVDD = 3.0V, IOL = 6mA 0.4
V
VVDD = 1.62V, IOL = 4mA 0.4
VOH Output high-level voltage
VVDD = 3.0V, IOH = 6mA VVDD - 0.4
V
VVDD = 1.62V, IOH = 4mA VVDD - 0.4
fMAX Output frequency(2)
VVDD = 3.0V, load = 10pF 87
MHz
VVDD = 3.0V, load = 30pF 58
tRISE Rise time(2)
VVDD = 3.0V, load = 10pF 2.3
ns
VVDD = 3.0V, load = 30pF 4.3
tFALL Fall time(2)
VVDD = 3.0V, load = 10pF 1.9
VVDD = 3.0V, load = 30pF 3.7
ILEAK Input leakage current 5.5V, pull-up resistors disabled 10 µA
CIN Input capacitance
TQFP48 package 4.5
pF
QFN48 package 4.2
TLLGA48 package 4.2
TQFP64 package 4.6
QFN64 package 4.2
Table 35-9. TWI Pin Characteristics(1)
Symbol Parameter Condition Min Typ Max Units
RPULLUP Pull-up resistance 25 35 60 kOhm
VIL Input low-level voltage
VVDD = 3.0V -0.3 0.3 * VVDD V
VVDD = 1.62V -0.3 0.3 * VVDD
VIH
Input high-level voltage
VVDD = 3.6V 0.7 * VVDD VVDD + 0.3
V
VVDD = 1.98V 0.7 * VVDD VVDD + 0.3
Input high-level voltage, 5V tolerant
SMBUS compliant pins
VVDD = 3.6V 0.7 * VVDD 5.5
V
VVDD = 1.98V 0.7 * VVDD 5.5
905
32142D–06/2013
ATUC64/128/256L3/4U
Note: 1. VVDD corresponds to either VVDDIN or VVDDIO, depending on the supply for the pin. Refer to Section on page 10 for details.
35.6 Oscillator Characteristics
35.6.1 Oscillator 0 (OSC0) Characteristics
35.6.1.1 Digital Clock Characteristics
The following table describes the characteristics for the oscillator when a digital clock is applied
on XIN.
Note: 1. These values are based on simulation and characterization of other AVR microcontrollers manufactured in the same process
technology. These values are not covered by test limits in production.
35.6.1.2 Crystal Oscillator Characteristics
The following table describes the characteristics for the oscillator when a crystal is connected
between XIN and XOUT as shown in Figure 35-3. The user must choose a crystal oscillator
where the crystal load capacitance CL is within the range given in the table. The exact value of CL
VOL Output low-level voltage IOL = 3mA 0.4 V
ILEAK Input leakage current Pull-up resistors disabled 1
IIL Input low leakage 1 µA
IIH Input high leakage 1
CIN Input capacitance
TQFP48 package 3.8
pF
QFN48 package 3.5
TLLGA48 package 3.5
TQFP64 package 3.9
QFN64 package 3.5
tFALL Fall time
Cbus = 400pF, VVDD > 2.0V 250
ns
Cbus = 400pF, VVDD > 1.62V 470
fMAX Max frequency Cbus = 400pF, VVDD > 2.0V 400 kHz
Table 35-9. TWI Pin Characteristics(1)
Symbol Parameter Condition Min Typ Max Units
Table 35-10. Digital Clock Characteristics
Symbol Parameter Conditions Min Typ Max Units
fCPXIN XIN clock frequency 50 MHz
tCPXIN XIN clock duty cycle(1) 40 60 %
tSTARTUP Startup time 0 cycles
CIN XIN input capacitance
TQFP48 package 7.0
pF
QFN48 package 6.7
TLLGA48 package 6.7
TQFP64 package 7.1
QFN64 package 6.7
906
32142D–06/2013
ATUC64/128/256L3/4U
can be found in the crystal datasheet. The capacitance of the external capacitors (CLEXT) can
then be computed as follows:
where CPCB is the capacitance of the PCB and Ci
is the internal equivalent load capacitance.
Notes: 1. Please refer to the SCIF chapter for details.
2. Nominal crystal cycles.
3. These values are based on simulation and characterization of other AVR microcontrollers manufactured in the same process
technology. These values are not covered by test limits in production.
Figure 35-3. Oscillator Connection
CLEXT 2 CL Ci – CPCB = –
Table 35-11. Crystal Oscillator Characteristics
Symbol Parameter Conditions Min Typ Max Unit
fOUT Crystal oscillator frequency(3) 0.45 10 16 MHz
CL Crystal load capacitance(3) 6 18
pF
Ci Internal equivalent load capacitance 2
tSTARTUP Startup time SCIF.OSCCTRL.GAIN = 2(1) 30 000(2) cycles
IOSC Current consumption
Active mode, f = 0.45MHz,
SCIF.OSCCTRL.GAIN = 0 30
µA Active mode, f = 10MHz,
SCIF.OSCCTRL.GAIN = 2 220
XIN
XOUT
CLEXT
CLEXT
CL
Ci
UC3L
907
32142D–06/2013
ATUC64/128/256L3/4U
35.6.2 32KHz Crystal Oscillator (OSC32K) Characteristics
Figure 35-3 and the equation above also applies to the 32KHz oscillator connection. The user
must choose a crystal oscillator where the crystal load capacitance CL is within the range given
in the table. The exact value of CL can then be found in the crystal datasheet.
Notes: 1. Nominal crystal cycles.
2. These values are based on simulation and characterization of other AVR microcontrollers manufactured in the same process
technology. These values are not covered by test limits in production.
35.6.3 Phase Locked Loop (PLL) Characteristics
Note: 1. These values are based on simulation and characterization of other AVR microcontrollers manufactured in the same process
technology. These values are not covered by test limits in production.
Table 35-12. 32 KHz Crystal Oscillator Characteristics
Symbol Parameter Conditions Min Typ Max Unit
fOUT Crystal oscillator frequency 32 768 Hz
tSTARTUP Startup time RS = 60kOhm, CL = 9pF 30 000(1) cycles
CL Crystal load capacitance(2) 6 12.5
pF Ci
Internal equivalent load
capacitance 2
IOSC32 Current consumption 0.6 µA
RS Equivalent series resistance(2) 32 768Hz 35 85 kOhm
Table 35-13. Phase Locked Loop Characteristics
Symbol Parameter Conditions Min Typ Max Unit
fOUT Output frequency(1) 40 240
MHz
fIN Input frequency(1) 4 16
IPLL Current consumption 8 µA/MHz
tSTARTUP
Startup time, from enabling
the PLL until the PLL is
locked
fIN= 4MHz 200
µs
fIN= 16MHz 155
908
32142D–06/2013
ATUC64/128/256L3/4U
35.6.4 Digital Frequency Locked Loop (DFLL) Characteristics
Notes: 1. Spread Spectrum Generator (SSG) is disabled by writing a zero to the EN bit in the DFLL0SSG register.
2. These values are based on simulation and characterization of other AVR microcontrollers manufactured in the same process
technology. These values are not covered by test limits in production.
3. The FINE and COARSE values are selected by wrirting to the DFLL0VAL.FINE and DFLL0VAL.COARSE field respectively.
Table 35-14. Digital Frequency Locked Loop Characteristics
Symbol Parameter Conditions Min Typ Max Unit
fOUT Output frequency(2) 20 150 MHz
fREF Reference frequency(2) 8 150 kHz
FINE resolution step FINE > 100, all COARSE values (3) 0.38 %
Frequency drift over voltage
and temperature Open loop mode See Figure
35-4
Accuracy(2)
FINE lock, fREF = 32kHz, SSG disabled 0.1 0.5
%
ACCURATE lock, fREF = 32kHz, dither clk
RCSYS/2, SSG disabled 0.06 0.5
FINE lock, fREF = 8-150kHz, SSG
disabled 0.2 1
ACCURATE lock, fREF = 8-150kHz,
dither clk RCSYS/2, SSG disabled 0.1 1
IDFLL Power consumption 25 µA/MHz
tSTARTUP Startup time(2) Within 90% of final values 100 µs
tLOCK Lock time
fREF = 32kHz, FINE lock, SSG disabled 8
ms fREF = 32kHz, ACCURATE lock, dithering
clock = RCSYS/2, SSG disabled 28
909
32142D–06/2013
ATUC64/128/256L3/4U
Figure 35-4. DFLL Open Loop Frequency Variation(1)(2)
Notes: 1. The plot shows a typical open loop mode behavior with COARSE= 99 and FINE= 255.
2. These values are based on simulation and characterization of other AVR microcontrollers manufactured in the same process
technology. These values are not covered by test limits in production.
35.6.5 120MHz RC Oscillator (RC120M) Characteristics
Note: 1. These values are based on simulation and characterization of other AVR microcontrollers manufactured in the same process
technology. These values are not covered by test limits in production.
DFLL Open Loop Frequency variation
80
90
100
110
120
130
140
150
160
-40 -20 0 20 40 60 80
Temperature
Frequencies (MHz)
1,98V
1,8V
1.62V
Table 35-15. Internal 120MHz RC Oscillator Characteristics
Symbol Parameter Conditions Min Typ Max Unit
fOUT Output frequency(1) 88 120 152 MHz
IRC120M Current consumption 1.2 mA
tSTARTUP Startup time(1) VVDDCORE = 1.8V 3 µs
910
32142D–06/2013
ATUC64/128/256L3/4U
35.6.6 32kHz RC Oscillator (RC32K) Characteristics
Note: 1. These values are based on simulation and characterization of other AVR microcontrollers manufactured in the same process
technology. These values are not covered by test limits in production.
35.6.7 System RC Oscillator (RCSYS) Characteristics
35.7 Flash Characteristics
Table 35-18 gives the device maximum operating frequency depending on the number of flash
wait states and the flash read mode. The FSW bit in the FLASHCDW FSR register controls the
number of wait states used when accessing the flash memory.
Table 35-16. 32kHz RC Oscillator Characteristics
Symbol Parameter Conditions Min Typ Max Unit
fOUT Output frequency(1) 20 32 44 kHz
IRC32K Current consumption 0.7 µA
tSTARTUP Startup time(1) 100 µs
Table 35-17. System RC Oscillator Characteristics
Symbol Parameter Conditions Min Typ Max Unit
fOUT Output frequency Calibrated at 85C 111.6 115 118.4 kHz
Table 35-18. Maximum Operating Frequency
Flash Wait States Read Mode Maximum Operating Frequency
1
High speed read mode
50MHz
0 25MHz
1
Normal read mode
30MHz
0 15MHz
Table 35-19. Flash Characteristics
Symbol Parameter Conditions Min Typ Max Unit
tFPP Page programming time
fCLK_HSB = 50MHz
5
ms
tFPE Page erase time 5
tFFP Fuse programming time 1
tFEA Full chip erase time (EA) 6
tFCE JTAG chip erase time (CHIP_ERASE) fCLK_HSB = 115kHz 310
911
32142D–06/2013
ATUC64/128/256L3/4U
35.8 ABDACB Electrical Characteristics.
Notes: 1. Test Condition: Common Mode Offset Control disabled (CR.CMOC = 0). Alternative Upsampling Ratio disabled
(CR.ALTUPR = 0). Volume at maximum level (VCR0.VOLUME = 0x7FFF and VCR1.VOLUME = 0x7FFF). Device is battery
powered (9V) through an LDO, VDDIO at 3.3V. Analog low pass filter as shown in Figure 35-5(1. order differential low pass
filter followed by a 4. order low-pass), +VCC at +9V and -VCC at -9V. Test signal stored on a SD card and read by the SPI
Interface.
2. Performance numbers for dynamic range, SNR, and THD performance are very dependent on the application and circuit
board design. Since the design has 0dB Power Supply Rejection Ratio (PSRR), noise on the IO power supply will couple
directly through to the output and be present in the audio signal. To get the best performance one should reduce toggling of
other IO pins as much as possible and make sure the device has sufficient decoupling on the IO supply pins.
3. These values are based on simulation and characterization of other AVR microcontrollers manufactured in the same process
technology. These values are not covered by test limits in production.
Figure 35-5. Differential Analog Low-pass Filter
Table 35-20. Flash Endurance and Data Retention
Symbol Parameter Conditions Min Typ Max Unit
NFARRAY Array endurance (write/page) 100k
cycles
NFFUSE General Purpose fuses endurance (write/bit) 10k
tRET Data retention 15 years
Table 35-21. ABDACB Electrical Characteristics
Symbol Parameter Conditions MIN TYP MAX Unit
Resolution 16 Bits
Dynamic range(1)(2)(3) FS = 48.000kHz > 76 dB
SNR(1)(2)(3) FS = 48.000kHz > 46 dB
THD(1)(2)(3) FS = 48.000kHz < 0.02 %
PSRR 0 dB
VOut maximum CR.CMOC = 0 97/128 * VDDIO V
VOut minimum CR.CMOC = 0 31/128 * VDDIO V
Common mode
CR.CMOC = 0
CR.CMOC = 1, DAC_0 and DAC_1 pins
CR.CMOC = 1, DACN_0 and DACN_1 pins
64/128 * VDDIO
80/128 * VDDIO
48/128 * VDDIO
V
R1, 22K
C2
140p
R2, 22K
R4, 22K
C1, 140p
R3, 22K
R6, 22K
R5, 22K
R7, 22K
C4
270p
C3
310p
-Vcc
+Vcc
-Vcc
+Vcc
DAC
DACN
R8, 22K R9, 22K
C6
110p
C5
750p
-Vcc
+Vcc
GND GND GND GND GND
Out
912
32142D–06/2013
ATUC64/128/256L3/4U
35.9 Analog Characteristics
35.9.1 Voltage Regulator Characteristics
Note: 1. These values are based on simulation and characterization of other AVR microcontrollers manufactured in the same process
technology. These values are not covered by test limits in production.
Note: 1. Refer to Section 6.1.2 on page 39.
Table 35-22. VREG Electrical Characteristics
Symbol Parameter Condition Min Typ Max Units
VVDDIN Input voltage range 1.98 3.3 3.6
V
VVDDCORE Output voltage, calibrated value VVDDIN >= 1.98V 1.8
Output voltage accuracy(1)
IOUT = 0.1mA to 60mA,
VVDDIN > 1.98V
2
%
IOUT = 0.1mA to 60mA,
VVDDIN <1.98V
4
IOUT DC output current(1)
Normal mode 60
mA
Low power mode 1
IVREG Static current of internal regulator
Normal mode 13
µA
Low power mode 4
Table 35-23. Decoupling Requirements
Symbol Parameter Condition Typ Techno. Units
CIN1 Input regulator capacitor 1 33
nF
CIN2 Input regulator capacitor 2 100
CIN3 Input regulator capacitor 3 10 µF
COUT1 Output regulator capacitor 1 100 nF
COUT2 Output regulator capacitor 2 2.2 Tantalum
0.5 3.0V, fADC = 6MHz,
12-bit resolution mode,
low impedance source
28
kSPS
VVDD > 3.0V, fADC = 6MHz,
10-bit resolution mode,
low impedance source
460
VVDD > 3.0V, fADC = 6MHz,
8-bit resolution mode,
low impedance source
460
VADVREFP Reference voltage range VADVREFP = VVDDANA 1.62 1.98 V
IADC Current consumption on VVDDANA ADC Clock = 6MHz 350
µA
IADVREFP
Current consumption on ADVREFP
pin fADC = 6MHz 150
Table 35-30. Analog Inputs
Symbol Parameter Conditions Min Typ Max Units
VADn Input Voltage Range
12-bit mode
10-bit mode 0 VADVREFP V
8-bit mode
CONCHIP Internal Capacitance(1) 22.5 pF
RONCHIP Internal Resistance(1)
VVDDIO = 3.0V to 3.6V,
VVDDCORE = 1.8V 3.15
kOhm
VVDDIO = VVDDCORE = 1.62V to 1.98V 55.9
RONCHIP CONCHIP RSOURCE
917
32142D–06/2013
ATUC64/128/256L3/4U
( ) of the PCB and source must be taken into account when calculating the required
sample and hold time. Figure 35-8 shows the ADC input channel equivalent circuit.
Figure 35-8. ADC Input
The minimum sample and hold time (in ns) can be found using this formula:
Where n is the number of bits in the conversion. is defined by the SHTIM field in the
ADCIFB ACR register. Please refer to the ADCIFB chapter for more information.
35.9.6.2 Applicable Conditions and Derating Data
Note: 1. These values are based on simulation and characterization of other AVR microcontrollers manufactured in the same process
technology. These values are not covered by test limits in production.
CSOURCE
ADCVREFP/2
CONCHIP
RONCHIP R Positive Input SOURCE
CSOURCE VIN
t
SAMPLEHOLD RONCHIP + RSOURCE CONCHIP CSOURCE + 2n + 1 ln
t
SAMPLEHOLD
Table 35-31. Transfer Characteristics 12-bit Resolution Mode(1)
Parameter Conditions Min Typ Max Units
Resolution 12 Bit
Integral non-linearity
ADC clock frequency = 6MHz,
Input Voltage Range = 0 - VADVREFP
+/-4
LSB
ADC clock frequency = 6MHz,
Input Voltage Range = (10% VADVREFP) -
(90% VADVREFP)
+/-2
Differential non-linearity
ADC clock frequency = 6MHz
-1.5 1.5
Offset error +/-3
Gain error +/-5
Table 35-32. Transfer Characteristics, 10-bit Resolution Mode(1)
Parameter Conditions Min Typ Max Units
Resolution 10 Bit
Integral non-linearity
ADC clock frequency = 6MHz
+/-1
LSB Differential non-linearity -1.0 1.0
Offset error +/-1
Gain error +/-2
918
32142D–06/2013
ATUC64/128/256L3/4U
Note: 1. These values are based on simulation and characterization of other AVR microcontrollers manufactured in the same process
technology. These values are not covered by test limits in production.
Note: 1. These values are based on simulation and characterization of other AVR microcontrollers manufactured in the same process
technology. These values are not covered by test limits in production.
35.9.7 Temperature Sensor Characteristics
Note: 1. The Temperature Sensor is not calibrated. The accuracy of the Temperature Sensor is governed by the ADC accuracy.
Table 35-33. Transfer Characteristics, 8-bit Resolution Mode(1)
Parameter Conditions Min Typ Max Units
Resolution 8 Bit
Integral non-linearity
ADC clock frequency = 6MHz
+/-0.5
LSB Differential non-linearity -0.3 0.3
Offset error +/-1
Gain error +/-1
Table 35-34. Temperature Sensor Characteristics(1)
Symbol Parameter Condition Min Typ Max Units
Gradient 1 mV/°C
ITS Current consumption 1 µA
tSTARTUP Startup time 0 µs
919
32142D–06/2013
ATUC64/128/256L3/4U
35.9.8 Analog Comparator Characteristics
Notes: 1. AC.CONFn.FLEN and AC.CONFn.HYS fields, refer to the Analog Comparator Interface chapter.
2. Referring to fAC.
3. These values are based on simulation and characterization of other AVR microcontrollers manufactured in the same process
technology. These values are not covered by test limits in production.
35.9.9 Capacitive Touch Characteristics
35.9.9.1 Discharge Current Source
Note: 1. These values are based on simulation and characterization of other AVR microcontrollers manufactured in the same process
technology. These values are not covered by test limits in production.
Table 35-35. Analog Comparator Characteristics
Symbol Parameter Condition Min Typ Max Units
Positive input
voltage range(3) -0.2 VVDDIO + 0.3
V
Negative input
voltage range(3) -0.2 VVDDIO - 0.6
Statistical offset(3)
VACREFN = 1.0V,
fAC = 12MHz,
filter length = 2,
hysteresis = 0(1)
20 mV
fAC
Clock frequency for
GCLK4(3) 12 MHz
Throughput rate(3) fAC = 12MHz 12 000 000 Comparisons
per second
Propagation delay
Delay from input
change to
Interrupt Status
Register Changes
ns
IAC
Current
consumption(3)
All channels,
VDDIO = 3.3V,
fA = 3MHz
420 µA
tSTARTUP Startup time 3 cycles
Input current per
pin(3) 0.2 µA/MHz(2)
Table 35-36. DICS Characteristics
Symbol Parameter Min Typ Max Unit
RREF Internal resistor 170 kOhm
k Trim step size(1) 0.7 %
1
t
CLKACIFB f
AC ---------------------------------------- + 3 t
CLKACIFB
920
32142D–06/2013
ATUC64/128/256L3/4U
35.9.9.2 Strong Pull-up Pull-down
35.9.10 USB Transceiver Characteristics
The USB on-chip buffers comply with the Universal Serial Bus (USB) v2.0 standard. All AC
parameters related to these buffers can be found within the USB 2.0 electrical specifications.
35.9.10.1 Electrical Characteristics
Table 35-37. Strong Pull-up Pull-down
Parameter Min Typ Max Unit
Pull-down resistor 1
kOhm
Pull-up resistor 1
Table 35-38. Electrical Parameters
Symbol Parameter Conditions Min Typ Max Unit
REXT
Recommended external USB
series resistor
In series with each USB pin with
±5% 39 Ohm
921
32142D–06/2013
ATUC64/128/256L3/4U
35.10 Timing Characteristics
35.10.1 Startup, Reset, and Wake-up Timing
The startup, reset, and wake-up timings are calculated using the following formula:
Where and are found in Table 35-39. is the period of the CPU clock. If a
clock source other than RCSYS is selected as the CPU clock, the oscillator startup time,
, must be added to the wake-up time from the stop, deepstop, and static sleep
modes. Please refer to the source for the CPU clock in the ”Oscillator Characteristics” on page
905 for more details about oscillator startup times.
Note: 1. These values are based on simulation and characterization of other AVR microcontrollers manufactured in the same process
technology. These values are not covered by test limits in production.
35.10.2 RESET_N Timing
Note: 1. These values are based on simulation and characterization of other AVR microcontrollers manufactured in the same process
technology. These values are not covered by test limits in production.
t tCONST NCPU t
CPU = +
t
CONST NCPU t
CPU
t
OSCSTART
Table 35-39. Maximum Reset and Wake-up Timing(1)
Parameter Measuring Max (in µs) Max
Startup time from power-up, using
regulator
Time from VDDIN crossing the VPOT+ threshold of
POR33 to the first instruction entering the decode
stage of CPU. VDDCORE is supplied by the internal
regulator.
2210 0
Startup time from power-up, no
regulator
Time from VDDIN crossing the VPOT+ threshold of
POR33 to the first instruction entering the decode
stage of CPU. VDDCORE is connected to VDDIN.
1810 0
Startup time from reset release
Time from releasing a reset source (except POR18,
POR33, and SM33) to the first instruction entering
the decode stage of CPU.
170 0
Wake-up
Idle
From wake-up event to the first instruction of an
interrupt routine entering the decode stage of the
CPU.
0 19
Frozen 0 110
Standby 0 110
Stop 27 + 116
Deepstop 27 + 116
Static 97 + 116
Wake-up from shutdown From wake-up event to the first instruction entering
the decode stage of the CPU. 1180 0
t
CONST NCPU
t
OSCSTART
t
OSCSTART
t
OSCSTART
Table 35-40. RESET_N Waveform Parameters(1)
Symbol Parameter Conditions Min Max Units
tRESET RESET_N minimum pulse length 10 ns
922
32142D–06/2013
ATUC64/128/256L3/4U
35.10.3 USART in SPI Mode Timing
35.10.3.1 Master mode
Figure 35-9. USART in SPI Master Mode with (CPOL= CPHA= 0) or (CPOL= CPHA= 1)
Figure 35-10. USART in SPI Master Mode with (CPOL= 0 and CPHA= 1) or (CPOL= 1 and
CPHA= 0)
Notes: 1. These values are based on simulation and characterization of other AVR microcontrollers manufactured in the same process
technology. These values are not covered by test limits in production.
2. Where:
USPI0 USPI1
MISO
SPCK
MOSI
USPI2
USPI3 USPI4
MISO
SPCK
MOSI
USPI5
Table 35-41. USART in SPI Mode Timing, Master Mode(1)
Symbol Parameter Conditions Min Max Units
USPI0 MISO setup time before SPCK rises
VVDDIO from
3.0V to 3.6V,
maximum
external
capacitor =
40pF
28.7 + tSAMPLE(2)
ns
USPI1 MISO hold time after SPCK rises 0
USPI2 SPCK rising to MOSI delay 16.5
USPI3 MISO setup time before SPCK falls 25.8 + tSAMPLE(2)
USPI4 MISO hold time after SPCK falls 0
USPI5 SPCK falling to MOSI delay 21.19
t
SAMPLE t
SPCK
t
SPCK
2 t
CLKUSART ------------------------------------ 1
2
-- t
CLKUSART = –
923
32142D–06/2013
ATUC64/128/256L3/4U
Maximum SPI Frequency, Master Output
The maximum SPI master output frequency is given by the following formula:
Where is the MOSI delay, USPI2 or USPI5 depending on CPOL and NCPHA. is
the maximum frequency of the SPI pins. Please refer to the I/O Pin Characteristics section for
the maximum frequency of the pins. is the maximum frequency of the CLK_SPI. Refer
to the SPI chapter for a description of this clock.
Maximum SPI Frequency, Master Input
The maximum SPI master input frequency is given by the following formula:
Where is the MISO setup and hold time, USPI0 + USPI1 or USPI3 + USPI4 depending on
CPOL and NCPHA. is the SPI slave response time. Please refer to the SPI slave
datasheet for . is the maximum frequency of the CLK_SPI. Refer to the SPI chapter
for a description of this clock.
35.10.3.2 Slave mode
Figure 35-11. USART in SPI Slave Mode with (CPOL= 0 and CPHA= 1) or (CPOL= 1 and
CPHA= 0)
f
SPCKMAX MIN fPINMAX
1
SPIn
------------ f
CLKSPI 2
9 = (, ) ----------------------------
SPIn fPINMAX
f
CLKSPI
f
SPCKMAX MIN 1
SPIn tVALID + ----------------------------------- f
CLKSPI 2
9 = ( ,) -----------------------------
SPIn
TVALID
TVALID f
CLKSPI
USPI7 USPI8
MISO
SPCK
MOSI
USPI6
924
32142D–06/2013
ATUC64/128/256L3/4U
Figure 35-12. USART in SPI Slave Mode with (CPOL= CPHA= 0) or (CPOL= CPHA= 1)
Figure 35-13. USART in SPI Slave Mode, NPCS Timing
Notes: 1. These values are based on simulation and characterization of other AVR microcontrollers manufactured in the same process
technology. These values are not covered by test limits in production.
2. Where:
USPI10 USPI11
MISO
SPCK
MOSI
USPI9
USPI14
USPI12
USPI15
USPI13
NSS
SPCK, CPOL=0
SPCK, CPOL=1
Table 35-42. USART in SPI mode Timing, Slave Mode(1)
Symbol Parameter Conditions Min Max Units
USPI6 SPCK falling to MISO delay
VVDDIO from
3.0V to 3.6V,
maximum
external
capacitor =
40pF
37.3
ns
USPI7 MOSI setup time before SPCK rises 2.6 + tSAMPLE(2) +
tCLK_USART
USPI8 MOSI hold time after SPCK rises 0
USPI9 SPCK rising to MISO delay 37.0
USPI10 MOSI setup time before SPCK falls 2.6 + tSAMPLE(2) +
tCLK_USART
USPI11 MOSI hold time after SPCK falls 0
USPI12 NSS setup time before SPCK rises 27.2
USPI13 NSS hold time after SPCK falls 0
USPI14 NSS setup time before SPCK falls 27.2
USPI15 NSS hold time after SPCK rises 0
t
SAMPLE t
SPCK
t
SPCK
2 tCLKUSART ------------------------------------ 1
2
+ -- t
CLKUSART = –
925
32142D–06/2013
ATUC64/128/256L3/4U
Maximum SPI Frequency, Slave Input Mode
The maximum SPI slave input frequency is given by the following formula:
Where is the MOSI setup and hold time, USPI7 + USPI8 or USPI10 + USPI11 depending
on CPOL and NCPHA. is the maximum frequency of the CLK_SPI. Refer to the SPI
chapter for a description of this clock.
Maximum SPI Frequency, Slave Output Mode
The maximum SPI slave output frequency is given by the following formula:
Where is the MISO delay, USPI6 or USPI9 depending on CPOL and NCPHA. is
the SPI master setup time. Please refer to the SPI master datasheet for . is the
maximum frequency of the CLK_SPI. Refer to the SPI chapter for a description of this
clock. is the maximum frequency of the SPI pins. Please refer to the I/O Pin Characteristics
section for the maximum frequency of the pins.
35.10.4 SPI Timing
35.10.4.1 Master mode
Figure 35-14. SPI Master Mode with (CPOL= NCPHA= 0) or (CPOL= NCPHA= 1)
f
SPCKMAX MIN f
CLKSPI 2
9 ----------------------------- 1
SPIn = ( ,) ------------
SPIn
f
CLKSPI
f
SPCKMAX MIN f
CLKSPI 2
9 ---------------------------- f
PINMAX 1
SPIn tSETUP + = ( ,) ------------------------------------
SPIn TSETUP
TSETUP f
CLKSPI
f
PINMAX
SPI0 SPI1
MISO
SPCK
MOSI
SPI2
926
32142D–06/2013
ATUC64/128/256L3/4U
Figure 35-15. SPI Master Mode with (CPOL= 0 and NCPHA= 1) or (CPOL= 1 and NCPHA= 0)
Note: 1. These values are based on simulation and characterization of other AVR microcontrollers manufactured in the same process
technology. These values are not covered by test limits in production.
Maximum SPI Frequency, Master Output
The maximum SPI master output frequency is given by the following formula:
Where is the MOSI delay, SPI2 or SPI5 depending on CPOL and NCPHA. is the
maximum frequency of the SPI pins. Please refer to the I/O Pin Characteristics section for the
maximum frequency of the pins.
Maximum SPI Frequency, Master Input
The maximum SPI master input frequency is given by the following formula:
Where is the MISO setup and hold time, SPI0 + SPI1 or SPI3 + SPI4 depending on
CPOL and NCPHA. is the SPI slave response time. Please refer to the SPI slave
datasheet for .
SPI3 SPI4
MISO
SPCK
MOSI
SPI5
Table 35-43. SPI Timing, Master Mode(1)
Symbol Parameter Conditions Min Max Units
SPI0 MISO setup time before SPCK rises
VVDDIO from
3.0V to 3.6V,
maximum
external
capacitor =
40pF
33.4 + (tCLK_SPI)/2
ns
SPI1 MISO hold time after SPCK rises 0
SPI2 SPCK rising to MOSI delay 7.1
SPI3 MISO setup time before SPCK falls 29.2 + (tCLK_SPI)/2
SPI4 MISO hold time after SPCK falls 0
SPI5 SPCK falling to MOSI delay 8.63
f
SPCKMAX MIN fPINMAX
1
SPIn = ( ,) ------------
SPIn f
PINMAX
f
SPCKMAX
1
SPIn tVALID + = -----------------------------------
SPIn
t
VALID
tVALID
927
32142D–06/2013
ATUC64/128/256L3/4U
35.10.4.2 Slave mode
Figure 35-16. SPI Slave Mode with (CPOL= 0 and NCPHA= 1) or (CPOL= 1 and NCPHA= 0)
Figure 35-17. SPI Slave Mode with (CPOL= NCPHA= 0) or (CPOL= NCPHA= 1)
Figure 35-18. SPI Slave Mode, NPCS Timing
SPI7 SPI8
MISO
SPCK
MOSI
SPI6
SPI10 SPI11
MISO
SPCK
MOSI
SPI9
SPI14
SPI12
SPI15
SPI13
NPCS
SPCK, CPOL=0
SPCK, CPOL=1
928
32142D–06/2013
ATUC64/128/256L3/4U
Note: 1. These values are based on simulation and characterization of other AVR microcontrollers manufactured in the same process
technology. These values are not covered by test limits in production.
Maximum SPI Frequency, Slave Input Mode
The maximum SPI slave input frequency is given by the following formula:
Where is the MOSI setup and hold time, SPI7 + SPI8 or SPI10 + SPI11 depending on
CPOL and NCPHA. is the maximum frequency of the CLK_SPI. Refer to the SPI chapter
for a description of this clock.
Maximum SPI Frequency, Slave Output Mode
The maximum SPI slave output frequency is given by the following formula:
Where is the MISO delay, SPI6 or SPI9 depending on CPOL and NCPHA. is the
SPI master setup time. Please refer to the SPI master datasheet for . is the maximum
frequency of the SPI pins. Please refer to the I/O Pin Characteristics section for the
maximum frequency of the pins.
35.10.5 TWIM/TWIS Timing
Figure 35-45 shows the TWI-bus timing requirements and the compliance of the device with
them. Some of these requirements (tr
and tf
) are met by the device without requiring user intervention.
Compliance with the other requirements (tHD-STA, tSU-STA, tSU-STO, tHD-DAT, tSU-DAT-TWI, tLOWTWI,
tHIGH, and fTWCK) requires user intervention through appropriate programming of the relevant
Table 35-44. SPI Timing, Slave Mode(1)
Symbol Parameter Conditions Min Max Units
SPI6 SPCK falling to MISO delay
VVDDIO from
3.0V to 3.6V,
maximum
external
capacitor =
40pF
29.4
ns
SPI7 MOSI setup time before SPCK rises 0
SPI8 MOSI hold time after SPCK rises 6.0
SPI9 SPCK rising to MISO delay 29.0
SPI10 MOSI setup time before SPCK falls 0
SPI11 MOSI hold time after SPCK falls 5.5
SPI12 NPCS setup time before SPCK rises 3.4
SPI13 NPCS hold time after SPCK falls 1.1
SPI14 NPCS setup time before SPCK falls 3.3
SPI15 NPCS hold time after SPCK rises 0.7
f
SPCKMAX MIN fCLKSPI
1
SPIn = ( ,) ------------
SPIn
f
CLKSPI
f
SPCKMAX MIN fPINMAX
1
SPIn tSETUP + = (, ) ------------------------------------
SPIn t
SETUP
t
SETUP fPINMAX
929
32142D–06/2013
ATUC64/128/256L3/4U
TWIM and TWIS user interface registers. Please refer to the TWIM and TWIS sections for more
information.
Notes: 1. Standard mode: ; fast mode: .
2. A device must internally provide a hold time of at least 300 ns for TWD with reference to the falling edge of TWCK.
Notations:
Cb = total capacitance of one bus line in pF
tclkpb = period of TWI peripheral bus clock
tprescaled = period of TWI internal prescaled clock (see chapters on TWIM and TWIS)
The maximum tHD;DAT has only to be met if the device does not stretch the LOW period (tLOW-TWI)
of TWCK.
Table 35-45. TWI-Bus Timing Requirements
Symbol Parameter Mode
Minimum Maximum Uni
Requirement Device Requirement Device t
tr TWCK and TWD rise time
Standard(
1) - 1000
ns
Fast(1) 20 + 0.1Cb 300
tf TWCK and TWD fall time
Standard - 300
ns
Fast 20 + 0.1Cb 300
tHD-STA (Repeated) START hold time
Standard 4
tclkpb - s
Fast 0.6
tSU-STA
(Repeated) START set-up
time
Standard 4.7
tclkpb - s
Fast 0.6
tSU-STO STOP set-up time
Standard 4.0
4tclkpb - s
Fast 0.6
tHD-DAT Data hold time
Standard
0.3(2) 2tclkpb
3.45()
15tprescaled +
tclkpb
s
Fast 0.9()
tSU-DATTWI
Data set-up time
Standard 250
2tclkpb - ns
Fast 100
tSU-DAT - -tclkpb - -
tLOW-TWI TWCK LOW period
Standard 4.7
4tclkpb - s
Fast 1.3
tLOW - -tclkpb - -
tHIGH TWCK HIGH period
Standard 4.0
8tclkpb - s
Fast 0.6
fTWCK TWCK frequency
Standard - 100
kHz
Fast 400
1
12tclkpb
-----------------------
fTWCK 100 kHz f
TWCK 100 kHz
930
32142D–06/2013
ATUC64/128/256L3/4U
35.10.6 JTAG Timing
Figure 35-19. JTAG Interface Signals
Note: 1. These values are based on simulation and characterization of other AVR microcontrollers manufactured in the same process
technology. These values are not covered by test limits in production.
JTAG2
JTAG3
JTAG1
JTAG4
JTAG0
TMS/TDI
TCK
TDO
JTAG5
JTAG6
JTAG7 JTAG8
JTAG9
JTAG10
Boundary
Scan Inputs
Boundary
Scan Outputs
Table 35-46. JTAG Timings(1)
Symbol Parameter Conditions Min Max Units
JTAG0 TCK Low Half-period
VVDDIO from
3.0V to 3.6V,
maximum
external
capacitor =
40pF
21.8
ns
JTAG1 TCK High Half-period 8.6
JTAG2 TCK Period 30.3
JTAG3 TDI, TMS Setup before TCK High 2.0
JTAG4 TDI, TMS Hold after TCK High 2.3
JTAG5 TDO Hold Time 9.5
JTAG6 TCK Low to TDO Valid 21.8
JTAG7 Boundary Scan Inputs Setup Time 0.6
JTAG8 Boundary Scan Inputs Hold Time 6.9
JTAG9 Boundary Scan Outputs Hold Time 9.3
JTAG10 TCK to Boundary Scan Outputs Valid 32.2
931
32142D–06/2013
ATUC64/128/256L3/4U
36. Mechanical Characteristics
36.1 Thermal Considerations
36.1.1 Thermal Data
Table 36-1 summarizes the thermal resistance data depending on the package.
36.1.2 Junction Temperature
The average chip-junction temperature, TJ, in °C can be obtained from the following:
1.
2.
where:
• JA = package thermal resistance, Junction-to-ambient (°C/W), provided in Table 36-1.
• JC = package thermal resistance, Junction-to-case thermal resistance (°C/W), provided in
Table 36-1.
• HEAT SINK = cooling device thermal resistance (°C/W), provided in the device datasheet.
• PD = device power consumption (W) estimated from data provided in Section 35.4 on page
898.
• TA = ambient temperature (°C).
From the first equation, the user can derive the estimated lifetime of the chip and decide if a
cooling device is necessary or not. If a cooling device is to be fitted on the chip, the second
equation should be used to compute the resulting average chip-junction temperature TJ in °C.
Table 36-1. Thermal Resistance Data
Symbol Parameter Condition Package Typ Unit
JA Junction-to-ambient thermal resistance Still Air TQFP48 54.4 C/W
JC Junction-to-case thermal resistance TQFP48 15.7
JA Junction-to-ambient thermal resistance Still Air QFN48 26.0 C/W
JC Junction-to-case thermal resistance QFN48 1.6
JA Junction-to-ambient thermal resistance Still Air TLLGA48 25.4 C/W
JC Junction-to-case thermal resistance TLLGA48 12.7
JA Junction-to-ambient thermal resistance Still Air TQFP64 52.9 C/W
JC Junction-to-case thermal resistance TQFP64 15.5
JA Junction-to-ambient thermal resistance Still Air QFN64 22.9 C/W
JC Junction-to-case thermal resistance QFN64 1.6
TJ TA PD JA = +
TJ TA PD HEATSINK JC = + +
932
32142D–06/2013
ATUC64/128/256L3/4U
36.2 Package Drawings
Figure 36-1. TQFP-48 Package Drawing
Table 36-2. Device and Package Maximum Weight
140 mg
Table 36-3. Package Characteristics
Moisture Sensitivity Level MSL3
Table 36-4. Package Reference
JEDEC Drawing Reference MS-026
JESD97 Classification E3
933
32142D–06/2013
ATUC64/128/256L3/4U
Figure 36-2. QFN-48 Package Drawing
Note: The exposed pad is not connected to anything internally, but should be soldered to ground to increase board level reliability.
Table 36-5. Device and Package Maximum Weight
140 mg
Table 36-6. Package Characteristics
Moisture Sensitivity Level MSL3
Table 36-7. Package Reference
JEDEC Drawing Reference M0-220
JESD97 Classification E3
934
32142D–06/2013
ATUC64/128/256L3/4U
Figure 36-3. TLLGA-48 Package Drawing
Table 36-8. Device and Package Maximum Weight
39.3 mg
Table 36-9. Package Characteristics
Moisture Sensitivity Level MSL3
Table 36-10. Package Reference
JEDEC Drawing Reference N/A
JESD97 Classification E4
935
32142D–06/2013
ATUC64/128/256L3/4U
Figure 36-4. TQFP-64 Package Drawing
Table 36-11. Device and Package Maximum Weight
300 mg
Table 36-12. Package Characteristics
Moisture Sensitivity Level MSL3
Table 36-13. Package Reference
JEDEC Drawing Reference MS-026
JESD97 Classification E3
936
32142D–06/2013
ATUC64/128/256L3/4U
Figure 36-5. QFN-64 Package Drawing
Note: The exposed pad is not connected to anything internally, but should be soldered to ground to increase board level reliability.
Table 36-14. Device and Package Maximum Weight
200 mg
Table 36-15. Package Characteristics
Moisture Sensitivity Level MSL3
Table 36-16. Package Reference
JEDEC Drawing Reference M0-220
JESD97 Classification E3
937
32142D–06/2013
ATUC64/128/256L3/4U
36.3 Soldering Profile
Table 36-17 gives the recommended soldering profile from J-STD-20.
A maximum of three reflow passes is allowed per component.
Table 36-17. Soldering Profile
Profile Feature Green Package
Average Ramp-up Rate (217°C to Peak) 3°C/s max
Preheat Temperature 175°C ±25°C 150-200°C
Time Maintained Above 217°C 60-150 s
Time within 5C of Actual Peak Temperature 30 s
Peak Temperature Range 260°C
Ramp-down Rate 6°C/s max
Time 25C to Peak Temperature 8 minutes max
938
32142D–06/2013
ATUC64/128/256L3/4U
37. Ordering Information
Table 37-1. Ordering Information
Device Ordering Code Carrier Type Package Package Type
Temperature Operating
Range
ATUC256L3U
ATUC256L3U-AUTES ES
TQFP 64
JESD97 Classification E3
N/A
ATUC256L3U-AUT Tray
Industrial (-40C to 85C)
ATUC256L3U-AUR Tape & Reel
ATUC256L3U-Z3UTES ES
QFN 64
N/A
ATUC256L3U-Z3UT Tray
Industrial (-40C to 85C)
ATUC256L3U-Z3UR Tape & Reel
ATUC128L3U
ATUC128L3U-AUT Tray TQFP 64
JESD97 Classification E3 Industrial (-40C to 85C)
ATUC128L3U-AUR Tape & Reel
ATUC128L3U-Z3UT Tray QFN 64
ATUC128L3U-Z3UR Tape & Reel
ATUC64L3U
ATUC64L3U-AUT Tray TQFP 64
JESD97 Classification E3 Industrial (-40C to 85C) ATUC64L3U-AUR Tape & Reel
ATUC64L3U-Z3UT Tray QFN 64
ATUC64L3U-Z3UR Tape & Reel
939
32142D–06/2013
ATUC64/128/256L3/4U
ATUC256L4U
ATUC256L4U-AUTES ES
TQFP 48
JESD97 Classification E3
N/A
ATUC256L4U-AUT Tray Industrial (-40C to 85C)
ATUC256L4U-AUR Tape & Reel
ATUC256L4U-ZAUTES ES
QFN 48
N/A
ATUC256L4U-ZAUT Tray
Industrial (-40C to 85C) ATUC256L4U-ZAUR Tape & Reel
ATUC256L4U-D3HES ES
TLLGA 48 JESD97 Classification E4
N/A
ATUC256L4U-D3HT Tray
Industrial (-40C to 85C)
ATUC256L4U-D3HR Tape & Reel
ATUC128L4U
ATUC128L4U-AUT Tray TQFP 48
JESD97 Classification E3
ATUC128L4U-AUR Tape & Reel
ATUC128L4U-ZAUT Tray QFN 48
ATUC128L4U-ZAUR Tape & Reel
ATUC128L4U-D3HT Tray TLLGA 48 JESD97 Classification E4
ATUC128L4U-D3HR Tape & Reel
ATUC64L4U
ATUC64L4U-AUT Tray TQFP 48
JESD97 Classification E3
ATUC64L4U-AUR Tape & Reel
ATUC64L4U-ZAUT Tray QFN 48
ATUC64L4U-ZAUR Tape & Reel
ATUC64L4U-D3HT Tray TLLGA 48 JESD97 Classification E4
ATUC64L4U-D3HR Tape & Reel
Table 37-1. Ordering Information
Device Ordering Code Carrier Type Package Package Type
Temperature Operating
Range
940
32142D–06/2013
ATUC64/128/256L3/4U
38. Errata
38.1 Rev. C
38.1.1 SCIF
1. The RC32K output on PA20 is not always permanently disabled
The RC32K output on PA20 may sometimes re-appear.
Fix/Workaround
Before using RC32K for other purposes, the following procedure has to be followed in order
to properly disable it:
- Run the CPU on RCSYS
- Disable the output to PA20 by writing a zero to PM.PPCR.RC32OUT
- Enable RC32K by writing a one to SCIF.RC32KCR.EN, and wait for this bit to be read as
one
- Disable RC32K by writing a zero to SCIF.RC32KCR.EN, and wait for this bit to be read as
zero.
2. PLLCOUNT value larger than zero can cause PLLEN glitch
Initializing the PLLCOUNT with a value greater than zero creates a glitch on the PLLEN signal
during asynchronous wake up.
Fix/Workaround
The lock-masking mechanism for the PLL should not be used.
The PLLCOUNT field of the PLL Control Register should always be written to zero.
3. Writing 0x5A5A5A5A to the SCIF memory range will enable the SCIF UNLOCK feature
The SCIF UNLOCK feature will be enabled if the value 0x5A5A5A5A is written to any location
in the SCIF memory range.
Fix/Workaround
None.
38.1.2 SPI
1. SPI data transfer hangs with CSR0.CSAAT==1 and MR.MODFDIS==0
When CSR0.CSAAT==1 and mode fault detection is enabled (MR.MODFDIS==0), the SPI
module will not start a data transfer.
Fix/Workaround
Disable mode fault detection by writing a one to MR.MODFDIS.
2. Disabling SPI has no effect on the SR.TDRE bit
Disabling SPI has no effect on the SR.TDRE bit whereas the write data command is filtered
when SPI is disabled. Writing to TDR when SPI is disabled will not clear SR.TDRE. If SPI is
disabled during a PDCA transfer, the PDCA will continue to write data to TDR until its buffer
is empty, and this data will be lost.
Fix/Workaround
Disable the PDCA, add two NOPs, and disable the SPI. To continue the transfer, enable the
SPI and PDCA.
3. SPI disable does not work in SLAVE mode
SPI disable does not work in SLAVE mode.
Fix/Workaround
Read the last received data, then perform a software reset by writing a one to the Software
Reset bit in the Control Register (CR.SWRST).
941
32142D–06/2013
ATUC64/128/256L3/4U
4. SPI bad serial clock generation on 2nd chip_select when SCBR=1, CPOL=1, and
NCPHA=0
When multiple chip selects (CS) are in use, if one of the baudrates equal 1 while one
(CSRn.SCBR=1) of the others do not equal 1, and CSRn.CPOL=1 and CSRn.NCPHA=0,
then an additional pulse will be generated on SCK.
Fix/Workaround
When multiple CS are in use, if one of the baudrates equals 1, the others must also equal 1
if CSRn.CPOL=1 and CSRn.NCPHA=0.
5. SPI mode fault detection enable causes incorrect behavior
When mode fault detection is enabled (MR.MODFDIS==0), the SPI module may not operate
properly.
Fix/Workaround
Always disable mode fault detection before using the SPI by writing a one to MR.MODFDIS.
6. SPI RDR.PCS is not correct
The PCS (Peripheral Chip Select) field in the SPI RDR (Receive Data Register) does not
correctly indicate the value on the NPCS pins at the end of a transfer.
Fix/Workaround
Do not use the PCS field of the SPI RDR.
38.1.3 TWI
1. SMBALERT bit may be set after reset
The SMBus Alert (SMBALERT) bit in the Status Register (SR) might be erroneously set after
system reset.
Fix/Workaround
After system reset, clear the SR.SMBALERT bit before commencing any TWI transfer.
2. Clearing the NAK bit before the BTF bit is set locks up the TWI bus
When the TWIS is in transmit mode, clearing the NAK Received (NAK) bit of the Status Register
(SR) before the end of the Acknowledge/Not Acknowledge cycle will cause the TWIS to
attempt to continue transmitting data, thus locking up the bus.
Fix/Workaround
Clear SR.NAK only after the Byte Transfer Finished (BTF) bit of the same register has been
set.
38.1.4 TC
1. Channel chaining skips first pulse for upper channel
When chaining two channels using the Block Mode Register, the first pulse of the clock
between the channels is skipped.
Fix/Workaround
Configure the lower channel with RA = 0x1 and RC = 0x2 to produce a dummy clock cycle
for the upper channel. After the dummy cycle has been generated, indicated by the
SR.CPCS bit, reconfigure the RA and RC registers for the lower channel with the real
values.
38.1.5 CAT
1. CAT QMatrix sense capacitors discharged prematurely
At the end of a QMatrix burst charging sequence that uses different burst count values for
different Y lines, the Y lines may be incorrectly grounded for up to n-1 periods of the periph-
942
32142D–06/2013
ATUC64/128/256L3/4U
eral bus clock, where n is the ratio of the PB clock frequency to the GCLK_CAT frequency.
This results in premature loss of charge from the sense capacitors and thus increased variability
of the acquired count values.
Fix/Workaround
Enable the 1kOhm drive resistors on all implemented QMatrix Y lines (CSA 1, 3, 5, 7, 9, 11,
13, and/or 15) by writing ones to the corresponding odd bits of the CSARES register.
2. Autonomous CAT acquisition must be longer than AST source clock period
When using the AST to trigger CAT autonomous touch acquisition in sleep modes where the
CAT bus clock is turned off, the CAT will start several acquisitions if the period of the AST
source clock is larger than one CAT acquisition. One AST clock period after the AST trigger,
the CAT clock will automatically stop and the CAT acquisition can be stopped prematurely,
ruining the result.
Fix/Workaround
Always ensure that the ATCFG1.max field is set so that the duration of the autonomous
touch acquisition is greater than one clock period of the AST source clock.
38.1.6 aWire
1. aWire MEMORY_SPEED_REQUEST command does not return correct CV
The aWire MEMORY_SPEED_REQUEST command does not return a CV corresponding to
the formula in the aWire Debug Interface chapter.
Fix/Workaround
Issue a dummy read to address 0x100000000 before issuing the
MEMORY_SPEED_REQUEST command and use this formula instead:
38.2 Flash
1. Corrupted data in flash may happen after flash page write operations
After a flash page write operation from an external programmer, reading (data read or code
fetch) in flash may fail. This may lead to an exception or to others errors derived from this
corrupted read access.
Fix/Workaround
Before any flash page write operation, each write in the page buffer must preceded by a
write in the page buffer with 0xFFFF_FFFF content at any address in the page.
38.3 Rev. B
38.3.1 SCIF
1. The RC32K output on PA20 is not always permanently disabled
The RC32K output on PA20 may sometimes re-appear.
Fix/Workaround
Before using RC32K for other purposes, the following procedure has to be followed in order
to properly disable it:
- Run the CPU on RCSYS
- Disable the output to PA20 by writing a zero to PM.PPCR.RC32OUT
- Enable RC32K by writing a one to SCIF.RC32KCR.EN, and wait for this bit to be read as
one
f
sab
7f
aw
CV – 3 = ----------------
943
32142D–06/2013
ATUC64/128/256L3/4U
- Disable RC32K by writing a zero to SCIF.RC32KCR.EN, and wait for this bit to be read as
zero.
2. PLLCOUNT value larger than zero can cause PLLEN glitch
Initializing the PLLCOUNT with a value greater than zero creates a glitch on the PLLEN signal
during asynchronous wake up.
Fix/Workaround
The lock-masking mechanism for the PLL should not be used.
The PLLCOUNT field of the PLL Control Register should always be written to zero.
3. Writing 0x5A5A5A5A to the SCIF memory range will enable the SCIF UNLOCK feature
The SCIF UNLOCK feature will be enabled if the value 0x5A5A5A5A is written to any location
in the SCIF memory range.
Fix/Workaround
None.
38.3.2 WDT
1. WDT Control Register does not have synchronization feedback
When writing to the Timeout Prescale Select (PSEL), Time Ban Prescale Select (TBAN),
Enable (EN), or WDT Mode (MODE) fieldss of the WDT Control Register (CTRL), a synchronizer
is started to propagate the values to the WDT clcok domain. This synchronization
takes a finite amount of time, but only the status of the synchronization of the EN bit is
reflected back to the user. Writing to the synchronized fields during synchronization can lead
to undefined behavior.
Fix/Workaround
-When writing to the affected fields, the user must ensure a wait corresponding to 2 clock
cycles of both the WDT peripheral bus clock and the selected WDT clock source.
-When doing writes that changes the EN bit, the EN bit can be read back until it reflects the
written value.
38.3.3 SPI
1. SPI data transfer hangs with CSR0.CSAAT==1 and MR.MODFDIS==0
When CSR0.CSAAT==1 and mode fault detection is enabled (MR.MODFDIS==0), the SPI
module will not start a data transfer.
Fix/Workaround
Disable mode fault detection by writing a one to MR.MODFDIS.
2. Disabling SPI has no effect on the SR.TDRE bit
Disabling SPI has no effect on the SR.TDRE bit whereas the write data command is filtered
when SPI is disabled. Writing to TDR when SPI is disabled will not clear SR.TDRE. If SPI is
disabled during a PDCA transfer, the PDCA will continue to write data to TDR until its buffer
is empty, and this data will be lost.
Fix/Workaround
Disable the PDCA, add two NOPs, and disable the SPI. To continue the transfer, enable the
SPI and PDCA.
3. SPI disable does not work in SLAVE mode
SPI disable does not work in SLAVE mode.
Fix/Workaround
Read the last received data, then perform a software reset by writing a one to the Software
Reset bit in the Control Register (CR.SWRST).
944
32142D–06/2013
ATUC64/128/256L3/4U
4. SPI bad serial clock generation on 2nd chip_select when SCBR=1, CPOL=1, and
NCPHA=0
When multiple chip selects (CS) are in use, if one of the baudrates equal 1 while one
(CSRn.SCBR=1) of the others do not equal 1, and CSRn.CPOL=1 and CSRn.NCPHA=0,
then an additional pulse will be generated on SCK.
Fix/Workaround
When multiple CS are in use, if one of the baudrates equals 1, the others must also equal 1
if CSRn.CPOL=1 and CSRn.NCPHA=0.
5. SPI mode fault detection enable causes incorrect behavior
When mode fault detection is enabled (MR.MODFDIS==0), the SPI module may not operate
properly.
Fix/Workaround
Always disable mode fault detection before using the SPI by writing a one to MR.MODFDIS.
6. SPI RDR.PCS is not correct
The PCS (Peripheral Chip Select) field in the SPI RDR (Receive Data Register) does not
correctly indicate the value on the NPCS pins at the end of a transfer.
Fix/Workaround
Do not use the PCS field of the SPI RDR.
38.3.4 TWI
1. TWIS may not wake the device from sleep mode
If the CPU is put to a sleep mode (except Idle and Frozen) directly after a TWI Start condition,
the CPU may not wake upon a TWIS address match. The request is NACKed.
Fix/Workaround
When using the TWI address match to wake the device from sleep, do not switch to sleep
modes deeper than Frozen. Another solution is to enable asynchronous EIC wake on the
TWIS clock (TWCK) or TWIS data (TWD) pins, in order to wake the system up on bus
events.
2. SMBALERT bit may be set after reset
The SMBus Alert (SMBALERT) bit in the Status Register (SR) might be erroneously set after
system reset.
Fix/Workaround
After system reset, clear the SR.SMBALERT bit before commencing any TWI transfer.
3. Clearing the NAK bit before the BTF bit is set locks up the TWI bus
When the TWIS is in transmit mode, clearing the NAK Received (NAK) bit of the Status Register
(SR) before the end of the Acknowledge/Not Acknowledge cycle will cause the TWIS to
attempt to continue transmitting data, thus locking up the bus.
Fix/Workaround
Clear SR.NAK only after the Byte Transfer Finished (BTF) bit of the same register has been
set.
38.3.5 PWMA
1. The SR.READY bit cannot be cleared by writing to SCR.READY
The Ready bit in the Status Register will not be cleared when writing a one to the corresponding
bit in the Status Clear register. The Ready bit will be cleared when the Busy bit is
set.
Fix/Workaround
945
32142D–06/2013
ATUC64/128/256L3/4U
Disable the Ready interrupt in the interrupt handler when receiving the interrupt. When an
operation that triggers the Busy/Ready bit is started, wait until the ready bit is low in the Status
Register before enabling the interrupt.
38.3.6 TC
1. Channel chaining skips first pulse for upper channel
When chaining two channels using the Block Mode Register, the first pulse of the clock
between the channels is skipped.
Fix/Workaround
Configure the lower channel with RA = 0x1 and RC = 0x2 to produce a dummy clock cycle
for the upper channel. After the dummy cycle has been generated, indicated by the
SR.CPCS bit, reconfigure the RA and RC registers for the lower channel with the real
values.
38.3.7 CAT
1. CAT QMatrix sense capacitors discharged prematurely
At the end of a QMatrix burst charging sequence that uses different burst count values for
different Y lines, the Y lines may be incorrectly grounded for up to n-1 periods of the peripheral
bus clock, where n is the ratio of the PB clock frequency to the GCLK_CAT frequency.
This results in premature loss of charge from the sense capacitors and thus increased variability
of the acquired count values.
Fix/Workaround
Enable the 1kOhm drive resistors on all implemented QMatrix Y lines (CSA 1, 3, 5, 7, 9, 11,
13, and/or 15) by writing ones to the corresponding odd bits of the CSARES register.
2. Autonomous CAT acquisition must be longer than AST source clock period
When using the AST to trigger CAT autonomous touch acquisition in sleep modes where the
CAT bus clock is turned off, the CAT will start several acquisitions if the period of the AST
source clock is larger than one CAT acquisition. One AST clock period after the AST trigger,
the CAT clock will automatically stop and the CAT acquisition can be stopped prematurely,
ruining the result.
Fix/Workaround
Always ensure that the ATCFG1.max field is set so that the duration of the autonomous
touch acquisition is greater than one clock period of the AST source clock.
3. CAT consumes unnecessary power when disabled or when autonomous touch not
used
A CAT prescaler controlled by the ATCFG0.DIV field will be active even when the CAT module
is disabled or when the autonomous touch feature is not used, thereby causing
unnecessary power consumption.
Fix/Workaround
If the CAT module is not used, disable the CLK_CAT clock in the PM module. If the CAT
module is used but the autonomous touch feature is not used, the power consumption of the
CAT module may be reduced by writing 0xFFFF to the ATCFG0.DIV field.
38.3.8 aWire
1. aWire MEMORY_SPEED_REQUEST command does not return correct CV
The aWire MEMORY_SPEED_REQUEST command does not return a CV corresponding to
the formula in the aWire Debug Interface chapter.
Fix/Workaround
946
32142D–06/2013
ATUC64/128/256L3/4U
Issue a dummy read to address 0x100000000 before issuing the
MEMORY_SPEED_REQUEST command and use this formula instead:
38.4 Flash
2. Corrupted data in flash may happen after flash page write operations
After a flash page write operation from an external programmer, reading (data read or code
fetch) in flash may fail. This may lead to an exception or to others errors derived from this
corrupted read access.
Fix/Workaround
Before any flash page write operation, each write in the page buffer must preceded by a
write in the page buffer with 0xFFFF_FFFF content at any address in the page.
38.5 Rev. A
38.5.1 Device
3. JTAGID is wrong
The JTAGID reads 0x021DF03F for all devices.
Fix/Workaround
None.
38.5.2 FLASHCDW
1. General-purpose fuse programming does not work
The general-purpose fuses cannot be programmed and are stuck at 1. Please refer to the
Fuse Settings chapter in the FLASHCDW for more information about what functions are
affected.
Fix/Workaround
None.
2. Set Security Bit command does not work
The Set Security Bit (SSB) command of the FLASHCDW does not work. The device cannot
be locked from external JTAG, aWire, or other debug accesses.
Fix/Workaround
None.
3. Flash programming time is longer than specified
f
sab
7f
aw
CV – 3 = ----------------
947
32142D–06/2013
ATUC64/128/256L3/4U
The flash programming time is now:
Fix/Workaround
None.
4. Power Manager
5. Clock Failure Detector (CFD) can be issued while turning off the CFD
While turning off the CFD, the CFD bit in the Status Register (SR) can be set. This will
change the main clock source to RCSYS.
Fix/Workaround
Solution 1: Enable CFD interrupt. If CFD interrupt is issues after turning off the CFD, switch
back to original main clock source.
Solution 2: Only turn off the CFD while running the main clock on RCSYS.
6. Sleepwalking in idle and frozen sleep mode will mask all other PB clocks
If the CPU is in idle or frozen sleep mode and a module is in a state that triggers sleep walking,
all PB clocks will be masked except the PB clock to the sleepwalking module.
Fix/Workaround
Mask all clock requests in the PM.PPCR register before going into idle or frozen mode.
4. Unused PB clocks are running
Three unused PBA clocks are enabled by default and will cause increased active power
consumption.
Fix/Workaround
Disable the clocks by writing zeroes to bits [27:25] in the PBA clock mask register.
38.5.3 SCIF
1. The RC32K output on PA20 is not always permanently disabled
The RC32K output on PA20 may sometimes re-appear.
Fix/Workaround
Before using RC32K for other purposes, the following procedure has to be followed in order
to properly disable it:
- Run the CPU on RCSYS
- Disable the output to PA20 by writing a zero to PM.PPCR.RC32OUT
- Enable RC32K by writing a one to SCIF.RC32KCR.EN, and wait for this bit to be read as
one
- Disable RC32K by writing a zero to SCIF.RC32KCR.EN, and wait for this bit to be read as
zero.
2. PLL lock might not clear after disable
Table 38-1. Flash Characteristics
Symbol Parameter Conditions Min Typ Max Unit
TFPP Page programming time
fCLK_HSB= 50MHz
7.5
ms
TFPE Page erase time 7.5
TFFP Fuse programming time 1
TFEA Full chip erase time (EA) 9
TFCE
JTAG chip erase time
(CHIP_ERASE) fCLK_HSB= 115kHz 250
948
32142D–06/2013
ATUC64/128/256L3/4U
Under certain circumstances, the lock signal from the Phase Locked Loop (PLL) oscillator
may not go back to zero after the PLL oscillator has been disabled. This can cause the propagation
of clock signals with the wrong frequency to parts of the system that use the PLL
clock.
Fix/Workaround
PLL must be turned off before entering STOP, DEEPSTOP or STATIC sleep modes. If PLL
has been turned off, a delay of 30us must be observed after the PLL has been enabled
again before the SCIF.PLL0LOCK bit can be used as a valid indication that the PLL is
locked.
3. PLLCOUNT value larger than zero can cause PLLEN glitch
Initializing the PLLCOUNT with a value greater than zero creates a glitch on the PLLEN signal
during asynchronous wake up.
Fix/Workaround
The lock-masking mechanism for the PLL should not be used.
The PLLCOUNT field of the PLL Control Register should always be written to zero.
4. RCSYS is not calibrated
The RCSYS is not calibrated and will run faster than 115.2kHz. Frequencies around 150kHz
can be expected.
Fix/Workaround
If a known clock source is available the RCSYS can be runtime calibrated by using the frequency
meter (FREQM) and tuning the RCSYS by writing to the RCCR register in SCIF.
5. Writing 0x5A5A5A5A to the SCIF memory range will enable the SCIF UNLOCK feature
The SCIF UNLOCK feature will be enabled if the value 0x5A5A5A5A is written to any location
in the SCIF memory range.
Fix/Workaround
None.
38.5.4 WDT
1. Clearing the Watchdog Timer (WDT) counter in second half of timeout period will
issue a Watchdog reset
If the WDT counter is cleared in the second half of the timeout period, the WDT will immediately
issue a Watchdog reset.
Fix/Workaround
Use twice as long timeout period as needed and clear the WDT counter within the first half
of the timeout period. If the WDT counter is cleared after the first half of the timeout period,
you will get a Watchdog reset immediately. If the WDT counter is not cleared at all, the time
before the reset will be twice as long as needed.
2. WDT Control Register does not have synchronization feedback
When writing to the Timeout Prescale Select (PSEL), Time Ban Prescale Select (TBAN),
Enable (EN), or WDT Mode (MODE) fieldss of the WDT Control Register (CTRL), a synchronizer
is started to propagate the values to the WDT clcok domain. This synchronization
takes a finite amount of time, but only the status of the synchronization of the EN bit is
reflected back to the user. Writing to the synchronized fields during synchronization can lead
to undefined behavior.
Fix/Workaround
-When writing to the affected fields, the user must ensure a wait corresponding to 2 clock
cycles of both the WDT peripheral bus clock and the selected WDT clock source.
-When doing writes that changes the EN bit, the EN bit can be read back until it reflects the
written value.
949
32142D–06/2013
ATUC64/128/256L3/4U
38.5.5 GPIO
1. Clearing Interrupt flags can mask other interrupts
When clearing interrupt flags in a GPIO port, interrupts on other pins of that port, happening
in the same clock cycle will not be registered.
Fix/Workaround
Read the PVR register of the port before and after clearing the interrupt to see if any pin
change has happened while clearing the interrupt. If any change occurred in the PVR
between the reads, they must be treated as an interrupt.
38.5.6 SPI
1. SPI data transfer hangs with CSR0.CSAAT==1 and MR.MODFDIS==0
When CSR0.CSAAT==1 and mode fault detection is enabled (MR.MODFDIS==0), the SPI
module will not start a data transfer.
Fix/Workaround
Disable mode fault detection by writing a one to MR.MODFDIS.
2. Disabling SPI has no effect on the SR.TDRE bit
Disabling SPI has no effect on the SR.TDRE bit whereas the write data command is filtered
when SPI is disabled. Writing to TDR when SPI is disabled will not clear SR.TDRE. If SPI is
disabled during a PDCA transfer, the PDCA will continue to write data to TDR until its buffer
is empty, and this data will be lost.
Fix/Workaround
Disable the PDCA, add two NOPs, and disable the SPI. To continue the transfer, enable the
SPI and PDCA.
3. SPI disable does not work in SLAVE mode
SPI disable does not work in SLAVE mode.
Fix/Workaround
Read the last received data, then perform a software reset by writing a one to the Software
Reset bit in the Control Register (CR.SWRST).
4. SPI bad serial clock generation on 2nd chip_select when SCBR=1, CPOL=1, and
NCPHA=0
When multiple chip selects (CS) are in use, if one of the baudrates equal 1 while one
(CSRn.SCBR=1) of the others do not equal 1, and CSRn.CPOL=1 and CSRn.NCPHA=0,
then an additional pulse will be generated on SCK.
Fix/Workaround
When multiple CS are in use, if one of the baudrates equals 1, the others must also equal 1
if CSRn.CPOL=1 and CSRn.NCPHA=0.
5. SPI mode fault detection enable causes incorrect behavior
When mode fault detection is enabled (MR.MODFDIS==0), the SPI module may not operate
properly.
Fix/Workaround
Always disable mode fault detection before using the SPI by writing a one to MR.MODFDIS.
6. SPI RDR.PCS is not correct
The PCS (Peripheral Chip Select) field in the SPI RDR (Receive Data Register) does not
correctly indicate the value on the NPCS pins at the end of a transfer.
Fix/Workaround
Do not use the PCS field of the SPI RDR.
950
32142D–06/2013
ATUC64/128/256L3/4U
38.5.7 TWI
1. TWIS may not wake the device from sleep mode
If the CPU is put to a sleep mode (except Idle and Frozen) directly after a TWI Start condition,
the CPU may not wake upon a TWIS address match. The request is NACKed.
Fix/Workaround
When using the TWI address match to wake the device from sleep, do not switch to sleep
modes deeper than Frozen. Another solution is to enable asynchronous EIC wake on the
TWIS clock (TWCK) or TWIS data (TWD) pins, in order to wake the system up on bus
events.
2. SMBALERT bit may be set after reset
The SMBus Alert (SMBALERT) bit in the Status Register (SR) might be erroneously set after
system reset.
Fix/Workaround
After system reset, clear the SR.SMBALERT bit before commencing any TWI transfer.
3. Clearing the NAK bit before the BTF bit is set locks up the TWI bus
When the TWIS is in transmit mode, clearing the NAK Received (NAK) bit of the Status Register
(SR) before the end of the Acknowledge/Not Acknowledge cycle will cause the TWIS to
attempt to continue transmitting data, thus locking up the bus.
Fix/Workaround
Clear SR.NAK only after the Byte Transfer Finished (BTF) bit of the same register has been
set.
4. TWIS stretch on Address match error
When the TWIS stretches TWCK due to a slave address match, it also holds TWD low for
the same duration if it is to be receiving data. When TWIS releases TWCK, it releases TWD
at the same time. This can cause a TWI timing violation.
Fix/Workaround
None.
5. TWIM TWALM polarity is wrong
The TWALM signal in the TWIM is active high instead of active low.
Fix/Workaround
Use an external inverter to invert the signal going into the TWIM. When using both TWIM
and TWIS on the same pins, the TWALM cannot be used.
38.5.8 PWMA
1. The SR.READY bit cannot be cleared by writing to SCR.READY
The Ready bit in the Status Register will not be cleared when writing a one to the corresponding
bit in the Status Clear register. The Ready bit will be cleared when the Busy bit is
set.
Fix/Workaround
Disable the Ready interrupt in the interrupt handler when receiving the interrupt. When an
operation that triggers the Busy/Ready bit is started, wait until the ready bit is low in the Status
Register before enabling the interrupt.
38.5.9 TC
1. Channel chaining skips first pulse for upper channel
When chaining two channels using the Block Mode Register, the first pulse of the clock
between the channels is skipped.
951
32142D–06/2013
ATUC64/128/256L3/4U
Fix/Workaround
Configure the lower channel with RA = 0x1 and RC = 0x2 to produce a dummy clock cycle
for the upper channel. After the dummy cycle has been generated, indicated by the
SR.CPCS bit, reconfigure the RA and RC registers for the lower channel with the real
values.
38.5.10 ADCIFB
1. ADCIFB DMA transfer does not work with divided PBA clock
DMA requests from the ADCIFB will not be performed when the PBA clock is slower than
the HSB clock.
Fix/Workaround
Do not use divided PBA clock when the PDCA transfers from the ADCIFB.
38.5.11 CAT
1. CAT QMatrix sense capacitors discharged prematurely
At the end of a QMatrix burst charging sequence that uses different burst count values for
different Y lines, the Y lines may be incorrectly grounded for up to n-1 periods of the peripheral
bus clock, where n is the ratio of the PB clock frequency to the GCLK_CAT frequency.
This results in premature loss of charge from the sense capacitors and thus increased variability
of the acquired count values.
Fix/Workaround
Enable the 1kOhm drive resistors on all implemented QMatrix Y lines (CSA 1, 3, 5, 7, 9, 11,
13, and/or 15) by writing ones to the corresponding odd bits of the CSARES register.
2. Autonomous CAT acquisition must be longer than AST source clock period
When using the AST to trigger CAT autonomous touch acquisition in sleep modes where the
CAT bus clock is turned off, the CAT will start several acquisitions if the period of the AST
source clock is larger than one CAT acquisition. One AST clock period after the AST trigger,
the CAT clock will automatically stop and the CAT acquisition can be stopped prematurely,
ruining the result.
Fix/Workaround
Always ensure that the ATCFG1.max field is set so that the duration of the autonomous
touch acquisition is greater than one clock period of the AST source clock.
3. CAT consumes unnecessary power when disabled or when autonomous touch not
used
A CAT prescaler controlled by the ATCFG0.DIV field will be active even when the CAT module
is disabled or when the autonomous touch feature is not used, thereby causing
unnecessary power consumption.
Fix/Workaround
If the CAT module is not used, disable the CLK_CAT clock in the PM module. If the CAT
module is used but the autonomous touch feature is not used, the power consumption of the
CAT module may be reduced by writing 0xFFFF to the ATCFG0.DIV field.
4. CAT module does not terminate QTouch burst on detect
The CAT module does not terminate a QTouch burst when the detection voltage is
reached on the sense capacitor. This can cause the sense capacitor to be charged more
than necessary. Depending on the dielectric absorption characteristics of the capacitor, this
can lead to unstable measurements.
Fix/Workaround
Use the minimum possible value for the MAX field in the ATCFG1, TG0CFG1, and
TG1CFG1 registers.
952
32142D–06/2013
ATUC64/128/256L3/4U
38.5.12 aWire
1. aWire MEMORY_SPEED_REQUEST command does not return correct CV
The aWire MEMORY_SPEED_REQUEST command does not return a CV corresponding to
the formula in the aWire Debug Interface chapter.
Fix/Workaround
Issue a dummy read to address 0x100000000 before issuing the
MEMORY_SPEED_REQUEST command and use this formula instead:
38.5.13 Flash
5. Corrupted data in flash may happen after flash page write operations
After a flash page write operation from an external programmer, reading (data read or code
fetch) in flash may fail. This may lead to an exception or to others errors derived from this
corrupted read access.
Fix/Workaround
Before any flash page write operation, each write in the page buffer must preceded by a
write in the page buffer with 0xFFFF_FFFF content at any address in the page.
38.5.14 I/O Pins
1. PA05 is not 3.3V tolerant.
PA05 should be grounded on the PCB and left unused if VDDIO is above 1.8V.
Fix/Workaround
None.
2. No pull-up on pins that are not bonded
PB13 to PB27 are not bonded on UC3L0256/128, but has no pull-up and can cause current
consumption on VDDIO/VDDIN if left undriven.
Fix/Workaround
Enable pull-ups on PB13 to PB27 by writing 0x0FFFE000 to the PUERS1 register in the
GPIO.
3. PA17 has low ESD tolerance
PA17 only tolerates 500V ESD pulses (Human Body Model).
Fix/Workaround
Care must be taken during manufacturing and PCB design.
f
sab
7f
aw
CV – 3 = ----------------
953
32142D–06/2013
ATUC64/128/256L3/4U
39. Datasheet Revision History
Please note that the referring page numbers in this section are referred to this document. The
referring revision in this section are referring to the document revision.
39.1 Rev. D – 06/2013
39.2 Rev. C – 01/2012
39.3 Rev. B – 12/2011
39.4 Rev. A – 12/2011
1. Updated the datasheet with a new ATmel blue logo and the last page.
2. Added Flash errata.
1. Description: DFLL frequency is 20 to 150MHz, not 40 to 150MHz.
2. Block Diagram: GCLK_IN is input, not output. CAT SMP corrected from I/O to output. SPI
NPCS corrected from output to I/O.
3, Package and Pinout: EXTINT0 in Signal Descriptions table is NMI.
4, Supply and Startup Considerations: In 1.8V single supply mode figure, the input voltage is
1.62-1.98V, not 1.98-3.6V. “On system start-up, the DFLL is disabled” is replaced by “On
system start-up, all high-speed clocks are disabled”.
5, ADCIFB: PRND signal removed from block diagram.
6, Electrical Charateristics: Added 64-pin package information to I/O Pin Characteristics tables
and Digital Clock Characteristics table.
7, Mechanical Characteristics: QFN48 Package Drawing updated. Note that the package drawing
for QFN48 is correct in datasheet rev A, but wrong in rev B. Added notes to package drawings.
8. Summary: Removed Programming and Debugging chapter, added Processor and Architecture
chapter.
1. JTAG Data Registers subchapter added in the Programming and Debugging chapter,
containing JTAG IDs.
1. Initial revision.
i
32142D–06/2013
ATUC64/128/256L3/4U
Table of Contents
Features ..................................................................................................... 1
1 Description ............................................................................................... 3
2 Overview ................................................................................................... 5
2.1 Block Diagram ...................................................................................................5
2.2 Configuration Summary .....................................................................................6
3 Package and Pinout ................................................................................. 7
3.1 Package .............................................................................................................7
3.2 See Section 3.3 for a description of the various peripheral signals. ................12
3.3 Signal Descriptions ..........................................................................................15
3.4 I/O Line Considerations ...................................................................................18
4 Processor and Architecture .................................................................. 21
4.1 Features ..........................................................................................................21
4.2 AVR32 Architecture .........................................................................................21
4.3 The AVR32UC CPU ........................................................................................22
4.4 Programming Model ........................................................................................26
4.5 Exceptions and Interrupts ................................................................................30
5 Memories ................................................................................................ 35
5.1 Embedded Memories ......................................................................................35
5.2 Physical Memory Map .....................................................................................35
5.3 Peripheral Address Map ..................................................................................36
5.4 CPU Local Bus Mapping .................................................................................37
6 Supply and Startup Considerations ..................................................... 39
6.1 Supply Considerations .....................................................................................39
6.2 Startup Considerations ....................................................................................44
7 Peripheral DMA Controller (PDCA) ...................................................... 45
7.1 Features ..........................................................................................................45
7.2 Overview ..........................................................................................................45
7.3 Block Diagram .................................................................................................46
7.4 Product Dependencies ....................................................................................46
7.5 Functional Description .....................................................................................47
7.6 Performance Monitors .....................................................................................49
7.7 User Interface ..................................................................................................51
ii
32142D–06/2013
ATUC64/128/256L3/4U
7.8 Module Configuration ......................................................................................79
8 USB Interface (USBC) ............................................................................ 81
8.1 Features ..........................................................................................................81
8.2 Overview ..........................................................................................................81
8.3 Block Diagram .................................................................................................81
8.4 I/O Lines Description .......................................................................................83
8.5 Product Dependencies ....................................................................................84
8.6 Functional Description .....................................................................................85
8.7 User Interface ...............................................................................................101
8.8 Module Configuration ....................................................................................134
9 Flash Controller (FLASHCDW) ........................................................... 135
9.1 Features ........................................................................................................135
9.2 Overview ........................................................................................................135
9.3 Product Dependencies ..................................................................................135
9.4 Functional Description ...................................................................................136
9.5 Flash Commands ..........................................................................................141
9.6 General-purpose Fuse Bits ............................................................................143
9.7 Security Bit ....................................................................................................146
9.8 User Interface ................................................................................................147
9.9 Fuse Settings .................................................................................................157
9.10 Serial Number ................................................................................................160
9.11 Module Configuration ....................................................................................160
10 Secure Access Unit (SAU) .................................................................. 162
10.1 Features ........................................................................................................162
10.2 Overview ........................................................................................................162
10.3 Block Diagram ...............................................................................................163
10.4 Product Dependencies ..................................................................................164
10.5 Functional Description ...................................................................................164
10.6 User Interface ................................................................................................168
10.7 Module Configuration ....................................................................................183
11 HSB Bus Matrix (HMATRIXB) .............................................................. 184
11.1 Features ........................................................................................................184
11.2 Overview ........................................................................................................184
11.3 Product Dependencies ..................................................................................184
11.4 Functional Description ...................................................................................184
iii
32142D–06/2013
ATUC64/128/256L3/4U
11.5 User Interface ................................................................................................188
11.6 Module Configuration ....................................................................................196
12 Interrupt Controller (INTC) .................................................................. 198
12.1 Features ........................................................................................................198
12.2 Overview ........................................................................................................198
12.3 Block Diagram ...............................................................................................198
12.4 Product Dependencies ..................................................................................199
12.5 Functional Description ...................................................................................199
12.6 User Interface ................................................................................................202
12.7 Module Configuration ....................................................................................206
12.8 Interrupt Request Signal Map ........................................................................206
13 Power Manager (PM) ............................................................................ 209
13.1 Features ........................................................................................................209
13.2 Overview ........................................................................................................209
13.3 Block Diagram ...............................................................................................210
13.4 I/O Lines Description .....................................................................................210
13.5 Product Dependencies ..................................................................................210
13.6 Functional Description ...................................................................................211
13.7 User Interface ................................................................................................220
13.8 Module Configuration ....................................................................................243
14 System Control Interface (SCIF) ......................................................... 244
14.1 Features ........................................................................................................244
14.2 Overview ........................................................................................................244
14.3 I/O Lines Description .....................................................................................244
14.4 Product Dependencies ..................................................................................244
14.5 Functional Description ...................................................................................245
14.6 User Interface ................................................................................................265
14.7 Module Configuration ....................................................................................318
15 Asynchronous Timer (AST) ................................................................ 322
15.1 Features ........................................................................................................322
15.2 Overview ........................................................................................................322
15.3 Block Diagram ...............................................................................................323
15.4 Product Dependencies ..................................................................................323
15.5 Functional Description ...................................................................................324
15.6 User Interface ................................................................................................330
iv
32142D–06/2013
ATUC64/128/256L3/4U
15.7 Module Configuration ....................................................................................351
16 Watchdog Timer (WDT) ....................................................................... 352
16.1 Features ........................................................................................................352
16.2 Overview ........................................................................................................352
16.3 Block Diagram ...............................................................................................352
16.4 Product Dependencies ..................................................................................352
16.5 Functional Description ...................................................................................353
16.6 User Interface ................................................................................................358
16.7 Module Configuration ....................................................................................364
17 External Interrupt Controller (EIC) ..................................................... 365
17.1 Features ........................................................................................................365
17.2 Overview ........................................................................................................365
17.3 Block Diagram ...............................................................................................365
17.4 I/O Lines Description .....................................................................................366
17.5 Product Dependencies ..................................................................................366
17.6 Functional Description ...................................................................................366
17.7 User Interface ................................................................................................370
17.8 Module Configuration ....................................................................................386
18 Frequency Meter (FREQM) .................................................................. 387
18.1 Features ........................................................................................................387
18.2 Overview ........................................................................................................387
18.3 Block Diagram ...............................................................................................387
18.4 Product Dependencies ..................................................................................387
18.5 Functional Description ...................................................................................388
18.6 User Interface ................................................................................................390
18.7 Module Configuration ....................................................................................401
19 General-Purpose Input/Output Controller (GPIO) ............................. 403
19.1 Features ........................................................................................................403
19.2 Overview ........................................................................................................403
19.3 Block Diagram ...............................................................................................403
19.4 I/O Lines Description .....................................................................................404
19.5 Product Dependencies ..................................................................................404
19.6 Functional Description ...................................................................................405
19.7 User Interface ................................................................................................410
19.8 Module Configuration ....................................................................................433
v
32142D–06/2013
ATUC64/128/256L3/4U
20 Universal Synchronous Asynchronous Receiver Transmitter (USART)
434
20.1 Features ........................................................................................................434
20.2 Overview ........................................................................................................434
20.3 Block Diagram ...............................................................................................435
20.4 I/O Lines Description ....................................................................................436
20.5 Product Dependencies ..................................................................................436
20.6 Functional Description ...................................................................................437
20.7 User Interface ................................................................................................463
20.8 Module Configuration ....................................................................................485
21 Serial Peripheral Interface (SPI) ......................................................... 486
21.1 Features ........................................................................................................486
21.2 Overview ........................................................................................................486
21.3 Block Diagram ...............................................................................................487
21.4 Application Block Diagram .............................................................................487
21.5 I/O Lines Description .....................................................................................488
21.6 Product Dependencies ..................................................................................488
21.7 Functional Description ...................................................................................488
21.8 User Interface ................................................................................................499
21.9 Module Configuration ....................................................................................526
22 Two-wire Master Interface (TWIM) ...................................................... 527
22.1 Features ........................................................................................................527
22.2 Overview ........................................................................................................527
22.3 List of Abbreviations ......................................................................................528
22.4 Block Diagram ...............................................................................................528
22.5 Application Block Diagram .............................................................................529
22.6 I/O Lines Description .....................................................................................529
22.7 Product Dependencies ..................................................................................529
22.8 Functional Description ...................................................................................531
22.9 User Interface ................................................................................................543
22.10 Module Configuration ....................................................................................560
23 Two-wire Slave Interface (TWIS) ......................................................... 561
23.1 Features ........................................................................................................561
23.2 Overview ........................................................................................................561
23.3 List of Abbreviations ......................................................................................562
vi
32142D–06/2013
ATUC64/128/256L3/4U
23.4 Block Diagram ...............................................................................................562
23.5 Application Block Diagram .............................................................................563
23.6 I/O Lines Description .....................................................................................563
23.7 Product Dependencies ..................................................................................563
23.8 Functional Description ...................................................................................564
23.9 User Interface ................................................................................................574
23.10 Module Configuration ....................................................................................590
24 Inter-IC Sound Controller (IISC) .......................................................... 591
24.1 Features ........................................................................................................591
24.2 Overview ........................................................................................................591
24.3 Block Diagram ...............................................................................................592
24.4 I/O Lines Description .....................................................................................592
24.5 Product Dependencies ..................................................................................592
24.6 Functional Description ...................................................................................593
24.7 IISC Application Examples ............................................................................598
24.8 User Interface ................................................................................................600
24.9 Module configuration .....................................................................................614
25 Pulse Width Modulation Controller (PWMA) ..................................... 615
25.1 Features ........................................................................................................615
25.2 Overview ........................................................................................................615
25.3 Block Diagram ...............................................................................................616
25.4 I/O Lines Description .....................................................................................616
25.5 Product Dependencies ..................................................................................616
25.6 Functional Description ...................................................................................617
25.7 User Interface ................................................................................................623
25.8 Module Configuration ....................................................................................641
26 Timer/Counter (TC) .............................................................................. 642
26.1 Features ........................................................................................................642
26.2 Overview ........................................................................................................642
26.3 Block Diagram ...............................................................................................643
26.4 I/O Lines Description .....................................................................................643
26.5 Product Dependencies ..................................................................................643
26.6 Functional Description ...................................................................................644
26.7 User Interface ................................................................................................659
26.8 Module Configuration ....................................................................................682
vii
32142D–06/2013
ATUC64/128/256L3/4U
27 Peripheral Event System ..................................................................... 683
27.1 Features ........................................................................................................683
27.2 Overview ........................................................................................................683
27.3 Peripheral Event System Block Diagram .......................................................683
27.4 Functional Description ...................................................................................683
27.5 Application Example ......................................................................................686
28 Audio Bit Stream DAC (ABDACB) ...................................................... 687
28.1 Features ........................................................................................................687
28.2 Overview ........................................................................................................687
28.3 Block Diagram ...............................................................................................687
28.4 I/O Lines Description .....................................................................................688
28.5 Product Dependencies ..................................................................................688
28.6 Functional Description ...................................................................................689
28.7 User Interface ................................................................................................696
28.8 Module Configuration ....................................................................................710
29 ADC Interface (ADCIFB) ...................................................................... 711
29.1 Features ........................................................................................................711
29.2 Overview ........................................................................................................711
29.3 Block Diagram ...............................................................................................712
29.4 I/O Lines Description .....................................................................................713
29.5 Product Dependencies ..................................................................................713
29.6 Functional Description ...................................................................................714
29.7 Resistive Touch Screen .................................................................................718
29.8 Operating Modes ...........................................................................................724
29.9 User Interface ................................................................................................726
29.10 Module Configuration ....................................................................................745
30 Analog Comparator Interface (ACIFB) ............................................... 746
30.1 Features ........................................................................................................746
30.2 Overview ........................................................................................................746
30.3 Block Diagram ...............................................................................................747
30.4 I/O Lines Description .....................................................................................747
30.5 Product Dependencies ..................................................................................748
30.6 Functional Description ...................................................................................749
30.7 Peripheral Event Triggers ..............................................................................754
30.8 AC Test mode ................................................................................................754
viii
32142D–06/2013
ATUC64/128/256L3/4U
30.9 User Interface ................................................................................................755
30.10 Module Configuration ....................................................................................769
31 Capacitive Touch Module (CAT) ......................................................... 770
31.1 Features ........................................................................................................770
31.2 Overview ........................................................................................................770
31.3 Block Diagram ...............................................................................................771
31.4 I/O Lines Description .....................................................................................771
31.5 Product Dependencies ..................................................................................772
31.6 Functional Description ...................................................................................774
31.7 User Interface ................................................................................................781
31.8 Module Configuration ....................................................................................816
32 Glue Logic Controller (GLOC) ............................................................ 817
32.1 Features ........................................................................................................817
32.2 Overview ........................................................................................................817
32.3 Block Diagram ...............................................................................................817
32.4 I/O Lines Description .....................................................................................818
32.5 Product Dependencies ..................................................................................818
32.6 Functional Description ...................................................................................818
32.7 User Interface ................................................................................................820
32.8 Module Configuration ....................................................................................825
33 aWire UART (AW) ................................................................................. 826
33.1 Features ........................................................................................................826
33.2 Overview ........................................................................................................826
33.3 Block Diagram ...............................................................................................826
33.4 I/O Lines Description .....................................................................................827
33.5 Product Dependencies ..................................................................................827
33.6 Functional Description ...................................................................................827
33.7 User Interface ................................................................................................830
33.8 Module Configuration ....................................................................................843
34 Programming and Debugging ............................................................ 844
34.1 Overview ........................................................................................................844
34.2 Service Access Bus .......................................................................................844
34.3 On-Chip Debug ..............................................................................................847
34.4 JTAG and Boundary-scan (JTAG) .................................................................855
34.5 JTAG Instruction Summary ...........................................................................863
ix
32142D–06/2013
ATUC64/128/256L3/4U
34.6 aWire Debug Interface (AW) .........................................................................880
35 Electrical Characteristics .................................................................... 897
35.1 Absolute Maximum Ratings* .........................................................................897
35.2 Supply Characteristics ...................................................................................897
35.3 Maximum Clock Frequencies ........................................................................898
35.4 Power Consumption ......................................................................................898
35.5 I/O Pin Characteristics ...................................................................................902
35.6 Oscillator Characteristics ...............................................................................905
35.7 Flash Characteristics .....................................................................................910
35.8 ABDACB Electrical Characteristics. .............................................................911
35.9 Analog Characteristics ...................................................................................912
35.10 Timing Characteristics ...................................................................................921
36 Mechanical Characteristics ................................................................. 931
36.1 Thermal Considerations ................................................................................931
36.2 Package Drawings .........................................................................................932
36.3 Soldering Profile ............................................................................................937
37 Ordering Information ........................................................................... 938
38 Errata ..................................................................................................... 940
38.1 Rev. C ............................................................................................................940
38.2 Flash ..............................................................................................................942
38.3 Rev. B ............................................................................................................942
38.4 Flash .............................................................................................................946
38.5 Rev. A ............................................................................................................946
39 Datasheet Revision History ................................................................ 953
39.1 Rev. D – 06/2013 ...........................................................................................953
39.2 Rev. C – 01/2012 ...........................................................................................953
39.3 Rev. B – 12/2011 ...........................................................................................953
39.4 Rev. A – 12/2011 ...........................................................................................953
Table of Contents....................................................................................... i
Atmel Corporation
1600 Technology Drive
San Jose, CA 95110
USA
Tel: (+1) (408) 441-0311
Fax: (+1) (408) 487-2600
www.atmel.com
Atmel Asia Limited
Unit 01-5 & 16, 19F
BEA Tower, Millennium City 5
418 Kwun Tong Roa
Kwun Tong, Kowloon
HONG KONG
Tel: (+852) 2245-6100
Fax: (+852) 2722-1369
Atmel Munich GmbH
Business Campus
Parkring 4
D-85748 Garching b. Munich
GERMANY
Tel: (+49) 89-31970-0
Fax: (+49) 89-3194621
Atmel Japan G.K.
16F Shin-Osaki Kangyo Bldg
1-6-4 Osaki, Shinagawa-ku
Tokyo 141-0032
JAPAN
Tel: (+81) (3) 6417-0300
Fax: (+81) (3) 6417-0370
© 2013 Atmel Corporation. All rights reserved. / Rev.: 32142D–AVR32–06/2013
Atmel®, logo and combinations thereof, AVR®, picoPower®, QTouch®, AKS® and others are registered trademarks or trademarks of Atmel Corporation
or its subsidiaries. Other terms and product names may be trademarks of others.
Disclaimer: The information in this document is provided in connection with Atmel products. No license, express or implied, by estoppel or otherwise, to any intellectual property right is granted by this
document or in connection with the sale of Atmel products. EXCEPT AS SET FORTH IN THE ATMEL TERMS AND CONDITIONS OF SALES LOCATED ON THE ATMEL WEBSITE, ATMEL ASSUMES
NO LIABILITY WHATSOEVER AND DISCLAIMS ANY EXPRESS, IMPLIED OR STATUTORY WARRANTY RELATING TO ITS PRODUCTS INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT,
CONSEQUENTIAL, PUNITIVE, SPECIAL OR INCIDENTAL DAMAGES (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS AND PROFITS, BUSINESS INTERRUPTION, OR LOSS OF
INFORMATION) ARISING OUT OF THE USE OR INABILITY TO USE THIS DOCUMENT, EVEN IF ATMEL HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. Atmel makes no
representations or warranties with respect to the accuracy or completeness of the contents of this document and reserves the right to make changes to specifications and products descriptions at any time
without notice. Atmel does not make any commitment to update the information contained herein. Unless specifically provided otherwise, Atmel products are not suitable for, and shall not be used in,
automotive applications. Atmel products are not intended, authorized, or warranted for use as components in applications intended to support or sustain life.
USB Demonstrations Help
MPLAB Harmony Integrated Software Framework
© 2013-2018 Microchip Technology Inc. All rights reserved.
Volume I: Getting Started With MPLAB Harmony Libraries and Applications
This volume introduces the MPLAB® Harmony Integrated Software Framework.
Description
MPLAB Harmony is a layered framework of modular libraries that provide flexible and interoperable software "building
blocks" for developing embedded PIC32 applications. MPLAB Harmony is also part of a broad and expandable
ecosystem, providing demonstration applications, third-party offerings, and convenient development tools, such as the
MPLAB Harmony Configurator (MHC), which integrate with the MPLAB X IDE and MPLAB XC32 language tools.
Legal Notices
Please review the Software License Agreement prior to using MPLAB Harmony. It is the responsibility of the end-user to know and understand the
software license agreement terms regarding the Microchip and third-party software that is provided in this installation. A copy of the agreement is
available in the /doc folder of your MPLAB Harmony installation.
The OPENRTOS® demonstrations provided in MPLAB Harmony use the OPENRTOS evaluation license, which is meant for demonstration
purposes only. Customers desiring development and production on OPENRTOS must procure a suitable license. Please refer to one of the
following documents, which are located in the /third_party/rtos/OPENRTOS/Documents folder of your MPLAB Harmony
installation, for information on obtaining an evaluation license for your device:
• OpenRTOS Click Thru Eval License PIC32MXxx.pdf
• OpenRTOS Click Thru Eval License PIC32MZxx.pdf
TIP!
Throughout this documentation, occurrences of refer to the default MPLAB Harmony installation path:
• Windows: C:/microchip/harmony/
• Mac OS/Linux: ~/microchip/harmony/
Volume I: Getting Started With MPLAB Harmony
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 2
Applications Help
This section provides information on the various application demonstrations that are included in MPLAB Harmony.
Description
Applications determine how MPLAB Harmony libraries (device drivers, middleware, and system services) are used to do something useful. In a
MPLAB Harmony system, there may be one main application, there may be multiple independent applications or there may be one or more
Operating System (OS) specific applications. Applications interact with MPLAB Harmony libraries through well defined interfaces. Applications may
operate in a strictly polling environment, they may be interrupt driven, they may be executed in OS-specific threads, or they may be written so as to
be flexible and easily configured for any of these environments. Applications generally fit into one of the following categories.
Demonstration Applications
Demonstration applications are provided (with MPLAB Harmony or in separate installations) to demonstrate typical or interesting usage models of
one or more MPLAB Harmony libraries. Demonstration applications can demonstrate realistic solutions to real-life problems.
Sample Applications
Sample applications are extremely simple applications provided with MPLAB Harmony as examples of how to use individual features of a library.
They will not normally accomplish anything useful on their own. They are provided primarily as documentation to show how to use a library.
USB Demonstrations
This section provides descriptions of the USB demonstrations.
MPLAB Harmony is available for download from the Microchip website by visiting: http://www.microchip.com/mplabharmony. Once you are on the
site, click the Downloads tab to access the appropriate download for your operating system. For additional information on this demonstration, refer
to the “Applications Help” section in the MPLAB Harmony Help.
Introduction
USB Library Demonstration Applications Help
Description
This distribution package contains a variety of USB-related firmware projects that demonstrate the capabilities of the MPLAB Harmony USB stack.
This section describes the hardware requirement and procedures to run these firmware projects on Microchip demonstration and development
boards.
To know more about the MPLAB Harmony USB stack and configuring the USB stack and the APIs provided by the USB stack, refer to the USB
Library documentation.
Program, Data Memory, and Stack Component Memory
Refer to USB Device Stack Demonstration Application Program and Data Memory Requirements and USB Device Stack Component Memory
Requirements for important memory information.
Pen Drive Tests
Refer to USB MSD Host USB Pen Drive Tests for information on the tests conducted on USB Flash devices.
USB Device Stack Demonstration Application Program and Data Memory Requirements
Provides information on program and data memory requirements, as well as pen drive test specifications.
Description
Program Memory and Data Memory Requirements with -O1 Optimization
The following table shows the program memory and data memory requirements of the USB Device Stack demonstration applications. All size
figures are in bytes. Demonstration applications were compiled with the MPLAB XC32 C/C++ Compiler, v1.40, with –O1 optimization.
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 3
Note:
The msd_basic, cdc_msd_basic, and the hid_msd_basic demonstrations use the PIC32 program Flash memory as the MSD
storage media. The difference in Data Memory requirements between the PIC32MX and PIC32MZ microcontrollers for these
demonstration examples, is due to an application demonstration buffer whose size is equal to the erase page size of the PIC32
microcontroller. On the PIC32MX795F512L, this size is 4096 bytes. On the PIC32MZ2048ECH144, the erase page size is 16 KB.
Program Memory and Data Memory Requirements with -Os Optimization
The following table shows the program memory and data memory requirements of the USB Device Stack demonstration applications. All size
figures are in bytes. Demonstration applications were compiled with the MPLAB XC32 C/C++ Compiler, v1.40, with –Os optimization.
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 4
USB Device Stack Component Memory Requirements
Provides memory requirements.
Description
The following table shows the Program and Data Memory requirements for individual components in the MPLAB Harmony USB Device Stack.
Device Stack Component Program
Memory
Data Memory
Device Layer 5688 184
CDC Function Driver 2420 64 + (36 * Queue Size)
MSD Function Driver 5352 217
HID Function Driver 2376 40 + (36 * Queue Size)
Vendor 912 8 + (36 * Queue Size)
PIC32MX USB Driver 5636 144 + (32 * Number of Endpoints)
PIC32MZ USB Driver 10244 192 + (32 * Number of Endpoints)
Notes:
1. Memory requirements (in bytes) for a single instance.
2. Size measured for USB Device Stack Components in MPLAB Harmony.
3. Data Memory does not include function call stack memory size.
USB MSD Host USB Pen Drive Tests
Provides pen drive test specifications.
Description
USB MSD Host USB Pen Drive Tests
The following table lists the commercially available USB pen drives, which have been tested to successfully enumerate with the MSD Host Driver
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 5
in the MPLAB Harmony USB Host. Note that if the USB pen drive you are using in not included in the table, this indicates that this USB pen drive
has not been tested with the MSD Host Driver. However, the USB pen drive could still potentially work with MSD Host Driver. Some USB pen
drives in this table did not have their manufacturer or model data available. The USB Pen drives were tested with the msd_basic USB Host
demonstration in the latest version of the MPLAB Harmony USB Host Stack.
VID PID Manufacturer Model/Drive Capacity
0x1B1C 0x1A0F Corsair Components Flash Voyager Go 8 GB
0x03F0 0x0AB7 Hewlett-Packard 64 GB
0xABCD 0x1234 Microchip Technology Inc. 4 GB
0x125F 0xCB10 Adata Dashdrive UV100 8 GB
0x8644 0x8003 Verico T Series 16 GB
0x8564 0x1000 Transcend USB 3.0 32 GB
0x0951 0x16A7 Dell Kingston Technology 16 GB
0x0718 0x0704 Imation 16 GB Pen Drive
0x048D 0x1168 iBall Jaldi 16 GB Pen Drive
0x058F 0x6366 Alcor Micro AXL 32 GB
0x154B 0x005B PNY Cube 16 GB
0x0930 0x6544 Toshiba Hatabusa Pen Drive 8 GB
0x058F 0x6387 Alcor ZipMem 16 GB
0x090C 0x1000 Silicon Motion Inc. Axl 8GB
0x18A5 0x0245 Verbatim Store N Go Audio USB 8 GB
0x05DC 0xC75C Lexar USB Pen Drive 8 GB
0x1005 0xb113 Apacer 8 GB (AH233)
0x054C 0x06B0 Sony 8 GB
0x054C 0x0862 Sony Micro Vault USM-V 8 GB
0x0781 0x557c SanDisk 8 GB
0x1E4E 0x3257 Etron iBall 16 GB
0x1EC9 0x0101 Moserbaer Swivel 16 GB Pen Drive
0x0BDA 0x0109 SanDisk Standard A and Mini-B connector 16 GB
0x1908 0x1320 ZBEL Wrist Band Flash Drive 4 GB
0x0951 0x1665 Kingston Data Traveler SE9 16 GB
USB HID Host Keyboard and Mouse Tests
Provides information on tested USB keyboard and mouse devices.
Description
The following table lists the commercially available USB keyboard and mouse devices, which have been tested to successfully enumerate with the
HID Host Driver in the MPLAB Harmony USB Host. Note that if the USB HID device you are using in not included in the table, this indicates that
this USB HID device has not been tested, but could still potentially work with the HID Host Driver.
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 6
Note:
The above tests have been performed only on the PIC32M family of devices.
Demonstration Application Configurations
This topic provides information on the available USB demonstration project configurations.
Description
The available USB Demonstration application MPLAB X IDE projects feature support for multiple configurations. Selecting these configurations
allow for the demonstration projects to run across different PIC32 microcontrollers and development boards. The following project configurations
are available:
Configuration name Description
pic32mx_usb_sk2_int_dyn Selecting this configuration will set up the demonstration application to run on the PIC32 USB Starter Kit II
development board, with the PIC32MX795F512L microcontroller. The USB Stack will be configured for Interrupt
mode operation and the USB Driver will be configured for Dynamic operation mode.
pic32mx_usb_sk2_poll_dyn Selecting this configuration will set up the demonstration application to run on the PIC32 USB Starter Kit II
development board, with the PIC32MX795F512L microcontroller. The USB Stack will be configured for Polled
mode operation and the USB driver will be configured for Dynamic operation mode.
pic32mx_usb_sk3_int_dyn Selecting this configuration will set up the demonstration application to run on the PIC32 USB Starter Kit III
development board, with the PIC32MX470F512L microcontroller. The USB Stack will be configured for Interrupt
mode operation and the USB Driver will be configured for Dynamic operation mode.
pic32mx_bt_sk_int_dyn Selecting this configuration will set up the demonstration application to run on the PIC32 Bluetooth Starter Kit
development board, with the PIC32MX270F256D microcontroller. The USB Stack will be configured for Interrupt
mode operation and the USB Driver will be configured for dynamic operation mode.
pic32mz_da_sk_intddr_int_dyn Selecting this configuration will set up the demonstration application to run on the PIC32MZ Embedded
Graphics with Internal DRAM (DA) Starter Kit development board, with the PIC32MZ2064DAH169
microcontroller. The USB Stack will be configured for Interrupt mode operation and the USB Driver will be
configured for Dynamic operation mode.
pic32mz_ec_sk_int_dyn Selecting this configuration will set up the demonstration application to run on the PIC32MZ EC Starter Kit
development board, with the PIC32MZ2048ECH144 microcontroller. The USB Stack will be configured for
Interrupt mode operation and the USB Driver will be configured for Dynamic operation mode.
pic32mz_ec_sk_poll_dyn Selecting this configuration will set up the demonstration application to run on the PIC32MZ EC Starter Kit
development board, with the PIC32MC2048ECH144 microcontroller. The USB Stack will be configured for
Polled mode operation and the USB Driver will be configured for Dynamic operation mode.
pic32mz_ec_sk_meb2_int_dyn Selecting this configuration will set up the demonstration application to run on the PIC32MZ EC Starter Kit, with
the PIC32MZ2048ECH144 microcontroller board attached to the MEB II. The USB Stack will be configured for
Interrupt mode operation and the USB Driver will be configured for Dynamic operation mode.
pic32mz_ef_sk_int_dyn Selecting this configuration will set up the demonstration application to run on the PIC32MZ EF Starter Kit, with
the PIC32MZ2048EFM144 microcontroller. The USB Stack will be configured for Interrupt mode operation and
the USB Driver will be configured for Dynamic operation mode.
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 7
pic32mz_ef_sk_poll_dyn Selecting this configuration will set up the demonstration application to run on the PIC32MZ EF Starter Kit
development board, with the PIC32MZ2048EFM144 microcontroller. The USB Stack will be configured for
Polled mode operation and the USB Driver will be configured for Dynamic operation mode.
pic32mx795_pim_e16_int_dyn Selecting this configuration will set up the demonstration application to run on the Explorer 16 Development
Board along with the PIC32MX795F512L microcontroller Plug In Module and USB PICtail Plus Daughter Board.
The USB Stack will be configured for Interrupt mode operation and the USB Driver will be configured for
Dynamic operation mode.
pic32mx460_pim_e16_int_dyn Selecting this configuration will set up the demonstration application to run on the Explorer 16 Development
Board along with the PIC32MX460F512L microcontroller Plug In Module and USB PICtail Plus Daughter Board.
The USB Stack will be configured for Interrupt mode operation and the USB Driver will be configured for
Dynamic operation mode.
pic32mx470_curiosity Selecting this configuration will set up the demonstration application to run on the PIC32MX470 Curiosity
Development Board, with the PIC32MX470F512H microcontroller. The USB Stack will be configured for
Interrupt mode operation and the USB Driver will be configured for Dynamic operation mode.
pic32mz_ef_curiosity Selecting this configuration will set up the demonstration application to run on the PIC32MZ EF Curiosity
Development Board, with the PIC32MZ2048EFM100 microcontroller. The USB Stack will be configured for
Interrupt mode operation and the USB Driver will be configured for Dynamic operation mode.
pic32mk_evk_int_dyn Selecting this configuration will set up the demonstration application to run on the PIC32MK GP Development
Board, with the PIC32MK1024GPE100 microcontroller. The USB Stack will be configured for Interrupt mode
operation and the USB Driver will be configured for Dynamic operation mode.
pic32mx_xlp_sk_int_dyn Selecting this configuration will set up the demonstration application to run on the PIC32MX XLP Starter Kit, with
the PIC32MX274F256D microcontroller. The USB Stack will be configured for Interrupt mode operation and the
USB Driver will be configured for Dynamic operation mode.
chipkit_wf32 Selecting this configuration will set up the demonstration application to run on the chipKIT WF32 Wi-Fi
Development Board, with the PIC32MZ2048EFG100 microcontroller. The USB Stack will be configured for
Interrupt mode operation and the USB Driver will be configured for Dynamic operation mode.
chipkit_wifire Selecting this configuration will set up the demonstration application to run on the chipKIT Wi-FIRE
Development Board, with the PIC32MX275F256D microcontroller. The USB Stack will be configured for
Interrupt mode operation and the USB Driver will be configured for Dynamic operation mode.
The following figure shows how a configuration can be selected in MPLAB X IDE.
Alternatively, the active configuration can be selected in the Project Properties.
USB Device Demonstrations Matrix
The following table shows the availability of a configuration across available USB Device demonstration applications. Green indicates support.
Red indicates no support.
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 8
USB Host Demonstration Matrix
The following table shows the availability of a configuration across available USB Host demonstration applications. Green indicates support. Red
indicates no support.
USB Multiple Controller Demonstration Matrix
The following table shows the availability of a configuration across available USB Multiple Controller Demonstration applications. Green indicates
support. Red indicates no support.
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 9
Demonstrations
The USB Demonstrations are grouped into USB Device Stack, USB Host Stack, USB Dual Role, and USB demonstrations that make use of
multiple USB controllers on certain PIC32 family devices.
Device
This section describes the USB Device demonstrations.
Description
The MPLAB Harmony USB Device Stack demonstration applications uses LEDs on the development board to indicate the USB state of the device.
The following table provides details on the development board specific LEDs and the USB Device State these indicate when active. This indication
scheme is implemented by all USB Device Stack Demonstration applications.
USB Device State and LED Indication
Demonstration Board Reset State Configured
State
Suspended
State
Explorer 16 Development Board and PIM D3, D4 D5 D4, D5
PIC32 USB Starter Kit II LED1, LED2 LED3 LED2, LED3
PIC32MZ Embedded Connectivity (EC) Starter Kit LED1, LED2 LED3 LED2, LED3
PIC32MZ Embedded Connectivity with Floating Point Unit (EF) Starter Kit LED1, LED2 LED3 LED2, LED3
PIC32 USB Starter Kit III LED1, LED2 LED3 LED2, LED3
PIC32 Bluetooth Starter Kit Red LED,
Green LED
Blue LED Green LED,
Blue LED
PIC32MX470 Curiosity Development Board LED1, LED2 LED3 LED2, LED3
PIC32MZ EF Curiosity Development Board LED1, LED2 LED3 LED2, LED3
cdc_com_port_dual
Demonstrates a USB CDC device, emulating dual serial COM ports - one looping back into the other.
Description
This demonstration application creates a USB CDC Device that enumerates as two serial ports on the USB Host personal computer. This
application demonstrates the ability of the MPLAB Harmony USB Device Stack to support multiple instances of the same Device class.
Building the Application
This section identifies the MPLAB X IDE project name and location and lists and describes the available configurations for the USB CDC Device
Dual COM Port Demonstration.
Description
To build this project, you must open the cdc_com_port_dual.X project in MPLAB X IDE, and then select the desired configuration.
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 10
The following tables list and describe the project and supported configurations. The parent folder for these files is
/apps/usb/device/cdc_com_port_dual.
MPLAB X IDE Project
This table lists the name and location of the MPLAB X IDE project folder for the demonstration.
Project Name Location
cdc_com_port_dual.X /apps/usb/device/cdc_com_port_dual/firmware
MPLAB X IDE Project Configurations
This table lists and describes the supported configurations of the demonstration, which are located within ./firmware/src/system_config.
Project Configuration Name BSP Used Description
pic32mx460_pim_e16_int_dyn pic32mx460_pim+e16 Select this MPLAB X IDE project configuration to run the demonstration on the Explorer
16 Development Board configured for Interrupt mode and dynamic operation. This
configuration also requires PIC32MX460F512L Plug-In Module (PIM) and the USB
PICtail Plus Daughter Board.
pic32mx_bt_sk_int_dyn pic32mx_bt_sk Select this MPLAB X IDE project configuration to run the demonstration on the PIC32
Bluetooth Starter Kit configured for Interrupt mode and dynamic operation.
pic32mx_usb_sk3_int_dyn pic32mx_usb_sk3 Select this MPLAB X IDE project configuration to run the demonstration on the PIC32
USB Starter Kit III configured for Interrupt mode and dynamic operation.
pic32mx_usb_sk2_int_dyn pic32mx_usb_sk2 Select this MPLAB X IDE project configuration to run the demonstration on the PIC32
USB Starter Kit II configured for Interrupt mode and dynamic operation.
pic32mx_xlp_sk_int_dyn pic32mx_xlp_sk Select this MPLAB X IDE project configuration to run the demonstration on the PIC32MX
XLP Starter Kit configured for Interrupt mode and dynamic operation.
pic32mz_ef_sk_int_dyn pic32mz_ef_sk Select this MPLAB X IDE project configuration to run the demonstration on the PIC32MZ
Embedded Connectivity with Floating Point Unit (EF) Starter Kit configured for Interrupt
mode and dynamic operation.
pic32mx470_curiosity pic32mx470_curiosity Select this MPLAB X IDE project configuration to run the demonstration application to
run on the PIC32MX470 Curiosity Development Board, with the PIC32MX470F512H
microcontroller. The USB Stack will be configured for Interrupt mode operation and the
USB Driver will be configured for Dynamic operation mode.
pic32mz_ef_curiosity pic32mz_ef_curiosity Select this MPLAB X IDE project configuration to run the demonstration application to
run on the PIC32MZ EF Curiosity Development Board, with the PIC32MZ2048EFM100
microcontroller. The USB Stack will be configured for Interrupt mode operation and the
USB Driver will be configured for Dynamic operation mode.
Configuring the Hardware
Describes how to configure the supported hardware.
Description
PIC32 USB Starter Kit II
Remove jumper JP2.
PIC32MZ EC Starter Kit
Remove jumper JP1.
PIC32MZ EF Starter Kit
No hardware related configuration or jumper setting changes are necessary.
PIC32MX XLP Starter Kit
No hardware related configuration or jumper setting changes are necessary.
PIC32 USB Starter Kit III
Remove jumper JP1.
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 11
PIC32 Bluetooth Starter Kit
Jumper J8 should either be shorted between pins 2 and 3 or should be completely open.
PIC32MX460F512L PIM
Jumper J10 should be removed. This plug-in module should be used along with the Explorer 16 Development Board and the USB PICtail Plus
daughter board. The microcontroller PIM should be plugged into the PIM_socket_on the board. The USB PICtail Plus daughter board should be
connected to the edge connector J9.
On the Explorer 16 Development Board:
• Switch S2 should be set to PIM
• Jumper JP2 should be in place
On the USB PICtail Plus Daughter Board:
• Jumper JP1 should be in place
• Jumper JP2 and JP4 should be removed
On the PIC32MX460F512L PIM:
• Keep jumper J10 open
• Keep all jumpers in J9 open
PIC32MX470 Curiosity Development Board
• Ensure that a jumper is placed at 4-3 on J8, to select supply from debug USB connector.
• Power the PIC32MX470 Curiosity Development Board from a Host PC through a Type-A male to mini-B USB cable connected to Mini-B port
(J3).
• Ensure that jumper is not present in the J13 header to use the Curiosity board in device mode.
• Plug in a USB cable with a micro-B type connector to Micro-B port (J12), and plug the other end into your computer.
PIC32MZ EF Curiosity Development Board
• Ensure that a jumper is placed at 4-3 on J8, to select supply from debug USB connector.
• Power the PIC32MZ EF Curiosity Development Board from a Host PC through a Type-A male to micro-B USB cable connected to Micro-B port
(J3).
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 12
• Ensure that jumper is not present in the J13 header to use the Curiosity board in device mode.
• Plug in a USB cable with a micro-B type connector to Micro-B port (J12), and plug the other end into your computer.
Running the Demonstration
Provides instructions on how to build and run the CDC Dual COM Port demonstration.
Description
This demonstration allows the device to appear like dual serial (COM) ports to the host. Do the following to run this demonstration:
1. First compile and program the target device. While compiling, select the appropriate MPLAB X IDE project configuration based on the
demonstration board. Refer to Building the Application for details.
2. Attach the device to the host. If the host is a personal computer and this is the first time you have plugged this device into the computer you
may be prompted for a .inf file.
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 13
3. Select the "Install from a list or specific location (Advanced)" option. Specify the
/apps/usb/device/cdc_com_port_dual/inf directory.
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 14
Note:
As an option, to specify the driver, you may open the device manager and expand the Ports (COM & LPT) tab, and right click on
“Update Driver Software…”
Verify that the enumerated USB device is seen as a virtual USB serial comport in Device Manager.
4. Once the device is successfully installed, open up two instances of a terminal program, such as HyperTerminal. Select the appropriate COM
port for each of these terminal instances. The following screen shot shows the COM port selection for the Tera Term terminal program.
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 15
5. The LEDs on the demonstration board will indicate the USB state of the device, as described in the USB Device State and LED Indication
Table in the Device section.
6. To run the demonstration, turn on local echo on both the terminals. For Tera Term terminal application, navigate to Setup->Terminal to turn on
local echo. Type a character or string in one terminal window. The same character or string appears on the second terminal window. Similarly,
any character typed in the second window appears in the first window. The following screen shot shows two instances of Tera Term.
Note:
Some terminal programs, like HyperTerminal, require users to click the disconnect button before removing the device from the
computer. Failing to do so may result in having to close and open the program again to reconnect to the device.
cdc_com_port_single
Demonstrates a USB CDC device, emulating a serial COM port.
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 16
Description
This demonstration application creates a USB CDC Device that enumerates as a single COM port on the host personal computer. The application
demonstrates two-way communication between the USB device and the personal computer host.
Building the Application
This section identifies the MPLAB X IDE project name and location and lists and describes the available configurations for the USB CDC Device
Single COM Port Demonstration.
Description
To build this project, you must open the cdc_com_port_single.X project in MPLAB X IDE, and then select the desired configuration.
The following tables list and describe the project and supported configurations. The parent folder for these files is
/apps/usb/device/cdc_com_port_single.
MPLAB X IDE Project
This table lists the name and location of the MPLAB X IDE project folder for the demonstration.
Project Name Location
cdc_com_port_single.X /apps/usb/device/cdc_com_port_single/firmware
MPLAB X IDE Project Configurations
This table lists and describes the supported configurations of the demonstration, which are located within ./firmware/src/system_config.
Project Configuration Name BSP Used Description
pic32mx460_pim_e16_int_dyn pic32mx460_pim+e16 Select this MPLAB X IDE project configuration to run the demonstration on the
Explorer 16 Development Board configured for Interrupt mode and dynamic
operation. This configuration also requires PIC32MX460F512L Plug-In Module
(PIM) and the USB PICtail Plus Daughter Board.
pic32mx_usb_sk2_poll_dyn pic32mx_bt_sk Select this MPLAB X IDE project configuration to run the demonstration on the
PIC32 USB Starter Kit II with the USB Device Stack configured for Polled mode and
dynamic operation.
pic32mx_usb_sk3_int_dyn pic32mx_usb_sk3 Select this MPLAB X IDE project configuration to run the demonstration on the
PIC32 USB Starter Kit III configured for Interrupt mode and dynamic operation.
pic32mx_usb_sk2_int_dyn pic32mx_usb_sk2 Select this MPLAB X IDE project configuration to run the demonstration on the
PIC32 USB Starter Kit II configured for Interrupt mode and dynamic operation.
pic32mz_da_sk_intddr_int_dyn pic32mz_da_sk_intddr Select this MPLAB X IDE project configuration to run the demonstration on the
PIC32MZ Embedded Graphics with Internal DRAM (DA) Starter Kit configured for
Interrupt mode and dynamic operation.
pic32mz_ef_sk_int_dyn_micromips pic32mz_ef_sk Select this MPLAB X IDE project configuration to run the demonstration on the
PIC32MZ Embedded Connectivity with Floating Point Unit (EF) Starter Kit
configured in microMIPS mode for Interrupt mode and dynamic operation.
pic32mz_ef_sk_int_dyn pic32mz_ef_sk Select this MPLAB X IDE project configuration to run the demonstration on the
PIC32MZ Embedded Connectivity with Floating Point Unit (EF) Starter Kit
configured for Interrupt mode and dynamic operation.
pic32mz_ef_sk_poll_dyn pic32mz_ef_sk Select this MPLAB X IDE project configuration to run the demonstration on the
PIC32MZ Embedded Connectivity with Floating Point Unit (EF) Starter Kit with the
USB Device Stack configured for Polled mode and dynamic operation.
pic32mx_125_sk_int_dyn pic32mx_125_sk Select this MPLAB X IDE project configuration to run the demonstration on the
PIC32MX1/2/5 Starter Kit with the USB Device Stack configured for Interrupt mode
and dynamic operation.
Configuring the Hardware
Describes how to configure the supported hardware.
Description
PIC32 USB Starter Kit II
Remove jumper JP2.
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 17
PIC32MZ Embedded Graphics with Internal DRAM (DA) Starter Kit
No hardware related configuration or jumper setting changes are necessary.
PIC32MZ EF Starter Kit
No hardware related configuration or jumper setting changes are necessary.
PIC32 USB Starter Kit III
Remove jumper JP1.
PIC32MX460F512L PIM
Jumper J10 should be removed. This plug-in module should be used along with the Explorer 16 Development Board and the USB PICtail Plus
daughter board. The microcontroller PIM should be plugged into the PIM_socket_on the board. The USB PICtail Plus daughter board should be
connected to the edge connector J9.
On the Explorer 16 Development Board:
• Switch S2 should be set to PIM
• Jumper JP2 should be in place
On the USB PICtail Plus Daughter Board:
• Jumper JP1 should be in place
• Jumper JP2 and JP4 should be removed
On the PIC32MX460F512L PIM:
• Keep jumper J10 open
• Keep all jumpers in J9 open
PIC32WK Wi-Fi Starter Kit
No hardware related configuration or jumper setting changes are necessary.
Running the Demonstration
Provides instructions on how to build and run the CDC Single COM Port demonstration.
Description
This demonstration allows the device to appear like a serial (COM) port to the host. Do the following to run this demonstration:
1. First compile and program the target device. While compiling, select the appropriate MPLAB X IDE project configuration based on the
demonstration board. Refer to Building the Application for details.
2. Attach the device to the host. If the host is a personal computer and this is the first time you have plugged this device into the computer, you
may be prompted for a .inf file.
3. Select the "Install from a list or specific location (Advanced)" option. Specify the
/apps/usb/device/cdc_com_port_single/inf directory.
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 18
4. Once the device is successfully installed, open up a terminal program, such as HyperTerminal and select the appropriate COM port. On most
machines this will be COM5 or higher. Set the communication properties to 9600 baud, 1 Stop bit and No parity, with Flow Control set to None.
5. The LEDs on the demonstration board will indicate the USB state of the device, as described in the USB Device State and LED Indication
Table in the Device section.
6. Once connected to the device, there are two ways to run this example project:
• a) Typing a key in the terminal window will result in the attached device echoing the next letter. Therefore, if the letter 'b' is pressed, the
device will echo 'c'.
• b) If the push button is pressed, the device will echo "PUSH BUTTON PRESSED" to the terminal window.
The following table shows the switch buttons to be pressed for different demonstration boards.
Demonstration Board Button
PIC32 USB Starter Kit II
PIC32 USB Starter Kit III
PIC32MZ Embedded Graphics with Internal DRAM (DA) Starter Kit
PIC32MZ Embedded Connectivity (EC) Starter Kit
PIC32MZ Embedded Connectivity with Floating Point Unit (EF) Starter Kit
PIC32WK Wi-Fi Starter Kit
SW1
Explorer 16 Development Board S3
Note:
Some terminal programs, like HyperTerminal, require users to click the disconnect button before removing the device from the
computer. Failing to do so may result in having to close and open the program again to reconnect to the device.
cdc_msd_basic
Demonstrates a composite USB device emulating a COM port and Flash drive.
Description
This demonstration application creates a composite USB Device that enumerates as a COM port and as Flash drive simultaneously.
Building the Application
This section identifies the MPLAB X IDE project name and location and lists and describes the available configurations for the USB CDC MSD
Composite Device Demonstration.
Description
To build this project, you must open the cdc_msd_basic.X project in MPLAB X IDE, and then select the desired configuration.
The following tables list and describe the project and supported configurations. The parent folder for these files is
/apps/usb/device/cdc_msd_basic.
MPLAB X IDE Project
This table lists the name and location of the MPLAB X IDE project folder for the demonstration.
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 19
Project Name Location
cdc_msd_basic.X /apps/usb/device/cdc_msd_basic/firmware
MPLAB X IDE Project Configurations
This table lists and describes the supported configurations of the demonstration, which are located within ./firmware/src/system_config.
Project Configuration
Name
BSP Used Description
pic32mx_usb_sk2_int_dyn pic32mx_usb_sk2 Select this MPLAB X IDE project configuration to run the demonstration on the PIC32 USB
Starter Kit II configured for Interrupt mode and dynamic operation.
pic32mz_ef_sk_int_dyn pic32mz_ef_sk Select this MPLAB X IDE project configuration to run the demonstration on the PIC32MZ
Embedded Connectivity with Floating Point Unit (EF) Starter Kit configured for Interrupt mode
and dynamic operation.
Configuring the Hardware
Description
PIC32 USB Starter Kit II
Remove jumper JP2.
PIC32MZ EF Starter Kit
No hardware related configuration or jumper setting changes are necessary.
Running the Demonstration
Provides instructions on how to build and run the USB CDC MSD Composite Device demonstration.
Description
This demonstration application creates a composite USB Device that works simultaneously as a CDC and as a MSD device. This application
combines the functionality of the cdc_com_port_single and msd_basic demonstration applications into one device.
Refer to Running the Demonstration section of the cdc_com_port_single demonstration and the Running the Demonstration section of the
msd_basic demonstration for details on exercising the CDC and MSD device features, respectively.
The LEDs on the demonstration board will indicate the USB state of the device, as described in the USB Device State and LED Indication Table in
the Device section.
cdc_serial_emulator
This application demonstrates the use of the CDC device class in implementing a USB-to-Serial Dongle.
Description
This application demonstrates the use of the CDC device class in implementing a USB-to-Serial Dongle. The application enumerates a COM port
on the personal computer. Data received through the CDC USB interface is forwarded to a UART. Data received on the UART is forwarded to the
CDC USB interface. This emulates a USB-to-Serial Dongle.
Building the Application
This section identifies the MPLAB X IDE project name and location and lists and describes the available configurations for the USB CDC Device
USB-to-Serial Demonstration.
Description
To build this project, you must open the cdc_serial_emulator.X project in MPLAB X IDE, and then select the desired configuration.
The following tables list and describe the project and supported configurations. The parent folder for these files is
/apps/usb/device/cdc_serial_emulator.
MPLAB X IDE Project
This table lists the name and location of the MPLAB X IDE project folder for the demonstration.
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 20
Project Name Location
cdc_serial_emulator.X /apps/usb/device/cdc_serial_emulator/firmware
MPLAB X IDE Project Configurations
This table lists and describes the supported configurations of the demonstration, which are located within ./firmware/src/system_config.
Project Configuration Name BSP Used Description
pic32mx795_pim_e16_int_dyn pic32mx795_pim+e16 Select this MPLAB X IDE project configuration to run the demonstration on the Explorer
16 Development Board configured for Interrupt mode and dynamic operation. This
configuration also requires the PIC32MX795F512L Plug-In Module (PIM) and the USB
PICtail Plus Daughter Board.
pic32mz_ef_sk_int_dyn pic32mz_ef_sk Select this MPLAB X IDE project configuration to run the demonstration on the PIC32MZ
EF Starter Kit configured for Interrupt mode and dynamic operation.
Configuring the Hardware
Describes how to configure the supported hardware.
Description
PIC32MZ EF Starter Kit
No hardware related configuration or jumper setting changes are necessary.
PIC32MX795F512L CAN-USB PIM
Jumper J10 should be removed. Jumper J1 and J2 should_connect_to positions 1 and 2. This PIM should be used along with the Explorer 16
Development Board and the USB PICtail Plus daughter board. The microcontroller PIM should be plugged into the PIM_socket_on the board. The
USB PICtail Plus daughter board should be connected to the edge connector J9.
On the Explorer 16 Development Board:
• Switch S2 should be set to PIM
• Jumper JP2 should be in place
On the USB PICtail Plus Daughter Board:
• Jumper JP1 should be in place
• Jumper JP2 and JP4 should be removed
On the PIC32MX795F512L PIM:
• Keep jumper J10 open
• Keep all jumpers in J9 open
• Jumper J1 should be shorted between positions 1 and 2. This configuration is only applicable for the PIC32MX795F512L USB CAN PIM
(MA320003), and not the PIC32MX795F512L USB PIM (MA320002).
• Jumper J2 should be shorted between positions 1 and 2. This configuration is only applicable for the PIC32MX795F512L USB CAN PIM
(MA320003) and not the PIC32MX795F512L USB PIM (MA320002).
Running the Demonstration
Provides instructions on how to build and run the CDC Serial Emulator Demonstration.
Prior to using this demonstration, it is recommended to review the MPLAB Harmony Release Notes for any known issues. A PDF copy of the
release notes is provided in the /doc folder of your installation.
Description
This application demonstrates the use of the CDC Device class in implementing a USB-to-Serial Dongle. The application enumerates a COM port
on the personal computer. Data received through the CDC USB interface is forwarded to a UART. Data received on the UART is forwarded to the
CDC USB interface. This emulates a USB-to-Serial Dongle.
1. Open_the project in MPLAB X IDE and select the desired configuration.
2. Build the code and program the device.
3. Depending on the hardware in use, do one of the following:
• If you are using the Explorer 16 board, connect the mini-B device connector on the USB PICtail Plus Daughter Board to the personal computer
• If you a are using the PIC32MZ EF starter kit, connect the micro-USB device connector to the personal computer
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 21
7. Select the "Install from a list or specific location (Advanced)" option. Specify the
/apps/usb/device/cdc_serial_emulator/inf directory.
The LEDs on the demonstration board will indicate the USB state of the device, as described in the USB Device State and LED Indication Table in
the Device section.
8. Open_a terminal emulation program of your choice and select the enumerated USB COM port.
9. Connect the USB-to-Serial Dongle to the same personal computer.
10. Open_another instance of the terminal emulation program and select the USB-to-Serial Dongle.
11. Connect the serial connector of the USB-to-Serial Dongle to the UART connector (P1) on the Explorer 16 Development Board.
12. Choose a baud rate of 9600, 1 Stop bit and no parity while opening both of the terminal emulation programs.
The setup should be similar to the following diagram.
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 22
Any text entered into the terminal 1 program will be echoed on terminal 2 and vice versa.
cdc_serial_emulator_msd
Demonstrates a USB to Serial Dongle combined with a MSD class.
Description
This demonstration application creates a USB Device that combines the functionality of the cdc_serial_emulator and msd_basic demonstration
applications.
Building the Application
This section identifies the MPLAB X IDE project name and location and lists and describes the available configurations for the this demonstration
application.
Description
To build this project, you must open the cdc_serial_emulator_msd.X project in MPLAB X IDE, and then select the desired configuration.
The following tables list and describe the project and supported configurations. The parent folder for these files is
/apps/usb/cdc_serial_emulator_msd.
MPLAB X IDE Project
This table lists the name and location of the MPLAB X IDE project folder for the demonstration.
Project Name Location
cdc_serial_emulator_msd.X /apps/usb/device/cdc_serial_emulator_msd/firmware
MPLAB X IDE Project Configurations
This table lists and describes the supported configurations of the demonstration, which are located within ./firmware/src/system_config.
Project Configuration Name BSP Used Description
pic32mx795_pim_e16_int_dyn pic32mx795_pim+e16 Select this MPLAB X IDE project configuration to run the demonstration on the Explorer
16 Development Board configured for Interrupt mode and dynamic operation. This
configuration also requires the PIC32MX795F512L Plug-In Module (PIM) and the USB
PICtail Plus Daughter Board.
Configuring the Hardware
Describes how to configure the supported hardware.
Description
PIC32MX795F512L CAN-USB PIM
Jumper J10 should be removed. Jumper J1 and J2 should_connect_to positions 1 and 2. This PIM should be used along with the Explorer 16
Development Board and the USB PICtail Plus daughter board. The microcontroller PIM should be plugged into the PIM_socket_on the board. The
USB PICtail Plus daughter board should be connected to the edge connector J9.
On the Explorer 16 Development Board:
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 23
• Switch S2 should be set to PIM
• Jumper JP2 should be in place
On the USB PICtail Plus Daughter Board:
• Jumper JP1 should be in place
• Jumper JP2 and JP4 should be removed
On the PIC32MX795F512L PIM:
• Keep jumper J10 open.
• Keep all jumpers in J9 open
• Jumper J1 should be shorted between positions 1 and 2
• Jumper J2 should be shorted between positions 1 and 2
Running the Demonstration
Provides instructions on how to build and run the demonstration.
Description
This demonstration functions as a composite USB Device that combines the features of the devices created by the cdc_serial_emulator and the
msd_basic demonstration applications. Refer to Running the Demonstration section of the cdc_serial_emulator demonstration and Running the
Demonstration section of the msd_basic demonstration for details on exercising the CDC and MSD functions, respectively.
The LEDs on the demonstration board will indicate the USB state of the device, as described in the USB Device State and LED Indication Table in
the Device section.
hid_basic
This demonstration application creates a custom HID device that can be controlled by a personal computer-based utility.
Description
This application creates a custom HID device that can be controlled by a personal computer-based utility. The device allows the USB Host utility to
control the LEDs on the board and query the status of a switch.
Building the Application
This section identifies the MPLAB X IDE project name and location and lists and describes the available configurations for the USB HID Basic
Demonstration.
Description
To build this project, you must open the hid_basic.X project in MPLAB X IDE, and then select the desired configuration.
The following tables list and describe the project and supported configurations. The parent folder for these files is
/apps/usb/device/hid_basic.
MPLAB X IDE Project
This table lists the name and location of the MPLAB X IDE project folder for the demonstration.
Project Name Location
hid_basic.X /apps/usb/device/hid_basic/firmware
MPLAB X IDE Project Configurations
This table lists and describes the supported configurations of the demonstration, which are located within ./firmware/src/system_config.
Project Configuration Name BSP Used Description
pic32mx460_pim_e16_int_dyn pic32mx460_pim+e16 Select this MPLAB X IDE project configuration to run the demonstration on the Explorer
16 Development Board configured for Interrupt mode and dynamic operation. This
configuration also requires the PIC32MX460F512L Plug-In Module (PIM) and the USB
PICtail Plus Daughter Board.
pic32mx_usb_sk3_int_dyn pic32mx_usb_sk3 Select this MPLAB X IDE project configuration to run the demonstration on the PIC32
USB Starter Kit III configured for Interrupt mode and dynamic operation.
pic32mx_usb_sk2_int_dyn pic32mx_usb_sk2 Select this MPLAB X IDE project configuration to run the demonstration on the PIC32
USB Starter Kit II configured for Interrupt mode and dynamic operation.
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 24
pic32mz_ef_sk_int_dyn pic32mz_ef_sk Select this MPLAB X IDE project configuration to run the demonstration on the PIC32MZ
Embedded Connectivity with Floating Point Unit (EF) Starter Kit configured for Interrupt
mode and dynamic operation.
Configuring the Hardware
Describes how to configure the supported hardware.
Description
PIC32 USB Starter Kit II
Remove jumper JP2.
PIC32MZ EF Starter Kit
No hardware related configuration or jumper setting changes are necessary.
PIC32 USB Starter Kit III
Remove jumper JP1.
PIC32MX460F512L PIM
Jumper J10 should be removed. This plug-in module should be used along with the Explorer 16 Development Board and the USB PICtail Plus
daughter board. The microcontroller PIM should be plugged into the PIM_socket_on the board. The USB PICtail Plus daughter board should be
connected to the edge connector J9.
On the Explorer 16 Development Board:
• Switch S2 should be set to PIM
• Jumper JP2 should be in place
On the USB PICtail Plus Daughter Board:
• Jumper JP1 should be in place
• Jumper JP2 and JP4 should be removed
On the PIC32MX460F512L PIM:
• Keep jumper J10 open
• Keep all jumpers in J9 open
Running the Demonstration
Provides instructions on how to build and run the HID Basic demonstration.
Description
This demonstration uses the selected hardware platform as a HID class USB device, but uses the HID class for general purpose I/O operations.
While compiling, select the appropriate MPLAB X IDE project configuration based on the demonstration board. Refer to Building the Application for
details.
Typically, the HID class is used to implement human interface products, such as mice and keyboards. The HID protocol, is however, quite flexible,
and can be adapted and used to send/receive general purpose data to/from a USB device. Using the HID class for general purpose I/O operations
is quite advantageous, in that it does not require any kind of custom driver installation process. HID class drivers are already provided by and are
distributed with common operating systems. Therefore, upon plugging in a HID class device into a typical computer system, no user installation of
drivers is required, the installation is fully automatic.
The LEDs on the demonstration board will indicate the USB state of the device, as described in the USB Device State and LED Indication Table in
the Device section.
HID devices primarily communicate through one interrupt IN endpoint and one interrupt OUT endpoint. In most applications, this effectively limits
the maximum achievable bandwidth for full speed HID devices to 64 kBytes/s of IN traffic, and 64 kBytes/s of OUT traffic (64 kB/s, but effectively
"full duplex").
The GenericHIDSimpleDemo.exe program, and the associated firmware demonstrate how to use the HID protocol for basic general purpose
USB data transfer.
Before you can run the GenericHIDSimpleDemo.exe executable, you will need to have the Microsoft® .NET Framework Version 2.0
Redistributable Package (later versions are probably acceptable, but have not been tested) installed on your computer. Programs that were built in
the Visual Studio® .NET languages require the .NET redistributable package. The redistributable package can be freely downloaded from
Microsoft’s website. Users of Windows Vista® operating systems will not need to install the .NET framework, as it comes preinstalled as part of the
operating system.
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 25
Launching the Application
To launch the application, simply double click the executable GenericHIDSimpleDemo.exe in the
\apps\usb\device\hid_basic\bin directory. A property sheet similar to the following should appear:
Note:
If instead of this window, an error message appears while trying to launch the application, it is likely the Microsoft .NET Framework
Version 2.0 Redistributable Package has not yet been installed. Please install it and try again.
Send/Receive Packets
To begin sending/receiving packets to the device, you must first find and_connect_ to the device. As configured by default, the application is
looking for HID class USB devices with VID = 0x04D8 and PID = 0x003F. The device descriptor in the firmware project meant to be used with this
demonstration uses the same VID/PID. If you plug in a USB device programmed with the correct precompiled .hex file, and click Connect, the
other push buttons should become enabled. If clicking Connect has no effect, it is likely the USB device is either not connected, or has not been
programmed with the correct firmware.
Clicking Toggle LED(s) should send a single packet of general purpose generic data to the HID class USB peripheral device. The data will arrive
on the interrupt OUT endpoint. The firmware has been configured to receive this generic data packet, parse the packet looking for the Toggle
LED(s) command, and should respond appropriately by controlling the LED(s) on the demonstration board.
The Get Pushbutton State option will send one packet of data over the USB to the peripheral device (to the interrupt OUT endpoint) requesting the
current push button state. The firmware will process the received Get Pushbutton State command, and will prepare an appropriate response
packet depending upon the pushbutton state.
The following table shows the button that has to be pressed on the demonstration board to see the change in the push button state.
Demonstration Board Button
PIC32 USB Starter Kit II
PIC32 USB Starter Kit III
PIC32MZ Embedded Connectivity (EC) Starter Kit
PIC32MZ Embedded Connectivity with Floating Point Unit (EF) Starter Kit
SW1
Explorer 16 Development Board S3
hid_joystick
Demonstrates a USB HID device emulating a joystick.
Description
This demonstration application creates a custom HID joystick. This application is only intended to demonstrate creation of Joystick HID Report
descriptors and may not be a definite end solution. The end application requirements may need the report descriptor to be modified.
Building the Application
This section identifies the MPLAB X IDE project name and location and lists and describes the available configurations for the USB HID Joystick
Demonstration.
Description
To build this project, you must open the hid_joystick.X project in MPLAB X IDE, and then select the desired configuration.
The following tables list and describe the project and supported configurations. The parent folder for these files is
/apps/usb/device/hid_joystick.
MPLAB X IDE Project
This table lists the name and location of the MPLAB X IDE project folder for the demonstration.
Project Name Location
hid_joystick.X /apps/usb/device/hid_joystick/firmware
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 26
MPLAB X IDE Project Configurations
This table lists and describes the supported configurations of the demonstration, which are located within ./firmware/src/system_config.
Project Configuration Name BSP Used Description
pic32mx460_pim_e16_int_dyn pic32mx460_pim+e16 Select this MPLAB X IDE project configuration to run the demonstration on the Explorer
16 Development Board configured for Interrupt mode and dynamic operation. This
configuration also requires the PIC32MX460F512L Plug-In Module (PIM) and the USB
PICtail Plus Daughter Board.
pic32mx_usb_sk3_int_dyn pic32mx_usb_sk3 Select this MPLAB X IDE project configuration to run the demonstration on the PIC32
USB Starter Kit III configured for Interrupt mode and dynamic operation.
pic32mx_usb_sk2_int_dyn pic32mx_usb_sk2 Select this MPLAB X IDE project configuration to run the demonstration on the PIC32
USB Starter Kit II configured for Interrupt mode and dynamic operation.
pic32mz_ef_sk_int_dyn pic32mz_ef_sk Select this MPLAB X IDE project configuration to run the demonstration on the PIC32MZ
Embedded Connectivity with Floating Point Unit (EF) Starter Kit configured for Interrupt
mode and dynamic operation.
Configuring the Hardware
Describes how to configure the supported hardware.
Description
PIC32 USB Starter Kit II
Remove jumper JP2.
PIC32MZ EF Starter Kit
No hardware related configuration or jumper setting changes are necessary.
PIC32 USB Starter Kit III
Remove jumper JP1.
PIC32MX460F512L PIM
Jumper J10 should be removed. This plug-in module should be used along with the Explorer 16 Development Board and the USB PICtail Plus
daughter board. The microcontroller PIM should be plugged into the PIM_socket_on the board. The USB PICtail Plus daughter board should be
connected to the edge connector J9.
On the Explorer 16 Development Board:
• Switch S2 should be set to PIM
• Jumper JP2 should be in place
On the USB PICtail Plus Daughter Board:
• Jumper JP1 should be in place
• Jumper JP2 and JP4 should be removed
On the PIC32MX460F512L PIM:
• Keep jumper J10 open
• Keep all jumpers in J9 open
Running the Demonstration
Provides instructions on how to build and run the USB HID Joystick demonstration.
Description
This demonstration uses the selected hardware platform as a USB Joystick. Select the appropriate MPLAB X IDE project configuration based on
the demonstration board. Refer to Building the Application for details.
The LEDs on the demonstration board will indicate the USB state of the device, as described in the USB Device State and LED Indication Table in
the Device section.
To test the joystick feature, navigate to the /apps/usb/device/hid_joystick/bin directory and open
JoystickTester.exe:
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 27
Pressing the button will cause the device to:
• Indicate that the "x" button is pressed, but no others
• Move the hat switch to the "east" position
• Move the X and Y coordinates to their extreme values
The Following table shows the button that has to be pressed on the demonstration board to emulate the joystick.
Demonstration Board Button
PIC32 USB Starter Kit II
PIC32 USB Starter Kit III
PIC32MZ Embedded Connectivity (EC) Starter Kit
PIC32MZ Embedded Connectivity with Floating Point Unit (EF) Starter Kit
SW1
Explorer 16 Development Board S3
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 28
hid_keyboard
Demonstrates a USB HID device, emulating a keyboard.
Description
This demonstration application creates a Generic HID keyboard. Pressing a key on the board emulates a keyboard key press.
Building the Application
This section identifies the MPLAB X IDE project name and location and lists and describes the available configurations for the USB HID Keyboard
Demonstration.
Description
To build this project, you must open the hid_keyboard.X project in MPLAB X IDE, and then select the desired configuration.
The following tables list and describe the project and supported configurations. The parent folder for these files is
/apps/usb/device/hid_keyboard.
MPLAB X IDE Project
This table lists the name and location of the MPLAB X IDE project folder for the demonstration.
Project Name Location
hid_keyboard.X /apps/usb/device/hid_keyboard/firmware
MPLAB X IDE Project Configurations
This table lists and describes the supported configurations of the demonstration, which are located within ./firmware/src/system_config.
Project Configuration Name BSP Used Description
pic32mx460_pim_e16_int_dyn pic32mx460_pim+e16 Select this MPLAB X IDE project configuration to run the demonstration on the Explorer
16 Development Board configured for Interrupt mode and dynamic operation. This
configuration also requires the PIC32MX460F512L Plug-In Module (PIM) and the USB
PICtail Plus Daughter Board.
pic32mx_usb_sk3_int_dyn pic32mx_usb_sk3 Select this MPLAB X IDE project configuration to run the demonstration on the PIC32
USB Starter Kit III configured for Interrupt mode and dynamic operation.
pic32mx_usb_sk2_int_dyn pic32mx_usb_sk2 Select this MPLAB X IDE project configuration to run the demonstration on the PIC32
USB Starter Kit II configured for Interrupt mode and dynamic operation.
pic32mz_ef_sk_int_dyn pic32mz_ef_sk Select this MPLAB X IDE project configuration to run the demonstration on the PIC32MZ
Embedded Connectivity with Floating Point Unit (EF) Starter Kit configured for Interrupt
mode and dynamic operation.
Configuring the Hardware
Describes how to configure the supported hardware.
Description
PIC32 USB Starter Kit II
Remove jumper JP2.
PIC32MZ EF Starter Kit
No hardware related configuration or jumper setting changes are necessary.
PIC32 USB Starter Kit III
Remove jumper JP1.
PIC32MX460F512L PIM
Jumper J10 should be removed. This plug-in module should be used along with the Explorer 16 Development Board and the USB PICtail Plus
daughter board. The microcontroller PIM should be plugged into the PIM_socket_on the board. The USB PICtail Plus daughter board should be
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 29
connected to the edge connector J9.
On the Explorer 16 Development Board:
• Switch S2 should be set to PIM
• Jumper JP2 should be in place
On the USB PICtail Plus Daughter Board:
• Jumper JP1 should be in place
• Jumper JP2 and JP4 should be removed
On the PIC32MX460F512L PIM:
• Keep jumper J10 open
• Keep all jumpers in J9 open
Running the Demonstration
Provides instructions on how to build and run the USB HID Keyboard demonstration.
Description
This demonstration uses the selected hardware platform as a USB keyboard. While compiling, select the appropriate MPLAB X IDE project
configuration based on the demonstration board. Refer to Building the Application for details.
The LEDs on the demonstration board will indicate the USB state of the device, as described in the USB Device State and LED Indication Table in
the Device section.
Before pressing the button, select a window in which it is safe to type text freely. Pressing the button on the demonstration board will cause the
device to print a character on the screen.
The following table shows the button that has to be pressed on the demonstration board to print a character.
Demonstration Board Button
PIC32 USB Starter Kit II
PIC32 USB Starter Kit III
PIC32MZ Embedded Connectivity (EC) Starter Kit
PIC32MZ Embedded Connectivity with Floating Point Unit (EF) Starter Kit
SW1
Explorer 16 Development Board S3
hid_mouse
Demonstrates a USB HID device, emulating a mouse pointing device.
Description
This demonstration application creates a USB HID based two-button mouse device. When connected, the device emulates mouse operation by
moving the cursor in a circular pattern.
Building the Application
This section identifies the MPLAB X IDE project name and location and lists and describes the available configurations for the USB HID Mouse
Demonstration.
Description
To build this project, you must open the hid_mouse.X project in MPLAB X IDE, and then select the desired configuration.
The following tables list and describe the project and supported configurations. The parent folder for these files is
/apps/usb/device/hid_mouse.
MPLAB X IDE Project
This table lists the name and location of the MPLAB X IDE project folder for the demonstration.
Project Name Location
hid_mouse.X /apps/usb/device/hid_mouse/firmware
MPLAB X IDE Project Configurations
This table lists and describes the supported configurations of the demonstration, which are located within ./firmware/src/system_config.
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 30
Project Configuration Name BSP Used Description
pic32mx460_pim_e16_int_dyn pic32mx460_pim+e16 Select this MPLAB X IDE project configuration to run the demonstration on the Explorer
16 Development Board configured for Interrupt mode and dynamic operation. This
configuration also requires the PIC32MX460F512L Plug-In Module (PIM) and the USB
PICtail Plus Daughter Board.
pic32mx_usb_sk3_int_dyn pic32mx_usb_sk3 Select this MPLAB X IDE project configuration to run the demonstration on the PIC32
USB Starter Kit III configured for Interrupt mode and dynamic operation.
pic32mx_usb_sk2_int_dyn pic32mx_usb_sk2 Select this MPLAB X IDE project configuration to run the demonstration on the PIC32
USB Starter Kit II configured for Interrupt mode and dynamic operation.
pic32mz_ef_sk_int_dyn pic32mz_ef_sk Select this MPLAB X IDE project configuration to run the demonstration on the PIC32MZ
Embedded Connectivity with Floating Point Unit (EF) Starter Kit configured for Interrupt
mode and dynamic operation.
Configuring the Hardware
Describes how to configure the supported hardware.
Description
PIC32 USB Starter Kit II
Remove jumper JP2.
PIC32MZ EF Starter Kit
No hardware related configuration or jumper setting changes are necessary.
PIC32 USB Starter Kit III
Remove jumper JP1.
PIC32MX460F512L PIM
Jumper J10 should be removed. This plug-in module should be used along with the Explorer 16 Development Board and the USB PICtail Plus
daughter board. The microcontroller PIM should be plugged into the PIM_socket_on the board. The USB PICtail Plus daughter board should be
connected to the edge connector J9.
On the Explorer 16 Development Board:
• Switch S2 should be set to PIM
• Jumper JP2 should be in place
On the USB PICtail Plus Daughter Board:
• Jumper JP1 should be in place
• Jumper JP2 and JP4 should be removed
On the PIC32MX460F512L PIM:
• Keep jumper J10 open
• Keep all jumpers in J9 open
Running the Demonstration
Provides instructions on how to build and run the HID Mouse Demonstration.
Description
This demonstration uses the selected hardware platform as a USB mouse. While compiling, select the appropriate MPLAB X IDE project
configuration based on the demonstration board. Refer to Building the Application for details.
The LEDs on the demonstration board will indicate the USB state of the device, as described in the USB Device State and LED Indication Table in
the Device section.
Before connecting the board to the computer through the USB cable please be aware that the device will begin moving the mouse cursor on the
computer. There are two ways to stop the device from allowing the cursor to continue to move. The first way is to disconnect the device from the
computer. The second is to press the correct button on the hardware platform. Pressing the button again will cause the mouse cursor to start
moving in a circle again.
The following table shows the button that has to be pressed on the demonstration board to stop the circular motion:
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 31
Demonstration Board Button
PIC32 USB Starter Kit II
PIC32 USB Starter Kit III
PIC32MZ Embedded Connectivity (EC) Starter Kit
PIC32MZ Embedded Connectivity with Floating Point Unit (EF) Starter Kit
SW1
Explorer 16 Development Board S3
hid_msd_basic
Demonstrates a HID Device Class and MSD class composite USB Device.
Description
This demonstration application creates a USB Device that combines the functionality of the hid_basic and msd_basic demonstration applications.
Building the Application
This section identifies the MPLAB X IDE project name and location and lists and describes the available configurations for the this demonstration
application.
Description
To build this project, you must open the hid_msd_basic.X project in MPLAB X IDE, and then select the desired configuration.
The following tables list and describe the project and supported configurations. The parent folder for these files is
/apps/usb/device/hid_msd_basic.
MPLAB X IDE Project
This table lists the name and location of the MPLAB X IDE project folder for the demonstration.
Project Name Location
hid_msd_basic.X /apps/usb/device/hid_msd_basic/firmware
MPLAB X IDE Project Configurations
This table lists and describes the supported configurations of the demonstration, which are located within ./firmware/src/system_config.
Project Configuration
Name
BSP Used Description
pic32mx_usb_sk2_int_dyn pic32mx_usb_sk2 Select this configuration to run the demonstration application on the PIC32 USB Starter Kit II
configured for Interrupt mode and dynamic operation.
pic32mz_ef_sk_int_dyn pic32mz_ef_sk Select this configuration to run the demonstration application on the PIC32MZ Embedded
Connectivity with Floating Point Unit (EF) Starter Kit configured for Interrupt mode and
dynamic operation.
Configuring the Hardware
Describes how to configure the supported hardware.
Description
PIC32 USB Starter Kit II
Remove jumper JP2.
PIC32MZ EF Starter Kit
No hardware related configuration or jumper setting changes are necessary.
Running the Demonstration
Provides instructions on how to build and run the demonstration.
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 32
Description
This demonstration functions as composite USB Device that combines the features of the devices created by the hid_basic and the msd_basic
demonstration applications. Refer to Running the Demonstration section of the hid_basic demonstration and Running the Demonstration section of
the msd_basic demonstration for details on exercising the HID and MSD functions, respectively.
The LEDs on the demonstration board will indicate the USB state of the device, as described in the USB Device State and LED Indication Table in
the Device section.
msd_basic
Demonstrates a USB MSD Device emulating a Flash Drive.
Description
This demonstration application creates a Flash drive using the Mass Storage Device Class.
Building the Application
This section identifies the MPLAB X IDE project name and location and lists and describes the available configurations for the USB MSD Basic
Demonstration.
Description
To build this project, you must open the msd_basic.X project in MPLAB X IDE, and then select the desired configuration.
The following tables list and describe the project and supported configurations. The parent folder for these files is
/apps/usb/device/msd_basic.
MPLAB X IDE Project
This table lists the name and location of the MPLAB X IDE project folder for the demonstration.
Project Name Location
msd_basic.X /apps/usb/device/msd_basic/firmware
MPLAB X IDE Project Configurations
This table lists and describes the supported configurations of the demonstration, which are located within ./firmware/src/system_config.
Project Configuration
Name
BSP Used Description
pic32mx_bt_sk_int_dyn pic32mx_bt_sk Select this MPLAB X IDE project configuration to run the demonstration on the PIC32
Bluetooth Starter Kit configured for Interrupt mode and dynamic operation.
pic32mx_usb_sk2_poll_dyn pic32mx_usb_sk2 Select this MPLAB X IDE project configuration to run the demonstration on the PIC32 USB
Starter Kit II with the USB Device Stack configured for Polled mode and dynamic operation..
pic32mx_usb_sk2_int_dyn pic32mx_usb_sk2 Select this MPLAB X IDE project configuration to run the demonstration on the PIC32 USB
Starter Kit II configured for Interrupt mode and dynamic operation.
pic32mx_usb_sk3_int_dyn pic32mx_usb_sk3 Select this MPLAB X IDE project configuration to run the demonstration on the PIC32 USB
Starter Kit III configured for Interrupt mode and dynamic operation.
pic32mz_ef_sk_int_dyn pic32mz_ef_sk Select this MPLAB X IDE project configuration to run the demonstration on the PIC32MZ
Embedded Connectivity with Floating Point Unit (EF) Starter Kit configured for Interrupt mode
and dynamic operation.
pic32mz_ef_sk_poll_dyn pic32mz_ef_sk Select this MPLAB X IDE project configuration to run the demonstration on the PIC32MZ
Embedded Connectivity with Floating Point Unit (EF) Starter Kit configured for Polled mode
and dynamic operation.
Configuring the Hardware
Describes how to configure the supported hardware.
Description
PIC32 USB Starter Kit II
Remove jumper JP2.
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 33
PIC32MZ EF Starter Kit
No hardware related configuration or jumper setting changes are necessary.
PIC32 USB Starter Kit III
Remove jumper JP1.
PIC32 Bluetooth Starter Kit
No hardware related configuration or jumper settings required.
PIC32MX460F512L PIM
Jumper J10 should be removed. This plug-in module should be used along with the Explorer 16 Development Board and the USB PICtail Plus
daughter board. The microcontroller PIM should be plugged into the PIM_socket_on the board. The USB PICtail Plus daughter board should be
connected to the edge connector J9.
On the Explorer 16 Development Board:
• Switch S2 should be set to PIM
• Jumper JP2 should be in place
On the USB PICtail Plus Daughter Board:
• Jumper JP1 should be in place
• Jumper JP2 and JP4 should be removed
Running the Demonstration
Provides instructions on how to build and run the USB MSD Basic demonstration.
Description
This demonstration uses the selected hardware platform as a logical drive on the computer using the internal Flash of the device as the drive
storage media. Connect the hardware platform to a computer through a USB cable. The device should appear as a new drive on the computer
named "Drive Name". The drive can used to store files.
The LEDs on the demonstration board will indicate the USB state of the device, as described in the USB Device State and LED Indication Table in
the Device section.
Note:
Reprogramming the development board will cause any stored files to be erased.
msd_fs_spiflash
This application demonstrates accessing the SPI Flash connected to the PIC32 device as a media by multiple clients.
Description
This application demonstrates accessing the SPI Flash connected to the PIC32 device as a media by multiple clients. When connected via USB to
the Host Computer, the SPI Flash is shown as the storage media. The Host writes files to the media, which is later accessed by the application
running on the PIC32 device using the File System.
Building the Application
This section identifies the MPLAB X IDE project name and location and lists and describes the available configurations for the USB MSD File
System SPI Flash Demonstration.
Description
To build this project, you must open the msd_fs_spiflash.X project in MPLAB X IDE, and then select the desired configuration.
The following tables list and describe the project and supported configurations. The parent folder for these files is
/apps/usb/device/msd_fs_spiflash.
MPLAB X IDE Project
This table lists the name and location of the MPLAB X IDE project folder for the demonstration.
Project Name Location
msd_fs_spiflash.X /apps/usb/device/msd_fs_spiflash/firmware
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 34
MPLAB X IDE Project Configurations
This table lists and describes the supported configurations of the demonstration, which are located within ./firmware/src/system_config.
Project Configuration
Name
BSP Used Description
bt_audio_dk_int_dyn bt_audio_dk Select this MPLAB X IDE project configuration to run the demonstration on the PIC32
Bluetooth Audio Development Kit.
Configuring the Hardware
Describes how to configure the supported hardware.
Description
PIC32 Bluetooth Audio Develoment Kit
Ensure that switch S1 is set to PIC32_MCLR.
Running the Demonstration
Provides instructions on how to build and run the USB MSD File System SPI Flash demonstration.
Description
This demonstration shows an example of:
• Accessing the media attached to PIC32 by multiple clients
• Application running on the PIC32 firmware accesses the media using the MPLAB Harmony File System
When connected to the USB Host the very first time, the user is expected to format the media and create a file named FILE.TXT in the root
directory of the media. The user can update the file to provide input for the application to glow the LEDs present on the development kit. The
application running on the PIC32 reads and interprets the data present in the file and accordingly turns ON or OFF the LEDs LED8 and LED9 of
the development kit. The format of input in the file FILE.TXT should be as follows:
• For turning ON an LED:
• LED8:1
• LED9:1
• For turning OFF an LED:
• LED8:0
• LED9:0
After having set the appropriate values in the file, the user can then press and release the wwitch SW1 located on the development kit for the
MPLAB Harmony File System running on the PIC32 to act upon the contents of the file.
The FS state machine of the demonstration is only triggered by the switch SW1. When the user presses and releases SW1 the following occurs:
• LED5 is turned ON to indicate that the FS state machine is running
• The USB is detached
• The file system on the SPI Flash is mounted
• The contents of FILE.TXT is read and acted upon. Depending on the values set in the file, the LEDs are either turned ON or OFF.
• Next, the file system is unmounted and the USB is reattached
• LED5 is turned OFF to indicate that FS state machine is no longer running
• If LED6 is turned ON during any part of the demonstration, this indicates the demonstration has failed
msd_multiple_luns
This topic demonstrates data transfer between two storage media - SD card and non-volatile memory (NVM) - and a computer through USB Mass
Storage Device (MSD).
Description
This application demonstrates the creation of a USB device with multiple logical units. The storage media, SD Card, acts as one logical unit, and
the NVM acts as the second logical unit. Data transfer between a computer and the logical units (SD Card / NVM) takes place through USB MSD.
Building the Application
This section identifies the MPLAB X IDE project name and location, and then lists and describes the available configurations for the USB MSD
multiple LUNs demonstration.
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 35
Description
To build this project, you must open the msd_multiple_luns.X project in MPLAB X IDE, and then select the desired configuration. The
following tables lists and describes the project and the supported configurations. The parent folder for these files is
/apps/usb/device/msd_multiple_luns
MPLAB X IDE Project
This table lists the name and location of the MPLAB X IDE project folder for the demonstration.
Project Name Location
msd_multiple_luns.X /apps/usb/device/msd_multiple_luns/firmware
MPLAB X IDE Project Configurations
This table lists and describes the supported configurations of the demonstration, which are located within ./firmware/src/system_config.
Project
Configuration Name
BSP Used Description
pic32mx470_curiosity pic32mx470_curiosity Select this MPLAB X IDE project configuration to run the demonstration on the PIC32MX470
Curiosity board with the USB device stack configured for Interrupt mode and full speed operation.
The LUN0 media type is configured as SD Card and LUN1 media type is configured as NVM.
pic32mz_ef_curiosity pic32mz_ef_curiosity Select this MPLAB X IDE project configuration to run the demonstration on the PIC32MZ EF
Curiosity board with the USB device stack configured for Interrupt mode and high speed
operation. The LUN0 media type is configured as SD Card and LUN1 media type is configured as
NVM.
Configuring the Hardware
This section describes how to configure the supported hardware.
Description
PIC32MX470 Curiosity Development Board
1. Ensure that a jumper is placed at 4-3 on J8, to select supply from debug USB connector.
2. Mount the SD Click board, "microSD click" from MikroElektronika (http://www.mikroe.com/click/microsd/) on the mikro bus interface J10.
3. Plug a micro SD card into the microSD click board card slot.
4. Power the PIC32MX470 Curiosity Development Board from a Host PC through a Type-A male to mini-B USB cable connected to Mini-B port
(J3).
5. Connect a Type-A male to micro USB cable to the micro USB port (J12) on PIC32MX470 Curiosity Development Board.
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 36
PIC32MZ EF Curiosity Development Board
1. Ensure that a jumper is placed at 4-3 on J8, to select supply from debug USB connector.
2. Mount the SD Click board, "microSD click" from MikroElektronika (http://www.mikroe.com/click/microsd/) on the mikro bus interface J10.
3. Plug a micro SD card into the microSD click board card slot.
4. Power the PIC32MZ EF Curiosity Development Board from a Host PC through a Type-A male to micro USB cable connected to micro USB port
(J3).
5. Connect a Type-A male to micro USB cable to the micro USB port (J12) on PIC32MZ EF Curiosity Development Board.
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 37
Running the Demonstration
This section provides instructions about how to build and run the USB MSD Multiple LUNs demonstration.
Description
This demonstration uses SD card and NVM as drive storage media and shows them as two logical drives on the computer.
• Connect the hardware platform to a computer through a USB cable.
• The device should appear as two new drives on the computer.
• The NVM media should appear as "Drive Name" and should have a sample “FILE.txt” file. The drive name for the SD card media depends
on the micro SD card vendor. The drives can then be used to store files.
• The LEDs on the demonstration board will indicate the USB state of the device, as described in the USB Device State and LED Indication
Table in the Device section.
Note:
Reprogramming the development board will cause any stored files in the NVM media to be erased.
msd_sdcard
Demonstrates data transfer from a SD card and a computer through USB MSD.
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 38
Description
This application demonstrates the usage of a SD card reader through the USB Mass Storage Device (MSD) class to transfer data between a
computer and SD card. High-Speed USB is used for communication between the Host computer and the PIC32 device, while a SD card is used as
the storage medium.
Building the Application
This section identifies the MPLAB X IDE project name and location and lists and describes the available configurations for the USB MSD SD Card
Demonstration.
Description
To build this project, you must open the msd_sdcard.X project in MPLAB X IDE, and then select the desired configuration.
The following tables list and describe the project and supported configurations. The parent folder for these files is
/apps/usb/device/msd_sdcard.
MPLAB X IDE Project
This table lists the name and location of the MPLAB X IDE project folder for the demonstration.
Project Name Location
msd_sdcard.X /apps/usb/device/msd_sdcard/firmware
MPLAB X IDE Project Configurations
This table lists and describes the supported configurations of the demonstration, which are located within ./firmware/src/system_config.
Project Configuration
Name
BSP Used Description
pic32mz_ec_sk_int_dyn pic32mz_ec_sk+meb2 Select this MPLAB X IDE project configuration to run the demonstration on the PIC32MZ EC
Starter Kit connected to the MEB II. The media drivers are configured for Interrupt mode and
dynamic operation.
Configuring the Hardware
Describes how to configure the supported hardware.
Description
PIC32MZ Embedded Connectivity (EC) Starter Kit and Multimedia Expansion Board II (MEB II)
No hardware related configuration or jumper settings required.
Running the Demonstration
Provides instructions on how to build and run the USB MSD SD Card demonstration.
Description
This demonstration uses the selected hardware platform as a logical drive on the computer using the SD card as the drive storage media. Connect
the hardware platform to a computer through a USB cable. The device should appear as a new drive on the computer named "Drive Name". The
drive can then be used to store files.
The LEDs on the demonstration board will indicate the USB state of the device, as described in the USB Device State and LED Indication Table in
the Device section.
vendor
Demonstrates a custom USB Device created by using the USB Device Layer Endpoint functions.
Description
This demonstration application creates a custom USB device using the USB Device Layer Endpoint functions.
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 39
Building the Application
This section identifies the MPLAB X IDE project name and location and lists and describes the available configurations for the Vendor USB Device
Demonstration.
Description
To build this project, you must open the vendor.X project in MPLAB X IDE, and then select the desired configuration.
The following tables list and describe the project and supported configurations. The parent folder for these files is
/apps/usb/device/vendor.
MPLAB X IDE Project
This table lists the name and location of the MPLAB X IDE project folder for the demonstration.
Project Name Location
vendor.X /apps/usb/device/vendor/firmware
MPLAB X IDE Project Configurations
This table lists and describes the supported configurations of the demonstration, which are located within ./firmware/src/system_config.
Project Configuration Name BSP Used Description
pic32mx460_pim_e16_int_dyn pic32mx460_pim+e16 Select this MPLAB X IDE project configuration to run the demonstration on the Explorer
16 Development Board configured for Interrupt mode and dynamic operation. This
configuration also requires the PIC32MX460F512L Plug-In Module (PIM) and the USB
PICtail Plus Daughter Board.
pic32mx_usb_sk3_int_dyn pic32mx_usb_sk3 Select this MPLAB X IDE project configuration to run the demonstration on the PIC32
USB Starter Kit III configured for Interrupt mode and dynamic operation.
pic32mx_usb_sk2_int_dyn pic32mx_usb_sk2 Select this MPLAB X IDE project configuration to run the demonstration on the PIC32
USB Starter Kit II configured for Interrupt mode and dynamic operation.
pic32mz_ef_sk_int_dyn pic32mz_ef_sk Select this MPLAB X IDE project configuration to run the demonstration on the PIC32MZ
Embedded Connectivity with Floating Point Unit (EF) Starter Kit configured for Interrupt
mode and dynamic operation.
Configuring the Hardware
Describes how to configure the supported hardware.
Description
PIC32 USB Starter Kit II
Remove jumper JP2.
PIC32MZ EF Starter Kit
No hardware related configuration or jumper setting changes are necessary.
PIC32 USB Starter Kit III
Remove jumper JP1.
PIC32MX460F512L PIM
Jumper J10 should be removed. This plug-in module should be used along with the Explorer 16 Development Board and the USB PICtail Plus
daughter board. The microcontroller PIM should be plugged into the PIM_socket_on the board. The USB PICtail Plus daughter board should be
connected to the edge connector J9.
On the Explorer 16 Development Board:
• Switch S2 should be set to PIM
• Jumper JP2 should be in place
On the USB PICtail Plus Daughter Board:
• Jumper JP1 should be in place
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 40
• Jumper JP2 and JP4 should be removed
On the PIC32MX460F512L PIM:
• Keep jumper J10 open
• Keep all jumpers in J9 open
Running the Demonstration
Provides instructions on how to build and run the Vendor USB Device demonstration.
Description
The Vendor device can be exercised by using the WinUSB PnP Demonstration application, which is provided in your installation of MPLAB
Harmony.
The LEDs on the demonstration board will indicate the USB state of the device, as described in the USB Device State and LED Indication Table in
the Device section.
This application allows the state of the LEDs on the board to be toggled and indicates the state of a switch (pressed/released) on the board.
To launch the application, double click WinUSB PnP Demo.exe located in /apps/usb/device/vendor/bin. A dialog box
similar to the following should appear:
The appropriate device family that is under testing should be selected in the utility. Pressing the Toggle LED button will cause the LED on the
board to toggle. The Pushbutton State field in the application indicates the state of a button on connected USB Device. Pressing the switch on the
development board will update the Pressed/Not Pressed status of the Pushbutton State field.
Demonstration Board Button
PIC32 USB Starter Kit II
PIC32 USB Starter Kit III
PIC32MZ Embedded Connectivity (EC) Starter Kit
PIC32MZ Embedded Connectivity with Floating Point Unit (EF) Starter Kit
SW1
Explorer 16 Development Board S3
Note:
The device family under test should be selected appropriately. An incorrect selection will result in an invalid push button status.
Host
This section describes the USB Host demonstrations.
audio_speaker
This application demonstrates the use of the Audio v1.0 Host Class Driver to enumerate and operate an audio speaker device.
Description
This application demonstrates the use of the Audio v1.0 Host Class Driver to enumerate and an audio speaker device. The application uses the
USB Host Layer and Audio 1.0 class driver to enumerate an Audio v1.0 USB device. The demonstration host application then operates and uses
the functionality of the attached audio speaker device.
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 41
Building the Application
This section identifies the MPLAB X IDE project name and location and lists and describes the available configurations for the USB Host Audio
Speaker Demonstration.
Description
To build this project, you must open the audio_speaker.X project in MPLAB X IDE, and then select the desired configuration.
The following tables list and describe the project and supported configurations. The parent folder for these files is
/apps/usb/host/audio_speaker.
MPLAB X IDE Project
This table lists the name and location of the MPLAB X IDE project folder for the demonstration.
Project Name Location
audio_speaker.X /apps/usb/host/audio_speaker/firmware
MPLAB X IDE Project Configurations
This table lists and describes the supported configurations of the demonstration, which are located within ./firmware/src/system_config.
Project Configuration
Name
BSP Used Description
pic32mx_usb_sk2_int_dyn pic32mx_usb_sk2 Select this MPLAB X IDE project configuration to run the demonstration on the PIC32 USB
Starter Kit II configured for Interrupt mode and dynamic operation.
pic32mz_ef_sk_int_dyn pic32mz_ef_sk Select this MPLAB X IDE project configuration to run the demonstration on the PIC32MZ
Embedded Connectivity with Floating Point Unit (EF) Starter Kit configured for Interrupt mode
and dynamic operation.
Configuring the Hardware
Describes how to configure the supported hardware.
Description
PIC32 USB Starter Kit II
JP2 should be in place.
PIC32MZ EF Starter Kit
No hardware related configuration or jumper setting changes are necessary.
Running the Demonstration
Provides instructions on how to build and run the USB Host Audio v1.0 Basic Demo.
Description
This application demonstrates the use of the Audio v1.0 Host Class Driver to enumerate and operate an Audio v1.0 Device. The application uses
the USB Host layer and Audio v1.0 class driver to enumerate a Audio v1.0 USB device. The demonstration host application then operates and
uses the functionality of the attached Audio v1.0 Device.
Prior to using this demonstration, it is recommended to review the MPLAB Harmony Release Notes for any known issues. A PDF copy of the
release notes is provided in the /doc folder of your installation.
1. Open the project in MPLAB X IDE and select the desired project configuration.
2. Build the code and program the device.
3. Attach a commercially available USB speaker to the board.
4. LED1 is turned ON if the attached device is accepted by the Audio 1.0 class driver.
5. The speaker should produce a 1 kHz sine wave.
6. LED2 will continue blinking if the demonstration application cannot accept the device.
7. Press switch SW1 to mute the audio.
8. Press switch SW2 to unmute the audio
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 42
cdc_basic
This application demonstrates the use of the CDC Host Class Driver to enumerate and operate a CDC Device.
Description
This application demonstrates the use of the CDC Host Class Driver to enumerate and operate a CDC Device. The application uses the USB
Host_layer and CDC class driver to enumerate a CDC USB device. The demonstration host application then operates and uses the functionality of
the attached CDC Device.
Building the Application
This section identifies the MPLAB X IDE project name and location and lists and describes the available configurations for the USB CDC Host
Basic Demonstration.
Description
To build this project, you must open the cdc_basic.X project in MPLAB X IDE, and then select the desired configuration.
The following tables list and describe the project and supported configurations. The parent folder for these files is
/apps/usb/host/cdc_basic.
MPLAB X IDE Project
This table lists the name and location of the MPLAB X IDE project folder for the demonstration.
Project Name Location
cdc_basic.X /apps/usb/host/cdc_basic/firmware
MPLAB X IDE Project Configurations
This table lists and describes the supported configurations of the demonstration, which are located within ./firmware/src/system_config.
Project Configuration
Name
BSP Used Description
pic32mx_usb_sk2_int_dyn pic32mx_usb_sk2 Select this MPLAB X IDE project configuration to run the demonstration on the PIC32 USB
Starter Kit II configured for Interrupt mode and dynamic operation.
pic32mx_usb_sk2_poll_dyn pic32mx_usb_sk2 Select this MPLAB X IDE project configuration to run the demonstration on the PIC32 USB
Starter Kit II configured for Polled mode and dynamic operation.
pic32mz_ef_sk_int_dyn pic32mz_ef_sk Select this MPLAB X IDE project configuration to run the demonstration on the PIC32MZ
Embedded Connectivity with Floating Point Unit (EF) Starter Kit configured for Interrupt
mode and dynamic operation.
Configuring the Hardware
Describes how to configure the supported hardware.
Description
PIC32 USB Starter Kit II
JP2 should be in place.
PIC32MZ EF Starter Kit
No hardware related configuration or jumper setting changes are necessary.
Running the Demonstration
Provides instructions on how to build and run the USB Host CDC Basic Demo.
Description
This application demonstrates the use of the CDC Host Class Driver to enumerate and operate a CDC Device. The application uses the USB
Host_layer and CDC class driver to enumerate a CDC USB device. The demonstration host application then operates and uses the functionality of
the attached CDC Device.
Prior to using this demonstration, it is recommended to review the MPLAB Harmony Release Notes for any known issues. A PDF copy of the
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 43
release notes is provided in the /doc folder of your installation.
1. Open_the project in MPLAB X IDE and select the desired project configuration.
2. Build the code and program the device.
3. Follow the directions for setting up and running the cdc_serial_emulator USB device demonstration.
4. Connect the UART (P1) port on the Explorer 16 Development Board (running the cdc_serial_emulator demonstration) to a USB Host personal
computer via a commercially available Serial-to-USB Dongle.
5. Start a terminal program on the USB Host personal computer and select the Serial-to-USB Dongle as the communication port. Select the baud
rate as 9600, no parity, 1 Stop bit and no flow control.
6. Connect the mini – B connector on the USB PICtail Plus Daughter Board, of the cdc_serial_emulator demonstration setup, to the USB host
connector on the starter kit. For PIC32M-based starter kits, connect to the on-board Type-A connector.
7. A prompt (LED :) will be displayed immediately on the terminal emulation program.
8. Pressing either the 1, 2, or 3 key on the USB Host keyboard will cause LEDs on the PIC32 starter kit (running the USB CDC Host application)
to switch on, respectively. On PIC32M-based starter kits, the LEDs are LED1, LED2, and LED3.
9. The prompt will again be displayed on terminal emulation program, and step 8 can be repeated.
The setup should be similar to the following diagram.
The cdc_serial_emulator demonstration emulates a USB-to-Serial Dongle. The CDC Host (running the cdc_basic demonstration application)
sends the prompt message to the CDC device. The CDC device forwards the prompt to the UART port from where it is transmitted to the personal
computer USB Host through the USB-to-Serial Dongle. A key press on the personal computer USB Host is transmitted to the CDC device, which in
turn presents the key press data to the CDC host. The cdc_basic demonstration then analyzes the key press data and switches on the respective
LED.
cdc_msd
Demonstrates host support for multiple device classes.
Description
This demonstration application creates a USB Host that can support different device classes in one application.
Building the Application
This section identifies the MPLAB X IDE project name and location and lists and describes the available configurations for this USB CDC MSD
Host Demonstration.
Description
To build this project, you must open the cdc_msd.X project in MPLAB X IDE, and then select the desired configuration.
The following tables list and describe the project and supported configurations. The parent folder for these files is
/apps/usb/host/cdc_msd.
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 44
MPLAB X IDE Project
This table lists the name and location of the MPLAB X IDE project folder for the demonstration.
Project Name Location
cdc_msd.X /apps/usb/host/cdc_msd/firmware
MPLAB X IDE Project Configurations
This table lists and describes the supported configurations of the demonstration, which are located within ./firmware/src/system_config.
Project Configuration
Name
BSP Used Description
pic32mx_usb_sk2_int_dyn pic32mx_usb_sk2 Select this MPLAB X IDE project configuration to run the demonstration on the PIC32 USB
Starter Kit II configured for Interrupt mode and dynamic operation.
pic32mz_ef_sk_int_dyn pic32mz_ef_sk Select this MPLAB X IDE project configuration to run the demonstration on the PIC32MZ
Embedded Connectivity with Floating Point Unit (EF) Starter Kit configured for Interrupt mode
and dynamic operation.
Configuring the Hardware
Describes how to configure the supported hardware.
Description
PIC32 USB Starter Kit II
JP2 should be in place.
PIC32MZ EF Starter Kit
No hardware related configuration or jumper setting changes are necessary.
Running the Demonstration
Provides instructions on how to build and run the USB CDC MSD demonstration.
Description
This demonstration application creates a USB Host application that enumerates a CDC and a MSD device. This application combines the
functionality of the Host cdc_basic and msd_basic demonstration applications into one application. If a CDC device is connected, the
demonstration application behaves like the cdc_basic host application. If a MSD device is connected, the demonstration application behaves like
the msd_basic host application.
Refer to Running the Demonstration section of the host cdc_basic demonstration and the Running the Demonstration section of the host
msd_basic demonstration for details on exercising the CDC and MSD host aspects of the demonstration.
hid_basic_keyboard
Demonstrates using the USB HID Host Client driver with the Keyboard Usage driver to facilitate the use of a USB HID Keyboard with a PIC32 USB
Host.
Description
This application demonstrates the use of the USB HID Host Client Driver to enumerate and operate a HID keyboard device. The application uses
the USB Host layer, HID Client driver and HID Keyboard Usage driver to enumerates a USB keyboard and understand keyboard press release
events.
The keyboard events are displayed using a terminal emulator on a personal computer.
Building the Application
This section identifies the MPLAB X IDE project name and location and lists and describes the available configurations for the USB HID Basic
Keyboard Demonstration.
Description
To build this project, you must open the hid_basic_keyboard.X project in MPLAB X IDE, and then select the desired configuration.
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 45
The following tables list and describe the project and supported configurations. The parent folder for these files is
/apps/usb/host/hid_basic_keyboard.
MPLAB X IDE Project
This table lists the name and location of the MPLAB X IDE project folder for the demonstration.
Project Name Location
hid_basic_keyboard.X /apps/usb/host/hid_basic_keyboard/firmware
MPLAB X IDE Project Configurations
This table lists and describes the supported configurations of the demonstration, which are located within ./firmware/src/system_config.
Project Configuration Name BSP Used Description
pic32mx795_pim_e16_int_dyn pic32mx795_pim+e16 Select this MPLAB X IDE project configuration to run the demonstration configured for
Interrupt mode and dynamic operation on the PIC32MX795F512L PIM connected to the
Explorer 16 Development Board with the USB PICtail Plus Daughter Board attached.
pic32mz_ef_sk_int_dyn pic32mz_ef_sk Select this MPLAB X IDE project configuration to run the demonstration on the PIC32MZ
Embedded Connectivity with Floating Point Unit (EF) Starter Kit configured for Interrupt
mode and dynamic operation.
Configuring the Hardware
Describes how to configure the supported hardware.
Description
PIC32MZ Embedded Connectivity with Floating Point Unit (EF) Starter Kit
No hardware related configuration or jumper setting changes are necessary.
Explorer 16 Development Board
• Switch S2 should be set to PIM
USB PICtail Plus Daughter Board
• Jumper the Host Enable pins
• Device Enable and OTG Enable should be open
PIC32MX795F512L CAN-USB PIM
• Keep jumper J10 open
• Keep all jumpers in J9 open
• Jumper J1 should be shorted between positions 1 and 2. This configuration is only applicable for the PIC32MX795F512L USB CAN PIM
(MA320003), and not the PIC32MX795F512L USB PIM (MA320002).
• Jumper J2 should be shorted between positions 1 and 2. This configuration is only applicable for the PIC32MX795F512L USB CAN PIM
(MA320003) and not the PIC32MX795F512L USB PIM (MA320002).
For the pic32mx795_pim_e16_int_dyn configuration:
1. Ensure that the PIC32MX795F512L PIM is connected properly to the PIM socket on the Explorer 16 Development Board.
2. Connect the Serial Port connector on the Explorer 16 Development Board to a PC using a Serial-to-USB converter cable.
3. Connect the USB PICtail Plus Daughter Board to the horizontal edge connector (J9) of the Explorer 16 Development Board.
For the pic32mz_ef_sk_int_dyn configuration:
Connect the USB to the UART connector (J11) on the PIC32MZ EF Starter Kit to a PC using a USB micro cable.
Running the Demonstration
Provides instructions on how to build and run the USB HID Basic Keyboard demonstration.
Description
1. Open the project in MPLAB X IDE and select the project configuration.
2. Build the code and program the device.
3. Launch a terminal emulator, such as Tera Term, and select the appropriate COM port and set the serial port settings to 115200-N-1.
4. If a USB keyboard is not connected to the PIC32 USB Host, the terminal emulator window will show the Connect Keyboard prompt.
5. Attach a USB keyboard to the Host connector of the target hardware. The message, Keyboard Connected, will appear in the terminal emulator
window.
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 46
6. Begin typing on the keyboard and the appropriate keys should be displayed on the serial terminal. Subsequent press and release of modifier
keys (i.e., CAPS LOCK, NUM LOCK, etc.) will result in the appropriate keyboard LEDs to turning ON and OFF.
7. Disconnecting the keyboard will result in the message, Connect Keyboard.
hid_basic_mouse_usart
This topic demonstrates USB Host support for a USB HID Mouse.
Description
This application demonstrates the use of the USB HID Host Client Driver to enumerate and operate a HID mouse device. The application uses the
USB Host layer, HID Client driver and HID Mouse Usage driver to enumerate USB mouse and decode mouse-generated data.
Mouse-specific movements events are demonstrated by displaying relative coordinate changes using a serial terminal emulator on a personal
computer. Mouse button clicks are indicated by LEDs.
Building the Application
This section does the following:
• Identifies the MPLAB X IDE project name and location.
• Lists and describes the available configurations for the USB HID Basic Mouse USART demonstration.
Description
To build this project, you must open the hid_basic_mouse_usart.X project in MPLAB X IDE, and then select the desired configuration.
The following tables list and describe the project and supported configurations. The parent folder for these files is
/apps/usb/host/hid_basic_mouse_usart.
MPLAB X IDE Project
This table lists the name and location of the MPLAB X IDE project folder for the demonstration.
Project Name Location
hid_basic_mouse_usart.X /apps/usb/host/hid_basic_mouse_usart/firmware
MPLAB X IDE Project Configurations
This table lists and describes the supported configurations of the demonstration, which are located within ./firmware/src/system_config.
Project
Configuration Name
BSP Used Description
pic32mz_ef_sk_meb2 pic32mz_ef_sk+meb2 Select this MPLAB X IDE project configuration to run the demonstration on the PIC32MZ
Embedded Connectivity with Floating Point Unit (EF) Starter Kit attached to Multimedia
Expansion Board II (MEB II) board.
Configuring the Hardware
This section describes how to configure the supported hardware.
Description
1. Ensure that the PIC32MZ Embedded Connectivity with Floating Point Unit (EF) Starter Kit is securely fastened into the MEB II expansion board.
2. Connect the USB to the UART connector (J11) on the PIC32MZ EF Starter Kit to a PC using a USB micro cable.
Note:
No hardware related configuration or jumper setting changes are necessary.
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 47
Running the Demonstration
This section provides instructions about how to build and run the USB HID Mouse USART demonstration.
Description
1. Open the project in MPLAB X IDE and select the project configuration.
2. Build the code and program the device.
3. Launch a terminal emulator, such as Tera Term. Select the appropriate COM port and set the serial port settings to 115200-N-1.
• If a USB mouse is not connected to the Host connector by using J5 on the PIC32 MZ EF Starter Kit, the serial terminal emulator window will
show the "Connect Mouse" prompt.
4. Attach a USB mouse to the Host connector of the target hardware. The message, "Mouse Connected", will display in the serial terminal
emulator window.
5. Begin moving the mouse and the appropriate relative coordinate changes for X,Y, and Z axes should be displayed in the serial terminal window.
6. Click the mouse button to toggle LEDs on the MEB II board as shown in the following table.
Mouse Click MEB II LED
Left D3
Right D4
Middle D5
Lower Left D6
Lower Right D7
• Disconnecting the mouse will result in the message, "Connect Mouse", to reappear on the serial console.
hub_cdc_hid
Demonstrates the enumeration of a HID mouse and CDC emulator device via an external hub.
Description
This application demonstrates the capability of the USB Host Stack to access and manage multiple USB Devices through a Hub. The
demonstration application enumerates a HID mouse and CDC emulator device via an external hub. The host will demonstrate the communication
from the CDC emulator device and the HID mouse.
Building the Application
This topic identifies the MPLAB X IDE project name and location and lists and describes the available configurations for the USB Host HUB CDC
HID Demonstration.
Description
To build this project, you must open the hub_cdc_hid.X project in MPLAB X IDE, and then select the desired configuration.
The following tables list and describe the project and supported configurations. The parent folder for these files is
/apps/usb/host/hub_cdc_hid.
MPLAB X IDE Project
This table lists the name and location of the MPLAB X IDE project folder for the demonstration.
Project Name Location
hub_cdc_hid.X /apps/usb/host/hub_cdc_hid/firmware
MPLAB X IDE Project Configurations
This table lists and describes the supported configurations of the demonstration, which are located within ./firmware/src/system_config.
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 48
Project Configuration
Name
BSP Used Description
pic32mx_usb_sk2_int_dyn pic32mx_usb_sk2 Select this MPLAB X IDE project configuration to run the demonstration on the PIC32 USB
Starter Kit II configured for Interrupt mode and dynamic operation.
pic32mz_ef_sk_int_dyn pic32mz_ef_sk Select this MPLAB X IDE project configuration to run the demonstration on the PIC32MZ
EF Starter Kit configured for Interrupt mode and dynamic operation.
Configuring the Hardware
Describes how to configure the supported hardware.
Description
PIC32 USB Starter Kit II
JP2 should be in place.
PIC32MZ EF Starter Kit
No hardware related configuration or jumper setting changes are necessary.
Running the Demonstration
Provides instructions on how to build and run the USB Host HUB CDC HID demonstration.
Description
This application demonstrates the capability of the USB Host Stack to access and manage multiple USB Devices through a Hub. The
demonstration application enumerates a HID mouse and CDC emulator device via an external hub. The host will demonstrate the communication
from the CDC emulator device and the HID mouse.
1. Open the project in MPLAB X IDE and select the desired project configuration.
2. Build the code and program the device.
3. Connect a hub to the Type A Host connector on the desired board.
4. Connect a mouse to a spare port on the hub.
5. Connect the CDC emulator device to another spare port on the hub.
6. Click the mouse to toggle LEDs on the starter kit.
7. On the personal computer, open a terminal emulator. At the prompt, (LED:), enter 1, 2, or 3 to toggle the LEDs on the starter kit.
hub_msd
This application demonstrates the capability of the USB Host stack to support multiple MSD device through a hub.
Description
This application demonstrates the use of the Hub Driver and the MSD Host Client Driver, with File System, to support multiple MSD devices and
Hub. The demonstration application copies a file from one pen driver into another pen drive.
Building the Application
This section identifies the MPLAB X IDE project name and location and lists and describes the available configurations for the USB Host Hub MSD
Demonstration.
Description
To build this project, you must open the hub_msd.X project in MPLAB X IDE, and then select the desired configuration.
The following tables list and describe the project and supported configurations. The parent folder for these files is
/apps/usb/host/hub_msd.
MPLAB X IDE Project
This table lists the name and location of the MPLAB X IDE project folder for the demonstration.
Project Name Location
hub_msd.X /apps/usb/host/hub_msd/firmware
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 49
MPLAB X IDE Project Configurations
This table lists and describes the supported configurations of the demonstration, which are located within ./firmware/src/system_config.
Project Configuration
Name
BSP Used Description
pic32mx_usb_sk2_int_dyn pic32mx_usb_sk2 Select this MPLAB X IDE project configuration to run the demonstration on the PIC32 USB
Starter Kit II configured for Interrupt mode and dynamic operation.
pic32mz_ef_sk_int_dyn pic32mz_ef_sk Select this MPLAB X IDE project configuration to run the demonstration on the PIC32MZ
Embedded Connectivity with Floating Point Unit (EF) Starter Kit configured for Interrupt mode
and dynamic operation.
Configuring the Hardware
Describes how to configure the supported hardware.
Description
PIC32 USB Starter Kit II
JP2 should be in place.
PIC32MZ EF Starter Kit
No hardware related configuration or jumper setting changes are necessary.
Running the Demonstration
Provides instructions on how to build and run the USB Host Hub MSD demonstration.
Description
This application demonstrates the capability of the USB Host Stack to access and manage multiple USB Devices through a Hub. The
demonstration application copies a file from one USB pen drive (i.e., a USB Flash storage device) to another USB pen drive, where these pen
drives are attached to a hub.
Note:
The demonstration will search for a file named file.txt on any of the connected pen drives. Such a file should be created on
one of the pen drives through any suitable method.
1. Open the project in MPLAB X IDE and select the desired project configuration.
2. Build the code and program the device.
3. Connect a hub to the Type A Host connector on the desired board.
4. Connect a USB Pen drive containing an arbitrary file named file.txt to a spare port on the hub.
5. Connect another USB pen drive to another spare port on the hub.
6. The application will copy the file file.txt from the drive containing this file to the other drive. The copied file will be renamed as
newfile.txt. LED 2 on the demonstration board will illuminate to indicate completion of the file transfer.
7. Disconnect the drives and confirm demonstration success by inserting them into a personal computer and verifying the file transfer completed
as expected.
The demonstration application will always be in state where it waits for two pen drives to be connected to the hub and at least one of these pen
drives contains a file named file.txt.
msd_basic
This application demonstrates the use of the MSD Host Class Driver to write a file to USB Flash Drive.
Description
This application demonstrates the use of the MSD Host Class Driver to write a file to a USB Flash drive. The application uses the USB Host_layer ,
MSD class driver and the MPLAB Harmony File System Framework to enumerate a USB Flash drive and to write a file to it.
Building the Application
This section identifies the MPLAB X IDE project name and location, and lists and describes the available configurations for the USB MSD Host
Class Driver Demonstration.
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 50
Description
To build this project, you must open the msd_basic.X project in MPLAB X IDE, and then select the desired configuration.
The following tables list and describe the project and supported configurations. The parent folder for these files is
/apps/usb/host/msd_basic.
MPLAB X IDE Project
This table lists the name and location of the MPLAB X IDE project folder for the demonstration.
Project Name Location
msd_basic.X /apps/usb/host/msd_basic/firmware
MPLAB X IDE Project Configurations
This table lists and describes the supported configurations of the demonstration, which are located within ./firmware/src/system_config.
Project Configuration Name BSP Used Description
chipkit_wf32 chipkit_wf32 Demonstration running on the chipKIT WF32 Development Board.
chipkit_wifire chipkit_wifire Demonstration running on the chipKIT Wi-FIRE Development Board.
pic32mx_usb_sk2_int_dyn pic32mx_usb_sk2 Select this MPLAB X IDE project configuration to run the demonstration on the
PIC32 USB Starter Kit II configured for Interrupt mode and dynamic operation.
pic32mx_usb_sk3_int_dyn pic32mx_usb_sk3 Select this MPLAB X IDE project configuration to run the demonstration on the
PIC32 USB Starter Kit III with the PIC32MX470F512L microcontroller
configured for Interrupt mode and dynamic operation.
pic32mz_da_sk_intddr_int_dyn pic32mz_da_sk_intddr Select this MPLAB X IDE project configuration to run the demonstration on the
PIC32MZ Embedded Graphics with Internal DRAM (DA) Starter Kit configured
for Interrupt mode and dynamic operation.
pic32mz_ef_sk_int_dyn pic32mz_ef_sk Select this MPLAB X IDE project configuration to run the demonstration on the
PIC32MZ Embedded Connectivity with Floating Point Unit (EF) Starter Kit
configured for Interrupt mode and dynamic operation.
pic32mx_xlp_sk_int_dyn pic32mx_xlp_sk Select this MPLAB X IDE project configuration to run the demonstration on the
PIC32MX XLP Starter Kit configured for Interrupt mode and dynamic operation.
pic32wk_sk_int_dyn pic32wk_gbp_gpd_sk+module Select this MPLAB X IDE project configuration to run the demonstration
application to run on the PIC32WK Wi-Fi Starter Kit, with the WM32 Wi-Fi
module. The USB Stack will be configured for Interrupt mode operation and the
USB Driver will be configured for Dynamic operation mode.
pic32mx470_curiosity pic32mx470_curiosity Select this MPLAB X IDE project configuration to run the demonstration
application to run on the PIC32MX470 Curiosity Development Board, with the
PIC32MX470F512H microcontroller. The USB Stack will be configured for
Interrupt mode operation and the USB Driver will be configured for Dynamic
operation mode.
pic32mz_ef_curiosity pic32mz_ef_curiosity Select this MPLAB X IDE project configuration to run the demonstration
application to run on the PIC32MZ EF Curiosity Development Board, with the
PIC32MZ2048EFM100 microcontroller. The USB Stack will be configured for
Interrupt mode operation and the USB Driver will be configured for Dynamic
operation mode.
Configuring the Hardware
Describes how to configure the supported hardware.
Description
PIC32 USB Starter Kit II
JP2 should be in place.
PIC32 USB Starter Kit III
JP1 should be in place.
PIC32MZ Embedded Graphics with Internal DRAM (DA) Starter Kit
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 51
No hardware related configuration or jumper setting changes are necessary.
PIC32MZ EC Starter Kit
JP1 should be in place and the Ethernet plug-in board should be removed.
PIC32MZ EF Starter Kit
No hardware related configuration or jumper setting changes are necessary.
chipKIT WF32 Wi-Fi Development Board
No hardware related configuration or jumper setting changes are necessary.
chipKIT Wi-FIRE Development Board
No hardware related configuration or jumper setting changes are necessary.
PIC32MX470 Curiosity Development Board
• Ensure that a jumper is placed at 4-3 on J8, to select supply from debug USB connector.
• Power the PIC32MX470 Curiosity Development Board from a Host PC through a Type-A male to mini-B USB cable connected to Mini-B port
(J3)
• Place a jumper on J13 to drive VBUS in Host mode
• Plug in a USB peripheral with a micro-A USB connector, or use a micro USB OTG to USB adapter.
PIC32MZ EF Curiosity Development Board
• Ensure that a jumper is placed at 4-3 on J8, to select supply from debug USB connector.
• Power the PIC32MZ EF Curiosity Development Board from a Host PC through a Type-A male to micro-B USB cable connected to Micro-B port
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 52
(J3).
• Place a jumper on J13 to drive VBUS in Host mode.
• Plug in a USB peripheral with a micro-A USB connector, or use a micro USB OTG to USB adapter.
PIC32WK Wi-Fi Starter Kit
No hardware related configuration or jumper setting changes are necessary.
Running the Demonstration
Provides instructions on how to build and run the USB Host MSD Basic demonstration.
Description
This application demonstrates the use of the MSD Host Class Driver to write a file to USB Flash drive. The application uses the USB Host_layer,
MSD class driver and the MPLAB Harmony File System Framework to enumerate a USB Flash drive and to write a file to it.
Prior to using this demonstration, it is recommended to review the MPLAB Harmony Release Notes for any known issues. A PDF copy of the
release notes is provided in the /doc folder of your installation.
1. Open_the project in MPLAB X IDE and select the desired project configuration.
2. Build the code and program the device.
3. With the code running, attach a USB Flash drive to the Host connector on the desired starter kit.
4. The demonstration application will then create a file named file.txt. It will then write the text "Hello World" to this file, and then close the file.
5. The demonstration will then move to Idle mode, which is indicated when the LED on the starter kit illuminates. On PIC32M-based starter kits
the LED is LED2.
6. The USB Flash drive can then be attached to a USB Host personal computer to verify the demonstration application operation.
7. Steps 3 through 6 can be repeated.
8. If the USB Flash drive already contains a file with the name file.txt, the demonstration application will append the text "Hello World" to the
end of the file contents.
9. The LED on the starter kit illuminates if the file creation or write failed. On PIC32M-based starter kits, the LED is LED1.
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 53
Multiple USB Controller
This section describes the demonstrations that make use of multiple USB controllers on certain PIC32 microcontrollers.
cdc_com_port_dual
This application demonstrates dual USB Device operation on a PIC32 microcontroller with two USB Controllers.
Description
This application demonstrates dual USB Device operation on a PIC32 microcontroller with Two USB Controllers. In this demonstration both of the
USB controllers act as CDC devices.
Building the Application
This section identifies the MPLAB X IDE project name and location and lists and describes the available configurations for the Multiple USB CDC
Device Dual COM Port Demonstration.
Description
To build this project, you must open the cdc_com_port_dual.X project in MPLAB X IDE, and then select the desired configuration.
The following tables list and describe the project and supported configurations. The parent folder for these files is
/apps/usb/multi_usb/cdc_com_port_dual.
MPLAB X IDE Project
This table lists the name and location of the MPLAB X IDE project folder for the demonstration.
Project Name Location
cdc_com_port_dual.X /apps/usb/multi_usb/cdc_com_port_dual/firmware
MPLAB X IDE Project Configurations
This table lists and describes the supported configurations of the demonstration, which are located within ./firmware/src/system_config.
Project Configuration
Name
BSP Used Description
pic32mk_gp_db_int_dyn pic32mk_gp_db Select this MPLAB X IDE project configuration to run the demonstration on the PIC32MK
Evaluation Kit configured for interrupt mode and dynamic operation.
Configuring the Hardware
Describes how to configure the supported hardware.
Description
PIC32MK General Purpose (GP) Development Board
Switch S4 should be set to the Device position.
Running the Demonstration
This section provides instructions on how to build and run the USB Multiple Controller CDC Com Port Dual demonstration.
Description
This application demonstrates dual USB Device operation on a PIC32 microcontroller with two USB Controllers. The MPLAB Harmony USB Stack
is capable of handling multiple USB controllers. In this demonstration, both of the USB controllers act as CDC devices.
This demonstration allows the each controller on the PIC32 to appear like a serial (COM) port to the host. Do the following to run this
demonstration:
1. First compile and program the target device. Refer to Building the Application for details.
2. Attach both USB connectors J15 and J13 to the host.
3. Refer to the Running the Demonstration section of the USB Device cdc_com_port_single demonstration for details on exercising the CDC
device features.
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 54
msd_dual
This application demonstrates the capability of a PIC32 microcontroller and MPLAB Harmony USB Host stack to work with two USB Controllers in
an application.
Description
This application demonstrates the capability of a PIC32 microcontroller and the MPLAB Harmony USB Host stack to work with two USB
Controllers in an application. The MPLAB Harmony USB Stack is capable of handling multiple USB controllers.
Building the Application
This section identifies the MPLAB X IDE project name and location and lists and describes the available configurations for the Dual MSD
demonstration.
Description
To build this project, you must open the msd_dual.X project in MPLAB X IDE, and then select the desired configuration.
The following tables list and describe the project and supported configurations. The parent folder for these files is
/apps/usb/multi_usb/dual_msd.
MPLAB X IDE Project
This table lists the name and location of the MPLAB X IDE project folder for the demonstration.
Project Name Location
msd_dual.X /apps/usb/multi_usb/msd_dual/firmware
MPLAB X IDE Project Configurations
This table lists and describes the supported configurations of the demonstration, which are located within ./firmware/src/system_config.
Project Configuration
Name
BSP Used Description
pic32mk_gp_deb_int_dyn pic32mk_gp_db Select this MPLAB X IDE project configuration to run the demonstration on the PIC32MK
Evaluation Kit configured for interrupt mode and dynamic operation.
Configuring the Hardware
Describes how to configure the supported hardware.
Description
PIC32MK General Purpose (GP) Development Board
• Switch S4 should be set to Host position
• Jumper J28 must be installed
• USB Connector J12 must be connected to a USB Host for powering the board
• USB Flash drive should be attached to Connector J15 and J14 after programming the microcontroller
Running the Demonstration
This section provides instructions on how to build and run the USB Multiple Controller Dual MSD demonstration.
Description
This application demonstrates the capability of a PIC32 microcontroller and the MPLAB Harmony USB Host stack to work with two USB
Controllers in an application. The MPLAB Harmony USB Stack is capable of handling multiple USB controllers. The application uses the USB
Host_layer, MSD class driver, and the MPLAB Harmony File System Framework to enumerate a USB Flash drive and to write a file to it.
Prior to using this demonstration, it is recommended to review the MPLAB Harmony Release Notes for any known issues. A PDF copy of the
release notes is provided in the /doc folder of your installation. Do the following to run this demonstration:
1. Open the project in MPLAB X IDE and select the desired project configuration.
2. Build the code and program the device.
3. With the code running, attach a USB Flash drive with a file “file.txt” in it to one of the Host connector on the board.
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 55
4. Connect another USB Flash drive to other Host connector on the board. Ensure this flash drive does not contain any file named newfile.txt.
5. The application will copy the file file.txt from the drive containing this file to the other drive. The copied file will be renamed as newfile.txt.
LED2 on the demonstration board will illuminate to indicate completion of the file transfer.
6. Disconnect the drives and confirm demonstration success by inserting them into a personal computer and verifying the file transfer completed
as expected.
Dual Role
This section describes the USB Dual Role Demonstrations. These demonstrations project demonstrate operation of the USB Host and the USB
Device stack in the same project.
host_msd_device_hid
This application demonstrates role switching between USB Host MSD Stack and USB Device HID function. The role switch is trigger by a switch
press.
Description
This application demonstrates role switching between USB Host MSD Stack and USB Device HID function. The role switch is trigger by a switch
press. In the USB Host mode, the application performs read and write operations to a USB pen drive. In the USB Device mode, the application
emulates a HID mouse.
Building the Application
This section identifies the MPLAB X IDE project name and location and lists and describes the available configurations for the USB Host MSD and
USB HID Mouse Device Dual Role application.
Description
To build this project, you must open the host_msd_device_hid.X project in MPLAB X IDE, and then select the desired configuration.
The following tables list and describe the project and supported configurations. The parent folder for these files is
/apps/usb/dual_role/host_msd_device_hid.
MPLAB X IDE Project
This table lists the name and location of the MPLAB X IDE project folder for the demonstration.
Project Name Location
host_msd_device_hid.X /apps/usb/dual_role/host_msd_device_hid/firmware
MPLAB X IDE Project Configurations
This table lists and describes the supported configurations of the demonstration, which are located within ./firmware/src/system_config.
Project
Configuration Name
BSP Used Description
pic32mz_ef_sk_int_dyn pic32mz_ef_sk Select this MPLAB X IDE project configuration to run the demonstration on the PIC32MZ
Embedded Connectivity with Floating Point Unit (EF) Starter Kit configured for Interrupt mode and
dynamic operation.
Configuring the Hardware
Describes how to configure the supported hardware.
Description
PIC32MZ EF Starter Kit
No hardware related configuration or jumper setting changes are necessary.
Running the Demonstration
Provides instructions no how to build and run the USB Host MSD and USB HID Mouse Device Dual Role application.
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 56
Description
This application demonstrates the Dual Role capability of the MPLAB Harmony USB Stack. The application project includes both, the USB Host
and Device Stacks. Both the stacks are initialized during application initialization. During operation, the application polls the switch SW2 on the
starter kit to trigger a USB role switch. Note that the application cannot simultaneously operate as a host and device. The one USB role is
exclusive of the other.
Prior to using this demonstration, it is recommended to review the MPLAB Harmony Release Notes for any known issues. A PDF copy of the
release notes is provided in the /doc folder of your installation.
1. Open the project and in MPLAB X IDE and select the desired project operation
2. Build the code and program the device. The application initially will not operate in any USB role.
3. Press SW2 on the starter kit. This places the application in a USB Device mode.
4. Connect a USB cable between micro USB connector (J4) on the starter kit and a PC USB host. The application will emulate a USB HID mouse
function. The cursor on the PC will rotate. Pressing SW1 will enable and disable the cursor movements. Exercise device plug-n-play operation
to confirm USB Device operation
5. Now try switching the USB role. Disconnect the USB cable between micro USB connector (J4) on the starter kit and a PC USB host. Press
SW2 on the starter kit.
6. The application now will be in USB Host role. Connect a USB pen drive to the Type-A USB Host connector (J5) on the starter kit. The
application will create a file (file.txt) on the pen drive. The completion of the operation is indicated by LED2 on the starter kit. Disconnect
the pen driver and connect it to a PC to verify the contents of the file.
7. Repeat steps 3 through 6 to exercise the role switching capability.
Volume I: Getting Started With MPLAB Harmony Applications Help USB Demonstrations
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 57
Index
A
Applications Help 3
audio_speaker 41
B
Building the Application 10, 17, 19, 20, 23, 24, 26, 29, 30, 32, 33, 34, 35,
39, 40, 42, 43, 44, 45, 47, 48, 49, 50, 54, 55, 56
C
cdc_basic 43
cdc_com_port_dual 10, 54
cdc_com_port_single 16
cdc_msd 44
cdc_msd_basic 19
cdc_serial_emulator 20
cdc_serial_emulator_msd 23
Configuring the Hardware 11, 17, 20, 21, 23, 25, 27, 29, 31, 32, 33, 35,
36, 39, 40, 42, 43, 45, 46, 47, 49, 50, 51, 54, 55, 56
USB Device Demonstration (hid_msd_basic) 32
D
Demonstration Application Configurations 7
Demonstrations 10
USB 10
Device 10
Dual Role 56
H
hid_basic 24
hid_basic_keyboard 45
hid_basic_mouse_usart 47
hid_joystick 26
hid_keyboard 29
hid_mouse 30
hid_msd_basic 32
Host 41
host_msd_device_hid 56
hub_cdc_hid 48
hub_msd 49
I
Introduction 3
M
msd_basic 33, 50
msd_dual 55
msd_fs_spiflash 34
msd_multiple_luns 35
msd_sdcard 38
Multiple USB Controller 54
R
Running the Demonstration 13, 18, 20, 21, 24, 25, 27, 30, 31, 32, 34, 35,
38, 39, 41, 42, 43, 45, 46, 48, 49, 50, 53, 54, 55, 56
USB Device Demonstration (hid_keyboard) 29
USB Device Demonstrations (audio_speaker) 42
USB Device Demonstrations (hid_keyboard) 30
U
USB Demonstrations 3
USB Device Stack Component Memory Requirements 5
USB Device Stack Demonstration Application Program and Data
Memory Requirements 3
USB HID Host Keyboard and Mouse Tests 6
USB MSD Host USB Pen Drive Tests 5
V
vendor 39
Volume I: Getting Started With MPLAB Harmony Libraries and
Applications 2
Index
© 2013-2017 Microchip Technology Inc. MPLAB Harmony v2.06 58
2000 Microchip Technology Inc. DS39500A
PICmicro® 18C MCU Family
Reference Manual
39500 18C Reference Manual.book Page i Monday, July 10, 2000 6:12 PM
DS39500A-page ii 2000 Microchip Technology Inc.
“All rights reserved. Copyright © 2000, Microchip Technology
Incorporated, USA. Information contained in this publication
regarding device applications and the like is intended through
suggestion only and may be superseded by updates. No representation
or warranty is given and no liability is assumed by
Microchip Technology Incorporated with respect to the accuracy
or use of such information, or infringement of patents or
other intellectual property rights arising from such use or otherwise.
Use of Microchip’s products as critical components in
life support systems is not authorized except with express
written approval by Microchip. No licenses are conveyed,
implicitly or otherwise, under any intellectual property rights.
The Microchip logo and name are registered trademarks of
Microchip Technology Inc. in the U.S.A. and other countries.
All rights reserved. All other trademarks mentioned herein are
the property of their respective companies. No licenses are
conveyed, implicitly or otherwise, under any intellectual property
rights.”
Trademarks
The Microchip name, logo, KEELOQ, PIC, PICMASTER,
PICmicro, PRO MATE, PICSTART, MPLAB, and SEEVAL are
registered trademarks of Microchip Technology Incorporated
in the U.S.A. and other countries.
Total Endurance, In-Circuit Serial Programming (ICSP),
microID, FilterLab are trademarks of Microchip Technology
Incorporated in the U.S.A.
Serialized Quick Term Programming (SQTP) is a service mark
of Microchip Technology Incorporated in the U.S.A.
All other trademarks mentioned herein are property of their
respective companies.
© 2000, Microchip Technology Incorporated, Printed in the
U.S.A., All Rights Reserved.
39500 18C Reference Manual.book Page ii Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39500A-page iii
PAGE
COMPANY PROFILE 1-1
SECTION 1. INTRODUCTION 1-1
Introduction ...................................................................................................................................................... 1-2
Manual Objective ............................................................................................................................................. 1-3
Device Structure ............................................................................................................................................... 1-4
Development Support ...................................................................................................................................... 1-6
Device Varieties ............................................................................................................................................... 1-7
Style and Symbol Conventions ...................................................................................................................... 1-12
Related Documents ........................................................................................................................................ 1-14
Related Application Notes .............................................................................................................................. 1-17
Revision History ............................................................................................................................................. 1-18
SECTION 2. OSCILLATOR 2-1
Introduction ...................................................................................................................................................... 2-2
Control Register ............................................................................................................................................... 2-3
Oscillator Configurations .................................................................................................................................. 2-4
Crystal Oscillators/Ceramic Resonators ........................................................................................................... 2-6
External RC Oscillator .................................................................................................................................... 2-15
HS4 ................................................................................................................................................................ 2-18
Switching to Low Power Clock Source ........................................................................................................... 2-19
Effects of Sleep Mode on the On-Chip Oscillator ........................................................................................... 2-23
Effects of Device Reset on the On-Chip Oscillator ......................................................................................... 2-23
Design Tips .................................................................................................................................................... 2-24
Related Application Notes .............................................................................................................................. 2-25
Revision History ............................................................................................................................................. 2-26
SECTION 3. RESET 3-1
Introduction ...................................................................................................................................................... 3-2
Resets and Delay Timers ................................................................................................................................. 3-4
Registers and Status Bit Values ..................................................................................................................... 3-14
Design Tips .................................................................................................................................................... 3-20
Related Application Notes .............................................................................................................................. 3-21
Revision History ............................................................................................................................................. 3-22
SECTION 4. ARCHITECTURE 4-1
Introduction ...................................................................................................................................................... 4-2
Clocking Scheme/Instruction Cycle .................................................................................................................. 4-5
Instruction Flow/Pipelining ............................................................................................................................... 4-6
I/O Descriptions ................................................................................................................................................ 4-7
Design Tips .................................................................................................................................................... 4-14
Related Application Notes .............................................................................................................................. 4-15
Revision History ............................................................................................................................................. 4-16
Table of Contents
39500 18C Reference Manual.book Page iii Monday, July 10, 2000 6:12 PM
DS39500A-page iv 2000 Microchip Technology Inc.
PAGE
SECTION 5. CPU AND ALU 5-1
Introduction ...................................................................................................................................................... 5-2
General Instruction Format .............................................................................................................................. 5-6
Central Processing Unit (CPU) ......................................................................................................................... 5-7
Instruction Clock ............................................................................................................................................... 5-8
Arithmetic Logical Unit (ALU) ........................................................................................................................... 5-9
STATUS Register ........................................................................................................................................... 5-11
Design Tips .................................................................................................................................................... 5-14
Related Application Notes .............................................................................................................................. 5-15
Revision History ............................................................................................................................................. 5-16
SECTION 6. HARDWARE 8X8 MULTIPLIER 6-1
Introduction ...................................................................................................................................................... 6-2
Operation ......................................................................................................................................................... 6-3
Design Tips ...................................................................................................................................................... 6-6
Related Application Notes ................................................................................................................................ 6-7
Revision History ............................................................................................................................................... 6-8
SECTION 7. MEMORY ORGANIZATION 7-1
Introduction ...................................................................................................................................................... 7-2
Program Memory ............................................................................................................................................. 7-3
Program Counter (PC) ..................................................................................................................................... 7-6
Lookup Tables .................................................................................................................................................. 7-9
Stack .............................................................................................................................................................. 7-12
Data Memory Organization ............................................................................................................................ 7-13
Return Address Stack .................................................................................................................................... 7-17
Initialization .................................................................................................................................................... 7-23
Design Tips .................................................................................................................................................... 7-24
Related Application Notes .............................................................................................................................. 7-25
Revision History ............................................................................................................................................. 7-26
SECTION 8. TABLE READ/TABLE WRITE 8-1
Introduction ...................................................................................................................................................... 8-2
Control Registers ............................................................................................................................................. 8-3
Program Memory ............................................................................................................................................. 8-6
Enabling Internal Programming ...................................................................................................................... 8-12
External Program Memory Operation ............................................................................................................. 8-12
Initialization .................................................................................................................................................... 8-13
Design Tips .................................................................................................................................................... 8-14
Related Application Notes .............................................................................................................................. 8-15
Revision History ............................................................................................................................................. 8-16
Table of Contents
39500 18C Reference Manual.book Page iv Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39500A-page v
PAGE
SECTION 9. SYSTEM BUS 9-1
Revision History ............................................................................................................................................... 9-2
SECTION 10. INTERRUPTS 10-1
Introduction .................................................................................................................................................... 10-2
Control Registers ........................................................................................................................................... 10-6
Interrupt Handling Operation ........................................................................................................................ 10-19
Initialization .................................................................................................................................................. 10-29
Design Tips .................................................................................................................................................. 10-30
Related Application Notes ............................................................................................................................ 10-31
Revision History ........................................................................................................................................... 10-32
SECTION 11. I/O PORTS 11-1
Introduction .................................................................................................................................................... 11-2
PORTA, TRISA, and the LATA Register ........................................................................................................ 11-8
PORTB, TRISB, and the LATB Register ...................................................................................................... 11-12
PORTC, TRISC, and the LATC Register ..................................................................................................... 11-16
PORTD, LATD, and the TRISD Register ..................................................................................................... 11-19
PORTE, TRISE, and the LATE Register ...................................................................................................... 11-21
PORTF, LATF, and the TRISF Register ....................................................................................................... 11-23
PORTG, LATG, and the TRISG Register ..................................................................................................... 11-25
PORTH, LATH, and the TRISH Register ................................................................................................... 11-27
PORTJ, LATJ, and the TRISJ Register ........................................................................................................ 11-29
PORTK, LATK, and the TRISK Register ...................................................................................................... 11-31
PORTL, LATL, and the TRISL Register ....................................................................................................... 11-33
Functions Multiplexed on I/O Pins ................................................................................................................ 11-35
I/O Programming Considerations ................................................................................................................. 11-37
Initialization .................................................................................................................................................. 11-40
Design Tips .................................................................................................................................................. 11-41
Related Application Notes ............................................................................................................................ 11-43
Revision History ........................................................................................................................................... 11-44
SECTION 12. PARALLEL SLAVE PORT 12-1
Introduction .................................................................................................................................................... 12-2
Control Register ............................................................................................................................................. 12-3
Operation ....................................................................................................................................................... 12-5
Operation in SLEEP Mode ............................................................................................................................. 12-6
Effect of a RESET .......................................................................................................................................... 12-6
PSP Waveforms ............................................................................................................................................. 12-6
Design Tips .................................................................................................................................................... 12-8
Related Application Notes .............................................................................................................................. 12-9
Revision History ........................................................................................................................................... 12-10
Table of Contents
39500 18C Reference Manual.book Page v Monday, July 10, 2000 6:12 PM
DS39500A-page vi 2000 Microchip Technology Inc.
PAGE
SECTION 13. TIMER0 13-1
Introduction .................................................................................................................................................... 13-2
Control Register ............................................................................................................................................. 13-3
Operation ....................................................................................................................................................... 13-4
Timer0 Interrupt .............................................................................................................................................. 13-5
Using Timer0 with an External Clock ............................................................................................................. 13-6
Timer0 Prescaler ............................................................................................................................................ 13-7
Initialization .................................................................................................................................................... 13-9
Design Tips .................................................................................................................................................. 13-10
Related Application Notes ............................................................................................................................ 13-11
Revision History ........................................................................................................................................... 13-12
SECTION 14. TIMER1 14-1
Introduction .................................................................................................................................................... 14-2
Control Register ............................................................................................................................................. 14-4
Timer1 Operation in Timer Mode ................................................................................................................... 14-5
Timer1 Operation in Synchronized Counter Mode ......................................................................................... 14-5
Timer1 Operation in Asynchronous Counter Mode ........................................................................................ 14-6
Reading and Writing of Timer1 ...................................................................................................................... 14-7
Timer1 Oscillator .......................................................................................................................................... 14-10
Typical Application ....................................................................................................................................... 14-11
Sleep Operation ........................................................................................................................................... 14-12
Resetting Timer1 Using a CCP Trigger Output ............................................................................................ 14-12
Resetting Timer1 Register Pair (TMR1H:TMR1L) ........................................................................................ 14-13
Timer1 Prescaler .......................................................................................................................................... 14-13
Initialization .................................................................................................................................................. 14-14
Design Tips .................................................................................................................................................. 14-16
Related Application Notes ............................................................................................................................ 14-17
Revision History ........................................................................................................................................... 14-18
SECTION 15. TIMER2 15-1
Introduction .................................................................................................................................................... 15-2
Control Register ............................................................................................................................................. 15-3
Timer Clock Source ........................................................................................................................................ 15-4
Timer (TMR2) and Period (PR2) Registers .................................................................................................... 15-4
TMR2 Match Output ....................................................................................................................................... 15-4
Clearing the Timer2 Prescaler and Postscaler ............................................................................................... 15-4
Sleep Operation ............................................................................................................................................. 15-4
Initialization .................................................................................................................................................... 15-5
Design Tips .................................................................................................................................................... 15-6
Related Application Notes .............................................................................................................................. 15-7
Revision History ............................................................................................................................................. 15-8
Table of Contents
39500 18C Reference Manual.book Page vi Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39500A-page vii
PAGE
SECTION 16. TIMER3 16-1
Introduction .................................................................................................................................................... 16-2
Control Registers ........................................................................................................................................... 16-3
Timer3 Operation in Timer Mode ................................................................................................................... 16-4
Timer3 Operation in Synchronized Counter Mode ......................................................................................... 16-4
Timer3 Operation in Asynchronous Counter Mode ........................................................................................ 16-5
Reading and Writing of Timer3 ...................................................................................................................... 16-6
Timer3 using the Timer1 Oscillator ................................................................................................................ 16-9
Timer3 and CCPx Enable ............................................................................................................................ 16-10
Timer3 Prescaler .......................................................................................................................................... 16-10
16-bit Mode Timer Reads/Writes .................................................................................................................. 16-11
Typical Application ....................................................................................................................................... 16-12
Sleep Operation ........................................................................................................................................... 16-13
Timer3 Prescaler .......................................................................................................................................... 16-13
Initialization .................................................................................................................................................. 16-14
Design Tips .................................................................................................................................................. 16-16
Related Application Notes ............................................................................................................................ 16-17
Revision History ........................................................................................................................................... 16-18
SECTION 17. COMPARE/CAPTURE/PWM (CCP) 17-1
Introduction .................................................................................................................................................... 17-2
CCP Control Register ..................................................................................................................................... 17-3
Capture Mode ................................................................................................................................................ 17-4
Compare Mode .............................................................................................................................................. 17-7
PWM Mode .................................................................................................................................................. 17-10
Initialization .................................................................................................................................................. 17-15
Design Tips .................................................................................................................................................. 17-17
Related Application Notes ............................................................................................................................ 17-19
Revision History ........................................................................................................................................... 17-20
SECTION 18. ECCP 18-1
SECTION 19. SYNCHRONOUS SERIAL PORT (SSP) 19-1
Introduction .................................................................................................................................................... 19-2
Control Registers ........................................................................................................................................... 19-4
SPI Mode ....................................................................................................................................................... 19-8
SSP I2C Operation ....................................................................................................................................... 19-18
Initialization .................................................................................................................................................. 19-28
Design Tips .................................................................................................................................................. 19-30
Related Application Notes ............................................................................................................................ 19-31
Revision History ........................................................................................................................................... 19-32
Table of Contents
39500 18C Reference Manual.book Page vii Monday, July 10, 2000 6:12 PM
DS39500A-page viii 2000 Microchip Technology Inc.
PAGE
SECTION 20. MASTER SSP 20-1
Introduction .................................................................................................................................................... 20-2
Control Registers ........................................................................................................................................... 20-4
SPI Mode ....................................................................................................................................................... 20-9
MSSP I2C Operation .................................................................................................................................... 20-18
Design Tips .................................................................................................................................................. 20-58
Related Application Notes ............................................................................................................................ 20-59
Revision History ........................................................................................................................................... 20-60
SECTION 21. ADDRESSABLE USART 21-1
Introduction .................................................................................................................................................... 21-2
Control Registers ........................................................................................................................................... 21-3
USART Baud Rate Generator (BRG) ............................................................................................................. 21-5
USART Asynchronous Mode ......................................................................................................................... 21-9
USART Synchronous Master Mode ............................................................................................................. 21-18
USART Synchronous Slave Mode ............................................................................................................... 21-23
Initialization .................................................................................................................................................. 21-25
Design Tips .................................................................................................................................................. 21-26
Related Application Notes ............................................................................................................................ 21-27
Revision History ........................................................................................................................................... 21-28
SECTION 22. CAN 22-1
Introduction .................................................................................................................................................... 22-2
Control Registers for the CAN Module ........................................................................................................... 22-3
CAN Overview .............................................................................................................................................. 22-28
CAN Bus Features ....................................................................................................................................... 22-32
CAN Module Implementation ....................................................................................................................... 22-33
Frame Types ................................................................................................................................................ 22-37
Modes of Operation ...................................................................................................................................... 22-44
CAN Bus Initialization ................................................................................................................................... 22-48
Message Reception ..................................................................................................................................... 22-49
Transmission ................................................................................................................................................ 22-60
Error Detection ............................................................................................................................................. 22-69
Baud Rate Setting ........................................................................................................................................ 22-71
Interrupts ...................................................................................................................................................... 22-75
Timestamping ............................................................................................................................................... 22-77
CAN Module I/O ........................................................................................................................................... 22-77
Design Tips .................................................................................................................................................. 22-78
Related Application Notes ............................................................................................................................ 22-79
Revision History ........................................................................................................................................... 22-80
Table of Contents
39500 18C Reference Manual.book Page viii Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39500A-page ix
PAGE
SECTION 23. COMPARATOR VOLTAGE REFERENCE 23-1
Introduction .................................................................................................................................................... 23-2
Control Register ............................................................................................................................................. 23-3
Configuring the Voltage Reference ................................................................................................................ 23-4
Voltage Reference Accuracy/Error ................................................................................................................. 23-5
Operation During Sleep .................................................................................................................................. 23-5
Effects of a Reset ........................................................................................................................................... 23-5
Connection Considerations ............................................................................................................................ 23-6
Initialization .................................................................................................................................................... 23-7
Design Tips .................................................................................................................................................... 23-8
Related Application Notes .............................................................................................................................. 23-9
Revision History ........................................................................................................................................... 23-10
SECTION 24. COMPARATOR 24-1
Introduction .................................................................................................................................................... 24-2
Control Register ............................................................................................................................................. 24-3
Comparator Configuration .............................................................................................................................. 24-4
Comparator Operation ................................................................................................................................... 24-6
Comparator Reference ................................................................................................................................... 24-6
Comparator Response Time .......................................................................................................................... 24-8
Comparator Outputs ....................................................................................................................................... 24-8
Comparator Interrupts .................................................................................................................................... 24-9
Comparator Operation During SLEEP ........................................................................................................... 24-9
Effects of a RESET ........................................................................................................................................ 24-9
Analog Input Connection Considerations ..................................................................................................... 24-10
Initialization .................................................................................................................................................. 24-11
Design Tips .................................................................................................................................................. 24-12
Related Application Notes ............................................................................................................................ 24-13
Revision History ........................................................................................................................................... 24-14
SECTION 25. COMPATIBLE 10-BIT A/D CONVERTER 25-1
Introduction .................................................................................................................................................... 25-2
Control Register ............................................................................................................................................. 25-4
Operation ....................................................................................................................................................... 25-7
A/D Acquisition Requirements ....................................................................................................................... 25-8
Selecting the A/D Conversion Clock ............................................................................................................ 25-10
Configuring Analog Port Pins ....................................................................................................................... 25-11
A/D Conversions .......................................................................................................................................... 25-12
Operation During Sleep ................................................................................................................................ 25-16
Effects of a Reset ......................................................................................................................................... 25-16
A/D Accuracy/Error ...................................................................................................................................... 25-17
Connection Considerations .......................................................................................................................... 25-18
Transfer Function ......................................................................................................................................... 25-18
Initialization .................................................................................................................................................. 25-19
Design Tips .................................................................................................................................................. 25-20
Related Application Notes ............................................................................................................................ 25-21
Revision History ........................................................................................................................................... 25-22
Table of Contents
39500 18C Reference Manual.book Page ix Monday, July 10, 2000 6:12 PM
DS39500A-page x 2000 Microchip Technology Inc.
PAGE
SECTION 26. 10-BIT A/D CONVERTER 26-1
Introduction .................................................................................................................................................... 26-2
Control Register ............................................................................................................................................. 26-4
Operation ....................................................................................................................................................... 26-7
A/D Acquisition Requirements ....................................................................................................................... 26-8
Selecting the A/D Conversion Clock ............................................................................................................ 26-10
Configuring Analog Port Pins ....................................................................................................................... 26-11
A/D Conversions .......................................................................................................................................... 26-12
Operation During Sleep ................................................................................................................................ 26-16
Effects of a Reset ......................................................................................................................................... 26-16
A/D Accuracy/Error ...................................................................................................................................... 26-17
Connection Considerations .......................................................................................................................... 26-18
Transfer Function ......................................................................................................................................... 26-18
Initialization .................................................................................................................................................. 26-19
Design Tips .................................................................................................................................................. 26-20
Related Application Notes ............................................................................................................................ 26-21
Revision History ........................................................................................................................................... 26-22
SECTION 27. LOW VOLTAGE DETECT 27-1
Introduction .................................................................................................................................................... 27-2
Control Register ............................................................................................................................................. 27-4
Operation ....................................................................................................................................................... 27-5
Operation During Sleep .................................................................................................................................. 27-6
Effects of a Reset ........................................................................................................................................... 27-6
Initialization .................................................................................................................................................... 27-7
Design Tips .................................................................................................................................................... 27-8
Related Application Notes .............................................................................................................................. 27-9
Revision History ........................................................................................................................................... 27-10
SECTION 28. WDT AND SLEEP MODE 28-1
Introduction .................................................................................................................................................... 28-2
Control Register ............................................................................................................................................. 28-3
Watchdog Timer (WDT) Operation ................................................................................................................. 28-4
SLEEP (Power-Down) Mode .......................................................................................................................... 28-5
Initialization .................................................................................................................................................. 28-11
Design Tips .................................................................................................................................................. 28-12
Related Application Notes ............................................................................................................................ 28-13
Revision History ........................................................................................................................................... 28-14
Table of Contents
39500 18C Reference Manual.book Page x Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39500A-page xi
PAGE
SECTION 29. DEVICE CONFIGURATION BITS 29-1
Introduction .................................................................................................................................................... 29-2
Configuration Word Bits ................................................................................................................................. 29-3
Program Verification/Code Protection .......................................................................................................... 29-10
ID Locations ................................................................................................................................................. 29-11
Device ID ...................................................................................................................................................... 29-11
Design Tips .................................................................................................................................................. 29-12
Related Application Notes ............................................................................................................................ 29-13
Revision History ........................................................................................................................................... 29-14
SECTION 30. IN-CIRCUIT SERIAL PROGRAMMING™ (ICSP™) 30-1
Introduction .................................................................................................................................................... 30-2
Entering In-Circuit Serial Programming Mode ................................................................................................ 30-3
Application Circuit .......................................................................................................................................... 30-4
Programmer ................................................................................................................................................... 30-6
Programming Environment ............................................................................................................................ 30-6
Other Benefits ................................................................................................................................................ 30-7
Field Programming of PICmicro OTP MCUs .................................................................................................. 30-8
Field Programming of FLASH PICmicros ..................................................................................................... 30-10
Design Tips .................................................................................................................................................. 30-12
Related Application Notes ............................................................................................................................ 30-13
Revision History ........................................................................................................................................... 30-14
SECTION 31. INSTRUCTION SET 31-1
Introduction .................................................................................................................................................... 31-2
Data Memory Map .......................................................................................................................................... 31-3
Instruction Formats ........................................................................................................................................ 31-9
Special Function Registers as Source/Destination ...................................................................................... 31-12
Fast Register Stack ...................................................................................................................................... 31-13
Q Cycle Activity ............................................................................................................................................ 31-13
Instruction Descriptions ................................................................................................................................ 31-14
Design Tips ................................................................................................................................................ 31-136
Related Application Notes .......................................................................................................................... 31-137
Revision History ......................................................................................................................................... 31-138
Table of Contents
39500 18C Reference Manual.book Page xi Monday, July 10, 2000 6:12 PM
DS39500A-page xii 2000 Microchip Technology Inc.
PAGE
SECTION 32. ELECTRICAL SPECIFICATIONS 32-1
Introduction .................................................................................................................................................... 32-2
Absolute Maximums ....................................................................................................................................... 32-3
Voltage vs Frequency Graph ......................................................................................................................... 32-4
Device Voltage Specifications ........................................................................................................................ 32-6
Device Current Specifications ........................................................................................................................ 32-7
Input Threshold Levels ................................................................................................................................. 32-10
I/O Current Specifications ............................................................................................................................ 32-11
Output Drive Levels ...................................................................................................................................... 32-12
I/O Capacitive Loading ................................................................................................................................. 32-13
Low Voltage Detect (LVD) ............................................................................................................................ 32-14
EPROM/FLASH/Data EEPROM .................................................................................................................. 32-15
Comparators and Voltage Reference ........................................................................................................... 32-16
Timing Parameter Symbology ...................................................................................................................... 32-18
Example External Clock Timing Waveforms and Requirements .................................................................. 32-19
Example Phase Lock Loop (PLL) Timing Waveforms and Requirements ................................................... 32-20
Example Power-up and RESET Timing Waveforms and Requirements ...................................................... 32-22
Example Timer0 and Timer1 Timing Waveforms and Requirements ........................................................... 32-23
Example CCP Timing Waveforms and Requirements ................................................................................. 32-24
Example Parallel Slave Port (PSP) Timing Waveforms and Requirements ................................................. 32-25
Example SSP and Master SSP SPI Mode Timing Waveforms and Requirements ...................................... 32-26
Example SSP I2C Mode Timing Waveforms and Requirements .................................................................. 32-30
Example Master SSP I2C Mode Timing Waveforms and Requirements ...................................................... 32-32
Example USART/SCI Timing Waveforms and Requirements ...................................................................... 32-34
CAN Specifications ...................................................................................................................................... 32-35
Example 8-bit A/D Timing Waveforms and Requirements ........................................................................... 32-36
Example 10-bit A/D Timing Waveforms and Requirements ......................................................................... 32-38
Design Tips .................................................................................................................................................. 32-40
Related Application Notes ............................................................................................................................ 32-41
Revision History ........................................................................................................................................... 32-42
SECTION 33. DEVICE CHARACTERISTICS 33-1
Introduction .................................................................................................................................................... 33-2
Characterization vs. Electrical Specification ................................................................................................... 33-2
DC and AC Characteristics Graphs and Tables ............................................................................................. 33-2
Revision History ........................................................................................................................................... 33-26
Table of Contents
39500 18C Reference Manual.book Page xii Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39500A-page xiii
PAGE
SECTION 34. DEVELOPMENT TOOLS 34-1
Introduction .................................................................................................................................................... 34-2
The Integrated Development Environment (IDE) ........................................................................................... 34-3
MPLAB® Software Language Support ........................................................................................................... 34-6
MPLAB-SIM Simulator Software .................................................................................................................... 34-8
MPLAB Emulator Hardware Support .............................................................................................................. 34-9
MPLAB High Performance Universal In-Circuit Emulator with MPLAB IDE ................................................... 34-9
MPLAB-ICD In-Circuit Debugger .................................................................................................................... 34-9
MPLAB Programmer Support ...................................................................................................................... 34-10
Supplemental Tools ..................................................................................................................................... 34-11
Development Boards .................................................................................................................................... 34-12
Development Tools for Other Microchip Products ........................................................................................ 34-14
Related Application Notes ............................................................................................................................ 34-15
Revision History ........................................................................................................................................... 34-16
SECTION 35. CODE DEVELOPMENT 35-1
Overview ........................................................................................................................................................ 35-2
Good Practice ................................................................................................................................................ 35-3
Diagnostic Code Techniques ......................................................................................................................... 35-5
Example Scenario and Implementation ......................................................................................................... 35-6
Implications of Using a High Level Language (HLL) ...................................................................................... 35-7
Revision History ............................................................................................................................................. 35-8
SECTION 36. APPENDIX 36-1
Appendix A: I2C Overview............................................................................................................................... 36-1
Appendix B: CAN Overview ......................................................................................................................... 36-12
Appendix C: Module Block Diagrams and Registers..................................................................................... 36-13
Appendix D: Register Definitions .................................................................................................................. 36-14
Appendix E: Migration Tips ........................................................................................................................... 36-15
SECTION 37. GLOSSARY 37-1
Revision History ........................................................................................................................................... 37-14
SOURCE CODE
INDEX
Table of Contents
39500 18C Reference Manual.book Page xiii Monday, July 10, 2000 6:12 PM
DS39500A-page xiv 2000 Microchip Technology Inc.
PAGE
NOTES:
Table of Contents
39500 18C Reference Manual.book Page xiv Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS00027U-page xv
The Embedded Control Solutions Company
Since its inception, Microchip Technology has focused
its resources on delivering innovative semiconductor
products to the global embedded control marketplace.
To do this, we have focused our technology,
engineering, manufacturing and marketing resources
on synergistic product lines: PICmicro®
microcontrollers (MCUs), high-endurance Serial
EEPROMs, an expanding product portfolio of analog/
interface products, RFID tags and KEELOQ® security
devices – all aimed at delivering comprehensive,
high-value embedded control solutions to a growing
base of customers.
Inside Microchip Technology you will find:
• An experienced executive team focused on
innovation and committed to listening to our
customers
• A focus on providing high-performance,
cost-effective embedded control solutions
• Fully integrated manufacturing capabilities
• A global network of manufacturing and customer
support facilities
• A unique corporate culture dedicated to
continuous improvement
• Distributor network support worldwide including
certified distribution FAEs
• A Complete Product Solution including:
- RISC OTP, FLASH, EEPROM and ROM
MCUs
- A full family of advanced analog MCUs
- KEELOQ security devices featuring patented
code hopping technology
- Stand-alone analog and interface products
plus microID™ RFID tagging devices
- A complete line of high-endurance Serial
EEPROMs
- World-class, easy-to-use development tools
- An Automotive Products Group to engage
with key automotive accounts and provide
necessary application expertise and
customer service
Business Scope
Microchip Technology Inc. designs, manufactures, and
markets a variety of CMOS semiconductor
components to support the market for cost-effective
embedded control solutions.
Microchip's products feature compact size, integrated
functionality, ease of development and technical
support so essential to timely and cost-effective
product development by our customers.
Company Profile
Chandler, Arizona: Company headquarters near
Phoenix, Arizona; executive offices, R&D and wafer
fabrication occupy this 242,000 square-foot multi-building
campus.
Tempe, Arizona: Microchip’s 200,000 square-foot wafer
fabrication facility provides increased manufacturing
capacity today and for the future.
39500 18C Reference Manual.book Page xv Monday, July 10, 2000 6:12 PM
DS00027U-page xvi 2000 Microchip Technology Inc.
Market Focus
Microchip targets select markets where our advanced
designs, progressive process technology and
industry-leading product performance enables us to
deliver decidedly superior performance. Our Company
is positioned to provide a complete product solution for
embedded control applications found throughout the
consumer, automotive, telecommunication, office
automation and industrial control markets. Microchip
products are also meeting the unique design
requirements of targeted embedded applications
including internet, safety and security.
Certified Quality Systems
Microchip’s quality systems have been certified to
QS-9000 requirements. Its worldwide headquarters
and wafer fabrication facilities in Chandler and Tempe,
Arizona, received certification on July 23, 1999. The
scope of this certification is the design and
manufacture of RISC-based MCUs, related
non-volatile memory products and microperipheral
devices. The quality systems for Microchip’s product
test facility in Bangkok, Thailand, were QS-9000
certified on February 26, 1999. The scope of this
certification is the design and testing of integrated
circuits. In addition, Microchip’s quality system for the
design and manufacture of development systems is
ISO 9001 certified.
QS-9000 was developed by Chrysler, Ford and
General Motors to establish fundamental quality
systems that provide for continuous improvement,
emphasizing defect prevention and the reduction of
variation and waste in the supply chain. Microchip was
audited by QS-9000 registrar Det Norske Veritas
Certification Inc. of Houston, the same firm which
granted Microchip its ISO 9001 Quality System
certification in 1997. QS-9000 certification recognizes
Microchip’s quality systems conform to the stringent
standards set forth by the automotive industry,
benefiting all customers.
Fully Integrated Manufacturing
Microchip delivers fast turnaround and consistent
quality through total control over all phases of
production. Research and development, design, mask
making, wafer fabrication, and the major part of
assembly and quality assurance testing are conducted
at facilities wholly-owned and operated by Microchip.
Our integrated approach to manufacturing along with
rigorous use of advanced Statistical Process Control
(SPC) and a continuous improvement culture has
resulted in high and consistent yields which have
positioned Microchip as a quality leader in its global
markets. Microchip’s unique approach to SPC provides
customers with excellent pricing, quality, reliability and
on-time delivery.
A Global Network of Plants and Facilities
Microchip is a global competitor providing local
services to the world’s technology centers. The
Company’s design and technology advancement
facilities, and wafer fabrication sites are located in
Chandler and Tempe, Arizona.
The Tempe facility provides an additional 200,000
square feet of manufacturing space that meets the
increased production requirements of a growing
customer base, and provides production capacity
which more than doubles that of Chandler.
Microchip facilities in Bangkok, Thailand, and
Shanghai, China, serve as the foundation of
Microchip’s extensive assembly and test capability
located throughout Asia. The use of multiple
fabrication, assembly and test sites, with more than
640,000-square-feet of facilities worldwide, ensures
Microchip’s ability to meet the increased production
requirements of a fast growing customer base.
Microchip supports its global customer base from direct
sales and engineering offices in Asia, North America,
Europe and Japan. Offices are staffed to meet the high
quality expectations of our customers, and can be
accessed for technical and business support. The
Company also franchises more than 60 distributors and
a network of technical manufacturer’s representatives
serving 24 countries worldwide.
Bangkok, Thailand: Microchip’s 200,000 square-foot
manufacturing facility houses the technology and
assembly/test equipment for high speed testing and
packaging.
39500 18C Reference Manual.book Page xvi Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS00027U-page xvii
Embedded Control Overview
Unlike “processor” applications such as personal
computers and workstations, the computing or
controlling elements of embedded control applications
are embedded inside the application. The consumer is
only concerned with the very top-level user interface
such as keypads, displays and high-level commands.
Very rarely does an end-user know (or care to know)
the embedded controller inside (unlike the
conscientious PC users, who are intimately familiar not
only with the processor type, but also its clock speed,
DMA capabilities and so on).
It is, however, most vital for designers of embedded
control products to select the most suitable controller
and companion devices. Embedded control products
are found in all market segments: consumer,
commercial, PC peripherals, telecommunications,
automotive and industrial. Most embedded control
products must meet special requirements: cost
effectiveness, low-power, small-footprint and a high
level of system integration.
Typically, most embedded control systems are
designed around an MCU which integrates on-chip
program memory, data memory (RAM) and various
peripheral functions, such as timers and serial
communication. In addition, these systems usually
require complementary Serial EEPROM,
analog/interface devices, display drivers, keypads or
small displays.
Microchip has established itself as a leading supplier of
embedded control solutions. The combination of
high-performance PIC12CXXX, PIC16C5X,
PIC16CXXX, PIC17CXXX and PIC18CXXX MCU
families with Migratable Memory™ technology, along
with non-volatile memory products, provide the basis
for this leadership. By further expanding our product
portfolio to provide precision analog and interface
products, Microchip is committed to continuous
innovation and improvement in design, manufacturing
and technical support to provide the best possible
embedded control solutions to you.
PICmicro MCU Overview and Roadmap
Microchip PICmicro MCUs combine high-performance,
low-cost, and small package size, offering the best
price/performance ratio in the industry. More than one
billion of these devices have shipped to customers
worldwide since 1990. Microchip offers five families of
MCUs to best fit your application needs:
• PIC12CXXX 8-pin 12-bit/14-bit program word
• PIC16C5X 12-bit program word
• PIC16CXXX 14-bit program word
• PIC17CXXX 16-bit program word
• PIC18CXXX enhanced 16-bit program word
All families offer OTP, low-voltage and low-power
options, with a variety of package options. Selected
members are available in ROM, EEPROM or
reprogrammable FLASH versions.
PIC12CXXX: 8-Pin, Family
The PIC12CXXX family packs Microchip’s powerful
RISC-based PICmicro architecture into 8-pin DIP and
SOIC packages. These PIC12CXXX products are
available with either a 12-bit or 14-bit wide instruction
set, a low operating voltage of 2.5V, small package
footprints, interrupt handling, a deeper hardware stack,
multiple channels and EEPROM data memory. All of
these features provide an intelligence level not
previously available in applications because of cost or
size considerations.
PIC16C5X: 12-Bit Architecture Family
The PIC16C5X is the well-established base-line family
that offers the most cost-effective solution. These
PIC16C5X products have a 12-bit wide instruction set
and are currently offered in 14-, 18-, 20- and 28-pin
packages. In the SOIC and SSOP packaging options,
these devices are among the smallest footprint MCUs
in the industry. Low-voltage operation, down to 2.0V for
OTP MCUs, makes this family ideal for battery
operated applications. Additionally, the PIC16HV5XX
can operate up to 15 volts for use directly with a battery.
PIC16CXXX: 14-Bit Architecture Family
With the introduction of new PIC16CXXX family
members, Microchip now provides the industry’s
highest performance Analog-to-Digital Converter
capability at 12-bits for an MCU. The PIC16CXXX
family offers a wide-range of options, from 18- to 68-pin
packages as well as low to high levels of peripheral
integration. This family has a 14-bit wide instruction set,
interrupt handling capability and a deep, 8-level
hardware stack. The PIC16CXXX family provides the
performance and versatility to meet the more
demanding requirements of today’s cost-sensitive
marketplace for mid-range applications.
PIC17CXXX: 16-Bit Architecture Family
The PIC17CXXX family offers the world’s fastest
execution performance of any MCU family in the
industry. The PIC17CXXX family extends the PICmicro
MCU’s high-performance RISC architecture with a
16-bit instruction word, enhanced instruction set and
powerful vectored interrupt handling capabilities. A
powerful array of precise on-chip peripheral features
provides the performance for the most demanding
applications.
PIC18CXXX: 16-Bit Enhanced Architecture Family
The PIC18CXXX is a family of high performance,
CMOS, fully static, 16-bit MCUs with integrated
analog-to-digital (A/D) converter. All PIC18CXXX
MCUs incorporate an advanced RISC architecture.
The PIC18CXXX has enhanced core features, 32
level-deep stack, and multiple internal and external
interrupts sources. The separate instruction and data
busses of the Harvard architecture allow a 16-bit wide
instruction word with the separate 8-bit wide data. The
two-stage instruction pipeline allows all instructions to
execute in a single cycle, except for program branches,
which require two cycles. A total of 77 instructions
(reduced instruction set) are available. Additionally, a
large register set gives some of the architectural
39500 18C Reference Manual.book Page xvii Monday, July 10, 2000 6:12 PM
DS00027U-page xviii 2000 Microchip Technology Inc.
innovations used to achieve a very high performance of
10 MIPS for an MCU. The PIC18CXXX family has
special features to reduce external components, thus
reducing cost, enhancing system reliability and
reducing power consumption. These include
programmable Low Voltage Detect (LVD) and
programmable Brown-Out Detect (BOD).
The Mechatronics Revolution
The nature of the revolution is the momentous shift
from analog/electro-mechanical timing and control to
digital electronics. It is called the Mechatronics
Revolution, and it is being staged in companies
throughout the world, with design engineers right on
the front lines: make it smarter, make it smaller, make it
do more, make it cost less to manufacture – and make
it snappy.
To meet the needs of this growing customer base,
Microchip is rapidly expanding its already broad line of
PICmicro MCUs. The PIC12CXXX family’s size opens
up new possibilities for product design.
PICmicro MCU Naming Convention
The PICmicro architecture offers users a wider range of
cost/performance options than any MCU family. In
order to identify the families, the following naming
conventions have been applied to the PICmicro MCUs:
TABLE 1: PICmicro MCU NAMING CONVENTION*
*Please check with your local Microchip distributor, sales representative or sales office for the latest product information.
Family Architectural Features Name Technology
PIC18CXXX
8-bit HighPerformance
MCU Family
• 10 MIPS @ 40 MHz
• 4x PLL clock
• 16-bit wide instruction set
• C compiler efficient
instruction set
• Internal/external vectored
interrupts
PIC18CXX2
PIC18FXXX
OTP program memory with higher resolution analog functions
FLASH program memory
PIC17CXXX
8-bit
High-Performance
MCU Family
• 16-bit wide instruction set
• Internal/external vectored
interrupts
• DC - 33 MHz clock speed
• 120 ns instruction cycle
(@ 33 MHz)
• Hardware multiply
PIC17C4X OTP program memory, digital only
PIC17CR4X ROM program memory, digital only
PIC17C7XX OTP program memory with mixed-signal functions
PIC16CXXX
8-bit
Mid-Range
MCU Family
• 14-bit wide instruction set
• Internal/external interrupts
• DC - 20 MHz clock speed
(Note 1)
• 200 ns instruction cycle
(@ 20 MHz)
PIC14CXXX OTP program memory with A/D and D/A functions
PIC16C55X OTP program memory, digital only
PIC16C6X OTP program memory, digital only
PIC16CR6X ROM program memory, digital only
PIC16C62X OTP program memory with comparators
PIC16CR62X ROM program memory with comparators
PIC16CE62X OTP program memory with comparators and EEPROM data
memory
PIC16F62X FLASH program memory with comparators and EEPROM data
memory
PIC16C64X OTP program memory with comparators
PIC16C66X OTP program memory with comparators
PIC16C7X OTP program memory with analog functions (i.e. A/D)
PIC16CR7X ROM program memory with analog functions
PIC16C7XX OTP program memory with higher resolution analog functions
PIC16F8X FLASH program memory and EEPROM data memory
PIC16CR8X ROM program memory and EEPROM data memory
PIC16F87X FLASH program memory with higher resolution analog functions
PIC16C9XX OTP program memory, LCD driver
PIC16C5X
8-bit
Base-Line
MCU Family
• 12-bit wide instruction set
• DC - 20 MHz clock speed
• 200 ns instruction cycle
(@ 20 MHz)
PIC16C5X OTP program memory, digital only
PIC16CR5X ROM program memory, digital only
PIC16C505 OTP program memory, digital only, internal 4 MHz oscillator
PIC16HV540 OTP program memory with high voltage operation
PIC12CXXX
8-bit, 8-pin
MCU Family
• 12- or 14-bit wide
instruction set
• DC - 10 MHz clock speed
• 400 ns instruction cycle
(@ 10 MHz)
• Internal 4 MHz oscillator
PIC12C5XX OTP program memory, digital only
PIC12CE5XX OTP program memory, digital only with EEPROM data memory
PIC12CR5XX ROM program memory, digital only
PIC12C67X OTP program memory with analog functions
PIC12CE67X OTP program memory with analog functions and EEPROM data
memory
Note 1: The maximum clock speed for some devices is less than 20 MHz.
39500 18C Reference Manual.book Page xviii Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS00027U-page xix
Development Systems
Microchip is committed to providing useful and
innovative solutions to your embedded system
designs. Our installed base of application development
systems has grown to an impressive 170,000 systems
worldwide.
Among support products offered are MPLAB®-ICE
2000 In-Circuit Emulator running under the Windows
environment. This new real-time emulator supports
low-voltage emulation, to 2.0 volts, and full-speed
emulation. MPLAB, a complete Integrated Development
Environment (IDE), is provided with MPLAB-ICE 2000.
MPLAB allows the user to edit, compile and emulate
from a single user interface, making the developer
productive very quickly. MPLAB-ICE 2000 is designed to
provide product development engineers with an
optimized design tool for developing target applications.
This universal in-circuit emulator provides a complete
MCU design toolset for PICmicro MCUs in the
PIC12CXXX, PIC16C5X, PIC16CXXX, PIC17CXXX
and PIC18CXXX families. MPLAB-ICE 2000 is CE
compliant.
Microchip’s newest development tool, MPLAB In-Circuit
Debugger (ICD) Evaluation Kit, uses the in-circuit
debugging capabilities of the PIC16FXXX and
PIC18FXXX MCU family and Microchip’s ICSP™
capability to debug source code in the application,
debug hardware in real time and program a target
PIC16FXXX and PIC18FXXX device.
PRO MATE II, the full-featured, modular device
programmer, enables you to quickly and easily program
user software into PICmicro MCUs, HCS products and
Serial EEPROMs. PRO MATE II runs under MPLAB IDE
and operates as a stand-alone unit or in conjunction with
a PC-compatible host system.
The PICSTART Plus development kit is a low-cost
development system for the PIC12CXXX, PIC16C5X,
PIC16CXXX and PIC17CXXX MCUs.
PICDEM low-cost demonstration boards are simple
boards which demonstrate the basic capabilities of the
full range of Microchip’s MCUs. Users can program the
sample MCUs provided with PICDEM boards, on a
PRO MATE II or PICSTART Plus programmer, and
easily test firmware. KEELOQ Evaluation Tools support
Microchip’s HCS Secure Data Products.
The Serial EEPROM Designer’s Kit includes
everything necessary to read, write, erase or program
special features of any Microchip Serial EEPROMs.
The Total Endurance Disk is included to aid in
trade-off analysis and reliability calculations. The total
kit can significantly reduce time-to-market and result in
an optimized system.
The FilterLab™ Active Filter Design Tool simplifies
active filter design for embedded systems designers.
The unique FilterLab software automates the design of
the anti-aliasing filter for an analog-to-digital
converter-based data acquisition system. FilterLab
also provides full schematic diagrams of the filter circuit
with component values, a SPICE model, and displays
the frequency and phase response.
In addition to the FilterLab Active Filter Design Tool,
Microchip offers a second analog development tool, the
MXDEV™1 Analog Evaluation System, making it
easier for embedded systems designers to evaluate
and develop with Microchip’s line of stand-alone analog
products. The hardware and software within the
MXDEV 1 system is configured device-specific and
allows single or continuous conversions ofr the
analog-to-digital converter under evaluation.
The MCP2510 Controller Area Network (CAN)
Developer’s Kit makes software developing easy by
using a variety of features to manipulate the
functionality of the MCP2510. The MCP2510 CAN
Developer’s kit provides the ability to read, display and
modify all registers of the MCP2510 on a bit-by-bit or a
byte-by-byte basis.
The microID™ Developer’s Kit is an easy-to-use tool
for design engineers at all skill levels. Available in a
variety of configurations, the microID family of RFID
tags can be configured to match existing tags and be
directly installed - upgrading to contactless
programmability at no added cost. This kit includes all
the hardware, software, reference designs and
samples required to get started in RFID designs.
TABLE 2: PICmicro SYNERGISTIC DEVELOPMENT TOOLS
Development Tool Name PIC12CXXX PIC16C5X PIC16CXXX PIC16F87X PIC17CXXX PIC18CXXX
Integrated Development
Environment (IDE) MPLAB ✔✔✔ — ✔ ✔
C Compiler
MPLAB-C17 — — — — ✔
MPLAB-C18 — — — — — ✔
Full-Featured, Modular
In-Circuit Emulator MPLAB-ICE 2000 ✔✔✔ — ✔ ✔
In-Circuit Debugger
Evaluation Kit MPLAB-ICD — — — ✔ — —
Full-Featured, Modular
Device Programmer PRO MATE II ✔✔✔ — ✔ ✔
Entry-Level Development Kit
with Programmer PICSTART Plus ✔✔✔ — ✔ ✔
39500 18C Reference Manual.book Page xix Monday, July 10, 2000 6:12 PM
DS00027U-page xx 2000 Microchip Technology Inc.
Software Support
MPLAB Integrated Development Environment (IDE) is
a Windows-based development platform for
Microchip’s PICmicro MCUs. MPLAB IDE offers a
project manager and program text editor, a
user-configurable toolbar containing four pre-defined
sets and a status bar which communicates editing and
debugging information.
MPLAB-IDE is the common user interface for Microchip
development systems tools including MPLAB Editor,
MPASM Assembler, MPLAB-SIM Software Simulator,
MPLIB, MPLINK, MPLAB-C17 Compiler, MPLAB-C18
Compiler, MPLAB-ICE 2000, PRO MATE II
Programmer and PICSTART Plus Development
Programmer.
Microchip endeavors at all times to provide the best
service and responsiveness possible to its customers.
The Microchip Internet site can provide you with the
latest technical information, production released
software for development tools, application notes and
promotional news on Microchip products and
technology. The Microchip World Wide Web address is
http://www.microchip.com.
Secure Data Products Overview
Microchip’s patented KEELOQ® code hopping
technology is the perfect solution for remote keyless
entry and logical/physical access control systems. The
initial device in the family, the HCS300 encoder,
replaces current fixed code encoders in transmitter
applications providing a low cost, integrated solution.
The KEELOQ family is continuing to expand with the
HCS301 (high voltage encoder), HCS200 (low-end,
low-cost encoder), and high-end encoders (HCS360
and HCS361) that meet OEM specifications and
requirements. The HCS410, a self-powered
transponder superset of the HCS360, is the initial
device in a new and expanding encoder/transponder
family.
Microchip provides flexible decoder solutions by
providing optimized routines for Microchip’s PICmicro
MCUs. This allows the designer to combine the
decoder and system functionality in a MCU. The
decoder routines are available under a license
agreement. The HCS500, HCS512 and HCS515 are
the first decoder devices in the KEELOQ family. These
devices are single chip decoder solutions and simplify
designs by handling learning and decoding of
transmitters.
The KEELOQ product family is expanding to include
enhanced encoders and decoders. Typical applications
include automotive RKE, alarm and immobilizer
systems, garage door openers and home security
systems.
*Contact Microchip Technology Inc. for availability.
Analog/Interface Products
Using its technology achievements in developing
analog circuitry for its PICmicro MCU family, the
Company launched a complementary line of
stand-alone analog and interface products. Many of
these stand-alone devices support functionality that
may not currently available on PICmicro MCUs.
Stand-alone analog IC products currently offered
include:
• Analog-to-Digital Converters
• Operational Amplifiers
• System Supervisors
Microchip also offers innovative silicon products to
support a variety of bus interfaces used to transmit data
to and from embedded control systems. The first
interface products support Controller Area Network
(CAN), a bus protocol highly integrated into a variety of
networked applications including automotive.
High-Performance 12-Bit Analog-to-Digital
Converters
The MCP320X 12-bit analog-to-digital converter
(ADC) family is based on a successive approximation
register architecture. The first four members include:
MCP3201, MCP3202, MCP3204 and MCP3208. The
MCP320X family features 100K samples per second
throughput, low power of 400 microamps active and
500 nanoamps standby, wide supply voltage of
2.7-5.5 volts, extended industrial temperature range
of –40° to 85°, +/- 1 LSB DNL and +/- 1 LSB INL max.
at 100 ksps., no missing codes, and a serial output
with an industry-standard SPI™ bus interface. The
MCP320X is available in 1-, 2-, 4-, and 8-input
channel versions (the MCP3201, MPC3202,
MCP3204 and MCP3208, respectively). The devices
KEELOQ Encoder Devices
Product
Transmission
Code
Length Bits
Code
Hopping
Bits
Prog.
Encryption
Key
Bits
Seed
Length
Operating
Voltage
HCS101* 66 — — — 3.5V to 13.0V
HCS200 66 32 64 32 3.5V to 13.0V
HCS201* 66 32 64 32 3.5V to 13.0V
HCS300 66 32 64 32 2.0V to 6.3V
HCS301 66 32 64 32 3.5V to 13.0V
HCS320 66 32 64 32 3.5V to 13.0V
HCS360 67 32 64 48 2.0V to 6.6V
HCS361 67 32 64 48 2.0V to 6.6V
HCS365* 69 32 2 x 64 60 2.0V to 6.6V
HCS370* 69 32 2 x 64 60 2.0V to 6.6V
HCS410 69 32 64 60 2.0V to 6.6V
HCS412* 69 32 64 60 2.0V to 6.6V
HCS470* 69 32 2 x 64 60 2.0V to 6.6V
KEELOQ Decoder Devices
Product
Reception
Length Bits
Transmitters
Supported
Functions
Operating
Voltage
HCS500 67 Up to 7 15 Serial Functions 4.5V to 5.5V
HCS512 67 Up to 4 15 (S0, S1, S2, S3); VLOW, Serial 3.0V to 6.0V
HCS515 67 Up to 7 15 Serial; 3 Parallel 4.5V to 5.5V
39500 18C Reference Manual.book Page xx Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS00027U-page xxi
are offered in PDIP, SOIC and TSSOP packages.
Applications include data acquisition, instrumentation
and measurement, multi-channel data loggers,
industrial PCs, motor control, robotics, industrial
automation, smart sensors, portable instrumentation,
and home medical appliances.
Operational Amplifiers
The MCP60X Operational Amplifier family includes
four devices: MCP601, MCP602, MCP603 and
MCP604. These devices are Microchip’s first 2.7 volt
single supply operational amplifier products. The
MCP60X family offers a gain bandwidth product of 2.8
MHz with low typical operating current of 230 µA. The
MCP60X devices use Microchip's advanced CMOS
technology which provides low bias current, high speed
operation, high open-loop gain and rail-to-rail output
swing.
System Supervisors
Microchip offers a complete family of system
supervisor products. The new devices include the
MCP809/810 and MCP100/101 supervisory circuits
with push-pull output and the MCP120/130 supervisory
circuits with open drain output. The devices are
functionally and pin-out comparable to products from
other analog suppliers.
Controller Area Network (CAN)
Microchip is enhancing its product portfolio by
introducing the CAN Product Family. The MCP2510 is
the smallest, easiest-to-use, CAN controller on the
market today. Combining the MCP2510 with
Microchip’s broad range of high-performance PICmicro
MCUs enables Microchip to support for virtually all of
today’s CAN-based applications. Other potential
benefits of having a separate CAN controller include
the ability for system designers to select from a much
wider variety of MCUs for an optimal performance
solution.
Additional products planned for Microchip’s CAN
product portfolio include other CAN peripherals and a
family of PICmicro MCUs with integrated CAN support.
microID™ RFID Tagging Devices
Only Microchip manufactures world-class components
for every application in the radio frequency
identification (RFID) system. From the advanced,
feature-packed microID family of RFID tags and
high-endurance Serial EEPROMs to high performance
PICmicro MCUs and KEELOQ code hopping encoders -
Microchip's full range of RFID solutions are available
for your tag, peripheral and reader application designs.
The microID family can emulate almost any standard
on the market today. It provides drop-in compatible
solutions to the most commonly used 125 kHz and
13.56 MHz tags and an upgrade migration path for
virtually any application with higher performance and
new features.
Serial EEPROM Overview
Microchip’s high-endurance Serial EEPROMs
complement the diverse MCU product families. Serial
EEPROMs are available in a variety of densities,
operating voltages, bus interface protocols, operating
temperature ranges and space-saving packages.
Densities:
The densities range from 128 bits to 256 Kbits with
higher density devices in development.
Bus Interface Protocols:
We offer all popular protocols: I2C™, Microwire and
SPI.
Operating Voltages:
In addition to standard 5V devices there are two low
voltage families. The “LC” devices operate down to
2.5V, while the breakthrough “AA” family operates, in
both read and write mode, down to 1.8V, making these
devices highly suitable for alkaline and NiCd battery
powered applications.
Temperature Ranges:
Like all Microchip devices, many Serial EEPROMs are
offered in Commercial (0°C to +70°C), Industrial (-40°C
to +85°C) and Extended (-40°C to +125°C) operating
temperature ranges.
Packages:
Small footprint packages include: industry standard
5-lead SOT-23, 8-lead DIP, 8-lead SOIC in JEDEC and
EIAJ body widths, and 14-lead SOIC. The SOIC comes
in two body widths; 150 mil and 207 mil.
Technology Leadership:
Selected Microchip Serial EEPROMs are backed by a
1 million Erase/Write cycle. Microchip's erase/write
cycle endurance is among the best in the world, and only
Microchip offers such unique and powerful development
tools as the Total Endurance disk. This mathematical
software model is an innovative tool used by system
designers to optimize Serial EEPROM performance and
reliability within the application.
Microchip offers Plug-and-Play to the DIMM module
market with the 24LCS52, a special function
single-chip EEPROM that is available in space saving
packages. For Plug-and-Play video monitor
applications, Microchip offers the 24LC21, a
single-chip DDC1™/DDC2-compatible solution. In
addition, Microchip released a high-speed 1 MHz
2-wire Serial EEPROM device ideal for
high-performance embedded systems.
Microchip is a high-volume supplier of Serial
EEPROMs to all the major markets worldwide. The
Company continues to develop new Serial EEPROM
solutions for embedded control applications.
39500 18C Reference Manual.book Page xxi Monday, July 10, 2000 6:12 PM
DS00027U-page xxii 2000 Microchip Technology Inc.
OTP EPROM Overview
Microchip’s CMOS EPROM devices are produced in
densities from 64K to 512K. Typical applications
include computer peripherals, instrumentation, and
automotive devices. Microchip’s expertise in surface
mount packaging on SOIC and TSOP packages led to
the development of the surface mount OTP EPROM
market where Microchip is a leading supplier today.
Microchip is also a leading supplier of low-voltage
EPROMs for battery powered applications.
MIGRATABLE MEMORY™
TECHNOLOGY
Microchip’s innovative Migratable Memory technology
(MMT) provides socket and software compatibility
among all of its equivalent ROM, OTP and FLASH
memory MCUs. MMT allows customers to match the
selection of MCU memory technology to the product life
cycle of their application, providing an easy migration
path to a lower cost solution whenever appropriate.
FLASH memory is an ideal solution for engineers
designing products for embedded systems – especially
during the development and early stages of the
product. In certain products and applications, FLASH
memory may be used for the life of the product
because of the advantages of field upgradability or
where product inventory flexibility is required.
Once the design enters the pre-production stage and
continues through introduction and growth stages,
OTP program memory provides maximum
programming flexibility and minimum inventory
scrappage. The OTP device is pin and socket
compatible with the FLASH device – providing a lower
cost, high-volume flexible solution.
As the design enters a mature stage and program code
stabilizes, a lower cost, socket compatible ROM
memory device could be used. In some cases, OTP
memory may still be used as the most cost-effective
memory technology for the product. Compatibility and
flexibility are key to the success of the PICmicro MCU
product family, and ultimately the success of our
customers.
FLEXIBLE PROGRAMMING OPTIONS
To meet the stringent design requirements placed on
our customers, the following innovative programming
options are offered. These programming options
address procurement issues by reducing and limiting
work-in-process liability and facilitating finished goods
code revisions. Microchip's worldwide distributors
stock reprogrammable and one-time programmable
inventory, allowing customers to respond to immediate
sales opportunities or accommodate engineering
changes off the shelf.
FLASH (electrically reprogrammable)
PICmicro FLASH MCUs allow erase and
reprogramming of the MCU program memory.
Reprogrammability offers a highly flexible solution to
today's ever-changing market demands – and can
substantially reduce time to market. Users can program
their systems very late in the manufacturing process or
update systems in the field. This allows easy code
revisions, system parameterization or
customer-specific options with no scrappage.
Reprogrammability also reduces the design verification
cycle.
One-Time Programmable (OTP)
PICmicro OTP MCUs are manufactured in high
volumes without customer specific software and can be
shipped immediately for custom programming. This is
useful for customers who need rapid time to market
and flexibility for frequent software updates.
In-Circuit Serial Programming™ (ICSP™)
Microchip's PICmicro FLASH and OTP MCUs feature
ICSP capability. ICSP allows the MCU to be
programmed after being placed in a circuit board,
offering tremendous flexibility, reduced development
time, increased manufacturing efficiency and improved
time to market. This popular technology also enables
reduced cost of field upgrades, system calibration
during manufacturing, the addition of unique
identification codes to the system and system
calibration. Requiring only two I/O pins for most
devices, Microchip offers the most non-intrusive
programming methodology in the industry.
Self Programming
Microchip's PIC16F87X family features self
programming capability. Self programming enables
remote upgrades to the FLASH program memory and
the end equipment through a variety of medium ranging
from Internet and Modem to RF and Infrared. To setup
for self programming, the designer programs a simple
boot loader algorithm in a code protected area of the
FLASH program memory. Through the selected
medium, a secure command allows entry into the
PIC16F87X MCU through the USART, I2C or SPI serial
communication ports. The boot loader is then enabled
to reprogram the PIC16F87X FLASH program memory
with data received over the desired medium. And, of
course, self programming is accomplished without the
need for external components and without limitations
on the PIC16F87X’s operating speed or voltage.
Quick-Turn Programming (QTP)
Microchip offers a QTP programming service for
factory production orders. This service is ideal for
customers who choose not to program a medium to
high unit volume in their own factories, and whose
production code patterns have stabilized.
39500 18C Reference Manual.book Page xxii Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS00027U-page xxiii
Serialized Quick-Turn Programming (SQTPSM)
SQTP is a unique, flexible programming option that
allows Microchip to program serialized, random or
pseudo-random numbers into each device. Serial
programming allows each device to have a unique
number which can serve as an entry-code, password or
ID number.
Masked ROM
Microchip offers Masked ROM versions of many of its
most popular PICmicro MCUs, giving customers the
lowest cost option for high volume products with stable
firmware.
Future Products and Technology
Microchip is constantly developing advanced process
technology modules and new products that utilize our
advanced manufacturing capabilities. Current
production technology utilizes lithography dimensions
down to 0.7 micron.
Microchip’s research and development activities
include exploring new process technologies and
products that have industry leadership potential.
Particular emphasis is placed on products that can be
put to work in high-performance broad-based markets.
Equipment is continually updated to bring the most
sophisticated process, CAD and testing tools online.
Cycle times for new technology development are
continuously reduced by using in-house mask
generation, a high-speed pilot line within the
manufacturing facility and continuously improving
methodologies.
Objective specifications for new products are
developed by listening to our customers and by close
co-operation with our many customer-partners
worldwide.
39500 18C Reference Manual.book Page xxiii Monday, July 10, 2000 6:12 PM
DS00027U-page xxiv 2000 Microchip Technology Inc.
NOTES:
39500 18C Reference Manual.book Page xxiv Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39501A-page 1-1
Introduction
1
Section 1. Introduction
HIGHLIGHTS
This section of the manual contains the following major topics:
1.1 Introduction .................................................................................................................... 1-2
1.2 Manual Objective ........................................................................................................... 1-3
1.3 Device Structure ............................................................................................................ 1-4
1.4 Development Support .................................................................................................... 1-6
1.5 Device Varieties ............................................................................................................. 1-7
1.6 Style and Symbol Conventions .................................................................................... 1-12
1.7 Related Documents ..................................................................................................... 1-14
1.8 Related Application Notes............................................................................................ 1-17
1.9 Revision History........................................................................................................... 1-18
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39501A-page 1-2 2000 Microchip Technology Inc.
1.1 Introduction
Microchip is the Embedded Control Solutions Company. 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)
• 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).
In the past, 8-bit MCU users were fixed on the traditional MCU model for production, a ROM device.
Microchip has been the leader in changing this perception by showing that OTP devices can give
a better lifetime product cost compared to ROM versions.
Microchip has strength in FLASH and EPROM technology. This makes it the memory technology
of choice for the PICmicro MCU’s program memory. Microchip has minimized the cost difference
between EPROM and ROM memory technology. Therefore, Microchip can pass these benefits on
to our customers. This is not true for other MCU vendors, and is seen in the price difference
between their FLASH/EPROM and ROM versions.
The growth of Microchip’s 8-bit MCU market share is a testament to the PICmicro MCU’s ability to
meet the needs of many customers. This growth has made the PICmicro architecture one of the
top two architectures available in the general market today. This growth was fueled by the Microchip
vision of the benefits of a low cost Field Programmable MCU solution. Some of the benefits
for the customer include:
• Quick time to market
• Allows code changes to product during production run
• No Non-Recurring Engineering (NRE) charges for Mask Revisions
• Ability to easily serialize the product
• Ability to store calibration data without additional hardware
• Better able to maximize use of PICmicro MCU inventory
• Less risk, since the same device is used for development as well as for production.
Microchip’s PICmicro 8-bit MCUs offer a price/performance ratio that allows them to be considered
for any traditional 8-bit MCU application, as well as some traditional 4-bit applications (Base-Line
family), low-end 16-bit applications (PIC17CXXX and PIC18CXXX families), dedicated logic
replacement and low-end DSP applications (High-End and Enhanced families). These features
and price-performance mix make PICmicro MCUs an attractive solution for most applications.
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39501A-page 1-3
Section 1. Introduction
Introduction
1
1.2 Manual Objective
PICmicro devices are grouped by the size of their Instruction Word and their Instruction Set. The
four current PICmicro families and their Instruction Word length are:
1. Base-Line: 12-bit Instruction Word length
2. Mid-Range: 14-bit Instruction Word length
3. High-End: 16-bit Instruction Word length
4. Enhanced: 16-bit Instruction Word length
This manual focuses on the Enhanced MCU family of devices, which are also referred to as the
PIC18CXXX MCU family.
The operation of the Enhanced MCU family architecture and peripheral modules is explained,
but does not cover, the specifics of each device. This manual is not intended to replace the
device data sheets, but complement them. In other words, this guide supplies the general details
and operation of the PICmicro architecture and peripheral modules, while the data sheet gives
the specific details (such as device memory mapping).
Initialization 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.
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39501A-page 1-4 2000 Microchip Technology Inc.
1.3 Device Structure
Each part of a device can be placed into one of three groups:
1. Core
2. Peripherals
3. Special Features
1.3.1 Core
The core pertains to the basic features that are required to make the device operate. These
include:
1. Oscillator Revision “DS39502A”
2. Reset Revision “DS39503A”
3. Architecture Revision “DS39504A”
4. CPU (Central Processing Unit) and Revision “DS39505A”
ALU (Arithmetic Logical Unit)
5. Hardware 8x8 Multiplier Revision “DS31006A”
6. Memory Revision “DS31007A”
7. Table Read / Table Write Revision “DS39508A”
8. System Bus Revision “DS39509A”
9. Interrupts Revision “DS39510A”
10. Instruction Set Revision “DS39532A”
1.3.2 Peripherals
Peripherals are the features that add a differentiation from a microprocessor. These ease in interfacing
to the external world (such as general purpose I/O, A/D inputs, and PWM outputs), and
internal tasks, such as keeping different time bases (i.e. timers). The peripherals that are discussed
are:
1. I/O Revision “DS39511A”
1. Parallel Slave Port (PSP) Revision “DS39512A”
2. Timer0 Revision “DS39513A”
3. Timer1 Revision “DS39514A”
4. Timer2 Revision “DS39515A”
5. Timer3 Revision “DS39516A”
6. Capture/Compare/PWM (CCP) Revision “DS39517A”
7. Serial Slave Port (SSP) Revision “DS39519A”
8. Master Synchronous Serial Port (MSSP) Revision “DS39520A”
9. Addressable USART Revision “DS39521A”
10. CAN Revision “DS39522A”
11. Comparator Voltage Reference Revision “DS31023A”
12. Comparators Revision “DS39525A”
13. Compatible 10-bit A/D Converter Revision “DS31026A”
14. 10-bit A/D Converter Revision “DS31027A”
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39501A-page 1-5
Section 1. Introduction
Introduction
1
1.3.3 Special Features
Special features are the unique features that help to:
• Decrease system cost
• Increase system reliability
• Increase design flexibility
The Enhanced PICmicro MCUs offer several features that help achieve these goals. The special
features discussed are:
1. Low Voltage Detect Revision “DS39528A”
2. WDT and Sleep Operation Revision “DS31029A”
3. Device Configuration Bits Revision “DS39530A”
4. In-Circuit Serial Programming™ (ICSP™) Revision “DS39531A”
1.3.4 Other Sections
This section provides the cross references for the remaining sections of this manual.
1. Introduction Revision “DS39501A”
2. Electrical Specifications Revision “DS31033A”
3. Device Characteristics Revision “DS31034A”
4. Development Tools Revision “DS31035A”
5. Code Development Revision “DS31036A”
6. Appendix Revision “DS39537A”
7. Glossary Revision “DS39538A”
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39501A-page 1-6 2000 Microchip Technology Inc.
1.4 Development Support
Microchip offers a wide range of development tools that allow users to efficiently develop and
debug application code. Microchip’s development tools can be broken down into four categories:
1. Code generation
2. Hardware/Software debug
3. Device programmer
4. Product evaluation boards
All tools developed by Microchip operate under the MPLAB® Integrated Development Environment
(IDE), while some third party tools may not. The code generation tools include:
• MPASM
• MPLAB®-C17 (for PIC17CXXX family only)
• MPLAB®-C18 (for PIC18CXXX family only)
These software development programs include device header files. Each header file defines the
register names (as shown in the device data sheet) to the specified address or bit location. Using
the header files eases code migration and reduces the tediousness of memorizing a register’s
address or a bit’s position in a register.
Tools which ease in debugging software are:
• MPLAB®-ICE In-Circuit Emulator
• PICMASTER® In-Circuit Emulator
• ICEPIC In-Circuit Emulator
• MPLAB®-SIM Software Simulator
After generating and debugging the application software, the device will need to be programmed.
Microchip offers two levels of programmers:
1. PICSTART Plus programmer
2. PRO MATE II programmer
Demonstration boards allow the developer of software code to evaluate the capability and suitability
of the device to the application. The demo boards offered are:
• PICDEM-1
• PICDEM-2 (can be used with PIC18CXX2 devices)
• PICDEM-3
• PICDEM-14A
• PICDEM-17
At the time of publication, only PICDEM-2 could be used with some Enhanced MCU devices.
A full description of each of Microchip’s development tools is discussed in the “Development
Tools” section. As new tools are developed, product briefs and user guides may be obtained
from the Microchip web site (www.microchip.com) or from your local Microchip Sales Office.
Code development recommendations and techniques are provided in the “Code Development”
section.
Microchip offers other reference tools to speed the development cycle. These include:
• Application Notes
• Reference Designs
• Microchip web site
• Local Sales Offices with Field Application Support
• Corporate Support Line
The Microchip web site lists other sites that may be useful references.
Note: Microchip strongly recommends that the supplied header files be used in the source
code of your program. This eases code migration, improves code readability, and
increases the quality and depth of the technical support that Microchip can offer.
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39501A-page 1-7
Section 1. Introduction
Introduction
1
1.5 Device Varieties
Once the functional requirements of the device are specified, other choices need to be made.
These include:
• Memory technology
• Operating voltage
• Operating temperature range
• Operating frequency
• Packaging
Microchip has a large number of options and option combinations, one of which should fulfill your
requirements.
1.5.1 Memory Varieties
Memory technology has no effect on the logical operation of a device. Due to the different processing
steps required, some electrical characteristics may vary between devices with the same
feature set/pinout but with different memory technologies. An example is the electrical characteristic
VIL (Input Low Voltage), which may have some difference between a typical EPROM device
and a typical ROM device.
Each device has a variety of frequency ranges and packaging options available. Depending on
application and production requirements, the proper device options can be identified using the
information in the Product Identification System section at the end of each data sheet. When
placing orders, please use the “Product Identification System” at the back of the data sheet to
specify the correct part number.
When discussing the functionality of the device, the memory technology and the voltage range
do not matter. Microchip offers three program memory types. The memory type is designated in
the part number by the first letter(s) after the family affiliation designators.
1. C, as in PIC18CXXX. These devices have EPROM type memory.
2. CR, as in PIC18CRXXX. These devices have ROM type memory.
3. F, as in PIC18FXXX. These devices have FLASH type memory.
1.5.1.1 EPROM
Microchip focuses on Erasable Programmable Read Only Memory (EPROM) technology to give
customers flexibility throughout their entire design cycle. With this technology, Microchip offers
various packaging options as well as services.
1.5.1.2 Read Only Memory (ROM) Devices
Microchip offers a masked Read Only Memory (ROM) version of several of the highest volume
parts, thus giving customers a lower cost option for high volume, mature products.
ROM devices do not allow serialization information in the program memory space.
For information on submitting ROM code, please contact your local Microchip sales office.
1.5.1.3 FLASH Memory Devices
These devices are electrically erasable, and can therefore be offered in a low cost plastic package.
Being electrically erasable, these devices can be erased and reprogrammed without
removal from the circuit. A device will have the same specifications whether it is used for prototype
development, pilot programs or production.
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39501A-page 1-8 2000 Microchip Technology Inc.
1.5.2 Operating Voltage Range Options
All Enhanced PICmicro MCUs operate over the standard voltage range. Devices are also offered
which operate over an extended voltage range (and reduced frequency range). Table 1-1 shows
all possible memory types and voltage range designators for the PIC18CXXX MCU family. The
designators are in bold typeface.
Table 1-1: Device Memory Type and Voltage Range Designators
As you can see in Table 1-2, Microchip specifies its extended range devices at a more conservative
voltage range until device characterization has ensured they will be able to meet the goal of
their final design specifications.
Table 1-2: Typical Voltage Ranges for Each Device Type
Memory Type
Voltage Range
Standard Extended
EPROM PIC18CXXX PIC18LCXXX
ROM PIC18CRXXX PIC18LCRXXX
FLASH PIC18FXXX PIC18LFXXX
Note: Not all memory types may be available for a particular device.
Typical Voltage Range EPROM ROM Flash
Standard C 4.2 - 5.5V CR 4.2 - 5.5V F 4.2 - 5.5V
Extended Before device characterization LC 3.0 - 5.5V LCR 3.0 - 5.5V LF 3.0 - 5.5V
Final specification (1) LC 2.5 - 5.5V LCR 2.5 - 5.5V LF 2.0 - 5.5V
Note 1: This voltage range depends on the results of device characterization.
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39501A-page 1-9
Section 1. Introduction
Introduction
1
Figure 1-1 and Figure 1-2 show example Voltage to Frequency Charts for the Enhanced MCU
family. The voltages and frequencies of any given device may be different than those shown.
These figures are intended to show that with an LC (extended voltage) device, the user can make
a trade-off between voltage of operation and the frequency of the device. The device FMAX is
given below the graph. As the voltages and frequencies of the device change, the equation for
the device FMAX will change. Equation 1-1 shows the general equation to determine the device
FMAX.
Equation 1-1: Generic FMAX Equation
Figure 1-1: PIC18CXXX Voltage-Frequency Graph - Example
Figure 1-2: PIC18LCXXX Voltage-Frequency Graph - Example
FMAX = (slope) (VDDAPPMIN - VDDMIN) + offset
Frequency
Voltage
6.0 V
5.5 V
4.5 V
4.0 V
2.0 V
40 MHz
5.0 V
3.5 V
3.0 V
2.5 V
PIC18CXXX
4.2V
Frequency
Voltage
6.0 V
5.5 V
4.5 V
4.0 V
2.0 V
40 MHz
5.0 V
3.5 V
3.0 V
2.5 V
PIC18LCXXX
6 MHz
4.2V
Note: VDDAPPMIN is the minimum voltage of the PICmicro device in the application.
FMAX = (20.0 MHz/V) (VDDAPPMIN - 2.5 V) + 6 MHz
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39501A-page 1-10 2000 Microchip Technology Inc.
1.5.3 Packaging Varieties
Depending on the development phase of your project, one of three package types would be
used.
The first package type is ceramic with an erasure window. The window allows ultraviolet light into
the package so that the device inside may be erased. The package is used for the development
phase, since the device’s program memory can be erased and reprogrammed many times.
The second package type is a low cost plastic package. This package type is used in production
where device cost is to be kept to a minimum.
Lastly, there is the Die option. A Die is an unpackaged device that has been tested. Dies are used
in low cost designs and designs where board space is at a minimum. For additional information
on die support, please refer to the Die Support Document (DS30258).
Table 1-3 shows a quick summary of the typical use for each package type.
Table 1-3: Typical Package Uses
1.5.3.1 UV Erasable Devices
The UV erasable version of EPROM program memory devices is optimal for prototype development
and pilot programs.
These devices can be erased and reprogrammed to any of the configuration modes. Third party
programmers are available. Refer to Microchip’s Third Party Guide (DS00104) for a list of
sources.
The amount of time required to completely erase a UV erasable device depends on the:
• Wavelength of the light
• Intensity of the light
• Distance of the device from the UV source
• Process technology of the device (size of the memory cells).
1.5.3.2 One-Time-Programmable (OTP) Devices
The availability of OTP devices is especially useful for customers expecting code changes and
updates.
OTP devices in plastic packages permit the user to program them once. Often the system can
be designed so that programming may be performed in-circuit (after the device has been
mounted on the circuit board).
1.5.3.3 FLASH Devices
These devices are electrically erasable, and can therefore be offered in a low cost plastic package.
Being electrically erasable, these devices can be both erased and reprogrammed without
removal from the circuit. A device will have the same specifications whether it is used for prototype
development, pilot programs, or production.
Package Type Typical Usage
Windowed Development mode
Plastic Production
Die Special applications, such as those which require minimum board space
Note: Fluorescent lights and sunlight both emit ultraviolet light at the erasure wavelength.
Leaving a UV erasable device’s window uncovered could cause, over time, the
device’s memory cells to become erased. The erasure time for a fluorescent light is
about three years, while sunlight requires only about one week. To prevent the
memory cells from losing data, an opaque label should be placed over the erasure
window.
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39501A-page 1-11
Section 1. Introduction
Introduction
1
1.5.3.4 ROM Devices
ROM devices have their program memory fixed at the time of the silicon manufacture. Since the
program memory cannot be changed, the device is usually housed in the low cost plastic package.
1.5.3.5 Die
The Die option allows the board size to become as small as physically possible. The Die Support
document (DS30258) explains general information about using and designing with Die. There
are also individual specification sheets that detail Die specific information. Manufacturing with
Die requires special knowledge and equipment. This means that the number of manufacturing
houses that support Die will be limited. If you decide to use the Die option, please research your
manufacturing sites to ensure that they will be able to meet the specialized requirements of Die
use.
1.5.3.6 Specialized Services
For OTP customers with established code, Microchip offers two specialized services. These two
services, Quick Turn Production Programming and Serialized Quick Turn Production Programming,
allow customers to shorten their manufacturing cycle time.
1.5.3.6.1 Quick Turn Production (QTP) Programming
Microchip offers this programming service for factory production orders. This service is made
available for users who choose not to program a medium to high quantity of units at their factory
and whose code patterns have stabilized. The devices are identical to the OTP devices, but with
all EPROM locations and configuration options already programmed by Microchip. Certain code
and prototype verification procedures apply before production shipments are available. Please
contact your local Microchip sales office for more details.
1.5.3.6.2 Serialized Quick Turn Production (SQTPSM) Programming
Microchip offers a unique programming service where a few user-defined locations in each
device are programmed with unique numbers. These numbers may be:
• Random numbers
• Pseudo-random numbers
• Sequential numbers
Serial programming allows each device to have a unique number which can serve as an
entry-code, password, ID, or serial number.
39500 18C Reference Manual.book Page 11 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39501A-page 1-12 2000 Microchip Technology Inc.
1.6 Style and Symbol Conventions
Throughout this document, certain style and font format conventions are used. Most format conventions
imply a distinction should be made for the emphasized text. The MCU industry has
many symbols and non-conventional word definitions/abbreviations. Table 1-4 provides a
description for many of the conventions contained in this document. A glossary is provided in the
“Glossary” section, which contains more word and abbreviation definitions that are used
throughout this manual.
1.6.1 Document Conventions
Table 1-4 defines some of the symbols and terms used throughout this manual.
Table 1-4: Document Conventions
Symbol or Term Description
set To force a bit/register to a value of logic ‘1’.
clear To force a bit/register to a value of logic ‘0’.
reset 1) To force a register/bit to its default state.
2) A condition in which the device places itself after a device reset
occurs. Some bits will be forced to ‘0’ (such as interrupt enable bits),
while others will be forced to ‘1’ (such as the I/O data direction bits).
0xnn or nnh Designates the number ‘nn’ in the hexadecimal number system. These
conventions are used in the code examples.
B’bbbbbbbb’ Designates the number ‘bbbbbbbb’ in the binary number system. This
convention is used in the text and in figures and tables.
R-M-W Read - Modify - Write. This is when a register or port is read, then the
value is modified, and that value is then written back to the register or
port. This action can occur from a single instruction (such as bit set file,
BSF) or a sequence of instructions.
: (colon) Used to specify a range or the concatenation of registers/bits/pins.
One example is TMR1H:TMR1L, which is the concatenation of two 8-bit
registers to form a 16-bit timer value, while SSPM3:SSPM0 are 4-bits
used to specify the mode of the SSP module.
Concatenation order (left-right) usually specifies a positional relationship
(MSb to LSb, higher to lower).
< > Specifies bit(s) locations in a particular register.
One example is SSPCON (or SSPCON<3:0>) which
specifies the register and associated bits or bit positions.
Courier Font Used for code examples, binary numbers and for Instruction Mnemonics
in the text.
Times Font Used for equations and variables.
Times, Bold Font,
Italics
Used in explanatory text for items called out from a graphic/equation/example.
Note A Note presents information that we wish to reemphasize, either to help
you avoid a common pitfall, or make you aware of operating differences
between some device family members. A Note is always in a shaded box
(as below), unless used in a table, where it is at the bottom of the table
(as in this table).
Note: This is a Note in a note box.
Caution (1) A caution statement describes a situation that could potentially damage
software or equipment.
Warning (1) A warning statement describes a situation that could potentially cause
personal harm.
Note 1: The information in a caution or a warning is provided for your protection. Please read
each caution and warning carefully.
39500 18C Reference Manual.book Page 12 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39501A-page 1-13
Section 1. Introduction
Introduction
1
1.6.2 Electrical Specifications
Throughout this manual, there will be references to electrical specification parameter numbers.
A parameter number represents a unique set of characteristics and conditions that is consistent
between every data sheet, though the actual parameter value may vary from device to device.
The “Electrical Specifications” section shows all the specifications that are documented for all
devices. No one device has all these specifications. This section is intended to let you know the
types of parameters that Microchip specifies. The value of each specification is device dependent,
though we strongly attempt to keep them consistent across all devices.
Table 1-5: Electrical Specification Parameter Numbering Convention
Parameter
Number
Format
Comment
DXXX DC Specification
AXXX DC Specification for Analog Peripherals
XXX Timing (AC) Specification
PDXXX Device Programming DC Specification
PXXX Device Programming Timing (AC) Specification
Legend: XXX represents a number.
39500 18C Reference Manual.book Page 13 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39501A-page 1-14 2000 Microchip Technology Inc.
1.7 Related Documents
Microchip, as well as other sources, offers additional documentation which can aid in your development
with PICmicro MCUs. These lists contain the most common documentation, but other
documents may also be available. Please check the Microchip web site (www.microchip.com) for
the latest published technical documentation.
1.7.1 Microchip Documentation
The following documents are available from Microchip. Many of these documents provide application
specific information that give actual examples of using, programming and designing with
PICmicro MCUs.
1. MPASM and MPLINK (w/ MPLIB) User’s Guide (DS33014)
This document explains how to use Microchip’s MPASM assembler.
2. MPLAB®-CXX Compiler User’s Guide (DS51217)
This document explains how to use Microchip’s MPLAB-C17 and MPLAB-C18 compilers.
3. MPLAB® IDE, Simulator, Editor User’s Guide (DS51025)
This document explains how to use Microchip’s MPLAB Integrated Development Environment.
4. MPLAB®-CXX Reference Guide Libraries and Precompiled Object Files (DS51224)
This document explains how to use Microchip’s MPLAB Reference Guide Libraries and
Precompiled Object Files.
5. PICMASTER® User’s Guide (DS30421)
This document explains how to use Microchip’s PICMASTER In-Circuit Emulator.
6. PRO MATE® User’s Guide (DS30082)
This document explains how to use Microchip’s PRO MATE Universal Programmer.
7. PICSTART®-Plus User’s Guide (DS51028)
This document explains how to use Microchip’s PICSTART-Plus low-cost universal programmer.
8. PICmicro® Mid-Range MCU Family Reference Manual (DS33023)
This document discusses the operation of PICmicro Mid-Range MCU devices, explaining
the detailed operation of the architecture and peripheral modules. It is a compliment to the
device data sheets for the Mid-Range family.
9. Embedded Control Handbook Volume I (DS00092)
This document contains a plethora of application notes. This is useful for insight on how
to use the device (or parts of it), as well as getting started on your particular application
due to the availability of extensive code files.
10. Embedded Control Handbook Update 2000 (DS00711)
This document contains additional application notes.
11. Embedded Control Handbook Volume II Math Library (DS00167)
This document contains the Math Libraries for PICmicro MCUs.
12. In-Circuit Serial Programming Guide™ (DS30277)
This document discusses implementing In-Circuit Serial Programming.
13. PICDEM-1 User’s Guide (DS33015)
This document explains how to use Microchip’s PICDEM-1 demo board.
14. PICDEM-2 User’s Guide (DS30374)
This document explains how to use Microchip’s PICDEM-2 demo board.
15. PICDEM-3 User’s Guide (DS51079)
This document explains how to use Microchip’s PICDEM-3 demo board.
16. PICDEM-14A User’s Guide (DS51097)
This document explains how to use Microchip’s PICDEM-14A demo board.
17. PICDEM-17 User’s Guide (DS39024)
This document explains how to use Microchip’s PICDEM-17 demo board.
18. Third Party Guide (DS00104)
This document lists Microchip’s third parties, as well as various consultants.
19. Die Support (DS30258)
This document gives information on using Microchip products in Die form.
39500 18C Reference Manual.book Page 14 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39501A-page 1-15
Section 1. Introduction
Introduction
1
1.7.2 Third Party Documentation
There are several documents available from third party sources around the world. Microchip
does not review these documents for technical accuracy. However, they may be a helpful source
for understanding the operation of Microchip PICmicro MCU devices. This is not necessarily a
complete list, but are the documents that we were aware of at the time of printing. For more information
on how to contact some of these sources, as well as any new sources that we become
aware of, please visit the Microchip web site (www.microchip.com).
DOCUMENT LANGUAGE
The PIC16C5X Microcontroller: A Practical Approach to
Embedded Control
Bill Rigby/ Terry Dalby, Tecksystems Inc.
0-9654740-0-3 ........................................................................................................... English
Easy PIC'n
David Benson, Square 1 Electronics
0-9654162-0-8 ........................................................................................................... English
A Beginner’s Guide to the Microchip PIC®
Nigel Gardner, Bluebird Electronics
1-899013-01-6 ........................................................................................................... English
PIC Microcontroller Operation and Applications
DN de Beer, Cape Technikon..................................................................................... English
Digital Systems and Programmable Interface Controllers
WP Verburg, Pretoria Technikon ................................................................................ English
Mikroprozessor PIC16C5X
Michael Rose, Hüthig
3-7785-2169-1 .......................................................................................................... German
Mikroprozessor PIC17C42
Michael Rose, Hüthig
3-7785-2170-5 .......................................................................................................... German
Les Microcontrolleurs PIC et mise en oeuvre
Christian Tavernier, Dunod
2-10-002647-X ............................................................................................................ French
Microcontrolleurs PIC a structure RISC
C.F. Urbain, Publitronic
2-86661-058-X ............................................................................................................ French
New Possibilities with the Microchip PIC
RIGA ......................................................................................................................... Russian
39500 18C Reference Manual.book Page 15 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39501A-page 1-16 2000 Microchip Technology Inc.
DOCUMENT LANGUAGE
PIC16C5X/71/84 Development and Design, Part 1
United Tech Electronic Co. Ltd
957-21-0807-7...........................................................................................................Chinese
PIC16C5X/71/84 Development and Design, Part 2
United Tech Electronic Co. Ltd
957-21-1152-3...........................................................................................................Chinese
PIC16C5X/71/84 Development and Design, Part 3
United Tech Electronic Co. Ltd
957-21-1187-6...........................................................................................................Chinese
PIC16C5X/71/84 Development and Design, Part 4
United Tech Electronic Co. Ltd
957-21-1251-1...........................................................................................................Chinese
PIC16C5X/71/84 Development and Design, Part 5
United Tech Electronic Co. Ltd
957-21-1257-0...........................................................................................................Chinese
PIC16C84 MCU Architecture and Software Development
ICC Company
957-8716-79-6...........................................................................................................Chinese
39500 18C Reference Manual.book Page 16 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39501A-page 1-17
Section 1. Introduction
Introduction
1
1.8 Related Application Notes
This section lists application notes that are related to this section of the manual. These application
notes may not be written specifically for the Enhanced MCU family (they may be written for
the Base-Line, Mid-Range, or High-End families), but the concepts are pertinent, and could be
used (with modification and possible limitations). The current application notes related to an introduction
to Microchip’s PICmicro MCUs are:
Title Application Note #
A Comparison of Low End 8-bit Microcontrollers AN520
PIC16C54A EMI Results AN577
Continuous Improvement AN503
Improving the Susceptibility of an Application to ESD AN595
Plastic Packaging and the Effects of Surface Mount Soldering Techniques AN598
Migrating Designs from PIC16C74A/74B to PIC18C442 AN716
PIC17CXXX to PIC18CXXX Migration AN726
Note: Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
http://www.microchip.com/10/faqs/codeex/
39500 18C Reference Manual.book Page 17 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39501A-page 1-18 2000 Microchip Technology Inc.
1.9 Revision History
Revision A
This is the initial released revision of Enhanced MCU Introduction.
39500 18C Reference Manual.book Page 18 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39502A-page 2-1
Oscillator
2
Section 2. Oscillator
HIGHLIGHTS
This section of the manual contains the following major topics:
2.1 Introduction .................................................................................................................... 2-2
2.2 Control Register............................................................................................................. 2-3
2.3 Oscillator Configurations................................................................................................ 2-4
2.4 Crystal Oscillators/Ceramic Resonators ........................................................................ 2-6
2.5 External RC Oscillator.................................................................................................. 2-15
2.6 HS4 (HS oscillator with 4xPLL enabled) ...................................................................... 2-18
2.7 Switching to Low Power Clock Source......................................................................... 2-19
2.8 Effects of Sleep Mode on the On-Chip Oscillator......................................................... 2-23
2.9 Effects of Device Reset on the On-Chip Oscillator ...................................................... 2-23
2.10 Design Tips.................................................................................................................. 2-24
2.11 Related Application Notes............................................................................................ 2-25
2.12 Revision History........................................................................................................... 2-26
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39502A-page 2-2 2000 Microchip Technology Inc.
2.1 Introduction
The device system clock is required for the device to execute instructions and for the peripherals
to function. Four device system clock periods (TSCLK) generate one internal instruction clock
cycle (TCY).
The device system clock (TSCLK) is derived from an external system clock. This external system
clock can be generated in one of eight different oscillator modes. The device configuration bits
select the oscillator mode. Device configuration bits are nonvolatile memory locations and the
operating mode is determined by the value written during device programming. The oscillator
modes are:
• EC External Clock
• ECIO External Clock with I/O pin enabled
• LP Low Frequency (Power) Crystal
• XT Crystal/Resonator
• HS High Speed Crystal/Resonator
• RC External Resistor/Capacitor
• RCIO External Resistor/Capacitor with I/O pin enabled
• HS4 High Speed Crystal/Resonator with 4x frequency PLL multiplier enabled
Multiple oscillator circuits can be implemented on an Enhanced Architecture device. There is the
default oscillator (OSC1), and additional oscillators may be available, such as the Timer1 oscillator.
Software may allow these auxiliary oscillators to be switched in as the device oscillator. The
Timer1 oscillator is a low frequency (low power) oscillator that is designed to be operated at
32kHz. Figure2-1 shows a block diagram of the oscillator options.
The output signal of the Timer1 oscillator circuitry is a low frequency (power) clock source (TT1P).
The source for the device system clock can be switched from the default clock (TSCLK) to the
32kHz-clock low power clock source (TT1P) under software control. Switching to the 32kHz low
frequency (power) clock source from any of the eight default clock sources may allow power
saving.
These oscillator options are made available to allow a single device type the flexibility to fit applications
with different oscillator requirements. The RC oscillator option saves system cost, while
the LP crystal option saves power. The HS4 option allows frequency of incoming crystal oscillator
signal to be multiplied by four for higher internal clock frequency. This is useful for customers who
are concerned with EMI due to high frequency crystals. The device configuration bits are used
to select these various options. For more details on the device configuration bits, see the “Device
Configuration Bits” section.
Figure 2-1: Device Clock Sources
PIC18CXXX
TOSC
4 x PLL
TT1P
TSCLK
Clock
Source MUX
TOSC/4
Timer1 Oscillator
T1OSCEN
Enable
Oscillator
T1OSO
T1OSI
Clock Source option
for other modules
OSC1
OSC2
Sleep
Main Oscillator
(FOSC2:FOSC0)
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39502A-page 2-3
Section 2. Oscillator
Oscillator
2
2.2 Control Register
Register 2-1 shows the OSCCON register which contains the control bit to allow switching of the
system clock between the primary oscillator and the Timer1 oscillator.
Register 2-1: OSCCON Register
U-0 U-0 U-0 U-0 U-0 U-0 U-0 R/W-1
— — — — — — — SCS
bit 7 bit 0
bit 7-1 Unimplemented: Read as '0'
bit 0 SCS: System Clock Switch bit
when OSCSEN configuration bit = ’0’ and T1OSCEN bit is set:
1 = Switch to Timer1 Oscillator/Clock pin
0 = Use primary Oscillator/Clock input pin
when OSCSEN and T1OSCEN are in other states:
bit is forced clear
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = Bit is set ’0’ = Bit is cleared x = Bit is unknown
Note: The Timer1 oscillator must be enabled to switch the system clock source. The
Timer1 oscillator is enabled by setting the T1OSCEN bit in the Timer1 control register
(T1CON). If the Timer1 oscillator is not enabled, then any write to the SCS bit will be
ignored (SCS bit forced cleared) and the main oscillator will continue to be the system
clock source.
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39502A-page 2-4 2000 Microchip Technology Inc.
2.3 Oscillator Configurations
The oscillator selection is configured at time of device programming. The user can program up
to three device configuration bits (FOSC2:FOSC0) to select one of eight modes.
2.3.1 Oscillator Types
PIC18CXXX devices can have up to eight different oscillator modes for the default clock source
(TSCLK). These eight modes are:
• EC External Clock
• ECIO External Clock with IO pin enabled
• LP Low Frequency (Power) Crystal
• XT Crystal/Resonator
• HS High Speed Crystal/Resonator
• RC External Resistor/Capacitor
• RCIO External Resistor/Capacitor with IO pin enabled
• HS4 High Speed Crystal/Resonator with 4x frequency PLL multiplier enabled
The main difference between the LP, XT and HS modes is the gain of the internal inverter of the
oscillator circuit, which allows the different frequency ranges. Table 2-1 gives information to aid
in selecting an oscillator mode. 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,
component variations (resistor, capacitor, and internal microcontroller oscillator circuitry).
Switching the system clock source to the alternate clock source is controlled by the application
software. The user can switch from any of the eight default clock sources. This is done by setting
the SCS (System Clock Switch) bit in the OSCCON register. The requirements for switching to
the alternate clock source are:
• Timer1 clock oscillator must be enabled (T1OSCEN is set ’1’).
• The OSCEN configuration bit must be cleared (‘0’).
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39502A-page 2-5
Section 2. Oscillator
Oscillator
2
Table 2-1: Selecting the Oscillator Mode for Devices
FOSC2:FOSC0
Configuration
Bits
OSC
Mode
OSC
Feedback
Inverter
Gain
OSC2/CLKO
Function Comment
111 RCIO Zero Gain.
Device
turned off to
save current.
I/O Least expensive solution for device oscillation
(only an external resistor and capacitor is
required).
Most variation in time-base. Device’s default
mode. OSC2/CLKO is configured as general
purpose I/O pin. This pin is multiplexed with one
of the device’s PORT pins.
110 HS4 High Gain — Highest frequency application.
This works with the HS oscillator circuit mode
and phase lock loop. This mode consumes the
most current. The internal phase lock loop
circuit multiplies the external oscillator frequency
by 4.
101 ECIO Zero Gain.
Device
turned off to
save current.
I/O External clock mode with OSC2/CLKO configured
as general purpose I/O pin. This pin is multiplexed
with one of the device’s PORT pins.
OSC1/CLKI is hi-impedance and can be driven
by CMOS drivers.
100 EC Zero Gain.
Device
turned off to
save current.
Clock out
with oscillator
frequency
divided by 4.
External clock mode with OSC2/CLKO configured
with oscillator frequency divided by 4.
OSC1/CLKI is hi-impedance and can be driven
by CMOS drivers.
011 RC Zero Gain.
Device
turned off to
save current.
Clock out
with oscillator
frequency
divided by 4.
Inexpensive solution for device oscillation.
Most variation in timebase.
CLKOUT is enabled on OSC2/CLKO with oscillator
frequency divided by 4.
010 HS High Gain — High frequency application.
Oscillator circuit’s mode consumes the most
current of the three crystal modes.
001 XT Medium Gain — Standard crystal/resonator frequency.
000 LP Low Gain — Low power/frequency applications.
Oscillator circuit’s mode consumes the least
current of the three crystal modes.
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39502A-page 2-6 2000 Microchip Technology Inc.
2.4 Crystal Oscillators/Ceramic Resonators
In XT, LP, HS and HS4 modes, a crystal or ceramic resonator is connected to the OSC1 and
OSC2 pins to establish oscillation (Figure2-2). The PIC18CXXX oscillator design requires the
use of a parallel cut crystal. Using a series cut crystal may give a frequency out of the crystal
manufacturer’s specifications. When in EC and ECIO mode, the device can have an external
clock source drive the OSC1 pin (Figure2-3).
See Table 3-1 in the “Reset” section for time-out delays associated with crystal oscillators.
Figure 2-2: Crystal or Ceramic Resonator Operation (HS4, HS, XT or LP Oscillator
Mode)
Figure 2-3: External Clock Input Operation (EC or ECIO Oscillator Modes)
C1 (3)
C2 (3)
XTAL
OSC2
RS (1)
OSC1
RF (2) SLEEP
To internal logic
PIC18CXXX
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 Table 2-2 and 2-3 for example values of C1 and C2.
CLKI
Open CLKO
Clock from
ext. system PIC18CXXX
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39502A-page 2-7
Section 2. Oscillator
Oscillator
2
2.4.1 Oscillator/Resonator Start-up
As the device voltage increases from VSS, the oscillator will start its oscillations. The time
required for the oscillator to start oscillating depends on many factors. These include:
• Crystal/resonator frequency
• Capacitor values used (C1 and C2 in Figure2-2)
• Device VDD rise time
• System temperature
• Series resistor value and type if used (Rs in Figure2-2)
• Oscillator mode selection of device (selects the gain of the internal oscillator inverter)
• Crystal quality
• Oscillator circuit layout
• System noise
Figure2-4 graphs an example oscillator/resonator start-up. The peak-to-peak voltage of the oscillator
waveform can be quite low (less than 50% of device VDD), when the waveform is centered
at VDD/2 (refer to parameters D033 and D043 in the “Electrical Specifications” section).
Figure 2-4: Example Oscillator/Resonator Start-up Characteristics
Voltage
Crystal Start-up Time
Time
Device VDD
Maximum VDD of System
0V
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39502A-page 2-8 2000 Microchip Technology Inc.
2.4.2 Component Selection
Figure2-2 is a diagram of the device’s crystal or ceramic resonator circuitry. The resistance for
the feedback resistor, RF, is typically within the 2 to 10 MΩ range. This varies with device voltage,
temperature and process variations. A series resistor, Rs, may be required if an AT strip cut crystal
is used. Be sure to include the device’s operating voltage and the device’s manufacturing process
when determining resistor requirements. As you can see in Figure2-2, the connection to the
device’s internal logic is device dependent. See the applicable data sheet for device specifics.
The typical values of capacitors (C1, C2) are given in Table 2-2 and Table 2-3. Each device’s data
sheet will give the specific values that we test to at Microchip.
Table 2-2: Example Capacitor Selection for Ceramic Resonators
Ranges tested:
Mode Frequency C1 (1) C2 (1)
XT 455 kHz
2.0 MHz
4.0 MHz
TBD
TBD
TBD
TBD
TBD
TBD
HS 8.0 MHz
16.0 MHz
TBD
TBD
TBD
TBD
Resonators used:
Frequency Manufacturer Tolerance
455 kHz Panasonic EFO-A455K04B ±0.3%
2.0 MHz Murata Erie CSA2.00MG ±0.5%
4.0 MHz Murata Erie CSA4.00MG ±0.5%
8.0 MHz Murata Erie CSA8.00MT ±0.5%
16.0 MHz Murata Erie CSA16.00MX ±0.5%
Note 1: Recommended values of C1 and C2 are identical to the ranges tested above.
Higher capacitance increases the stability of the oscillator but also increases the
start-up time. These values are for design guidance only. Since each resonator has
its own characteristics, the user should consult the resonator manufacturer for appropriate
values of external components or verify oscillator performance.
2: All resonators tested required external capacitors.
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39502A-page 2-9
Section 2. Oscillator
Oscillator
2
Table 2-3: Example Capacitor Selection for Crystal Oscillator
Mode Frequency C1 (1) C2 (1)
LP 32 kHz
200 kHz
TBD
TBD
TBD
TBD
XT 200 kHz
1 MHz
4 MHz
TBD
TBD
TBD
TBD
TBD
TBD
HS 4.0 MHz
8 MHz
20 MHz
25 MHz
TBD
TBD
TBD
TBD
TBD
TBD
TBD
TBD
Crystals used:
Frequency Manufacturer Tolerance
32.0 kHz Epson C-001R32.768K-A ± 20 PPM
200 kHz STD XTL 200.000 kHz ± 20 PPM
1.0 MHz ECS ECS-10-13-1 ± 50 PPM
4.0 MHz ECS ECS-40-20-1 ± 50 PPM
8.0 MHz EPSON CA-301 8.000 M-C ± 30 PPM
20.0 MHz EPSON CA-301 20.000 M-C ± 30 PPM
Note 1: Higher capacitance increases the stability of the oscillator, but also increases the
start-up time. These values are for design guidance only. A series resistor, Rs, may
be required in HS mode, as well as XT mode, to avoid overdriving crystals with low
drive level specification. Since each crystal has its own characteristics, the user
should consult the crystal manufacturer for appropriate values of external components
or verify oscillator performance.
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39502A-page 2-10 2000 Microchip Technology Inc.
2.4.3 Tuning the Oscillator Circuit
Since Microchip devices have wide operating ranges (frequency, voltage, and temperature;
depending on the part and version ordered) and external components (crystals, capacitors,...) of
varying quality and manufacture, validation of operation needs to be performed to ensure that
the component selection will comply with the requirements of the application.
There are many factors that go into the selection and arrangement of these external components.
These factors include:
• amplifier gain
• desired frequency
• resonant frequency(s) of the crystal
• temperature of operation
• supply voltage range
• start-up time
• stability
• crystal life
• power consumption
• simplification of the circuit
• use of standard components
• combination which results in fewest components
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39502A-page 2-11
Section 2. Oscillator
Oscillator
2
2.4.3.1 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 parameters
may be important to your design, such as temperature or frequency tolerance. Application
Note AN588 is an excellent reference if you would like to know more about crystal operation and
their ordering information.
The PICmicro’s 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 20 pF to 32 pF
range. The crystal will oscillate closest to the desired frequency with capacitance in this range. It
may be necessary to sometimes alter these values a bit, as described later, in order to achieve
other benefits.
Clock mode is primarily chosen by using the FOSC parameter specification (parameter 1A) in the
device data sheet, based on frequency. Clock modes (except RC and EC) are simply gain selections;
lower gain for lower frequencies, higher gain for higher frequencies. It is possible to select
a higher or lower gain, if desired, based on the specific needs of the oscillator circuit.
C1 and C2 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 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 great 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 (see also 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 tricky business, 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 20 pF and scope probe was 10 pF, a 30 pF capacitor may actually be
called for). The output signal should not be clipping or squashed. Overdriving the crystal can also
lead to the circuit jumping to a higher harmonic level or even crystal damage.
39500 18C Reference Manual.book Page 11 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39502A-page 2-12 2000 Microchip Technology Inc.
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 squashing near VDD and VSS at the top
and bottom, increasing load capacitors will risk too much current through the crystal or push the
value too far from the manufacturer’s load specification. Add a trimpot between the output pin
and C2, and adjust it until the sine wave is clean. Keeping it fairly close to maximum amplitude
at the low temperature and high VDD combination will assure this is the maximum amplitude the
crystal will see and 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 20k ohms, 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 crystal, try increasing C2 to compensate. Try to get
a combination where Rs is around 10k or less and load capacitance is not too far from the 20 pF
or 32 pF manufacturer specification.
2.4.3.1.1 Start-up
The most difficult time for the oscillator to start-up is when waking up from sleep. This is because
the load capacitors have both partially charged to some quiescent value, and phase differential
at wake-up is minimal. Thus, more time is required to achieve stable oscillation. Remember also
that low voltage, high temperatures and the lower frequency clock modes also impose limitations
on loop gain, which in turn affects start-up. Each of the following factors makes the start-up time
worse:
• a low frequency design (with its low gain clock mode)
• a quiet environment (such as a battery operated device)
• operating in a shielded box (away from the noisy RF area)
• low voltage
• high temperature
• waking up from sleep.
Noise actually helps a design for oscillator start-up, since it helps “kick start” the oscillator.
39500 18C Reference Manual.book Page 12 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39502A-page 2-13
Section 2. Oscillator
Oscillator
2
2.4.4 External Clock Input
Two of the oscillator modes use an external clock. These modes are EC and ECIO oscillator
modes.
In the EC mode (Figure2-5), the OSC1 pin can be driven by CMOS drivers. In this mode, the
OSC1/CLKI pin is hi-impedance and the OSC2/CLKO pin is the CLKO output (FOSC/4). The output
is at a frequency of the selected oscillator divided by 4. This output clock is useful for testing
or synchronization purposes. If the power-up timer is disabled, then there is no time-out after a
POR, or else there will be a power-up timer. There is always a power-up time after a brown-out
reset.
The feedback device between OSC1 and OSC2 is turned off to save current. There is no oscillator
start-up time required after wake-up from sleep mode. If the power-up timer is disabled,
then there is no time-out after a POR, or else (power-up timer enabled) there will be a power-up
timer delay after POR. There is always a power-up timer after a brown-out reset.
Figure 2-5: External Clock Input Operation (EC Oscillator Configuration)
In the ECIO mode (Figure2-6), the OSC1 pin can be driven by CMOS drivers. In this mode, the
OSC1/CLKI pin is hi-impedance and the OSC2/CLKO is now multiplexed with a general purpose
I/O pin.
The feedback device between OSC1 and OSC2 is turned off to save current. There is no oscillator
start-up time required after wake-up from sleep mode. If the power-up timer is disabled,
then there is no time-out after a POR, or else (power-up timer enabled) there will be a power-up
timer delay after POR. There is always a power-up timer after a brown-out reset.
Figure 2-6: External Clock Input Operation (ECIO Oscillator Configuration)
OSC1
FOSC/4 OSC2
Clock from
ext. system PIC18CXXX
CLKI
IO pin I/O (CLKO)
Clock from
ext. system PIC18CXXX
39500 18C Reference Manual.book Page 13 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39502A-page 2-14 2000 Microchip Technology Inc.
2.4.5 External Crystal Oscillator Circuit for Device Clock
Sometimes more than one device needs to be clocked from a single crystal. Since Microchip
does not recommend connecting other logic to the PICmicro’s internal oscillator circuit, an external
crystal oscillator circuit is recommended. Each device will then have an external clock source,
and the number of devices that can be driven will depend on the buffer drive capability. This circuit
is also useful when more than one device needs to operate synchronously to each other.
Either a prepackaged oscillator can be used or a simple oscillator circuit with TTL gates can be
built. Prepackaged oscillators provide a wide operating range and better stability. A
well-designed crystal oscillator will provide good performance with TTL gates. Two types of crystal
oscillator circuits can be used; one with series resonance or one with parallel resonance.
Figure2-7 shows implementation of an external parallel resonant oscillator circuit. The circuit is
designed to use the fundamental frequency of the crystal. The 74AS04 inverter performs the
180-degree phase shift that a parallel oscillator requires. The 4.7 kΩ resistor affects the circuit in
three ways:
1. Provides negative feedback.
2. Biases the 74AS04 (#1) into the linear region.
3. Bounds the gain of the amplifier.
The 10 kΩ potentiometer is used to prevent overdriving of the crystal. It dissipates the power of
the amplifier and allows the requirements of the crystal to be met.
Figure 2-7: External Parallel Resonant Crystal Oscillator Circuit
Figure2-8 shows an external series resonant oscillator circuit. This circuit is also designed to use
the fundamental frequency of the crystal. The inverter performs a 180-degree phase shift in a
series resonant oscillator circuit. The 330 kΩ resistors provide the negative feedback to bias the
inverters in their linear region.
Figure 2-8: External Series Resonant Crystal Oscillator Circuit
When the device is clocked from an external clock source (as in Figure2-7 or Figure2-8) then the
microcontroller’s oscillator should be configured for EC or ECIO mode (Figure2-3).
20 pF
+5V
20 pF
10kΩ
4.7 kΩ
10 kΩ
74AS04
XTAL
10 kΩ
74AS04
CLKI
To Other
Devices
PIC18CXXX
(#1)
(#2)
330 kΩ
74AS04 74AS04 PIC18CXXX
CLKI
To Other
Devices
XTAL
330 kΩ
74AS04
0.1 µF
39500 18C Reference Manual.book Page 14 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39502A-page 2-15
Section 2. Oscillator
Oscillator
2
2.5 External RC Oscillator
For timing insensitive applications, the RC and RCIO device options offer additional cost savings.
The RC oscillator frequency is a function of the:
• Supply voltage
• External resistor (REXT) values
• External capacitor (CEXT) values
• Operating temperature
In addition to this, the oscillator frequency will vary from unit to unit due to normal process parameter
variation. Furthermore, the difference in lead frame capacitance between package types will
also affect the oscillation frequency, especially for low CEXT values. The user also needs to take
into account variation due to tolerance of external REXT and CEXT components used. Figure2-9
shows how the RC combination is connected. For REXT values below 2.2 kΩ, oscillator operation
may become unstable, or stop completely. For very high REXT values (e.g. 1 MΩ), the oscillator
becomes sensitive to noise, humidity and leakage. Thus, we recommend keeping REXT between
3 kΩ and 100 kΩ.
Figure 2-9: RC Oscillator Mode
Although the oscillator will operate with no external capacitor (CEXT = 0 pF), we recommend
using values above 20 pF 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.
See characterization data for RC frequency variation from part to part due to normal process variation.
The variation is larger for larger resistance (since leakage current variation will affect RC
frequency more for large R) and for smaller capacitance (since variation of input capacitance will
affect RC frequency more).
See characterization data for the variation of oscillator frequency due to VDD for given REXT/CEXT
values, as well as frequency variation due to operating temperature for given REXT, CEXT and
VDD values.
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 (see Figure 4-3: "Clock/Instruction Cycle" in the
“Architecture” section, for waveform).
OSC2/CLKO
CEXT
VDD
REXT
VSS
PIC18CXXX
OSC1
FOSC/4 (1)
Internal
Clock FOSC
Note 1: This output may also be configured as a general purpose I/O pin.
39500 18C Reference Manual.book Page 15 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39502A-page 2-16 2000 Microchip Technology Inc.
2.5.1 RC Oscillator with I/O Enabled
The RCIO oscillator mode functions in the exact same manner as the RC oscillator mode. The
only difference is that OSC2 pin does not output oscillator frequency divided by 4, but in this
mode is configured as an I/O pin.
As in the RC mode, the user needs to take into account any variation of the clock frequency due
to tolerance of external REXT and CEXT components used, process variation, voltage, and temperature.
Figure2-10 shows how the RC with the I/O pin combination is connected.
Figure 2-10: RCIO Oscillator Mode
I/O (OSC2)
CEXT
REXT
VSS PIC18CXXX
OSC1 Internal
Clock
VDD
39500 18C Reference Manual.book Page 16 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39502A-page 2-17
Section 2. Oscillator
Oscillator
2
2.5.2 RC Start-up
As the device voltage increases, the RC will start its oscillations immediately after the pin voltage
levels meet the input threshold specifications (parameters D032 and D042 in the “Electrical
Specifications” section). The time required for the RC to start oscillating depends on many factors.
These include:
• Resistor value used
• Capacitor value used
• Device VDD rise time
• System temperature
There is no oscillator start-up time (TOST) regardless of the source of reset or when sleep is terminated.
If the power-up timer is disabled, then there is no time-out after a POR, or else
(power-up timer enabled) there will be a power-up timer delay after POR. There is always a
power-up time after a brown-out reset.
39500 18C Reference Manual.book Page 17 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39502A-page 2-18 2000 Microchip Technology Inc.
2.6 HS4 (HS oscillator with 4xPLL enabled)
A Phase Locked Loop (PLL) circuit is provided as a programmable option for users that want to
multiply the frequency of the incoming crystal oscillator signal by 4. For an input clock frequency
of 10 MHz, the internal clock frequency will be multiplied to 40 MHz. This is useful for customers
who are concerned with EMI due to high frequency crystals.
The PLL can only be enabled when the oscillator configuration bits are programmed for HS4
mode (FOSC2:FOSC0 = ‘110’). If they are programmed for any other mode, the PLL is not
enabled and the system clock will come directly from OSC1. The oscillator mode is specified
during device programming.
The PLL is divided into four basic parts (see Figure2-11):
• Phase comparator
• Loop filter
• VCO (Voltage Controlled Oscillator)
• Feedback divider
When in HS4 mode, the incoming clock is sampled by the phase comparator and is compared
to PLL output clock divided by four. If the two are not in phase, the phase comparator drives an
input to the loop filter to "pump" the voltage to the VCO, either up or down, depending upon
whether the input clock was leading or lagging the output clock. This process continues until the
incoming clock on OSC1 and the divide by 4 output clock of the VCO are in phase. The output
clock is now "locked" in phase with the incoming clock, and its frequency is four times greater.
A PLL lock timer is used to ensure that the PLL has locked before device execution starts. The
PLL lock timer has a time-out that is called TPLL. This delay is shown in Figure2-14.
Figure 2-11: PLL Block Diagram
MUX
VCO
Loop
Filter
Divide by 4
Crystal
Oscillator
OSC2
OSC1
SYSCLK
Phase
Comparator
CVCO
Circuitry
FOSC2:FOSC0 = ‘110’
PIC18CXXX
39500 18C Reference Manual.book Page 18 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39502A-page 2-19
Section 2. Oscillator
Oscillator
2
2.7 Switching to Low Power Clock Source
This feature allows the clock source to switch from the default clock source that is selected by
the FOSC2:FOSC0 bits to the Timer1 oscillator clock source. The availability of this feature is
device dependent.
2.7.1 Switching Oscillator Mode Option
This feature is enabled by clearing the Oscillator System Clock Switch Enable (OSCSEN) configuration
bit. This provides the ability to switch to a low power execution mode if the alternate
clock source (such as Timer1) is configured in oscillator mode with a low frequency (32 kHz, for
example) crystal.
The enabling of the low power clock source is determined by the state of the SCS control bit in
the Oscillator control register (OSCCON). (Register 2-1)
2.7.1.2 System Clock Switch Bit
The system clock switch bit, SCS (OSCCON) controls the switching of the oscillator source. It
can be configured for either the Timer1 Oscillator clock source, or the default clock source
(selected by the Fosc2:Fosc0 bits). When the SCS bit is set, it enables the Timer1 Oscillator
clock source as the system clock. When the SCS bit is cleared, the system clock comes from
the clock source specified by the Fosc2:Fosc0 bits. The SCS bit is cleared on all forms of reset.
Note: The Timer1 oscillator must be enabled in order to switch the system clock source.
The Timer1 oscillator is enabled by setting the T1OSCEN bit in the Timer1 Control
Register (T1CON). If the Timer1 oscillator is not enabled, then any write to the SCS
bit will be ignored, and the SCS bit will remain in the default state with the clock
source coming from OSC1 or the PLL output.
39500 18C Reference Manual.book Page 19 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39502A-page 2-20 2000 Microchip Technology Inc.
2.7.2 Oscillator Transitions
Switching from the default clock to the Timer1 Oscillator clock source is controlled as shown in
the flow diagram (Figure2-16). This ensures a clean transition when switching oscillator clocks.
Circuitry is used to prevent "glitches" due to transitions when switching from the default clock
source to the low power clock source and vice versa. Essentially, the circuitry waits for eight rising
edges of the clock input to which the processor is switching. This ensures that the clock output
pulse width will not be less than the shortest pulse width of the two clock sources. No additional
delays are required when switching from the default clock source to the low power clock source.
Figure2-12 through Figure2-15 show different transition waveforms when switching between the
oscillators.
Figure 2-12: Transition From OSC1 to Timer1 Oscillator Waveform
Figure 2-13: Transition Between Timer1 and OSC1 Waveform (HS, XT, LP)
Q2 Q3 Q4 Q1 Q2 Q3
OSC1
Internal
SCS
Program PC PC + 2
Note 1: Delay on internal system clock is eight oscillator cycles for synchronization.
2: The T1OSCEN bit is set.
3: The OSCSEN configuration bit is cleared.
Q1
T1OSI (2)
Q4 Q1
PC + 4
Q1
Tscs
Clock
Counter
System
Q2 Q3 Q4 Q1
TDLY
TT1P
TOSC
1 34 5678 2
(OSCCON)
Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3
OSC1
Internal
SCS
(OSCCON)
Program PC PC + 2
Note 1: TOST = 1024TOSC (drawing not to scale).
T1OSI
OSC2
TOST
Q1
PC + 6
TT1P
TOSC
TSCS
1 2 34 567 8
System Clock
Counter
39500 18C Reference Manual.book Page 20 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39502A-page 2-21
Section 2. Oscillator
Oscillator
2
Figure 2-14: Transition Between Timer1 and OSC1 Waveform (HS4)
Figure 2-15: Transition Between Timer1 and OSC1 Waveform (RC, EC, ECIO)
Additional delays may occur before switching from the low power clock source back to the main
oscillator. The sequence of events that take place will depend upon the main oscillator setting in
the configuration register (the mode of the main oscillator).
If the main oscillator is configured as a RC oscillator (RC, RCIO) or External Clock (EC, ECIO),
then there is no oscillator start-up time. The transition from a low power clock to the main oscillator
occurs after 8 clock cycles are counted on OSC1.
If the main oscillator is configured as a crystal (HS4, HS, XT or LP), then the transition will take
place after an oscillator start-up time (TOST).
If the main oscillator is configured as a crystal with PLL (HS4) enabled, then the transition will
take place after an oscillator start-up time (TOST) plus an additional PLL time-out, TPLL (see
“Electrical Specifications” section, parameter 32). This is necessary because the crystal oscillator
had been powered down until the time of the transition. In order to provide the system with
a reliable clock when the change-over has occurred, the clock will not be released to the
change-over circuit until the oscillator start-up time has expired. The additional TPLL time is
required after oscillator start-up to allow the phase lock loop ample time to lock to the incoming
oscillator frequency from OSC1.
Q4 Q1 Q1 Q2 Q3 Q4 Q1 Q2
OSC1
SCS
(OSCCON)
Program PC PC + 2
Note 1: TOST = 1024TOSC (drawing not to scale).
T1OSI
TOST
Q3
PC + 4
TPLL
TOSC
TT1P
TSCS
Q4
OSC2
PLL Clock
Input 1 234 5678
Internal
System Clock
Counter
Q3 Q4 Q1 Q1 Q2 Q3 Q4 Q1 Q2 Q3
OSC1
SCS
(OSCCON)
PC PC + 2
Note 1: RC oscillator mode assumed.
PC + 4
T1OSI
OSC2
Q4 TT1P
TOSC
TSCS
1 2 3 4 5 6 7 8
Program
Counter
Internal
System Clock
39500 18C Reference Manual.book Page 21 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39502A-page 2-22 2000 Microchip Technology Inc.
A flow diagram for switching between a low power clock and the default oscillator clock is shown
in Figure2-16.
Figure 2-16: Switching Oscillator Flow Diagram
Start
SCS = 0?
Has SCS
Begin switch to
low power clock
N = 0,
hold CPU clock
Transition
on Newclk?
N=N+1
N = 8?
Sysclk = Newclk,
Release Q clocks
Begin switch to
high speed clock
FOSC2:FOSC0 =
XT, LP,
Start OST,
wait 1024
oscillations
on OSC1
Newclk =
XT, HS, LP
FOSC2:FOSC0 =
HS4
Newclk =
HS4
Newclk =
T1OSC input
Newclk = EC or RC
Start OST,
wait 1024
oscillations
on OSC1
Yes
Yes Yes
Yes
Yes
No
No No
No
No
T1OSCEN = 1?
Yes
No No switch to low
power clock.
Set SCS = 0
End
End
changed state?
Wait TPLL for
PLL to lock
in Q1 state
OSCSEN = 0?
No
Yes
End
No switch to low
power clock
or HS?
39500 18C Reference Manual.book Page 22 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39502A-page 2-23
Section 2. Oscillator
Oscillator
2
2.8 Effects of Sleep Mode on the On-Chip Oscillator
When the device executes a SLEEP instruction, the on-chip clocks and oscillator are turned off
and the device is held at the beginning of an instruction cycle (Q1 state). With the oscillator off,
the OSC1 and OSC2 signals will stop oscillating. Since all the transistor switching currents have
been removed, SLEEP mode achieves the lowest current consumption of the device (only leakage
currents). Enabling any on-chip feature that will operate during SLEEP will increase the current
consumed. The user can wake from SLEEP through external reset, Watchdog Timer Reset
or through an interrupt.
See Table 3-1 in the “Reset” section for time-outs due to SLEEP and MCLR reset.
Table 2-4: OSC1 and OSC2 Pin States in Sleep Mode
2.9 Effects of Device Reset on the On-Chip Oscillator
Device resets have no effect on the on-chip crystal oscillator circuitry. The oscillator will continue
to operate as it does under normal execution. While in RESET, the device logic is held at the
Q1 state so that when the device exits RESET, it is at the beginning of an instruction cycle. The
OSC2 pin, when used as the external clockout (RC, EC mode), will be held low during RESET,
and as soon as the MCLR pin is at VIH (input high voltage), the RC will start to oscillate.
See Table 3-1 in the “Reset” section for time-outs due to SLEEP and MCLR reset.
2.9.1 Power-up Delays
Power-up delays are controlled by two timers, so that no external reset circuitry is required for
most applications. The delays ensure that the device is kept in RESET until the device power
supply and clock are stable. For additional information on RESET operation, see the “Reset”
section.
The Power-up Timer (PWRT) provides a fixed 72 ms delay on power-up due to POR or BOR,
and keeps the part in RESET until the device power supply is stable. When a crystal is used (LP,
XT, HS), the Oscillator Start-Up Timer (OST) keeps the chip in RESET until the PWRT timer
delay has expired, allowing the crystal oscillator to stabilize on power up. The PWRTEN bit must
be cleared for this time-out to occur.
When the PLL is enabled (HS4 oscillator mode), the Power-up Timer (PWRT) is used to keep
the device in RESET for an extra nominal delay (TPLL) above crystal mode. This delay ensures
that the PLL is locked to the crystal frequency.
For additional information on RESET operation, see the “Reset” section.
OSC Mode OSC1 Pin OSC2 Pin
RC Floating, external resistor should
pull high
At logic low
RCIO Floating, external resistor should
pull high Configured as I/O pin
ECIO Floating Configured as I/O pin
EC Floating At logic low
LP, XT and HS Feedback inverter disabled at
quiescent voltage level
Feedback inverter disabled at
quiescent voltage level
HS4 Feedback inverter disabled at
quiescent voltage level
Feedback inverter disabled at
quiescent voltage level
39500 18C Reference Manual.book Page 23 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39502A-page 2-24 2000 Microchip Technology Inc.
2.10 Design Tips
Question 1: When looking at the OSC2 pin after power-up with an oscilloscope, there is
no clock. What can cause this?
Answer 1:
1. Executing a SLEEP instruction 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 RCIO. Most parts come with the clock selected in the default RC 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 PICmicro device starts, but runs at a frequency much higher than the
resonant frequency of the crystal.
Answer 2:
The gain is too high for this oscillator circuit. Refer to subsection 2.4 “Crystal Oscillators/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 3:
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 4:
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 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 5:
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.
39500 18C Reference Manual.book Page 24 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39502A-page 2-25
Section 2. Oscillator
Oscillator
2
2.11 Related Application Notes
This section lists application notes that are related to this section of the manual. These application
notes may not be written specifically for the Enhanced MCU family (that is they may be written
for the Base-Line, Mid-Range, or High-End families), but the concepts are pertinent, and
could be used (with modification and possible limitations). The current application notes related
to the oscillator are:
Title Application Note #
PICmicro Microcontrollers Oscillator Design Guide AN588
Low Power Design using PICmicro Microcontrollers AN606
Note: Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
http://www.microchip.com/10/faqs/codeex/
39500 18C Reference Manual.book Page 25 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39502A-page 2-26 2000 Microchip Technology Inc.
2.12 Revision History
Revision A
This is the initial released revision of the Enhanced MCU oscillators description.
39500 18C Reference Manual.book Page 26 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39503A-page 3-1
Reset
3
Section 3. Reset
HIGHLIGHTS
This section of the manual contains the following major topics:
3.1 Introduction .................................................................................................................... 3-2
3.2 Resets and Delay Timers............................................................................................... 3-4
3.3 Registers and Status Bit Values................................................................................... 3-14
3.4 Design Tips.................................................................................................................. 3-20
3.5 Related Application Notes............................................................................................ 3-21
3.6 Revision History........................................................................................................... 3-22
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39503A-page 3-2 2000 Microchip Technology Inc.
3.1 Introduction
The reset logic is used to place the device into a known state. The source of the reset can be
determined by reading the device status bits. The reset logic is designed with features that
reduce system cost and increase system reliability.
Devices differentiate between various kinds of reset:
a) Power-on Reset (POR)
b) MCLR Reset during normal operation
c) MCLR Reset during SLEEP
d) WDT Reset (normal operation)
e) Programmable Brown-out Reset (BOR)
f) RESET Instruction
g) Stack Overflow Reset
h) Stack Underflow Reset
Most registers are unaffected by a reset; their status is unknown on POR and unchanged by all
other resets. The other registers are forced to a “reset state” on Power-on Reset, MCLR, WDT
Reset, Brown-out Reset, MCLR Reset during SLEEP and by the RESET instruction.
Most registers are not affected by a WDT wake-up, since this is viewed as the resumption of normal
operation. Status bits from the RCON register, RI, TO, PD, POR and BOR are set or cleared
differently in different reset situations as indicated in Table 3-3. These bits are used in software
to determine the nature of the reset. See Table 3-4 for a full description of the reset states of all
registers.
A simplified block diagram of the on-chip reset circuit is shown in Figure 3-1. This block diagram
is a superset of reset features. To determine the features that are available on a specific device,
please refer to the device’s Data Sheet.
Note: While the Enhanced MCU is in a reset state, the internal phase clock is held at Q1
(beginning of an instruction cycle).
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39503A-page 3-3
Section 3. Reset
Reset
3
Figure 3-1: Simplified Block Diagram of On-chip Reset Circuit
S
R Q
External Reset
MCLR
VDD
OSC1
WDT
Module
OST/PWRT
On-chip (1)
RC OSC
WDT
Time-out
Power-on Reset
OST
10-bit Ripple counter
PWRT
Chip_Reset
10-bit Ripple counter
Reset
Enable OSTT (2)
Enable PWRT
SLEEP
Note 1: This is a separate oscillator from the RC oscillator of the CLKIN pin.
2: See Table 3-1 for time-out situations.
Brown-out
Reset BOREN
RESET
Instruction
Stack
Pointer Stack Overflow/Underflow Reset
VDD rise
detect
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39503A-page 3-4 2000 Microchip Technology Inc.
3.2 Resets and Delay Timers
The device has many sources for a device reset. Depending on the source of the reset, different
delays may be initiated. These reset sources and the delays are discussed in the following subsections.
3.2.1 Power-on Reset (POR)
A Power-on Reset pulse is generated on-chip when VDD rise is detected. To take advantage of
the POR, just tie the MCLR pin directly (or through a resistor) to VDD as shown in Figure 3-2. This
will eliminate external RC components usually needed to create a Power-on Reset delay. A minimum
rise time for VDD is required. See parameter D003 and parameter D004 in the “Electrical
Specifications” section for details.
Figure 3-2: Using On-Chip POR
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. Ensure the delay is long enough to get all operating parameters
within specification.
Figure 3-3 shows a possible POR circuit for a slow power supply ramp up. The external Power-on
Reset circuit is only required if the device would exit reset before the device VDD is in the valid
operating range. The diode, D, helps discharge the capacitor quickly when VDD powers down.
Figure 3-3: External Power-on Reset Circuit (For Slow VDD Power-up)
VDD
MCLR
PIC18CXXX
VDD
R (1)
Note 1: The resistor is optional.
VDD VDD
Note 1: R < 40 kΩ is recommended to ensure that the voltage drop across R does not violate
the device’s electrical specification.
2: R1 = 100Ω to 1 kΩ 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 (EOS).
C
R1
D R
MCLR
PIC18CXXX
2000 Microchip Technology Inc. DS39503A-page 3-5
Section 3. Reset
Reset
3
3.2.2 Power-up Timer (PWRT)
The Power-up Timer provides a delay on Power-on Reset (POR) or Brown-out Reset (BOR).
See parameter D033 in the ““Electrical Specifications” section. The Power-up Timer operates
on a dedicated internal RC oscillator. The device is kept in reset as long as the PWRT is active.
The PWRT delay allows VDD to rise to an acceptable level. A configuration bit (PWRTEN) is provided
to enable/disable the Power-up Timer.
The power-up time delay will vary from device to device due to VDD, temperature and process
variations. See DC parameters for details.
3.2.3 Oscillator Start-up Timer (OST)
The Oscillator Start-Up Timer (OST) provides a 1024 oscillator cycle delay (from OSC1 input)
(parameter 32) after the PWRT delay is over. This ensures that the crystal oscillator or resonator
has started and is stable.
The OST time-out is invoked only for XT, LP and HS modes, on Power-on Reset, Brown-out
Reset, wake-up from SLEEP, or on a transition from Timer1 input clock as the system clock to
the oscillator as the system clock by clearing the SCS bit. The oscillator start-up timer is disabled
for all resets and wake-ups in RC and EC modes. (See Table 3-1)
The OST counts the oscillator pulses on the OSC1/CLKIN pin. The counter only starts incrementing
after the amplitude of the signal reaches the oscillator input thresholds. This delay allows the
crystal oscillator or resonator to stabilize before the device exits the OST delay. The length of the
time-out is a function of the crystal/resonator frequency.
Figure 3-4 shows the operation of the OST circuit in conjunction with the power-up timer. For low
frequency crystals, this start-up time can become quite long. That is because the time it takes
the low frequency oscillator to start oscillating is longer than the power-up timer’s delay. The time
from when the power-up timer times out to when the oscillator starts to oscillate is a dead time.
There is no minimum or maximum time for this dead time (TDEADTIME), and is dependent on the
time for the oscillator circuitry to have “good” oscillations.
Figure 3-4: Oscillator Start-up Time
3.2.3.1 PLL Lock Time-out
When the PLL is enabled, the time-out sequence following a Power-on Reset is different from
other oscillator modes. A portion of the Power-up Timer is used to provide a fixed time-out that
is sufficient for the PLL to lock to the main oscillator frequency. This PLL lock time-out TPLL (2ms
nominal, Parameter 7 in the “Electrical Specifications” section) follows the Oscillator Start-up
Time-out (OST).
Note: Some devices require the Power-up Timer to be enabled when the Brown-out Reset
circuitry is enabled. Please refer to the device data sheet for requirements.
VDD
MCLR
Oscillator
OST TIME_OUT
PWRT TIME_OUT
INTERNAL RESET
TOSC1
TOST
TPWRT
POR or BOR Trip Point
TOSC1 = Time for the crystal oscillator to react to an oscillation level detectable by the
Oscillator Start-up Timer (OST).
TOST = 1024TOSC.
TDEADTIME
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39503A-page 3-6 2000 Microchip Technology Inc.
3.2.4 Power-up Sequence
On power-up, the time-out sequence is as follows: First the internal POR is detected, then, if
enabled, the PWRT time-out is invoked. After the PWRT time-out is over, the OST is activated.
The total time-out will vary based on oscillator configuration and PWRTEN bit status. For example,
in RC mode with the PWRTEN bit set (PWRT disabled), there will be no time-out at all.
Figure 3-5, Figure 3-6 and Figure 3-7 depict time-out sequences.
Since the time-outs occur from the internal POR pulse, if MCLR is kept low long enough, the
time-outs will expire. Bringing MCLR high will begin execution immediately (Figure 3-7). This is
useful for testing purposes or to synchronize more than one device operating in parallel.
If the device voltage is not within the electrical specifications by the end of a time-out, the
MCLR/VPP pin must be held low until the voltage is within the device specification. The use of an
external RC delay is sufficient for many of these applications.
On wake-up from sleep, the OST is activated for various oscillator configurations. When the PLL
is activated in HS mode, an additional delay called TPLL (2 ms nominal) is added to the OST
time-out to allow the necessary lock time for the PLL. See parameter D003 in the “Electrical
Specifications” section for details.
Table 3-1 shows the time-outs that occur in various situations, while Figure 3-5 through
Figure 3-8 show four different cases that can happen on powering up the device.
Table 3-1: Time-out in Various Situations
Figure 3-5: Time-out Sequence on Power-up (MCLR Tied to VDD)
Oscillator
Configuration
Power-up (2) or Brown-Out (3) Wake-up from
SLEEP or
PWRTEN Oscillator Switch = 0 PWRTEN = 1
HS with PLL enabled (1) 72 ms + 1024Tosc + 2ms 1024Tosc + 2 ms 1024Tosc + 2 ms
HS, XT, LP 72 ms + 1024Tosc 1024Tosc 1024Tosc
EC 72 ms — —
External RC 72 ms — —
Note 1: 2 ms = Nominal time required for the PLL to lock. See the “Electrical Specifications” section.
2: 72 ms is the nominal power-up timer delay. See the “Electrical Specifications” section.
3: It is recommended that the power-up timer is enabled when using the Brown-out Reset module.
TPWRT (1)
TOST
VDD
MCLR
INTERNAL POR
PWRT TIME-OUT
OST TIME-OUT
INTERNAL RESET
Note 1: TPWRT only occurs when PWRTEN = ‘1’.
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39503A-page 3-7
Section 3. Reset
Reset
3
Figure 3-6: Time-out Sequence on Power-up (MCLR not Tied to VDD): Case 1
Figure 3-7: Time-out Sequence on Power-up (MCLR not Tied to VDD): Case 2
Figure 3-8: Time-out Sequence on Power-up with Slow Rise Time (MCLR Tied to VDD)
TPWRT (1)
TOST
VDD
MCLR
INTERNAL POR
PWRT TIME-OUT
OST TIME-OUT
INTERNAL RESET
Note 1: TPWRT only occurs when PWRTEN = ‘1’.
VDD
MCLR
INTERNAL POR
PWRT TIME-OUT
OST TIME-OUT
INTERNAL RESET
TOST
Note 1: TPWRT only occurs when PWRTEN = ‘1’.
TPWRT (1)
VDD
MCLR
INTERNAL POR
PWRT TIME-OUT
OST TIME-OUT
INTERNAL RESET
0V
5V
TOST
TDEADTIME
Note 1: TPWRT only occurs when PWRTEN = ‘1’.
TPWRT (1)
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39503A-page 3-8 2000 Microchip Technology Inc.
Figure 3-9: Time-out Sequence on POR w/ PLL Enabled (MCLR Tied to VDD)
TOST
VDD
MCLR
IINTERNAL POR
PWRT TIME-OUT
OST TIME-OUT
INTERNAL RESET
PLL TIME-OUT
TPLL
TOST = 1024 clock cycles.
TPLL = PLL lock time.
TPWRT (1)
Note 1: TPWRT only occurs when PWRTEN = ‘1’.
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39503A-page 3-9
Section 3. Reset
Reset
3
3.2.5 Brown-Out Reset (BOR)
On-chip Brown-out Reset circuitry places the device into reset when the device voltage (VDD)
falls below a trip point (VBOR). This ensures that the device does not continue program execution
outside the valid voltage operation range of the device. Brown-out resets are typically used in AC
line applications (such as appliances) or large battery applications where large loads may be
switched in (such as automotive).
Appliances encounter brown-out situations during plug-in and online voltage dip. Automotive
electronics encounter brown-out when the ignition key is turned. In these application scenarios,
the device voltage temporarily falls below the specified operating minimum.
If the brown-out circuit meets the current consumption requirements of the system, it may also
be used as a voltage supervisory function.
Figure 3-10 shows typical brown-out situations. The Brown-out Reset module is enabled by
default. To disable the module, the BOREN configuration bit must be cleared at device programming.
Figure 3-10: Brown-Out Situations
Note: Before using the on-chip brown-out for a voltage supervisory function (monitor battery
decay), please review the electrical specifications to ensure that they meet your
requirements.
Note 1: It is recommended that the power-up timer be enabled when using the BOR module.
The power-up timer is enabled by programming the PWRTEN configuration bit
to ‘0’.
Note 2: Some devices require the Power-up Timer to be enabled when the Brown-out Reset
circuitry is enabled. Please refer to the device data sheet for requirements.
Power-up time
VDD
Internal
Reset
VBOR
VDD
Internal
Reset
VBOR
VDD
Internal
Reset
VBOR
Note 1: The Electrical Specification Parameter (parameter 33) has a typical value
of 72 ms.
parameter 33
parameter 33
parameter 33 (1)
(parameter 33)
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39503A-page 3-10 2000 Microchip Technology Inc.
3.2.5.1 BOR Operation
The BOREN configuration bit can disable (if clear/programmed) or enable (if set) the Brown-out
Reset circuitry. If VDD falls below VBOR (parameter D005 in the “Electrical Specifications”
section), for greater than the Brown-out Pulse Width Time (TBOR), parameter 35, the brown-out
situation will reset the chip. A reset is not guaranteed to occur if VDD falls below VBOR for less
than parameter 35.
The chip will remain in Brown-out Reset until VDD rises above VBOR. After which, the Power-up
Timer is invoked and will keep the chip in reset an additional time delay (parameter 33). If VDD
drops below VBOR while the Power-up Timer is running, the chip will go back into Reset and the
Power-up Timer will be re-initialized. Once VDD rises above VBOR, the Power-up Timer will again
start a time delay.
When the BOREN bit is set, all voltages below VBOR will hold the device in the reset state. This
includes during the power-up sequence.
The brown-out trip point is user programmable at time of device programming. Figure 3-11 is a
block diagram for the BOR circuit.
Figure 3-11: Block Diagram of BOR Circuit
BOR
VDD
EN
BOR
3 to 1 MUX
BOREN
LVDEN
VREN
BORV1:BORV0
Configuration Bits
Internally Generated
Reference Voltage
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39503A-page 3-11
Section 3. Reset
Reset
3
The Brown-out Reset circuit has four available reset trip point voltages. The device selected
determines which trip points make sense in an application. All devices have the trip points of
4.2V and 4.5V available. PIC18LCXXX devices add two more trip points. The first is 2.7V, while
the second is dependent on the minimum operating voltage of that device. This means that the
lowest trip point voltage will either be 2.5V or 1.8V. Table 3-2 shows the state of the configuration
bits (BORV1:BORV0) and the BOR trip points that they select.
Table 3-2: Example BOR Trip Point Levels
The BOR is programmable to ensure that the BOR can be optimized to the voltage-frequency of
the device, since the minimum device VDD value will depend on the frequency of operation. For
example, VDD min. at 40 MHz may be 4.2V, whereas at 2 MHz it may be 1.8V.
BORV1:BORV0
Configuration Bits
Minimum Voltage
Trip Point
Maximum Voltage
Trip Point Comment
1 1 1.8 V 1.86 V PIC18LCXXX Devices
(w/ VDDMIN = 1.8V)
1 1 2.5 V 2.58 V PIC18LCXXX Devices
(w/ VDDMIN ≥ 2.0V)
1 0 2.7 V 2.78 V PIC18LCXXX Devices
0 1 4.2 V 4.33 V All Devices
0 0 4.5 V 4.64 V All Devices
Note: The minimum voltage at which the Brown-out Reset trip point can occur should be
in the valid operating voltage range of the device.
39500 18C Reference Manual.book Page 11 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39503A-page 3-12 2000 Microchip Technology Inc.
3.2.5.2 Current Implications for BOR Operation
There are three components to the current consumption of the BOR operation. These are:
1. Current from Internal Reference Voltage
2. Current from BOR comparator
3. Current from resistor ladder
The Internal Reference Voltage is also used by the Low Voltage Detect circuitry and the A/D
voltage references. The resistor ladder is also used by the Low Voltage Detect circuitry. If the
Low Voltage Detect is enabled, then only the additional current of the comparator is added for
enabling the BOR feature.
When the module is enabled, the BOR comparator and voltage divider are enabled and consume
static current. The “Electrical Specifications” section parameter 32 gives the current
specification.
The Brown-out Comparator circuit consumes current when enabled. To eliminate this current
consumption, the Brown-out Reset can be disabled by programming the Brown-out Reset
Enable configuration bit (BOREN) to '0'.
3.2.5.3 BOR Initialization
The BOR module must be enabled and programmed through the device configuration bits.
These include BOREN, which enables or disables the module, and BORV1:BORV0, which set
the BOR voltage.
39500 18C Reference Manual.book Page 12 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39503A-page 3-13
Section 3. Reset
Reset
3
3.2.5.4 External Brown-Out Reset Circuits
There are some applications where the device’s programmable Brown-out Reset trip point levels
may still not be at the desired level for the application.
Figure 3-12 shows a circuit for external brown-out protection using the MCP100 device.
Figure 3-13 and Figure 3-14 are two examples of external circuitry that may be implemented.
Each option needs to be evaluated to determine if they match the requirements of the application.
Figure 3-12: External Brown-Out Protection Using the MCP100
Figure 3-13: External Brown-Out Protection Circuit 1
Figure 3-14: External Brown-Out Protection Circuit 2
VSS
RST
MCP100
VDD
bypass
capacitor
PIC18CXXX
VDD
MCLR
Note 1: Internal Brown-out Reset circuitry should be disabled when using this circuit.
2: Resistors should be adjusted for the characteristics of the transistor.
3: This circuit will activate reset when VDD goes below (Vz + 0.7V)
where Vz = Zener voltage.
VDD
33 kΩ
10 kΩ
40 kΩ
VDD
MCLR
PIC18CXXX
Q1
R2 40 kΩ
VDD
MCLR
PIC18CXXX
R1
Q1
VDD
Note 1: This circuit is less expensive, but less accurate. Transistor Q1 turns off when VDD
is below a certain level such that:
2: Internal Brown-out Reset circuitry should be disabled when using this circuit.
3: Resistors should be adjusted for the characteristics of the transistor.
VDD • R1
R1 + R2
= 0.7V
39500 18C Reference Manual.book Page 13 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39503A-page 3-14 2000 Microchip Technology Inc.
3.3 Registers and Status Bit Values
Table 3-3 shows the significance of the device status bits and the initialization conditions for the
RCON register. Table 3-4 shows the reset conditions for the Special Function Registers.
Register 3-1 shows the bits of the RCON register and Table 3-3 shows the initialization values.
Register 3-1: RCON Register Bits and Positions
Table 3-3: Status Bits, Their Significance, and the Initialization Condition for RCON Register
R/W-0 R/W-0 U-0 R/W-1 R/W-1 R/W-1 R/W-1 R/W-u
IPEN LWRT — RI TO PD POR BOR
bit 7 bit 0
Condition Program
Counter
RCON
Register
RI TO PD POR BOR STKFUL STKUNF
Power-on Reset 0000h 00-1 1100 111 0 u u u
MCLR Reset during normal operation 0000h 00-u uuuu uuu u u u u
Software Reset during normal operation 0000h 0u-0 uuuu 0uu u u u u
Stack Overflow Reset during normal
operation
0000h 0u-u uu11 uuu u u u 1
Stack Underflow Reset during normal
operation
0000h 0u-u uu11 uuu u u 1 u
MCLR Reset during SLEEP 0000h 00-u 10uu u10 u u u u
WDT Reset 0000h 0u-u 01uu 101 u u u u
WDT Wake-up PC + 2 uu-u 00uu u00 u u u u
Brown-out Reset 0000h 0u-1 11u0 111 1 0 u u
Interrupt Wake-up from SLEEP PC + 2 (1) uu-u 00uu u10 u u u u
Legend: u = unchanged, x = unknown, - = unimplemented bit read as '0'.
Note 1: When the wake-up is due to an interrupt and the GIEH or GIEL bits are set, the PC is loaded with the
interrupt vector (0008h or 0018h).
39500 18C Reference Manual.book Page 14 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39503A-page 3-15
Section 3. Reset
Reset
3
Table 3-4: Initialization Conditions for SFR Registers
Register Power-on Reset,
Brown-out Reset
MCLR Resets
WDT Reset
Reset Instruction
Stack Resets
Wake-up via WDT or
Interrupt
TOSU ---0 0000 ---0 0000 ---0 uuuu (3)
TOSH 0000 0000 0000 0000 uuuu uuuu (3)
TOSL 0000 0000 0000 0000 uuuu uuuu (3)
STKPTR 00-0 0000 00-0 0000 uu-u uuuu (3)
PCLATU ---0 0000 ---0 0000 ---u uuuu
PCLATH 0000 0000 0000 0000 uuuu uuuu
PCL 0000 0000 0000 0000 PC + 2 (2)
TBLPTRU --00 0000 --00 0000 --uu uuuu
TBLPTRH 0000 0000 0000 0000 uuuu uuuu
TBLPTRL 0000 0000 0000 0000 uuuu uuuu
TABLAT 0000 0000 0000 0000 uuuu uuuu
PRODH xxxx xxxx uuuu uuuu uuuu uuuu
PRODL xxxx xxxx uuuu uuuu uuuu uuuu
INTCON 0000 000x 0000 000u uuuu uuuu (1)
INTCON2 1111 -1-1 1111 -1-1 uuuu -u-u (1)
INTCON3 11-0 0-00 11-0 0-00 uu-u u-uu (1)
INDF0 N/A N/A N/A
POSTINC0 N/A N/A N/A
POSTDEC0 N/A N/A N/A
PREINC0 N/A N/A N/A
PLUSW0 N/A N/A N/A
FSR0H ---- 0000 ---- 0000 ---- uuuu
FSR0L xxxx xxxx uuuu uuuu uuuu uuuu
WREG xxxx xxxx uuuu uuuu uuuu uuuu
INDF1 N/A N/A N/A
POSTINC1 N/A N/A N/A
POSTDEC1 N/A N/A N/A
PREINC1 N/A N/A N/A
Legend: u = unchanged, x = unknown, - = unimplemented bit, read as '0', q = value depends
on condition.
Note 1: One or more bits in the INTCONx or PIRx registers will be affected (to cause
wake-up).
2: When the wake-up is due to an interrupt and the GIEL or GIEH bit is set, the PC is
loaded with the interrupt vector (0008h or 0018h).
3: When the wake-up is due to an interrupt and the GIEL or GIEH bit is set, the TOSU,
TOSH and TOSL are updated with the current value of the PC. The STKPTR is modified
to point to the next location in the hardware stack.
4: The long write enable is only reset on a POR or MCLR reset.
5: The bits in the PIR, PIE, and IPR registers are device dependent. Their function and
location may change from device to device.
39500 18C Reference Manual.book Page 15 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39503A-page 3-16 2000 Microchip Technology Inc.
PLUSW1 N/A N/A N/A
FSR1H ---- 0000 ---- 0000 ---- uuuu
FSR1L xxxx xxxx uuuu uuuu uuuu uuuu
BSR ---- 0000 ---- 0000 ---- uuuu
INDF2 N/A N/A N/A
POSTINC2 N/A N/A N/A
POSTDEC2 N/A N/A N/A
PREINC2 N/A N/A N/A
PLUSW2 N/A N/A N/A
FSR2H ---- 0000 ---- 0000 ---- uuuu
FSR2L xxxx xxxx uuuu uuuu uuuu uuuu
STATUS ---x xxxx ---u uuuu ---u uuuu
TMR0H xxxx xxxx uuuu uuuu uuuu uuuu
TMR0L xxxx xxxx uuuu uuuu uuuu uuuu
T0CON 1111 1111 1111 1111 uuuu uuuu
OSCCON ---- ---0 ---- ---0 ---- ---u
LVDCON --00 0101 --00 0101 --uu uuuu
WDTCON ---- ---0 ---- ---0 ---- ---u
RCON (4) 00-1 11q0 00-1 qquu uu-u qquu
TMR1H xxxx xxxx uuuu uuuu uuuu uuuu
TMR1L xxxx xxxx uuuu uuuu uuuu uuuu
T1CON 0-00 0000 u-uu uuuu u-uu uuuu
TMR2 xxxx xxxx uuuu uuuu uuuu uuuu
PR2 1111 1111 1111 1111 1111 1111
T2CON -000 0000 -000 0000 -uuu uuuu
SSPBUF xxxx xxxx uuuu uuuu uuuu uuuu
SSPADD 0000 0000 0000 0000 uuuu uuuu
SSPSTAT 0000 0000 0000 0000 uuuu uuuu
SSPCON1 0000 0000 0000 0000 uuuu uuuu
SSPCON2 0000 0000 0000 0000 uuuu uuuu
Table 3-4: Initialization Conditions for SFR Registers (Continued)
Register Power-on Reset,
Brown-out Reset
MCLR Resets
WDT Reset
Reset Instruction
Stack Resets
Wake-up via WDT or
Interrupt
Legend: u = unchanged, x = unknown, - = unimplemented bit, read as '0', q = value depends
on condition.
Note 1: One or more bits in the INTCONx or PIRx registers will be affected (to cause
wake-up).
2: When the wake-up is due to an interrupt and the GIEL or GIEH bit is set, the PC is
loaded with the interrupt vector (0008h or 0018h).
3: When the wake-up is due to an interrupt and the GIEL or GIEH bit is set, the TOSU,
TOSH and TOSL are updated with the current value of the PC. The STKPTR is modified
to point to the next location in the hardware stack.
4: The long write enable is only reset on a POR or MCLR reset.
5: The bits in the PIR, PIE, and IPR registers are device dependent. Their function and
location may change from device to device.
39500 18C Reference Manual.book Page 16 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39503A-page 3-17
Section 3. Reset
Reset
3
ADRESH xxxx xxxx uuuu uuuu uuuu uuuu
ADRESL xxxx xxxx uuuu uuuu uuuu uuuu
ADCON0 0000 0000 0000 0000 uuuu uuuu
ADCON1 --0- 0000 --0- 0000 --u- uuuu
CCPR1H xxxx xxxx uuuu uuuu uuuu uuuu
CCPR1L xxxx xxxx uuuu uuuu uuuu uuuu
CCP1CON --00 0000 --00 0000 --uu uuuu
CCPR2H xxxx xxxx uuuu uuuu uuuu uuuu
CCPR2L xxxx xxxx uuuu uuuu uuuu uuuu
CCP2CON --00 0000 --00 0000 --uu uuuu
TMR3H xxxx xxxx uuuu uuuu uuuu uuuu
TMR3L xxxx xxxx uuuu uuuu uuuu uuuu
T3CON 0000 0000 uuuu uuuu uuuu uuuu
SPBRG xxxx xxxx uuuu uuuu uuuu uuuu
RCREG xxxx xxxx uuuu uuuu uuuu uuuu
TXREG xxxx xxxx uuuu uuuu uuuu uuuu
TXSTA 0000 -01x 0000 -01u uuuu -uuu
RCSTA 0000 000x 0000 000u uuuu uuuu
IPR2 (5) 11 u
PIR2 (5) 0 0 u (1)
PIE2 (5) 00 u
IPR1 (5) 11 u
PIR1 (5) 0 0 u (1)
PIE1 (5) 00 u
Table 3-4: Initialization Conditions for SFR Registers (Continued)
Register Power-on Reset,
Brown-out Reset
MCLR Resets
WDT Reset
Reset Instruction
Stack Resets
Wake-up via WDT or
Interrupt
Legend: u = unchanged, x = unknown, - = unimplemented bit, read as '0', q = value depends
on condition.
Note 1: One or more bits in the INTCONx or PIRx registers will be affected (to cause
wake-up).
2: When the wake-up is due to an interrupt and the GIEL or GIEH bit is set, the PC is
loaded with the interrupt vector (0008h or 0018h).
3: When the wake-up is due to an interrupt and the GIEL or GIEH bit is set, the TOSU,
TOSH and TOSL are updated with the current value of the PC. The STKPTR is modified
to point to the next location in the hardware stack.
4: The long write enable is only reset on a POR or MCLR reset.
5: The bits in the PIR, PIE, and IPR registers are device dependent. Their function and
location may change from device to device.
39500 18C Reference Manual.book Page 17 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39503A-page 3-18 2000 Microchip Technology Inc.
TRISE 0000 -111 0000 -111 uuuu -uuu
TRISD 1111 1111 1111 1111 uuuu uuuu
TRISC 1111 1111 1111 1111 uuuu uuuu
TRISB 1111 1111 1111 1111 uuuu uuuu
TRIS -111 1111 -111 1111 -uuu uuuu
LATE ---- -xxx ---- -uuu ---- -uuu
LATD xxxx xxxx uuuu uuuu uuuu uuuu
LATC xxxx xxxx uuuu uuuu uuuu uuuu
LATB xxxx xxxx uuuu uuuu uuuu uuuu
LATA -xxx xxxx -uuu uuuu -uuu uuuu
PORTE ---- -000 ---- -000 ---- -uuu
PORTD xxxx xxxx uuuu uuuu uuuu uuuu
PORTC xxxx xxxx uuuu uuuu uuuu uuuu
PORTB xxxx xxxx uuuu uuuu uuuu uuuu
PORTA -x0x 0000 -u0u 0000 -uuu uuuu
Table 3-4: Initialization Conditions for SFR Registers (Continued)
Register Power-on Reset,
Brown-out Reset
MCLR Resets
WDT Reset
Reset Instruction
Stack Resets
Wake-up via WDT or
Interrupt
Legend: u = unchanged, x = unknown, - = unimplemented bit, read as '0', q = value depends
on condition.
Note 1: One or more bits in the INTCONx or PIRx registers will be affected (to cause
wake-up).
2: When the wake-up is due to an interrupt and the GIEL or GIEH bit is set, the PC is
loaded with the interrupt vector (0008h or 0018h).
3: When the wake-up is due to an interrupt and the GIEL or GIEH bit is set, the TOSU,
TOSH and TOSL are updated with the current value of the PC. The STKPTR is modified
to point to the next location in the hardware stack.
4: The long write enable is only reset on a POR or MCLR reset.
5: The bits in the PIR, PIE, and IPR registers are device dependent. Their function and
location may change from device to device.
39500 18C Reference Manual.book Page 18 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39503A-page 3-19
Section 3. Reset
Reset
3
3.3.1 Reset Control (RCON) Register
The Reset Control (RCON) register contains flag bits to allow differentiation between resets. The
Reset Control register has seven bits.
The POR (Power-on Reset) bit is cleared on a Power-on Reset and is unaffected otherwise. The
user sets this bit following a Power-on Reset. On subsequent resets, if the POR bit is clear (= ‘0’),
it will indicate that a Power-on Reset must have occurred.
The power-down bit (PD) provides indication if the device was placed into sleep mode. It is set
by a power-up, a CLRWDT instruction or by user software. The PD bit is cleared when the SLEEP
instruction is executed or by user software.
Register 3-2: RCON Register
Note: The state of the BOR bit is unknown on Power-on Reset. It must be set by the user
and checked on subsequent resets to see if the BOR bit is clear, indicating a
brown-out has occurred. The BOR status bit is a “don't care” and is not necessarily
predictable if the brown-out circuit is disabled (by clearing the BOREN bit in the
Configuration register).
R/W-0 R/W-0 U-0 R/W-1 R/W-1 R/W-1 R/W-1 R/W-u
IPEN LWRT — RI TO PD POR BOR
bit 7 bit 0
bit 7 IPEN: Interrupt Priority Enable bit
1 = Enable priority levels on interrupts
0 = Disable priority levels on interrupts
bit 6 LWRT: Long Write Enable bit
1 = Enable Table Writes to internal program memory
Once this bit is set, it can only be cleared by a POR or MCLR reset.
0 = Disable Table Writes to internal program memory; Table Writes only to external program
memory.
bit 5 Unimplemented: Read as '0'
bit 4 RI: Reset Instruction Flag bit
1 = The RESET instruction was not invoked
0 = The RESET instruction was executed
(must be set in software after the RESET instruction is executed)
bit 3 TO: Time-out bit
1 = After power-up, CLRWDT instruction or SLEEP instruction
0 = A WDT time-out occurred
bit 2 PD: Power-down bit
1 = After power-up or by the CLRWDT instruction
0 = By execution of the SLEEP instruction
bit 1 POR: Power-on Reset Flag bit
1 = A Power-on Reset has not occurred
0 = A Power-on Reset occurred
(must be set in software after a Power-on Reset occurs)
bit 0 BOR: Brown-out Reset Flag bit
1 = A Brown-out Reset has not occurred
0 = A Brown-out Reset occurred
(must be set in software after a Brown-out Reset or Power-on Reset occurs)
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
39500 18C Reference Manual.book Page 19 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39503A-page 3-20 2000 Microchip Technology Inc.
3.4 Design Tips
Question 1: With windowed devices, my system resets and operates properly. With an
OTP device, my system does not operate properly.
Answer 1:
The most common reason for this is that the windowed device has not had its window covered.
The background light causes the device to power-up in a different state than would typically be
seen in a device where no light is present. In most cases, all the General Purpose RAM and Special
Function Registers were not initialized by the application software.
39500 18C Reference Manual.book Page 20 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39503A-page 3-21
Section 3. Reset
Reset
3
3.5 Related Application Notes
This section lists application notes that are related to this section of the manual. These application
notes may not be written specifically for the Enhanced family (that is, they may be written for
the Base-Line, the Mid-Range or High-End families), but the concepts are pertinent and could be
used (with modification and possible limitations). The current application notes related to Resets
are:
Title Application Note #
Power-up Trouble Shooting AN607
Power-up Considerations AN522
Note: Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
http://www.microchip.com/10/faqs/codeex/
39500 18C Reference Manual.book Page 21 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39503A-page 3-22 2000 Microchip Technology Inc.
3.6 Revision History
Revision A
This is the initial released revision of the Enhanced MCU Reset description.
39500 18C Reference Manual.book Page 22 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39504A-page 4-1
Architechture
4
Section 4. Architecture
HIGHLIGHTS
This section of the manual contains the following major topics:
4.1 Introduction .................................................................................................................... 4-2
4.2 Clocking Scheme/Instruction Cycle ............................................................................... 4-5
4.3 Instruction Flow/Pipelining ............................................................................................. 4-6
4.4 I/O Descriptions ............................................................................................................. 4-7
4.5 Design Tips.................................................................................................................. 4-14
4.6 Related Application Notes............................................................................................ 4-15
4.7 Revision History........................................................................................................... 4-16
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39504A-page 4-2 2000 Microchip Technology Inc.
4.1 Introduction
The high performance of the PIC18CXXX devices can be attributed to a number of architectural
features commonly found in RISC microprocessors. These include:
• Harvard architecture
• Long Word Instructions
• Single Word Instructions
• Single Cycle Instructions
• Instruction Pipelining
• Reduced Instruction Set
• Register File Architecture
• Orthogonal (Symmetric) Instructions
Figure 4-2 shows a general block diagram for PIC18CXXX devices.
Harvard Architecture:
Harvard architecture has the program memory and data memory as separate memories which
are accessed from separate buses. This improves bandwidth over traditional von Neumann
architecture in which program and data are fetched from the same memory using the same bus.
To execute an instruction, a von Neumann machine must make one or more (generally more)
accesses across the 8-bit bus to fetch the instruction. Then data may need to be fetched, operated
on and possibly written. As can be seen from this description, the bus can become
extremely congested. With a Harvard architecture, the instruction is fetched in a single instruction
cycle (all 16 bits). While the program memory is being accessed, the data memory is on an independent
bus and can be read and written. These separated busses allow one instruction to execute,
while the next instruction is fetched. A comparison of Harvard and von Neumann
architectures is shown in Figure 4-1.
Figure 4-1: Harvard vs. von Neumann Block Architectures
Long Word Instructions:
Long word instructions have a wider (more bits) instruction bus than the 8-bit data memory bus.
This is possible because the two buses are separate. This allows instructions to be sized differently
than the 8-bit wide data word and allows a more efficient use of the program memory, since
the program memory width is optimized to the architectural requirements.
Single Word Instructions:
Single word instruction opcodes are 16-bits wide making it possible to have all but a few instructions
be single word instructions. A 16-bit wide program memory access bus fetches a 16-bit
instruction in a single cycle. With single word instructions, the number of words of program memory
locations equals the number of instructions for the device. This means that all locations are
valid instructions.
Typically in the von Neumann architecture, most instructions are multi-byte. In general, a device
with 4 Kbytes of program memory would allow approximately 2K of instructions. This 2:1 ratio is
generalized and dependent on the application code. Since each instruction may take multiple
bytes, there is no assurance that each location is a valid instruction.
Program
Memory
Data
Memory
Program
Memory
and
Data CPU CPU
8 16 8
Harvard von Neumann
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39504A-page 4-3
Section 4 Architecture
Architechture
4
Double Word Instructions:
Some operations require more information then can be stored in the 16 bits of a program memory
location. These operations require a double word instruction, and are therefore 32-bits wide.
Instructions that require this second instruction word are:
• Memory to memory move instruction (12 bits for each RAM address)
- MOVFF SourceReg, DestReg
• Literal value to FSR move instruction (12 bits for data and 2 bits for FSR to load)
- LFSR FSR#, Address
• Call and goto operations (20 bits for address)
- CALL Address
- GOTO Address
The first word indicates to the CPU that the next program memory location is the additional information
for this instruction and not an instruction. If the CPU tries to execute the second word of
an instruction (due to a software modified PC pointing to that location as an instruction), the
fetched data is executed as a NOP.
Double word instruction execution is not split between the two TCY cycles by an interrupt request.
That is, when an interrupt request occurs during the execution of a double word instruction, the
execution of the instruction is completed before the processor vectors to the interrupt address.
The interrupt latency is preserved.
Instruction Pipeline:
The instruction pipeline is a two-stage pipeline that overlaps the fetch and execution of instructions.
The fetch of the instruction takes one TCY, while the execution takes another TCY. However,
due to the overlap of the fetch of current instruction and execution of previous instruction, an
instruction is fetched and another instruction is executed every TCY.
Single Cycle Instructions:
With the program memory bus being 16-bits wide, the entire instruction is fetched in a single
machine cycle (TCY), except for double word instructions. The instruction contains all the information
required and is executed in a single cycle. There may be a one cycle delay in execution
if the result of the instruction modified the contents of the program counter. This requires the pipeline
to be flushed and a new instruction to be fetched.
Two Cycle Instructions:
Double word instructions require two cycles to execute, since all the required information is in the
32 bits.
Reduced Instruction Set:
When an instruction set is well designed and highly orthogonal (symmetric), fewer instructions
are required to perform all needed tasks. With fewer instructions, the whole set can be more rapidly
learned.
Register File Architecture:
The register files/data memory can be directly or indirectly addressed. All special function registers,
including the program counter, are mapped in the data memory.
Orthogonal (Symmetric) Instructions:
Orthogonal instructions make it possible to carry out any operation on any register using any
addressing mode. This symmetrical nature and lack of “special instructions” make programming
simple yet efficient. In addition, the learning curve is reduced significantly. The Enhanced MCU
instruction set uses only three non-register oriented instructions, which are used for two of the
cores features. One is the SLEEP instruction, which places the device into the lowest power use
mode. The second is the CLRWDT instruction, which verifies the chip is operating properly by preventing
the on-chip Watchdog Timer (WDT) from overflowing and resetting the device. The third
is the RESET instruction, which resets the device.
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39504A-page 4-4 2000 Microchip Technology Inc.
Figure 4-2: General Enhanced MCU Block Diagram
Power-up
Timer
Oscillator
Start-up Timer
Power-on
Reset
Watchdog
Timer
Instruction
Decode &
Control
OSC1/CLKIN
OSC2/CLKOUT
MCLR VDD, VSS
PORTA
PORTB
PORTC
RA4
RA5
RB0/INT0
RB<7:4>
RC0
RC1
RC2
RC3
RC4
RC5
RC6
RC7
Brown-out
Reset
Note 1: Many of the general purpose I/O pins are multiplexed with one or more peripheral module functions. The multiplexing combinations are
device dependent.
RA3
RA2
RA1
RA0
Timing
Generation
4X PLL
RB1/INT1
Data Latch
Data RAM
(up to 4K
address reach)
Address Latch
Address<12>
12
BSR FSR0 Bank0, F
FSR1
FSR2
inc / dec Decode logic
4 12 4
PCH PCL
PCLATH
8
31 Level Stack
Program Counter
PRODH PRODL
8 x 8 Multiply
W
8
BITOP
8 8
ALU<8>
8
Address Latch
Program Memory
(up to 2M Bytes)
Data Latch
20
21
21
16
8
8
8
Table Pointer<21>
inc/dec logic
21
8
Data Bus<8>
TABLELATCH
8
Instruction
12
3
ROMLATCH
PORTD
RB2/INT2
RB3
T1OSI
T1OSO
PCLATU
PCU
RA6
Precision
Reference
Bandgap
Register
8
Addressable CCP’s Synchronous
Timer0 Timer1 Timer2
Serial Port
Timer3 A/D Converter
Enhanced
USART
Master
Other
Peripherals
RD0
RD1
RD2
RD3
RD4
RD5
RD6
RD7
PORTE
RE0
RE1
RE2
RE3
RE4
RE5
RE6
RE7
Peripheral Modules (Note 1)
CAN USB
PORTx
Rx0
Rx1
Rx2
Rx3
Rx4
Rx5
Rx6
Rx7
CCP’s
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39504A-page 4-5
Section 4 Architecture
Architechture
4
4.2 Clocking Scheme/Instruction Cycle
The clock input is internally divided by four to generate four non-overlapping quadrature clocks,
namely Q1, Q2, Q3 and Q4. Internally, the program counter is incremented every Q1, and the
instruction is fetched from the program memory and latched into the instruction register in Q4.
The instruction is decoded and executed during the following Q1 through Q4. The clocks and
instruction execution flow are illustrated in Figure 4-3 and Example 4-1.
Figure 4-3: Clock/Instruction Cycle
4.2.1 Phase Lock Loop (PLL)
The clock input is multiplied by four by the PLL. Therefore, when it is internally divided by four, it
provides an instruction cycle that is the same frequency as the external clock frequency. Four
non-overlapping quadrature clocks, namely Q1, Q2, Q3 and Q4 are still generated internally.
Internally, the program counter (PC) is incremented every Q1, and the instruction is fetched from
the program memory and latched into the instruction register in Q4. The instruction is decoded
and executed during the following Q1 through Q4. The clocks and instruction execution flow are
illustrated in Figure 4-4 and Example 4-1.
Figure 4-4: Clock/Instruction Cycle with PLL
Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4
Device Clock
Q1
Q2
Q3
Q4
PC
CLKOUT
(RC mode)
PC PC+2 PC+4
Fetch INST (PC)
Execute INST (PC-2) Fetch INST (PC+2)
Execute INST (PC) Fetch INST (PC+4)
Execute INST (PC+2)
Internal
phase
clock
TCY1 TCY2 TCY3
(OSC1 or T1OSCI)
Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4
PLL Output
Q1
Q2
Q3
Q4
PC
OSC2/CLKOUT
(RC mode)
PC PC+2 PC+4
Fetch INST (PC)
Execute INST (PC-2) Fetch INST (PC+2)
Execute INST (PC) Fetch INST (PC+4)
Execute INST (PC+2)
Internal
phase
clock
TCY1 TCY2 TCY3
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39504A-page 4-6 2000 Microchip Technology Inc.
4.3 Instruction Flow/Pipelining
An “Instruction Cycle” consists of four Q cycles (Q1, Q2, Q3 and Q4). Fetch takes one instruction
cycle, while decode and execute takes another instruction cycle. However, due to pipelining,
each instruction effectively executes in one cycle. If an instruction causes the program counter
to change (e.g. GOTO instruction), then an extra cycle is required to complete the instruction (See
Example 4-1).
The instruction fetch begins with the program counter incrementing in Q1.
In the execution cycle, the fetched instruction is latched into the “Instruction Register (IR)” in
cycle Q1. This instruction is then decoded and executed during the Q2, Q3 and Q4 cycles. Data
memory is read during Q2 (operand read) and written during Q4 (destination write).
Example 4-1 shows the operation of the two stage pipeline for the instruction sequence shown.
At time TCY0, the first instruction is fetched from program memory. During TCY1, the first instruction
executes, while the second instruction is fetched. During TCY2, the second instruction executes,
while the third instruction is fetched. During TCY3, the fourth instruction is fetched, while
the third instruction (CALL SUB_1) is executed. When the third instruction completes execution,
the CPU forces the address of instruction four onto the Stack and then changes the Program
Counter (PC) to the address of SUB_1. This means that the instruction that was fetched during
TCY3 needs to be “flushed” from the pipeline. During TCY4, instruction four is flushed (executed
as a NOP) and the instruction at address SUB_1 is fetched. Finally during TCY5, instruction five is
executed and the instruction at address SUB_1 + 2 is fetched.
Example 4-1: Instruction Pipeline Flow
Most instructions are single cycle. Program branches take two cycles, since the fetch instruction is “flushed” from
the pipeline while the new instruction is being fetched and then executed.
TCY0 TCY1 TCY2 TCY3 TCY4 TCY5
1. MOVLW 55h Fetch 1 Execute 1
2. MOVWF PORTB Fetch 2 Execute 2
3. CALL SUB_1 Fetch 3 Execute 3
4. BSF PORTA, BIT3 (Forced NOP) Fetch 4 Flush
5. Instruction @ address SUB_1 Fetch SUB_1 Execute SUB_1
Fetch SUB_1 + 2
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39504A-page 4-7
Section 4 Architecture
Architechture
4
4.4 I/O Descriptions
Table 4-1 gives a brief description of device pins and the functions that may be multiplexed to a
port pin. Multiple functions may exist on one port pin. When multiplexing occurs, the peripheral
module’s functional requirements may force an override of the data direction (TRIS bit) of the port
pin (such as in the A/D and Comparator modules).
Table 4-1: I/O Descriptions
Pin Name Pin
Type
Buffer
Type Description
A19 O — System bus address line 19
A18 O — System bus address line 18
A17 O — System bus address line 17
A16 O — System bus address line 16
AD15 I/O TTL System bus address/data line 15
AD14 I/O TTL System bus address/data line 14
AD13 I/O TTL System bus address/data line 13
AD12 I/O TTL System bus address/data line 12
AD11 I/O TTL System bus address/data line 11
AD10 I/O TTL System bus address/data line 10
AD9 I/O TTL System bus address/data line 9
AD8 I/O TTL System bus address/data line 8
AD7 I/O TTL System bus address/data line 7
AD6 I/O TTL System bus address/data line 6
AD5 I/O TTL System bus address/data line 5
AD4 I/O TTL System bus address/data line 4
AD3 I/O TTL System bus address/data line 3
AD2 I/O TTL System bus address/data line 2
AD1 I/O TTL System bus address/data line 1
AD0 I/O TTL System bus address/data line 0
ALE O — System bus address latch enable strobe
Analog Input Channels
AN0 I Analog
AN1 I Analog
AN2 I Analog
AN3 I Analog
AN4 I Analog
AN5 I Analog
AN6 I Analog
AN7 I Analog
AN8 I Analog
AN9 I Analog
AN10 I Analog
AN11 I Analog
AN12 I Analog
AN13 I Analog
AN14 I Analog
AN15 I Analog
AVDD P P Analog Power
Legend: TTL = TTL-compatible input CMOS = CMOS compatible input or output
ST = Schmitt Trigger input with CMOS levels O = output
PU = Weak internal pull-up I = input
Analog = Analog input or output P = Power
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39504A-page 4-8 2000 Microchip Technology Inc.
AVSS P P Analog Ground
BA0 O — System bus byte address 0
CANRX I ST CAN bus receive pin
CANTX0 O — CAN bus transmit
CANTX1 O — CAN bus complimentary transmit or CAN bus bit time clock
CCP1 I/O ST Capture1 input/Compare1 output/PWM1 output
CCP2 I/O ST Capture2 input/Compare2 output/PWM2 output.
CK I/O ST USART Synchronous Clock, always associated with TX pin function
(See related TX, RX, DT)
CLKI I ST/CMOS External clock source input. Always associated with pin function
OSC1. (See related OSC1/CLKIN, OSC2/CLKOUT pins)
CLKO O — Oscillator crystal output. Connects to crystal or resonator in crystal
oscillator mode. In RC mode, OSC2 pin outputs CLKOUT which has
1/4 the frequency of OSC1, and denotes the instruction cycle rate.
Always associated with OSC2 pin function. (See related OSC2,
OSC1)
CMPA O — Comparator A output
CMPB O — Comparator B output
CS I TTL Chip select control for parallel slave port (See related RD and WR)
CVREF O Analog Comparator voltage reference output
DT I/O ST USART Synchronous Data. Always associated RX pin function. (See
related RX, TX, CK)
Table 4-1: I/O Descriptions (Continued)
Pin Name Pin
Type
Buffer
Type Description
Legend: TTL = TTL-compatible input CMOS = CMOS compatible input or output
ST = Schmitt Trigger input with CMOS levels O = output
PU = Weak internal pull-up I = input
Analog = Analog input or output P = Power
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39504A-page 4-9
Section 4 Architecture
Architechture
4
INT0 I ST External Interrupt0
INT1 I ST External Interrupt1
INT2 I ST External Interrupt2
LB O — System bus low byte strobe
LVDIN I Analog Low voltage detect input
MCLR I/P ST Master clear (reset) input or programming voltage input. This pin is
an active low reset to the device.
NC — — These pins should be left unconnected.
OE O — System bus output enable strobe
OSC1 I ST/CMOS Oscillator crystal input or external clock source input. ST buffer when
configured in RC mode. CMOS otherwise.
OSC2 O — Oscillator crystal output. Connects to crystal or resonator in crystal
oscillator mode. In RC mode, OSC2 pin outputs CLKOUT, which has
1/4 the frequency of OSC1, and denotes the instruction cycle rate.
PSP0 I/O TTL Parallel Slave Port for interfacing to a microprocessor port. These
PSP1 I/O TTL pins have TTL input buffers when PSP module is enabled.
PSP2 I/O TTL
PSP3 I/O TTL
PSP4 I/O TTL
PSP5 I/O TTL
PSP6 I/O TTL
PSP7 I/O TTL
PORTA is a bi-directional I/O port.
RA0 I/O TTL
RA1 I/O TTL
RA2 I/O TTL
RA3 I/O TTL
RA4 I/O ST RA4 is an open drain when configured as output.
RA5 I/O TTL
RA6 I/O TTL
PORTB is a bi-directional I/O port. PORTB can be software programmed
for internal weak pull-ups on all inputs.
RB0 I/O TTL
RB1 I/O TTL
RB2 I/O TTL
RB3 I/O TTL
RB4 I/O TTL Interrupt on change pin.
RB5 I/O TTL Interrupt on change pin.
RB6 I/O TTL/ST Interrupt on change pin. Serial programming clock. TTL input
buffer as general purpose I/O, Schmitt Trigger input buffer when
used as the serial programming clock.
RB7 I/O TTL/ST Interrupt on change pin. Serial programming data. TTL input
buffer as general purpose I/O, Schmitt Trigger input buffer when
used as the serial programming data.
Table 4-1: I/O Descriptions (Continued)
Pin Name Pin
Type
Buffer
Type Description
Legend: TTL = TTL-compatible input CMOS = CMOS compatible input or output
ST = Schmitt Trigger input with CMOS levels O = output
PU = Weak internal pull-up I = input
Analog = Analog input or output P = Power
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39504A-page 4-10 2000 Microchip Technology Inc.
PORTC is a bi-directional I/O port.
RC0 I/O ST
RC1 I/O ST
RC2 I/O ST
RC3 I/O ST
RC4 I/O ST
RC5 I/O ST
RC6 I/O ST
RC7 I/O ST
RD I TTL Read control for parallel slave port. (See also WR and CS pins.)
PORTD is a bi-directional I/O port.
RD0 I/O ST
RD1 I/O ST
RD2 I/O ST
RD3 I/O ST
RD4 I/O ST
RD5 I/O ST
RD6 I/O ST
RD7 I/O ST
PORTE is a bi-directional I/O port.
RE0 I/O ST
RE1 I/O ST
RE2 I/O ST
RE3 I/O ST
RE4 I/O ST
RE5 I/O ST
RE6 I/O ST
RE7 I/O ST
PORTF is a digital input
RF0 I/O ST
RF1 I/O ST
RF2 I/O ST
RF3 I/O ST
RF4 I/O ST
RF5 I/O ST
RF6 I/O ST
RF7 I/O ST
Table 4-1: I/O Descriptions (Continued)
Pin Name Pin
Type
Buffer
Type Description
Legend: TTL = TTL-compatible input CMOS = CMOS compatible input or output
ST = Schmitt Trigger input with CMOS levels O = output
PU = Weak internal pull-up I = input
Analog = Analog input or output P = Power
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39504A-page 4-11
Section 4 Architecture
Architechture
4
PORTG is a digital input
RG0 I/O ST
RG1 I/O ST
RG2 I/O ST
RG3 I/O ST
RG4 I/O ST
RG5 I/O ST
RG6 I/O ST
RG7 I/O ST
PORTH is a digital input
RH0 I/O ST
RH1 I/O ST
RH2 I/O ST
RH3 I/O ST
RH4 I/O ST
RH5 I/O ST
RH6 I/O ST
RH7 I/O ST
PORTJ is a digital input
RJ0 I/O ST
RJ1 I/O ST
RJ2 I/O ST
RJ3 I/O ST
RJ4 I/O ST
RJ5 I/O ST
RJ6 I/O ST
RJ7 I/O ST
PORTK is a digital input
RK0 I/O ST
RK1 I/O ST
RK2 I/O ST
RK3 I/O ST
RK4 I/O ST
RK5 I/O ST
RK6 I/O ST
RK7 I/O ST
Table 4-1: I/O Descriptions (Continued)
Pin Name Pin
Type
Buffer
Type Description
Legend: TTL = TTL-compatible input CMOS = CMOS compatible input or output
ST = Schmitt Trigger input with CMOS levels O = output
PU = Weak internal pull-up I = input
Analog = Analog input or output P = Power
39500 18C Reference Manual.book Page 11 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39504A-page 4-12 2000 Microchip Technology Inc.
PORTL is a digital input
RL0 I/O ST
RL1 I/O ST
RL2 I/O ST
RL3 I/O ST
RL4 I/O ST
RL5 I/O ST
RL6 I/O ST
RL7 I/O ST
RX I ST USART Asynchronous Receive
SCL I/O ST Synchronous serial clock input/output for I2C mode.
SCLA I/O ST Synchronous serial clock for I2C interface.
SCLB I/O ST Synchronous serial clock for I2C interface.
SDA I/O ST I2C™ Data I/O
SDAA I/O ST Synchronous serial data I/O for I2C interface
SDAB I/O ST Synchronous serial data I/O for I2C interface
SCK I/O ST Synchronous serial clock input/output for SPI mode.
SDI I ST SPI Data In
SDO O — SPI Data Out (SPI mode)
SS I ST SPI Slave Select input
T0CKI I ST Timer0 external clock input
T1CKI I ST Timer1 external clock input
T1OSO O CMOS Timer1 oscillator output
T1OSI I CMOS Timer1 oscillator input
TX O — USART Asynchronous Transmit (See related RX)
UB O — System bus upper byte strobe
Table 4-1: I/O Descriptions (Continued)
Pin Name Pin
Type
Buffer
Type Description
Legend: TTL = TTL-compatible input CMOS = CMOS compatible input or output
ST = Schmitt Trigger input with CMOS levels O = output
PU = Weak internal pull-up I = input
Analog = Analog input or output P = Power
39500 18C Reference Manual.book Page 12 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39504A-page 4-13
Section 4 Architecture
Architechture
4
VREF I Analog Analog High Voltage Reference input.
DR reference voltage output on devices with comparators.
VREF+ I Analog Analog High Voltage Reference input.
Usually multiplexed onto an analog pin.
VREF- I Analog Analog Low Voltage Reference input.
Usually multiplexed onto an analog pin.
VSS P — Ground reference for logic and I/O pins.
VDD P — Positive supply for logic and I/O pins.
VPP P — Programming voltage input
WR I TTL Write control for parallel slave port (See CS and RD pins also).
WRL O — System bus write low byte strobe
WRH O — System bus write high byte strobe
Table 4-1: I/O Descriptions (Continued)
Pin Name Pin
Type
Buffer
Type Description
Legend: TTL = TTL-compatible input CMOS = CMOS compatible input or output
ST = Schmitt Trigger input with CMOS levels O = output
PU = Weak internal pull-up I = input
Analog = Analog input or output P = Power
39500 18C Reference Manual.book Page 13 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39504A-page 4-14 2000 Microchip Technology Inc.
4.5 Design Tips
No related design tips at this time.
39500 18C Reference Manual.book Page 14 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39504A-page 4-15
Section 4 Architecture
Architechture
4
4.6 Related Application Notes
This section lists application notes that are related to this section of the manual. These application
notes may not be written specifically for the Enhanced family (that is, they may be written for
the Base-Line, the Mid-Range, or High-End families), but the concepts are pertinent and could
be used (with modification and possible limitations). The current application notes related to
Architecture are:
Title Application Note #
No related application notes at this time.
Note: Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
http://www.microchip.com/10/faqs/codeex/
39500 18C Reference Manual.book Page 15 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39504A-page 4-16 2000 Microchip Technology Inc.
4.7 Revision History
Revision A
This is the initial released revision of the Enhanced MCU Architecture description.
39500 18C Reference Manual.book Page 16 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39505A-page 5-1
CPU and ALU
5
Section 5. CPU and ALU
HIGHLIGHTS
This section of the manual contains the following major topics:
5.1 Introduction .................................................................................................................... 5-2
5.2 General Instruction Format ............................................................................................ 5-6
5.3 Central Processing Unit (CPU) ...................................................................................... 5-7
5.4 Instruction Clock ............................................................................................................ 5-8
5.5 Arithmetic Logical Unit (ALU)......................................................................................... 5-9
5.6 STATUS Register ......................................................................................................... 5-11
5.7 Design Tips.................................................................................................................. 5-14
5.8 Related Application Notes............................................................................................ 5-15
5.9 Revision History........................................................................................................... 5-16
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39505A-page 5-2 2000 Microchip Technology Inc.
5.1 Introduction
The Central Processing Unit (CPU) is responsible for using the information in the program memory
(instructions) to control the operation of the device. Many of these instructions operate on
data memory. To operate on data memory, the Arithmetic Logical Unit (ALU) is required. In addition
to performing arithmetical and logical operations, the ALU controls the state of the status bits,
which are found in the STATUS register. The result of some instructions force status bits to a
value depending on the state of the result.
The machine codes that the CPU recognizes are shown in Table 5-1, as well as the instruction
mnemonics that the MPASM uses to generate these codes.
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39505A-page 5-3
Section 5. CPU and ALU
CPU and ALU
5
Table 5-1: PIC18CXXX Instruction Set
Mnemonic,
Operands Description Cycles (4) 16-Bit Instruction Word Status
Affected Notes
MSb LSb
BYTE-ORIENTED FILE REGISTER OPERATIONS
ADDWF
ADDWFC
ANDWF
CLRF
COMF
CPFSEQ
CPFSGT
CPFSLT
DECF
DECFSZ
DCFSNZ
INCF
INCFSZ
INFSNZ
IORWF
MOVF
MOVFF
MOVWF
MULWF
NEGF
RLCF
RLNCF
RRCF
RRNCF
SETF
SUBFWB
SUBWF
SUBWFB
SWAPF
TSTFSZ
XORWF
f, d, a
f, d, a
f, d, a
f, a
f, d, a
f, a
f, a
f, a
f, d, a
f, d, a
f, d, a
f, d, a
f, d, a
f, d, a
f, d, a
f, d, a
fs, fd
f, a
f, a
f, a
f, d, a
f, d, a
f, d, a
f, d, a
f, a
f, d, a
f, d, a
f, d, a
f, d, a
f, a
f, d, a
Add WREG and f
Add WREG and Carry bit to f
AND WREG with f
Clear f
Complement f
Compare f with WREG, skip =
Compare f with WREG, skip >
Compare f with WREG, skip <
Decrement f
Decrement f, Skip if 0
Decrement f, Skip if Not 0
Increment f
Increment f, Skip if 0
Increment f, Skip if Not 0
Inclusive OR WREG with f
Move f
Move fs (source) to
fd (destination)
Move WREG to f
Multiply WREG with f
Negate f
Rotate Left f through Carry
Rotate Left f (No Carry)
Rotate Right f through Carry
Rotate Right f (No Carry)
Set f
Subtract f from WREG with
Subtract WREG from f
Subtract WREG from f with
Swap nibbles in f
Test f, skip if 0
Exclusive OR WREG with f
1
1
1
1
1
1 (2 or 3)
1 (2 or 3)
1 (2 or 3)
1
1 (2 or 3)
1 (2 or 3)
1
1 (2 or 3)
1 (2 or 3)
1
1
2
1
1
1
1
1
1
1
1
1
1
1
1
1 (2 or 3)
1
0010
0010
0001
0110
0001
0110
0110
0110
0000
0010
0100
0010
0011
0100
0001
0101
1100
1111
0110
0000
0110
0011
0100
0011
0100
0110
0101
0101
0101
0011
0110
0001
01da
00da
101a
11da
11da
001a
010a
000a
01da
11da
11da
10da
11da
10da
00da
00da
ffff
ffff
111a
001a
110a
01da
01da
00da
00da
100a
01da
11da
10da
10da
011a
10da
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
C, DC, Z, OV, N
C, DC, Z, OV, N
Z, N
Z, N
Z, N
None
None
None
C, DC, Z, OV, N
None
None
C, DC, Z, OV, N
None
None
Z
Z
None
None
None
C, DC, Z, OV, N
C, DC, Z, N
C, DC, Z, N
C, DC, Z, N
C, DC, Z, N
None
C, DC, Z, OV, N
C, DC, Z, OV, N
C, DC, Z, OV, N
None
None
Z, N
1, 2
1, 2
1,2
2
1, 2
4
4
1, 2
1, 2, 3, 4
1, 2, 3, 4
1, 2
1, 2, 3, 4
4
1, 2
1, 2
1, 2
1, 2
1, 2
1, 2
4
1, 2
BIT-ORIENTED FILE REGISTER OPERATIONS
BCF
BSF
BTFSC
BTFSS
BTG
f, b, a
f, b, a
f, b, a
f, b, a
f, d, a
Bit Clear f
Bit Set f
Bit Test f, Skip if Clear
Bit Test f, Skip if Set
Bit Toggle f
1
1
1 (2 or 3)
1 (2 or 3)
1
1001
1000
1011
1010
0111
bbba
bbba
bbba
bbba
bbba
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
None
None
None
None
None
1, 2
1, 2
3, 4
3, 4
1, 2
Note 1: When an I/O register is modified as a function of itself (e.g., MOVF PORTB, 1, 0), the value used will be that
value present on the pins themselves. For example, if the data latch is '1' for a pin configured as input and is driven
low by an external device, the data will be written back with a '0'.
2: If this instruction is executed on the TMR0 register (and, where applicable, d = 1), the prescaler will be cleared if
assigned to the Timer0 Module.
3: If Program Counter (PC) is modified or a conditional test is true, the instruction requires two cycles. The second
cycle is executed as a NOP.
4: Some instructions are 2 word instructions. The second word of these instructions will be executed as a NOP, unless
the first word retrieves the information embedded in these 16 bits. This ensures that all program memory locations
have a valid instruction.
5: If the Table Write starts the write cycle to internal memory, the write will continue until terminated.
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39505A-page 5-4 2000 Microchip Technology Inc.
CONTROL OPERATIONS
BC
BN
BNC
BNN
BNOV
BNZ
BOV
BRA
BZ
CALL
CLRWDT
DAW
GOTO
NOP
NOP
POP
PUSH
RCALL
RESET
RETFIE
RETLW
RETURN
SLEEP
TBLRD
TBLWT
n
n
n
n
n
n
n
n
n
n, s
—
—
n
—
—
—
—
n
s
k
s
—
m
m
Branch if Carry
Branch if Negative
Branch if Not Carry
Branch if Not Negative
Branch if Not Overflow
Branch if Not Zero
Branch if Overflow
Branch Unconditionally
Branch if Zero
Call subroutine 1st word
2nd word
Clear Watchdog Timer
Decimal Adjust WREG
Go to address 1st word
2nd word
No Operation
No Operation (4)
Pop top of return stack (TOS)
Push top of return stack
(TOS)
Relative Call
Software device RESET
Return from interrupt enable
Return with literal in WREG
Return from Subroutine
Go into standby mode
Table Read * → mm = 00
*+ → mm = 01
*- → mm = 10
+* → mm = 11
Table Write * → mm = 00
*+ → mm = 01
*- → mm = 10
+* → mm = 11
1 (2)
1 (2)
1 (2)
1 (2)
1 (2)
2
1 (2)
1 (2)
1 (2)
2
1
1
2
1
1
1
1
2
1
2
2
2
1
2
2
1110
1110
1110
1110
1110
1110
1110
1101
1110
1110
1111
0000
0000
1110
1111
0000
1111
0000
0000
1101
0000
0000
0000
0000
0000
0000
0000
0010
0110
0011
0111
0101
0001
0100
0nnn
0000
110s
kkkk
0000
0000
1111
kkkk
0000
xxxx
0000
0000
1nnn
0000
0000
1100
0000
0000
0000
0000
nnnn
nnnn
nnnn
nnnn
nnnn
nnnn
nnnn
nnnn
nnnn
kkkk
kkkk
0000
0000
kkkk
kkkk
0000
xxxx
0000
0000
nnnn
1111
0001
kkkk
0001
0000
0000
0000
nnnn
nnnn
nnnn
nnnn
nnnn
nnnn
nnnn
nnnn
nnnn
kkkk
kkkk
0100
0111
kkkk
kkkk
0000
xxxx
0110
0101
nnnn
1111
000s
kkkk
001s
0011
10mm
11mm
None
None
None
None
None
None
None
None
None
None
TO, PD
C
None
None
None
None
None
None
All
GIEH, GIEL
None
None
TO, PD
None
None
5
Table 5-1: PIC18CXXX Instruction Set (Continued)
Mnemonic,
Operands Description Cycles (4) 16-Bit Instruction Word Status
Affected Notes
MSb LSb
Note 1: When an I/O register is modified as a function of itself (e.g., MOVF PORTB, 1, 0), the value used will be that
value present on the pins themselves. For example, if the data latch is '1' for a pin configured as input and is driven
low by an external device, the data will be written back with a '0'.
2: If this instruction is executed on the TMR0 register (and, where applicable, d = 1), the prescaler will be cleared if
assigned to the Timer0 Module.
3: If Program Counter (PC) is modified or a conditional test is true, the instruction requires two cycles. The second
cycle is executed as a NOP.
4: Some instructions are 2 word instructions. The second word of these instructions will be executed as a NOP, unless
the first word retrieves the information embedded in these 16 bits. This ensures that all program memory locations
have a valid instruction.
5: If the Table Write starts the write cycle to internal memory, the write will continue until terminated.
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39505A-page 5-5
Section 5. CPU and ALU
CPU and ALU
5
LITERAL OPERATIONS
ADDLW
ANDLW
IORLW
MOVLB
LFSR
MOVLW
MULLW
RETLW
SUBLW
XORLW
k
k
k
k
f, k
k
k
k
k
k
Add literal and WREG
AND literal with WREG
Inclusive OR literal with
WREG
Move literal to BSR<3:0>
Move literal (12-bit) to FSRx
2nd word
Move literal to WREG
Multiply literal with WREG
Return with literal in WREG
Subtract WREG from literal
Exclusive OR literal with
WREG
1
1
1
1
2
1
1
2
1
1
0000
0000
0000
0000
1110
1111
0000
0000
0000
0000
0000
1111
1011
1001
0001
1110
0000
1110
1101
1100
1000
1010
kkkk
kkkk
kkkk
0000
00ff
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
C, DC, Z, OV, N
Z, N
Z, N
None
None
None
None
None
C, DC, Z, OV, N
Z, N
Table 5-1: PIC18CXXX Instruction Set (Continued)
Mnemonic,
Operands Description Cycles (4) 16-Bit Instruction Word Status
Affected Notes
MSb LSb
Note 1: When an I/O register is modified as a function of itself (e.g., MOVF PORTB, 1, 0), the value used will be that
value present on the pins themselves. For example, if the data latch is '1' for a pin configured as input and is driven
low by an external device, the data will be written back with a '0'.
2: If this instruction is executed on the TMR0 register (and, where applicable, d = 1), the prescaler will be cleared if
assigned to the Timer0 Module.
3: If Program Counter (PC) is modified or a conditional test is true, the instruction requires two cycles. The second
cycle is executed as a NOP.
4: Some instructions are 2 word instructions. The second word of these instructions will be executed as a NOP, unless
the first word retrieves the information embedded in these 16 bits. This ensures that all program memory locations
have a valid instruction.
5: If the Table Write starts the write cycle to internal memory, the write will continue until terminated.
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39505A-page 5-6 2000 Microchip Technology Inc.
5.2 General Instruction Format
The Enhanced family instructions can be broken down into five general formats as shown in
Figure 5-1. As can be seen, the opcode for the instruction varies from 4 bits to 8 bits. This variable
opcode size is what allows 77 instructions to be implemented.
Figure 5-1: General Format for Instructions
Byte-oriented file register operations
15 10 9 8 7 0
d = 0 for result destination to be WREG register
OPCODE d a f (FILE #)
d = 1 for result destination to be file register (f)
a = 0 to force Access Bank
Bit-oriented file register operations
15 12 11 9 8 7 0
OPCODE b (BIT #) a f (FILE #)
b = 3-bit position of bit in file register (f)
Literal operations
15 8 7 0
OPCODE k (literal)
k = 8-bit immediate value
Byte to Byte move operations (2-word)
15 12 11 0
OPCODE f (Source FILE #)
CALL, GOTO and Branch operations
15 8 7 0
OPCODE n<7:0> (literal)
n = 20-bit immediate value
a = 1 for BSR to select bank
f = 8-bit file register address
a = 0 to force Access Bank
a = 1 for BSR to select bank
f = 8-bit file register address
15 12 11 0
1111 n<19:8> (literal)
15 12 11 0
1111 f (Destination FILE #)
f = 12-bit file register address
Control operations
Example Instruction
ADDWF MYREG, W, a
MOVFF MYREG1, MYREG2
BSF MYREG, bit, a
MOVLW 0x7F
GOTO Label
15 8 7 0
OPCODE n<7:0> (literal)
15 12 11 0
CALL MYFUNC
15 11 10 0
OPCODE n<10:0> (literal)
S = Fast bit
BRA MYFUNC
15 8 7 0
OPCODE n<7:0> (literal) BC MYFUNC
S
1111 n<19:8> (literal)
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39505A-page 5-7
Section 5. CPU and ALU
CPU and ALU
5
5.3 Central Processing Unit (CPU)
The CPU can be thought of as the “brains” of the device. It is responsible for fetching the correct
instruction for execution, decoding that instruction and then executing that instruction.
The CPU sometimes works in conjunction with the ALU to complete the execution of the instruction
(in arithmetic and logical operations).
The CPU controls the program memory address bus, the data memory address bus and
accesses to the stack.
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39505A-page 5-8 2000 Microchip Technology Inc.
5.4 Instruction Clock
There are three oscillator clock sources from which the device can operate. These are
1. External System Clock (TOSC)
2. Phase Lock Loop (PLL)
3. Timer1 Oscillator (TT1P)
Figure 5-2 shows these clock inputs and the device clock output (TSCLK). TSCLK is the system
clock. Four TSCLK cycles are an instruction cycle (TCY).
The external system clock (TOSC) goes into the device and is input into a multiplexer anda4x
Phase Lock Loop (PLL). The output of the PLL also enters the multiplexer and has a name
TOSC/4. Some devices may also have an alternate oscillator called Timer1 oscillator (see
“Timer1” section), which can provide another system clock. Timer1 has a cycle time called TT1P.
This clock source also enters into the multiplexer.
Figure 5-2: Device Clock Sources
Each instruction cycle (TCY) is comprised of four Q cycles (Q1-Q4). The Q cycle time is the same
as the system clock cycle time (TSCLK). The Q cycles provide the timing/designation for the
Decode, Read, Process Data, Write, etc., of each instruction cycle.
The four Q cycles that make up an instruction cycle (TCY) are shown in Figure 5-3. The relationship
of the Q cycles to the instruction cycle can be generalized as:
Q1: Instruction Decode Cycle or forced No Operation (NOP)
Q2: Instruction Read Data Cycle or No Operation (NOP)
Q3: Process the Data
Q4: Instruction Write Data Cycle or No Operation (NOP)
Each instruction description will show a detailed Q cycle operation for the instruction.
Figure 5-3: Q Cycle Activity
PIC18CXXX
OSC1
PLL
TSCLK
Clock
Source MUX
TOSC/4
T1OSI
TOSC
TT1P
Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4
TCY1 TCY2 TCY3
TDOSC
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39505A-page 5-9
Section 5. CPU and ALU
CPU and ALU
5
5.5 Arithmetic Logical Unit (ALU)
PICmicro devices contain an 8-bit ALU and an 8-bit working register (WREG). The ALU is a general
purpose arithmetic and logical unit. It performs arithmetic and Boolean functions between
the data in the working register and any register file. The WREG register is directly addressable
and in the SFR memory map.
Figure 5-4: Operation of the ALU and WREG Register
The ALU is 8-bits wide and is capable of addition, subtraction, multiplication, shift and logical
operations. Unless otherwise mentioned, arithmetic operations are two's complement in nature.
In two-operand instructions, typically one operand is the working register (WREG register). The
other operand is a file register or an immediate constant. In single operand instructions, the operand
is either the WREG register or a file register.
The 8x8 multiplier operates in a single cycle, placing the 16-bit result in the PRODH:PRODL
register pair.
Depending on the instruction executed, the ALU may affect the values of the Carry (C), Digit
Carry (DC), Zero (Z), Overflow (OV), and Negative (N) bits in the STATUS register. The C and
DC bits operate as a borrow bit and a digitborrow out bit, respectively, in subtraction. See the
SUBLW and SUBWF instructions in the “Instruction Set” section for examples.
WREG Register
Register
File
8
d bit, or from instruction
8
8
8-bit literal
(from instruction word)
(SFR’s)
and
General
Purpose
RAM
ALU (GPR)
8
8
Special
Function
Registers
8-bit register value
(from direct or indirect
address of instruction)
STATUS Register
C bit
N, OV, Z,
DC, and C bits
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39505A-page 5-10 2000 Microchip Technology Inc.
5.5.1 Signed Math
Signed arithmetic is comprised of a magnitude and a sign bit. The overflow bit indicates if the
magnitude overflows and causes the sign bit to change state when the result of an 8-bit signed
operation is greater than 127 (7Fh) or less than -128 (80h).
Signed math can have greater than 7-bit values (magnitude), if more than one byte is used. The
overflow bit only operates on bit6 (MSb of magnitude) and bit7 (sign bit) of each byte value in the
ALU. That is, the overflow bit is not useful if trying to implement signed math where the magnitude,
for example, is 11 bits.
If the signed math values are greater than 7 bits (such as 15, 24 or 31 bits), the algorithm must
ensure that the low order bytes of the signed value ignore the overflow status bit.
Example 5-1 shows two cases of doing signed arithmetic. The Carry (C) bit and the Overflow
(OV) bit are the most important status bits for signed math operations.
Example 5-1: 8-bit Math Addition
Case 1:
The Negative bit is used to indicate if the MSb of the result is set or cleared.
Hex Value Signed Values Unsigned Values
FFh
+ 01h
= 00h
C bit = 1
OV bit = 0
DC bit = 1
Z bit = 1
N bit = 0
-1
+ 1
= 0 (FEh)
C bit = 1
OV bit = 0
DC bit = 1
Z bit = 1
N bit = 0
255
+ 1
= 256 → 00h
C bit = 1
OV bit = 0
DC bit = 1
Z bit = 1
N bit = 0
Case 2:
Hex Value Signed Values Unsigned Values
7Fh
+ 01h
= 80h
C bit = 0
OV bit = 1
DC bit = 1
Z bit = 0
N bit = 1
127
+ 1
= 128 → 00h
C bit = 0
OV bit = 1
DC bit = 1
Z bit = 0
N bit = 1
127
+ 1
= 128
C bit = 0
OV bit = 1
DC bit = 1
Z bit = 0
N bit = 1
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39505A-page 5-11
Section 5. CPU and ALU
CPU and ALU
5
5.6 STATUS Register
The STATUS register, shown in Register 5-1, contains the arithmetic status of the ALU. The
STATUS register can be the destination for any instruction, as with any other register. If the
STATUS register is the destination for an instruction that affects the Z, DC, C, OV or N bits, then
the write to these five bits is disabled. These bits are set or cleared according to the device logic.
Therefore, the result of an instruction with the STATUS register as destination may be different
than intended.
For example, CLRF STATUS will clear the upper three bits and set the Z bit. This leaves the
STATUS register as 000u u1uu (where u = unchanged).
It is recommended, therefore, that only BCF, BSF, SWAPF, MOVFF, and MOVWF instructions
are used to alter the STATUS register, because these instructions do not affect the Z, C, DC, OV
or N bits of the STATUS register. For other instructions, not affecting any status bits, see
Table 5-1.
Note 1: The C and DC bits operate as a borrow and digitborrow bit, respectively, in subtraction.
39500 18C Reference Manual.book Page 11 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39505A-page 5-12 2000 Microchip Technology Inc.
Register 5-1: STATUS Register
U-0 U-0 U-0 R/W-x R/W-x R/W-x R/W-x R/W-x
— — — N OV Z DC C
bit 7 bit 0
bit 7-5 Unimplemented: Read as '0'
bit 4 N: Negative bit
This bit is used for signed arithmetic (2’s complement). It indicates whether the result was negative,
(ALU MSb = 1).
1 = Result was negative
0 = Result was positive
bit 3 OV: Overflow bit
This bit is used for signed arithmetic (2’s complement). It indicates an overflow of the 7-bit magnitude,
which causes the sign bit (bit7) to change state.
1 = Overflow occurred for signed arithmetic (in this arithmetic operation)
0 = No overflow occurred
bit 2 Z: Zero bit
1 = The result of an arithmetic or logic operation is zero
0 = The result of an arithmetic or logic operation is not zero
bit 1 DC: Digit carry/borrow bit
For ADDWF, ADDLW, SUBLW, and SUBWF instructions
1 = A carry-out from the 4th low order bit of the result occurred
0 = No carry-out from the 4th low order bit of the result
Note: For borrow, the polarity is reversed. A subtraction is executed by adding the 2’s complement
of the second operand. For rotate (RRF, RLF) instructions, this bit is loaded
with either the bit4 or bit3 of the source register.
bit 0 C: Carry/borrow bit
For ADDWF, ADDLW, SUBLW, and SUBWF instructions
1 = A carry-out from the most significant bit of the result occurred
0 = No carry-out from the most significant bit of the result occurred
Note: For borrow, the polarity is reversed. A subtraction is executed by adding the 2’s complement
of the second operand. For rotate (RRF, RLF) instructions, this bit is loaded
with either the high or low order bit of the source register.
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
39500 18C Reference Manual.book Page 12 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39505A-page 5-13
Section 5. CPU and ALU
CPU and ALU
5
5.6.1 RCON Register
The Reset Control (RCON) register contains flag bit(s) that allow the user to differentiate
between the device resets.
Register 5-2: RCON Register
Note 1: If the BOREN configuration bit is set, BOR is ’0’ on Power-on Reset. If the BOREN
configuration bit is clear, BOR is unknown on Power-on Reset.
The BOR status bit is a "don't care" and is not necessarily predictable if the
brown-out circuit is disabled (the BOREN configuration bit is clear).
2: It is recommended that the POR bit be set after a Power-on Reset has been
detected, so that subsequent Power-on Resets may be detected.
R/W-0 R/W-0 U-0 R/W-1 R/W-1 R/W-1 R/W-0 R/W-0
IPEN LWRT — RI TO PD POR BOR
bit 7 bit 0
bit 7 IPEN: Interrupt Priority Enable bit
This bit reflects the value of the MPEEN configuration bit.
1 = Enable priority levels on interrupts
0 = Disable priority levels on interrupts (PIC16CXXX compatibility mode)
bit 6 LWRT: Long Write Enable
1 = Enable Table Writes to internal program memory
Once this bit is set, it can only be cleared by a POR or MCLR reset.
0 = Disable Table Writes to internal program memory; Table Writes only to external program
memory
bit 5 Unimplemented: Read as '0'
bit 4 RI: Reset Instruction Flag bit
1 = The Reset instruction was not executed to cause the device reset
0 = The Reset instruction was executed
(must be set in software after a Brown-out Reset occurs)
bit 3 TO: Watchdog Time-out Flag bit
1 = After Power-up, CLRWDT instruction, or SLEEP instruction
0 = A WDT time-out occurred
bit 2 PD: Power-down Detection Flag bit
1 = After Power-up or by the CLRWDT instruction
0 = By execution of the SLEEP instruction
bit 1 POR: Power-on Reset Status bit
1 = A Power-on Reset has not occurred
0 = A Power-on Reset occurred
(After a Power-on Reset occurs, this bit must be set in software to detect subsequent
occurrences of Power-on Reset.
bit 0 BOR: Brown-out Reset Status bit
1 = A Brown-out Reset has not occurred
0 = A Brown-out Reset occurred
(must be set in software after a Brown-out Reset occurs)
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
39500 18C Reference Manual.book Page 13 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39505A-page 5-14 2000 Microchip Technology Inc.
5.7 Design Tips
Question 1: My program algorithm does not seem to function correctly.
Answer 1:
There are many possible reasons for this. A couple of possibilities are:
1. The destination of the instruction may be specifying the WREG register (d = 0) instead of
the file register (d = 1).
2. The access bit may be specifying the Virtual RAM Bank instead of the desired bank of
RAM.
When possible, the use of an In-Circuit Emulator (such as MPLAB-ICE) or a simulator (such as
MPLAB-SIM) can assist in locating the reason for the unexpected execution flow.
Question 2: I cannot seem to modify the STATUS register flags.
Answer 2:
If the STATUS register is the destination for an instruction that affects the Z, DC, C, OV or N bits,
then the write to those bits is disabled. These bits are set or cleared based on device logic. Therefore,
to modify bits in the STATUS register, it is recommended to use the BCF and BSF instructions.
39500 18C Reference Manual.book Page 14 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39505A-page 5-15
Section 5. CPU and ALU
CPU and ALU
5
5.8 Related Application Notes
This section lists application notes that are related to this section of the manual. These application
notes may not be written specifically for the Enhanced family (that is they may be written for
the Base-Line, the Mid-Range or High-End families), but the concepts are pertinent and could be
used (with modification and possible limitations). The current application notes related to the
CPU or the ALU are:
Title Application Note #
IEEE 754 Compliant Floating Point Routines AN575
Fixed Point Routines AN617
Floating Point Math Functions AN660
Note: Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
http://www.microchip.com/10/faqs/codeex/
39500 18C Reference Manual.book Page 15 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39505A-page 5-16 2000 Microchip Technology Inc.
5.9 Revision History
Revision A
This is the initial released revision of the Enhanced MCU CPU and ALU description.
39500 18C Reference Manual.book Page 16 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39506-page 6-1
Hardware 8x8
Multiplier
6
Section 6. Hardware 8x8 Multiplier
HIGHLIGHTS
This section of the manual contains the following major topics:
6.1 Introduction .................................................................................................................... 6-2
6.2 Operation ....................................................................................................................... 6-3
6.3 Design Tips .................................................................................................................... 6-6
6.4 Related Application Notes.............................................................................................. 6-7
6.5 Revision History ............................................................................................................. 6-8
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39506-page 6-2 2000 Microchip Technology Inc.
6.1 Introduction
An 8 x 8 hardware multiplier is included in the ALU of the devices. By making the multiplication
a hardware operation, it completes in a single instruction cycle. This is an unsigned multiplication
that gives a 16-bit result. The result is stored into the 16-bit Product register (PRODH:PRODL).
The multiplier does not affect any flags in the ALUSTA register.
Making the 8 x 8 multiplier execute in a single cycle gives the following advantages:
• Higher computational throughput
• Reduces code size requirements for multiplication algorithms
The performance increase allows the device to be used in applications previously reserved for
Digital Signal Processors.
Table 6-1 shows a performance comparison between devices using the single cycle hardware
multiplier and performing the same function without the hardware multiplier.
Table 6-1: Performance Comparison
Routine Multiply Method
Program
Memory
(Words)
Cycles
(Max)
Time
@ 40 MHz @ 10 MHz @ 4 MHz
8 x 8 unsigned Without hardware multiplier 13 69 6.9 µs 27.6 µs 69 µs
Hardware multiply 1 1 100 ns 400 ns 1 µs
8 x 8 signed Without hardware multiplier 33 91 9.1 µs 36.4 µs 91 µs
Hardware multiply 6 6 600 ns 2.4 µs 6 µs
16 x 16 unsigned Without hardware multiplier 21 242 24.2 µs 96.8 µs 242 µs
Hardware multiply 24 24 2.4 µs 9.6 µs 24 µs
16 x 16 signed Without hardware multiplier 52 254 25.4 µs 102.6 µs 254 µs
Hardware multiply 36 36 3.6 µs 14.4 µs 36 µs
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39506-page 6-3
Section 6. Hardware 8x8 Multiplier
Hardware 8x8
Multiplier
6
6.2 Operation
Example 6-1 shows the sequence to do an 8 x 8 unsigned multiply. Only one instruction is
required when one argument of the multiply is already loaded in the WREG register.
Example 6-2 shows the sequence to do an 8 x 8 signed multiply. To account for the sign bits of
the arguments, each argument’s most significant bit (MSb) is tested and the appropriate subtractions
are done.
Example 6-1: 8 x 8 Unsigned Multiply Routine
Example 6-2: 8 x 8 Signed Multiply Routine
Example 6-3 shows the sequence to do a 16 x 16 unsigned multiply. Equation 6-1 shows the
algorithm that is used. The 32-bit result is stored in four registers, RES3, RES2, RES1 and RES0.
Equation 6-1: 16 x 16 Unsigned Multiplication Algorithm
MOVFF ARG1, WREG ;
MULWF ARG2 ; ARG1 * ARG2 ->
; PRODH:PRODL
MOVFF ARG1, WREG
MULWF ARG2 ; ARG1 * ARG2 ->
; PRODH:PRODL
BTFSC ARG2, SB ; Test Sign Bit
SUBWF PRODH, F ; PRODH = PRODH
; - ARG1
MOVFF ARG2, WREG
BTFSC ARG1, SB ; Test Sign Bit
SUBWF PRODH, F ; PRODH = PRODH
; - ARG2
RES3:RES2:RES1:RES0 = ARG1H:ARG1L • ARG2H:ARG2L
= (ARG1H • ARG2H • 2 16)+
(ARG1H • ARG2L • 2 8)+
(ARG1L • ARG2H • 2 8)+
(ARG1L • ARG2L)
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39506-page 6-4 2000 Microchip Technology Inc.
Example 6-3: 16 x 16 Unsigned Multiply Routine
Example 6-4 shows the sequence to do a 16 x 16 signed multiply. Equation 6-2 shows the algorithm
used. The 32-bit result is stored in four registers, RES3, RES2, RES1 and RES0. To
account for the sign bits of the arguments, each argument pairs’ most significant bit (MSb) is
tested and the appropriate subtractions are done.
Equation 6-2: 16 x 16 Signed Multiplication Algorithm
MOVFF ARG1L, WREG
MULWF ARG2L ; ARG1L * ARG2L ->
; PRODH:PRODL
MOVFF PRODH, RES1 ;
MOVFF PRODL, RES0 ;
;
MOVFF ARG1H, WREG
MULWF ARG2H ; ARG1H * ARG2H ->
; PRODH:PRODL
MOVFF PRODH, RES3 ;
MOVFF PRODL, RES2 ;
;
MOVFF ARG1L, WREG
MULWF ARG2H ; ARG1L * ARG2H ->
; PRODH:PRODL
MOVFF PRODL, WREG ;
ADDWF RES1, F ; Add cross
MOVFF PRODH, WREG ; products
ADDWFC RES2, F ;
CLRF WREG, F ;
ADDWFC RES3, F ;
;
MOVFF ARG1H, WREG ;
MULWF ARG2L ; ARG1H * ARG2L ->
; PRODH:PRODL
MOVFF PRODL, WREG ;
ADDWF RES1, F ; Add cross
MOVFF PRODH, WREG ; products
ADDWFC RES2, F ;
CLRF WREG, F ;
ADDWFC RES3, F ;
RES3:RES2:RES1:RES0
= ARG1H:ARG1L • ARG2H:ARG2L
= (ARG1H • ARG2H • 2 16) +
(ARG1H • ARG2L • 2 8) +
(ARG1L • ARG2H • 2 8) +
(ARG1L • ARG2L) +
(-1 • ARG2H<7> • ARG1H:ARG1L • 2 16)+
(-1 • ARG1H<7> • ARG2H:ARG2L • 2 16)
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39506-page 6-5
Section 6. Hardware 8x8 Multiplier
Hardware 8x8
Multiplier
6
Example 6-4: 16 x 16 Signed Multiply Routine
MOVFF ARG1L, WREG
MULWF ARG2L ; ARG1L * ARG2L ->
; PRODH:PRODL
MOVFF PRODH, RES1 ;
MOVFF PRODL, RES0 ;
;
MOVFF ARG1H, WREG
MULWF ARG2H ; ARG1H * ARG2H ->
; PRODH:PRODL
MOVFF PRODH, RES3 ;
MOVFF PRODL, RES2 ;
;
MOVFF ARG1L, WREG
MULWF ARG2H ; ARG1L * ARG2H ->
; PRODH:PRODL
MOVFF PRODL, WREG ;
ADDWF RES1, F ; Add cross
MOVFF PRODH, WREG ; products
ADDWFC RES2, F ;
CLRF WREG, F ;
ADDWFC RES3, F ;
;
MOVFF ARG1H, WREG ;
MULWF ARG2L ; ARG1H * ARG2L ->
; PRODH:PRODL
MOVFF PRODL, WREG ;
ADDWF RES1, F ; Add cross
MOVFF PRODH, WREG ; products
ADDWFC RES2, F ;
CLRF WREG, F ;
ADDWFC RES3, F ;
;
BTFSS ARG2H, 7 ; ARG2H:ARG2L neg?
GOTO SIGN_ARG1 ; no, check ARG1
MOVFF ARG1L, WREG ;
SUBWF RES2 ;
MOVFF ARG1H, WREG ;
SUBWFB RES3
;
SIGN_ARG1
BTFSS ARG1H, 7 ; ARG1H:ARG1L neg?
GOTO CONT_CODE ; no, done
MOVFF ARG2L, WREG ;
SUBWF RES2 ;
MOVFF ARG2H, WREG ;
SUBWFB RES3
;
CONT_CODE
:
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39506-page 6-6 2000 Microchip Technology Inc.
6.3 Design Tips
None.
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39506-page 6-7
Section 6. Hardware 8x8 Multiplier
Hardware 8x8
Multiplier
6
6.4 Related Application Notes
This section lists application notes that are related to this section of the manual. These application
notes may not be written specifically for the Enhanced family (that is, they may be written for
the Base-Line, the Mid-Range, or High-End families), but the concepts are pertinent, and could
be used (with modification and possible limitations). The current application notes related to the
H/W Multiplier modules are:
Title Application Note #
IEEE 754 Compliant Floating Point Routines AN575
Fixed Point Routines AN617
Floating Point Math Functions AN660
Note: Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
http://www.microchip.com/10/faqs/codeex/
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39506-page 6-8 2000 Microchip Technology Inc.
6.5 Revision History
Revision A
This is the initial released revision of the Enhanced MCE Hardware Multiplier module description.
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39507A-page 7-1
Memory
7
Section 7. Memory Organization
HIGHLIGHTS
This section of the manual contains the following major topics:
7.1 Introduction .................................................................................................................... 7-2
7.2 Program Memory ........................................................................................................... 7-3
7.3 Program Counter (PC) ................................................................................................... 7-6
7.4 Lookup Tables................................................................................................................ 7-9
7.5 Stack ............................................................................................................................ 7-12
7.6 Data Memory Organization.......................................................................................... 7-13
7.7 Return Address Stack .................................................................................................. 7-17
7.8 Initialization .................................................................................................................. 7-23
7.9 Design Tips .................................................................................................................. 7-24
7.10 Related Application Notes............................................................................................ 7-25
7.11 Revision History ........................................................................................................... 7-26
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39507A-page 7-2 2000 Microchip Technology Inc.
7.1 Introduction
There are two memory blocks in the memory map; program memory and data memory. Each
block has its own bus, so that access to each block can occur during the same instruction cycle.
The data memory can further be broken down into General Purpose RAM and the Special Function
Registers (SFRs). The operation of the SFRs that control the “core” are described here. The
SFRs used to control the peripheral modules are described in the section discussing each individual
peripheral module.
In addition, there are other registers used that are neither part of the program nor data memory
spaces. These registers are not directly addressable and include:
• return address stack
• fast return stack
Table 7-1 shows the program memory space used depending on the memory allocated, and
Table 7-2 shows the data memory space used.
Table 7-1: PIC18CXXX Program
Memory Ranges
Table 7-2: PIC18CXXX Data
Memory Ranges
Program
Memory
Program Memory
Address Range Data Memory Banks
1K x 8 0000h - 3FFh 64 0, 15
2K x 8 0000h - 7FFh 128 0, 15
4K x 8 0000h - FFFh 256 0, 15
8K x 8 0000h - 1FFFh 512 0-1, 15
12K x 8 0000h - 2FFFh 640 0-2, 15
16K x 8 0000h - 3FFFh 768 0-2, 15
24K x 8 0000h - 5FFFh 1024 0-3, 15
32K x 8 0000h - 7FFFh 1280 0-4, 15
48K x 8 0000h - BFFFh 1536 0-5,15
64K x 8 0000h - FFFFh 1792 0-6, 15
96K x 8 0000h - 17FFFh 2048 0-7, 15
128K x 8 0000h - 1FFFFh 2304 0-8, 15
160K x 8 0000h - 27FFFh 2560 0-9, 15
192K x 8 0000h - 2FFFFh 2816 0-10, 15
256K x 8 0000h - 3FFFFh 3072 0-11, 15
384K x 8 0000h - 5FFFFh 3328 0-12, 15
512K x 8 0000h - 7FFFFh 3584 0-13,15
768K x 8 0000h - BFFFFh 3840 0-14,15
1024K x 8 0000h - FFFFFh 3968 0-15
1536K x 8 0000h - 17FFFFh
2048K x 8 0000h - 1FFFFFh
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39507A-page 7-3
Section 7. Memory
Memory
7
7.2 Program Memory
Enhanced MCU devices have a 21-bit program counter capable of addressing 2 Mbytes
(1Mwords) of program memory space. The program memory contains instructions for execution
and data tables for storing fixed data. Data tables may be written once using table write instructions
and read as required, using the table read instructions.
The program space is implemented as a single contiguous block. The reset vector is at address
000000h, the high priority interrupt vector is at address 000008h, and the low priority interrupt
vector is at address 000018h (Figure 7-1).
CALL and GOTO instructions can address any location in the memory map, while the BRA and
RCALL instructions have a limited program memory reach (+1024, -1023 program memory word
locations). To allow the CALL and GOTO instructions to contain the entire address, it requires that
these instructions use 2 program memory words (2 word instruction).
Instructions are also available to move information between the data memory and the program
memory areas. These are called table operations. Table operations work with byte entities. This
is discussed in detail in the “Table Read/Table Write” section.
Figure 7-1: Program Memory Map and Stack for PIC18CXXX
PC<20:0>
Stack Level 1
Stack Level 31
Reset Vector
Low Priority Interrupt Vector
CALL,BSUB,RETURN
RETFIE,RETLW
21
0000h
0018h
On-chip
High Priority Interrupt Vector 0008h
User Memory Space
External/Unimplemented
1FFFFFh
200000h
Program Memory
(Read as ’0’ in
microcontroller mode)
Program Memory
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39507A-page 7-4 2000 Microchip Technology Inc.
7.2.1 Reset Vector
On any Enhanced MCU device, a reset forces the Program Counter (PC) to address 0h. This is
known as the “Reset Vector Address”, since this is the address that program execution will
branch to when a device reset occurs.
Any reset will also clear the contents of the PCLATU and PCLATH registers.
7.2.2 Interrupt Vectors
Two interrupt vectors are implemented; one for interrupts programmed as high priority and the
other for the interrupts programmed as low priority. The vector addresses are 08h for high priority
interrupts and 18h for low priority interrupts. If the interrupt priority is not used, all interrupts are
treated as high priority.
When an interrupt is acknowledged, the PC is forced to address 0008h or 0018h. This is known
as the “Interrupt Vector Address”. When the PC is forced to the interrupt vector, the PCLATU and
PCLATH registers are not modified. Once in the service interrupt routine (ISR), before any write
to the PC, the PCLATH register should be written with the value that will specify the desired location
in program memory. Before the PCLATH register is modified by the Interrupt Service Routine
(ISR), the contents of the PCLATH may need to be saved so it can be restored before returning
from the ISR.
7.2.3 Calibration Information
Some devices have calibration information stored in their program memory. This information is
programmed by Microchip when the device is under final test. The use of these values allows the
application to achieve better results. The calibration information is typically at the end of program
memory. These bytes can be accessed with the table read instructions.
Note: For windowed devices, write down all calibration values BEFORE erasing. This
allows the device’s calibration values to be restored when the device is re-programmed.
When possible, writing the values on the package is recommended.
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39507A-page 7-5
Section 7. Memory
Memory
7
7.2.4 Instructions in Program Memory
The program memory is addressed in bytes. Instructions are stored as two bytes or four bytes
in program memory. The least significant byte of an instruction word is always stored in a program
memory location with an even address (LSb = ’0’). Figure 7-2 shows an example of how
instruction words are stored in the program memory. To maintain alignment with instruction
boundaries, the PC increments in steps of 2 and the LSb will always read ’0’.
The CALL and GOTO instructions have an absolute program memory address embedded into the
instruction. Since instructions are always stored on word boundaries, the data contained in the
instruction is a word address. The word address is written to PC<20:1>, which accesses the
desired byte address in program memory. Instruction #2 in Figure 7-2 shows how the instruction
"GOTO 000006h’ is encoded in the program memory. Program branch instructions which encode
a relative address offset operate in the same manner. The offset value stored in a branch instruction
represents the number of single word instructions that the PC will be offset by. The “Instruction
Set” section provides further details of the instruction set.
Figure 7-2: Instructions in Program Memory
Word Address
High Byte Low Byte ↓
Program Memory
Byte Locations →
000000h
000002h
000004h
000006h
Instruction 1: MOVLW 055h 0Fh 55h 000008h
Instruction 2: GOTO 000006h EFh 03h 00000Ah
F0h 00h 00000Ch
Instruction 3: MOVFF 123h, 456h C1h 23h 00000Eh
F4h 56h 000010h
000012h
000014h
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39507A-page 7-6 2000 Microchip Technology Inc.
7.3 Program Counter (PC)
The Program Counter (PC) specifies the address of the instruction to fetch for execution. The PC
is 21-bits wide and addresses each byte (rather than words) in the program memory. The low
byte is called the PCL register (PC<7:0>). This register is readable and writable. The high byte
is called the PCH register (PC<15:8>). This register is not directly readable or writable. Updates
to the PCH register may be performed through the PCLATH register.
The upper byte is called the PCU register (PC<20:16>). The PCU register is not directly readable
or writable. Updates to the PCU register may be performed through the PCLATU register. The
PC structure is PCU<4:0>:PCH<7:0>:PCL<7:0> and is equivalent to PC<20:0>.
Figure 7-3 shows the interaction of the PCU, PCH, and PCL registers with the PCLATU and
PCLATH registers.
Figure 7-3: Program Counter Structure
The low byte of the PC (PCL<7:0>) is mapped in the data memory. PCL is readable and writable
just as is any other register. PCU and PCH are the upper and high bytes of the PC respectively,
and are not directly addressable. Registers PCLATU<4:0> (PC upper latch) and PCLATH<7:0>
(PC high latch) are used as holding latches for the high bytes of the PCU and PCH, and are
mapped into data memory. The user can read and write PCH through PCLATH and PCU through
PCLATU. Any time PCL is read, the current contents of PCH and PCU are transferred to PCLATH
and PCLATU, respectively. Any time PCL is written to, the contents of PCLATH and PCLATU are
transferred to PCH and PCU, respectively.
The PC addresses bytes rather than words in the program memory. Because the PC must
access the instructions in program memory on an even byte boundary, the LSb of the PC is a
forced '0' and the PC increments by two for each instruction. The LSb bit of the PCL is readable
but not writable. Any write to the LSb is ignored.
Figure 7-4 shows the four situations for the loading of the PC. Situation 1 shows how the PC is
loaded on a write to PCL (PCLATH<4:0> → PCH). Situation 2 shows how the PC is loaded during
a GOTO instruction (PCLATH<4:3> → PCH). Situation 4 shows how the PC is loaded during a
CALL instruction (PCLATH<4:3> → PCH), with the PC loaded (PUSHed) onto the Top of Stack.
Situation 6 shows how the PC is loaded during one of the return instructions where the PC is
loaded (POPed) from the Top of Stack.
PC
21 15 16 0 8 7
PCLATU PCLATH
PCU PCH PCL
23 20
Reserved. Maintain these bits cleared.
Note: The values in PCLATU and PCLATH do not always reflect the current value in PCU
and PCH. When needing to modify the current Program Counter (PC) value, first
read the PCL register to update the values in the PCLATU and PCLATH registers.
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39507A-page 7-7
Section 7. Memory
Memory
7
Figure 7-4: Loading of PC In Different Situations
PC
ALU Result
8
PCL
Situation 1 - Instruction with PCL as destination
Situation 2 - GOTO Instruction
PCLATU PCLATH
20 8 7 0 15 PCH 16 PCU
PCL
20 8 7 0 15 PCH
16
PCU 9 1
0
K19:K8
(2nd word
K7:K0
(1st word
of instruction) of instruction)
STACK (21-bits x 31)
Top of STACK
STACK (21-bits x 31)
Top of STACK
20 8 7 0 16 1 15
ADDR
Situation 3 - BRA Instruction in Conditional Branch Instruction STACK (21-bits x 31)
Top of STACK
Offset
from
Instruction
0
PCU PCH PCL
Situation 4 - CALL Instruction
20
PCL
20 8 7 0 15
PCH
16
PCU
9 1
0
K19:K8
(2nd word
K7:K0
(1st word
STACK (21-bits x 31)
Top of STACK
of instruction) of instruction)
Note: PCLATU and PCLATH are not updated with the contents of PCH.
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39507A-page 7-8 2000 Microchip Technology Inc.
Figure 7-4: Loading of PC In Different Situations (Continued)
Situation 6 - RETURN, RETFIE, or RETLW Instruction
PCL
20 8 7 0 15
PCH
16
PLU
9 1
PCLATU PCLATH
STACK (21-bits x 31)
Top of STACK
Situation 5 - RCALL Instruction
20 8 7 0 16 15 1
ADDR
Offset
from
Instruction
0
PCU PCH PCL
STACK (21-bits x 31)
Top of STACK
21
Note: PCLATU and PCLATH are not updated with the contents of PCH.
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39507A-page 7-9
Section 7. Memory
Memory
7
7.3.1 Computed GOTO
A computed GOTO is accomplished by adding an offset to the program counter (ADDWF PCL).
When doing a table read using a computed GOTO method, care should be exercised if the table
location crosses a PCL memory boundary (each 256 byte block) and the PCH memory boundary
(each 64Kbyte block).
A lookup table can be formed with an ADDWF PCL instruction and a group of RETLW 0xnn
instructions. WREG is loaded with an offset into the table before executing a call to that table.
The first instruction of the called routine is the ADDWF PCL instruction. The next instruction executed
will be one of the RETLW 0xnn instructions that returns the value 0xnn to the calling function.
Since the Program Counter is a byte counter (instead of a word counter), adds to the PCL allow
a table size of 128 entries before the PCLATH needs to be modified.
In this method of storing tables in PIC18CXXX devices, only one data value may be stored in
each instruction location, and room on the return address stack is required. A better method of
storing data in program memory is through the use of table reads and writes. Two bytes of data
can now be stored in each instruction location.
7.4 Lookup Tables
Look-up tables instructions are implemented two ways in the PIC18CXXX devices. The computed
goto is compatible with the PIC16CXXX and PIC17CXXX parts. Code written for those
devices will run on the PIC18CXXX devices with minor modifications.
Table read instructions are implemented on the PIC17CXXX and PIC18CXXX devices. However,
table operations on the PIC18CXXX work differently than on the PIC17CXXX.
7.4.1 Table Reads/Table Writes
Lookup table data may be stored 2 bytes per program word. By using TBLPTR and TABLAT, data
may be retrieved from program memory one byte at a time as required.
Table writes to program memory can be executed as many times as desired. Remember that the
technology of the program memory determines the outcome of the table write. Table writes to
EPROM memory allow the program memory cell to go from a ’1’ state to a ’0’ state, but not the
other direction. FLASH memory allows the cell to go from a ’1’ to a ’0’ and a ’0’ to a ’1’ (though
typically a program memory word or block location is always written).
Note: Since the Program Counter is 21-bits, the uppercase PCLATU register may also
need to be modified when doing computed gotos.
Note: Any write to the Program Counter (PCL) will cause the contents of PCLATU and
PCLATH to be loaded into PCU and PCH, respectively.
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39507A-page 7-10 2000 Microchip Technology Inc.
Example 7-1: PIC18CXXX Table Lookup
Example 7-2: PIC17CXXX Table Lookup
MOVLW BYTE_COUNT ; Load the Byte Count value
MOVWF CNTR ; into CNTR
;
;; MOVLW UPPER(TBL_ADDR) ; Load the Table Address
;; MOVWF TBLPTRU ; (on POR TBLPTRU = 0, so
;; ; loading TBLPTRU is not
;; ; required for conversions)
MOVLW HIGH(TBL_ADDR) ; Load the Table Address
MOVWF TBLPTRH ;
MOVLW LOW(TBL_ADDR) ;
MOVWF TBLPTRL ;
LOOP1 TBLRD*+ ; Read value into TABLAT,
; Increment TBLPTR
MOVFF TABLAT, POSTINC0 ; Copy byte to RAM @ FSR0
; Increment FSR0
DECFSZ CNTR ; Read Byte Count locations
GOTO LOOP1 ; Read next Byte
MOVLW WORD_COUNT ; Load the Word Count value
MOVWF CNTR ; into CNTR
;
MOVLW HIGH(TBL_ADDR) ; Load the Table Address
MOVWF TBLPTRH ;
MOVLW LOW(TBL_ADDR) ;
MOVWF TBLPTRL ;
TABLRD 0, 1, DUMMY ; Dummy read,
; Updates TABLATH
; Increments TBLPTR
LOOP1 TLRD 1, INDF0 ; Read HI byte in TABLATH
TABLRD 0, 1, INDF0 ; Read LO byte in TABLATL,
; update TABLATH:TABLATL,
; and increment TBLPTR
DECFSZ CNTR ; Read Word Count locations
GOTO LOOP1 ; Read next word
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39507A-page 7-11
Section 7. Memory
Memory
7
Example 7-3: PIC16CXXX Table Lookup
CLRF CNTR ;
TABLELP
MOVF CNTR, W ; Place value in
; WREG register
CALL TABLE1
MOVWF INDF
INCF FSR
INCF CNTR
BTFSS CNTR, 3 ; CNTR = 00001000b?
GOTO TABLE_LP
:
:
TABLE1
ADDWF PCL ; Enusure that table does
; not cross 256 byte
; page boundary.
RETLW ’G’
RETLW ’O’
RETLW ’ ’
RETLW ’M’
RETLW ’C’
RETLW ’H’
RETLW ’P’
RETLW ’!’
39500 18C Reference Manual.book Page 11 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39507A-page 7-12 2000 Microchip Technology Inc.
7.5 Stack
The stack allows a combination of up to 31 program calls and interrupts to occur. The stack contains
the return address from this branch in program execution.
Enhanced MCU devices have an 31-level deep x 21-bit wide hardware stack. The stack space
is not part of either program or data space and the stack pointer is not readable nor writable. The
PC is PUSHed onto the stack when a CALL instruction is executed or an interrupt causes a
branch. The stack is POPed in the event of a RETURN, RETLW or a RETFIE instruction execution.
PCLATH is not modified when the stack is PUSHed or POPed.
After the PC is PUSHed onto the stack 31 times (without POPing any values off the stack), the
32nd PUSH over-writes the value from the 31st PUSH and sets the STKFUL bit while the
STKPTR remains at 11111b. The 33rd PUSH overwrites the 32nd PUSH (and so on) while
STKPTR remains 11111b. When the stack overflow enable bit is enabled a device reset will
occur.
Figure 7-5: Stack Modification
Whenever the program branches, the return address is saved to the stack. Such branches
include CALL, RCALL, or an interrupt. The stack pointer is incremented and PC<20:1> is
PUSHed onto the return stack. PC<0> is always assumed to be 0. When a branch return is executed,
the top of the stack is POPed to the Program Counter and the stack pointer is decremented.
PCLATU and PCLATH are not affected during these branches.
The PC is word incremented by 2 after each instruction fetch during Q1 unless:
• Modified by a GOTO, CALL, RCALL, RETURN, RETLW, RETFIE, or branch instruction
• Modified by an interrupt response
• Due to a write to PCL by an instruction
Skips are equivalent to a forced NOP cycle at the skipped address.
Top of Stack (1)
STACK
STACK POINTER
11111b
00000b
Note1:The stack pointer value does not increment past 11111b.
39500 18C Reference Manual.book Page 12 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39507A-page 7-13
Section 7. Memory
Memory
7
7.6 Data Memory Organization
Data memory is made up of the Special Function Registers (SFR) area and the General Purpose
Registers (GPR) area. The SFRs are used for control and status of the microcontroller and
peripheral functions, while GPRs are the general area for user data storage and scratch pad
operations.
Each register has a 12-bit address. This allows up to 4096 bytes of data memory. This memory
is partitioned into 16 banks of 256 bytes that contain the General Purpose Registers (GPRs) and
Special Function Registers (SFRs).
The data memory can be banked for both the GPR and SFR areas. Banking requires the use of
BSR Register. Figure 7-6 shows the data memory map organizations, while Table 7-2 shows
which banks will be used depending on the memory size of the devices.
SFRs start at the last location of Bank 15 (0xFFF) and work up. Once the SFR space ends, any
lower locations in that bank may be implemented as GPRs. GPRs start at the first location of
Bank 0 (0h) and work down. Any read of an unimplemented location will read as ’0’s.
The Instruction set and architecture allows operations across all banks. To move values from one
register to another register, the MOVFF instruction can be used. This is a two word / two cycle
instruction.
The entire data memory can be accessed either directly or indirectly. Direct addressing may
require the use of the BSR register. Indirect addressing requires the use of the File Select Registers
(FSRs). Each FSR holds a 12-bit value that can access any location in the Data Memory
map.
To ensure that commonly used registers (SFRs and select GPRs) can be accessed in a single
cycle, regardless of the current BSR values, an Access Bank is implemented. This is explained
in Section 7.6.1.
The GPR area is banked to allow greater than 256 bytes of general purpose RAM to be
addressed. SFRs are for the registers that control the peripheral and core functions.
Figure 7-6: The Data Memory Map and the Access Bank
Bank 0
Bank 1
Bank 14
Bank 15
BSR<3:0> Data Memory Map
= 0000b
= 0001b
= 1110b
= 1111b
00h
FFh
00h
FFh
Access Bank
When a = 0,
the BSR is ignored and this Access
Bank is used.
The first 128 bytes are General Purpose
RAM (from Bank 0).
The second 128 bytes are Special
Function Registers (from Bank 15).
See Section 7.6.1.
When a = 1,
the BSR is used to specify the RAM
location that the instruction uses.
Bank n
39500 18C Reference Manual.book Page 13 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39507A-page 7-14 2000 Microchip Technology Inc.
7.6.1 Access Bank
The Access Bank is an architectural enhancement that is very useful for C compiler code optimization.
The techniques used by the C compiler may also be useful for programs written in assembly.
This data memory region can be used for:
• Intermediate computational values
• Local variables of subroutines
• Faster context saving/switching of variables
• Common variables
• Faster evaluation/control of SFRs (no banking)
The Access Bank is comprised of the upper portion of Bank 15 (SFRs) and the lower portion of
Bank 0 (GPR). These two sections will be referred to as Access RAM High and Access RAM Low,
respectively. Figure 7-6 indicates the Access RAM areas. The actual size of memory used from
Bank 0 and Bank 15 depends on the specific device. When appropriate, devices will use
128 bytes from Bank 0 (GPR) and 128 bytes from Bank 15 (SFR). In larger devices with more
SFRs, the GPR Access bank size may be reduced to allocate that space to SFRs Access space.
A bit in the instruction word specifies if the operation is to occur in the bank specified by the BSR
register or in the Access Bank. This bit is denoted by the ’a’ bit (for access bit).
When forced in the Access Bank (a = ’0’), the last address in Access RAM Low is followed by the
first address in Access RAM High. Access RAM High maps the Special Function Registers so
that these registers can be accessed without any software overhead. This is useful for testing
status flags, modifying control bits, software stacks, and context saving of registers.
7.6.2 General Purpose Registers (GPR)
Enhanced MCU devices may have banked memory in the GPR area. GPRs are not initialized by
a Power-on Reset and are unchanged on all other resets.
The register file can be accessed either directly, or indirectly, using the File Select Register
(FSR). Some devices have areas that are shared across the data memory banks, so a read/write
to that area will appear as the same location (value), regardless of the current bank. We refer to
this area as the Common RAM.
Data RAM is available for use as GPR registers by all instructions. Most banks of data memory
contain only GPR registers starting with bank 0. The top half of bank 15 (0xF80 to 0xFFF) contains
SFRs.
Each data memory bank has 256 locations and can be addressed using an 8-bit address.
39500 18C Reference Manual.book Page 14 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39507A-page 7-15
Section 7. Memory
Memory
7
7.6.3 Special Function Registers
The SFRs are used by the CPU and peripheral modules for controlling the desired operation of
the device. These registers are implemented as static RAM.
The SFRs can be classified into two sets; those associated with the “core” function and those
related to the peripheral functions. Those registers related to the “core” are described in this section,
while those related to the operation of the peripheral features are described in the section
of that peripheral feature.
The SFRs are typically distributed among the peripherals whose functions they control.
If the SFRs do not use all the available locations on a particular device, the unused locations will
be unimplemented and read as '0's. In devices that have a high integration of features, some of
the SFRs may be in banks other than bank 15. See Figure 7-7 for addresses for the SFRs. As
new devices are introduced with new SFRs, this register map will be updated. Please refer to the
device data sheet for that device’s register map.
Figure 7-7: Special Function Register Map
FFFh TOSU FDFh INDF2 (2) FBFh CCPR1H F9Fh IPR1
FFEh TOSH FDEh POSTINC2 (2) FBEh CCPR1L F9Eh PIR1
FFDh TOSL FDDh POSTDEC2 (2) FBDh CCP1CON F9Dh PIE1
FFCh STKPTR FDCh PREINC2 (2) FBCh CCPR2H F9Ch —
FFBh PCLATU FDBh PLUSW2 (2) FBBh CCPR2L F9Bh —
FFAh PCLATH FDAh FSR2H FBAh CCP2CON F9Ah —
FF9h PCL FD9h FSR2L FB9h — F99h —
FF8h TBLPTRU FD8h STATUS FB8h — F98h —
FF7h TBLPTRH FD7h TMR0H FB7h — F97h —
FF6h TBLPTRL FD6h TMR0L FB6h — F96h TRISE
FF5h TABLAT FD5h T0CON FB5h — F95h TRISD
FF4h PRODH FD4h — FB4h — F94h TRISC
FF3h PRODL FD3h OSCCON FB3h TMR3H F93h TRISB
FF2h INTCON FD2h LVDCON FB2h TMR3L F92h TRISA
FF1h INTCON2 FD1h WDTCON FB1h T3CON F91h —
FF0h INTCON3 FD0h RCON FB0h — F90h —
FEFh INDF0 (2) FCFh TMR1H FAFh SPBRG F8Fh —
FEEh POSTINC0 (2) FCEh TMR1L FAEh RCREG F8Eh —
FEDh POSTDEC0 (2) FCDh T1CON FADh TXREG F8Dh LATE
FECh PREINC0 (2) FCCh TMR2 FACh TXSTA F8Ch LATD
FEBh PLUSW0 (2) FCBh PR2 FABh RCSTA F8Bh LATC
FEAh FSR0H FCAh T2CON FAAh — F8Ah LATB
FE9h FSR0L FC9h SSPBUF FA9h — F89h LATA
FE8h WREG FC8h SSPADD FA8h — F88h —
FE7h INDF1 (2) FC7h SSPSTAT FA7h — F87h —
FE6h POSTINC1 (2) FC6h SSPCON1 FA6h — F86h —
FE5h POSTDEC1 (2) FC5h SSPCON2 FA5h — F85h —
FE4h PREINC1 (2) FC4h ADRESH FA4h — F84h PORTE
FE3h PLUSW1 (2) FC3h ADRESL FA3h — F83h PORTD
FE2h FSR1H FC2h ADCON0 FA2h IPR2 F82h PORTC
FE1h FSR1L FC1h ADCON1 FA1h PIR2 F81h PORTB
FE0h BSR FC0h — FA0h PIE2 F80h PORTA
Note 1: Unimplemented-registers are read as ’0’.
2: This is not a physical register.
39500 18C Reference Manual.book Page 15 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39507A-page 7-16 2000 Microchip Technology Inc.
7.6.4 Bank Select Register (BSR)
The need for a large general purpose memory space dictated a general purpose RAM banking
scheme. A Special Function Register (named BSR) selects the currently active general purpose
RAM bank. Only the lower middle of the BSR register (BSR<3:0>) is used. This allows access to
potentially 16 banks. Direct long addressing mode is limited to 12-bit addresses. This also allows
accesses to any of the 16 banks. BSR<7:4> will always read 0’s, and writes have no effect. All
data memory is implemented as static RAM.
A MOVLB bank instruction has been provided in the instruction set to assist in selecting banks.
If the currently selected bank is not implemented, any read will return all '0's, and all writes are
ignored and the STATUS register bits will be set/cleared as appropriate for the instruction performed.
39500 18C Reference Manual.book Page 16 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39507A-page 7-17
Section 7. Memory
Memory
7
7.7 Return Address Stack
The Return Address Stack allows any combination of up to 31 program calls and interrupts to
occur. The PC (Program Counter) is PUSHed onto the stack when a CALL or RCALL instruction
is executed or an interrupt is acknowledged. The PC value is pulled off the stack on a RETURN,
RETLW, or a RETFIE instruction. PCLATU and PCLATH are not affected by any of the return
instructions.
The stack operates as a 31 word by 21-bit RAM and a 5-bit stack pointer (STKPTR), with the
stack pointer initialized to 00000b after all resets. There is no RAM associated with stack pointer
location 00000b. This is only a reset value. During a CALL type instruction causing a PUSH onto
the stack, the stack pointer is first incremented and the RAM location pointed to by the stack
pointer is written with the contents of the PC. During a RETURN type instruction causing a POP
from the stack, the contents of the RAM location pointed to by the STKPTR register are transferred
to the PC and then the stack pointer is decremented.
The stack space is not part of either program or data space and the stack pointer is neither readable
nor writable. The address on the top of the stack is readable and writable through SFR registers.
Data can also be PUSHed to or POPed from the stack using the top-of-stack SFRs. Status
bits indicate if the stack pointer attempts to exceed the 31 levels provided. The stack does not
wrap when the stack is PUSHed greater than 31 times.
Figure 7-8: Return Address Stack and Associated Registers
7.7.1 Top-Of-Stack Access
The Top-of-Stack (TOS) is readable and writable. Three register locations, TOSU, TOSH and
TOSL, hold the contents of the stack location pointed to by the STKPTR register. This allows
users to implement a software stack if necessary. After a CALL, RCALL or interrupt, the software
can read the PUSHed value by reading the TOSU, TOSH and TOSL registers. These values can
be placed on a user defined software stack. At return time, the software can replace the TOSU,
TOSH and TOSL and do a return.
The user must disable the global interrupt enable bits during this time to prevent inadvertent
stack operations.
0x001A34
11111
11110
11101
...
...
...
00011
00010
00001
00000
00010
Return Address Stack
Top of Stack
0x000D58
TOSU TOSH TOSL
0x00 0x1A 0x34
STKPTR<4:0>
Note: The user must disable interrupts when manipulating the stack.
39500 18C Reference Manual.book Page 17 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39507A-page 7-18 2000 Microchip Technology Inc.
7.7.2 PUSH and POP Instructions
Since the Top-of-Stack (TOS) is readable and writable, the ability to PUSH values onto the stack
and pull values off the stack without disturbing normal program execution is a desirable option.
To PUSH the current PC value onto the stack, a PUSH instruction can be executed. This will increment
the stack pointer and load the current PC value onto the stack. TOSU, TOSH, and TOSL
can then be modified to place data on the stack instead of a return address. This data may be a
new return address. This may be done in the operation of a Real Time Operating System
(RTOS).
The ability to pull the TOS value off of the stack and replace it with the value that was previously
PUSHed onto the stack, without disturbing normal execution, is achieved by using the POP
instruction. The POP instruction discards the current TOS by decrementing the stack pointer. The
previous value PUSHed onto the stack then becomes the TOS value.
Example 7-4: Using the PUSH Instruction
Example 7-5: Using the POP Instruction
MOVLW Dummy_TOSU ;
MOVWF TOSU ;
MOVLW Dummy_TOSH ;
MOVWF TOSH ;
MOVLW Dummy_TOSL ;
MOVWF TOSL ;
PUSH ;
MOVFF TOSU, PREINC1 ;
MOVFF TOSH, PREINC1 ;
MOVFF TOSL, PREINC1 ;
POP ;
39500 18C Reference Manual.book Page 18 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39507A-page 7-19
Section 7. Memory
Memory
7
7.7.3 Return Stack Pointer (STKPTR)
The STKPTR register contains the return stack pointer value and the overflow and underflow bits.
The stack overflow bit (STKFUL) and underflow bit (STKUNF) allow software verification of a
stack condition. The STKFUL and STKUNF bits are cleared only after a POR reset.
After the PC is PUSHed onto the stack 31 times (without POPing any values off the stack), the
32nd PUSH over-writes the value from the 31st PUSH and sets the STKFUL bit, while the
STKPTR remains at 11111b. The 33rd PUSH overwrites the 32nd PUSH (and so on), while
STKPTR remains 11111b.
After the stack is POPed enough times to unload the stack, the next POP will return a value of
zero to the PC and set the STKUNF bit while the STKPTR remains at 00000b. The next POP
returns zero again (and so on), while STKPTR remains 00000b.
The stack pointer can be accessed through the STKPTR register. The user may read and write
the stack pointer values. This can be used by a Real Time Operating System (RTOS) for return
stack maintenance. Figure 7-8 shows the STKPTR register. The value of the stack pointer will be
0 through 31. At reset, the stack pointer value will be 0. The stack pointer will increment when
PUSHing and will decrement when POPing.
7.7.4 Stack Full/Underflow Resets
At the user’s option, the overflow and underflow can cause a device reset to interrupt the program
code. The reset is enabled with a configuration bit, STVREN. When the STVREN bit is disabled,
a full or underflow condition will set the appropriate STKFUL or STKUNF bit but not cause a reset.
When the STVREN bit is enabled, a overflow or underflow will set the appropriate STKFUL or
STKUNF bit and then cause a device reset very similar in nature to the WDT reset. In either case,
the STKFUL or STKUNF bits are only cleared by user software or a POR reset.
7.7.5 Fast Register Stack
A "fast interrupt return" option is available for interrupts. A fast register stack is provided for the
STATUS, WREG, and BSR registers and are only one in depth. The stack is neither readable nor
writable and is loaded with the current value of the corresponding register when the processor
vectors for an interrupt. The values in the registers are then loaded back into the working registers
if the fast return instruction is used to return from the interrupt.
Low or high priority interrupt PUSHes values into the stack registers. If both low and high priority
interrupts are enabled, the stack registers cannot be used reliably for low priority interrupts. A
high priority interrupt, if one occurs while servicing a low priority interrupt, will overwrite the stack
registers stored by the low priority interrupt.
If high priority interrupts are not disabled during low priority interrupts, users must save the key
registers in software during a low priority interrupt.
If no interrupts are used, the fast register stack can be used to restore the STATUS, WREG and
BSR registers at the end of a subroutine call. To use the fast register stack for a subroutine call,
a fast call instruction must be executed.
Note: Returning a zero to the PC on an underflow has the effect of vectoring the program
to the reset vector, where the stack conditions can be verified and appropriate
actions can be taken.
39500 18C Reference Manual.book Page 19 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39507A-page 7-20 2000 Microchip Technology Inc.
7.7.6 Indirect Addressing, INDF, and FSR Registers
Indirect addressing is a mode of addressing data memory where the data memory address in
the instruction is not fixed. An SFR register is used as a pointer to the data memory location that
is to be read or written. Since this pointer is in RAM, the contents can be modified by the program.
This can be useful for data tables in the data memory and for software stacks. Figure 7-9
shows the operation of indirect addressing. This shows the moving of the value to the data
memory address specified by the value of the FSR register.
Indirect addressing is possible by using the INDF register. Any instruction using the INDF register
actually accesses the register pointed to by the File Select Register, FSR. Reading the INDF register
itself indirectly (FSR = '0') will read 00h. Writing to the INDF register indirectly results in a
no-operation (although status bits may be affected). The FSR register contains a 12-bit address,
which is shown in Figure 7-9.
Figure 7-9: FSR Operation (Indirect Addressing)
There are three indirect addressing registers. To address the entire Data Memory space (4096
bytes), these registers are 12 bits wide. To store the 12 bits of addressing information, two 8-bit
registers are required. These indirect addressing registers are:
1. FSR0: composed of FSR0H:FSR0L
2. FSR1: composed of FSR1H:FSR1L
3. FSR2: composed of FSR2H:FSR2L
In addition, there are registers INDF0, INDF1 and INDF2, which are not physically implemented.
Reading or writing to these registers activates indirect addressing, with the value in the corresponding
FSR register being the address of the data.
If an instruction writes a value to INDF0, the value will be written to the address pointed to by
FSR0H:FSR0L. A read from INDF1 actually reads the data from the address pointed to by
FSR1H:FSR1L. INDFn can be used in code anywhere an operand can be used.
If the INDF0, INDF1 or INDF2 register is read indirectly via an FSR, all '0's are read (Zero bit is
set). Similarly, if INDF0, INDF1or INDF2 is written to indirectly, the operation will be equivalent to
a NOP, and the STATUS bits are not affected.
Opcode Address
File Address = INDF
FSR
Instruction
Executed
Instruction
Fetched
RAM
Opcode File
12 12
12
BSR<3:0>
4 8
39500 18C Reference Manual.book Page 20 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39507A-page 7-21
Section 7. Memory
Memory
7
7.7.6.1 Indirect Addressing Operation
Each FSR register has an INDF register plus four addresses associated with it. The same INDFn,
and FSRnH:FSRnL registers are used, but depending on the INDFn address selected, the
FSRnH:FSRnL registers may be modified.
When a data access is done to the one of the five INDFn locations, the address selected will configure
the FSRn register to:
• Do nothing to FSRn after an indirect access (no change) - INDFn
• Auto-decrement FSRn after an indirect access (post-decrement) - POSTDECn
• Auto-increment FSRn after an indirect access (post-increment) - POSTINCn
• Auto-increment FSRn before an indirect access (pre-increment) - PREINCn
• Use the value in the WREG register as an offset to FSRn. Do not modify the value of the
WREG or the FSRn register after an indirect access (no change) - PLUSWn
When using the auto-increment or auto-decrement features, the effect on the FSR is not reflected
in the STATUS register. For example, if the indirect address causes the FSR to equal '0', the Z
bit will not be set.
Incrementing or decrementing an FSR affects all 12 bits. That is, when FSRnL overflows from an
increment, FSRnH will be incremented automatically.
Adding these features allows the FSRn to be used as a stack pointer in addition to its uses for
table operations in data memory.
Each FSR has an address associated with it that performs an indexed indirect access. When a
data access to this INDFn location (PLUSWn) occurs, the FSRn is configured to add the signed
value in the WREG register and the value in FSR to form the address before an indirect access.
The FSR value is not changed.
If an FSR register contains a value that points to one of the INDFn, an indirect read will read 00h
(Zero bit is set), while an indirect write will be equivalent to a NOP (STATUS bits are not affected).
If an indirect addressing operation is done where the target address is an FSRnH or FSRnL register,
the write operation will dominate over the pre- or post-increment/decrement functions.
Figure 7-10 shows the interaction of the FSR register and the data memory.
Figure 7-10: FSR Operation (Indirect Addressing)
Note: Accessing the PLUSWn address causes indexed indirect access. The addressed
register is the addition of the value in the FSRn register and the SIGNED value in
the WREG register.
11 FSRn 0 Bank0
Bank1
Bank15
0h
1h
Bank
Fh
39500 18C Reference Manual.book Page 21 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39507A-page 7-22 2000 Microchip Technology Inc.
Example 7-6 shows a simple use of indirect addressing to clear RAM (locations 20h-2Fh) in a
minimum number of instructions. A similar concept could be used to move a defined number of
bytes (block) of data to the USART transmit register (TXREG). The starting address of the block
of data to be transmitted could easily be modified by the program.
Example 7-6: Indirect Addressing
CLRF FSR1H ; Clear High byte of FSR
MOVLW 0x20 ; Load Low byte of 20h
MOVWF FSR1L ;
NEXT CLRF POSTINC1 ; Clear register and the
; increment
BTFSS FSR1L, 4 ;
GOTO NEXT ;
CONTINUE ;
:
39500 18C Reference Manual.book Page 22 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39507A-page 7-23
Section 7. Memory
Memory
7
7.8 Initialization
Example 7-7 shows how the bank switching occurs for direct addressing, while Example 7-8
shows some code to do initialization (clearing) of General Purpose RAM.
Example 7-7: Bank Switching
Example 7-8: RAM Initialization
CLRF BSR ; Clear BSR register (Bank0)
: ;
BSF BSR, 0 ; Bank1
: ;
BCF BSR, 0 ; Bank0
: ;
MOVLW 0x06 ;
MOVWF BSR ; Bank6
: ;
BCF BSR, 2 ; Bank2
: ;
BCF BSR, 1 ; Bank0
CLRF FSR1H
CLRF FSR1L
CLR_LP CLRF POSTINC1 ; Clear location, increment
MOVLW 0x0F ; Bank is FSR1H:FSR1L
SUBWF FSR1H,W ; Are we now in Bank 15?
BNZ CLR_LP ; NO, continue to clear GPRs
CONTINUE ;
:
:
39500 18C Reference Manual.book Page 23 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39507A-page 7-24 2000 Microchip Technology Inc.
7.9 Design Tips
Question 1: I need to initialize RAM to ’0’s. What is an easy way to do that?
Answer 1:
Example 7-8 shows this. If the device you are using does not use all 15 data memory banks, the
value to compare FSR1H against will need to be modified.
Question 2: I want to convert from a PIC16C77 which has 368 bytes of RAM (across 4
banks). What is the best way to remap this memory?
Answer 2:
In devices where the Access GPR region is greater or equal to 128 bytes and Bank 1 contains
256 bytes of GPR, the RAM should be partitioned with the RAM in Bank0 at locations 0x00 to
0x7F and all of Bank1. This allows a total of 384 bytes, which is larger than the 368 bytes in the
PIC16C77. Now the BSR can be loaded with 0x01 (pointing to Bank1). All memory access are
now either in Bank1 or the Access RAM, so no bank switching is required.
39500 18C Reference Manual.book Page 24 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39507A-page 7-25
Section 7. Memory
Memory
7
7.10 Related Application Notes
This section lists application notes that are related to this section of the manual. These application
notes may not be written specifically for the Enhanced family (that is they may be written for
the Base-Line, the Mid-Range, or High-End families), but the concepts are pertinent, and could
be used (with modification and possible limitations). The current application notes related to the
Memory Organization are:
Title Application Note #
Implementing a Table Read AN556
Note: Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
http://www.microchip.com/10/faqs/codeex/
39500 18C Reference Manual.book Page 25 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39507A-page 7-26 2000 Microchip Technology Inc.
7.11 Revision History
Revision A
This is the initial released revision of the Enhanced MCU Memory Organization description.
39500 18C Reference Manual.book Page 26 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39508-page 8-1
Table Write
Table Read/
8
HIGHLIGHTS
This section of the manual contains the following major topics:
8.1 Introduction .................................................................................................................... 8-2
8.2 Control Registers ........................................................................................................... 8-3
8.3 Program Memory ........................................................................................................... 8-6
8.4 Enabling Internal Programming ................................................................................... 8-12
8.5 External Program Memory Operation .......................................................................... 8-12
8.6 Initialization .................................................................................................................. 8-13
8.7 Design Tips .................................................................................................................. 8-14
8.8 Related Application Notes............................................................................................ 8-15
8.9 Revision History ........................................................................................................... 8-16
Section 8. Table Read/Table Write
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39508-page 8-2 2000 Microchip Technology Inc.
8.1 Introduction
Enhanced devices have two memory spaces. The program memory space and the data memory
space. The program memory space is 16 bits wide, while the data memory space is 8 bits wide.
Table Reads and Table Writes have been provided to move data between these two memory
spaces through an 8-bit register (TABLAT).
The operations that allow the processor to move data between the data and program memory
spaces are:
• Table Read (TBLRD)
• Table Write (TBLWT)
Table Read operations retrieve data from program memory and place it into the data memory
space. Figure 8-1 shows the operation of a Table Read with program and data memory.
Table Write operations store data from the data memory space into program memory. Figure 8-2
shows the operation of a Table Write with program and data memory.
Table operations work with byte entities. A table block containing data is not required to be word
aligned, so a table block can start and end at any byte address. If Enhanced MCU instructions
are being written to program memory, these instructions must be word aligned.
Figure 8-1: Table Read Operation
Figure 8-2: Table Write Operation
TABLE POINTER (1) TABLE LATCH (8-bit)
Program Memory
TBLPTRH TBLPTRL TABLAT
Program Memory Address
(TBLPTR)
TBLPTRU
Instruction: TBLRD*
Note 1: Table Pointer points to a byte in
program memory.
TABLE POINTER (1) TABLE LATCH (8-bit)
Program Memory
TBLPTRU TBLPTRH TBLPTRL TABLAT
Instruction: TBLWT*
Note 1: Table Pointer points to a byte in
program memory.
Program Memory Address
(TBLPTR)
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39508-page 8-3
Section 8. Table Read/Table Write
Table Write
Table Read/
8
8.2 Control Registers
Several control registers are used in conjunction with the TBLRD and TBLWT instructions. These
include the:
• RCON register
• MEMCON register
• TBLPTR registers
• TABLAT register
8.2.1 RCON Register
The LWRT bit specifies the operation of Table Writes to internal memory when the VPP voltage
is applied to the MCLR pin. When the LWRT bit is set, the controller continues to execute user
code, but long Table Writes are allowed (for programming internal program memory) from user
mode. The LWRT bit can be cleared only by performing either a Power-On Reset (POR) or MCLR
reset. The other bits of the RCON register do not relate to Table Read nor Table Write operation.
Register 8-1: RCON Register
R/W-0 R/W-0 U-0 R/W-1 R/W-1 R/W-1 R/W-0 R/W-0
IPEN LWRT — RI TO PD POR BOR
bit 7 bit 0
bit 7 IPEN: Interrupt Priority Enable
1 = Enable priority levels on interrupts
0 = Disable priority levels on interrupts (PIC16CXXX compatibility mode)
bit 6 LWRT: Long Write Enable
1 = Enable TABLE WRITE to internal program memory
0 = Disable TABLE WRITE to internal program memory
Note 1: Only cleared on a POR or MCLR reset.
Note 2: This bit has no effect on TBLWT instructions to external program memory.
bit 5 Unimplemented: Read as '0'
bit 4 RI: Reset Instruction Flag bit
1 = No Reset instruction occurred
0 = A Reset instruction occurred
bit 3 TO: Time-out bit
1 = After power-up, CLRWDT instruction, or SLEEP instruction
0 = A WDT time-out occurred
bit 2 PD: Power-down bit
1 = After power-up or by the CLRWDT instruction
0 = By execution of the SLEEP instruction
bit 1 POR: Power-On Reset Status bit
1 = No Power-On Reset occurred
0 = A Power-On Reset occurred (must be set in software after a Power-On Reset occurs)
bit 0 BOR: Brown-out Reset Status bit
1 = No Brown-out Reset or POR reset occurred
0 = A Brown-out Reset or POR reset occurred
(must be set in software after a Brown-out Reset occurs)
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39508-page 8-4 2000 Microchip Technology Inc.
8.2.2 MEMCON Register
This register is only available on devices with a system bus to interface to external program memory.
The MEMCON register is used to specify the operation of the 16-bit external system bus for
Table Write operations. For additional information see the “System Bus” section. This register
is not implemented in devices without a System Bus.
Register 8-2: MEMCON Register
R/W-0 R/W-0 R/W-0 R/W-0 U-0 U-0 R/W-0 R/W-0
EBDIS PGRM WAIT1 WAIT0 — — WM1 WM0
bit 7 bit 0
bit 7 EBDIS: External bus disable bit
This bit is used to disable the System Bus pins when in Extended Microcontroller mode. When
disabled, the system bus pins become general purpose I/O.
1 = External system bus disabled, all I/O pin functions are enabled
0 = External system bus enabled, and I/O pin functions are disabled
bit 6 PGRM: Program RAM enable bit
This bit is used to configure internal GPR locations into the program memory map. This is useful
for boot loaders in devices operating in microprocessor mode. The amount of GPR mapped will
be device dependant
1 = GPR memory is mapped to internal program memory space. External program memory
at these locations is unused. The internal GPR memory locations are disabled and
returns 00h.
0 = GPR memory remains in data memory space. External program memory space is available.
bit 5-4 WAIT1:WAIT0: Wait Cycle count bits
Table reads and writes bus cycle wait count
11 = Table reads and writes will wait 0 TCY
10 = Table reads and writes will wait 1 TCY
01 = Table reads and writes will wait 2 TCY
00 = Table reads and writes will wait 3 TCY
bit 3-2 Unimplemented: Read as '0'
bit 1-0 WM1:WM0: Write Mode bit
Table Write write mode operation with 16-bit bus
11 = Word Write Mode: TABLAT0 and TABLAT1 word output,
WRH active when TABLAT1 written
10 = Reserved
01 = Byte Select Mode: TABLAT data copied on both MS and LS Byte,
WRH and (UB or LB) will activate
00 = Byte Write Mode: TABLAT data copied on both MS and LS Byte,
WRH or WRL will activate
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
Note: Any register that has a protected bit requires that the entire register is protected. To
write to a protected register requires the proper write sequence on the
CMLK1:CMLK0 bits before this register can be updated.
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39508-page 8-5
Section 8. Table Read/Table Write
Table Write
Table Read/
8
8.2.3 TABLAT - Table Latch Register
The Table Latch (TABLAT) is an 8-bit register mapped into the SFR space. The Table Latch is
used to hold 8-bit data during data transfers between program memory and data memory.
8.2.4 TBLPTR - Table Pointer Register
The Table Pointer (TBLPTR) addresses a byte within the program memory. The TBLPTR is comprised
of three SFR registers (Table Pointer Upper byte, High byte, and Low byte). These three
registers (TBLPTRU:TBLPTRH:TBLPTRL) join to form a 22-bit wide pointer. The low order
21-bits allows the device to address up to 2M bytes (or 1M words) of program memory space.
The 22nd bit allows access to the Device ID, the User ID, and the Configuration bits.
The Table Pointer, TBLPTR, is used by the TBLRD and TBLWT instructions. These instructions
can update the TBLPTR in one of four ways, based on the table operation. These operations are
shown in Table 8-1. These operations on the TBLPTR only affect the low order 21-bits.
Table 8-1: Table Pointer Operations with TBLRD and TBLWT Instructions
Instruction Operation on Table Pointer
TBLRD*
TBLWT* TBLPTR is not modified
TBLRD*+
TBLWT*+ TBLPTR is incremented after the read/write
TBLRD*-
TBLWT*- TBLPTR is decremented after the read/write
TBLRD+*
TBLWT+* TBLPTR is incremented before the read/write
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39508-page 8-6
Section 8. Table Read/Table Write
Table Write
Table Read/
8
8.3 Program Memory
The program memory can be either internal or external. External program memory requires that
the device has the system bus interface. The operation of Table Reads and Table Writes is different
depending on the location of the program memory (internal or external).
For the device to access external memory, the device needs to be operating in either extended
microcontroller mode (some program memory is also internal), or microprocessor mode (no program
memory is internal).
In this section, the discussion of Table Read and Table Write operation will be limited to the operation
with internal program memory. For operation with external program memory, please refer
to the “System Bus” section.
8.3.1 Internal Program Memory
The device selected will determine the program memory technology used. The Internal Program
Memory can currently be one of three different memory technologies:
1. EPROM
2. FLASH
3. ROM
Depending on the memory technology the following statements can be made.
For EPROM devices:
• All unprogrammed memory locations will read back 0xFF (all bits set)
• Any bit that is set can be programmed clear
• Locations with data can be reprogrammed only if 1’s are changed to 0’s
• No cleared bit can be set unless the entire device is erased, which is only possible with windowed
parts.
For FLASH devices:
• Any bit can be modified on a byte/block basis (individual bits cannot be modified)
• All writes occur with the write of an entire write block
• The size of the write block is device dependent
For ROM devices:
• All unprogrammed memory locations will read back 0xFF (all bits set)
• No program memory location can be modified
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39508-page 8-7 2000 Microchip Technology Inc.
8.3.2 Internal Program Memory Operation
Table Read operation is independent of internal Program Memory Technology used. Table Write
operation will be dependent on the memory technology of the internal Program Memory.
The notation “TBLRD instruction” means any of the four Table Read forms (TBLRD*, TBLRD*+,
TBLRD*-, TBLRD+*) and the notation “TBLWT instruction” means any of the four Table Write
forms (TBLWT*, TBLWT*+, TBLWT*-, TBLWT+*). For additional details on the operation of these
instructions refer to the “Instruction Set” section.
8.3.2.1 Table Read Overview (TBLRD)
The TBLRD instructions are used to read data from program memory to data memory.
The Table Reads from program memory are performed one byte at a time.
The TBLPTR points to a byte address in program space. Executing a TBLRD instruction moves
the contents of the addressed byte into the TABLAT register. In addition, the TBLPTR can be
modified automatically for the next Table Read operation.
The TBLPTR can be automatically modified, depending on the form of the TBLRD instruction (see
Table 8-1). All of the TBLRD instructions require two instruction cycles (TCY) to execute.
8.3.2.1.1 Effects of a Reset
The TABLAT register will retain the value read from program memory (if the instruction completed).
The Table Pointer registers will not change, and the RCON register will be forced to the
appropriate reset state.
8.3.2.2 Table Write Overview (TBLWT)
The TBLWT instructions are used to write data from data memory to program memory.
For devices with EPROM Program Memory, Table Writes are performed in pairs, one byte at a
time. Table Writes to an even program memory address (TBLPTR<0> is clear) will load an internal
memory latch from TABLAT, and is known as a short write. Table Writes to an odd program
memory address (TBLPTR<0> is set) will start long writes. (TABLAT is programmed to the program
word high byte, and the internal memory latch is programmed to the same word low byte).
For devices using another program memory technology, the operation may be different. Please
refer to the device data sheet.
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39508-page 8-8 2000 Microchip Technology Inc.
8.3.2.2.1 Memory Write Block Size
Depending on the device used, the write block size will be different. The larger the block size, the
faster the entire internal program memory space can be programmed. This is because the
EPROM/FLASH write time is much longer than the time to load the holding registers. For internal
program memory, the write block size can vary from 2 bytes to many bytes (in FLASH devices).
A write to the Most Significant byte (MSB) of the block causes the entire block to be written to
program memory. Writes to all other locations in the write block only modify the contents of the
specified holding register.
After a write cycle has completed, the contents of the Write Block Holding Registers are forced
set (‘1’s). This eases the writing of only a single byte within a program memory block. Figure 8-3
shows the write block for EPROM program memory. The write block size is 2 bytes.
If a single byte is to be programmed, the low (even) byte of the destination program word should
be read using TBLRD*, then modified if required, and written back to the same address using
TBLWT*+. Then the high (odd) byte should be read using TBLRD*, modified if required, and written
back to the same address using a TBLWT instruction. The write to an odd address will cause
a long write to begin (in EPROM program memory devices). This process ensures that existing
data in either byte will not be changed unless desired.
Figure 8-3: Holding Registers and the Write Block (EPROM Program Memory)
Block n
Block n + 1
Block n + 2
MSB
The write to the MSB of the write block causes the
entire block to be written to program memory. The
program memory block that is written depends on
the address that is written to in the MSB of the write
block.
All writes to the holding registers use only the LSb’s
of the address to specify into which holding register
to load the data.
Holding Registers
Program Memory (x 16-bits)
Write Block
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39508-page 8-9
Section 8. Table Read/Table Write
Table Write
Table Read/
8
8.3.2.2.2 EPROM Program Memory Operation
The long write is what actually programs the data into the internal memory. When a TBLWT
instruction to the MSB of the write block occurs, instruction execution is halted. During this time,
programming voltage and the data stored in internal latches is applied to program memory.
The sequence of steps to program the internal program memory is:
1. MCLR/VPP pin must be at the programming voltage
2. LWRT bit must be set
3. TBLWT to the address of the MSB of the write block
If the LWRT bit is clear, a short write will occur and program memory will not be changed. If the
TBLWT is not to the MSB of the write block, then the programming phase is not initiated.
Setting the LWRT bit enables long writes when the MCLR pin is taken to VPP voltage. Once the
LWRT bit is set, it can be cleared only by performing a Power-On Reset (POR) or MCLR reset.
To ensure that the memory location has been well programmed, a minimum programming time
is required. The long write can be terminated after the programming time has expired by any
event that can wake the controller from SLEEP. This may be a reset or an interrupt that operates
during sleep. Having only one interrupt source enabled to terminate the long write ensures that
no unintended interrupts will prematurely terminate the long write. Usable interrupt sources
include:
• WDT
• A/D
• External Interrupts (INT0, INT1, or INT2)
• PORTB interrupt on change
• USART on address detect
• Timer1 in async counter mode or async external clock mode.
• Timer3 in async counter mode or async external clock mode.
• Capture
• SPI
8.3.2.2.3 Sequence of events
The sequence of events for programming an internal program memory location should be:
1. Enable the interrupt that terminates the long write. Disable all other interrupts.
2. Clear the source interrupt flag.
3. If Interrupt Service Routine (ISR) execution is desired when the device wakes, enable global
interrupts (GIE, GIEH, or GIEL).
4. Set LWRT bit in RCON register.
5. Raise MCLR/VPP pin to the programming voltage, VPP.
6. Clear the WDT (if enabled).
7. Set the interrupt source to interrupt at the required time.
8. Load the desired Table Pointer Address.
9. Execute the Table Write for the lower (even) byte. This will be a short write.
10. Execute the Table Write for the upper (odd) byte. This will be a long write. The controller
will halt instruction execution while programming. The interrupt wakes the controller.
11. If GIE was set, service the interrupt request.
12. If more locations to program, go to step 2.
13. Lower MCLR/VPP pin to VDD.
14. Verify the memory location (Table Read).
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39508-page 8-10 2000 Microchip Technology Inc.
8.3.2.2.4 Interrupts
The long write must be terminated by a RESET or any interrupt that can wake the controller from
SLEEP mode. Usable interrupt sources include:
• WDT
• A/D
• INT0
• INT1
• INT2
• RB<7:4> interrupt on change
• USART on address detect
• Timer1 in asynchronous counter mode or asynchronous external clock mode
• Timer3 in asynchronous counter mode or asynchronous external clock mode
The interrupt source must have its interrupt enable bit set. When the source sets its interrupt flag,
programming will terminate. This will occur regardless of the settings of interrupt priority bits, the
GIE/GIEH bit, or the PIE/GIEL bit.
Depending on the states of interrupt priority bits, the GIE/GIEH bit, or the PIE/GIEL bit, program
execution can either be vectored to the high or low priority Interrupt Service Routine (ISR), or
resume program execution.
In either case, the interrupt flag will not be automatically cleared when programming is terminated,
and will need to be cleared by the software.
Table 8-2: SLEEP Mode, Interrupt Enable Bits and Interrupt Results
Interrupt
Source
GIE/
GIEH
PIE/
GIEL Priority Interrupt
Enable
Interrupt
Flag Action
Any
interrupt source
that operates
during
SLEEP
XX X 0
(default)
X SLEEP mode continues even if interrupt
flag becomes set during SLEEP.
X X X 1 0 SLEEP mode continues, will wake when
Interrupt flag is set.
0
(default)
0
(default)
X 1 1 Wakes controller, terminates long write,
executes next instruction. Interrupt flag
not cleared.
0
(default)
1 1
high priority
(default)
1 1 Wakes controller, terminates long write,
executes next instruction. Interrupt flag
not cleared.
1 0
(default)
0
low
1 1 Wakes controller, terminates long write,
executes next instruction. Interrupt flag
not cleared.
0
(default)
1 0
low
1 1 Wakes controller, terminates long write,
branches to low priority interrupt vector.
Interrupt flag can be cleared by ISR.
1 0
(default)
1
high priority
(default)
1 1 Wakes controller, terminates long write,
branches to high priority interrupt vector.
Interrupt flag can be cleared by ISR.
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39508-page 8-11
Section 8. Table Read/Table Write
Table Write
Table Read/
8
8.3.2.2.5 Unexpected Termination of Write Operations
If a table write operation is terminated by an unplanned event, such as loss of power, an unexpected
reset, or an interrupt that was not disabled, the memory location just programmed should
be verified and reprogrammed if needed.
For applications where a loss of power could occur, a Brown-out reset circuit is recommended to
ensure that the write operation is terminated cleanly. This reduces the possibility that a programmed
location could not be reprogrammed to the desired value.
8.3.2.2.6 Effects of a RESET
A device reset during a long write may cause the location being programmed to be incompletely
programmed. The location should be verified and reprogrammed if needed. A device reset during
a write (short) will not effect the value in the TABLAT register (if the write cycle completed). The
RCON register will be forced into the appropriate reset state.
39500 18C Reference Manual.book Page 11 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39508-page 8-12 2000 Microchip Technology Inc.
8.4 Enabling Internal Programming
There is a combination of actions that need to occur to enable programming of the internal program
memory. These modes are entered by applying the VIHH voltage on the MCLR/VPP pin and
either setting the LWRT bit (self-programming) or having RB6 and RB7 at a low level when VIHH
was detected (ICSP mode).
8.4.1 Programming Modes
Table 8-3 shows the device operating modes depending on the state of the MCLR pin, the LWRT
bit, and the RB7:RB6.
Table 8-3: Device Programming Mode
(Depending on MCLR voltage and LWRT bit and RB7 and RB6 pins)
8.5 External Program Memory Operation
Regardless of the system bus mode selected, Table Reads and Table Writes to external memory
execute in 2 TCY. For information regarding the modes and waveforms of the System Bus, see
the “System Bus” section. All further details of external program memory and table operations
will be described in that section.
MCLR/VPP
Voltage LWRT RB6 RB7 OPERATING MODE
VPP 0 0 0 ICSP
VPP 0 1 X Reserved
VPP 0 X 1 Reserved
VPP 1 X X Normal execution, long Table Writes enabled
VDD 1 X X Normal execution, short Table Writes only
VSS 0 (1) X X In Device Reset
Legend: X = Don’t care.
Note 1: The LWRT bit is cleared by any device reset.
39500 18C Reference Manual.book Page 12 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39508-page 8-13
Section 8. Table Read/Table Write
Table Write
Table Read/
8
8.6 Initialization
Example 8-1 shows the initialization of the Table pointer and the FSR0 register to read the value
from Program memory to a RAM buffer (starting at address RAMBUFADDR).
Example 8-2 shows the sequence to initialize these same registers and then write a word to the
internal EPROM Program memory.
Example 8-1: Initialization to do a Table Read
Example 8-2: Initialization to do a Table Write (to internal EPROM memory)
LFSR FSR0, RAMBUFADDR ;
MOVLW UPPER (Read Table) ;
MOVWF TBLPTRU ;
MOVLW HIGH (Read Table) ;
MOVWF TBLPTRH ;
MOVLW LOW (Read Table) ;
MOVWF TBLPTRL ;
TBLRD*+ ; Read location and then increment
; the table pointer
MOVFF TABLAT, POSTINC0 ; Copy contents of table latch to the
; indirect address and then
; increment the indirect address
; pointer.
: ; Set up interrupts to terminate
: ; long write
LFSR FSR0, RAMBUFADDR ;
MOVLW UPPER (Read Table) ;
MOVWF TBLPTRU ;
MOVLW HIGH (Read Table) ;
MOVWF TBLPTRH ;
MOVLW LOW (Read Table) ;
MOVWF TBLPTRL ;
MOVFF POSTINC0, TABLAT ; Load table latch with value
; to write
TBLWT*+ ; Write to holding register
MOVFF POSTINC0, TABLAT ; Load second byte to table latch
TBLWT*+ ; Write to MSB, (odd address)
; start long write
39500 18C Reference Manual.book Page 13 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39508-page 8-14 2000 Microchip Technology Inc.
8.7 Design Tips
Question 1: The location I programmed does not contain the value I wrote. What is
wrong?
Answer 1:
There are several possibilities. These include, but are not limited to:
• The maximum time requirement of the long write time was not met (for internal program
memory).
• The address of the location to program was changed during the write cycle.
• A device reset occurred during the write cycle.
• If the program memory is EPROM or EOTP, then required overprogramming was not done.
• An Interrupt flag may have been set, so the long write cycle was immediately completed
(violated long write time specification).
Question 2: Occasionally the device hangs. What is this?
Answer 2:
Your program may have executed a long write, and the device may not have the interrupts/modules
set up to terminate this long write.
Question 3: When programming the program memory are there any required algorithm
algorithms to follow?
Answer 3:
The programming algorithm will be dependent on the memory technology of the device. For complete
information on device programming please refer to the device’s programming specifications.
39500 18C Reference Manual.book Page 14 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39508-page 8-15
Section 8. Table Read/Table Write
Table Write
Table Read/
8
8.8 Related Application Notes
This section lists application notes that are related to this section of the manual. These application
notes may not be written specifically for the Enhanced family (that is, they may be written for
the Base-Line, the Mid-Range, or High-End families), but the concepts are pertinent, and could
be used (with modification and possible limitations). The current application notes related to the
oscillator are:
Title Application Note #
No related application notes at this time.
Note: Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
http://www.microchip.com/10/faqs/codeex/
39500 18C Reference Manual.book Page 15 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39508-page 8-16 2000 Microchip Technology Inc.
8.9 Revision History
This is the initial released revision of the Enhanced MCU Table Read/Table Write description.
39500 18C Reference Manual.book Page 16 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39509A-page 9-1
System Bus
9
Section 9. System Bus
Please check the Microchip web site for Revision B of the System Bus Section.
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39509A-page 9-2 2000 Microchip Technology Inc.
9.1 Revision History
Revision A
This is the initial released revision of the Enhanced MCU System Bus module description.
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39510A-page 10-1
Interrupts
10
Section 10. Interrupts
HIGHLIGHTS
This section of the manual contains the following major topics:
10.1 Introduction .................................................................................................................. 10-2
10.2 Control Registers ......................................................................................................... 10-6
10.3 Interrupt Handling Operation...................................................................................... 10-19
10.4 Initialization ................................................................................................................ 10-29
10.5 Design Tips ................................................................................................................ 10-30
10.6 Related Application Notes.......................................................................................... 10-31
10.7 Revision History ......................................................................................................... 10-32
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39510A-page 10-2 2000 Microchip Technology Inc.
10.1 Introduction
Interrupts can come from many sources. These sources currently include:
• External interrupt from the INT, INT1, and INT2 pins
• Change on RB7:RB4 pins
• TMR0 Overflow
• TMR1 Overflow
• TMR2 Overflow
• TMR3 Overflow
• USART Interrupts
- Receive buffer full
- Transmit buffer empty
• SSP Interrupt
• SSP I2C bus collision interrupt
• A/D conversion complete
• CCP interrupt
• LVD Interrupt
• Parallel Slave Port
• CAN interrupts
- Receive buffer 1 full
- Receive buffer 2 full
- Receive invalid
- Transmit buffer 0 empty
- Transmit buffer 1 empty
- Transmit buffer 2 empty
- Bus wakeup
- Bus invalid error
As other peripheral modules are developed, they will have interrupt sources. These sources will
map into the 10 registers used in the control and status of interrupts. These registers are:
• INTCON
• INTCON1
• INTCON2
• INTCON3
• PIR1
• PIR2
• PIE1
• PIE2
• IPR1
• IPR2
The INTCON register contains the GIE/GIEH bit. This is the Global Interrupt Enable bit. When
this bit is set, all interrupts are enabled. If needed for any single device, additional INTCON, PIR,
PIE, and IPR registers will be defined.
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39510A-page 10-3
Section 10. Interrupts
Interrupts
10
10.1.1 Interrupt Priority
There are two interrupt vectors. One interrupt vector is for high priority interrupts and is located
at address 000008h. The other interrupt vector is for low priority interrupts and is located at
address 000018h.
When a valid interrupt occurs, program execution vectors to one of these interrupt vector
addresses and the corresponding Global Interrupt Enable bit (GIE, GIEH, or GIEL) is automatically
cleared. In the interrupt service routine, the source(s) of the interrupt can be determined by
testing the interrupt flag bits. The interrupt flag bit(s) must be cleared before re-enabling interrupts
to avoid infinite interrupt requests. Most flag bits are required to be cleared by the application
software. There are some flag bits that are automatically cleared by the hardware.
When an interrupt condition is met, that individual interrupt flag bit will be set regardless of the
status of its corresponding mask bit .
For external interrupt events, such as the RB0/INT0 pin or PORTB change interrupt, the interrupt
latency will be three or four instruction cycles. The exact latency depends when the interrupt
event occurs. The interrupt latency is the same for one or two cycle instructions.
The “return from interrupt” instruction, RETFIE, can be used to mark the end of the interrupt service
routine. When this instruction is executed, the stack is “POPed” and the GIE bit is set (to
re-enable interrupts).
Figure 10-1: Interrupt Logic High Level Block Diagram
T0IE
GIEH/GIE
GIEL/PEIE
Wake-up if in SLEEP mode
Interrupt to CPU
Vector to location
0008h
INT2F
INT2E
INT2P
INT1F
INT1E
INT1P
T0IF
T0IE
T0IP
INT0F
INT0E
RBIF
RBIE
RBIP
IPEN
T0IF
T0IP
INT1F
INT1E
INT1P
INT2F
INT2E
INT2P
RBIF
RBIE
RBIP
INT0F
INT0E
GIEL\PEIE
IPEN
IPEN
Peripheral Interrupt Enable bit Peripheral Interrupt Flag bit
Peripheral Interrupt Priority bit
High Priority Interrupt Generation
Low Priority Interrupt Generation
Peripheral Interrupt Enable bit Peripheral Interrupt Flag bit
Peripheral Interrupt Priority bit
Additional Peripheral Interrupts
Additional Peripheral Interrupts
(If in SLEEP mode)
High Priority Interrupt initialized
(disable low priority interrupts)
(High Priority Interrupt
Vector Address)
Interrupt to CPU
Vector to Location 0018h
(Low Priority Interrupt
Vector Address)
Wake-up
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39510A-page 10-4 2000 Microchip Technology Inc.
Figure 10-2: High Priority Interrupt Logic Block Diagram
PSPIF
PSPIE
GIE/GIEH
PEIE/GIEL
Wake-up (If in SLEEP mode)
Interrupt to CPU
Vector to Location
00008h
PSPIP
ADIF
ADIE
ADIP
RCIF
RCIE
RCIP
TXIF
TXIE
TXIP
SSPIF
SSPIE
SSPIP
CCP1IF
CCP1IE
CCP1IP
CCP2IF
CCP2IE
CCP2IP
TMR1IF
TMR1IE
TMR1IP
TMR2IF
TMR2IE
TMR2IP
TMR3IF
TMR3IE
TMR3IP
BCLIF
BCLIE
BCLIP
LVDIF
LVDIE
LVDIP
INT2IF
INT2IE
INT2IP
INT1IF
INT1IE
INT1IP
TMR0IF
TMR0IE
TMR0IP
INT0IF
INT0IE
INT0IP
RBIF
RBIE
RBIP
IPEN
To low priority
interrupt logic
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39510A-page 10-5
Section 10. Interrupts
Interrupts
10
Figure 10-3: Low Priority Interrupt Logic Block Diagram
TMR0IE
TMR0IF
TMR0IP
INT1IF
INT1IE
INT1IP
INT2IF
INT2IE
INT2IP
RBIF
RBIE
RBIP
INT0IF
INT0IE
INT0IP
GIEL
Wake-up (If in SLEEP Mode)
Interrupt to CPU
Vector to Location 00018h
PSPIE
PSPIP
ADIF
ADIE
ADIP
RCIF
RCIE
RCIP
TXIF
TXIE
TXIP
SSPIF
SSPIE
SSPIP
CCP1IF
CCP1IE
CCP1IP
CCP2IF
CCP2IE
CCP2IP
TMR1IF
TMR1IE
TMR1IP
TMR2IF
TMR2IE
TMR2IP
TMR3IF
TMR3IE
TMR3IP
BCLIF
BCLIE
BCLIP
LVDIF
LVDIE
LVDIP
(Low Priority Interrupt Vector Address)
High priority interrupt initiated signal
(Disable Low Priority Interrupts)
IPEN
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39510A-page 10-6 2000 Microchip Technology Inc.
10.2 Control Registers
Generally devices have a minimum of four registers associated with interrupts. The INTCON register
contains the Global Interrupt Enable bit, GIE, as well as the Peripheral Interrupt Enable bit,
PEIE, the PIE / PIR register pair that enables the peripheral interrupts and displays the interrupt
flag status, and the Interrupt Priority Register (IPR) that controls whether the interrupt source is
a high priority or low priority interrupt.
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39510A-page 10-7
Section 10. Interrupts
Interrupts
10
10.2.1 INTCON Register
The INTCON Registers are readable and writable registers that contain various enable, priority,
and flag bits.
Register 10-1: INTCON Register
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-x
GIE/GIEH PEIE/GIEL TMR0IE INT0IE RBIE TMR0IF INT0IF RBIF
bit 7 bit 0
bit 7 GIE/GIEH: Global Interrupt Enable bit
When IPEN = 0:
1 = Enables all un-masked interrupts
0 = Disables all interrupts
When IPEN = 1:
1 = Enables all interrupts
0 = Disables all interrupts
bit 6 PEIE/GEIL: Peripheral Interrupt Enable bit
When IPEN = 0:
1 = Enables all un-masked peripheral interrupts
0 = Disables all peripheral interrupts
When IPEN = 1:
1 = Enables all low peripheral interrupts
0 = Disables all priority peripheral interrupts
bit 5 TMR0IE: TMR0 Overflow Interrupt Enable bit
1 = Enables the TMR0 overflow interrupt
0 = Disables the TMR0 overflow interrupt
bit 4 INT0IE: INT0 External Interrupt Enable bit
1 = Enables the INT0 external interrupt
0 = Disables the INT0 external interrupt
bit 3 RBIE: RB Port Change Interrupt Enable bit
1 = Enables the RB port change interrupt
0 = Disables the RB port change interrupt
bit 2 TMR0IF: TMR0 Overflow Interrupt Flag bit
1 = TMR0 register has overflowed (must be cleared in software)
0 = TMR0 register did not overflow
bit 1 INT0IF: INT0 External Interrupt Flag bit
1 = The INT0 external interrupt occurred (must be cleared in software)
0 = The INT0 external interrupt did not occur
bit 0 RBIF: RB Port Change Interrupt Flag bit
1 = At least one of the RB7:RB4 pins changed state (must be cleared in software)
0 = None of the RB7:RB4 pins have changed state
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
Note: Interrupt flag bits are set when an interrupt condition occurs, regardless of the state
of its corresponding enable bit or the global enable bit. User software should ensure
the appropriate interrupt flag bits are clear prior to enabling an interrupt. This feature
allows for software polling.
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39510A-page 10-8 2000 Microchip Technology Inc.
Register 10-2: INTCON2 Register
R/W-1 R/W-1 R/W-1 R/W-1 U-0 R/W-1 U-0 R/W-1
RBPU INTEDG0 INTEDG1 INTEDG2 — TMR0IP — RBIP
bit 7 bit 0
bit 7 RBPU: PORTB Pull-up Enable bit
1 = All PORTB pull-ups are disabled
0 = PORTB pull-ups are enabled by individual port latch values
bit 6 INTEDG0:External Interrupt0 Edge Select bit
1 = Interrupt on rising edge
0 = Interrupt on falling edge
bit 5 INTEDG1: External Interrupt1 Edge Select bit
1 = Interrupt on rising edge
0 = Interrupt on falling edge
bit 4 INTEDG2: External Interrupt2 Edge Select bit
1 = Interrupt on rising edge
0 = Interrupt on falling edge
bit 3 Unimplemented: Read as '1'
bit 2 TMR0IP: TMR0 Overflow Interrupt Priority bit
1 = TMR0 Overflow Interrupt is a high priority event
0 = TMR0 Overflow Interrupt is a low priority event
bit 1 Unimplemented: Read as '1'
bit 0 RBIP: RB Port Change Interrupt Priority bit
1 = RB Port Change Interrupt is a high priority event
0 = RB Port Change Interrupt is a low priority event
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
Note: Interrupt flag bits are set when an interrupt condition occurs, regardless of the state
of its corresponding enable bit or the global enable bit. User software should ensure
the appropriate interrupt flag bits are clear prior to enabling an interrupt. This feature
allows for software polling.
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39510A-page 10-9
Section 10. Interrupts
Interrupts
10
Register 10-3: INTCON3 Register
R/W-1 R/W-1 U-0 R/W-0 R/W-0 U-0 R/W-0 R/W-0
INT2IP INT1IP — INT2IE INT1IE — INT2IF INT1IF
bit 7 bit 0
bit 7 INT2IP: INT2 External Interrupt Priority bit
1 = INT2 External Interrupt is a high priority event
0 = INT2 External Interrupt is a low priority event
bit 6 INT1IP: INT1 External Interrupt Priority bit
1 = INT1 External Interrupt is a high priority event
0 = INT1 External Interrupt is a low priority event
bit 5 Unimplemented: Read as '0'
bit 4 INT2IE: INT2 External Interrupt Enable bit
1 = Enables the INT2 external interrupt
0 = Disables the INT2 external interrupt
bit 3 INT1IE: INT1 External Interrupt Enable bit
1 = Enables the INT1 external interrupt
0 = Disables the INT1 external interrupt
bit 2 Unimplemented: Read as '0'
bit 1 INT2IF: INT2 External Interrupt Flag bit
1 = The INT2 external interrupt occurred
(must be cleared in software)
0 = The INT2 external interrupt did not occur
bit 0 INT1IF: INT1 External Interrupt Flag bit
1 = The INT1 external interrupt occurred
(must be cleared in software)
0 = The INT1 external interrupt did not occur
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
Note: Interrupt flag bits are set when an interrupt condition occurs, regardless of the state
of its corresponding enable bit or the global enable bit. User software should ensure
the appropriate interrupt flag bits are clear prior to enabling an interrupt. This feature
allows for software polling.
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39510A-page 10-10 2000 Microchip Technology Inc.
10.2.2 PIE Register(s)
Depending on the number of peripheral interrupt sources, there may be multiple Peripheral Interrupt
Enable registers (such as PIE1 and PIE2). These registers contain the individual enable bits
for the peripheral interrupts. These registers will be generically referred to as PIE.
Although the PIE register bits have a general bit location with each register, future devices may
not have consistent placement. Bit location inconsistencies will not be a problem if you use the
supplied Microchip Include files for the symbolic use of these bits. This will allow the Assembler/Compiler
to automatically take care of the placement of these bits by specifying the correct
Register number and bit name.
Register 10-4: PIE Peripheral Interrupt Enable Registers
Note: If the device has a PIE register and IPEN = 0, the PEIE bit must be set to enable
any of the peripheral interrupts.
R/W-0
(Note 1)
bit 7 bit 0
bit TMR1IE: TMR1 Overflow Interrupt Enable bit
1 = Enables the TMR1 overflow interrupt
0 = Disables the TMR1 overflow interrupt
bit TMR2IE: TMR2 to PR2 Match Interrupt Enable bit
1 = Enables the TMR2 to PR2 match interrupt
0 = Disables the TMR2 to PR2 match interrupt
bit TMR3IE: TMR3 Overflow Interrupt Enable bit
1 = Enables the TMR3 overflow interrupt
0 = Disables the TMR3 overflow interrupt
bit CCPxIE: CCPx Interrupt Enable bit
1 = Enables the CCPx interrupt
0 = Disables the CCPx interrupt
bit ECCPxIE: Enhanced CCPx Interrupt Enable bit
1 = Enables the CCPx interrupt
0 = Disables the CCPx interrupt
bit SSPIE: Synchronous Serial Port Interrupt Enable bit
1 = Enables the SSP interrupt
0 = Disables the SSP interrupt
bit MSSPIE: Master Synchronous Serial Port Interrupt Enable bit
1 = Enables the MSSP interrupt
0 = Disables the MSSP interrupt
bit RCIE: USART Receive Interrupt Enable bit
1 = Enables the USART receive interrupt
0 = Disables the USART receive interrupt
bit TXIE: USART Transmit Interrupt Enable bit
1 = Enables the USART transmit interrupt
0 = Disables the USART transmit interrupt
bit IRXIE: CAN Invalid Received message Interrupt Enable bit
1 = Enable invalid message received interrupt
0 = Disable invalid message received interrupt
bit WAKIE: CAN Bus Activity Wake-up Interrupt Enable bit
1 = Enable Bus Activity Wake-up Interrupt
0 = Disable Bus Activity Wake-up Interrupt
bit ERRIE: CAN bus Error Interrupt Enable bit
1 = Enable CAN bus Error Interrupt
0 = Disable CAN bus Error Interrupt
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39510A-page 10-11
Section 10. Interrupts
Interrupts
10
bit TXB2IE: CAN Transmit Buffer 2 Interrupt Enable bit
1 = Enable Transmit Buffer 2 Interrupt
0 = Disable Transmit Buffer 2 Interrupt
bit TXB1IE: CAN Transmit Buffer 1 Interrupt Enable bit
1 = Enable Transmit Buffer 1 Interrupt
0 = Disable Transmit Buffer 1 Interrupt
bit TXB0IE: CAN Transmit Buffer 0 Interrupt Enable bit
1 = Enable Transmit Buffer 0 Interrupt
0 = Disable Transmit Buffer 0 Interrupt
bit RXB1IE: CAN Receive Buffer 1 Interrupt Enable bit
1 = Enable Receive Buffer 1 Interrupt
0 = Disable Receive Buffer 1 Interrupt
bit RXB0IE: CAN Receive Buffer 0 Interrupt Enable bit
1 = Enable Receive Buffer 0 Interrupt
0 = Disable Receive Buffer 0 Interrupt
bit ADIE: A/D Converter Interrupt Enable bit
1 = Enables the A/D interrupt
0 = Disables the A/D interrupt
bit PSPIE: Parallel Slave Port Read/Write Interrupt Enable bit
1 = Enables the PSP read/write interrupt
0 = Disables the PSP read/write interrupt
bit EEIE: EE Write Complete Interrupt Enable bit
1 = Enables the EE write complete interrupt
0 = Disables the EE write complete interrupt
bit CMIE: Comparator Interrupt Enable bit
1 = Enables the Comparator interrupt
0 = Disables the Comparator interrupt
bit BCLIE: Bus Collision Interrupt Enable bit
1 = Enabled
0 = Disabled
bit LVDIE: Low-voltage Detect Interrupt Enable bit
1 = Enabled
0 = Disabled
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
Note 1: The bit position of the enable bits is device dependent. Please refer to the device
data sheet for bit placement.
39500 18C Reference Manual.book Page 11 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39510A-page 10-12 2000 Microchip Technology Inc.
10.2.3 PIR Register(s)
Depending on the number of peripheral interrupt sources, there may be multiple Peripheral Interrupt
Flag registers (PIR1, PIR2). These registers contain the individual flag bits for the peripheral
interrupts. These registers will be generically referred to as PIR.
Although the PIR bits have a general bit location within each register, future devices may not
have consistent placement. It is recommended that you use the supplied Microchip Include files
for the symbolic use of these bits. This will allow the Assembler/Compiler to automatically take
care of the placement of these bits within the specified register.
Note 1: Interrupt flag bits are set when an interrupt condition occurs, regardless of the state
of its corresponding enable bit or the global enable bit, GIE (INTCON<7>).
Note 2: User software should ensure the appropriate interrupt flag bits are cleared prior to
enabling an interrupt and after servicing that interrupt.
39500 18C Reference Manual.book Page 12 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39510A-page 10-13
Section 10. Interrupts
Interrupts
10
Register 10-5: PIR Register
R/W-0
(Note 1)
bit 7 bit 0
bit TMR1IF: TMR1 Overflow Interrupt Flag bit
1 = TMR1 register overflowed
(must be cleared in software)
0 = TMR1 register did not overflow
bit TMR2IF: TMR2 to PR2 Match Interrupt Flag bit
1 = TMR2 to PR2 match occurred
(must be cleared in software)
0 = No TMR2 to PR2 match occurred
bit TMR3IF: TMR3 Overflow Interrupt Flag bit
1 = TMR3 register overflowed
(must be cleared in software)
0 = TMR3 register did not overflow
bit CCPxIF: CCPx Interrupt Flag bit
Capture Mode
1 = A TMR1 register capture occurred
(must be cleared in software)
0 = No TMR1 register capture occurred
Compare Mode
1 = A TMR1 register compare match occurred
(must be cleared in software)
0 = No TMR1 register compare match occurred
PWM Mode
Unused in this mode
bit ECCPxIF: Enhanced CCPx Interrupt Flag bit
Capture Mode
1 = A TMR1 register capture occurred
(must be cleared in software)
0 = No TMR1 register capture occurred
Compare Mode
1 = A TMR1 register compare match occurred
(must be cleared in software)
0 = No TMR1 register compare match occurred
PWM Mode
Unused in this mode
39500 18C Reference Manual.book Page 13 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39510A-page 10-14 2000 Microchip Technology Inc.
bit IRXIF: CAN Invalid Received message Interrupt Flag bit
1 = An invalid message has occurred on the CAN bus
0 = No invalid message on CAN bus
bit WAKIF: CAN Bus Activity Wake-up Interrupt Flag bit
1 = Activity on CAN bus has occurred
0 = No activity on CAN bus
bit ERRIF: CAN bus Error Interrupt Flag bit
1 = An error has occurred in the CAN module (multiple sources)
0 = No CAN module errors
bit TXB2IF: CAN Transmit Buffer 2 Interrupt Flag bit
1 = Transmit Buffer 2 has completed transmission of a message, and may be re-loaded
0 = Transmit Buffer 2 has not completed transmission of a message
bit TXB1IF: CAN Transmit Buffer 1 Interrupt Flag bit
1 = Transmit Buffer 1 has completed transmission of a message, and may be re-loaded
0 = Transmit Buffer 1 has not completed transmission of a message
bit TXB0IF: CAN Transmit Buffer 0 Interrupt Flag bit
1 = Transmit Buffer 0 has completed transmission of a message, and may be re-loaded
0 = Transmit Buffer 0 has not completed transmission of a message
bit RXB1IF: CAN Receive Buffer 1 Interrupt Flag bit
1 = Receive Buffer 1 has received a new message
0 = Receive Buffer 1 has not received a new message
bit RXB0IF: CAN Receive Buffer 0 Interrupt Flag bit
1 = Receive Buffer 0 has received a new message
0 = Receive Buffer 0 has not received a new message
bit SSPIF: Synchronous Serial Port Interrupt Flag bit
1 = The transmission/reception is complete
(must be cleared in software)
0 = Waiting to transmit/receive
bit MSSPIF: Master Synchronous Serial Port Interrupt Flag bit
1 = The transmission/reception is complete
(must be cleared in software)
0 = Waiting to transmit/receive
bit RCIF: USART Receive Interrupt Flag bit
1 = The USART receive buffer, RCREG, is full
(cleared when RCREG is read)
0 = The USART receive buffer is empty
bit TXIF: USART Transmit Interrupt Flag bit
1 = The USART transmit buffer, TXREG, is empty
(cleared when TXREG is written)
0 = The USART transmit buffer is full
39500 18C Reference Manual.book Page 14 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39510A-page 10-15
Section 10. Interrupts
Interrupts
10
bit ADIF: A/D Converter Interrupt Flag bit
1 = An A/D conversion completed
(must be cleared in software)
0 = The A/D conversion is not complete
bit PSPIF: Parallel Slave Port Read/Write Interrupt Flag bit
1 = A read or a write operation has taken place
(must be cleared in software)
0 = No read or write has occurred
bit EEIF: EE Write Complete Interrupt Flag bit
1 = The data EEPROM write operation is complete
(must be cleared in software)
0 = The data EEPROM write operation is not complete
bit CMIF: Comparator Interrupt Flag bit
1 = Comparator input has changed
(must be cleared in software)
0 = Comparator input has not changed
bit BCLIF: Bus Collision Interrupt Flag bit
1 = A Bus Collision occurred
(must be cleared in software)
0 = No Bus Collision occurred
bit LVDIF: Low-voltage Detect Interrupt Flag bit
1 = A Low Voltage condition occurred
(must be cleared in software)
0 = The device voltage is above the Low Voltage Detect trip point
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
Note 1: The bit position of the enable bits is device dependent. Please refer to the device
data sheet for bit placement.
39500 18C Reference Manual.book Page 15 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39510A-page 10-16 2000 Microchip Technology Inc.
10.2.4 IPR Register
Depending on the number of peripheral interrupt sources, there may be multiple Peripheral Interrupt
Priority registers (such as IPR1 and IPR2). These registers contain the individual priority bits
for the peripheral interrupts. These registers will be generically referred to as IPR. If the device
has an IPR register and IPEN = 0, the PEIE bit must be set to enable any of these peripheral
interrupts.
Although the IPR register bits have a general bit location with each register, future devices may
not have consistent placement. Bit location inconsistencies will not be a problem if you use the
supplied Microchip Include files for the symbolic use of these bits. This will allow the Assembler/Compiler
to automatically take care of the placement of these bits by specifying the correct
register and bit name.
Register 10-6:IPR Peripheral Interrupt Priority Register
Note: The IP bit specifies the priority of the peripheral interrupt.
R/W-0
(Note 1)
bit 7 bit 0
bit TMR1IP: TMR1 Overflow Interrupt Priority bit
1 = TMR1 Overflow Interrupt is a high priority event
0 = TMR1 Overflow Interrupt is a low priority event
bit TMR2IP: TMR2 to PR2 Match Interrupt Priority bit
1 = TMR2 to PR2 Match Interrupt is a high priority event
0 = TMR2 to PR2 Match Interrupt is a low priority event
bit TMR3IP: TMR3 Overflow Interrupt Priority bit
1 = TMR3 Overflow Interrupt is a high priority event
0 = TMR3 Overflow Interrupt is a low priority event
bit CCPxIP: CCPx Interrupt Priority bit
1 = CCPx Interrupt is a high priority event
0 = CCPx Interrupt is a low priority event
bit ECCPxIP: Enhanced CCPx Interrupt Priority bit
1 = Enhanced CCPx Interrupt is a high priority event
0 = Enhanced CCPx Interrupt is a low priority event
bit MSSPIP: Master Synchronous Serial Port Interrupt Priority bit
1 = Master Synchronous Serial Port Interrupt is a high priority event
0 = Master Synchronous Serial Port Interrupt is a low priority event
bit SSPIP: Synchronous Serial Port Interrupt Priority bit
1 = Synchronous Serial Port Interrupt is a high priority event
0 = Synchronous Serial Port Interrupt is a low priority event
bit RCIP: USART Receive Interrupt Priority bit
1 = USART Receive Interrupt is a high priority event
0 = USART Receive Interrupt is a low priority event
bit TXIP: USART Transmit Interrupt Priority bit
1 = USART Transmit Interrupt is a high priority event
0 = USART Transmit Interrupt is a low priority event
bit ADIP: A/D Converter Interrupt Priority bit
1 = A/D Converter Interrupt is a high priority event
0 = A/D Converter Interrupt is a low priority event
bit PSPIP: Parallel Slave Port Read/Write Interrupt Priority bit
1 = Parallel Slave Port Read/Write Interrupt is a high priority event
0 = Parallel Slave Port Read/Write Interrupt is a low priority event
39500 18C Reference Manual.book Page 16 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39510A-page 10-17
Section 10. Interrupts
Interrupts
10
bit IRXIP: CAN Invalid Received message Interrupt Priority bit
1 = CAN Invalid Received message Interrupt is a high priority event
0 = CAN Invalid Received message Interrupt is a low priority event
bit WAKIP: CAN Bus Activity Wake-up Interrupt Priority bit
1 = CAN Bus Activity Wake-up Interrupt is a high priority event
0 = CAN Bus Activity Wake-up Interrupt is a low priority event
bit ERRIP: CAN bus Error Interrupt Priority bit
1 = CAN bus Error Interrupt is a high priority event
0 = CAN bus Error Interrupt is a low priority event
bit TXB2IP: CAN Transmit Buffer 2 Interrupt Priority bit
1 = CAN Transmit Buffer 2 Interrupt is a high priority event
0 = CAN Transmit Buffer 2 Interrupt is a low priority event
bit TXB1IP: CAN Transmit Buffer 1 Interrupt Priority bit
1 = CAN Transmit Buffer 1 Interrupt is a high priority event
0 = CAN Transmit Buffer 1 Interrupt is a low priority event
bit TXB0IP: CAN Transmit Buffer 0 Interrupt Priority bit
1 = CAN Transmit Buffer 0 Interrupt is a high priority event
0 = CAN Transmit Buffer 0 Interrupt is a low priority event
bit RXB1IP: CAN Receive Buffer 1 Interrupt Priority bit
1 = CAN Receive Buffer 1 Interrupt is a high priority event
0 = CAN Receive Buffer 1 Interrupt is a low priority event
bit RXB0IP: CAN Receive Buffer 0 Interrupt Priority bit
1 = CAN Receive Buffer 0 Interrupt is a high priority event
0 = CAN Receive Buffer 0 Interrupt is a low priority event
bit EEIP: EE Write Complete Interrupt Priority bit
1 = EE Write Complete Interrupt is a high priority event
0 = EE Write Complete Interrupt is a low priority event
bit CMIP: Comparator Interrupt Priority bit
1 = Comparator Interrupt is a high priority event
0 = Comparator Interrupt is a low priority event
bit BCLIP: Bus Collision Interrupt Priority bit
1 = Bus Collision Interrupt is a high priority event
0 = Bus Collision Interrupt is a low priority event
bit LVDIP: Low-voltage Detect Interrupt Priority bit
1 = Low-voltage Detect Interrupt is a high priority event
0 = Low-voltage Detect Interrupt is a low priority event
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
Note 1: The bit position of the priority bits is device dependent. Please refer to the device
data sheet for bit placement.
39500 18C Reference Manual.book Page 17 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39510A-page 10-18 2000 Microchip Technology Inc.
10.2.5 RCON Register
The RCON register contains the bit that is used to enable prioritized interrupts (IPEN) as well as
status bits to indicate the cause of a device reset, if the device was in sleep mode and if long
writes to internal memory are enabled.
Register 10-7: RCON Register
R/W-0 R/W-0 U-0 R/W-1 R/W-1 R/W-1 R/W-0 R/W-0
IPEN LWRT — RI TO PD POR BOR
bit 7 bit 0
bit IPEN: Interrupt Priority Enable bit
1 = Enable priority levels (high and low) on interrupts
0 = Disable priority levels (all peripherals are high) on interrupts (PIC16CXXX compatibility)
(This causes the Interrupt Priority (IP) bits to be ignored)
bit 6 LWRT: Long Write Enable
For details of bit operation see description of RCON register bit in Register 3-2
bit 5 Unimplemented: Read as '0'
bit 4 RI: Reset Instruction Flag bit
For details of bit operation see description of RCON register bit in Register 3-2
bit 3 TO: Watchdog Time-out Flag bit
For details of bit operation see description of RCON register bit in Register 3-2
bit 2 PD: Power-down Detection Flag bit
For details of bit operation see description of RCON register bit in Register 3-2
bit 1 POR: Power-on Reset Status bit
For details of bit operation see description of RCON register bit in Register 3-2
bit 0 BOR: Brown-out Reset Status bit
For details of bit operation see description of RCON register bit in Register 3-2
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
39500 18C Reference Manual.book Page 18 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39510A-page 10-19
Section 10. Interrupts
Interrupts
10
10.3 Interrupt Handling Operation
The interrupts are controlled and monitored using several Special Function Registers. These
may include the following register types:
• INTCON registers
• PIR registers
• PIE registers
• IPR registers
The PIR registers contain the interrupt flag bits, the PIE registers contain the enable bits and the
IPR registers contain the priority bits. The number of PIR, PIE, and IPR registers depends on the
number of interrupt sources on the device.
10.3.1 Interrupt Priority
Each interrupt can be assigned a priority level by clearing or setting the corresponding interrupt
priority bit. The priority bits are located in the interrupt priority registers (IPR1, IPR2, IPR3,
INTCON2 and INTCON3). A ‘1’ in the priority register assigns high priority to the corresponding
interrupt. A ’0’ in the register assigns low priority to the interrupt. All interrupt priority bits are reset
to ’1’, meaning that all interrupts are assigned high priority at reset. The IPEN bit in the RCON
register enables priority levels for interrupts. If clear, all priorities are set to high.
10.3.1.1 High Priority Interrupts
A global interrupt enable bit, GIE/GIEH (INTCON<7>) enables (if set) all un-masked interrupts or
disables (if cleared) all interrupts. When bit GIE/GIEH is enabled and an interrupt’s flag bit and
enable bit are set while the priority is high, the interrupt will vector immediately. Individual interrupts
can be disabled through their corresponding enable bits in various registers. Individual
interrupt flag bits are set, regardless of the status of the GIE/GIEH bit. The GIE/GIEH bit is
cleared on reset.
When a high priority interrupt is responded to, the GIE/GIEH bit is automatically cleared to disable
any further interrupts, the return address is pushed onto the stack, and the PC is loaded with
000008h. Once in the interrupt service routine, the source of the interrupt can be determined by
polling the interrupt flag bits. The interrupt flag bit(s) must be cleared before re-enabling interrupts
to avoid recursive interrupts. Most flag bits are required to be cleared by the application
software. There are some flag bits that are automatically cleared by the hardware.
The “return from interrupt” instruction, RETFIE, exits the interrupt routine and sets the GIE/GIEH
bit, which re-enables high priority interrupts.
10.3.1.2 Low Priority Interrupts
Low priority interrupts are defined by having a “0” in an interrupt priority register IPRx. To enable
low priority interrupts, the IPEN bit must be set.
When the IPEN is set, the PEIE/GIEL bit (INTCON<6>) is no longer used to enable peripheral
interrupts. Its new function is to globally enable and disable low priority interrupts only. When the
service routine for a low priority interrupt is vectored to, the PEIE/GIEL bit is automatically cleared
in hardware to disable any further low priority interrupts.
The return address is pushed onto the stack and the PC is loaded with 000018h instead of
000008h (all low priority interrupts will vector to 000018h). Once in the interrupt service routine,
the source(s) of the low priority interrupt can be determined by polling the low priority interrupt
flag bits. The interrupt flag bit(s) must be cleared before re-enabling interrupts to avoid recursive
interrupts. Most flag bits are required to be cleared by the application software. There are some
flag bits that are automatically cleared by the hardware. The RETFIE instruction will reset the
PEIE/GIEL bit on return from low priority interrupts.
The GIE/GIEH bit’s function has not changed in that it still enables/disables all interrupts, however,
it is only cleared by hardware when servicing a high priority interrupt.
39500 18C Reference Manual.book Page 19 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39510A-page 10-20 2000 Microchip Technology Inc.
10.3.1.3 High Priority Interrupts Interrupting a Low Priority ISR
If a high priority interrupt flag and enable bits are set while servicing a low priority interrupt, the
high priority interrupt will cause the low priority ISR to be interrupted (regardless of the state of
the PEIE/GIEL bit), because it is used to disable/enable low priority interrupts only. The
GIE/GIEH bit is cleared by hardware to disable any further high and low priority interrupts, the
return address is pushed onto the stack, and the PC is loaded with 000008h (the high priority
interrupt vector). Once in the interrupt service routine, the source of the high priority interrupt can
be determined by polling the interrupt flag bits. The interrupt flag bit(s) must be cleared in software
before re-enabling interrupts to avoid recursive interrupts.
Figure 10-4 shows a high priority interrupt interrupting a low priority ISR. Figure 10-5 shows a
high priority FSR with a low priority interrupt pending.
Figure 10-4: Low Priority ISR Interrupted By High Priority Interrupt
Figure 10-5: High Priority Interrupt With Pending Low Priority Interrupt
Note: The GIEH bit, when cleared, will disable all interrupts regardless of priority.
Q1 Q2Q3 Q4 Q1 Q2Q3 Q4 Q1 Q2Q3 Q4 Q1 Q2Q3 Q4 Q1 Q2Q3 Q4 Q1 Q2Q3 Q4 Q1 Q2Q3 Q4 Q1 Q2Q3 Q4 Q1 Q2Q3 Q4 Q1 Q2Q3 Q4
OSC1
CLKOUT
INT2 pin
INT2IF
PEIE/GIEL
Program
Counter PC PC + 2
(low priority)
INT0 pin
INT0IF
GIE/GIEH
(high priority)
PC + 2
Inst(0018h)
0018h 001Ah 001Ch 001Ch 0008h 000Ah 000Ch
Inst(PC)
Inst(PC - 2)
Inst(PC + 2)
Inst(PC)
Inst(001Ah)
Inst(0018h)
Instruction Fetched
Instruction Executed Dummy Dummy
Vector to High Priority ISR
High Priority Interrupt Occurs Here
Inst(001Ah)
Inst(001Ch) Inst(0008h)
Dummy Dummy
Inst(000Ah)
Inst(0008h) Inst(000Ah)
Inst(000Ch)
Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4
OSC1
CLKOUT
INT0 pin
INT0IF
GIE/GIEH
Program
Counter PC PC + 2
(high priority)
INT2 pin
INT2IF
PEIE/GIEL
(low priority)
PC + 2
Inst(0008h)
0008h 000Ah 000Ch 000Eh PC + 2 PC + 2 0018h
Inst(PC)
Inst(PC - 2)
Inst(PC + 2)
Inst(PC)
Inst(000Ah)
Inst(0008h)
Instruction
Instruction Dummy Dummy
RETFIE
Inst(000Ah)
Inst(000Eh)
RETFIE Dummy Dummy
Fetched
Executed
Q1Q2 Q3 Q4
001Ah
Inst(PC+2)
Dummy Inst(0018h)
Vector to
Low Priority Interrupt
Vector to
High Priority Interrupt Return from
High Priority Interrupt
Inst(PC+2) Inst(0018h) Inst(001Ah)
39500 18C Reference Manual.book Page 20 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39510A-page 10-21
Section 10. Interrupts
Interrupts
10
Figure 10-6 and Figure 10-7 show the two cases where a low priority interrupt has occurred and
then a high priority interrupt occurs before the low priority ISR can begin execution. Figure 10-8
shows the first instruction of the low priority interrupt (at address 18h) beginning execution, when
the high priority interrupt causes the program counter to be forced to the high priority interrupt
vector address (08h).
Figure 10-6: Low Interrupt With High Interrupt Within 1 Cycle
Figure 10-7: Low Interrupt With High Interrupt Within 2 Cycles
Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4
OSC1
CLKOUT
Program
Counter PC
INT2 pin
INT2IF
PEIE/GIEL
(low priority)
PC
PC - 2
Instruction
Instruction
Fetched
Executed
Q1 Q2 Q3Q4
INT0 pin
INT0IF
GIE/GIEH
(high priority)
PC + 2
PC
-
Dummy
-
Dummy
0008h
Dummy
000Ah
0008h
RETFIE
000Ah
000Eh
RETFIE
0018h
Dummy
001Ah
0018h
001Ch
0018h
PC + 2 PC + 2 0018h 0008h 000Ah 000Ch 000Eh 0018h 001Ah 001Ch
Begin Vector to
Low Priority Interrupt
Return from
High Priority Interrupt
Vector to
High Priority Interrupt
to Low Priority ISR
Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4
OSC1
CLKOUT
Program
Counter PC
INT2 pin
INT2IF
PEIE/GIEL
(low priority)
PC
PC - 2
Instruction
Instruction
Fetched
Executed
Q1 Q2 Q3Q4
INT0 pin
INT0IF
GIE/GIEH
(high priority)
PC + 2
PC
-
Dummy
0018h
Dummy
-
Dummy
0008h
Dummy
000Ah
0008h
RETFIE
000Ah
000Eh
RETFIE
0018h
Dummy
001Ah
0018h
PC + 2 PC + 2 0018h 0018h 0008h 000Ah 000Ch 000Eh 0018h 001Ah
Vector to
Low Priority Interrupt
Vector to
High Priority Interrupt
Interrupt to Low Priority ISR
High Priority
Return from
39500 18C Reference Manual.book Page 21 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39510A-page 10-22 2000 Microchip Technology Inc.
Figure 10-8: Low Interrupt With High Interrupt Within 3 Cycles
Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4
OSC1
CLKOUT
Program
Counter PC
INT2 pin
INT2IF
PEIE/GIEL
(low priority)
PC
PC - 2
Instruction
Instruction
Fetched
Executed
Q1Q2 Q3 Q4
INT0 pin
INT0IF
GIE/GIEH
(high priority)
PC + 2
PC
-
Dummy
0018h
Dummy
001Ah
0018h
-
Dummy
0008h
Dummy
RETFIE
0008h
000Ch
RETFIE
001Ah
Dummy
001Ch
001Ah
PC + 2 PC + 2 0018h 001Ah 001Ah 0008h 000Ah 000Ch 001Ah 001Ch
Vector to
High Priority Interrupt
Vector to
Low Priority Interrupt
Return from
Interrupt to Low Priority ISR
High Priority
39500 18C Reference Manual.book Page 22 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39510A-page 10-23
Section 10. Interrupts
Interrupts
10
10.3.1.4 Low Priority Interrupts Interrupting a High Priority ISR
A low priority interrupt cannot interrupt a high priority ISR. The low priority interrupt will be served
after all high priority interrupts have been served.
10.3.1.5 Simultaneous High and Low Priority Interrupts
If a high priority interrupt and a low priority interrupt are sampled at the same time, the high priority
interrupt service routine is always serviced first. The GIE/GIEH bit is cleared by the hardware
and the device vectors to location 000008h to the high priority ISR. After the interrupt is
serviced, the corresponding interrupt flag should be cleared to avoid a recursive interrupt. The
RETFIE instruction resets the GIE/GIEH bit, and if no other high priority interrupts are pending,
the low priority interrupt is serviced.
10.3.1.6 Fast Context Saving During High Priority Interrupts
A "fast interrupt service" option is available for high priority interrupts. This is done by creating
shadow registers for a few key registers (WREG, BSR and STATUS). Shadow registers are provided
for the STATUS, WREG, and BSR registers and are only 1 deep. The shadow registers are
not readable and are loaded with the current value of their corresponding register when the processor
vectors for a high priority interrupt. The values in the shadow registers are then loaded
back into the actual register if the fast return instruction (RETFIE 0x01) is used to return from
the interrupt. An example for fast context saving is shown in Example 10-1.
Example 10-1: Fast Context Saving
ORG 0x08
;
; Interrupt Service Routine (ISR) code. WREG, BSR and STATUS need
; to be saved upon entering the high priority interrupt service
routine
; RETFIE 0x01 ; WREG, BSR and STATUS will be restored
Note: Fast interrupt saving cannot be used reliably if high and low priority interrupts are
enabled. See Section 10.3.1.7.
39500 18C Reference Manual.book Page 23 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39510A-page 10-24 2000 Microchip Technology Inc.
10.3.1.7 Context Saving During Low Priority Interrupts
Low priority interrupts may use the shadow registers. Any interrupt pushes values into the
shadow registers. If both low and high priority interrupts are enabled, the shadow registers cannot
be used reliably for low priority interrupts, as a high priority interrupt event will overwrite the
shadow registers.
Users must save the key registers in software during a low priority interrupt.
For example:
a) Store the STATUS, WREG and BSR registers on a software stack.
b) Execute the ISR code.
c) Restore the STATUS, WREG and BSR registers from the software stack.
39500 18C Reference Manual.book Page 24 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39510A-page 10-25
Section 10. Interrupts
Interrupts
10
Example 10-2 shows example service routine code for when high and low priority interrupts are
enabled.
Example 10-2: Interrupt Service Routine Template
ORG 0x08 ; high priority ISR
PUSH_REG_H MOVWF WREG_TEMP_HIGH
MOVFF BSR, BSR_TEMP_HIGH
MOVFF STATUS, STATUS_TEMP_HIGH
;
; High Priority Interrupt Service Routine (ISR) Code goes here
;
POP_REG_H MOVFF BSR_TEMP_HIGH, BSR
MOVF WREG_TEMP_HIGH, W
MOVFF STATUS_TEMP_HIGH, STATUS
RETFIE 0x00
;
PUSH_REG_L ORG 0x18 ; Low Priority ISR
MOVWF WREG_TEMP_LOW
MOVFF BSR, BSR_TEMP_LOW
MOVFF STATUS, STATUS_TEMP_LOW
;
; Low Priority Interrupt Service Routine (ISR) code goes here
;
Pop_REG_L MOVFF BSR_TEMP_LOW, BSR
MOVF WREG_TEMP_LOW
MOVFF STATUS_TEMP_LOW, STATUS
RETFIE 0x00
39500 18C Reference Manual.book Page 25 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39510A-page 10-26 2000 Microchip Technology Inc.
10.3.1.8 Interrupt Latency
For external interrupt events, such as the RB0/INT0 pin or PORTB change interrupt, the interrupt
latency will be three or four instruction cycles. The exact latency depends when the interrupt
event occurs. The interrupt latency is the same for one or two cycle instructions.
10.3.1.8.1 Interrupt Latency For One Cycle Instructions
Figure 10-9 shows the timing when an external interrupt is asserted during a one cycle instruction.
The interrupt is sampled on Q4. The interrupt is then acknowledged on the Q2 cycle of the
following instruction cycle when instruction PC is executed. This is followed by a forced NOP
(dummy cycle) and the contents of the PC are stored on the stack during the Q3 cycle of this
machine cycle. By the Q3/Q4 boundary of instruction cycle two, the interrupt vector is placed into
the PC, and is presented on the program memory bus on the following cycle. This cycle is also
a dummy cycle executing a forced NOP (FNOP) so that the CPU can fetch the first instruction from
the interrupt service routine.
Figure 10-9: Interrupt Flow on a 1 Cycle Instruction
INST(PC)
Executed here FNOP
Executed here FNOP
Executed here
PC PC PC+2 PC+2 PC+3 000Ch
INTxIF flag
INST (PC) INST (PC+2) INST (0008h)
0008h 000Ah
INST (000Ah) INST (PC+2)
INST(PC-1)
Executed here
INST(0008h)
Executed here INST(000Ah)
Executed here
Inst Fetched
STACK
RAM
register
Inst Execute
GIE/GIEH bit
39500 18C Reference Manual.book Page 26 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39510A-page 10-27
Section 10. Interrupts
Interrupts
10
10.3.1.8.2 Interrupt Latency For Two Cycle Instructions
Figure 10-10 shows the timing when an external interrupt is asserted during a two cycle instruction.
The interrupt is sampled on Q4. The interrupt is then acknowledged on the Q1 of the following
instruction cycle when instruction PC is executed. This is followed by the second cycle of the
instruction and the contents of the PC are stored on the stack during Q3 of this machine cycle.
For all two cycle instructions, the PC may be updated with a new PC value due to execution control
instructions like GOTO and CALL. The reason for the forced NOP (dummy cycle) is to maintain
consistent interrupt latency between one and two cycle instructions. Two cycle instructions
require this cycle for the update of the PC to a new PC value, because all two cycle instructions
with the exception of MOVFF and MOVLF are execution control type instructions that update the
PC with a new value (i.e. GOTO and CALL). The MOVFF and MOVLF instructions will increment
the PC by 2 in this cycle because an operand fetch takes place in the second cycle. By Q3/Q4
the interrupt vector 000008h is placed into the PC and is presented on the program memory bus
on the following cycle. This cycle is a dummy cycle executing a forced NOP (FNOP) so that the
CPU can fetch the first instruction from the interrupt service routine.
Figure 10-10:Interrupt Flow on a 2 Cycle or 2 Word Instruction
Note: When using the MOVFF instruction with any one of the PCL, TOSU, TOSH, and
TOSL registers as destination, all interrupts have to be disabled.
INST(PC)
Executed here CYCLE 2
Executed here FNOP
Executed here
PC PC PC+2 New PC PC+3 000Ch
INTxIF flag
INST (PC) INST (New PC) INST (0008h)
0008h 000Ah
INST (PC+2) INST (000Ah)
INST(PC-2)
Executed here INST(0008h)
Executed here INST(000Ah)
Executed here
Inst Fetched
STACK
RAM
register
Inst Execute
GIE/GIEH bit
39500 18C Reference Manual.book Page 27 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39510A-page 10-28 2000 Microchip Technology Inc.
10.3.1.9 InTerrupts During Table Write Operations (Long Writes)
The long write is necessary for programming the internal EPROM. Instruction execution is halted
while in a long write cycle. The long write will be terminated by any enabled interrupt. To ensure
that the EPROM location has been well programmed, a minimum programming time is required.
Typically, a Timer interrupt is used to time and terminate the long write. Having only one interrupt
enabled to terminate the long write ensures that no unintended interrupts will prematurely terminate
the long write.
Figure 10-11:INT0, INT1, and INT2 Pin Interrupt Timing (High Priority Shown)
Q1 Q3 Q4 Q2 Q1 Q3 Q4 Q2 Q1 Q3 Q4 Q2 Q2Q1 Q3 Q4 Q1 Q3 Q4 Q2
OSC1
CLKOUT
INT pin
INTxIF flag
GIE/GIEH bit
(INTCON<7>)
INSTRUCTION FLOW
PC
Instruction
fetched
Instruction
executed
Interrupt Latency
PC PC+2 PC+2 0008h 000Ah
Inst (0008h) Inst (000Ah)
Dummy Cycle
Inst (PC) Inst (PC+2)
Inst (PC-2) Dummy Cycle Inst (0008h) Inst (PC)
—
1
4
5
1
2
3
Note 1: INTxIF flag is sampled here (every Q1).
Note 2: Interrupt latency = 3-4TCY where TCY = instruction cycle time.
Latency is the same whether Inst (PC) is a single cycle or a 2-cycle instruction.
Note 3: CLKOUT is available only in RC oscillator mode.
Note 4: For minimum width of INT pulse, refer to AC specs.
Note 5: INTxIF is enabled to be set anytime during the Q1 cycle.
39500 18C Reference Manual.book Page 28 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39510A-page 10-29
Section 10. Interrupts
Interrupts
10
10.4 Initialization
Example 10-3 enables high and low priority interrupts. The priority level for the peripherals is
loaded into the IRP1 register (IRP1_VALUE) and the peripherals that are enabled depend on the
value of PIE1_VALUE, which is loaded into the PIE1 register.
Example 10-3: Generic Initialization Example
MOVLW RCON_VALUE ; RCON_VALUE = 1???????b
MOVWF RCON ;
MOVLW IPR1_VALUE ; Peripherals with high priority
; have a ’1’ in their bit
; position.
; Those with a low priority have
; a ’0’ in their bit position.
MOVWF IRP1 ;
CLRF PIR1 ; Clear all flag bits
MOVLW PIE1_VALUE ; Enable desired peripheral
; interrupts by setting their
; bit position.
; Disable others by clearing their
; bit position.
MOVWF PIE1 ;
CLRF INTCON3 ;
CLRF INTCON2 ;
MOVLW OxC0 ; Enable high and low global
; interrupts.
MOVWF INTCON ;
39500 18C Reference Manual.book Page 29 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39510A-page 10-30 2000 Microchip Technology Inc.
10.5 Design Tips
Question 1: My code does not seem to execute properly.
Answer 1:
There are many possible reasons. A couple of possibilities related to Interrupts are:
• Interrupts are not enabled, so the code cannot execute your expected ISR.
• The Interrupt may not be set to the priority level where your ISR code is located.
39500 18C Reference Manual.book Page 30 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39510A-page 10-31
Section 10. Interrupts
Interrupts
10
10.6 Related Application Notes
This section lists application notes that are related to this section of the manual. These application
notes may not be written specifically for the Enhanced family (that is they may be written for
the Base-Line, the Mid-Range, or High-End families), but the concepts are pertinent, and could
be used (with modification and possible limitations). The current application notes related to the
interrupts are:
Title Application Note #
No related application notes at this time.
Note: Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
http://www.microchip.com/10/faqs/codeex/
39500 18C Reference Manual.book Page 31 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39510A-page 10-32 2000 Microchip Technology Inc.
10.7 Revision History
Revision A
This is the initial released revision of the Enhanced MCU Interrupt description.
39500 18C Reference Manual.book Page 32 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39511A-page 11-1
I/O Ports
11
Section 11. I/O Ports
HIGHLIGHTS
This section of the manual contains the following major topics:
11.1 Introduction .................................................................................................................. 11-2
11.2 PORTA, TRISA, and the LATA Register ....................................................................... 11-8
11.3 PORTB, TRISB, and the LATB Register..................................................................... 11-12
11.4 PORTC, TRISC, and the LATC Register .................................................................... 11-16
11.5 PORTD, LATD, and the TRISD Register .................................................................... 11-19
11.6 PORTE, TRISE, and the LATE Register .................................................................... 11-21
11.7 PORTF, LATF, and the TRISF Register ...................................................................... 11-23
11.8 PORTG, LATG, and the TRISG Register ................................................................... 11-25
11.9 PORTH, LATH, and the TRISH Register.................................................................... 11-27
11.10 PORTJ, LATJ, and the TRISJ Register ...................................................................... 11-29
11.11 PORTK, LATK, and the TRISK Register .................................................................... 11-31
11.12 PORTL, LATL, and the TRISL Register...................................................................... 11-33
11.14 I/O Programming Considerations ............................................................................... 11-37
11.15 Initialization ................................................................................................................ 11-40
11.16 Design Tips ................................................................................................................ 11-41
11.17 Related Application Notes.......................................................................................... 11-43
11.18 Revision History ......................................................................................................... 11-44
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39511A-page 11-2 2000 Microchip Technology Inc.
11.1 Introduction
General purpose I/O pins can be considered the simplest of peripherals. They allow the PICmicro
to monitor and control other devices. To add flexibility and functionality to a device, some pins
are multiplexed with an alternate function(s). These functions depend on which peripheral features
are on the device. In general, when a peripheral is functioning, that pin may not be used as
a general purpose I/O pin.
For most ports, the I/O pin’s direction (input or output) is controlled by the data direction register,
called the TRIS register. TRIS controls the direction of PORT. A ’1’ in the TRIS bit corresponds
to that pin being an input, while a ’0’ corresponds to that pin being an output. An easy
way to remember is that a ’1’ looks like an I (input) and a ’0’ looks like an O (output).
The PORT register is the latch for the data to be output. When the PORT is read, the device reads
the levels present on the I/O pins (not the latch). This means that care should be taken with
read-modify-write commands on the ports and changing the direction of a pin from an input to an
output.
Figure 11-1 shows a typical I/O port. This does not take into account peripheral functions that
may be multiplexed onto the I/O pin. Reading the PORT register reads the status of the pins
whereas writing to it will write to the port latch. All write operations (such as BSF and BCF instructions)
are read-modify-write operations. Therefore, a write to a port implies that the port pins are
read, this value is modified, and then written to the port data latch.
Figure 11-1: Typical I/O Port
Data Bus
WR PORT
WR TRIS
RD PORT
Data Latch
TRIS Latch
P
VSS
I/O pin
D Q
CK Q
D Q
CK Q
Q D
EN
N
VDD
RD TRIS
Schmitt
Trigger
TTL or
RD LAT
Note : I/O pins have protection diodes to VDD and VSS.
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39511A-page 11-3
Section 11. I/O Ports
I/O Ports
11
When peripheral functions are multiplexed onto general I/O pins, the functionality of the I/O pins
may change to accommodate the requirements of the peripheral module. An example of this is
the Analog to Digital converter module which forces the I/O pin to the peripheral function when
the device is reset. This prevents the device from consuming excess current if any analog levels
were on the A/D pins after a reset occurred.
With some peripherals, the TRIS bit is overridden while the peripheral is enabled. Therefore,
read-modify-write instructions (BSF, BCF, XORWF) with TRIS as destination should be avoided.
The user should refer to the corresponding peripheral section for the correct TRIS bit settings.
PORT pins may be multiplexed with analog inputs and analog VREF inputs. The operation of each
of these pins is selected, to be an analog input or digital I/O, by clearing/setting the control bits
in other Special Function registers (SFRs). An example of this is the ADCON1 register for the
10-bit A/D module. Currently, when devices have pins selected as an analog input, these pins
will read as '0's.
The TRIS registers control the direction of the port pins, even when they are being used as analog
inputs. The user must ensure the TRIS bits are maintained set when using the pins as analog
inputs.
Note 1: If pins are multiplexed with analog inputs, then on a Power-on Reset these pins are
configured as analog inputs, as controlled by the ADCON1 register. Reading port
pins configured as analog inputs read a '0'.
Note 2: If pins are multiplexed with comparator inputs, then on a Power-on Reset these pins
are configured as analog inputs, as controlled by the CMCON register. Reading port
pins configured as analog inputs read a '0'.
Note 3: Pins may be multiplexed with the Parallel Slave Port (PSP). For the PSP to function,
the I/O pins must be configured as digital inputs and the PSPMODE bit must be set.
Note 4: At present, the Parallel Slave Port (PSP) is only multiplexed onto PORTD and
PORTE. The PSP port becomes enabled when the PSPMODE bit is set. In this
mode, the user must make sure that the TRISE bits are set (pins are configured as
digital inputs) and that PORTE is configured for digital I/O. PORTD will override the
values in the TRISD register. In this mode, the PORTD and PORTE input buffers
are TTL. The control bits for the PSP operation are located in TRISE.
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39511A-page 11-4 2000 Microchip Technology Inc.
11.1.1 Multiplexed Peripherals
Pins may be configured as either digital inputs or digital outputs. Digital inputs are either TTL buffers
or Schmitt Triggers. Outputs are CMOS drivers except for pin RA4, which is an open-drain
output.
All pins also support one or more peripheral modules. When configured to operate with a peripheral,
a pin may not be used for general input or output. In many cases, a pin must still be configured
for input or output, although some peripherals override the TRIS configuration.
Peripherals supported include:
• Analog to Digital Converter Modules (A/D)
• Timer Modules
- Timer0
- Timer1
- Timer2
- Timer3
• Capture/Compare/Pulse Width Modulation (CCP) modules
• External Interrupts
• Interrupt On Change pins
• Parallel Slave Port (PSP) module
• In Circuit Serial Programming
• System Oscillator
• Weak Pull-Up sources
• Synchronous Serial Port (SSP) module
- Serial Peripheral Interface (SPI)
- I2C
• Master Synchronous Serial Port (MSSP) module
- Serial Peripheral Interface (SPI)
- I2C with full hardware Master mode support
• Addressable USART module
• Controller Area Network (CAN) module
• Comparator modules
• Voltage Reference modules
• Low Voltage Detect (LVD) module
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39511A-page 11-5
Section 11. I/O Ports
I/O Ports
11
11.1.2 Output Data Latches (LATx) and Data Direction Register (TRISx)
All port pins have an output data latch. Writing to a port writes to that latch (LATx). The data latch
may also be read from and written to directly. If the pin is not being used by a peripheral, and is
configured as an output by its TRIS bit, data in the latch will be output to the pin.
All port pins have corresponding Data Direction Register bits (TRISx register) which configure
each pin as an input or output. Clearing a bit in a TRIS register (bit=0) configures the corresponding
pin for output, and drives the contents of the output data latch (LATx) to the selected pin. Setting
a TRIS register bit (bit=1) configures the corresponding pin as an input, and puts the
corresponding output driver in a high impedance state. After a reset, all pins are configured as
inputs.
Example 11-1 shows that writing the value in the WREG register to PORTB actually writes the
value to the LATB register.
Example 11-1: Writing to PORTB actually writes to LATB
There are two input paths from a port. One path simply reads back what is in the data latch (LATx)
without regard to whether or not the bits are being output, and may return values not present at
the pin. The other path reads back the state of the pin (PORTx) unless a peripheral forces it to
read back a fixed state.
Example 11-2 demonstrates the difference between reading a PORT and reading the output
latch of the PORT.
Example 11-2: Reading PORTB compared to reading LATB
Reading the PORTx register reads the status of the pins whereas writing to it will write to the port
data latch (LATx). A write to LATx can also be performed.
Example 11-3 shows the result of simply reading the PORT register. In this example, RB0 is
being overdrive low and RB1 is being overdriven high. This is NOT recommended, and may actually
violate device specifications, but is shown to give insight to the operation of an instruction
which reads the I/O port with respect to the I/O ports data latch.
Example 11-3: Reading PORTB reads the state of RB7:RB0
; LATB = 1100 0011
; RB<7:0> = 1001 0011
; TRISB = 1111 0000 1=input 0=output
; W_REG = 0010 1110
movwf PORTB ; writes W_REG to PORTB output data
; latch (LATB)
; LATB = 0010 1110
; RB<7:0> = 1001 1110 high nibble
; no change (TRISB)
; RB<7:0> = 1001 0101
; LATB = 0111 0101
; TRISB = 1111 0000 1=input 0=output
movf PORTB,W ; reads states of PORTB pins
; W_REG = 1001 0101
movf LATB,W ; reads contents of LATB data latch
; W_REG = 0111 0101
; RB<7:0> = 1001 0110
; LATB = 1100 0011
; TRISB = 1111 0000 1=input 0=output
movf PORTB,W ; reads state of pins
; W_REG = 1001 0110
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39511A-page 11-6 2000 Microchip Technology Inc.
Example 11-4 shows what effects can occur when writing to the PORT registers.
Example 11-4: Writing to PORTB
Example 11-5 shows what effects can occur when writing to the LAT registers.
Example 11-5: Writing to LATB
Any instruction that performs a write operates internally as a read-modify-write operation. Caution
must be used when these instructions are applied to a port where pins are switching between
input and output states.
For example, a BSF PORTB, 5 instruction will cause all eight bits of PORTB to be read into the
CPU. Then the instruction sets bit 5 and the resulting data is written to LATB.
If the RB7 pin is used for bi-directional I/O and is defined as an input when BSF PORTB, 5 executes,
the input signal present on the pin itself would be read into the CPU and be written to
LATB<7>, overwriting the previous contents. As long as the RB7 pin stays in the input mode, no
problem occurs. However, if the RB7 pin is switched to an output, the contents of the data latch
may be in an unintended state, causing the RB7 pin to be in the wrong state.
Example 11-6 shows how read-modify-write operations can affect the PORT register or the TRIS
register.
Example 11-6: Read-modify-write of PORTB, and TRISB change toggles RB7
A better solution would be to use the data latch instead. A BSF LATB, 5 instruction will read the
bits in the output latch, set bit 5, and write the results back to the output latch. LATB<7> will never
be at risk of being changed.
; TRISB = 1111 0000 1=input 0=output
; W_REG = 1011 0110
; LATB = 1100 0011
; RB<7:0> = 1001 0011
movwf PORTB ; writes W_REG to LATB
; LATB = 1011 0110
; RB<7:0> = 1001 0110 low nibble only
; is output
; TRISB = 1111 0000 1=input 0=output
; W_REG = 1011 0110
; LATB = 1100 0011
; RB<7:0> = 1001 0011
movwf LATB ; writes W_REG to LATB
; LATB = 1011 0110
; RB<7:0> = 1001 0110 same result as
; ‘movwf PORTB’
; RB<7:0> = 0001 0110
; LATB = 1001 0110
; TRISB = 1100 0000
bsf PORTB,5 ; read-modify-write operation.
; LATB = 0011 0110 bit 7 cleared
; RB<7:0> = 1011 0110 RB7 changes to high speed
bcf TRISB,7 ; changes RB7 from input to output
; TRISB = 0100 0000
; RB<7:0> = 0011 0110 RB7 in now driven low
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39511A-page 11-7
Section 11. I/O Ports
I/O Ports
11
Example 11-7 shows that doing read-modify-writes on the LATx register and TRISx register may
not cause the voltage level on the pin to change.
Example 11-7: Read-modify-write of LATB, and TRISB change has no effect on RB7
; RB<7:0> = 1001 0110
; LATB = 1001 0110 bit 7 is high
; TRISB = 1100 0000
bsf LATB,5 ; read-modify-write operation
; LATB = 1011 0110 bit 7 has not changed
; RB<7:0> = 1011 0110
bcf TRISB,7 ; changes RB7 from input to output
; TRISB = 0100 0000
; RB<7:0> = 1011 0110 RB7 remains high
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39511A-page 11-8 2000 Microchip Technology Inc.
11.2 PORTA, TRISA, and the LATA Register
PORTA is a 6-bit, or 7-bit latch depending upon the oscillator configuration selected by the FOSC
configuration bits. The corresponding data direction register is TRISA, the data output latch is
LATA, and the pins are PORTA. Except for RA4, all PORTA pins have TTL input buffers and full
CMOS output drivers. All pins are configured as inputs on a reset.
The RA4 pin is a Schmitt Trigger input and an open drain output. All other RA port pins have TTL
input levels and full CMOS output drivers. All pins have data direction bits (TRIS registers) which
can configure these pins as output or input.
Setting a TRISA register bit puts the corresponding output driver in a hi-impedance mode. Clearing
a bit in the TRISA register puts the contents of the output latch on the selected pin(s).
Example 11-8: Initializing PORTA
11.2.1 PORTA multi-plexed with Analog inputs
PORTA may be multiplexed with the AD module. When used as analog inputs, the TRISA must
configure the corresponding pins as digital inputs (‘1’ on TRIS bit). On all resets, the PORTA pins
are configured as analog inputs and a read of the digital inputs will result in read values of ‘0’.
CLRF PORTA ; Initialize PORTA by clearing output
; data latches
; CLRF LATA ; Alternate method to initialize PORTA
MOVLW 0xCF ; Value used to initialize data direction
MOVWF TRISA ; PORTA<3:0> = inputs PORTA<5:4> = outputs
; TRISA<7:6> always read as '0'
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39511A-page 11-9
Section 11. I/O Ports
I/O Ports
11
Figure 11-2: Block Diagram of RA3:RA0 and RA5 Pins
Data Bus
WR PORTA
WR TRISA
RD PORTA
Data Latch
TRIS Latch
P
VSS
I/O pin
To Peripheral Module(s)
D Q
CK Q
QD
CK Q
Q D
EN
N
Analog
input
mode
TTL
VDD
RD TRISA
Input
Buffer
RD LATA
or LATA
Note: I/O pins have protection diodes to VDD and VSS.
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39511A-page 11-10 2000 Microchip Technology Inc.
11.2.2 RA4 / Timer0 Clock Input
The RA4/T0CKI pin is a Schmitt Trigger input and an open drain output. Pin RA4 may be multiplexed
with the peripheral module. All other PORTA pins have TTL input levels and CMOS output
drivers.
Figure 11-3: Block Diagram of RA4 Pin
Data Bus
WR PORT
WR TRISA
RD PORTA
Data Latch
TRIS Latch
Schmitt
Trigger
Input
Buffer
N
VSS
To Peripheral Module
D Q
CK Q
D Q
CK Q
Q D
EN
RD TRISA
RA4 pin
RD LATA
or LATA
Note: I/O pins have protection diodes to VSS only.
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39511A-page 11-11
Section 11. I/O Ports
I/O Ports
11
Table 11-1: PORTA Functions
Table 11-2: Summary of Registers Associated with PORTA
Name Bit# Buffer Function
RA0 bit0 TTL Input/output port pin
RA1 bit1 TTL Input/output port pin
RA2 bit2 TTL Input/output port pin
RA3 bit3 TTL Input/output port pin
RA4/T0CKI bit4 ST Input/output port pin or external clock input for Timer0
Output is open drain type
RA5 bit5 TTL Input/output port pin
RA6 bit6 TTL Input/output port pin
Legend: TTL = TTL input, ST = Schmitt Trigger input.
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Value on:
POR,
BOR
Value on all
other resets
TRISA — PORTA Data Direction Control Register -111 1111 -111 1111
PORTA — Read PORTA pin/Write PORTA Data Latch -00x 0000 -00u 0000
LATA — Read PORTA Data Latch/Write PORTA Data Latch -xxx xxxx -uuu uuuu
ADCON1 ADFM ADCS2 — — PCFG3 PCFG2 PCFG1 PCFG0 00-- 0000 00-- 0000
Legend: x = unknown, u = unchanged, - = unimplemented locations read as '0'.
Shaded cells are not used by PORTA. ST = Schmitt Trigger input, TTL = TTL input.
39500 18C Reference Manual.book Page 11 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39511A-page 11-12 2000 Microchip Technology Inc.
11.3 PORTB, TRISB, and the LATB Register
PORTB is an 8-bit wide bidirectional port. The corresponding data direction register is TRISB,
the data output latch is LATB, and the pins are PORTB. All pins have TTL inputs.
Setting a bit in the TRISB register puts the corresponding output driver in a hi-impedance input
mode. Clearing a bit in the TRISB register puts the contents of the output latch on the selected
pin. All pins are configured as inputs on a reset.
Four of the PORTB pins have a weak internal pull-up. Clearing the RBPU bit (INTCON2<7>)
turns on pull-ups on all pins. The weak pull-up is automatically turned off when the port pin is
configured as an output. The pull-ups are disabled on a reset.
Example 11-9: Initializing PORTB
11.3.1 RB2:RB0 / External Interrupts INT2:INT0
RB2:RB0 pins can also function as external interrupt sources INT2:INT0 while working as digital
inputs. These interrupts are edge triggered on the edges selected by the bits. If enabled prior to
entering sleep mode, these interrupts can wake the controller.
INT2:INT0 inputs have Schmitt trigger inputs, while the RB2:RB0 inputs have TTL buffer inputs.
Figure 11-4: Block Diagram of RB3:RB0 Pins
CLRF PORTS ; Initialize PORTS by clearing output
; data latches
; CLRF LATB ; Alternate method to initialize data latches
MOVLW 0xCF ; Value used to initialize data direction
MOVWF TRISB ; PORTB<3:0> = inputs, PORTB<5:4> = outputs
; PORTB<7:6> = inputs
Data Latch
RBPU (2)
P
VDD
D Q
CK
D Q
CK
Q D
EN
Data Bus
WR PORTB
WR TRISB
RD TRISB
RD PORTB
weak
pull-up
RD PORTB
To Peripheral Module
TTL
Input
Buffer
Schmitt Trigger
Buffer
TRIS Latch
Note 1: I/O pins have diode protection to VDD and VSS.
Note : To enable weak pull-ups, set the appropriate TRIS bit(s) and clear the RBPU bit.
RD LATA
I/O pin (1)
39500 18C Reference Manual.book Page 12 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39511A-page 11-13
Section 11. I/O Ports
I/O Ports
11
Four of PORTB’s pins, RB7:RB4, have an interrupt on change feature. Only pins configured as
inputs can cause this interrupt to occur (i.e., any RB7:RB4 pin configured as an output is
excluded from the interrupt on change comparison). The input pins (of RB7:RB4) are compared
with the old value latched on the last read of PORTB. The present inputs of RB7:RB4 and their
previous values are XOR’ed together to detect a “mismatch” condition and set the RB Port
change interrupt flag bit RBIF. When enabled, this flag will generate an interrupt that can wake
the device from SLEEP.
This interrupt can wake the device from SLEEP. The user, in the interrupt service routine, can
clear the interrupt in the following manner:
a) Any read or write of PORTB will end the mismatch condition, except a write using the
MOVFF instruction.
b) Clear flag bit RBIF.
The MOVFF instruction will not end the mismatch condition if PORTB is used only as the destination
register. The contents of the destination register are not automatically read by this instruction
in the second cycle. All other reads, writes, and bit operations will read the port during execution.
A mismatch condition will continue to set flag bit RBIF. Reading PORTB will end the mismatch
condition, and allow flag bit RBIF to be cleared.
This interrupt on change (i.e., mismatch) feature, together with software configurable pull-ups on
these four pins allow easy interface to a keypad and make it possible for wake-up on key-depression.
The interrupt on change feature is recommended for wake-up on key depression and operations
where PORTB is only used for the interrupt on change feature. Polling of PORTB is not recommended
while using the interrupt on change feature.
39500 18C Reference Manual.book Page 13 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39511A-page 11-14 2000 Microchip Technology Inc.
Figure 11-5: Block Diagram of RB7:RB4 Pins
11.3.2 RB7:RB6 - In Circuit Serial Programming
If ICSP is implemented in the target application, some means of isolating RB7:RB6 from the rest
of the circuit should be provided. The ISCP inputs have Schmitt Triggers while the RB7:RB6
inputs have TTL inputs.
Note 1: I/O pins have diode protection to VDD and VSS.
Note 2: To enable weak pull-ups, set the appropriate TRIS bit(s) and clear the RBPU bit.
Data Latch
From other
RBPU (2)
P
D Q
CK
D Q
CK
Q D
EN
Q D
EN
Data Bus
WR PORTB
WR TRISB
Set RBIF
TRIS Latch
RD TRISB
RD PORTB
RB7:RB4 pins
weak
pull-up
RD PORTB
Latch
TTL
Input
Buffer
ST
Buffer
RB7:RB6 for In-Circuit Serial Programming mode
Q3
Q1
RD LATB
or LATB
VDD
I/O pin (1)
RD LATB
39500 18C Reference Manual.book Page 14 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39511A-page 11-15
Section 11. I/O Ports
I/O Ports
11
Table 11-3: PORTB Functions
Table 11-4: Summary of Registers Associated with PORTB
Name Bit# Buffer Function
RB0/INT0 bit0 TTL/ST (1) Input/output port pin or external interrupt0 input. Internal software
programmable weak pull-up.
RB1/INT1 bit1 TTL/ST (1) Input/output port pin or external interrupt1 input. Internal software programmable
weak pull-up.
RB2/INT2 bit2 TTL/ST (1) Input/output port pin or external interrupt2 input. Internal software programmable
weak pull-up.
RB3/CCP2 (3) bit3 TTL/ST (4) Input/output port pin or Capture2 input/Compare2 output/PWM2 output if
CCP2MX is enabled in the configuration register. Internal software programmable
weak pull-up.
RB4 bit4 TTL Input/output port pin (with interrupt on change). Internal software programmable
weak pull-up.
RB5 bit5 TTL Input/output port pin (with interrupt on change). Internal software programmable
weak pull-up.
RB6 bit6 TTL/ST (2) Input/output port pin (with interrupt on change). Internal software programmable
weak pull-up. Serial programming (CLOCK).
RB7 bit7 TTL/ST (2) Input/output port pin (with interrupt on change). Internal software programmable
weak pull-up. Serial programming (DATA).
Legend: TTL = TTL input, ST = Schmitt Trigger input.
Note 1: This buffer is a Schmitt Trigger input when configured as the external interrupt.
Note 2: This buffer is a Schmitt Trigger input when used in serial programming mode.
Note 3: The CCP2 input is only multiplexed on the RB3 pin if the CCP2MX configuration bit is ’0’.
Note 4: The CCP2 input is a Schmitt Trigger if the CCP2MX configuration bit is ’0’.
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Value on:
POR,
BOR
Value on all
other resets
TRISB PORTB Data Direction Register 1111 1111 1111 1111
PORTB Read PORTB pins/Write PORTB Data Latch xxxx xxxx uuuu uuuu
LATB Read PORTB Data Latch/Write PORTB Data Latch xxxx xxxx uuuu uuuu
INTCON GIE/GIEH PEIE/GIEL TMR0IE INT0IE RBIE TMR0IF INT0IF RBIF 0000 000x 0000 000u
INTCON2 RBPU INTEDG0 INTEDG1 INTEDG2 — TMR0IP — RBIP 1111 -1-1 1111 -1-1
INTCON3 INT2IP INT1IP — INT2IE INT1IE — INT2IF INT1IF 11-0 0-00 11-0 0-00
Legend: x = unknown, u = unchanged, - = unimplemented locations read as '0'.
Shaded cells are not used by PORTB.
39500 18C Reference Manual.book Page 15 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39511A-page 11-16 2000 Microchip Technology Inc.
11.4 PORTC, TRISC, and the LATC Register
PORTC is an 8-bit bi-directional port. Each pin is individually configurable as an input or output
through the TRISC register. The data output latch is LATC. PORTC pins have Schmitt Trigger
input buffers.
When enabling peripheral functions, care should be taken in defining TRIS bits for each PORTC
pin. Some peripherals override the TRIS bit to make a pin an output, while other peripherals override
the TRIS bit to make a pin an input, and other peripherals may not override the TRIS bits
(requires that TRIS bits are configured for proper peripheral operation). The user should refer to
the corresponding peripheral section for the correct TRIS bit settings.
Example 11-10: Initializing PORTC
Figure 11-6: PORTC Block Diagram (Peripheral Output Override)
CLRF PORTC ; Initialize PORTC
; by clearing output data latches
; CLRF LATC ; Alternate method
; to clear output latch
MOVLW 0xCF ; Value used to initialize data direction
MOVWF TRISC ; PORTC<3:0> = inputs,
; PORTC<5:4> = outputs,
; PORTC<7:6> = inputs
Data Latch
TRIS Latch
RD TRISC
P
VSS
QD
CK Q
D Q
CK Q
Q D
EN
N
VDD
0
1
WR PORTC
WR TRISC
Schmitt
Trigger
Peripheral Input
Peripheral OE (2)
Data Bus
PORT/PERIPHERAL Select (1)
Peripheral Data-out
RD PORTC
Note 1: Port/Peripheral select signal selects between port data and peripheral output.
Peripheral OE (output enable) is only activated if peripheral select is active.
I/O pins have diode protection to VDD and VSS.
I/O pin (3)
RD LATC
39500 18C Reference Manual.book Page 16 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39511A-page 11-17
Section 11. I/O Ports
I/O Ports
11
All PORTC pins have Schmitt Trigger input buffers. When a peripheral uses a pin for output, the
peripheral will override the TRIS and force the pin to be an output. Conversely, when a peripheral
uses a pin for input, the peripheral will override the TRIS and force the pin to be an input. The
TRIS is ignored while the peripheral controls the pin.
A read from the TRISC register bits will always yield the value contained in the TRISC latch
whether or not a peripheral TRIS override is being asserted. This will allow a user to read the
status of the TRISC bits at all times.
Since the TRIS bit override is in effect when the peripheral is enabled, read-modify-write instructions
(BSF, BCF and others) with TRIS as destination should be used with care.
These instructions will have no effect on the current state of the pin. However, prior to disabling
the peripheral and returning the pin to general use, the user should ensure that the TRIS bit is
correctly set for that pin.
When a peripheral uses a pin for output, the peripheral will override the TRIS and force the pin
to be an output. Conversely, when a peripheral uses a pin for input, the peripheral will override
the TRIS and force the pin to be an input. The TRIS is ignored while the peripheral controls the
pin.
A read from the TRISC register bits will always yield the value contained in the TRISC latch
whether or not a peripheral TRIS override is being asserted. This will allow a user to read the
status of the TRISC bits at all times.
Since the TRIS bit override is in effect when the peripheral is enabled, read-modify-write instructions
(BSF, BCF, and others) with TRIS as destination should be used with care.
These instructions will have no effect on the current state of the pin. However, prior to disabling
the peripheral and returning the pin to general use, the user should ensure that the TRIS bit is
correctly set for that pin.
Figure 11-7: PORTC Block Diagram (Peripheral Output Override)
Data Bus
WR LATC or
WR TRISC
RD TRISC
D Q
CK Q
Q D
CK
Peripheral Data Out
1
0
D Q
CK Q
RD PORTC
Peripheral Data In
WR PORTC RD LATC
Q
Peripheral Out
Select
Peripheral In
Select
RC7: RC0
ST Buffer
WR LATC
or PORTC
39500 18C Reference Manual.book Page 17 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39511A-page 11-18 2000 Microchip Technology Inc.
11.4.1 RC1 / CCP2 Input / Output
The RC1 pin can be multiplexed with the CCP2 module input/output. To achieve this, the
CCP2MX Configuration bit must be programmed to a ‘1’.
Table 11-5: PORTC Functions
Table 11-6: Summary of Registers Associated with PORTC
Name Bit# Buffer Type Function
RC0 bit0 ST Input/output port pin or Timer1 oscillator output or Timer1/Timer3 clock
input
RC1 bit1 ST Input/output port pin or Timer1 oscillator input
RC2 bit2 ST Input/output port pin or Capture1 input/Compare1 output/PWM1
output
RC3 bit3 ST Input/output port pin
RC4 bit4 ST Input/output port pin
RC5 bit5 ST Input/output port pin
RC6 bit6 ST Input/output port pin
RC7 bit7 ST Input/output port pin
Legend: ST = Schmitt Trigger input.
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Value on:
POR,
BOR
Value on all
other resets
TRISC PORTC Data Direction Control Register 1111 1111 1111 1111
PORTC Read PORTC pin/Write PORTC Data Latch (LATC) xxxx xxxx uuuu uuuu
LATC LATC Data Output Register xxxx xxxx uuuu uuuu
Legend: x = unknown, u = unchanged.
39500 18C Reference Manual.book Page 18 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39511A-page 11-19
Section 11. I/O Ports
I/O Ports
11
11.5 PORTD, LATD, and the TRISD Register
PORTD is an 8-bit port with Schmitt Trigger input buffers. Each pin is individually configured as
an input or output.
All PORTD pins have latch bits (LATD register). The LATD register, when read, will yield the contents
of the PORTD latch, and when written, will modify the contents of the PORTD latch. This
modifies the value driven out on a pin if the corresponding TRISD bit is configured for output. This
can be used in read-modify-write instructions that allow the user to modify the contents of the
latch register regardless of the status of the corresponding pins.
Example 11-11: Initializing PORTD
Figure 11-8: Typical PORTD Block Diagram (in I/O Port Mode)
CLRF PORTD ; Initialize PORTD
; by clearing output data latches
; CLRF LATD ; Alternate method to initialize
; data output latch
MOVLW 0xCF ; Value used to initialize data direction
MOVWF TRISD ; PORTD<3:0> = inputs,
; PORTD<5:4> = outputs,
; PORTD<7:6> = inputs
Data Bus
WR LATD
WR TRISD
RD PORTD
Data Latch
TRIS Latch
Schmitt
Trigger
Input
Buffer
D Q
CK
D Q
CK
Q D
EN
I/O pin (1)
RD TRISD
Note 1: I/O pins have protection diodes to VDD and VSS.
RD LATD
or PORTD
39500 18C Reference Manual.book Page 19 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39511A-page 11-20 2000 Microchip Technology Inc.
Table 11-7: PORTD Functions
Table 11-8: Summary of Registers Associated with PORTD
Name Bit# Buffer Type Function
RD0 bit0 ST Input/output port pin
RD1 bit1 ST Input/output port pin
RD2 bit2 ST Input/output port pin
RD3 bit3 ST Input/output port pin
RD4 bit4 ST Input/output port pin
RD5 bit5 ST Input/output port pin
RD6 bit6 ST Input/output port pin
RD7 bit7 ST Input/output port pin
Legend: ST = Schmitt Trigger input, TTL = TTL input.
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Value on:
POR,
BOR
Value on all
other resets
TRISD PORTD Data Direction Control Register 1111 1111 1111 1111
PORTD Read PORTD pin / Write PORTD Data Latch xxxx xxxx uuuu uuuu
LATD Read PORTD Data Latch/Write PORTD Data Latch xxxx xxxx uuuu uuuu
PSPCON (1) IBF OBF IBOV PSPMODE — — — — 0000 xxxx 0000 uuuu
Legend: x = unknown, u = unchanged.
Note 1: In some devices, the four bits in the PSPCON register may be located in the upper four bits of the TRISE
register.
39500 18C Reference Manual.book Page 20 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39511A-page 11-21
Section 11. I/O Ports
I/O Ports
11
11.6 PORTE, TRISE, and the LATE Register
PORTE can be up to an 8-bit port with Schmitt Trigger input buffers. Each pin is individually configurable
as an input or output.
Example 11-12: Initializing PORTE
Figure 11-9: Typical PORTE Block Diagram (in I/O Port Mode)
CLRF PORTE ; Initialize PORTE by clearing output
; data latches
; CLRF LATE ; Alternate method to initialize
; data output latch
MOVLW 0x03 ; Value used to initialize data direction
MOVWF TRISE ; PORTE<1:0> = inputs,
; PORTE<7:2> = outputs
Data Bus
WR PORT
WR TRIS
RD PORT
Data Latch
TRIS Latch
Schmitt
Trigger
Input
Buffer
D Q
CK Q
D Q
CK Q
Q D
EN
I/O pin (1)
RD TRIS
Note 1: I/O pins have protection diodes to VDD and VSS.
Note: On some devices with PORTE, the upper bits of the TRISE register are used for the
Parallel Slave Port control and status bits.
39500 18C Reference Manual.book Page 21 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39511A-page 11-22 2000 Microchip Technology Inc.
Table 11-9: PORTE Functions
Table 11-10: Summary of Registers Associated with PORTE
Name Bit# Buffer Type Function
RE0 bit0 ST Input/output port pin
RE1 bit1 ST Input/output port pin
RE2 bit2 ST Input/output port pin
Legend: ST = Schmitt Trigger input, TTL = TTL input.
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Value on:
POR,
BOR
Value on
all
other
resets
TRISE IBF OBF IBOV PSPMODE
— PORTE Data Direction Bits 0000 -111 0000 -111
PORTE — — — — — RE2 RE1 RE0 ---- -000 ---- -000
LATE — — — — — LATE Data Output Register ---- -xxx ---- -uuu
ADCON1 ADFM ADCS2 — — PCFG3 PCFG2 PCFG1 PCFG0 --0- 0000 --0- 0000
PSPCON (1) IBF OBF IBOV PSPMODE
— — — — 0000 xxxx 0000 uuuu
Legend: x = unknown, u = unchanged.
Note 1: In some devices, the four bits in the PSPCON register may be located in the upper four bits of the TRISE
register.
39500 18C Reference Manual.book Page 22 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39511A-page 11-23
Section 11. I/O Ports
I/O Ports
11
11.7 PORTF, LATF, and the TRISF Register
PORTF is an 8-bit port with Schmitt Trigger input buffers. Each pin is individually configured as
an input or output.
All PORTF pins have latch bits (LATF register). The LATF register, when read, will yield the contents
of the PORTF latch, and when written, will modify the contents of the PORTF latch. This
modifies the value driven out on a pin if the corresponding TRISF bit is configured for output. This
can be used in read-modify-write instructions that allow the user to modify the contents of the
latch register regardless of the status of the corresponding pins.
PORTF pins are multiplexed with analog inputs, system bus address bits, chip enables, and the
UB and LB external bus control signals. The operation of each analog pin is selected by clearing/setting
the control bits in the ADCON0 and ADCON1 register.
The TRISF register controls the direction of the RF pins, even when they are being used as analog
inputs. The user must ensure the bits in the TRISF register are maintained set when using
them as analog inputs.
Figure 11-10: RF1:RF0 Block Diagram
Note: On all forms of Reset, the RF2:RF0 are configured as analog inputs and read as '0'.
Data Bus
WR LATF
WR TRISF
RD PORTF
Data Latch
TRIS Latch
P
VSS
I/O pin (1)
D Q
CK Q
D Q
CK Q
Q D
EN
N
VDD
RD TRISF
RD LATF
or PORTF
To Peripheral Module
Analog
Input
Mode
ST
Input
Buffer
Note 1: I/O pins have protection diodes to VDD and VSS.
39500 18C Reference Manual.book Page 23 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39511A-page 11-24 2000 Microchip Technology Inc.
Table 11-11: PORTF Functions
Table 11-12: Summary of Registers Associated with PORTF
Name Bit# Buffer Type Function
RF0 bit0 ST Input/output port pin
RF1 bit1 ST Input/output port pin
RF2 bit2 ST Input/output port pin
RF3 bit3 ST Input/output port pin
RF4 bit4 ST Input/output port pin
RF5 bit5 ST Input/output port pin
RF6 bit6 ST Input/output port pin
RF7 bit7 ST Input/output port pin
Legend: ST = Schmitt Trigger input.
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Value on:
POR,
BOR
Value on all
other resets
TRISF PORTF Data Direction Control Register 1111 1111 1111 1111
PORTF Read PORTF pin / Write PORTF Data Latch xxxx xx00 uuuu u000
LATF Read PORTF Data Latch/Write PORTF Data Latch 0000 0000 uuuu u000
Legend: x = unknown, u = unchanged. Shaded cells are not used by Port F.
39500 18C Reference Manual.book Page 24 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39511A-page 11-25
Section 11. I/O Ports
I/O Ports
11
11.8 PORTG, LATG, and the TRISG Register
PORTG is a 5-bit port with Schmitt Trigger input buffers. Each pin is individually configured as an
input or output.
All PORTG pins have latch bits (LATG register). The LATG register, when read, will yield the contents
of the PORTG latch, and when written, will modify the contents of the PORTG latch. This
modifies the value driven out on a pin if the corresponding TRISG bit is configured for output.
This can be used in read-modify-write instructions that allow the user to modify the contents of
the latch register regardless of the status of the corresponding pins.
Figure 11-11: PORTG Block Diagram
Data Bus
WR LATG
WR TRISG
RD PORTG
Data Latch
TRIS Latch
Schmitt
Trigger
Input
Buffer
D Q
CK
D Q
CK
Q D
EN
I/O pin (1)
RD TRISG
Note 1: I/O pins have protection diodes to VDD and VSS.
RD LATG
or PORTG
39500 18C Reference Manual.book Page 25 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39511A-page 11-26 2000 Microchip Technology Inc.
Table 11-13: PORTG Functions
Table 11-14: Summary of Registers Associated with PORTG
Name Bit# Buffer Type Function
RG0 bit0 ST Input/output port pin
RG1 bit1 ST Input/output port pin
RG2 bit2 ST Input/output port pin
RG3 bit3 ST Input/output port pin
RG4 bit4 ST Input/output port pin
RG5 bit5 ST Input/output port pin
RG6 bit6 ST Input/output port pin
RG7 bit7 ST Input/output port pin
Legend: ST = Schmitt Trigger input.
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Value on:
POR,
BOR
Value on all
other resets
TRISG PORTG Data Direction Control Register ---1 1111 ---1 1111
PORTG Read PORTG pin / Write PORTG Data Latch ---x xxxx ---u uuuu
LATG Read PORTG Data Latch/Write PORTG Data Latch ---x xxxx ---u uuuu
Legend: x = unknown, u = unchanged.
39500 18C Reference Manual.book Page 26 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39511A-page 11-27
Section 11. I/O Ports
I/O Ports
11
11.9 PORTH, LATH, and the TRISH Register
PORTH is an 8-bit port with Schmitt Trigger input buffers. Each pin is individually configured as
an input or output.
All PORTH pins have latch bits (LATH register). The LATH register, when read, will yield the contents
of the PORTH latch, and when written, will modify the contents of the PORTH latch. This
modifies the value driven out on a pin if the corresponding TRISH bit is configured for output. This
can be used in read-modify-write instructions that allow the user to modify the contents of the
latch register regardless of the status of the corresponding pins.
Figure 11-12: PORTH Block Diagram
Data Bus
WR LATH
WR TRISG
RD PORTH
Data Latch
TRIS Latch
Schmitt
Trigger
Input
Buffer
D Q
CK
D Q
CK
Q D
EN
I/O pin (1)
RD TRISH
Note 1: I/O pins have protection diodes to VDD and VSS.
RD LATH
or PORTH
To Peripheral Module
39500 18C Reference Manual.book Page 27 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39511A-page 11-28 2000 Microchip Technology Inc.
Table 11-15: PORTH Functions
Table 11-16: Summary of Registers Associated with PORTH
Name Bit# Buffer Type Function
RH0 bit0 ST Input/output port pin
RH1 bit1 ST Input/output port pin
RH2 bit2 ST Input/output port pin
RH3 bit3 ST Input/output port pin
RH4 bit4 ST Input/output port pin
RH5 bit5 ST Input/output port pin
RH6 bit6 ST Input/output port pin
RH7 bit7 ST Input/output port pin
Legend: TTL = TTL input.
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Value on:
POR,
BOR
Value on all
other resets
TRISH PORTH Data Direction Control Register 1111 1111 1111 1111
PORTH Read PORTH pin / Write PORTH Data Latch 0000 xxxx 0000 uuuu
LATH Read PORTH Data Latch/Write PORTH Data Latch xxxx xxxx uuuu uuuu
Legend: x = unknown, u = unchanged, - = unimplemented. Shaded cells are not used by Port H.
39500 18C Reference Manual.book Page 28 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39511A-page 11-29
Section 11. I/O Ports
I/O Ports
11
11.10 PORTJ, LATJ, and the TRISJ Register
PORTJ is an 8-bit port with Schmitt Trigger input buffers. Each pin is individually configured as
an input or output.
All PORTJ pins have latch bits (LATJ register). The LATJ register, when read, will yield the contents
of the PORTJ latch, and when written, will modify the contents of the PORTJ latch. This
modifies the value driven out on a pin if the corresponding TRISJ bit is configured for output. This
can be used in read-modify-write instructions that allow the user to modify the contents of the
latch register regardless of the status of the corresponding pins.
Figure 11-13: PORTJ Block Diagram
Data Bus
WR LATJ
WR TRISJ
RD PORTJ
Data Latch
TRIS Latch
Schmitt
Trigger
Input
Buffer
D Q
CK
D Q
CK
Q D
EN
I/O pin (1)
RD TRISJ
Note 1: I/O pins have protection diodes to VDD and VSS.
RD LATJ
or PORTJ
39500 18C Reference Manual.book Page 29 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39511A-page 11-30 2000 Microchip Technology Inc.
Table 11-17: PORTJ Functions
Table 11-18: Summary of Registers Associated with PORTJ
Name Bit# Buffer Type Function
RJ0 bit0 ST Input/output port pin
RJ1 bit1 ST Input/output port pin
RJ2 bit2 ST Input/output port pin
RJ3 bit3 ST Input/output port pin
RJ4 bit4 ST Input/output port pin
RJ5 bit5 ST Input/output port pin
RJ6 bit6 ST Input/output port pin
RJ7 bit7 ST Input/output port pin
Legend: ST = Schmitt Trigger input.
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Value on:
POR,
BOR
Value on all
other resets
TRISJ PORTJ Data Direction Control Register 1111 1111 1111 1111
PORTJ Read PORTJ pin / Write PORTJ Data Latch xxxx xxxx uuuu uuuu
LATJ Read PORTJ Data Latch/Write PORTJ Data Latch xxxx xxxx uuuu uuuu
Legend: x = unknown, u = unchanged.
39500 18C Reference Manual.book Page 30 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39511A-page 11-31
Section 11. I/O Ports
I/O Ports
11
11.11 PORTK, LATK, and the TRISK Register
PORTK is an 8-bit port with Schmitt Trigger input buffers. Each pin is individually configured as
an input or output.
Figure 11-14: PORTK Block Diagram
Data Bus
WR LATK
WR TRISK
RD PORTK
Data Latch
TRIS Latch
Schmitt
Trigger
Input
Buffer
D Q
CK
D Q
CK
Q D
EN
I/O pin (1)
RD TRISK
Note 1: I/O pins have protection diodes to VDD and VSS.
RD LATK
or PORTK
39500 18C Reference Manual.book Page 31 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39511A-page 11-32 2000 Microchip Technology Inc.
Table 11-19: PORTK Functions
Table 11-20: Summary of Registers Associated with PORTK
Name Bit# Buffer Type Function
RK0 bit0 ST Input/output port pin
RK1 bit1 ST Input/output port pin
RK2 bit2 ST Input/output port pin
RK3 bit3 ST Input/output port pin
RK4 bit4 ST Input/output port pin
RK5 bit5 ST Input/output port pin
RK6 bit6 ST Input/output port pin
RK7 bit7 ST Input/output port pin
Legend: ST = Schmitt Trigger input.
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Value on:
POR,
BOR
Value on all
other resets
TRISK PORTK Data Direction Control Register 1111 1111 1111 1111
PORTK Read PORTK pin / Write PORTK Data Latch xxxx xxxx uuuu uuuu
LATK Read PORTK Data Latch/Write PORTK Data Latch xxxx xxxx uuuu uuuu
Legend: x = unknown, u = unchanged.
39500 18C Reference Manual.book Page 32 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39511A-page 11-33
Section 11. I/O Ports
I/O Ports
11
11.12 PORTL, LATL, and the TRISL Register
PORTL is a 8-bit port with Schmitt Trigger input buffers. Each pin is individually configured as an
input or output.
Figure 11-15: Block Diagram of PORTL Pins
Data Bus
WR LATL
WR TRISL
RD PORTL
Data Latch
TRIS Latch
Schmitt
Trigger
Input
Buffer
D Q
CK
D Q
CK
Q D
EN
I/O pin (1)
RD TRISL
Note 1: I/O pins have protection diodes to VDD and VSS.
RD LATL
or PORTL
39500 18C Reference Manual.book Page 33 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39511A-page 11-34 2000 Microchip Technology Inc.
Table 11-21: PORTL Functions
Table 11-22: Summary of Registers Associated with PORTL
Name Bit# Buffer Type Function
RL0 bit0 ST Input/output port pin
RL1 bit1 ST Input/output port pin
RL2 bit2 ST Input/output port pin
RL3 bit3 ST Input/output port pin
RL4 bit4 ST Input/output port pin
RL5 bit5 ST Input/output port pin
RL6 bit6 ST Input/output port pin
RL7 bit7 ST Input/output port pin
Legend: ST = Schmitt Trigger input.
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Value on:
POR,
BOR
Value on all
other resets
TRISL PORTL Data Direction Control Register 1111 1111 1111 1111
PORTL Read PORTL pin / Write PORTL Data Latch xxxx xxxx uuuu uuuu
LATL Read PORTL Data Latch/Write PORTL Data Latch xxxx xxxx uuuu uuuu
Legend: x = unknown, u = unchanged.
39500 18C Reference Manual.book Page 34 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39511A-page 11-35
Section 11. I/O Ports
I/O Ports
11
11.13 Functions Multiplexed on I/O Pins
This section discusses a couple of functions that are multiplexed on to I/O pins that are new concepts
when compared to the Mid-Range family.
11.13.1 Oscillator Configuration
If the system oscillator uses RCIO or ECIO mode, then the OSC2 pin may be used as a general
purpose I/O pin. If any other oscillator mode is used, the I/O pin multiplexed with OSC2 is disabled
and will read ‘0’, as will the TRIS bit and LAT bit associated with the I/O pin. Writes to I/O
pin will have no effect. See Table 11-23.
If the system oscillator uses RC or EC mode, then the I/O pin is configured as OSC2 and outputs
Fosc/4.
Table 11-23: RA6 Configuration for Oscillator Configuration
Figure 11-16: Block Diagram of I/O
Oscillator Configuration TRIS PORT LAT OSC2 / I/O
Function
RCIO / ERIO Read / Write Read / Write Read / Write General I/O
RC / EC Disabled
(reads 0)
Disabled
(reads 0)
Disabled
(reads 0)
FOSC/4
Other system oscillator modes Disabled
(reads 0)
Disabled
(reads 0)
Disabled
(reads 0)
OSC2
D Q
CK Q
D Q
CK Q
Q D
EN
P
N
WR TRIS
Data Latch
TRIS Latch
RD TRIS
RD PORT
Vss
VDD
I/O pin (1)
Note 1: I/O pins have protection diodes to VDD and VSS.
RD LAT
ECIO or RCIO enable
Data Bus
ECIO or
enable
Data Bus
TTL
Input
Buffer
RCIO
Data Bus
WR LAT
or PORT
39500 18C Reference Manual.book Page 35 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39511A-page 11-36 2000 Microchip Technology Inc.
11.13.2 CCP2 Pin Multiplexing
In the PIC18CXX2 devices, the RB3 pin can be multiplexed with the CCP2 module input/output.
To achieve this, the CCP2MX configuration bit must be programmed to a ‘0’.
Figure 11-17: Block Diagram of RB3
RB LATB
P
CK
Data Bus
weak
pull-up
CCP2 Input
TTL
Buffer
Schmitt Trigger
RBPU
P
N
VDD
Vss
RB3/CCP2
CCP2MX
QD
Q
1
0
CK
QD
Q
RD TRISB
WR TRISB
Q
Q D
CK
RD PORTB
PWM2 OUT
PWM2 OUT
CCP2 IN SELECT
WR LATB or
WR PORTB
SELECT
Note: I/O pin has diode protection to VDD and VSS.
Note:To enable weak pull-ups, set the appropriate TRIS bit(s) and clear the RBPU bit (INTCON2).
Note:The CCP2 input/output is multiplexed with RB3 if the CCP2MX bit is enabled (=’0’) in the configuration register.
VDD
39500 18C Reference Manual.book Page 36 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39511A-page 11-37
Section 11. I/O Ports
I/O Ports
11
11.14 I/O Programming Considerations
When using the ports as I/O, design considerations need to be taken into account to ensure that
the operation is as intended.
11.14.1 Bi-directional I/O Ports
Any instruction that performs a write operation, actually does a read followed by a write operation.
The BCF and BSF instructions, for example, read the register into the CPU, execute the bit operation
and write the result back to the register. Caution must be used when these instructions are
applied to a port with both inputs and outputs defined. For example, a BSF operation on bit5 of
PORTB will cause all eight bits of PORTB to be read into the CPU. Then the BSF operation takes
place on bit5 and PORTB is written to the output latches. If another bit of PORTB is used as a
bi-directional I/O pin (e.g., bit0) and it is defined as an input at this time, the input signal present
on the pin itself would be read into the CPU and rewritten to the data latch of this particular pin,
overwriting the previous content. As long as the pin stays in the input mode, no problem occurs.
However, if bit0 is switched to an output, the content of the data latch may now be unknown.
Reading the port register, reads the values of the port pins. Writing to the port register writes the
value to the port latch. When using read-modify-write instructions (e.g., BCF, BSF, etc.) on a
port, the value of the port pins is read, the desired operation is performed on this value, and the
value is then written to the port latch.
Example 11-13 shows the effect of two sequential read-modify-write instructions on an I/O port.
Example 11-13: Read-Modify-Write Instructions on an I/O Port
A pin configured as an output, actively driving a Low or High, should not be driven from external
devices at the same time in order to change the level on this pin (“wired-or”, “wired-and”). The
resulting high output currents may damage the chip.
; Initial PORT settings: PORTB<7:4> Inputs
; PORTB<3:0> Outputs
; PORTB<7:6> have external pull-ups and are not connected to other circuitry
;
; PORT latch PORT pins
; ---------- ---------
BCF PORTB, 7 ; 01pp pppp 11pp pppp
BCF PORTB, 6 ; 10pp pppp 11pp pppp
BCF TRISB, 7 ; 10pp pppp 11pp pppp
BCF TRISB, 6 ; 10pp pppp 10pp pppp
;
; Note that the user may have expected the pin values to be 00pp ppp.
; The 2nd BCF caused RB7 to be latched as the pin value (high).
39500 18C Reference Manual.book Page 37 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39511A-page 11-38 2000 Microchip Technology Inc.
11.14.2 Successive Operations on an I/O Port
The actual write to an I/O port happens at the end of an instruction cycle, whereas for reading,
the data must be valid at the beginning of the instruction cycle (Figure 11-18). Therefore, care
must be exercised if a write followed by a read operation is carried out on the same I/O port. The
sequence of instructions should be such to allow the pin voltage to stabilize (load dependent)
before the next instruction that causes that file to be read into the CPU is executed. Otherwise,
the previous state of that pin may be read into the CPU rather than the new state. When in doubt,
it is better to separate these instructions with a NOP or another instruction not accessing this I/O
port.
This example shows a write to PORTB followed by a read from PORTB.
Therefore, at higher clock frequencies, a write followed by a read may be problematic due to
external capacitance.
Figure 11-18: Successive I/O Operation
Note: Data setup time = (0.25TCY - TPD),
where TCY = instruction cycle,
TPD = propagation delay.
PC PC + 1 PC + 2 PC + 3
Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4
Instruction
fetched
RB7:RB0
MOVWF PORTB
write to
PORTB
NOP
Port pin
sampled here
NOP
MOVF PORTB,W
Instruction
executed
MOVWF PORTB
write to
PORTB
NOP
MOVF PORTB,W
PC
TPD
39500 18C Reference Manual.book Page 38 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39511A-page 11-39
Section 11. I/O Ports
I/O Ports
11
Figure 11-19 shows the I/O model that causes this situation. As the effective capacitance (C)
becomes larger, the rise/fall time of the I/O pin increases. As the device frequency increases or
the effective capacitance increases, the possibility of this subsequent PORTx read-modify-write
instruction issue increases. This effective capacitance includes the effects of the board traces.
A way to address this is to add an series resistor at the I/O pin. This resistor allows the I/O pin to
get to the desired level before the next instruction.
The use of NOP instructions between the subsequent PORTx read-modify-write instructions, is a
lower cost solution, but has the issue that the number of NOP instructions is dependent on the
effective capacitance C and the frequency of the device.
Figure 11-19: I/O Connection Issues
PIC18CXXX
I/O
C (1)
Q4 Q1 Q2 Q3 Q4 Q1
VIL
BSF PORTx, PINy
Q2 Q3
BSF PORTx, PINz
PORTx, PINy
Read PORTx, PINy as low
BSF PORTx, PINz clears the value
to be driven on the PORTx, PINy pin.
Note 1: This is not a capacitor to ground, but the effective capacitive loading on the trace.
39500 18C Reference Manual.book Page 39 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39511A-page 11-40 2000 Microchip Technology Inc.
11.15 Initialization
See the section describing each port for examples of initialization of the ports.
Note: It is recommended that when initializing the port, the PORT data latch (LAT or PORT
register) should be initialized first, and then the data direction (TRIS register). This
will eliminate a possible pin glitch, since the LAT register (PORT data latch values)
power up in a random state.
39500 18C Reference Manual.book Page 40 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39511A-page 11-41
Section 11. I/O Ports
I/O Ports
11
11.16 Design Tips
Question 1: Code will not toggle any I/O ports, but the oscillator is running. What can I
be doing wrong?
Answer 1:
1. Have the TRIS registers been initialized properly? These registers can be written to
directly in the access bank (Bank15).
2. Is there a peripheral multiplexed onto those pins that are enabled?
3. Is the Watchdog Timer enabled (done at programming)? If it is enabled, is it being cleared
properly with a CLRWDT instruction at least every 9 ms (or more if prescaled)?
4. Are you using the correct instructions to write to the port? More than one person has used
the MOVF command when they should have used MOVWF.
5. For parts with interrupts, are the interrupts disabled? If not, try disabling them to verify they
are not interfering.
Question 2: When my program reads a port, I get a different value than what I put in the
port register. What can cause this?
Answer 2:
1. When a port is read, it is always the pin that is read, regardless of its being set to input or
output. So if a pin is set to an input, you will read the value on the pin regardless of the
register value.
2. If a pin is set to output, for instance, it has a one in the data latch; if it is shorted to ground,
you will still read a zero on the pin. This is very useful for building fault tolerant systems,
or handling I2C bus conflicts. (The I2C bus is only driven low, and the pin is high impedance
for a one. If the pin is low and you are not driving it, some other device is trying to
take the bus).
3. Enhanced devices all have at least one open drain (or open collector) pin. These pins can
only drive a zero or high impedance. For most Enhanced devices, this is pin RA4. Open
drain pins must have a pull-up resistor to have a high state. This pin is useful for driving
odd voltage loads. The pull-up can be connected to a voltage (typically less than VDD)
which becomes the high state.
4. Some analog modules, when enabled, will force a read value of ‘0’ from the pin, regardless
of the voltage level on the pin.
Question 3: I have a PIC18CXX2 with pin RB0 configured as an interrupt input, but am
not getting interrupted. When I change my routine to poll the pin, it reads
the high input and operates fine. What is the problem?
Answer 3:
PORTB accepts TTL input levels (on most parts), so when you have an input of say 3V (with
VDD = 5V), you will read a ‘1’. However, the buffer to the interrupt structure from pin RB0 is a
Schmitt Trigger, which requires a higher voltage (than TTL input) before the high input is registered.
So it is possible to read a ‘1’, but not get the interrupt. The interrupt was given a Schmitt
Trigger input with hysteresis to minimize noise problems. It is one thing to have short noise spikes
on a pin that is a data input that can potentially cause bad data, but quite another to permit noise
to cause an interrupt, hence the difference.
39500 18C Reference Manual.book Page 41 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39511A-page 11-42 2000 Microchip Technology Inc.
Question 4: When I perform a BCF instruction, other pins get cleared in the port. Why?
Answer 4:
1. Another case where a read-modify-write instruction may seem to change other pin values
unexpectedly can be illustrated as follows: Suppose you make PORTC all outputs, and
drive the pins low. On each of the port pins is an LED connected to ground, such that a
high output lights it. Across each LED is a 100 µF capacitor. Let's also suppose that the
processor is running very fast, say 20 MHz. Now if you go down the port, setting each pin
in order; BSF PORTC,0 then BSF PORTC,1 then BSF PORTC,2 and so on, you may see
that only the last pin was set, and only the last LED actually turns on. This is because the
capacitors take a while to charge. As each pin was set, the pin before it was not charged
yet, and so was read as a zero. This zero is written back out to the port latch (r-m-w,
remember), which clears the bit you just tried to set in the previous instruction. This is usually
only a concern at high speeds and for successive port operations, but it can happen,
so take it into consideration.
2. If this is on a PIC18CXXX device with A/D, you have not configured the I/O pins properly
in the ADCON1 register. If a pin is configured for analog input, any read of that pin will read
a zero, regardless of the voltage on the pin. This is an exception to the normal rule that
the pin state is always read. You can still configure an analog pin as an output in the TRIS
register, and drive the pin high or low by writing to it, but you will always read a zero. Therefore,
if you execute a Read-Modify-Write instruction (see previous question), all analog
pins are read as zero; those not directly modified by the instruction will be written back to
the port latch as zero. A pin configured as analog is expected to have values that may be
neither high nor low to a digital pin, or floating. Floating inputs on digital pins are a no-no,
and can lead to high current draw in the input buffer, so the input buffer is disabled.
39500 18C Reference Manual.book Page 42 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39511A-page 11-43
Section 11. I/O Ports
I/O Ports
11
11.17 Related Application Notes
This section lists application notes that are related to this section of the manual. These application
notes may not be written specifically for the Enhanced family (that is they may be written for
the Baseline, the Midrange, or High-end families), but the concepts are pertinent, and could be
used (with modification and possible limitations). The current application notes related to I/O
ports are:
Title Application Note #
Improving the Susceptibility of an Application to ESD AN595
Clock Design using Low Power/Cost Techniques AN615
Implementing Wake-up on Keystroke AN528
Interfacing to AC Power Lines AN521
Multiplexing LED Drive and a 4 x 4 Keypad Sampling AN529
Using PIC16C5X as an LCD Drivers AN563
Serial Port Routines Without Using TMR0 AN593
Implementation of an Asynchronous Serial I/O AN510
Using the PORTB Interrupt on Change Feature as an External Interrupt AN566
Implementing Wake-up on Keystroke AN522
Apple Desktop Bus AN591
Software Implementation of Asynchronous Serial I/O AN555
Communicating with the I2C Bus using the PIC16C5X AN515
Interfacing 93CX6 Serial EEPROMs to the PIC16C5X Microcontrollers AN530
Logic Powered Serial EEPROMs AN535
Interfacing 24LCXXB Serial EEPROMs to the PIC16C54 AN567
Using the 24XX65 and 24XX32 with Stand-alone PIC16C54 Code AN558
Note: Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
http://www.microchip.com/10/faqs/codeex/
39500 18C Reference Manual.book Page 43 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39511A-page 11-44 2000 Microchip Technology Inc.
11.18 Revision History
Revision A
This is the initial released revision of the Enhanced MCU I/O Ports description.
39500 18C Reference Manual.book Page 44 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39512-page 12-1
Parallel
Slave Port
12
Section 12. Parallel Slave Port
HIGHLIGHTS
This section of the manual contains the following major topics:
12.1 Introduction .................................................................................................................. 12-2
12.2 Control Register ........................................................................................................... 12-3
12.3 Operation ..................................................................................................................... 12-5
12.4 Operation in SLEEP Mode........................................................................................... 12-6
12.5 Effect of a RESET........................................................................................................ 12-6
12.6 PSP Waveforms ........................................................................................................... 12-6
12.7 Design Tips .................................................................................................................. 12-8
12.8 Related Application Notes............................................................................................ 12-9
12.9 Revision History ......................................................................................................... 12-10
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39512-page 12-2 2000 Microchip Technology Inc.
12.1 Introduction
Some devices have an 8-bit wide Parallel Slave Port (PSP). This port is multiplexed onto one of
the device’s I/O ports. The port operates as an 8-bit wide Parallel Slave Port, or microprocessor
port, when the PSPMODE control bit is set. In this mode, the input buffers are TTL.
In slave mode, the module is asynchronously readable and writable by the external world through
the RD control input pin and the WR control input pin.
It can directly interface to an 8-bit microprocessor data bus. The external microprocessor can
read or write the PORT latch as an 8-bit latch. Setting the PSPMODE bit enables port pins to be
the RD input, the WR input, and the CS (chip select) input.
There are actually two 8-bit latches, one for data-out (from the PICmicro) and one for data input.
The user writes 8-bit data to the PORT data latch and reads data from the port pin latch (note
that they have the same address). In this mode, the TRIS register is ignored, since the microprocessor
is controlling the direction of data flow.
Register 12-1 shows the block diagram for the PSP module.
Figure 12-1: PORTD and PORTE Block Diagram (Parallel Slave Port)
Note 1: At present the Parallel Slave Port (PSP) is only multiplexed onto PORTD and
PORTE. The microprocessor port becomes enabled when the PSPMODE bit is set.
In this mode, the user must make sure that PORTD and PORTE are configured as
digital I/O. That is, peripheral modules multiplexed onto the PSP functions are disabled
(such as the A/D).
When PORTE is configured for digital I/O, PORTD will override the values in the
TRISD register.
2: In this mode the PORTD and PORTE input buffers are TTL. The control bits for the
PSP operation are located in TRISE.
EN
D Q
CK
Data Bus
WR LATD
RD PORTD
One bit of PORTD
Set interrupt flag
PSPIF
PSP<7:0>
TTL
TTL
Read
Chip Select
Write
RD
CS
WR
EN
Q D
EN
TTL
TTL
or PORTD
RD LATD
Note: I/O pins have protection diodes to VDD and VSS.
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39512-page 12-3
Section 12. Parallel Slave Port
Parallel
Slave Port
12
12.2 Control Register
Register 12-1 is the PSP control register (PSPCON). The TRISE register (Register 12-2) contains
the 4 bits for the PSP module found in some devices (such as PIC18C4X2) for compatibility
with 40-pin midrange devices.
Register 12-1: PSPCON Register
R-0 R-0 R/W-0 R/W-0 U-0 U-0 U-0 U-0
IBF OBF IBOV PSPMODE — — — —
bit 7 bit 0
bit 7 IBF: Input Buffer Full Status bit
1 = A word has been received and waiting to be read by the CPU
0 = No word has been received
bit 6 OBF: Output Buffer Full Status bit
1 = The output buffer still holds a previously written word
0 = The output buffer has been read
bit 5 IBOV: Input Buffer Overflow Detect bit (in microprocessor mode)
1 = A write occurred when a previously input word has not been read
(must be cleared in software)
0 = No overflow occurred
bit 4 PSPMODE: Parallel Slave Port Mode Select bit
1 = Parallel slave port mode
0 = General purpose I/O mode
bits 3:0 Unimplemented: Read as '0'
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39512-page 12-4 2000 Microchip Technology Inc.
Register 12-2: TRISE Register
R-0 R-0 R/W-0 R/W-0 U-0 R/W-1 R/W-1 R/W-1
IBF OBF IBOV PSPMODE — TRISE2 TRISE1 TRISE0
bit 7 bit 0
bit 7 IBF: Input Buffer Full Status bit
1 = A word has been received and waiting to be read by the CPU
0 = No word has been received
bit 6 OBF: Output Buffer Full Status bit
1 = The output buffer still holds a previously written word
0 = The output buffer has been read
bit 5 IBOV: Input Buffer Overflow Detect bit (in microprocessor mode)
1 = A write occurred when a previously input word has not been read
(must be cleared in software)
0 = No overflow occurred
bit 4 PSPMODE: Parallel Slave Port Mode Select bit
1 = Parallel slave port mode
0 = General purpose I/O mode
bit 3 Unimplemented: Read as '0'
bit 2 TRISE2: RE2 Direction Control bit
1 = Input
0 = Output
bit 1 TRISE1: RE1 Direction Control bit
1 = Input
0 = Output
bit 0 TRISE0: RE0 Direction Control bit
1 = Input
0 = Output
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39512-page 12-5
Section 12. Parallel Slave Port
Parallel
Slave Port
12
12.3 Operation
A write to the PSP from the external system occurs when both the CS and WR lines are first
detected low. When either the CS or WR lines become high (edge triggered), the Input Buffer Full
status flag bit IBF is set on the Q4 clock cycle following the next Q2 cycle. This signals that the
write is complete. The interrupt flag bit, PSPIF, is also set on the same Q4 clock cycle. The IBF
flag bit is inhibited from being cleared for additional TCY cycles (see parameter 66 in the "Electrical
Specifications" section). If the IBF flag bit is cleared by reading the PORTD input latch,
then this has to be a read-only instruction (i.e., MOVF) and not a read-modify-write instruction.
The Input Buffer Overflow status flag bit IBOV is set if a second write to the Parallel Slave Port is
attempted when the previous byte has not been read out of the buffer.
A read of the PSP from the external system occurs when both the CS and RD lines are first
detected low. The Output Buffer Full status flag bit OBF is cleared immediately indicating that the
PORTD latch was read by the external bus. When either the CS or RD pin becomes high (edge
triggered), the interrupt flag bit, PSPIF, is set on the Q4 clock cycle following the next Q2 cycle,
indicating that the read is complete. OBF remains low until data is written to PORTD by the user
firmware.
Input Buffer Full Status Flag bit, IBF, is set if a received word is waiting to be read by the CPU.
Once the PORT input latch is read, the IBF bit is cleared. The IBF bit is a read only status bit.
Output Buffer Full Status Flag bit, OBF, is set if a word written to the PORT latch is waiting to be
read by the external bus. Once the PORTD output latch is read by the microprocessor, OBF is
cleared. Input Buffer Overflow Status Flag bit, IBOV, is set if a second write to the microprocessor
port is attempted when the previous word has not been read by the CPU (the first word is retained
in the buffer).
When not in Parallel Slave Port mode, the IBF and OBF bits are held clear. However, if the IBOV
bit was previously set, it must be cleared in the software.
An interrupt is generated and latched into flag bit PSPIF when a read or a write operation is completed.
Interrupt flag bit PSPIF must be cleared by user software and the interrupt can be disabled
by clearing interrupt enable bit PSPIE.
Table 12-1: PORTE Functions
Name Function
RD Read Control Input in parallel slave port mode:
RD
1 = Not a read operation
0 = Read operation. Reads PORTD register (if chip selected)
WR Write Control Input in parallel slave port mode:
WR
1 = Not a write operation
0 = Write operation. Writes PORTD register (if chip selected)
CS Chip Select Control Input in parallel slave port mode:
CS
1 = Device is not selected
0 = Device is selected
Note: The PSP may have other functions multiplexed onto the same pins. For the PSP to
operate, the pins must be configured as digital I/O.
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39512-page 12-6 2000 Microchip Technology Inc.
12.4 Operation in SLEEP Mode
When in SLEEP mode, the microprocessor may still read and write the Parallel Slave Port. These
actions will set the PSPIF bit. If the PSP interrupts are enabled, this will wake the processor from
SLEEP mode so that the PSP data latch may be either read, or written with the next value for the
microprocessor.
12.5 Effect of a RESET
After any RESET, the PSP is disabled and PORTD and PORTE are forced to their default mode.
12.6 PSP Waveforms
Register 12-2 shows the waveform for a write from the microprocessor to the PSP, while
Register 12-3 shows the waveform for a read of the PSP by the microprocessor.
Figure 12-2: Parallel Slave Port Write Waveforms
Figure 12-3: Parallel Slave Port Read Waveforms
Q1 Q2 Q3 Q4
CS
Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4
WR
RD
IBF
OBF
PSPIF
PORTD<7:0>
Q1 Q2 Q3 Q4
CS
Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4
WR
IBF
PSPIF
RD
OBF
PORTD<7:0>
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39512-page 12-7
Section 12. Parallel Slave Port
Parallel
Slave Port
12
Table 12-2: Registers Associated with Parallel Slave Port
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Value on
POR, BOR
Value on all
other resets
PORTD Port data latch when written; port pins when read xxxx xxxx uuuu uuuu
LATD LATD Data Output Bits xxxx xxxx uuuu uuuu
TRISD PORTD Data Direction Bits 1111 1111 1111 1111
PORTE (1) — — — — — RE2 RE1 RE0 ---- -000 ---- -000
LATE — — — — — LATE Data Output Bits ---- -xxx ---- -uuu
TRISE (1) IBF OBF IBOV PSPMODE — PORTE Data Direction Bits 0000 -111 0000 -111
PSPCON IBF OBF IBOV PSPMODE — — — — 0000 ---- 0000 ----
INTCON GIE/
GIEH
PEIE/
GIEL
TMR0IF INT0IE RBIE TMR0IF INT0IF RBIF 0000 000x 0000 000u
PIR1 PSPIF ADIF RCIF TXIF SSPIF CCP1IF TMR2IF TMR1IF 0000 0000 0000 0000
PIE1 PSPIE ADIE RCIE TXIE SSPIE CCP1IE TMR2IE TMR1IE 0000 0000 0000 0000
IPR1 PSPIP ADIP RCIP TXIP SSPIP CCP1IP TMR2IP TMR1IP 0000 0000 0000 0000
ADCON1 ADFM ADCS2 — — PCFG3 PCFG2 PCFG1 PCFG0 --0- -000 --0- -000
Legend: x = unknown, u = unchanged, - = unimplemented read as '0'.
Shaded cells are not used by the Parallel Slave Port.
Note 1: On some devices the entire PORTE will be implemented with I/O functions. In these devices, the TRISE register will contain
the eight data direction bits and the PSP bits will be located in the PSPCON register.
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39512-page 12-8 2000 Microchip Technology Inc.
12.7 Design Tips
Question 1: Migrating from the PIC16C74 to the PIC18CXX2, the operation of the PSP
seems to have changed.
Answer 1:
Yes, a design change was made so the PIC18CXX2 is edge sensitive (while the PIC16C74 was
level sensitive).
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39512-page 12-9
Section 12. Parallel Slave Port
Parallel
Slave Port
12
12.8 Related Application Notes
This section lists application notes that are related to this section of the manual. These application
notes may not be written specifically for the Enhanced MCU family (that is, they may be written
for the Base-Line, the Mid-Range or High-End families), but the concepts are pertinent, and
could be used (with modification and possible limitations). The current application notes related
to the Parallel Slave Port are:
Title Application Note #
Using the 8-bit Parallel Slave Port AN579
Note: Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
http://www.microchip.com/10/faqs/codeex/
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39512-page 12-10 2000 Microchip Technology Inc.
12.9 Revision History
Revision A
This is the initial released revision of the Parallel Slave Port description.
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39513A-page 13-1
Timer0
13
Section 13. Timer0
HIGHLIGHTS
This section of the manual contains the following major topics:
13.1 Introduction .................................................................................................................. 13-2
13.2 Control Register ........................................................................................................... 13-3
13.3 Operation ..................................................................................................................... 13-4
13.4 Timer0 Interrupt ........................................................................................................... 13-5
13.5 Using Timer0 with an External Clock ........................................................................... 13-6
13.6 Timer0 Prescaler.......................................................................................................... 13-7
13.7 Initialization .................................................................................................................. 13-9
13.8 Design Tips ................................................................................................................ 13-10
13.9 Related Application Notes.......................................................................................... 13-11
13.10 Revision History ......................................................................................................... 13-12
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39513A-page 13-2 2000 Microchip Technology Inc.
13.1 Introduction
The Timer0 module has the following features:
• Software selectable as an 8-bit or 16-bit timer/counter
• Readable and writable
• Dedicated 8-bit software programmable prescaler
• Clock source selectable to be external or internal
• Interrupt on overflow from FFh to 00h (FFFFh to 0000h in 16-bit mode)
• Edge select for external clock
Figure 13-1 shows a simplified block diagram of the Timer0 module in 8-bit mode and
Figure 13-2 shows a simplified block diagram of the Timer0 module in 16-bit mode.
Figure 13-1: Timer0 Block Diagram in 8-bit Mode
Figure 13-2: Timer0 Block Diagram in 16-bit Mode
T0CKI pin
T0SE
0
1
0
1
T0CS
FOSC/4
Programmable
Prescaler
Sync with
Internal
clocks
TMR0
PSOUT
(2 TCY delay)
POUT
Data Bus
8
PSA
T0PS2:T0PS0 Set interrupt
flag bit T0IF
on overflow
3
Note 1: T0CS, T0SE, PSA, T0PS2:T0PS0 (T0CON<5:0>).
2: Upon reset, Timer0 is enabled in 8-bit mode, with clock input from T0CKI, max. prescale.
Note 1: T0CS, T0SE, PSA, T0PS2:T0PS0 (T0CON<5:0>).
2: Upon reset, Timer0 is enabled in 8-bit mode, with clock input from T0CKI, max. prescale.
T0CKI pin
T0SE
0
1
0
1
T0CS
FOSC/4
Programmable Prescaler
Sync with
Internal
clocks
TMR0L PSOUT
(2 TCY delay)
POUT
Data Bus<7:0>
8
PSA
T0PS2:T0PS0
3
TMR0
TMR0H
High Byte
8 8
8
Read TMR0L
Write TMR0L
Set interrupt
flag bit T0IF
on overflow
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39513A-page 13-3
Section 13. Timer0
Timer0
14
13.2 Control Register
The T0CON register is a readable and writable register that controls all the aspects of Timer0,
including the prescale selection.
Register 13-1: T0CON: TImer0 Control Register
R/W-1 R/W-1 R/W-1 R/W-1 R/W-1 R/W-1 R/W-1 R/W-1
TMR0ON T08BIT T0CS T0SE PSA T0PS2 T0PS1 T0PS0
bit 7 bit 0
bit 7 TMR0ON: Timer0 On/Off Control bit
1 = Enables Timer0
0 = Stops Timer0
bit 6 T08BIT: Timer0 8-bit/16-bit Control bit
1 = Timer0 is configured as an 8-bit timer/counter
0 = Timer0 is configured as a 16-bit timer/counter
bit 5 T0CS: Timer0 Clock Source Select bit
1 = Transition on T0CKI pin is clock (counter mode)
0 = Internal instruction cycle is clock (timer mode)
bit 4 T0SE: Timer0 Source Edge Select bit
1 = Increment on high-to-low transition on T0CKI pin
0 = Increment on low-to-high transition on T0CKI pin
bit 3 PSA: Timer0 Prescaler Assignment bit
1 = Timer0 prescaler is NOT assigned. Timer0 clock input bypasses prescaler.
0 = Timer0 prescaler is assigned. Timer0 clock input comes from prescaler output.
bit 2-0 T0PS2:T0PS0: Timer0 Prescaler Select bits
These bits are ignored if PSA = 1
111 = 1:256 prescale value
110 = 1:128 prescale value
101 = 1:64 prescale value
100 = 1:32 prescale value
011 = 1:16 prescale value
010 = 1:8 prescale value
001 = 1:4 prescale value
000 = 1:2 prescale value
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39513A-page 13-4 2000 Microchip Technology Inc.
13.3 Operation
When initializing Timer0, several options need to be specified. This is done by programming the
appropriate bits in the T0CON register.
13.3.1 8-Bit/16-Bit Modes
Timer0 can be configured as an 8-bit or a 16-bit counter. The default state for Timer0 is an 8-bit
counter. To configure the timer as a 16-bit counter, the T08BIT bit (T0CON register) must be
cleared.
If the timer is configured as an 8-bit timer, the MSB of TMR0 (TMR0H) is held clear and will read
00h.
Normally once the mode of the timer is selected, it is not changed. Some applications may
require the ability to switch back and forth between 8-bit and 16-bit modes. The two cases are:
1. Changing from 8-bit to 16-bit mode
2. Changing from 16-bit to 8-bit mode
The condition when bit 7 of the Timer0 rolls over must be addressed.
If Timer0 is configured as an 8-bit timer and is changed to a 16-bit timer on the same cycle as a
rollover occurs, no interrupt is generated.
If Timer0 is configured as a 16-bit timer and is changed to an 8-bit timer on the same cycle as a
rollover occurs, the TMR0IF bit will be set.
13.3.1.1 16-Bit Mode Timer Reads
TMR0H is not the high byte of the timer/counter, but actually a buffered version of the high byte
of Timer0. The high byte of the Timer0 counter/timer is not directly readable or writable. TMR0H
is updated with the contents of the high byte of Timer0 during a read of TMR0L. This provides a
user with the ability to read all 16 bits of Timer0 without having to verify that the read of the high
and low byte were valid due to a rollover between successive reads of the high and low byte. The
user simply reads the low byte of Timer0, followed by a read of TMR0H, which contains the value
in the high byte of Timer0 at the time that the low byte was read.
13.3.1.2 16-Bit Mode Timer Write
A write to the high byte of Timer0 must also take place through the TMR0H buffer register.
Timer0 high byte is updated with the contents of TMR0H when a write occurs to TMR0L. This
allows a user to update all 16 bits to both the high and low bytes of Timer0 at once (see
Figure 13-2).
When performing a write of TMR0, the carry is held off during the write of the TMR0L register.
Writes to the TMR0H register only modify the holding latch, not the timer (TMR0<15:8>).
Steps to write to the TMR0:
1. Load the TMR0H register.
2. Write to the TMR0L register.
13.3.1.3 16-Bit Read/Modify Write
Read-modify-write instructions like BSF or BCF, read the contents of a register, make the appropriate
changes, and place the result back into the register. The read cycle of a read-modify-write
instruction of TMR0L will not update the contents of the TMR0H buffer. The TMR0H buffer will
remain unchanged. When the write cycle (to TMR0L) of the instruction takes place, the contents
of TMR0H are placed into the high byte of Timer0.
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39513A-page 13-5
Section 13. Timer0
Timer0
14
13.3.2 Timer/Counter Modes
Timer mode is selected by clearing the T0CS bit (T0CON register). In timer mode, the Timer0
module will increment every instruction cycle (without prescaler). If the TMR0 register is written,
the increment is inhibited for the following two instruction cycles. The user can work around this
by writing an adjusted value to the TMR0 register.
Counter mode is selected by setting the T0CS bit (T0CON register). In counter mode, Timer0 will
increment either on every rising or falling edge of the T0CKI pin. The incrementing edge is determined
by the Timer0 Source Edge Select bit T0SE (T0CON register). Clearing the T0SE bit
selects the rising edge. Restrictions on the external clock input are discussed in detail in Section
13.5.1.
13.4 Timer0 Interrupt
The TMR0 interrupt flag bit is set when the TMR0 register overflows. When TMR0 is in 8-bit
mode, this means the overflow from FFh to 00h. When TMR0 is in 16-bit mode, this means the
overflow from FFFFh to 0000h.
This overflow sets the TMR0IF bit (INTCON register). The interrupt can be disabled by clearing
the TMR0IE bit (INTCON register). The TMR0IF bit must be cleared in software by the interrupt
service routine. The TMR0 interrupt cannot awaken the processor from SLEEP, since the timer
is shut off during SLEEP. See Figure 13-3 for Timer0 interrupt timing.
Figure 13-3: TMR0 Interrupt Timing
Q1 Q3 Q4 Q2 Q1 Q3 Q4 Q2 Q1 Q3 Q4 Q2 Q1 Q3 Q4 Q2 Q1 Q3 Q4 Q2
1 1
OSC1
CLKO(3)
8-bit Timer0
TMR0IF bit
(INTCON<2>)
FEh
GIE bit
(INTCON<7>)
INSTRUCTION
PC
Instruction
fetched
PC PC + 2 PC + 4 PC + 4 0008h
Instruction
executed
Inst (PC)
Inst (PC-2)
Inst (PC+2)
Inst (PC)
Inst (0008h)
Dummy cycle Dummy cycle
FFh 00h 01h 02h
FLOW
16-bit Timer0 FFFEh FFFFh 0000h 0001h 0002h
1
Inst (PC+4)
Inst (PC+2)
Note 1: Interrupt flag bit TMR0IF is sampled here (every Q1).
2: Interrupt latency = 4TCY where TCY = instruction cycle time.
3: CLKO is available only in RC oscillator mode.
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39513A-page 13-6 2000 Microchip Technology Inc.
13.5 Using Timer0 with an External Clock
When an external clock input is used for Timer0, it must meet certain requirements as detailed
in 13.5.1 “External Clock Synchronization”. The requirements ensure the external clock can
be synchronized with the internal phase clock (TSCLK). Also, there is a delay in the actual incrementing
of Timer0 after synchronization.
13.5.1 External Clock Synchronization
When no prescaler is used, the external clock input is used instead of the prescaler output. The
synchronization of T0CKI with the internal phase clocks is accomplished by sampling the prescaler
output on the Q2 and Q4 cycles of the internal phase clocks (Figure 13-4). Therefore, it is
necessary for T0CKI to be high for at least 2TSCLK (and a small RC delay) and low for at least
2TSCLK (and a small RC delay). Refer to parameters 40, 41 and 42 in the electrical specification
of the desired device.
When a prescaler is used, the external clock input is divided by the prescaler so that the prescaler
output is symmetrical. For the external clock to meet the sampling requirement, the ripple-counter
must be taken into account. Therefore, it is necessary for T0CKI to have a period of
at least 4TSCLK (and a small RC delay) divided by the prescaler value. The only requirement on
T0CKI high and low time is that they do not violate the minimum pulse width requirement. Refer
to parameters 40, 41 and 42 in the electrical specification of the desired device.
13.5.2 TMR0 Increment Delay
Since the prescaler output is synchronized with the internal clocks, there is a small delay from
the time the external clock edge occurs to the time the Timer0 module is actually incremented.
Figure 13-4 shows the delay from the external clock edge to the timer incrementing.
Figure 13-4: Timer0 Timing with External Clock
Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4
External Clock Input or
Prescaler output(2)
External Clock/Prescaler
Output after sampling
Increment Timer0 (Q4)
Timer0 T0 T0 + 1 T0 + 2
Small pulse
misses sampling
(3)
(1)
Note 1: Delay from clock input change to Timer0 increment is 3Tosc to 7Tosc. (Duration of Q = Tosc).
Therefore, the error in measuring the interval between two edges on Timer0 input = ±4Tosc max.
2: External clock if no prescaler selected, prescaler output otherwise.
3: The arrows indicate the points in time where sampling occurs.
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39513A-page 13-7
Section 13. Timer0
Timer0
14
13.6 Timer0 Prescaler
An 8-bit counter is available as a prescaler for the Timer0 module (Figure 13-5).
The PSA and T0PS2:T0PS0 bits (T0CON register) are the prescaler enable and prescale select
bits.
All instructions that write to the Timer0 (TMR0) register (such as: CLRF TMR0; BSF TMR0,x;
MOVWF TMR0; ....etc.) will clear the prescaler if enabled. The prescaler is not readable or writable.
Writes to TMR0H do not clear the Timer0 prescaler in 16-bit mode, because a write to TMR0H
only modifies the Timer0 latch and does not change the contents of Timer0. The prescaler is only
cleared on writes to TMR0L.
Figure 13-5: Block Diagram of the Timer0 Prescaler
The prescaler for Timer0 is enabled or disabled in software by the PSA bit (T0CON register). Setting
the PSA bit will enable the prescaler. The prescaler can be modified under software control
through the T0PS2:T0PS0 bits. This allows the prescaler reload value to be readable and writable.
The prescaler count value (the contents of the prescaler) can not be read or written. When
the prescaler is enabled, prescale values of 1:2, 1:4, ..., 1:256 are selectable.
T0CKI pin
T0SE
M
U
X
CLKO (=FOSC/4)
TMR0L
8-bit Prescaler
T0PS2:T0PS0 8 - to - 1 MUX
8
M
U
X
0
1 1
0
Data Bus
Set flag bit
8
PSA T0CS
TMR0
TMR0IF
on overflow
Data Bus
8
T08BIT
T08BIT
Set flag bit
TMR0IF
on overflow
for TMR0L
TMR0H
high reg
8
Synchronization 2 TCY
delay
Note: T0CS, T0SE, PSA, T0PS2:T0PS0 are located in the T0CON register.
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39513A-page 13-8 2000 Microchip Technology Inc.
Any write to the TMR0 register will cause a 2 instruction cycle (2TCY) inhibit. That is, after the
TMR0 register has been written with the new value, TMR0 will not be incremented until the third
instruction cycle later (Figure 13-6). When the prescaler is assigned to the Timer0 module, any
write to the TMR0 register will immediately update the TMR0 register and clear the prescaler.
The incrementing of Timer0 (TMR0 and Prescaler) will also be inhibited 2 instruction cycles
(TCY). So if the prescaler is configured as 2, then after a write to the TMR0 register, TMR0 will
not increment for 4 Timer0 clocks (Figure 13-7). After that, TMR0 will increment every prescaler
number of clocks later.
Figure 13-6: Timer0 Timing: Internal Clock/No Prescale
Figure 13-7: Timer0 Timing: Internal Clock/Prescale 1:2
Table 13-1: Registers Associated with Timer0
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Value on
POR, BOR
Value on all
other resets
TMR0L Timer0 Module’s Low Byte Register xxxx xxxx uuuu uuuu
TMR0H Timer0 Module’s High Byte Register 0000 0000 0000 0000
INTCON GIE/GIEH PEIE/GIEL TMR0IE INT0IE RBIE TMR0IF INT0IF RBIF 0000 000x 0000 000u
T0CON TMR0ON T08BIT T0CS T0SE PSA T0PS2 T0PS1 T0PS0 1111 1111 1111 1111
TRISA — — PORTA Data Direction Register --11 1111 --11 1111
Legend: x = unknown, u = unchanged, - = unimplemented locations read as '0'.
Shaded cells are not used by Timer0.
PC-2
PC Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4
(Program
Counter)
Instruction
Fetch
TMR0
PC PC+2 PC+4 PC+6 PC+8 PC+10 PC+12
T0 T0+1 T0+2 NT0 NT0 NT0 NT0+1 NT0+2 T0
MOVWF TMR0 MOVF TMR0,W MOVF TMR0,W MOVF TMR0,W MOVF TMR0,W MOVF TMR0,W
Write TMR0
executed
Read TMR0
reads NT0
Read TMR0
reads NT0
Read TMR0
reads NT0
Read TMR0
reads NT0 + 1
Read TMR0
reads NT0 + 2
Instruction
Executed
PC+6
PC-2
PC Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4
(Program
Counter)
Instruction
Fetch
TMR0
PC PC+2 PC+4 PC+6 PC+8 PC+10 PC+12
T0 NT0+1
MOVWF TMR0 MOVF TMR0,W MOVF TMR0,W MOVF TMR0,W MOVF TMR0,W MOVF TMR0,W
Write TMR0
executed
Read TMR0
reads NT0
Read TMR0
reads NT0
Read TMR0
reads NT0
Read TMR0
reads NT0
Read TMR0
reads NT0 + 1
T0+1 NT0
Instruction
Execute
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39513A-page 13-9
Section 13. Timer0
Timer0
14
13.7 Initialization
Since Timer0 has a software programmable clock source, there are two examples to show the
initialization of Timer0 with each source. Example 13-1 shows the initialization for the internal
clock source (timer mode), while Example 13-2 shows the initialization for the external clock
source (counter mode).
Example 13-1: Timer0 Initialization (Internal Clock Source)
Example 13-2: Timer0 Initialization (External Clock Source)
CLRF TMR0 ; Clear Timer0 register
CLRF INTCON ; Disable interrupts and clear T0IF
BCF INTCON2, RBPU ;
MOVLW 0x80 ; PortB pull-ups are disabled,
MOVWF T0CON ; Interrupt on rising edge of RB0,
; TMR0 = 16-Bit Time
; Timer0 increment from internal clock
; with a prescaler of 1:2.
;** BSF INTCON, T0IE ; Enable TMR0 interrupt
;** BSF INTCON, GIE ; Enable all interrupts
;
; The TMR0 interrupt is disabled, do polling on the overflow bit
;
T0_OVFL_WAIT
BTFSS INTCON, T0IF
GOTO T0_OVFL_WAIT
; Timer has overflowed
CLRF TMR0 ; Clear Timer0 register
CLRF INTCON ; Disable interrupts and clear T0IF
BCF INTCON2, RBPU ;
MOVLW 0xBF ; PortB pull-ups are enabled,
MOVWF T0CON ; Interrupt on falling edge of RB0
; Timer0 increment from external clock
; on the high-to-low transition
; of T0CKI
; with a prescaler of 1:256.
;** BSF INTCON, T0IE ; Enable TMR0 interrupt
;** BSF INTCON, GIE ; Enable all interrupts
;
; The TMR0 interrupt is disabled, do polling on the overflow bit
;
T0_OVFL_WAIT
BTFSS INTCON, T0IF
GOTO T0_OVFL_WAIT
; Timer has overflowed
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39513A-page 13-10 2000 Microchip Technology Inc.
13.8 Design Tips
Question 1: I am implementing a counter/clock, but the clock loses time or is inaccurate.
Answer 1:
If you are polling TMR0 to see if it has rolled over to zero, you could do this by executing:
wait MOVF TMR0,W ; read the timer into W
BTFSS STATUS,Z ; see if it was zero, if so,
; break from loop
GOTO wait ; if not zero yet, keep waiting
Two possible scenarios to lose clock cycles are:
1. If you are incrementing TMR0 from the internal instruction clock (or an external source that
is about as fast), the overflow could occur during the two cycle GOTO, so you could miss
it. In this case, the TMR0 source should be prescaled.
2. When writing to TMR0, two instruction clock cycles are lost. Often you have a specific time
period you want to count, say 100 decimal. In that case, you might put 156 into TMR0
(256 - 100 = 156). However, since two instruction cycles are lost when you write to TMR0
(for internal logic synchronization), you should actually write 158 to the timer.
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39513A-page 13-11
Section 13. Timer0
Timer0
14
13.9 Related Application Notes
This section lists application notes that are related to this section of the manual. These application
notes may not be written specifically for the Enhanced family (that is, they may be written for
the Base-Line, the Mid-Range or High-End families), but the concepts are pertinent, and could
be used (with modification and possible limitations). The current application notes related to
Timer0 are:
Title Application Note #
Frequency Counter Using PIC16C5X AN592
A Clock Design using the PIC16C54 for LED Display and Switch Inputs AN590
Note: Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
http://www.microchip.com/10/faqs/codeex/
39500 18C Reference Manual.book Page 11 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39513A-page 13-12 2000 Microchip Technology Inc.
13.10 Revision History
Revision A
This is the initial released revision of the Enhanced MCU Timer0 Module description.
39500 18C Reference Manual.book Page 12 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39514A-page 14-1
Timer1
14
Section 14. Timer1
HIGHLIGHTS
This section of the manual contains the following major topics:
14.1 Introduction .................................................................................................................. 14-2
14.2 Control Register ........................................................................................................... 14-4
14.3 Timer1 Operation in Timer Mode ................................................................................. 14-5
14.4 Timer1 Operation in Synchronized Counter Mode....................................................... 14-5
14.5 Timer1 Operation in Asynchronous Counter Mode...................................................... 14-6
14.6 Reading and Writing of Timer1 .................................................................................... 14-7
14.7 Timer1 Oscillator........................................................................................................ 14-10
14.8 Typical Application ..................................................................................................... 14-11
14.9 Sleep Operation ......................................................................................................... 14-12
14.10 Resetting Timer1 Using a CCP Trigger Output.......................................................... 14-12
14.11 Resetting Timer1 Register Pair (TMR1H:TMR1L) ..................................................... 14-13
14.12 Timer1 Prescaler........................................................................................................ 14-13
14.13 Initialization ................................................................................................................ 14-14
14.14 Design Tips ................................................................................................................ 14-16
14.15 Related Application Notes.......................................................................................... 14-17
14.16 Revision History ......................................................................................................... 14-18
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39514A-page 14-2 2000 Microchip Technology Inc.
14.1 Introduction
The Timer1 module is a 16-bit timer/counter consisting of two 8-bit registers (TMR1H and
TMR1L) that are readable and writable. The TMR1 register pair (TMR1H:TMR1L) increments
from 0000h to FFFFh and rolls over to 0000h. If enabled, the Timer1 Interrupt is generated on
overflow that is latched in the TMR1IF interrupt flag bit. This interrupt can be enabled/disabled
by setting/clearing the TMR1IE interrupt enable bit.
Timer1 can operate in one of three modes:
• As a synchronous timer
• As a synchronous counter
• As an asynchronous counter
The operating mode is determined by clock select bit, TMR1CS (T1CON register), and the synchronization
bit, T1SYNC (Figure 14-1).
In timer mode, Timer1 increments every instruction cycle. In counter mode, it increments on
every rising edge of the external clock input pin T1OSI.
Timer1 can be turned on and off using theTMR1ON control bit (T1CON register).
Timer1 also has an internal “reset input”, which can be generated by a CCP module.
Timer1 has the capability to operate off an external crystal. When the Timer1 oscillator is enabled
(T1OSCEN is set), the T1OSI and T1OSO pins become inputs, so their corresponding TRIS values
are ignored.
Figure 14-1: Timer1 Block Diagram
TMR1H TMR1L
T1SYNC
TMR1CS
T1CKPS1:T1CKPS0 SLEEP input
TMR1ON
on/off
Prescaler
1, 2, 4, 8
Synchronize
det
1
0
0
1
Synchronized
Clock Input
2
Set TMR1IF flag bit
on Overflow
TMR1
CLR
CCP Special Event Trigger
T1OSCEN
Enable
Oscillator T1OSI (1)
T1OSO/T1CKI
T1OSC
Note 1: When enable bit T1OSCEN is cleared, the inverter and feedback resistor are turned off. This
eliminates power drain.
Fosc/4
Internal
Clock
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39514A-page 14-3
Section 14. Timer1
Timer1
14
Figure 14-2: Timer1 Block Diagram 16-Bit Read/Write Mode
Timer 1 TMR1L
T1SYNC
TMR1CS
T1CKPS1:T1CKPS0
SLEEP input
T1OSCEN
Enable
Oscillator (1)
TMR1IF
Overflow
Interrupt
Fosc/4
Internal
Clock
TMR1ON
on/off
Prescaler
1, 2, 4, 8
Synchronize
det
1
0
0
1
Synchronized
Clock Input
2
T13CKI/
T1OSI
TMR1
flag bit
Note 1: When enable bit T1OSCEN is cleared, the inverter and feedback resistor are turned off. This
eliminates power drain.
Data Bus<7:0>
8
TMR1H
8 8
8
Read TMR1L
Write TMR1L
T1OSO
High Byte
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39514A-page 14-4 2000 Microchip Technology Inc.
14.2 Control Register
Register 14-1 shows the Timer1 Control register. This register controls the operating mode of the
Timer1 module and contains the Timer1 oscillator enable bit (T1OSCEN).
Register 14-1: T1CON: Timer1 Control Register
R/W-0 U-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
RD16 — T1CKPS1 T1CKPS0 T1OSCEN T1SYNC TMR1CS TMR1ON
bit 7 bit 0
bit 7 RD16: 16-bit Read/Write Mode Enable bit
1 = Enables register Read/Write of Timer1 in one 16-bit operation
0 = Enables register Read/Write of Timer1 in two 8-bit operations
bit 6 Unimplemented: Read as '0'
bit 5:4 T1CKPS1:T1CKPS0: Timer1 Input Clock Prescale Select bits
11 = 1:8 Prescale value
10 = 1:4 Prescale value
01 = 1:2 Prescale value
00 = 1:1 Prescale value
bit 3 T1OSCEN: Timer1 Oscillator Enable bit
1 = Timer1 Oscillator is enabled
0 = Timer1 Oscillator is shut off. The oscillator inverter and feedback resistor are turned off to
eliminate power drain.
bit 2 T1SYNC: Timer1 External Clock Input Synchronization Select bit
When TMR1CS = 1:
1 = Do not synchronize external clock input
0 = Synchronize external clock input
When TMR1CS = 0:
This bit is ignored. Timer1 uses the internal clock when TMR1CS = 0.
bit 1 TMR1CS: Timer1 Clock Source Select bit
1 = External clock from pin T1OSO/T13CKI (on the rising edge)
0 = Internal clock (FOSC/4)
bit 0 TMR1ON: Timer1 On bit
1 = Enables Timer1
0 = Stops Timer1
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39514A-page 14-5
Section 14. Timer1
Timer1
14
14.3 Timer1 Operation in Timer Mode
Timer mode is selected by clearing the TMR1CS (T1CON register) bit. In this mode, the input
clock to the timer is FOSC/4. The synchronize control bit, T1SYNC (T1CON register), has no
effect since the internal clock is always synchronized.
14.4 Timer1 Operation in Synchronized Counter Mode
Counter mode is selected by setting the TMR1CS bit. In this mode, the timer increments on every
rising edge of clock input on the T1OSI pin when the Timer1 oscillator enable bit (T1OSCEN) is
set, or the T1OSO/T13CKI pin when the T1OSCEN bit is cleared.
If the T1SYNC bit is cleared, then the external clock input is synchronized with internal phase
clocks. The synchronization is done after the prescaler stage. The prescaler operates asynchronously.
The timer increments at the Q4:Q1 edge.
In this configuration, during SLEEP mode, Timer1 will not increment even if the external clock is
present, since the synchronization circuit is shut off. The prescaler however will continue to increment.
14.4.1 External Clock Input Timing for Synchronized Counter Mode
When an external clock input is used for Timer1 in synchronized counter mode, it must meet certain
requirements. The external clock requirement is due to internal phase clock (TSCLK) synchronization.
Also, there is a delay in the actual incrementing of TMR1 after synchronization.
When the prescaler is 1:1, the external clock input is the same as the prescaler output. The synchronization
of T1CKI with the internal phase clocks is accomplished by sampling the prescaler
output on alternating TscLK clocks of the internal phase clocks. Therefore, it is necessary for the
T1CKI pin to be high for at least 2TscLK (and a small RC delay) and low for at least 2TscLK (and
a small RC delay). Refer to parameters 45, 46, and 47 in the “Electrical Specifications” section.
When a prescaler other than 1:1 is used, the external clock input is divided by the asynchronous
prescaler so that the prescaler output is symmetrical. In order for the external clock to meet the
sampling requirement, the prescaler counter must be taken into account. Therefore, it is necessary
for the T1CKI pin to have a period of at least 4TscLK (and a small RC delay) divided by the
prescaler value. Another requirement on the T1CKI pin high and low time is that they do not violate
the minimum pulse width requirements). Refer to parameters 40, 42, 45, 46, and 47 in the
“Electrical Specifications” section.
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39514A-page 14-6 2000 Microchip Technology Inc.
14.5 Timer1 Operation in Asynchronous Counter Mode
If T1SYNC (T1CON register) is set, the external clock input is not synchronized. The timer continues
to increment asynchronously to the internal phase clocks. The timer will continue to run
during SLEEP and can generate an interrupt on overflow that will wake-up the processor. However,
special precautions in software are needed to read/write the timer (Subsection
14.6.4 “Reading and Writing Timer1 in Asynchronous Counter Mode with RD16 = 0” ).
Since the counter can operate in sleep, Timer1 can be used to implement a true real-time clock.
The timer increments at the Q4:Q1 and Q2:Q3 edges.
In asynchronous counter mode, Timer1 cannot be used as a time-base for capture or compare
operations.
14.5.1 External Clock Input Timing with Unsynchronized Clock
If the T1SYNC control bit is set, the timer will increment completely asynchronously. The input
clock must meet certain minimum high time and low time requirements. Refer to the Device Data
Sheet “Electrical Specifications” section, timing parameters 45, 46, and 47.
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39514A-page 14-7
Section 14. Timer1
Timer1
14
14.6 Reading and Writing of Timer1
Timer1 has modes that allow the 16-bit timer register to be read/written as two 8-bit registers or
one 16-bit register. The mode depends on the state of the RD16 bit. The following subsections
discuss this operation.
14.6.1 Timer1 and 16-bit Read/Write Modes
Timer1 can be configured for 16-bit reads and writes. When the RD16 control bit (T1CON register)
is set, the address for TMR1H is mapped to a buffer register for the high byte of Timer1. A
read from TMR1L will load the contents of the high byte of Timer1 into the Timer1 high byte buffer.
This provides the user with the ability to accurately read all 16 bits of Timer1 without having to
determine whether a read of the high byte followed by a read of the low byte is valid due to a
rollover between reads.
14.6.2 16-bit Mode Timer Write
A write to the high byte of Timer1 must also take place through the TMR1H buffer register. Timer1
high byte is updated with the contents of TMR1H when a write occurs to TMR1L. This allows a
user to write all 16 bits to both the high and low bytes of Timer1 at once (See Figure 14-3).
The high byte of Timer1 is not directly readable or writable in this mode. All reads and writes must
take place through the Timer1 high byte buffer register.
Writes to TMR1H do not clear the Timer1 prescaler. The prescaler is only cleared on writes to
TMR1L.
14.6.3 16-bit Read-Modify-Write
Read-modify-write instructions like BSF or BCF will read the contents of a register, make the
appropriate changes, and place the result back into the register. In the case of Timer1 when
configured in 16-bit mode, the read portion of a read-modify-write instruction of TMR1L will not
update the contents of the TMR1H buffer. The TMR1H buffer will remain unchanged. When the
write of TMR1L portion of the instruction takes place, the contents of TMR1H will be placed into
the high byte of Timer1.
Figure 14-3: Timer1 Block Diagram When Configured in 16-bit Read/Write Mode
Timer 1 TMR1L
T1SYNC
TMR1CS
T1CKPS1:T1CKPS0
SLEEP input
TMR1IF
Overflow
Interrupt
FOSC/4
Internal
Clock
TMR1ON
on/off
Prescaler
1, 2, 4, 8
Synchronize
det
1
0
0
1
Synchronized
Clock Input
2
TMR1
flag bit high byte
Data Bus<7:0>
8
TMR1H
8 8
8
Read TMR1L
Write TMR1L
T1OSC
T1OSCEN
Enable
Oscillator (1)
T13CKI/
T1OSO TTIP
Note 1: When enable bit T1OSCEN is cleared, the inverter and feedback resistor are turned off. This
eliminates power drain.
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39514A-page 14-8 2000 Microchip Technology Inc.
14.6.4 Reading and Writing Timer1 in Asynchronous Counter Mode with RD16 = 0
Reading TMR1H or TMR1L while the timer is running from an external asynchronous clock will
ensure a valid read (taken care of in hardware). However, the user should keep in mind that reading
the 16-bit timer in two 8-bit values itself poses certain problems, since the timer may overflow
between the reads.
For writes, it is recommended that the user simply stop the timer and write the desired values. A
write contention may occur by writing to the timer registers while the register is incrementing. This
may produce an unpredictable value in the timer register.
Reading the 16-bit value requires some care, since two separate reads are required to read the
entire 16-bits. Example 14-1 shows why this may not be a straight forward read of the 16-bit register.
Example 14-1: Reading 16-bit Register Issues
TMR1
Sequence 1 Sequence 2
Action TMPH:TMPL Action TMPH:TMPL
04FFh READ TMR1L xxxxh READ TMR1H xxxxh
0500h Store in TMPL xxFFh Store in TMPH 04xxh
0501h READ TMR1H xxFFh READ TMR1L 04xxh
0502h Store in TMPH 05FFh Store in TMPL 0401h
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39514A-page 14-9
Section 14. Timer1
Timer1
14
Example 14-2 shows a routine to read the 16-bit timer value without experiencing the issues
shown in Example 14-1. This is useful if the timer cannot be stopped.
Example 14-2: Reading a 16-bit Free-Running Timer
Writing a 16-bit value to the 16-bit TMR1 register is straightforward. First the TMR1L register is
cleared to ensure that there are many Timer1 clock/oscillator cycles before there is a rollover into
the TMR1H register. The TMR1H register is then loaded, and finally the TMR1L register is
loaded. Example 14-3 shows a routine that does a 16-bit write to a Free Running Timer.
Example 14-3: Writing a 16-bit Free Running Timer
; All interrupts are disabled
MOVF TMR1H, W ; Read high byte
MOVWF TMPH ;
MOVF TMR1L, W ; Read low byte
MOVWF TMPL ;
MOVF TMR1H, W ; Read high byte
SUBWF TMPH, W ; Sub 1st read with 2nd read
BTFSC STATUS,Z ; Is result = 0
GOTO CONTINUE ; Good 16-bit read
;
; TMR1L may have rolled over between the read of the high and low bytes.
; Reading the high and low bytes now will read a good value.
;
MOVF TMR1H, W ; Read high byte
MOVWF TMPH ;
MOVF TMR1L, W ; Read low byte
MOVWF TMPL ;
; Re-enable the Interrupt (if required)
CONTINUE ; Continue with your code
; All interrupts are disabled
CLRF TMR1L ; Clear Low byte, Ensures no
; rollover into TMR1H
MOVLW HI_BYTE ; Value to load into TMR1H
MOVWF TMR1H, F ; Write High byte
MOVLW LO_BYTE ; Value to load into TMR1L
MOVWF TMR1H, F ; Write Low byte
; Re-enable the Interrupt (if required)
CONTINUE ; Continue with your code
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39514A-page 14-10 2000 Microchip Technology Inc.
14.7 Timer1 Oscillator
An alternate crystal oscillator circuit is built into the device. The output of this oscillator can be
selected as the input into Timer1. The Timer1 oscillator is primarily intended to operate as a timebase
for the timer modules; therefore, the oscillator is primarily intended for a 32 kHz crystal,
which is an ideal frequency for real-time keeping. In real-time applications, the timer needs to
increment during SLEEP, so SLEEP does not disable the Timer1 oscillator. For many applications,
power consumption is also an issue, so the oscillator is designed to minimize power consumption.
The Timer1 oscillator is enabled by setting the T1OSCEN control bit (T1CON register). After the
Timer1 oscillator is enabled, the user must provide a software time delay to ensure proper oscillator
start-up.
Table 14-1 shows the capacitor selection for the Timer1 oscillator.
Table 14-1: Capacitor Selection for the Timer1 Oscillator
Note: The Timer1 oscillator allows the counter to operate (increment) when the device is
in sleep mode. This allows Timer1 to be used as a real-time clock.
Osc Type Freq C1 C2
LP 32 kHz 33 pF 33 pF
100 kHz 15 pF 15 pF
200 kHz 15 pF 15 pF
Crystals Tested:
32.768 kHz Epson C-001R32.768K-A ± 20 PPM
100 kHz Epson C-2 100.00 KC-P ± 20 PPM
200 kHz STD XTL 200.000 kHz ± 20 PPM
Note 1: Higher capacitance increases the stability of oscillator but also increases the start-up
time.
2: Since each resonator/crystal has its own characteristics, the user should consult the
resonator/crystal manufacturer for appropriate values of external components.
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39514A-page 14-11
Section 14. Timer1
Timer1
14
14.8 Typical Application
In Figure 14-4 an example application is given, where Timer1 is driven from an external 32 kHz
oscillator. The external 32 kHz oscillator is typically used in applications where real-time needs
to be kept, but it is also desirable to have the lowest possible power consumption. The Timer1
oscillator allows the device to be placed in sleep while the timer continues to increment. When
Timer1 overflows, the interrupt wakes up the device so that the appropriate registers can be
updated.
Figure 14-4: Timer1 Application
In this example, a 32 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 Timer1 must be loaded with a value to allow
the Timer1 to overflow at the desired rate. In the case of a 1 second Timer1 overflow, the TMR1H
register should be loaded with a value of 80k after each overflow.
8
4
4
4
4x4
Keypad
Current Sink
TMR1
VSS
VDD
32 kHz
Backup
Battery
Power-Down
Detect
T1OSI
T1OSO
OSC1
TT1P
Note: The TMR1L register should never be modified, since an external clock is asychronous
to the system clock. Writes to the TRM1L register may corrupt the real time
counter value causing inaccuracies.
39500 18C Reference Manual.book Page 11 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39514A-page 14-12 2000 Microchip Technology Inc.
14.9 Sleep Operation
When Timer1 is configured for asynchronous operation, the TMR1 registers will continue to
increment for each timer clock (or prescale multiple of clocks). When the TMR1 register overflows,
the TMR1IF bit will get set. If enabled, this will generate an interrupt that will wake the processor
from sleep mode.
The Timer1 oscillator will add a delta current, due to the operation of this circuitry. That is, the
power-down current will no longer only be the leakage current of the device, but also the active
current of the Timer1 oscillator and other circuitry.
14.10 Resetting Timer1 Using a CCP Trigger Output
If a CCP module is configured in compare mode to generate a “Special Event Trigger”
(CCP1M3:CCP1M0 = 1011), this signal resets Timer1.
Timer1 must be configured for either timer or synchronized counter mode to take advantage of
the special event trigger feature. If Timer1 is running in asynchronous counter mode, this reset
operation may not work and should not be used.
In the event that a write to Timer1 coincides with a special event trigger from the CCP module,
the write will take precedence.
In this mode of operation, the CCPRxH:CCPRxL register pair effectively becomes the period register
for Timer1.
14.10.1 CCP Trigger and A/D Module
Some devices that have the CCP Trigger capability also have an A/D module. These devices
may be able to be configured, so the “Special Event Trigger” not only resets the Timer1 registers,
0but will start an A/D conversion. This allows a constant sampling rate for the A/D, as specified
by the value of the compare registers.
Note: The special event trigger from the CCP module does not set interrupt flag bit
TMR1IF.
39500 18C Reference Manual.book Page 12 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39514A-page 14-13
Section 14. Timer1
Timer1
14
14.11 Resetting Timer1 Register Pair (TMR1H:TMR1L)
TMR1H and TMR1L registers are not cleared on any reset, only by the CCP special event triggers.
T1CON register is reset to 00h on a Power-on Reset or a Brown-out Reset. In any other reset,
the register is unaffected.
Timer1 is the default time base for the CCP1 and CCP2 modules. The timer can be disabled as
the time base for either CCP1, CCP2, or both, and Timer3 can be substituted. This is achieved
by setting control bits in the Timer3 control register.
This is explained in Section 16.8 - Timer3 and CCPx Enable.
When Timer1 is disabled as a the time base for a CCP, the reset on Compare will have no effect
on Timer1.
14.12 Timer1 Prescaler
The prescaler counter is cleared on writes to the TMR1H or TMR1L registers.
14.12.1 Timer1 Prescaler 16-bit Read/WriteMode
Writes to TMR1H do not clear the Timer1 prescaler in 16-bit read/write mode, because a write
to TMR1H only modifies the Timer1 latch and does not change the contents of Timer1. The
prescaler is only cleared on writes to TMR1L.
Table 14-2: Registers Associated with Timer1 as a Timer/Counter
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Value on:
POR,
BOR
Value on
all other
resets
INTCON GIE PEIE T0IE INTE RBIE T0IF INTF RBIF 0000 000x 0000 000u
PIR TMR1IE (1) 0 0
PIE TMR1IE (1) 0 0
IPR TMR1IP (1) 0 0
TMR1L Holding register for the Least Significant Byte of the 16-bit TMR1 register xxxx xxxx uuuu uuuu
TMR1H Holding register for the Most Significant Byte of the 16-bit TMR1 register xxxx xxxx uuuu uuuu
T1CON RD16 — T1CKPS1 T1CKPS0 T1OSCEN T1SYNC TMR1CS TMR1ON --00 0000 --uu uuuu
Legend: x = unknown,u = unchanged,- = unimplemented read as '0'.
Shaded cells are not used by the Timer1 module.
Note 1: The placement of this bit is device dependent.
39500 18C Reference Manual.book Page 13 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39514A-page 14-14 2000 Microchip Technology Inc.
14.13 Initialization
Since Timer1 has a software programmable clock source, there are three examples to show the
initialization of each mode. Example 14-4 shows the initialization for the internal clock source,
Example 14-5 shows the initialization for the external clock source, and Example 14-6 shows the
initialization of the external oscillator mode.
Example 14-4: Timer1 Initialization (Internal Clock Source)
Example 14-5: Timer1 Initialization (External Clock Source)
CLRF T1CON ; Stop Timer1, Internal Clock Source,
; T1 oscillator disabled,
; prescaler = 1:1
CLRF TMR1H ; Clear Timer1 High byte register
CLRF TMR1L ; Clear Timer1 Low byte register
CLRF INTCON ; Disable interrupts
CLRF PIE1 ; Disable peripheral interrupts
CLRF PIR1 ; Clear peripheral interrupts Flags
MOVLW 0x30 ; Internal Clock source
; with 1:8 prescaler
MOVWF T1CON ; Timer1 is stopped and
; T1 osc is disabled
BSF T1CON, TMR1ON ; Timer1 starts to increment
;
; The Timer1 interrupt is disabled, do polling on the overflow bit
;
T1_OVFL_WAIT
BTFSS PIR1, TMR1IF
GOTO T1_OVFL_WAIT
;
; Timer has overflowed
;
BCF PIR1, TMR1IF
CLRF T1CON ; Stop Timer1, Internal Clock Source,
; T1 oscillator disabled,
; prescaler = 1:1
CLRF TMR1H ; Clear Timer1 High byte register
CLRF TMR1L ; Clear Timer1 Low byte register
CLRF INTCON ; Disable interrupts
CLRF PIE1 ; Disable peripheral interrupts
CLRF PIR1 ; Clear peripheral interrupts Flags
MOVLW 0x32 ; External Clock source
; with 1:8 prescaler
MOVWF T1CON ; Clock source is
; synchronized to device
; Timer1 is stopped
; and T1 osc is disabled
BSF T1CON, TMR1ON ; Timer1 starts to increment
;
; The Timer1 interrupt is disabled, do polling on the overflow bit
;
T1_OVFL_WAIT
BTFSS PIR1, TMR1IF
GOTO T1_OVFL_WAIT
;
; Timer has overflowed
;
BCF PIR1, TMR1IF
39500 18C Reference Manual.book Page 14 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39514A-page 14-15
Section 14. Timer1
Timer1
14
Example 14-6: Timer1 Initialization (External Oscillator Clock Source)
CLRF T1CON ; Stop Timer1, Internal Clock Source,
; T1 oscillator disabled,
; prescaler = 1:1
CLRF TMR1H ; Clear Timer1 High byte register
CLRF TMR1L ; Clear Timer1 Low byte register
CLRF INTCON ; Disable interrupts
CLRF PIE1 ; Disable peripheral interrupts
CLRF PIR1 ; Clear peripheral interrupts Flags
MOVLW 0x3E ; External Clock source
; with oscillator
MOVWF T1CON ; circuitry, 1:8 prescaler,
; Clock source is
; asynchronous to device
; Timer1 is stopped
BSF T1CON, TMR1ON ; Timer1 starts to increment
;
; The Timer1 interrupt is disabled, do polling on the overflow bit
;
T1_OVFL_WAIT
BTFSS PIR1, TMR1IF
GOTO T1_OVFL_WAIT
;
; Timer has overflowed
;
BCF PIR1, TMR1IF
39500 18C Reference Manual.book Page 15 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39514A-page 14-16 2000 Microchip Technology Inc.
14.14 Design Tips
Question 1: Timer1 does not seem to be keeping accurate time.
Answer 1:
There are a few reasons that this could occur:
1. You should never write to Timer1 where that could cause the loss of time. In most cases,
that means you should not write to the TMR1L register, but if the conditions are OK, you
may write to the TMR1H register. Normally, you write to the TMR1H register if you want
the Timer1 overflow interrupt to be sooner than the full 16-bit time-out.
2. You should ensure that your layout uses good PCB layout techniques so noise does not
couple onto the Timer1/Timer3 oscillator lines.
39500 18C Reference Manual.book Page 16 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39514A-page 14-17
Section 14. Timer1
Timer1
14
14.15 Related Application Notes
This section lists application notes that are related to this section of the manual. These application
notes may not be written specifically for the Enhanced family (that is they may be written for
the Baseline, the Midrange, or High-end families), but the concepts are pertinent, and could be
used (with modification and possible limitations). The current application notes related to Timer1
are:
Title Application Note #
Using Timer1 in Asynchronous Clock Mode AN580
Low Power Real Time Clock AN582
Yet another Clock using the PIC16C92X AN649
Note: Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
http://www.microchip.com/10/faqs/codeex/
39500 18C Reference Manual.book Page 17 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39514A-page 14-18 2000 Microchip Technology Inc.
14.16 Revision History
Revision A
This is the initial released revision of the Timer1 module description.
39500 18C Reference Manual.book Page 18 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39515A-page 15-1
Timer2
15
Section 15. Timer2
HIGHLIGHTS
This section of the manual contains the following major topics:
15.1 Introduction .................................................................................................................. 15-2
15.2 Control Register ........................................................................................................... 15-3
15.3 Timer Clock Source ..................................................................................................... 15-4
15.4 Timer (TMR2) and Period (PR2) Registers.................................................................. 15-4
15.5 TMR2 Match Output..................................................................................................... 15-4
15.6 Clearing the Timer2 Prescaler and Postscaler............................................................. 15-4
15.7 Sleep Operation ........................................................................................................... 15-4
15.8 Initialization .................................................................................................................. 15-5
15.9 Design Tips .................................................................................................................. 15-6
15.10 Related Application Notes............................................................................................ 15-7
15.11 Revision History ........................................................................................................... 15-8
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39515A-page 15-2 2000 Microchip Technology Inc.
15.1 Introduction
Timer2 is an 8-bit timer with a prescaler, a postscaler and a period register. Using the prescaler
and postscaler at their maximum settings, the overflow time is the same as a 16-bit timer.
Timer2 is the PWM time-base when the CCP module(s) is used in the PWM mode.
Figure 15-1 shows a block diagram of Timer2. The postscaler counts the number of times that
the TMR2 register matched the PR2 register. This can be useful in reducing the overhead of the
interrupt service routine on the CPU performance.
Figure 15-1: Timer2 Block Diagram
Comparator
TMR2 Sets flag
TMR2 reg
output (1)
Reset
Postscaler
Prescaler
PR2 reg
2
FOSC/4
1:1 1:16
1:1, 1:4, 1:16
EQ
4
bit TMR2IF
Note 1: TMR2 register output can be software selected by the SSP Module as a baud clock.
to
TOUTPS3:TOUTPS0
T2CKPS1:T2CKPS0
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39515A-page 15-3
Section 15. Timer2
Timer2
15
15.2 Control Register
Register 15-1 shows the Timer2 control register. The prescaler and postscaler selection of
Timer2 are controlled by this register.
Register 15-1: T2CON: Timer2 Control Register
U-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
— TOUTPS3 TOUTPS2 TOUTPS1 TOUTPS0 TMR2ON T2CKPS1 T2CKPS0
bit 7 bit 0
bit 7 Unimplemented: Read as '0'
bit 6-3 TOUTPS3:TOUTPS0: Timer2 Output Postscale Select bits
0000 = 1:1 Postscale
0001 = 1:2 Postscale
•
•
•
1111 = 1:16 Postscale
bit 2 TMR2ON: Timer2 On bit
1 = Timer2 is on
0 = Timer2 is off
bit 1-0 T2CKPS1:T2CKPS0: Timer2 Clock Prescale Select bits
00 = Prescaler is 1
01 = Prescaler is 4
1x = Prescaler is 16
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39515A-page 15-4 2000 Microchip Technology Inc.
15.3 Timer Clock Source
The Timer2 module has one source of input clock, the device clock (FOSC/4). A prescale option
of 1:1, 1:4 or 1:16 is software selected by control bits T2CKPS1:T2CKPS0 (T2CON register).
15.4 Timer (TMR2) and Period (PR2) Registers
The TMR2 register is readable and writable, and is cleared on all device resets. Timer2 increments
from 00h until it matches PR2 and then resets to 00h on the next increment cycle. PR2 is
a readable and writable register.
The TMR2 register is cleared and the PR2 register is set when a WDT, POR, MCLR or a BOR
reset occurs.
Timer2 can be shut off (disabled from incrementing) by clearing the TMR2ON control bit (T2CON
register). This minimizes the power consumption of the module.
15.5 TMR2 Match Output
The match output of TMR2 goes to two sources:
1. Timer2 Postscaler
2. SSP Clock Input
There are 4-bits which select the postscaler. This allows the postscaler a 1:1 to 1:16 scaling
(inclusive). After the postscaler overflows, the TMR2 interrupt flag bit (TMR2IF) is set to indicate
the Timer2 overflow. This is useful in reducing the software overhead of the Timer2 interrupt service
routine, since it will only execute once every postscaler # of matches.
The match output of TMR2 is also routed to the Synchronous Serial Port module, which may
select this via software, as the clock source for the shift clock.
15.6 Clearing the Timer2 Prescaler and Postscaler
The prescaler and postscaler counters are cleared when any of the following occurs:
• a write to the TMR2 register
• a write to the T2CON register
• any device reset (Power-on Reset, MCLR reset, Watchdog Timer Reset, Brown-out Reset)
15.7 Sleep Operation
During sleep, TMR2 will not increment. The prescaler will retain the last prescale count, ready
for operation to resume after the device wakes from sleep.
Table 15-1: Registers Associated with Timer2
Note: If the PR2 register = 00h, the TMR2 register will not increment (Timer2 cleared).
Note: When T2CON is written, TMR2 does not clear.
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Value on:
POR,
BOR
Value on
all other
resets
INTCON GIE PEIE TMR0IE INTE RBIE TMR0IF INTF RBIF 0000 000x 0000 000u
PIR TMR2IF (1) 0 0
PIE TMR2IE (1) 0 0
IPR TMR21P (1) 0 0
TMR2 Timer2 module’s register 0000 0000 0000 0000
T2CON — TOUTPS3 TOUTPS2 TOUTPS1 TOUTPS0 TMR2ON T2CKPS1 T2CKPS0 -000 0000 -000 0000
PR2 Timer2 Period Register 1111 1111 1111 1111
Legend: x = unknown,u = unchanged,- = unimplemented read as '0'.
Shaded cells are not used by the Timer2 module.
Note 1: The position of this bit is device dependent.
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39515A-page 15-5
Section 15. Timer2
Timer2
15
15.8 Initialization
Example 15-1 shows how to initialize the Timer2 module, including specifying the Timer2 prescaler
and postscaler.
Example 15-1:Timer2 Initialization
CLRF T2CON ; Stop Timer2, Prescaler = 1:1,
; Postscaler = 1:1
CLRF TMR2 ; Clear Timer2 register
CLRF INTCON ; Disable interrupts
LRF PIE1 ; Disable peripheral interrupts
CLRF PIR1 ; Clear peripheral interrupts Flags
MOVLW 0x72 ; Postscaler = 1:15, Prescaler = 1:16
MOVWF T2CON ; Timer2 is off
MOVLW PR2VALUE ; This is the value
MOVWF PR2 ; to load into the PR2 register.
BSF T2CON, TMR2ON ; Timer2 starts to increment
;
; The Timer2 interrupt is disabled, do polling on the overflow bit
;
T2_OVFL_WAIT
BTFSS PIR1, TMR2IF ; Has TMR2 interrupt occurred?
GOTO T2_OVFL_WAIT ; NO, continue loop
;
; Timer has overflowed
;
BCF PIR1, TMR2IF ; YES, clear flag and continue.
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39515A-page 15-6 2000 Microchip Technology Inc.
15.9 Design Tips
Question 1: Timer2 never seems to increment?
Answer 1:
Ensure that the Timer2 Period register (PR2) is not 0h. This is because when a period match
occurs, the TMR2 register is cleared on the next cycle so Timer2 will never increment.
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39515A-page 15-7
Section 15. Timer2
Timer2
15
15.10 Related Application Notes
This section lists application notes that are related to this section of the manual. These application
notes may not be written specifically for the Enhanced family (that is, they may be written for
the Base-Line, the Mid-Range or High-End families), but the concepts are pertinent, and could
be used (with modification and possible limitations). The current application notes related to the
Timer2 Module are:
Title Application Note #
Using the CCP Module AN594
Air Flow Control using Fuzzy Logic AN600
Adaptive Differential Pulse Code Modulation using the PIC16/17 AN643
Note: Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
http://www.microchip.com/10/faqs/codeex/
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39515A-page 15-8 2000 Microchip Technology Inc.
15.11 Revision History
Revision A
This is the initial released revision of the TImer2 module description.
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39516A-page 16-1
Timer3
16
Section 16. Timer3
HIGHLIGHTS
This section of the manual contains the following major topics:
16.1 Introduction .................................................................................................................. 16-2
16.2 Control Registers ......................................................................................................... 16-3
16.3 Timer3 Operation in Timer Mode ................................................................................. 16-4
16.4 Timer3 Operation in Synchronized Counter Mode....................................................... 16-4
16.5 Timer3 Operation in Asynchronous Counter Mode...................................................... 16-5
16.6 Reading and Writing of Timer3 .................................................................................... 16-6
16.7 Timer3 using the Timer1 Oscillator .............................................................................. 16-9
16.8 Timer3 and CCPx Enable .......................................................................................... 16-10
16.9 Timer3 Prescaler........................................................................................................ 16-10
16.10 16-bit Mode Timer Reads/Writes ............................................................................... 16-11
16.11 Typical Application ..................................................................................................... 16-12
16.12 Sleep Operation ......................................................................................................... 16-13
16.13 Timer3 Prescaler........................................................................................................ 16-13
16.14 Initialization ................................................................................................................ 16-14
16.15 Design Tips ................................................................................................................ 16-16
16.16 Related Application Notes.......................................................................................... 16-17
16.17 Revision History ......................................................................................................... 16-18
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39516A-page 16-2 2000 Microchip Technology Inc.
16.1 Introduction
The Timer3 module is a 16-bit timer/counter consisting of two 8-bit registers (TMR3H and
TMR3L) that are readable and writable. The TMR3 register pair (TMR3H:TMR3L) increments
from 0000h to FFFFh and rolls over to 0000h. The Timer3 Interrupt, if enabled, is generated on
overflow, which is latched in the TMR3IF interrupt flag bit. This interrupt can be enabled/disabled
by setting/clearing the TMR3IE interrupt enable bit.
Timer3 can operate in one of three modes:
• As a synchronous timer
• As a synchronous counter
• As an asynchronous counter
Some features of Timer3 include:
• TMR3 also has an internal “reset input”, which can be generated by a CCP module.
• TMR3 has the capability to operate off an external crystal/clock.
• TMR3 is the alternate time base for capture/compare
In timer mode, Timer3 increments every instruction cycle. In counter mode, it increments on
every rising edge of the external clock input.
The Timer3 increment can be enabled/disabled by setting/clearing control bit TMR3ON (T3CON
register).
Timer3 also has an internal “reset input”. This reset can be generated by a CCP special event
trigger (Capture/Compare/PWM) module. See the CCP (Capture/Compare/PWM) section for
details.
When the Timer1 oscillator is enabled (T1OSCEN, in T1CON, is set), the T1OSCI1 and T1OSO2
pins are configured as oscillator input and output, so the corresponding values in the TRIS register
are ignored.
The Timer3 module also has a software programmable prescaler.
The operating mode is determined by clock select bit, TMR3CS (T3CON register), and the synchronization
bit, T3SYNC (Figure 16-1).
Figure 16-1: Timer3 Block Diagram
TMR3H TMR3L
T3SYNC
TMR3CS
T3CKPS1:T3CKPS0 SLEEP input
FOSC/4
Internal
Clock
TMR3ON
on/off
Prescaler
1, 2, 4, 8
Synchronize
det
1
0
0
1
Synchronized
Clock Input
2
Set TMR3IF flag bit
on Overflow
TMR3
CLR
TT1P
CCP Special Trigger
T3CCPx
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39516A-page 16-3
Section 16. Timer3
Timer3
16
16.2 Control Registers
Register 16-1 shows the Timer3 control register. This register controls the operating mode of the
Timer3 module and contains the function of the CCP Special Event Trigger.
Register 16-1: T3CON: Timer3 Control Register
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
RD16 T3CCP2 T3CKPS1 T3CKPS0 T3CCP1 T3SYNC TMR3CS TMR3ON
bit 7 bit 0
bit 7 RD16: 16-bit Read/Write Mode Enable
1 = Enables register Read/Write of Timer3 in one 16-bit operation
0 = Enables register Read/Write of Timer3 in two 8-bit operations
bit 6,3 T3CCP2:T3CCP1: Timer3 and Timer1 to CCPx Enable bits
1x = Timer3 is the clock source for compare/capture of the CCP modules
01 = Timer3 is the clock source for compare/capture of CCP2,
Timer1 is the clock source for compare/capture of CCP1
00 = Timer1 is the clock source for compare/capture of the CCP modules
bit 5:4 T3CKPS1:T3CKPS0: Timer3 Input Clock Prescale Select bits
11 = 1:8 Prescale value
10 = 1:4 Prescale value
01 = 1:2 Prescale value
00 = 1:1 Prescale value
bit 2 T3SYNC: Timer3 External Clock Input Synchronization Control bit
(Not usable if the system clock comes from Timer1/Timer3)
When TMR3CS = 1:
1 = Do not synchronize external clock input
0 = Synchronize external clock input
When TMR3CS = 0:
This bit is ignored. Timer3 uses the internal clock when TMR3CS = 0.
bit 1 TMR3CS: Timer3 Clock Source Select bit
1 = External clock input from T1OSI or T1CKI (on the rising edge after the first falling edge)
0 = Internal clock (FOSC/4)
bit 0 TMR3ON: Timer3 On bit
1 = Enables Timer3
0 = Stops Timer3
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39516A-page 16-4 2000 Microchip Technology Inc.
16.3 Timer3 Operation in Timer Mode
Timer mode is selected by clearing the TMR3CS (T3CON register) bit. In this mode, the input
clock to the timer is FOSC/4. The synchronize control bit, T3SYNC (T3CON register), has no
effect since the internal clock is always synchronized.
16.4 Timer3 Operation in Synchronized Counter Mode
Counter mode is selected by setting bit TMR3CS. In this mode, the timer increments on every
rising edge of input on the T1OSI pin (when enable bit T1OSCEN is set) or the T13CKI pin (when
bit T1OSCEN is cleared).
If the T3SYNC bit is cleared, then the external clock input is synchronized with internal phase
clocks. The synchronization is done after the prescaler stage. The prescaler operates asynchronously.
The timer increments at the Q4:Q1 edge.
In this configuration, during SLEEP mode, Timer3 will not increment even if an external clock is
present, since the synchronization circuit is shut off. The prescaler, however, will continue to
increment.
16.4.1 External Clock Input Timing for Synchronized Counter Mode
When an external clock input is used for Timer3 in synchronized counter mode, it must meet certain
requirements. The external clock requirement is due to internal phase clock (TSCLK) synchronization.
Also, there is a delay in the actual incrementing of TMR3 after synchronization.
When the prescaler is 1:1, the external clock input is the same as the prescaler output. There is
synchronization of T1OSI/T13CKI with the internal phase clocks. Therefore, it is necessary for
(T1OSI/T13CKI to be high for at least 2TSCLK (and a small RC delay) and low for at least 2TSCLK
(and a small RC relay). Refer to parameters 45, 46, and 47 in the “Electrical Specifications”
section.
When a prescaler other than 1:1 is used, the external clock input is divided by the asynchronous
prescaler, so that the prescaler output is symmetrical. In order for the external clock to meet the
sampling requirement, the prescaler counter must be taken into account. Therefore, it is necessary
for T1OSI/T1CKI to have a period of at least 4TSCLK (and a small RC delay) divided by the
prescaler value. The only requirement on T1OSI/T1CKI high and low time is that they do not violate
the minimum pulse width requirements. Refer to parameters 40, 42, 45, 46, and 47 in the
“Electrical Specifications” section.
Note: Timer3 gets its external clock input from the same source as Timer1. The configuration
of the Timer1 and Timer3 clock input will be controlled by the T1OSCEN bit
in the Timer1 control register.
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39516A-page 16-5
Section 16. Timer3
Timer3
16
16.5 Timer3 Operation in Asynchronous Counter Mode
If T3SYNC (T3CON register) is set, the external clock input is not synchronized. The timer continues
to increment asynchronously to the internal phase clocks. The timer will continue to run
during SLEEP and can generate an interrupt on overflow that will wake-up the processor. However,
special precautions in software are needed to read/write the timer (Subsection
16.6.4 “Reading and Writing Timer3 in Asynchronous Counter Mode with RD16 = 0” ).
Since the counter can operate in sleep, Timer1 can be used to implement a true real-time clock.
The timer increments at the Q4:Q1 and Q2:Q3 edges.
In asynchronous counter mode, Timer3 cannot be used as a time-base for capture or compare
operations.
16.5.1 External Clock Input Timing with Unsynchronized Clock
If the T3SYNC control bit is set, the timer will increment completely asynchronously. The input
clock must meet certain minimum high time and low time requirements. Refer to the Device Data
Sheet “Electrical Specifications” section, timing parameters 45, 46, and 47.
Note: The control bit T3SYNC is not usable when the system clock source comes from the
same source as the Timer1/Timer3 clock input, because the T1CKI input will be
sampled at one quarter the frequency of the incoming clock.
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39516A-page 16-6 2000 Microchip Technology Inc.
16.6 Reading and Writing of Timer3
Timer3 has modes that allow the 16-bit timer register to be read/written as two 8-bit registers or
one 16-bit register. The mode depends on the state of the RD16 bit. The follow subsections discuss
this operation.
16.6.1 Timer3 and 16-bit Read/Write Modes
Timer3 can be configured for 16-bit reads. When the RD16 control bit (T3CON register) is set,
the address for TMR3H is mapped to a buffer register for the high byte of Timer3. A read from
TMR3L will load the contents of the high byte of Timer3 into the Timer3 high byte buffer. This provides
the user with the ability to accurately read all 16-bits of Timer3 without having to determine
whether a read of the high byte followed by a read of the low byte is valid due to a rollover
between reads.
16.6.2 16-bit Mode Timer Write
A write to the high byte of Timer3 must also take place through the TMR3H buffer register. Timer3
high byte is updated with the contents of TMR3H when a write occurs to TMR3L. This allows a
user to write all 16 bits to both the high and low bytes of Timer3 at once (See Figure 16-2).
The high byte of Timer3 is not directly readable or writable in this mode. All reads and writes must
take place through the Timer3 high byte buffer register.
Writes to TMR3H do not clear the Timer3 prescaler. The prescaler is only cleared on writes to
TMR3L.
16.6.3 16-bit Read-Modify-Write
Read-modify-write instructions like BSF or BCF will read the contents of a register, make the
appropriate changes, and place the result back into the register. In the case of Timer3 when
configured in 16-bit mode, the read portion of a read-modify-write instruction of TMR3L will not
update the contents of the TMR3H buffer. The TMR3H buffer will remain unchanged. When the
write of TMR3L portion of the instruction takes place, the contents of TMR3H will be placed into
the high byte of Timer3.
Figure 16-2: Timer3 Block Diagram When Configured in 16-bit Read/Write Mode
Timer 3 TMR3L
T1SYNC
TMR3CS
T3CKPS1:T3CKPS0
SLEEP input
TMR3IF
Overflow
Interrupt
FOSC/4
Internal
Clock
TMR3ON
on/off
Prescaler
1, 2, 4, 8
Synchronize
det
1
0
0
1
Synchronized
Clock Input
2
TMR1
flag bit high byte
Data Bus<7:0>
8
TMR3H
8 8
8
Read TMR3L
Write TMR3L
TT1P
CCP Special Trigger
T3CCPx
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39516A-page 16-7
Section 16. Timer3
Timer3
16
16.6.4 Reading and Writing Timer3 in Asynchronous Counter Mode with RD16 = 0
Reading TMR3H or TMR3L while the timer is running from an external asynchronous clock will
ensure a valid read (taken care of in hardware). However, the user should keep in mind that reading
the 16-bit timer in two 8-bit values poses certain problems, since the timer may overflow
between the reads.
For writes, it is recommended that the user simply stop the timer and write the desired values. A
write contention may occur by writing to the timer registers, while the register is incrementing.
This may produce an unpredictable value in the timer register.
Reading the 16-bit value requires some care, since two separate reads are required to read the
entire 16-bits. Example 16-1 shows why this may not be a straightforward read of the 16-bit register.
Example 16-1:Reading 16-bit Register Issues
TMR3
Sequence 1 Sequence 2
Action TMPH:TMPL Action TMPH:TMPL
04FFh READ TMR3L xxxxh READ TMR3H xxxxh
0500h Store in TMPL xxFFh Store in TMPH 04xxh
0501h READ TMR3H xxFFh READ TMR3L 04xxh
0502h Store in TMPH 05FFh Store in TMPL 0401h
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39516A-page 16-8 2000 Microchip Technology Inc.
Example 16-2 shows a routine to read the 16-bit timer value without experiencing the issues
shown in Example 16-1. This is useful if the timer cannot be stopped.
Example 16-2:Reading a 16-bit Free-Running Timer
Writing a 16-bit value to the 16-bit TMR3 register is straight forward. First the TMR3L register is
cleared to ensure that there are many Timer3 clock/oscillator cycles before there is a rollover into
the TMR3H register. The TMR3H register is then loaded, and finally, the TMR3L register is
loaded. Example 16-3 shows a routine that accomplishes this:
Example 16-3:Writing a 16-bit Free Running Timer
; All interrupts are disabled
MOVF TMR3H, W ; Read high byte
MOVWF TMPH ;
MOVF TMR3L, W ; Read low byte
MOVWF TMPL ;
MOVF TMR3H, W ; Read high byte
SUBWF TMPH, W ; Sub 1st read with 2nd read
BTFSC STATUS,Z ; Is result = 0
GOTO CONTINUE ; Good 16-bit read
;
; TMR3L may have rolled over between the read of the high and low bytes.
; Reading the high and low bytes now will read a good value.
;
MOVF TMR3H, W ; Read high byte
MOVWF TMPH ;
MOVF TMR3L, W ; Read low byte
MOVWF TMPL ;
; Re-enable the Interrupt (if required)
CONTINUE ; Continue with your code
; All interrupts are disabled
CLRF TMR3L ; Clear Low byte, Ensures no
; rollover into TMR3H
MOVLW HI_BYTE ; Value to load into TMR3H
MOVWF TMR3H, F ; Write High byte
MOVLW LO_BYTE ; Value to load into TMR3L
MOVWF TMR3H, F ; Write Low byte
; Re-enable the Interrupt (if required)
CONTINUE ; Continue with your code
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39516A-page 16-9
Section 16. Timer3
Timer3
16
16.7 Timer3 using the Timer1 Oscillator
An alternate crystal oscillator circuit is built into the device. The output of this oscillator can be
selected as the input into Timer3. The Timer1 oscillator is primarily intended to operate as a timebase
for the timer modules; therefore, the oscillator is primarily intended for a 32 kHz crystal,
which is an ideal frequency for real-time keeping. In real-time applications, the timer needs to
increment during SLEEP, so SLEEP does not disable the Timer1 oscillator. For many applications,
power consumption is also an issue, so the oscillator is designed to minimize consumption.
The Timer1 oscillator is enabled by setting the T1OSCEN control bit (T1CON register). After the
Timer1 oscillator is enabled, the user must provide a software time delay to ensure proper oscillator
start-up.
Table 16-1 shows the capacitor selection for the Timer1 oscillator.
Table 16-1: Capacitor Selection for the Timer1 oscillator
Note: The Timer1 oscillator allows the counter to operate (increment) when the device is
in sleep mode. This allows Timer1 to be used as a real-time clock.
Osc Type Freq C1 C2
LP 32 kHz 33 pF 33 pF
100 kHz 15 pF 15 pF
200 kHz 15 pF 15 pF
Crystals Tested:
32.768 kHz Epson C-001R32.768K-A ± 20 PPM
100 kHz Epson C-2 100.00 KC-P ± 20 PPM
200 kHz STD XTL 200.000 kHz ± 20 PPM
Note 1: Higher capacitance increases the stability of oscillator, but also increases the start-up
time.
2: Since each resonator/crystal has its own characteristics, the user should consult the
resonator/crystal manufacturer for appropriate values of external components.
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39516A-page 16-10 2000 Microchip Technology Inc.
16.8 Timer3 and CCPx Enable
Timer3 can be configured as the time base for capture and compare for either CCP2 or both
CCP1 and CCP2. Timer3 cannot be used as the time base for CCP1 only. Timer1 can be used
as the time base for CCP1 or both CCP1 and CCP2, but not CCP2 only. Control for the assignment
of each of the time bases is given by configuring the corresponding T3CCP2 and T3CCP1
bits in the Timer3 control register, and is described in Table 16-2.
Table 16-2: T3CCPx, TMR1, and TMR3
After reset, Timer1 defaults as the time base for compare and capture for both CCP’s.
16.8.1 Resetting Timer3 Using a CCP Trigger Output
If the T3CCP2 or T3CCP1 bit is set and CCP1 or CCP2 is configured in Compare mode to generate
a “Special Event Trigger” (CCPxM3:CCPxM0 = 1011), this signal will reset Timer3.
Timer3 must be configured for either timer or synchronized counter mode to take advantage of
this feature. If Timer3 is running in asynchronous counter mode, this reset operation may not
work.
In the event that a write to Timer3 coincides with a special event trigger from a CCP module, the
write will take precedence.
In this mode of operation, the CCPRxH:CCPRxL register pair effectively becomes the period register
for the Timer3 module.
16.8.2 Resetting of TMR3 Register Pair (TMR3H:TMR3L)
TMR3H and TMR3L registers are not cleared on any reset, only by the CCP special event triggers.
T1CON register is reset to 00h on a Power-on Reset or a Brown-out Reset. In any other reset,
the register is unaffected.
Timer3 is the default time base for the CCP1 and CCP2 modules. The timer can be disabled as
the time base for either CCP1, CCP2, or both, and Timer3 can be substituted. This is achieved
by setting control bits in the Timer3 control register.
This is explained in Section 16.8 - Timer3 and CCPx Enable.
When Timer3 is disabled as a the time base for a CCP, the reset on compare for that particular
CCP will have no effect on Timer3.
16.9 Timer3 Prescaler
The prescaler counter is cleared on writes to the TMR3H or TMR3L registers.
16.9.1 Timer3 Prescaler 16-bit Read/Write Mode
Writes to TMR3H do not clear the Timer3 prescaler in 16-bit read/write mode, because a write
to TMR3H only modifies the Timer3 latch and does not change the contents of Timer3. The
prescaler is only cleared on writes to TMR3L.
T3CCP2:T3CCP1 Time base for CCP1 Time base for CCP2
00 TMR1 TMR1
01 TMR1 TMR3
10 TMR3 TMR3
11 TMR3 TMR3
Note: The “Special Event Trigger” from the CCP1 and CCP2 modules will not set interrupt
flag bit TMR3IF.
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39516A-page 16-11
Section 16. Timer3
Timer3
16
16.10 16-bit Mode Timer Reads/Writes
Timer3 has modes that allow the 16-bit time register to be read as two 8-bit registers or one
16-bit register depending on the state of the RD16 bit.
When the RD16 control bit is set, the address for TMR3H is mapped to a buffer register for the
high byte of Timer3. A read from TMR3L will load the contents of the high byte of Timer3 into the
Timer3 high byte buffer. This provides the user with the ability to accurately read all 16 bits of
Timer3 without having to determine whether a read of the high byte followed by a read of the
low byte is valid due to a rollover between reads.
16.10.1 16-bit Mode Timer Write
A write to the high byte of Timer3 must also take place through the TMR3H buffer register. Timer3
high byte is updated with the contents of TMR3H when a write occurs to TMR3L. This allows a
user to write all 16 bits to both the high and low bytes of Timer3 at once (See Figure 16-3).
The high byte of Timer3 is not directly readable or writable in this mode. All reads and writes must
take place through the Timer3 high byte buffer register.
16.10.2 16-bit Read/Modify Write
Read modify write instructions like BSF or BCF will read the contents of a register, make the
appropriate changes, and place the result back into the register. In the case of Timer3 when configured
in 16-bit Read/Write mode, the read portion of a read-modify-write instruction of TMR3L
will not update the contents of the TMR3H buffer. The TMR3H buffer will remain unchanged.
When the write of TMR3L portion of the instruction takes place, the contents of TMR3H will be
placed into the high byte of Timer3.
Figure 16-3: Timer3 Block Diagram Configured in 16-bit Read/Write Mode
Timer3
TMR3L
T3SYNC
TMR3CS
T3CKPS1:T3CKPS0
SLEEP input
FOSC/4
Internal
Clock
TMR3ON
on/off
Prescaler
1, 2, 4, 8
Synchronize
det
1
0
0
1
Synchronized
Clock Input
2
TMR3
CLR
CCP Special Event Trigger
T3CCPx
To Timer1 Clock Input
High Byte
Data Bus<7:0>
8
TMR3H
8 8
8
Read TMR3L
Write TMR3L
Set TMR3IF flag bit
on Overflow
TT1P (1)
Note 1: Signal coming from TMR1 oscillator (see Figure 14-2 ).
39500 18C Reference Manual.book Page 11 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39516A-page 16-12 2000 Microchip Technology Inc.
16.11 Typical Application
The external oscillator clock input feature is typically used in applications where real-time needs
to be kept, but it is also desirable to have the lowest possible power consumption. The Timer1
oscillator allows the device to be placed in sleep, while the timer continues to increment. When
Timer3 overflows the interrupt wakes up the device so that the appropriate registers can be
updated.
Figure 16-4: Timer3 Application
In this example, a 32kHz 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 Timer1 must be loaded with a value to allow
the Timer1 to overflow at the desired rate. In the case of a 1 second Timer1 overflow, the TMR1H
register should be loaded with a value of 80k after each overflow.
8
4
4
4
4x4
Keypad
Current Sink
VSS
VDD
32 kHz
Backup
Battery
Power-Down
Detect
OSC1
TMR3
T1OSI
T1OSO
TT1P
Note: The TMR3L register should never be modified, since an external clock is asychronous
to the system clock. Writes to the TRM3L register may corrupt the real time
counter value causing inaccuracies.
39500 18C Reference Manual.book Page 12 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39516A-page 16-13
Section 16. Timer3
Timer3
16
16.12 Sleep Operation
When Timer3 is configured for asynchronous operation, the TMR3 registers will continue to
increment for each timer clock (or prescale multiple of clocks). When the TMR3 register overflows,
the TMR3IF bit will get set, and if enabled, generate an interrupt that will wake the processor
from sleep mode.
The Timer1 oscillator will add a delta current, due to the operation of this circuitry. That is, the
power-down current will no longer only be the leakage current of the device, but also the active
current of the Timer1 oscillator and other Timer1 circuitry.
16.13 Timer3 Prescaler
The prescaler counter is cleared on writes to the TMR3H or TMR3L registers.
Table 16-3: Registers Associated with Timer3 as a Timer/Counter
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Value on:
POR,
BOR
Value on
all other
resets
INTCON GIE PEIE T0IE INTE RBIE T0IF INTF RBIF 0000 000x 0000 000u
PIR TMR3IF (1) 0 0
PIE TMR3IE (1) 0 0
IPR TMR3IP (1) 0 0
TMR3L Holding register for the Least Significant Byte of the 16-bit TMR3 register xxxx xxxx uuuu uuuu
TMR3H Holding register for the Most Significant Byte of the 16-bit TMR3 register xxxx xxxx uuuu uuuu
T3CON RD16 T3CKPSI T3CKPS0 T30SCEN T3SYNC TMR3CS TMR3ON --00 0000 --uu uuuu
Legend: x = unknown, u = unchanged, - = unimplemented read as '0'.
Shaded cells are not used by the Timer1 module.
Note 1: The placement of this bit is device dependent.
39500 18C Reference Manual.book Page 13 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39516A-page 16-14 2000 Microchip Technology Inc.
16.14 Initialization
Since Timer3 has a software programmable clock source, there are three examples to show the
initialization of each mode. Example 16-4 shows the initialization for the internal clock source,
Example 16-5 shows the initialization for the external clock source, and Example 16-6 shows the
initialization of the external oscillator mode.
Example 16-4:Timer3 Initialization (Internal Clock Source)
Example 16-5:Timer3 Initialization (External Clock Source)
CLRF T3CON ; Stop Timer3, Internal Clock Source,
; T1 oscillator disabled,
; prescaler = 1:1
CLRF TMR3H ; Clear Timer3 High byte register
CLRF TMR3L ; Clear Timer3 Low byte register
CLRF INTCON ; Disable interrupts
CLRF PIE1 ; Disable peripheral interrupts
CLRF PIR1 ; Clear peripheral interrupts Flags
MOVLW 0x30 ; Internal Clock source
; with 1:8 prescaler
MOVWF T3CON ; Timer3 is stopped and
; T1 osc is disabled
BSF T3CON, TMR3ON ; Timer3 starts to increment
;
; The Timer3 interrupt is disabled, do polling on the overflow bit
;
T3_OVFL_WAIT
BTFSS PIR1, TMR3IF
GOTO T3_OVFL_WAIT
;
; Timer has overflowed
;
BCF PIR1, TMR3IF
CLRF T3CON ; Stop Timer3, Internal Clock Source,
; T1 oscillator disabled,
; prescaler = 1:1
CLRF TMR3H ; Clear Timer3 High byte register
CLRF TMR3L ; Clear Timer3 Low byte register
CLRF INTCON ; Disable interrupts
CLRF PIE1 ; Disable peripheral interrupts
CLRF PIR1 ; Clear peripheral interrupts Flags
MOVLW 0x32 ; External Clock source
; with 1:8 prescaler
MOVWF T3CON ; Clock source is
; synchronized to device
; Timer3 is stopped and
; T1 osc is disabled
BSF T3CON, TMR3ON ; Timer3 starts to increment
;
; The Timer3 interrupt is disabled, do polling on the overflow bit
;
T3_OVFL_WAIT
BTFSS PIR1, TMR3IF
GOTO T3_OVFL_WAIT
;
; Timer has overflowed
;
BCF PIR1, TMR3IF
39500 18C Reference Manual.book Page 14 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39516A-page 16-15
Section 16. Timer3
Timer3
16
Example 16-6:Timer3 Initialization (External Oscillator Clock Source)
CLRF T3CON ; Stop Timer3, Internal Clock Source,
; T1 oscillator disabled,
; prescaler = 1:1
CLRF TMR3H ; Clear Timer3 High byte register
CLRF TMR3L ; Clear Timer3 Low byte register
CLRF INTCON ; Disable interrupts
CLRF PIE1 ; Disable peripheral interrupts
CLRF PIR1 ; Clear peripheral interrupts Flags
MOVLW 0x3E ; External Clock source
; with oscillator
MOVWF T3CON ; circuitry, 1:8 prescaler,
; Clock source is
; asynchronous to device
; Timer3 is stopped
BSF T3CON, TMR3ON ; Timer3 starts to increment
;
; The Timer3 interrupt is disabled, do polling on the overflow bit
;
T3_OVFL_WAIT
BTFSS PIR1, TMR3IF
GOTO T3_OVFL_WAIT
;
; Timer has overflowed
;
BCF PIR1, TMR3IF
39500 18C Reference Manual.book Page 15 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39516A-page 16-16 2000 Microchip Technology Inc.
16.15 Design Tips
Question 1: Timer3 does not seem to be keeping accurate time.
Answer 1:
There are a few reasons that this could occur:
1. You should never write to Timer3, where that could cause the loss of time. In most cases,
that means you should not write to the TMR3L register, but if the conditions are ok, you
may write to the TMR3H register. Normally you write to the TMR3H register if you want
the Timer3 overflow interrupt to be sooner then the full 16-bit time-out.
2. You should ensure the your layout uses good PCB layout techniques so that noise does
not couple onto the Timer1/Timer3 oscillator lines.
39500 18C Reference Manual.book Page 16 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39516A-page 16-17
Section 16. Timer3
Timer3
16
16.16 Related Application Notes
This section lists application notes that are related to this section of the manual. These application
notes may not be written specifically for the Enhance family (that is they may be written for
the Baseline, the Midrange, or High-end families), but the concepts are pertinent, and could be
used (with modification and possible limitations). The current application notes related to Timer1
are:
Title Application Note #
Using Timer1 in Asynchronous Clock Mode AN580
Low Power Real Time Clock AN582
Yet another Clock using the PIC16C92X AN649
Note: Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
http://www.microchip.com/10/faqs/codeex/
39500 18C Reference Manual.book Page 17 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39516A-page 16-18 2000 Microchip Technology Inc.
16.17 Revision History
Revision A
This is the initial released revision of the Timer3 module description.
39500 18C Reference Manual.book Page 18 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39517A-page 17-1
CCP
17
Section 17. Compare/Capture/PWM (CCP)
HIGHLIGHTS
This section of the manual contains the following major topics:
17.1 Introduction .................................................................................................................. 17-2
17.2 CCP Control Register .................................................................................................. 17-3
17.3 Capture Mode .............................................................................................................. 17-4
17.4 Compare Mode ............................................................................................................ 17-7
17.5 PWM Mode ................................................................................................................ 17-10
17.6 Initialization ................................................................................................................ 17-15
17.7 Design Tips ................................................................................................................ 17-17
17.8 Related Application Notes.......................................................................................... 17-19
17.9 Revision History ......................................................................................................... 17-20
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39517A-page 17-2 2000 Microchip Technology Inc.
17.1 Introduction
Each CCP (Capture/Compare/PWM) module has three 8-bit registers. These are:
• An 8-bit control register (CCPxCON)
• A 16-bit register (CCPRxH:CCPRxL) that operates as:
- a 16-bit capture register
- a 16-bit compare register
- a 10-bit PWM master/slave duty cycle register
Multiple CCP modules may exist on a single device. The CCP modules are identical in operation,
with the exception of the operation of the special event trigger.
Throughout this section, we use generic names for the CCP registers. These generic names are
shown in Table 17-1.
Table 17-1: Specific to Generic CCP Nomenclature
17.1.1 Timer Resources
Table 17-2 shows the resources of the CCP modules, in each of its modes. Table 17-3 shows the
interactions between the CCP modules, where CCPx is one CCP module and CCPy is another
CCP module.
Table 17-2: CCP Mode - Timer Resource
Table 17-3: Interaction of Two CCP Modules
Generic Name CCP1 CCP2 Comment
CCPxCON CCP1CON CCP2CON CCP Control Register
CCPRxH CCPR1H CCPR2H CCP high byte
CCPRxL CCPR1L CCPR2L CCP low byte
CCPx CCP1 CCP2 CCP pin
CCP Mode Timer Resource
Capture
Compare
PWM
Timer1 or Timer3
Timer1 or Timer3
Timer2
CCPx
Mode
CCPy
Mode Interaction
Capture Capture TMR1 or TMR3 time-base. Time base can be different for each CCP.
Capture Compare The compare could be configured for the special event trigger, which
clears either TMR1 or TMR3 depending upon which time base is used.
Compare Compare The compare(s) could be configured for the special event trigger, which
clears TMR1 or TMR3 depending upon which time base is used.
PWM PWM The PWMs will have the same frequency, and update rate
(TMR2 interrupt).
PWM Capture None
PWM Compare None
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39517A-page 17-3
Section 17. CCP
CCP
17
17.2 CCP Control Register
Register 17-1 shows the CCP Control Register. This register selects the mode of operation of the
CCP module, as well as contains the 2-LSb of the PWM Duty Cycle.
Register 17-1: CCPxCON Register
U-0 U-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
— — DCxB1 DCxB0 CCPxM3 CCPxM2 CCPxM1 CCPxM0
bit 7 bit 0
bit 7-6 Unimplemented: Read as '0'
bit 5-4 DCxB<1:0>: PWM Duty Cycle bit1 and bit0
Capture Mode:
Unused
Compare Mode:
Unused
PWM Mode:
These bits are the two LSbs (bit1 and bit0) of the 10-bit PWM duty cycle. The upper eight
bits (DCx<9:2>) of the duty cycle are found in CCPRxL.
bit 3-0 CCPxM<3:0>: CCPx Mode Select bits
0000 = Capture/Compare/PWM off (resets CCPx module)
0001 = Reserved
0010 = Compare mode, toggle output on match (CCPxIF bit is set)
0011 = Reserved
0100 = Capture mode, every falling edge
0101 = Capture mode, every rising edge
0110 = Capture mode, every 4th rising edge
0111 = Capture mode, every 16th rising edge
1000 = Compare mode,
Initialize CCP pin Low, on compare match force CCP pin High (CCPIF bit is set)
1001 = Compare mode,
Initialize CCP pin High, on compare match force CCP pin Low (CCPIF bit is set)
1010 = Compare mode,
Generate software interrupt on compare match
(CCPIF bit is set, CCP pin is unaffected)
1011 = Compare mode,
Trigger special event (CCPIF bit is set)
11xx = PWM mode
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39517A-page 17-4 2000 Microchip Technology Inc.
17.3 Capture Mode
In Capture mode, CCPRxH:CCPRxL captures the 16-bit value of the TMR1 or TMR3 register
when an event occurs on the CCPx pin. An event is defined as:
• Every falling edge
• Every rising edge
• Every 4th rising edge
• Every 16th rising edge
An event is selected by control bits CCPxM3:CCPxM0 (CCPxCON<3:0>). When a capture is
made, the interrupt request flag bit, CCPxIF, is set. The CCPxIF bit must be cleared in software.
If another capture occurs before the value in register CCPRx is read, the old captured value will
be lost.
When the Capture mode is changed, a false capture interrupt may be generated. The user
should keep bit CCPxIE clear to avoid false interrupts and should clear flag bit CCPxIF following
any such change in operating mode.
Figure 17-1 shows that a capture does not modify (clear) the 16-bit timer register. This is so the
timer (Timer1 or Timer3) can also be used as the time-base for other operations.
The time between two captures can easily be computed as the difference between the value of
the 2nd capture and that of the 1st capture. When the timer overflows, the timer interrupt bit,
TMRxIF will be set. If enabled, an interrupt will occur, allowing the time-base to be extended to
greater than 16 bits.
Note: The dedicated time base (Timer1 or Timer3) must be running in Timer mode or Synchronized
Counter mode for the CCP module to use the capture feature. In Asynchronous
Counter mode, the capture operation may not work.
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39517A-page 17-5
Section 17. CCP
CCP
17
17.3.1 CCP Pin Configuration
In Capture mode, the CCPx pin should be configured as an input by setting its corresponding
TRIS bit. The prescaler can be used to get a very fine average resolution on a constant input
frequency. For example, if we have a stable input frequency and we set the prescaler to 1:16,
then the total error for those 16 periods is 1 TCY. This gives an effective resolution of TCY/16,
which at 40 MHz is 6.25 ns. This technique is only valid where the input frequency is “stable” over
the 16 samples. Without using the prescaler (1:1), each sample would have a resolution of TCY.
Figure 17-1: Capture Mode Operation Block Diagram
Note: If the CCPx pin is configured as an output, a write to the port can cause a capture
condition.
CCPR1H CCPR1L
TMR1H TMR1L
Set flag bit CCPxIF
TMR3
Enable
Q’s
CCP1CON<3:0>
CCPx Pin
Prescaler
³ 1, 4, 16
and
edge detect
TMR3H TMR3L
TMR1
Enable
T3CCP2
T3CCP2
CCPR2H CCPR2L
TMR1H TMR1L
Set flag bit CCP2IF
TMR3
Enable
Q’s
CCP2CON<3:0>
CCPx Pin
Prescaler
³ 1, 4, 16
and
edge detect
TMR3H TMR3L
TMR1
Enable
T3CCP2
T3CCP1
T3CCP2
T3CCP1
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39517A-page 17-6 2000 Microchip Technology Inc.
17.3.2 Changing Between Capture Modes
When the Capture mode is changed, a capture interrupt may be generated. The user should
keep the CCPxIE bit clear to disable these interrupts and should clear the CCPxIF flag bit following
any such change in operating mode.
17.3.2.1 CCP Prescaler
There are four prescaler settings, specified by the CCPxM3:CCPxM0 bits. Whenever the CCP
module is turned off, or the CCP module is not in capture mode, the prescaler counter is cleared.
This means that any reset will clear the prescaler counter.
Switching from one capture prescale setting to another may generate an interrupt. Also, the prescaler
counter will not be cleared, therefore the first capture may be from a non-zero prescaler.
Example 17-1 shows the recommended method for switching between capture prescale settings.
This example uses CCP1 and clears the prescaler counter so not to generate an unintended
interrupt.
Example 17-1:Changing Between Capture Prescalers
To clear the Capture prescaler count, the CCP module must be configured into any non-capture
CCP mode (Compare, PWM, or CCP off modes).
17.3.3 Sleep Operation
When the device is placed in SLEEP, the timer will not increment (since it is in synchronous
mode), but the prescaler will continue to count events (not synchronized). When a specified capture
event occurs, the CCPxIF bit will be set, but the capture register will not be updated. If the
CCP interrupt is enabled, the device will wake-up from SLEEP. The value in the 16-bit TMR1 register
is not transferred to the 16-bit capture register. Effectively, this allows the CCP pin to be
used as another external interrupt.
17.3.4 Effects of a Reset
The CCP module is off, and the value in the capture prescaler is cleared.
CLRF CCP1CON ; Turn CCP module off
MOVLW NEW_CAPT_PS ; Load the W reg with the new prescaler
; mode value and CCP ON
MOVWF CCP1CON ; Load CCP1CON with this value
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39517A-page 17-7
Section 17. CCP
CCP
17
17.4 Compare Mode
In Compare mode, the 16-bit CCPRx register value is constantly compared against the TMR1 or
TMR3 register pair value. When a match occurs, the CCPx pin is:
• Driven High
• Driven Low
• Toggle output (Low to High or High to Low)
• Not affected (remains unchanged) and configured as I/O pin
The action on the pin is based on the value of control bits CCPxM3:CCPxM0
(CCPxCON3:CCPxCON0). At the same time, interrupt flag bit CCPxIF is set.
Figure 17-2: Compare Mode Operation Block Diagram
Note: The dedicated time base (Timer1 or Timer3) must be running in Timer mode or Synchronized
Counter mode if the CCP module is using the compare feature. In Asynchronous
Counter mode, the compare operation may not work.
CCPR1H CCPR1L
TMR1H TMR1L
Comparator Q S
R
Output
Logic
Special Event Trigger
Set flag bit CCP1IF
CCP1 match
TRISX
CCP1CON<3:0>
Mode Select
Output Enable
Pin
Special event trigger will:
Reset Timer1or Timer3, but not set Timer1 or Timer3 interrupt flag bit,
and set bit GO/DONE (ADCON0 register),
which starts an A/D conversion (CCP2 only).
TMR3H TMR3L
T3CCP2
CCPR2H CCPR2L
Comparator
0 1
T3CCP2
T3CCP1
Q S
R
Output
Logic
Special Event Trigger
Set flag bit CCP2IF
CCP2 match
TRIS
CCP2CON<3:0>
Mode Select
Output Enable
Pin
0 1
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39517A-page 17-8 2000 Microchip Technology Inc.
17.4.1 CCP Pin Operation in Compare Mode
The user must configure the CCPx pin as an output by clearing the appropriate TRIS bit.
Selecting the compare output mode, forces the state of the CCP pin to the state that is opposite
of the match state. So if the Compare mode is selected to force the output pin low on match,
then the output will be forced high until the match occurs (or the mode is changed). In the compare
toggle mode, the CCPx pin output is initially forced to the low state.
17.4.2 Software Interrupt Mode
When Generate Software Interrupt mode is chosen, the CCPx pin is not affected. Only a CCP
interrupt is generated (if enabled).
17.4.3 Special Event Trigger
In this mode, an internal hardware trigger is generated that may be used to initiate an action.
The special event trigger output of CCPx resets the assigned timer register pair (TMR1 or TMR3
depending upon the state of the T3CCPx bits). This allows the CCPRxH:CCPRxL registers to
effectively be a 16-bit programmable period register for the timer (Timer1 or Timer3).
For some devices, the special trigger output of the CCP module resets the timer (TMR1 or TMR3)
register pair (depending upon the state of the T3CCPx bits), and starts an A/D conversion (if the
A/D module is enabled).
17.4.4 Sleep Operation
When the device is placed in SLEEP, the timer will not increment (since it is in Synchronous
mode), and the state of the module will not change. If the CCP pin is driving a value, it will continue
to drive that value. When the device wakes-up, it will continue from this state.
17.4.5 Effects of a Reset
The CCP module is off.
Note: Clearing the CCPxCON register will force the CCPx compare output latch to the
default low level. This is not the Port I/O data latch.
Note: The special event trigger will not set the Timers interrupt flag bit, TMRxIF.
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39517A-page 17-9
Section 17. CCP
CCP
17
Table 17-4: Registers Associated with Capture, Compare, Timer1 and Timer3
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Value on
POR,
BOR
Value on
all other
resets
INTCON GIE/
GIEH
PEIE/
GIEL
TMR0IE INT0IE RBIE TMR0IF INT0IF RBIF 0000 000x 0000 000u
PIR1 PSPIF (1) ADIF RCIF TXIF SSPIF CCP1IF TMR2IF TMR1IF 0000 0000 0000 0000
PIE1 PSPIE (1) ADIE RCIE TXIE SSPIE CCP1IE TMR2IE TMR1IE 0000 0000 0000 0000
IPR1 PSPIP (1) ADIP RCIP TXIP SSPIP CCP1IP TMR2IP TMR1IP 0000 0000 0000 0000
TRISC PORTC Data Direction Register 1111 1111 1111 1111
TMR1L Holding register for the Least Significant Byte of the 16-bit TMR1 register xxxx xxxx uuuu uuuu
TMR1H Holding register for the Most Significant Byte of the 16-bit TMR1register xxxx xxxx uuuu uuuu
T1CON RD16 — T1CKPS1 T1CKPS0 T1OSCEN T1SYNC TMR1CS TMR1ON --00 0000 --uu uuuu
CCPR1L Capture/Compare/PWM register1 (LSB) xxxx xxxx uuuu uuuu
CCPR1H Capture/Compare/PWM register1 (MSB) xxxx xxxx uuuu uuuu
CCP1CON — — DC1B1 DC1B0 CCP1M3 CCP1M2 CCP1M1 CCP1M0 --00 0000 --00 0000
CCPR2L Capture/Compare/PWM register2 (LSB) xxxx xxxx uuuu uuuu
CCPR2H Capture/Compare/PWM register2 (MSB) xxxx xxxx uuuu uuuu
CCP2CON — — DC2B1 DC2B0 CCP2M3 CCP2M2 CCP2M1 CCP2M0 --00 0000 --00 0000
PIR2 — — — — BCLIF LVDIF TMR3IF CCP2IF 0000 0000 0000 0000
PIE2 — — — — BCLIE LVDIE TMR3IE CCP2IE 0000 0000 0000 0000
IPR2 — — — — BCLIP LVDIP TMR3IP CCP2IP 0000 0000 0000 0000
TMR3L Holding register for the Least Significant Byte of the 16-bit TMR3 register xxxx xxxx uuuu uuuu
TMR3H Holding register for the Most Significant Byte of the 16-bit TMR3 register xxxx xxxx uuuu uuuu
T3CON RD16 T3CCP2 T3CKPS1 T3CKPS0 T3CCP1 T3SYNC TMR3CS TMR3ON -000 0000 -uuu uuuu
Legend: x = unknown, u = unchanged, - = unimplemented read as '0'.
Shaded cells are not used by Capture, Compare, Timer1 and Timer3.
Note 1: The PSPIF, PSPIE and PSPIP bits are reserved on the PIC18C2x2 devices. Always maintain these bits clear.
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39517A-page 17-10 2000 Microchip Technology Inc.
17.5 PWM Mode
In Pulse Width Modulation (PWM) mode, the CCPx pin produces up to a 10-bit resolution PWM
output. Since the CCPx pin is multiplexed with the PORT data latch, the corresponding TRIS bit
must be cleared to make the CCPx pin an output.
Figure 17-3 shows a simplified block diagram of one CCP module in PWM mode. Depending on
the device there can be more than one CCP module connected to Timer2. Each CCP module
can support one Pulse Width Modulation (PWM) output signal. This PWM signal can attain a resolution
of up to 10-bits, from the 8-bit Timer2 module. Two extra bits are used to extend Timer2
to 10 bits (see Section 17.5.1). A PWM output waveform is shown in Figure 17-4.
For a step-by-step procedure on how to set up the CCP module for PWM operation, see
Section 17.5.4.
Figure 17-3: Simplified PWM Block Diagram
Figure 17-4: PWM Output Waveform
Note: Clearing the CCPxCON register will force the CCPx PWM output latch to the default
low level. This is not the Port I/O data latch.
CCPRxL
CCPRxH (Slave)
Comparator
TMR2
Comparator
PR2
R Q
S
Duty Cycle Registers CCPxCON<5:4>
Clear Timer,
TRIS
CCPx
Timer2 Module
(Note 1)
8
8
10
10
10
CCP Module
Note 1: For 10-bit time base generation see Section 17.5.1.
(DCxB<9:2>)
(DCxB<1:0>)
Force CCPx pin high,
and latch the Duty Cycle
Period = PR2 + 1
Timer2 is cleared and new duty cycle value is loaded from the Duty Cycle latch into the
Timer2 value equals to value in Duty Cycle Latch register, CCP Pin is driven low
Timer2 overflow, value from Duty Cycle Latch is loaded into Slave Register, CCP Pin driven high
DutyCycle = DCxB9:DCxB0
1 3 2
2
3
1
Duty Cycle Slave register
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39517A-page 17-11
Section 17. CCP
CCP
17
17.5.1 10-bit Time Base Generation
The PWM output has up to 10-bits of resolution. This is achieved by creating a 10-bit PWM Time
base (TB9:TB0). Figure 17-5 shows the block diagram of this 10-bit PWM Time base. When
TSCLK is the clock source to the 10-bit counter, the counter increments on each Tsclk. If a
prescaler is selected, the 10-bit counter increments every prescale would by TSCLK.
Figure 17-5: 10-bit Time Base Block Diagram
17.5.2 PWM Period
The PWM period is specified by writing to the PR2 register. The PWM period can be calculated
using Equation 17-1.
Equation 17-1:Calculation for PWM Period
When TMR2 is equal to PR2, the following three events occur on the next increment cycle:
• TMR2 is cleared
• The CCPx pin is set (exception: if PWM duty cycle = 0%, the CCPx pin will not be set)
• The PWM duty cycle is latched from CCPRxL into CCPRxH
TMR2 TSCLK
Note 1: These two bits are not readable or writable and are not mapped into the data
memory.
TB0 (1) TB1 TB9 TB2 (1)
Prescaler
TMR2
Where PR2 = Value in PR2 Register
TSCLK = Oscillator Clock
TPWM period = [(PR2) + 1] • 4 • TSCLK • (TMR2 prescale value)
Note: The Timer2 postscaler is not used in the determination of the PWM frequency. The
postscaler could be used to generate TMR2 interrupts at a different frequency than
the PWM output.
39500 18C Reference Manual.book Page 11 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39517A-page 17-12 2000 Microchip Technology Inc.
17.5.3 PWM Duty Cycle
The PWM duty cycle is specified by writing to the CCPRxL register and to the DCxB1:DCxB0
(CCPxCON<5:4>) bits, if 10-bit resolution is desired. The CCPRxL contains the eight MSbs and
CCPxCON<5:4> contains the two LSbs. This 10-bit value is represented by DCxB9:DCxB0.
Equation 17-2 is used to calculate the PWM duty cycle.
Equation 17-2:Equation for calculating the PWM Duty Cycle
The DCxB<9:0> bits can be written to at any time, but the duty cycle value is not latched into
CCPRxH until after a match between PR2 and TMR2 occurs (which is the end of the current
period). In PWM mode, CCPRxH is a read-only register.
The CCPRxH register and a 2-bit internal latch are used to double buffer the PWM duty cycle.
This double buffering is essential for glitchless PWM operation.
When CCPRxH and a 2-bit latch match the value of TMR2 concatenated with the internal 2-bit
Q clock (or two bits of the TMR2 prescaler), the CCPx pin is cleared. This is the end of the duty
cycle. Equation 17-3 is used to calculate the maximum PWM resolution in bits for a given PWM
frequency.
Equation 17-3:Calculation for Maximum PWM Resolution
17.5.3.1 Minimum Resolution
The minimum resolution (in time) of each bit of the PWM duty cycle depends on the prescaler of
Timer2. Table 17-5 shows the selections for the minimum resolution time.
Table 17-5: Minimum Duty Cycle Bit Time
Where PWM Duty Cycle = PWM Duty Cycle Time
TSCLK = Oscillator Clock
PWM Duty Cycle = (DCxB<9:0> bits value) • TSLCK • (TMR2 prescale value)
log( FPWM
log(2)
FOSC )
Maximum PWM Resolution (bits) = bits
Note: If the PWM duty cycle value is longer than the PWM period, the CCPx pin will not
be cleared. This allows a duty cycle of 100%.
Prescaler
Value T2CKPS1:T2CKPS0 Minimum Resolution
(Time)
1 0 0 TSCLK
4 0 1 TCY
16 1 x 4 TCY
39500 18C Reference Manual.book Page 12 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39517A-page 17-13
Section 17. CCP
CCP
17
17.5.3.2 Example Calculation for PWM Period and Duty Cycle
This section shows an example calcuation for the PWM Period and Duty Cycle. Furthermore
example PWM frequencies based upon different oscillator frequencies are given.
Example 17-2:PWM Period and Duty Cycle Calculation
At most, an 8-bit resolution duty cycle can be obtained from a 78.125 kHz frequency and a
20 MHz oscillator (i.e., 0 ≤ DCxB9:DCxB0 ≤ 255). Any value greater than 255 will result in a 100%
duty cycle.
In order to achieve higher resolution, the PWM frequency must be decreased. In order to achieve
higher PWM frequency, the resolution must be decreased.
Table 17-6 lists example PWM frequencies and resolutions for FOSC = 20 MHz. Table 17-7 lists
example PWM frequencies and resolutions for FOSC = 40 MHz. The TMR2 prescaler and PR2
values are also shown.
Table 17-6: Example PWM Frequencies and Bit Resolutions at 20 MHz
Table 17-7: Example PWM Frequencies and Bit Resolutions at 40 MHz
Desired PWM frequency is 78.125 kHz,
Fosc = 20 MHz
TMR2 prescale = 1
1 / 78.125 kHz = [(PR2) + 1] • 4 • 1/20 MHz • 1
12.8 ms = [(PR2) + 1] • 4 • 50 ns • 1
PR2 = 63
Find the maximum resolution of the duty cycle that can be used with a 78.125 kHz frequency
and 20 MHz oscillator:
1 / 78.125 kHz = 2PWM RESOLUTION • 1/20 MHz • 1
12.8 ms = 2PWM RESOLUTION • 50 ns • 1
256 = 2PWM RESOLUTION
log(256) = (PWM Resolution) • log(2)
PWM Resolution= 8.0
PWM Frequency 1.22 kHz 4.88 kHz 19.53 kHz 78.12 kHz 156.3 kHz 208.3 kHz
Timer Prescaler
(1, 4, 16) 16 4 1 1 1 1
PR2 Value 0xFF 0xFF 0xFF 0x3F 0x1F 0x17
Maximum
Resolution (bits) 10 10 10 8 7 5.5
PWM Frequency 2.44 kHz 9.76 kHz 39.06 kHz 78.12 kHz 208.3 kHz 416.6 kHz
Timer Prescaler
(1, 4, 16) 16 4 1 1 1 1
PR2 Value 0xFF 0xFF 0xFF 0x3F 0x1F 0x17
Maximum
Resolution (bits) 10 10 10 8 7 5.5
39500 18C Reference Manual.book Page 13 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39517A-page 17-14 2000 Microchip Technology Inc.
17.5.4 Set-up for PWM Operation
The following steps configure the CCP module for PWM operation:
1. Establish the PWM period by writing to the PR2 register.
2. Establish the PWM duty cycle by writing to the DCxB9:DCxB0 bits.
3. Make the CCPx pin an output by clearing the appropriate TRIS bit.
4. Establish the TMR2 prescale value and enable Timer2 by writing to T2CON.
5. Configure the CCP module for PWM operation.
17.5.5 Sleep Operation
When the device is placed in sleep, Timer2 will not increment, and the state of the module will
not change. If the CCP pin is driving a value, it will continue to drive that value. When the device
wakes-up, it will continue from this state.
17.5.6 Effects of a Reset
The CCP module is off.
Table 17-8: Registers Associated with PWM and Timer2
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Value on
POR,
BOR
Value on
all other
resets
INTCON GIE/GIEH PEIE/GIEL TMR0IE INT0IE RBIE TMR0IF INT0IF RBIF 0000 000x 0000 000u
PIR1 TMR2IF (1) 0000 0000 0000 0000
PIE1 TMR2IE (1) 0000 0000 0000 0000
IPR1 TMR2IP (1) 0000 0000 0000 0000
TRISC PORTC Data Direction Register 1111 1111 1111 1111
TMR2 Timer2 module’s register 0000 0000 0000 0000
PR2 Timer2 module’s period register 1111 1111 1111 1111
T2CON — TOUTPS3 TOUTPS2 TOUTPS1 TOUTPS0 TMR2ON T2CKPS1 T2CKPS0 -000 0000 -000 0000
CCPR1L Capture/Compare/PWM register1 (LSB) xxxx xxxx uuuu uuuu
CCPR1H Capture/Compare/PWM register1 (MSB) xxxx xxxx uuuu uuuu
CCP1CON — — DC1B1 DC1B0 CCP1M3 CCP1M2 CCP1M1 CCP1M0 --00 0000 --00 0000
CCPR2L Capture/Compare/PWM register2 (LSB) xxxx xxxx uuuu uuuu
CCPR2H Capture/Compare/PWM register2 (MSB) xxxx xxxx uuuu uuuu
CCP2CON — — DC2B1 DC2B0 CCP2M3 CCP2M2 CCP2M1 CCP2M0 --00 0000 --00 0000
Legend: x = unknown, u = unchanged, — = unimplemented read as '0'.
Shaded cells are not used by PWM and Timer2.
Note 1: The PSPIF, PSPIE and PSPIP bits are reserved on the PIC18C2X2 devices. Always maintain these bits clear.
39500 18C Reference Manual.book Page 14 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39517A-page 17-15
Section 17. CCP
CCP
17
17.6 Initialization
The CCP module has three modes of operation. Example 17-3 shows the initialization of capture
mode, Example 17-4 shows the initialization of compare mode and Example 17-5 shows the
initialization of PWM mode.
Example 17-3:Capture Initialization
CLRF CCP1CON ; CCP Module is off
CLRF TMR1H ; Clear Timer1 High byte
CLRF TMR1L ; Clear Timer1 Low byte
CLRF INTCON ; Disable interrupts and clear T0IF
BSF TRISC, CCP1 ; Make CCP pin input
CLRF PIE1 ; Disable peripheral interrupts
CLRF PIR1 ; Clear peripheral interrupts Flags
MOVLW 0x06 ; Capture mode, every 4th rising edge
MOVWF CCP1CON ;
BSF T1CON, TMR1ON ; Timer1 starts to increment
;
; The CCP1 interrupt is disabled,
; do polling on the CCP Interrupt flag bit
;
Capture_Event
BTFSS PIR1, CCP1IF
GOTO Capture_Event
;
; Capture has occured
;
BCF PIR1, CCP1IF ; This needs to be done before
; next compare
39500 18C Reference Manual.book Page 15 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39517A-page 17-16 2000 Microchip Technology Inc.
Example 17-4:Compare Initialization
Example 17-5:PWM Initialization
CLRF CCP1CON ; CCP Module is off
CLRF TMR1H ; Clear Timer1 High byte
CLRF TMR1L ; Clear Timer1 Low byte
CLRF INTCON ; Disable interrupts and clear T0IF
MOVLW 0x80 ; Load 0x80 (Example Value)
; into W-Register
MOVWF CCPRIH ; Load value to compare into CCPRIH
MOVWF CCPRIL ; Load value to compare into CCPRIL
BCF TRISC, CCP1 ; Make CCP pin output if controlling
; state of pin
CLRF PIE1 ; Disable peripheral interrupts
CLRF PIR1 ; Clear peripheral interrupts Flags
MOVLW 0x08 ; Compare mode, set CCP1 pin on match
MOVWF CCP1CON ;
BSF T1CON, TMR1ON ; Timer1 starts to increment
;
; The CCP1 interrupt is disabled,
; do polling on the CCP Interrupt flag bit
;
Compare_Event
BTFSS PIR1, CCP1IF
GOTO Compare_Event
;
; Compare has occured
;
BCF PIR1, CCP1IF ; This needs to be done before
; next compare
CLRF CCP1CON ; CCP Module is off
CLRF TMR2 ; Clear Timer2
MOVLW 0x7F ;
MOVWF PR2 ;
MOVLW 0x1F ;
MOVWF CCPR1L ; Duty Cycle is 25% of PWM Period
CLRF INTCON ; Disable interrupts and clear T0IF
BCF TRISC, PWM1 ; Make pin output
CLRF PIE1 ; Disable peripheral interrupts
CLRF PIR1 ; Clear peripheral interrupts Flags
MOVLW 0x2C ; PWM mode, 2 LSbs of
; Duty cycle = 10
MOVWF CCP1CON ;
BSF T2CON, TMR2ON ; Timer2 starts to increment
;
; The CCP1 interrupt is disabled,
; do polling on the TMR2 Interrupt flag bit
;
PWM_Period_Match
BTFSS PIR1, TMR2IF
GOTO PWM_Period_Match
;
; Update this PWM period and the following PWM Duty cycle
;
BCF PIR1, TMR2IF
39500 18C Reference Manual.book Page 16 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39517A-page 17-17
Section 17. CCP
CCP
17
17.7 Design Tips
Question 1: What timers can I use for the capture and compare modes?
Answer 1:
The capture and compare modes are designed around Timer1 and Timer3, so no other timer can
be used for these functions. This also means that if multiple CCP modules are being used for a
capture or compare function, they can share the same timer.
Question 2: What timers can I use with the PWM mode?
Answer 2:
The PWM mode is designed around Timer2, so no other timer can be used for this function. It is
the only timer with a period register associated with it. If multiple CCP modules are doing PWM,
they will share the same timer and have the same PWM period and frequency.
Question 3: Can I use one CCP module to do capture (or compare) AND PWM at the
same time, since they use different timers as their reference?
Answer 3:
The timers may be different, but other logic functions are shared. However, you can switch from
one mode to the other. For a device with 2 CCP modules, you can also have CCP1 set up for
PWM and CCP2 set up for capture or compare (or vice versa) since they are two independent
modules.
Question 4: How does a reset affect the CCP module?
Answer 4:
Any reset will turn the CCP module off. See the “Reset” section to see reset values.
Question 5: I am setting up the CCP1CON module for “Compare Mode, trigger special
event” (1011) that resets TMR1. When a compare match occurs, will I have
both the TMR1 and the CCP1 interrupts pending (TMR1IF is set, CCP1IF is
set)?
Answer 5:
The CCP1IF flag will be set on the match condition. TMR1IF is set when Timer1 overflows, and
the special trigger reset of Timer1 is not considered an overflow. However, if both the CCPR1L
and CCPR1H registers are set at FFh, then an overflow occurs at the same time as the match,
which will then set both CCP1IF and TMR1IF.
Question 6: How do I use Timer2 as a general purpose timer, with an interrupt flag on
rollover?
Answer 6:
Timer2 always resets to zero when it equals PR2 and flag bit TMR2IF always gets set at this time.
By putting FFh into PR2, you will get an interrupt on overflow at FFh. Quite often it is desirable
to have an event occur at a periodic rate, perhaps an interrupt driven event. Normally an initial
value would be placed into the timer so that the overflow will occur at the desired time. This value
would have to be placed back into the timer every time it overflowed to make the interrupts occur
at the same desired rate. The benefit of Timer2 is that a value can be written to PR2 that will
cause it to reset at your desired time interval. This means you do not have the housekeeping
chore of reloading the timer every time it overflows, since PR2 maintains its value.
39500 18C Reference Manual.book Page 17 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39517A-page 17-18 2000 Microchip Technology Inc.
Question 7: I am using a CCP module in PWM mode. The duty cycle being outputted is
almost always 100%, even when my program writes a value like 7Fh to the
duty cycle register, which should be 50%. What am I doing wrong?
Answer 7:
1. The value in CCPRxL is higher than PR2. This happens quite often when a user desires
a fast PWM output frequency and writes a small value in the PR2. In this case, if a value
of 7Eh were written to PR2, then a value 7Fh in CCPRxL will result in 100% duty cycle.
2. If the TRIS bit corresponding to the CCP output pin you are using is configured as an
input, the PWM output cannot drive the pin. In this case, the pin would float and duty cycle
may appear to be 0%, 100% or some other floating value.
Question 8: I want to determine a signal frequency using the CCP module in capture
mode to find the period. I am currently resetting Timer1 on the first edge,
then using the value in the capture register on the second edge as the time
period. The problem is that my code to clear the timer does not occur until
almost twelve instructions after the first capture edge (interrupt latency
plus saving of registers in interrupt), so I cannot measure very fast frequencies.
Is there a better way to do this?
Answer 8:
You do not need to zero the counter to find the difference between two pulse edges. Just take
the first captured value and put it into another set of registers. Then when the second capture
event occurs, subtract the first event from the second. Assuming that your pulse edges are not
so far apart that the counter can wrap around past the last capture value, the answer will always
be correct. This is illustrated by the following example:
1. First captured value is FFFEh. Store this value in two registers.
2. The second capture value is 0001h (the counter has incremented three times).
3. 0001h - FFFEh = 0003, which is the same as if you had cleared Timer1 to zero and let it
count to 3. (Theoretically, except that there was a delay getting to the code that clears
Timer1, so actual values would differ).
The interrupt overhead is now less important because the values are captured automatically. For
even faster inputs, do not enable interrupts and just test the flag bit in a loop. If you must also
capture very long time periods, such that the timer can wrap around past the previous capture
value, then consider using an auto-scaling technique that starts with a large prescale, and
shorten the prescale as you converge on the exact frequency.
39500 18C Reference Manual.book Page 18 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39517A-page 17-19
Section 17. CCP
CCP
17
17.8 Related Application Notes
This section lists application notes that are related to this section of the manual. These application
notes may not be written specifically for the Enhanced family (that is, they may be written for
the Base-Line, the Mid-Range or High-End families), but the concepts are pertinent, and could
be used (with modification and possible limitations). The current application notes related to the
CCP modules are:
Title Application Note #
Using the CCP Modules AN594
Implementing Ultrasonic Ranging AN597
Air Flow Control Using Fuzzy Logic AN600
Adaptive Differential Pulse Code Modulation AN643
Note: Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
http://www.microchip.com/10/faqs/codeex/
39500 18C Reference Manual.book Page 19 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39517A-page 17-20 2000 Microchip Technology Inc.
17.9 Revision History
Revision A
This is the initial released revision of the Enhanced MCU CCP module description.
39500 18C Reference Manual.book Page 20 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39518A-page 18-1
ECCP
18
Section 18. ECCP
Please check the Microchip web site for Revision B of the ECCP Section.
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39518A-page 18-2 2000 Microchip Technology Inc.
18.1 Revision History
Revision A
This is the initial released revision of the Enhanced MCU ECCP module description.
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39519A-page 19-1
SSP
19
Section 19. Synchronous Serial Port (SSP)
HIGHLIGHTS
This section of the manual contains the following major topics:
19.1 Introduction .................................................................................................................. 19-2
19.2 Control Registers ......................................................................................................... 19-4
19.3 SPI Mode ..................................................................................................................... 19-8
19.4 SSP I2C Operation .................................................................................................... 19-18
19.5 Initialization ................................................................................................................ 19-28
19.6 Design Tips ................................................................................................................ 19-30
19.7 Related Application Notes.......................................................................................... 19-31
19.8 Revision History ......................................................................................................... 19-32
I
2C is a trademark of Philips Corporation.
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39519A-page 19-2 2000 Microchip Technology Inc.
19.1 Introduction
The Synchronous Serial Port (SSP) module is a serial interface useful for communicating with
other peripherals or microcontroller devices. These peripheral devices may be serial EEPROMs,
shift registers, display drivers, A/D converters, etc. The SSP module can operate in one of two
modes:
• Serial Peripheral Interface (SPI™)
• Inter-Integrated Circuit (I2C™)
- Slave mode
- I/O slope control, and Start and Stop bit detection to ease software implementation of
Master and Multi-master modes
SPI is a registered trademark of Motorola Corporation.
I
2C is a trademark of Philips Corporation.
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39519A-page 19-3
Section 19. SSP
SSP
19
Section 19.2 forced to next page for formatting purposes.
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39519A-page 19-4 2000 Microchip Technology Inc.
19.2 Control Registers
Register 19-1 shows the SSPSTAT register while Register 19-2 shows the SSPCON register.
Register 19-1: SSPSTAT: Synchronous Serial Port Status Register
R/W-0 R/W-0 R-0 R-0 R-0 R-0 R-0 R-0
SMP CKE D/A P S R/W UA BF
bit 7 bit 0
bit 7 SMP: SPI data input sample phase
SPI Master Mode
1 = Input data sampled at end of data output time
0 = Input data sampled at middle of data output time
SPI Slave Mode
SMP must be cleared when SPI is used in slave mode
I2C Mode
This bit must be maintained clear.
bit 6 CKE: SPI Clock Edge Select (Figure 19-3, Figure 19-4, and Figure 19-5)
SPI Mode
CKP = 0 (SSPCON<4>)
1 = Data transmitted on rising edge of SCK
0 = Data transmitted on falling edge of SCK
CKP = 1 (SSPCON<4>)
1 = Data transmitted on falling edge of SCK
0 = Data transmitted on rising edge of SCK
I
2C Mode
This bit must be maintained clear.
bit 5 D/A: Data/Address bit (I2C mode only)
1 = Indicates that the last byte received or transmitted was data
0 = Indicates that the last byte received or transmitted was address
bit 4 P: Stop bit
(I2C mode only. This bit is cleared when the SSP module is disabled)
1 = Indicates that a stop bit has been detected last (this bit is '0' on RESET)
0 = Stop bit was not detected last
bit 3 S: Start bit
(I2C mode only. This bit is cleared when the SSP module is disabled)
1 = Indicates that a start bit has been detected last (this bit is '0' on RESET)
0 = Start bit was not detected last
bit 2 R/W: Read/Write bit information (I2C mode only)
This bit holds the R/W bit information following the last address match. This bit is only valid from
the address match to the next start bit, stop bit, or not ACK bit.
1 = Read
0 = Write
bit 1 UA: Update Address (10-bit I2C mode only)
1 = Indicates that the user needs to update the address in the SSPADD register
0 = Address does not need to be updated
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39519A-page 19-5
Section 19. SSP
SSP
19
bit 0 BF: Buffer Full Status bit
Receive (SPI and I2C modes)
1 = Receive complete, SSPBUF is full
0 = Receive not complete, SSPBUF is empty
Transmit (I2
C mode only)
1 = Transmit in progress, SSPBUF is full
0 = Transmit complete, SSPBUF is empty
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39519A-page 19-6 2000 Microchip Technology Inc.
Register 19-2: SSPCON: Synchronous Serial Port Control Register
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
WCOL SSPOV SSPEN CKP SSPM3 SSPM2 SSPM1 SSPM0
bit 7 bit 0
bit 7 WCOL: Write Collision Detect bit
1 = The SSPBUF register was written to while the previous word was being transmitted.
(must be cleared in software)
0 = No collision
bit 6 SSPOV: Receive Overflow Indicator bit
In SPI mode:
1 = A new byte was received while the SSPBUF register was still holding the previous data. In
case of overflow, the data in SSPSR is lost and the SSPBUF is no longer updated. Overflow
can only occur in slave mode. The user must read the SSPBUF, even if only transmitting
data, to avoid setting overflow. In master mode the overflow bit is not set since each new
reception (and transmission) is initiated by writing to the SSPBUF register.
0 = No overflow
In I2C mode:
1 = A byte was received while the SSPBUF register was still holding the previous byte. SSPO
is a “don‘t care” in transmit mode. SSPOV must be cleared in software in either mode.
0 = No overflow
bit 5 SSPEN: Synchronous Serial Port Enable bit
In both modes, when enabled, these pins must be properly configured as input or output.
In SPI mode:
1 = Enables serial port and configures SCK, SDO, SDI, and SS as the source of the
serial port pins
0 = Disables serial port and configures these pins as I/O port pins
In I2C mode:
1 = Enables the serial port and configures the SDA and SCL pins as the source of the
serial port pins
0 = Disables serial port and configures these pins as I/O port pins
bit 4 CKP: Clock Polarity Select bit
In SPI mode:
1 = Idle state for clock is a high level
0 = Idle state for clock is a low level
In I2C mode:
SCK release control
1 = Enable clock
0 = Holds clock low (clock stretch) (Used to ensure data setup time)
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39519A-page 19-7
Section 19. SSP
SSP
19
bit 3:0 SSPM3:SSPM0: Synchronous Serial Port Mode Select bits
0000 = SPI master mode, clock = FOSC/4
0001 = SPI master mode, clock = FOSC/16
0010 = SPI master mode, clock = FOSC/64
0011 = SPI master mode, clock = TMR2 output/2
0100 = SPI slave mode, clock = SCK pin. SS pin control enabled.
0101 = SPI slave mode, clock = SCK pin. SS pin control disabled. SS can be used as I/O pin
0110 = I2C slave mode, 7-bit address
0111 = I2C slave mode, 10-bit address
1000 = Reserved
1001 = Reserved
1010 = Reserved
1011 = I2C firmware controlled master mode (slave idle)
1100 = Reserved
1101 = Reserved
1110 = I2C slave mode, 7-bit address with start and stop bit interrupts enabled
1111 = I2C slave mode, 10-bit address with start and stop bit interrupts enabled
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
Microwire is a trademark of National Semiconductor.
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39519A-page 19-8 2000 Microchip Technology Inc.
19.3 SPI Mode
The SPI mode allows 8-bits of data to be synchronously transmitted and received simultaneously.
All four modes of SPI are supported, as well as Microwire™ (sample edge) when the
SPI is in the master mode.
To accomplish communication, typically three pins are used:
• Serial Data Out (SDO)
• Serial Data In (SDI)
• Serial Clock (SCK)
Additionally a fourth pin may be used when in a slave mode of operation:
• Slave Select (SS)
19.3.1 Operation
When initializing the SPI, several options need to be specified. This is done by programming the
appropriate control bits in the SSPCON register (SSPCON<5:0>) and SSPSTAT<7:6>. These
control bits allow the following to be specified:
• Master Mode (SCK is the clock output)
• Slave Mode (SCK is the clock input)
• Clock Polarity (Idle state of SCK)
• Clock edge (output data on rising/falling edge of SCK)
• Data Input Sample Phase
• Clock Rate (Master mode only)
• Slave Select Mode (Slave mode only)
Figure 19-1 shows the block diagram of the SSP module, when in SPI mode.
Figure 19-1: SSP Block Diagram (SPI Mode)
Read Write
Internal
Data Bus
SDI
SDO
SS
SCK
SSPSR reg
SSPBUF reg
SSPM3:SSPM0
bit0 Shift Clock
SS Control
Enable
Edge
Select
Clock Select
TMR2 output
Prescaler TCY
4, 16, 64
TRIS bit of SCK pin
2
Edge
Select
2
4
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39519A-page 19-9
Section 19. SSP
SSP
19
The SSP consists of a transmit/receive Shift Register (SSPSR) and a buffer register (SSPBUF).
The SSPSR shifts the data in and out of the device, MSb first. The SSPBUF holds the data that
was written to the SSPSR, until the received data is ready. Once the 8-bits of data have been
received, that byte is moved to the SSPBUF register. Then the buffer full detect bit, BF
(SSPSTAT<0>), and interrupt flag bit, SSPIF, are set. This double buffering of the received data
(SSPBUF) allows the next byte to start reception before reading the data that was just received.
Any write to the SSPBUF register during transmission/reception of data will be ignored, and the
write collision detect bit, WCOL (SSPCON<7>), will be set. User software must clear the WCOL
bit so that it can be determined if the following write(s) to the SSPBUF register completed successfully.
When the application software is expecting to receive valid data, the SSPBUF should
be read before the next byte of data to transfer is written to the SSPBUF. Buffer full bit, BF
(SSPSTAT<0>), indicates when SSPBUF has been loaded with the received data (transmission
is complete). When the SSPBUF is read, the BF bit is cleared. This data may be irrelevant if the
SPI is only a transmitter. Generally the SSP Interrupt is used to determine when the transmission/reception
has completed. The SSPBUF must be read and/or written. If the interrupt method
is not going to be used, then software polling can be done to ensure that a write collision does
not occur. Example 19-1 shows the loading of the SSPBUF (SSPSR) for data transmission. The
shaded instruction is only required if the received data is meaningful (some SPI applications are
transmit only).
Example 19-1: Loading the SSPBUF (SSPSR) Register
The SSPSR is not directly readable or writable, and can only be accessed from addressing the
SSPBUF register. Additionally, the SSP status register (SSPSTAT) indicates the various status
conditions.
LOOP BTFSS SSPSTAT, BF ;Has data been received
; (transmit complete)?
GOTO LOOP ;No
MOVF SSPBUF, W ;W reg = contents of SSPBUF
MOVWF RXDATA ;Save in user RAM,
; if data is meaningful
MOVFF TXDATA, SSPBUF ;contents of TXDATA
; is the new data to transmit
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39519A-page 19-10 2000 Microchip Technology Inc.
19.3.2 Enabling SPI I/O
To enable the serial port the SSP Enable bit, SSPEN (SSPCON<5>), must be set. To reset or
reconfigure SPI mode, clear the SSPEN bit which re-initializes the SSPCON register, and then
set the SSPEN bit. This configures the SDI, SDO, SCK, and SS pins as serial port pins. For the
pins to behave as the serial port function, they must have their data direction bits (in the TRIS
register) appropriately programmed. That is:
• SDI must have the TRIS bit set
• SDO must have the TRIS bit cleared
• SCK (Master mode) must have the TRIS bit cleared
• SCK (Slave mode) must have the TRIS bit set
• SS must have the TRIS bit set
Any serial port function that is not desired may be overridden by programming the corresponding
data direction (TRIS) register to the opposite value. An example would be in master mode where
you are only sending data (to a display driver), then both SDI and SS could be used as general
purpose outputs by clearing their corresponding TRIS register bits.
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39519A-page 19-11
Section 19. SSP
SSP
19
19.3.3 Typical Connection
Figure 19-2 shows a typical connection between two microcontrollers. The master controller
(Processor 1) initiates the data transfer by sending the SCK signal. Data is shifted out of both
shift registers on their programmed clock edge, and latched on the edge of the clock specified
by the SMP bit. Both processors should be programmed to same Clock Polarity (CKP), so both
controllers would send and receive data at the same time. Whether the data is meaningful (or
dummy data) depends on the application software. This leads to three scenarios for data transmission:
• Master sends data — Slave sends dummy data
• Master sends data — Slave sends data
• Master sends dummy data — Slave sends data
Figure 19-2: SPI Master/Slave Connection
Serial Input Buffer
(SSPBUF)
Shift Register
(SSPSR)
MSb LSb
SDO
SDI
PROCESSOR 1
SCK
SPI Master SSPM3:SSPM0 = 00xxb
Serial Input Buffer
(SSPBUF)
Shift Register
(SSPSR)
MSb LSb
SDI
SDO
PROCESSOR 2
SCK
SPI Slave SSPM3:SSPM0 = 010xb
Serial Clock
39500 18C Reference Manual.book Page 11 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39519A-page 19-12 2000 Microchip Technology Inc.
19.3.4 Master Operation
The master can initiate the data transfer at any time because it controls the SCK. The master
determines when the slave (Processor 2) is to broadcast data by the software protocol.
In master mode the data is transmitted/received as soon as the SSPBUF register is written to. If
the SPI is only going to receive, the SDO output could be disabled (programmed as an input).
The SSPSR register will continue to shift in the signal present on the SDI pin at the programmed
clock rate. As each byte is received, it will be loaded into the SSPBUF register as if a normal
received byte (interrupts and status bits appropriately set). This could be useful in receiver applications
as a “line activity monitor” mode.
The clock polarity is selected by appropriately programming bit CKP (SSPCON<4>). This would
give waveforms for SPI communication as shown in Figure 19-3, Figure 19-4, and Figure 19-5
where the MSb is transmitted first. In master mode, the SPI clock rate (bit rate) is user programmable
to be one of the following:
• FOSC/4 (or TCY)
• FOSC/16 (or 4 • TCY)
• FOSC/64 (or 16 • TCY)
• Timer2 output/2
This allows a maximum data rate of 5 Mbps (at 20 MHz).
Figure 19-3: SPI Mode Waveform, Master Mode
4 clock
modes
Input
Sample (SMP = 0)
Input
Sample (SMP = 1)
SDI (SMP = 0)
bit7 bit0
SDO (CKE = 0) bit7 bit6 bit5 bit4 bit3 bit2 bit1 bit0
bit7 bit0
SDI (SMP = 1)
SSPIF
Write to
SSPBUF
SSPSR to
SSPBUF
SDO (CKE = 1) bit7 bit6 bit5 bit4 bit3 bit2 bit1 bit0
SCK (CKP = 0,
CKE = 0)
SCK (CKP = 0,
CKE = 1)
SCK (CKP = 1,
CKE = 0)
SCK (CKP = 1,
CKE = 1)
Next Q4 cycle
after Q2 ↓
39500 18C Reference Manual.book Page 12 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39519A-page 19-13
Section 19. SSP
SSP
19
19.3.5 Slave Operation
In slave mode, the data is transmitted and received as the external clock pulses appear on SCK.
When the last bit is latched, the interrupt flag bit SSPIF is set.
The clock polarity is selected by appropriately programming bit CKP (SSPCON). This then would
give waveforms for SPI communication as shown in Figure 19-3, Figure 19-4, and Figure 19-5
where the MSb is transmitted first. When in slave mode the external clock must meet the minimum
high and low times.
In sleep mode, the slave can transmit and receive data. When a byte is received, the device will
wake-up from sleep, if the interrupt is enabled.
Figure 19-4: SPI Mode Waveform (Slave Mode With CKE = 0)
SCK (CKP = 1,
SCK (CKP = 0,
Input
Sample (SMP = 0)
SDI
bit7 bit0
SDO bit6 bit5 bit4 bit3 bit2 bit1 bit0
SSPIF
CKE = 0)
CKE = 0)
(SMP = 0)
Write to
SSPBUF
SSPSR to
SSPBUF
SS
optional
Next Q4 Cycle
after Q2↓
bit7
39500 18C Reference Manual.book Page 13 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39519A-page 19-14 2000 Microchip Technology Inc.
19.3.6 Slave Select Mode
When in slave select mode, the SS pin allows multi-drop for multiple slaves with a single
master. The SPI must be in slave mode (SSPCON<3:0> = 04h) and the TRIS bit, for the
SS pin, must be set for the slave select mode to be enabled. When the SS pin is low, transmission
and reception are enabled and the SDO pin is driven. When the SS pin goes high,
the SDO pin is no longer driven, even if in the middle of a transmitted byte, and becomes
a floating output. External pull-up/ pull-down resistors may be desirable, depending on the
application.
When the SPI is in Slave Mode with SS pin control enabled, (SSPCON<3:0> = 0100) the SPI
module will reset if the SS pin is set to VDD. If the SPI is used in Slave Mode with the CKE bit is
set, then the SS pin control must be enabled.
When the SPI module resets, the bit counter is forced to 0. This can be done by either by forcing
the SS pin to a high level or clearing the SSPEN bit (Figure 19-6).
To emulate two-wire communication, the SDO pin can be connected to the SDI pin. When the
SPI needs to operate as a receiver the SDO pin can be configured as an input. This disables
transmissions from the SDO. The SDI can always be left as an input (SDI function) since it cannot
create a bus conflict.
Figure 19-5: SPI Mode Waveform (Slave Select Mode With CKE = 1)
SCK
(CKP = 1
SCK
(CKP = 0
Input
Sample
SDI
bit7 bit0
SDO bit7 bit6 bit5 bit4 bit3 bit2 bit1 bit0
SSPIF
Interrupt
(SMP = 0)
CKE = 1)
CKE = 1)
(SMP = 0)
Write to
SSPBUF
SSPSR to
SSPBUF
SS
Flag
(required)
Next Q4 cycle
after Q2↓
39500 18C Reference Manual.book Page 14 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39519A-page 19-15
Section 19. SSP
SSP
19
Figure 19-6: Slave Synchronization Waveform
SCK
(CKP = 1
SCK
(CKP = 0
Input
Sample
SDI
bit7
SDO bit7 bit6 bit7
SSPIF
Interrupt
(SMP = 0)
CKE = 0)
CKE = 0)
(SMP = 0)
Write to
SSPBUF
SSPSR to
SSPBUF
SS
Flag
bit0
bit7
bit0
(Required)
39500 18C Reference Manual.book Page 15 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39519A-page 19-16 2000 Microchip Technology Inc.
19.3.7 Sleep Operation
In master mode all module clocks are halted, and the transmission/reception will remain in that
state until the device wakes from sleep. After the device returns to normal mode, the module will
continue to transmit/receive data.
In slave mode, the SPI transmit/receive shift register operates asynchronously to the device. This
allows the device to be placed in sleep mode, and data to be shifted into the SPI transmit/receive
shift register. When all 8-bits have been received, the SSP interrupt flag bit will be set and if
enabled will wake the device from sleep.
39500 18C Reference Manual.book Page 16 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39519A-page 19-17
Section 19. SSP
SSP
19
19.3.8 Effects of a Reset
A reset disables the SSP module and terminates the current transfer.
Table 19-1: Registers Associated with SPI Operation
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Value on
POR,
BOR
Value on all
other resets
INTCON GIE/
GIEH
PEIE/
GIEL
TMR0IE INT0IE RBIE TMR0IF INT0IF RBIF 0000 000x 0000 000u
PIR SSPIF (1) 0 0
IPR SSPIP (1) 0 0
SSPBUF Synchronous Serial Port Receive Buffer/Transmit Register xxxx xxxx uuuu uuuu
SSPCON WCOL SSPOV SSPEN CKP SSPM3 SSPM2 SSPM1 SSPM0 0000 0000 0000 0000
TRISA — — PORTA Data Direction Register --11 1111 --11 1111
TRISC PORTC Data Direction Control Register 1111 1111 1111 1111
SSPSTAT SMP CKE D/A P S R/W UA BF 0000 0000 0000 0000
Legend: x = unknown, u = unchanged, - = unimplemented read as '0'. Shaded cells are not used by the SSP in SPI
mode.
Note 1: The position of this bit is device dependent.
39500 18C Reference Manual.book Page 17 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39519A-page 19-18 2000 Microchip Technology Inc.
19.4 SSP I2C Operation
The SSP module in I2C mode fully implements all slave functions, except general call support,
and provides interrupts on start and stop bits in hardware to facilitate software implementations
of the master functions. The SSP module implements the standard mode specifications as well
as 7-bit and 10-bit addressing. The "Appendix" section gives an overview of the I2C bus specification.
Two pins are used for data transfer. These are the SCL pin, which is the clock, and the SDA pin,
which is the data. The user must configure these pins as inputs through the TRIS bits. The SSP
module functions are enabled by setting SSP Enable bit, SSPEN (SSPCON).
A “glitch” filter is on the SCL and SDA pins when the pin is an input. This filter operates in both
the 100 KHz and 400 KHz modes. In the 100 KHz mode, when these pins are an output, there
is a slew rate control of the pin that is independent of device frequency.
Figure 19-7: SSP Block Diagram (I2C Mode)
Read Write
SSPSR reg
Match detect
SSPADD reg
Start and
Stop bit detect
SSPBUF reg
Internal
Data Bus
Address Match
Set, Reset
S, P bits
(SSPSTAT reg)
SCL
shift
clock
SDA MSb LSb
39500 18C Reference Manual.book Page 18 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39519A-page 19-19
Section 19. SSP
SSP
19
The SSP module has five registers for I2C operation. They are:
• SSP Control Register (SSPCON)
• SSP Status Register (SSPSTAT)
• Serial Receive/Transmit Buffer (SSPBUF)
• SSP Shift Register (SSPSR) - Not directly accessible
• SSP Address Register (SSPADD)
The SSPCON register allows control of the I2C operation. Four mode selection bits
(SSPCON<3:0>) allow one of the following I2C modes to be selected:
• I2C Slave mode (7-bit address)
• I2C Slave mode (10-bit address)
• I2C Firmware controlled Multi-Master mode (start and stop bit interrupts enabled)
• I2C Firmware controlled Multi-Master mode (start and stop bit interrupts enabled)
• I2C Firmware controlled Master mode, slave is idle
Before selecting any I2C mode, the SCL and SDA pins must be programmed to inputs by setting
the appropriate TRIS bits. Selecting an I2C mode by setting the SSPEN bit enables the SCL and
SDA pins to be used as the clock and data lines in I2C mode.
The SSPSTAT register gives the status of the data transfer. This information includes detection
of a START or STOP bit, specifies if the received byte was data or address, if the next byte is the
completion of 10-bit address, and if this will be a read or write data transfer.
The SSPBUF is the register to which transfer data is written to or read from. The SSPSR register
shifts the data in or out of the device. In receive operations, the SSPBUF and SSPSR create a
doubled buffered receiver. This allows reception of the next byte to begin before reading the last
byte of received data. When the complete byte is received, it is transferred to the SSPBUF register
and flag bit SSPIF is set. If another complete byte is received before the SSPBUF register
is read, a receiver overflow has occurred and the SSPOV bit (SSPCON<6>) is set and the byte
in the SSPSR is lost.
The SSPADD register holds the slave address. In 10-bit mode, the user needs to write the high
byte of the address (1111 0 A9 A8 0). Following the high byte address match, the low byte of
the address needs to be loaded (A7:A0).
39500 18C Reference Manual.book Page 19 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39519A-page 19-20 2000 Microchip Technology Inc.
19.4.1 Slave Mode
In slave mode, the SCL and SDA pins must be configured as inputs (TRIS set). The SSP module
will override the input state with the output data when required (slave-transmitter).
When an address is matched or the data transfer after an address match is received, the hardware
automatically will generate the acknowledge (ACK) pulse, and then load the SSPBUF register
with the received value currently in the SSPSR register.
There are certain conditions that will cause the SSP module not to give this ACK pulse. These
are if either (or both):
a) The buffer full bit, BF (SSPSTAT<0>), was set before the message completed.
b) The overflow bit, SSPOV (SSPCON<6>), was set before the message completed.
In this case, the SSPSR register value is not loaded into the SSPBUF, but the SSPIF and SSPOV
bits are set. Table 19-2 shows what happens when a data transfer byte is received, given the status
of bits BF and SSPOV. The shaded cells show the condition where user software did not properly
clear the overflow condition. The BF flag bit is cleared by reading the SSPBUF register while
bit SSPOV is cleared through software.
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 requirement of the SSP module is shown in the
Device Data Sheet electrical specifications parameters 100 and 101.
39500 18C Reference Manual.book Page 20 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39519A-page 19-21
Section 19. SSP
SSP
19
19.4.1.1 Addressing
Once the SSP module has been enabled, it waits for a START condition to occur. Following the
START condition, the 8-bits are shifted into the SSPSR register. All incoming bits are sampled
with the rising edge of the clock (SCL) line. The value of register SSPSR<7:1> is compared to
the value of the SSPADD register. The address is compared on the falling edge of the eighth
clock (SCL) pulse. If the addresses match, and the BF and SSPOV bits are clear, the following
events occur:
a) The SSPSR register value is loaded into the SSPBUF register on the falling edge of the
eighth SCL pulse.
b) The buffer full bit, BF, is set on the falling edge of the eighth SCL pulse.
c) An ACK pulse is generated.
d) The SSP interrupt flag bit, SSPIF, is set (and an interrupt is generated if enabled) - on the
falling edge of the ninth SCL pulse.
In 10-bit address mode, two address bytes need to be received by the slave. The five Most
Significant bits (MSbs) of the first address byte specify if this is a 10-bit address. The R/W bit
(SSPSTAT) must specify a write so the slave device will receive the second address byte. For a
10-bit address the first byte would equal ‘1111 0 A9 A8 0’, where A9 and A8 are the two MSbs
of the address. The sequence of events for a 10-bit address is as follows, with steps 7- 9 for
slave-transmitter:
1. Receive first (high) byte of Address (the SSPIF, BF, and UA (SSPSTAT) bits are set).
2. Update the SSPADD register with second (low) byte of Address (clears the UA bit and
releases the SCL line).
3. Read the SSPBUF register (clears the BF bit) and clear the SSPIF flag bit.
4. Receive second (low) byte of Address (the SSPIF, BF, and UA bits are set).
5. Update the SSPADD register with the high byte of Address. This will clear the UA bit and
releases SCL line.
6. Read the SSPBUF register (clears the BF bit) and clear the SSPIF flag bit.
7. Receive repeated START condition.
8. Receive first (high) byte of Address (the SSPIF and BF bits are set).
9. Read the SSPBUF register (clears the BF bit) and clear the SSPIF flag bit.
Table 19-2: Data Transfer Received Byte Actions
Note: Following the RESTART condition (step 7) in 10-bit mode, the user only needs to
match the first 7-bit address. The user does not update the SSPADD for the second
half of the address.
Status Bits as Data
Transfer is Received
SSPSR → SSPBUF
Generate ACK
Pulse
Set bit SSPIF
(SSP Interrupt occurs
BF SSPOV if enabled)
0 0 Yes Yes Yes
1 0 No No Yes
1 1 No No Yes
0 1 Yes No Yes
Note:Shaded cells show the conditions where the user software did not properly clear the
overflow condition.
39500 18C Reference Manual.book Page 21 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39519A-page 19-22 2000 Microchip Technology Inc.
19.4.1.2 Reception
When the R/W bit of the address byte is clear and an address match occurs, the R/W bit of the
SSPSTAT register is cleared. The received address is loaded into the SSPBUF register.
When the address byte overflow condition exists, then no acknowledge (ACK) pulse is given. An
overflow condition is defined as either the BF bit (SSPSTAT) is set or the SSPOV bit (SSPCON)
is set. When a byte is received with these conditions, and attempts to move from the SSPSR register
to the SSPBUF register, no acknowledge pulse is given.
An SSP interrupt is generated for each data transfer byte. The SSPIF flag bit must be cleared in
software. The SSPSTAT register is used to determine the status of the receive byte.
Figure 19-8: I
2
C Waveforms for Reception (7-bit Address)
5 76 8 9 P
D6D7 D5 D3D4 D2 D1 D0
S
A7 A6 A5 A4 A3 A2 A1SDA
SCL 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 23 4
Bus Master
terminates
transfer
Bit SSPOV is set because the SSPBUF register is still full.
Cleared in software
SSPBUF register is read
Receiving Data ACK Receiving Data
D6D7 D5 D3D4 D2 D1 D0 ACK
Receiving Address R/W=0
SSPIF
BF (SSPSTAT<0>)
SSPOV (SSPCON<6>)
ACK
ACK is not sent.
39500 18C Reference Manual.book Page 22 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39519A-page 19-23
Section 19. SSP
SSP
19
Figure 19-9: I
2
C Waveforms for Reception (10-bit Address) SDA SCL SSPIF BF (SSPSTAT<0>) S 1 2 34 56 7 8 9 1 234 5 67 89 1 2345 7 89 P 1 1 1 1 0 A9 A8 A7 A6 A5 A4 A3 A2 A1 A0 D7 D6 D5 D4 D3 D1 D0 Receive Data Byte ACK R/W = 0ACK Receive First Byte of Address Cleared in software
Bus Master
terminates
transfer
D2
6
(PIR1<3>)
Receive Second Byte of Address
Cleared by hardware when
SSPADD is updated.
UA (SSPSTAT<1>)
Clock is held low until
update of SSPADD has
taken place
UA is set indicating that
the SSPADD needs to be
updated
UA is set indicating that
SSPADD needs to be
updated
SSPBUF is written with
contents of SSPSR
Dummy read of SSPBUF
to clear BF flag
ACK
R/W = 1
Cleared in software
Dummy read of SSPBUF
to clear BF flag
Read of SSPBUF
clears BF flag
Cleared by hardware when
SSPADD is updated.
39500 18C Reference Manual.book Page 23 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39519A-page 19-24 2000 Microchip Technology Inc.
19.4.1.3 Transmission
When the R/W bit of the incoming address byte is set and an address match occurs, the R/W bit
of the SSPSTAT register is set. The received address is loaded into the SSPBUF register. The
ACK pulse will be sent on the ninth bit, and the SCL pin is held low. The transmit data must be
loaded into the SSPBUF register, which also loads the SSPSR register. Then the SCL pin should
be enabled by setting the CKP bit (SSPCON<4>). The master must monitor the SCL pin prior to
asserting another clock pulse. The slave devices may be holding off the master by stretching the
clock. The eight data bits are shifted out on the falling edge of the SCL input. This ensures that
the SDA signal is valid during the SCL high time (Figure 19-10).
An SSP interrupt is generated for each data transfer byte. The SSPIF flag bit must be cleared in
software, and the SSPSTAT register is used to determine the status of the byte transfer. The
SSPIF flag bit is set on the falling edge of the ninth clock pulse.
As a slave-transmitter, the ACK pulse from the master-receiver is latched on the rising edge of
the ninth SCL input pulse. If the SDA line was high (not ACK), then the data transfer is complete.
When the not ACK is latched by the slave, the slave logic is reset and the slave then monitors
for another occurrence of the START bit. If the SDA line was low (ACK), the transmit data must
be loaded into the SSPBUF register, which also loads the SSPSR register. Then the SCL pin
should be enabled by setting the CKP bit.
Figure 19-10: I
2C Waveforms for Transmission (7-bit Address)
SDA
SCL
SSPIF
BF (SSPSTAT<0>)
CKP (SSPCON<4>)
A7 A6 A5 A4 A3 A2 A1 ACK D7 D6 D5 D4 D3 D2 D1 D0
Receiving Address R/W = 1 Transmitting Data ACK
123456789 1234 56789 P
cleared in software
SSPBUF is written in software From SSP interrupt
service routine
Set bit after writing to SSPBUF
S Data in
sampled
SCL held low
while CPU responds to SSPIF
(the SSPBUF must be written-to
before the CKP bit can be set)
R/W = 0
39500 18C Reference Manual.book Page 24 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39519A-page 19-25
Section 19. SSP
SSP
19
Figure 19-11: I
2
C Waveforms for Transmission (10-bit Address) SDA SCL SSPIF BF (SSPSTAT<0>) S 1 234 56 7 8 9 1 234 5 67 89 1 2345 7 89 P 1 1 1 1 0 A9 A8 A7 A6 A5 A4 A3 A2 A1 A0 1 1 1 1 0 A8R/W=1 ACK ACK R/W = 0ACK Receive First Byte of Address Cleared in software
Master sends NACK
A9
6
(PIR1<3>)
Receive Second Byte of Address
Cleared by hardware when
SSPADD is updated.
UA (SSPSTAT<1>)
Clock is held low until
update of SSPADD has
taken place
UA is set indicating that
the SSPADD needs to be
updated
UA is set indicating that
SSPADD needs to be
updated
Cleared by hardware when
SSPADD is updated.
SSPBUF is written with
contents of SSPSR
Dummy read of SSPBUF
to clear BF flag
Receive First Byte of Address
D7 D6 D5 D4 D3 D1
12345 789
ACK
D2
6
Transmitting Data Byte
D0
Dummy read of SSPBUF
to clear BF flag
Sr
Cleared in software
Write of SSPBUF
initiates transmit
Cleared in software
Transmit is complete
CKP has to be set for clock to be released
Bus Master
terminates
transfer
39500 18C Reference Manual.book Page 25 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39519A-page 19-26 2000 Microchip Technology Inc.
19.4.1.4 Clock Arbitration
Clock arbitration has the SCL pin to inhibit the master device from sending the next clock pulse.
The SSP module in I2C slave mode will hold the SCL pin low when the CPU needs to respond
to the SSP interrupt (SSPIF bit is set and the CKP bit is cleared). The data that needs to be transmitted
will need to be written to the SSPBUF register, and then the CKP bit will need to be set to
allow the master to generate the required clocks.
19.4.2 Master Mode (Firmware)
Master mode of operation is supported by interrupt generation on the detection of the START and
STOP conditions. The STOP (P) and START (S) bits are cleared from a reset or when the SSP
module is disabled. Control of the I2C bus may be taken when the P bit is set, or the bus is idle
with both the S and P bits clear.
In master mode the SCL and SDA lines are manipulated by clearing the corresponding TRIS
bit(s). The output level is always low, irrespective of the value(s) in the PORT register. So when
transmitting data, a '1' data bit must have it’s TRIS bit set (input) and a '0' data bit must have it’s
TRIS bit cleared (output). The same scenario is true for the SCL line with the TRIS bit.
The following events will cause SSP Interrupt Flag bit, SSPIF, to be set (SSP Interrupt if enabled):
• START condition
• STOP condition
• Data transfer byte transmitted/received
Master mode of operation can be done with either the slave mode idle (SSPM3:SSPM0 = 1011)
or with the slave active (SSPM3:SSP0 = 1110 or 1111). When the slave modes are enabled, the
software needs to differentiate the source(s) of the interrupt.
19.4.3 Multi-Master Mode (Firmware)
In multi-Master mode, the interrupt generation on the detection of the START and STOP conditions
allows the determination of when the bus is free. The STOP (P) and START (S) bits are
cleared from a reset or when the SSP module is disabled. Control of the I2C bus may be taken
when the P bit (SSPSTAT<4>) is set, or the bus is idle with both the S and P bits clear. When the
bus is busy, enabling the SSP Interrupt will generate the interrupt when the STOP condition
occurs.
In Multi-Master operation, the SDA line must be monitored to see if the signal level is the
expected output level. This check only needs to be done when a high level is output. If a high
level is expected and a low level is present, the device needs to release the SDA and SCL lines
(set the TRIS bits). There are two stages where this arbitration can be lost, they are:
• Address transfer
• Data transfer
When the slave logic is enabled, the slave continues to receive. If arbitration was lost during the
address transfer stage, communication to the device may be in progress. If addressed an ACK
pulse will be generated. If arbitration was lost during the data transfer stage, the device will need
to retransfer the data at a later time.
39500 18C Reference Manual.book Page 26 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39519A-page 19-27
Section 19. SSP
SSP
19
19.4.4 Sleep Operation
While in sleep mode, the I2C module can receive addresses or data, and when an address match
or complete byte transfer occurs wake the processor from sleep (if the SSP interrupt is enabled).
19.4.5 Effect of a Reset
A reset disables the SSP module and terminates the current transfer.
Table 19-3: Registers Associated with I
2C Operation
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Value on
POR,
BOR
Value on all
other resets
INTCON GIE/
GIEH
PEIE/
GIEL
TMR0IE INT0IE RBIE TMR0IF INT0IF RBIF 0000 000x 0000 000u
PIR SSPIF (1) 0 0
IPR SSPIP (1) 0 0
SSPBUF Synchronous Serial Port Receive Buffer/Transmit Register xxxx xxxx uuuu uuuu
SSPADD Synchronous Serial Port (I2C mode) Address Register 0000 0000 0000 0000
SSPCON WCOL SSPOV SSPEN CKP SSPM3 SSPM2 SSPM1 SSPM0 0000 0000 0000 0000
SSPSTAT SMP CKE D/A P S R/W UA BF 0000 0000 0000 0000
Legend: x = unknown, u = unchanged, - = unimplemented read as '0'.
Shaded cells are not used by SSP in I2C mode.
Note 1: The positions of these bits are device dependent.
39500 18C Reference Manual.book Page 27 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39519A-page 19-28 2000 Microchip Technology Inc.
19.5 Initialization
Example 19-2: SPI Master Mode Initialization
CLRF SSPSTAT ; SMP = 0, CKE = 0, and clear status bits
BSF SSPSTAT, CKE ; CKE = 1
MOVLW 0x31 ; Set up SPI port, Master mode, CLK/16,
MOVWF SSPCON ; Data xmit on falling edge (CKE=1 & CKP=1)
; Data sampled in middle (SMP=0 & Master mode)
BSF PIE, SSPIE ; Enable SSP interrupt
BSF INTCON, GIE ; Enable, enabled interrupts
MOVLW DataByte ; Data to be Transmitted
; Could move data from RAM location
MOVWF SSPBUF ; Start Transmission
39500 18C Reference Manual.book Page 28 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39519A-page 19-29
Section 19. SSP
SSP
19
19.5.1 SSP Module / Basic SSP Module Compatibility
When upgrading from the Mid-Range family’s basic SSP module, the SSPSTAT register contains
two additional control bits. These bits are used only in SPI mode and are:
• SMP, SPI data input sample phase
• CKE, SPI Clock Edge Select
To be compatible with the SPI of the basic SSP module, these bits must be appropriately configured.
If these bits are not at the states shown in Table 19-4, improper SPI communication may
occur.
Table 19-4: New Bit States for Compatibility
Mid-Range Family’s
Basic SSP Module SSP Module
CKP CKP CKE SMP
1 100
0 000
39500 18C Reference Manual.book Page 29 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39519A-page 19-30 2000 Microchip Technology Inc.
19.6 Design Tips
Question 1: Using SPI mode, I do not seem able to talk to an SPI device.
Answer 1:
Ensure that you are using the correct SPI mode for that device. This SPI supports all four SPI
modes so you should be able to get it to function. Check the clock polarity and the clock phase.
These settings should match what the SPI is interfacing to.
Question 2: Using I2C mode, I do not seem able to make the master mode work.
Answer 2:
This SSP module does not have master mode fully automated in hardware, see Application Note
AN578 for software which uses the SSP module to implement master mode. If you require a fully
automated hardware implementation of I2C Master Mode, please refer to the Microchip Line Card
for devices that have the Master SSP module.
Question 3: Using I2C mode, I write data to the SSPBUF register, but the data did not
transmit.
Answer 3:
Ensure that you set the CKP bit to release the I2C clock.
39500 18C Reference Manual.book Page 30 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39519A-page 19-31
Section 19. SSP
SSP
19
19.7 Related Application Notes
This section lists application notes that are related to this section of the manual. These application
notes may not be written specifically for the Enhanced MCU family (that is they may be written
for the Base-Line, Mid-Range or High-End families), but the concepts are pertinent, and could
be used (with modification and possible limitations). The current application notes related to the
SSP Module are:
Title Application Note #
Use of the SSP Module in the I 2C Multi-Master Environment. AN578
Using Microchip 93 Series Serial EEPROMs with Microcontroller SPI Ports AN613
Software Implementation of I2C Bus Master AN554
Use of the SSP module in the Multi-master Environment AN578
Interfacing PIC16C64/74 to Microchip SPI Serial EEPROM AN647
Interfacing a Microchip PIC16C92x to Microchip SPI Serial EEPROM AN668
Note: Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
http://www.microchip.com/10/faqs/codeex/
39500 18C Reference Manual.book Page 31 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39519A-page 19-32 2000 Microchip Technology Inc.
19.8 Revision History
Revision A
This is the initial released revision of the SSP module description.
39500 18C Reference Manual.book Page 32 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39520A-page 20-1
Master SSP
20
Section 20. Master SSP
HIGHLIGHTS
This section of the manual contains the following major topics:
20.1 Introduction .................................................................................................................. 20-2
20.2 Control Registers ......................................................................................................... 20-4
20.3 SPI Mode ..................................................................................................................... 20-9
20.4 MSSP I2C Operation ................................................................................................. 20-17
20.5 Design Tips ................................................................................................................ 20-55
20.6 Related Application Notes.......................................................................................... 20-56
20.7 Revision History ......................................................................................................... 20-57
I
2C is a trademark of Philips
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39520A-page 20-2 2000 Microchip Technology Inc.
20.1 Introduction
The Master Synchronous Serial Port (MSSP) module is a 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 MSSP module can operate
in one of two modes:
• Serial Peripheral Interface (SPI)
• Inter-Integrated Circuit (I2C)
- Full Master Mode
- Slave Mode (with general address call)
The I2C interface supports the following modes in hardware:
• Master Mode
• Multi-Master Mode
• Slave Mode
Figure 20-1 shows a block diagram for the SPI Mode, while Figure 20-2 and Figure 20-3 show
the block diagrams for the two different I2C Modes of operation.
Figure 20-1: SPI Mode Block Diagram
Read Write
Internal
Data Bus
SSPSR Reg
SSPBUF Reg
SSPM3:SSPM0
bit0 Shift Clock
SS Control
Enable
Edge
Select
Clock Select
TMR2 Output
Prescaler TOSC
4, 16, 64
2
Edge
Select
2
4
Data to TX/RX in SSPSR
TRIS Bit
2
SMP:CKE
SDI
SDO
SS
SCK
( )
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39520A-page 20-3
Section 20. Master SSP
Master SSP
20
Figure 20-2: I2C Slave Mode Block Diagram
Figure 20-3: I2C Master Mode Block Diagram
Read Write
SSPSR Reg
Match Detect
SSPADD Reg
Start and
Stop Bit Detect
SSPBUF Reg
Internal
Data Bus
Address Match or
Set, Reset
S, P Bits
(SSPSTAT Reg)
SCL
Shift
Clock
SDA MSb LSb
General Call Detected
Read Write
SSPSR
Start Bit, Stop Bit,
SSPBUF
Internal
Data Bus
Set/Reset, S, P, WCOL (SSPSTAT)
Shift
Clock
MSb LSb
SDA
Acknowledge
Generate
SCL
SCL in
Bus Collision
SDA in Receive Enable
Clock Cntl
Clock Arbitrate/WCOL Detect
(Hold Off Clock Source)
SSPADD<6:0>
Baud
Set SSPIF, BCLIF
Reset ACKSTAT, PEN (SSPCON2)
Rate
Generator
SSPM3:SSPM0
Start Bit Detect
Stop Bit Detect
Write Collision Detect
Clock Arbitration
State Counter for
End of XMIT/RCV
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39520A-page 20-4 2000 Microchip Technology Inc.
20.2 Control Registers
The Master SSP (MSSP) module has three registers that control the operation and indicate the
status of the module. These are the SSPSTAT register (Register 20-1), the SSPCON1register
(Register 20-2), and the SSPCON2 register (Register 20-3).
Register 20-1: SSPSTAT: MSSP Status Register
R/W-0 R/W-0 R-0 R-0 R-0 R-0 R-0 R-0
SMP CKE D/A P S R/W UA BF
bit 7 bit 0
bit 7 SMP: Sample bit
SPI Master Mode
1 = Input data sampled at end of data output time
0 = Input data sampled at middle of data output time
SPI Slave Mode
SMP must be cleared when SPI is used in Slave Mode
In I2C Master or Slave Mode:
1= Slew rate control disabled for standard speed mode (100 kHz and 1 MHz)
0= Slew rate control enabled for high speed mode (400 kHz)
bit 6 CKE: SPI Clock Edge Select
CKP = 0
1 = Data transmitted on rising edge of SCK
0 = Data transmitted on falling edge of SCK
CKP = 1
1 = Data transmitted on falling edge of SCK
0 = Data transmitted on rising edge of SCK
bit 5 D/A: Data/Address bit (I2C Mode only)
1 = Indicates that the last byte received or transmitted was data
0 = Indicates that the last byte received or transmitted was address
bit 4 P: Stop bit
(I2C Mode only. This bit is cleared when the MSSP module is disabled, SSPEN is cleared)
1 = Indicates that a Stop bit has been detected last (this bit is '0' on RESET)
0 = Stop bit was not detected last
bit 3 S: Start bit
(I2C Mode only. This bit is cleared when the MSSP module is disabled, SSPEN is cleared)
1 = Indicates that a Start bit has been detected last (this bit is '0' on RESET)
0 = Start bit was not detected last
bit 2 R/W: Read/Write bit information (I2C Mode only)
This bit holds the R/W bit information following the last address match. This bit is only valid from
the address match to the next Start bit, Stop bit, or not ACK bit.
In I
2C Slave Mode:
1 = Read
0 = Write
In I
2C Master Mode:
1 = Transmit is in progress
0 = Transmit is not in progress.
Or’ing this bit with SEN, RSEN, PEN, RCEN, or ACKEN will indicate if the MSSP is
in idle Mode.
bit 1 UA: Update Address (10-bit I2C mode only)
1 = Indicates that the user needs to update the address in the SSPADD Register
0 = Address does not need to be updated
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39520A-page 20-5
Section 20. Master SSP
Master SSP
20
bit 0 BF: Buffer Full Status bit
Receive (SPI and I
2C Modes)
1 = Receive complete, SSPBUF is full
0 = Receive not complete, SSPBUF is empty
Transmit (I
2C Mode only)
1 = Data transmit in progress (does not include the ACK and Stop bits), SSPBUF is full
0 = Data transmit complete (does not include the ACK and Stop bits), SSPBUF is empty
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleard x = bit is unknown
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39520A-page 20-6 2000 Microchip Technology Inc.
Register 20-2: SSPCON1: MSSP Control Register1
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
WCOL SSPOV SSPEN CKP SSPM3 SSPM2 SSPM1 SSPM0
bit 7 bit 0
bit 7 WCOL: Write Collision Detect bit
Master Mode:
1 = A write to the SSPBUF Register was attempted while the I2C conditions were not valid for a
transmission to be started
0 = No collision
Slave Mode:
1 = The SSPBUF Register is written while it is still transmitting the previous word
(must be cleared in software)
0 = No collision
bit 6 SSPOV: Receive Overflow Indicator bit
In SPI Mode:
1 = A new byte is received while the SSPBUF Register is still holding the previous data. In case
of overflow, the data in SSPSR is lost. Overflow can only occur in Slave Mode. In Slave
Mode, the user must read the SSPBUF, even if only transmitting data, to avoid setting overflow.
In Master Mode the overflow bit is not set since each new reception (and transmission)
is initiated by writing to the SSPBUF Register. (Must be cleared in software)
0 = No overflow
In I2C Mode:
1 = A byte is received while the SSPBUF Register is still holding the previous byte. SSPOV is
a "don’t care" in transmit mode. (Must be cleared in software)
0 = No overflow
bit 5 SSPEN: Synchronous Serial Port Enable bit
In both modes, when enabled, the I/O pins must be properly configured as input or output.
In SPI Mode:
1 = Enables serial port and configures SCK, SDO, SDI, and SS as the source of the serial
port pins
0 = Disables serial port and configures these pins as I/O port pins
In I
2C Mode:
1 = Enables the serial port and configures the SDA and SCL pins as the source of the
serial port pins
0 = Disables serial port and configures these pins as I/O port pins
bit 4 CKP: Clock Polarity Select bit
In SPI Mode:
1 = Idle state for clock is a high level
0 = Idle state for clock is a low level
In I
2C Slave Mode:
SCK release control
1 = Enable clock
0 = Holds clock low (clock stretch) (Used to ensure data setup time)
In I
2C Master Mode
Unused in this mode
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39520A-page 20-7
Section 20. Master SSP
Master SSP
20
bit 3 - 0 SSPM3:SSPM0: Synchronous Serial Port Mode Select bits
0000 = SPI Master Mode, clock = FOSC/4
0001 = SPI Master Mode, clock = FOSC/16
0010 = SPI Master Mode, clock = FOSC/64
0011 = SPI Master Mode, clock = TMR2 output/2
0100 = SPI Slave Mode, clock = SCK pin. SS pin control enabled.
0101 = SPI Slave Mode, clock = SCK pin. SS pin control disabled. SS can be used as I/O pin
0110 = I2C Slave Mode, 7-bit address
0111 = I2C Slave Mode, 10-bit address
1000 = I2C Master Mode, clock = FOSC / (4 * (SSPADD+1) )
1001 = Reserved
1010 = Reserved
1011 = I2C firmware controlled master mode (Slave idle)
1100 = Reserved
1101 = Reserved
1110 = I2C Slave Mode, 7-bit address with Start and Stop bit interrupts enabled
1111 = I2C Slave Mode, 10-bit address with Start and Stop bit interrupts enabled
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleard x = bit is unknown
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39520A-page 20-8 2000 Microchip Technology Inc.
Register 20-3: SSPCON2: MSSP Control Register2
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
GCEN ACKSTAT ACKDT ACKEN RCEN PEN RSEN SEN
bit 7 bit 0
bit 7 GCEN: General Call Enable bit (In I2C Slave Mode only)
1 = Enable interrupt when a general call address (0000h) is received in the SSPSR
0 = General call address disabled
bit 6 ACKSTAT: Acknowledge Status bit (In I2C Master Mode only)
In Master Transmit Mode:
1 = Acknowledge was not received from slave
0 = Acknowledge was received from slave
bit 5 ACKDT: Acknowledge Data bit (In I2C Master Mode only)
In Master Receive Mode:
Value that will be transmitted when the user initiates an Acknowledge sequence at the end of a
receive.
1 = Not Acknowledge
0 = Acknowledge
bit 4 ACKEN: Acknowledge Sequence Enable bit (In I2C Master Mode only)
In Master Receive Mode:
1 = Initiate Acknowledge sequence on SDA and SCL pins, and transmit ACKDT data bit.
Automatically cleared by hardware.
0 = Acknowledge sequence idle
bit 3 RCEN: Receive Enable bit (In I2C Master Mode only)
1 = Enables Receive mode for I2C
0 = Receive idle
bit 2 PEN: Stop condition enable bit (In I2C Master Mode only)
SCK release control
1 = Initiate Stop condition on SDA and SCL pins. Automatically cleared by hardware.
0 = Stop condition idle
bit 1 RSEN: Repeated Start condition enabled bit (In I2C Master Mode only)
1 = Initiate Repeated Start condition on SDA and SCL pins. Automatically cleared by hardware.
0 = Repeated Start condition idle.
bit 0 SEN: Start condition enabled bit (In I2C Master Mode only)
1 = Initiate Start condition on SDA and SCL pins. Automatically cleared by hardware.
0 = Start condition idle
Note: For the ACKEN, RCEN, PEN, RSEN, SEN bits: If the I2C module is not in the idle
mode, the bit may not be set (no spooling) and the SSPBUF may not be written
(writes to the SSPBUF are disabled).
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleard x = bit is unknown
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39520A-page 20-9
Section 20. Master SSP
Master SSP
20
20.3 SPI Mode
The SPI mode allows 8 bits of data to be synchronously transmitted and received simultaneously.
All four modes of SPI are supported. To accomplish communication, typically three pins are used:
• Serial Data Out (SDO)
• Serial Data In (SDI)
• Serial Clock (SCK)
Additionally a fourth pin may be used when in a Slave Mode of operation:
• Slave Select (SS)
20.3.1 Operation
When initializing the SPI, several options need to be specified. This is done by programming the
appropriate control bits (SSPCON1<5:0>) and SSPSTAT<7:6>. These control bits allow the following
to be specified:
• Master Mode (SCK is the clock output)
• Slave Mode (SCK is the clock input)
• Clock Polarity (Idle state of SCK)
• Data input sample phase (middle or end of data output time)
• Clock edge (output data on rising/falling edge of SCK)
• Clock Rate (Master Mode only)
• Slave Select Mode (Slave Mode only)
Figure 20-4 shows the block diagram of the MSSP module, when in SPI mode.
Figure 20-4: MSSP Block Diagram (SPI Mode)
Read Write
Internal
Data Bus
SSPSR Reg
SSPBUF Reg
SSPM3:SSPM0
bit0 Shift
Clock
SS Control
Enable
Edge
Select
Clock Select
TMR2 Output
Prescaler TOSC
4, 16, 64
2
Edge
Select
2
4
Data to TX/RX in SSPSR
TRIS bit
2
SMP:CKE
SDI
SDO
SS
SCK
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39520A-page 20-10 2000 Microchip Technology Inc.
The MSSP consists of a transmit/receive Shift Register (SSPSR) and a Buffer Register
(SSPBUF). The SSPSR shifts the data in and out of the device, MSb first. The SSPBUF holds
the data that was written to the SSPSR, until the received data is ready. Once the 8 bits of data
have been received, that byte is moved to the SSPBUF Register. Then the buffer full detect bit,
BF (SSPSTAT register), and the interrupt flag bit, SSPIF, are set. This double buffering of the
received data (SSPBUF) allows the next byte to start reception before reading the data that was
just received. Any write to the SSPBUF Register during transmission/reception of data will be
ignored, and the write collision detect bit, WCOL (SSPCON1 register), will be set. User software
must clear the WCOL bit so that it can be determined if the following write(s) to the SSPBUF
Register completed successfully.
When the application software is expecting to receive valid data, the SSPBUF should be read
before the next byte of data to transfer is written to the SSPBUF. Buffer full bit, BF (SSPSTAT
register), indicates when SSPBUF has been loaded with the received data (transmission is
complete). When the SSPBUF is read, the BF bit is cleared. This data may be irrelevant if the
SPI is only a transmitter. Generally the MSSP Interrupt is used to determine when the transmission/reception
has completed. The SSPBUF must be read and/or written. If the interrupt method
is not going to be used, then software polling can be done to ensure that a write collision does
not occur. Example 20-1 shows the loading of the SSPBUF (SSPSR) for data transmission.
Example 20-1:Loading the SSPBUF (SSPSR) Register
The SSPSR is not directly readable or writable, and can only be accessed by addressing the
SSPBUF Register. Additionally, the MSSP Status Register (SSPSTAT) indicates the various status
conditions.
LOOP BTFSS SSPSTAT, BF ;Has data been received (transmit complete)?
GOTO LOOP ;No
MOVF SSPBUF, W ;WREG reg = contents of SSPBUF
MOVWF RXDATA ;Save in user RAM, if data is meaningful
MOVF TXDATA, W ;W reg = contents of TXDATA
MOVWF SSPBUF ;New data to xmit
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39520A-page 20-11
Section 20. Master SSP
Master SSP
20
20.3.2 Enabling SPI I/O
To enable the serial port, SSP Enable bit, SSPEN, must be set. To reset or reconfigure SPI mode,
clear the SSPEN bit, re-initialize the SSPCON Registers, and then set the SSPEN bit. This configures
the SDI, SDO, SCK, and SS pins as serial port pins. For the pins to behave as the serial
port function, some must have their data direction bits (in the TRIS Register) appropriately programmed.
That is:
• SDI is automatically controlled by the SPI module
• SDO must have the TRIS bit cleared
• SCK (Master Mode) must have the TRIS bit cleared
• SCK (Slave Mode) must have the TRIS bit set
• SS must have the TRIS bit set
Any serial port function that is not desired may be overridden by programming the corresponding
data direction (TRIS) Register to the opposite value.
20.3.3 Typical Connection
Figure 20-5 shows a typical connection between two microcontrollers. The master controller
(Processor 1) initiates the data transfer by sending the SCK signal. Data is shifted out of both
Shift Registers on their programmed clock edge, and latched on the opposite edge of the clock.
Both processors should be programmed to same Clock Polarity (CKP), then both controllers
would send and receive data at the same time. Whether the data is meaningful (or dummy data)
depends on the application software. This leads to three scenarios for data transmission:
• Master sends data — Slave sends dummy data
• Master sends data — Slave sends data
• Master sends dummy data — Slave sends data
Figure 20-5:SPI Master/Slave Connection
Serial Input Buffer
(SSPBUF)
Shift Register
(SSPSR)
MSb LSb
SDO
SDI
PROCESSOR 1
SCK
SPI Master SSPM3:SSPM0 = 00xxb
Serial Input Buffer
(SSPBUF)
Shift Register
(SSPSR)
MSb LSb
SDI
SDO
PROCESSOR 2
SCK
SPI Slave SSPM3:SSPM0 = 010xb
Serial Clock
39500 18C Reference Manual.book Page 11 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39520A-page 20-12 2000 Microchip Technology Inc.
20.3.4 SPI Master Mode
The master can initiate the data transfer at any time because it controls the SCK. The master
determines when the slave (Processor 2, Figure 20-5) is to broadcast data by the software protocol.
In Master Mode, the data is transmitted/received as soon as the SSPBUF Register is written to.
If the SPI is only going to receive, the SDO output could be disabled (programmed as an input).
The SSPSR Register will continue to shift in the signal present on the SDI pin at the programmed
clock rate. As each byte is received, it will be loaded into the SSPBUF Register (interrupts and
status bits appropriately set). This could be useful in receiver applications as a “line activity monitor”
mode.
The clock polarity is selected by appropriately programming the CKP bit. This gives waveforms
for SPI communication as shown in Figure 20-6, Figure 20-8, and Figure 20-9 where the Msb is
transmitted first. In Master Mode, the SPI clock rate (bit rate) is user programmable to be one of
the following:
• FOSC/4 (or TCY)
• FOSC/16 (or 4 • TCY)
• FOSC/64 (or 16 • TCY)
• Timer2 output/2
This allows a maximum data rate (at 40 MHz) of 10.00 Mbps.
Figure 20-6 shows the waveforms for Master Mode. When the CKE bit is set, the SDO data is
valid before there is a clock edge on SCK. The change of the input sample is shown based on
the state of the SMP bit. The time when the SSPBUF is loaded with the received data is shown.
Figure 20-6:SPI Mode Waveform (Master Mode)
SCK
(CKP = 0
SCK
(CKP = 1
SCK
(CKP = 0
SCK
(CKP = 1
4 clock
modes
Input
Sample
Input
Sample
SDI
bit7 bit0
SDO bit7 bit6 bit5 bit4 bit3 bit2 bit1 bit0
bit7 bit0
SDI
SSPIF
(SMP = 1)
(SMP = 0)
(SMP = 1)
CKE = 1)
CKE = 0)
CKE = 1)
CKE = 0)
(SMP = 0)
Write to
SSPBUF
SSPSR to
SSPBUF
SDO bit7 bit6 bit5 bit4 bit3 bit2 bit1 bit0
(CKE = 0)
(CKE = 1)
Next Q4 cycle
after Q2↓
39500 18C Reference Manual.book Page 12 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39520A-page 20-13
Section 20. Master SSP
Master SSP
20
20.3.5 SPI Slave Mode
In Slave Mode, the data is transmitted and received as the external clock pulses appear on SCK.
When the last bit is latched, the SSPIF interrupt flag bit is set.
While in Slave Mode, the external clock is supplied by the external clock source on the SCK pin.
This external clock must meet the minimum high and low times as specified in the electrical specifications.
While in sleep mode, the slave can transmit/receive data. When a byte is received, the device
will wake-up from sleep.
20.3.6 Slave Select Synchronization
The SS pin is a Slave Select pin, and functions similar to a chip select pin. The SPI must
be in Slave Mode with SS pin control enabled (SSPCON1<3:0> = 04h). The pin must be configured
as an input by setting the corresponding TRIS bit. When the SS pin is low, transmission
and reception are enabled and the SDO pin is driven. When the SS pin goes high,
the SDO pin is no longer driven, even if in the middle of a transmitted byte, and becomes
a floating output. External pull-up/ pull-down resistors may be desirable, depending on the
application.
If the TRIS bit is cleared, making the pin an output, and the pin outputs a high , the SPI
receive logic (slave mode) will be in reset. It will remain in reset until either the pin outputs
a low, or the pin’s TRIS bit is set and external circuits pull the pin low.
When the SPI module resets, the bit counter is forced to 0. This can be done by either by forcing
the SS pin to a high level or clearing the SSPEN bit.
To emulate two-wire communication, the SDO pin can be connected to the SDI pin. When the
SPI needs to operate as a receiver, the SDO pin can be configured as an input. This disables
transmissions from the SDO. The SDI can always be left as an input (SDI function) since it cannot
create a bus conflict.
Note 1: When the SPI is in Slave Mode with SS pin control enabled, (SSPCON<3:0> =
0100) the SPI module will reset if the SS pin is set to VDD.
Note 2: If the SPI is used in Slave Mode with CKE set, then the SS pin control must be
enabled.
39500 18C Reference Manual.book Page 13 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39520A-page 20-14 2000 Microchip Technology Inc.
Figure 20-7:Slave Synchronization Waveform
Figure 20-8:SPI Slave Mode Waveform (CKE = 0)
bit7
bit7 bit6 bit7 bit0
bit7
bit0
Next Q4 cycle
after Q2Ø
SS
SCK
(CKP = 0)
(CKE = 0)
SCK
(CKP = 1)
(CKE = 0)
Write to
SSPBUF
SDI
(SMP = 0)
Input
Sample
(SMP = 0)
SSPIF
Interrupt
Flag
SSPSR to
SSPBUF
SDO
bit7 bit0
bit7 bit6 bit5 bit4 bit3 bit2 bit1 bit0
Next Q4 cycle
after Q2Ø
SS
SCK
(CKP = 0)
(CKE = 0)
SCK
(CKP = 1)
(CKE = 0)
Write to
SSPBUF
SDI
(SMP = 0)
Input
Sample
(SMP = 0)
SSPIF
Interrupt
Flag
SSPSR to
SSPBUF
SDO
39500 18C Reference Manual.book Page 14 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39520A-page 20-15
Section 20. Master SSP
Master SSP
20
Figure 20-9:SPI Slave Mode Waveform (CKE = 1)
SCK
(CKP = 1)
SCK
(KP = 0)
Input
Sample
SDI
bit7 bit0
SDO bit7 bit6 bit5 bit4 bit3 bit2 bit1 bit0
SSPIF
Interrupt
(SMP = 0)
(SMP = 0)
Write to
SSPBUF
SSPSR to
SSPBUF
SS
Flag
required
Next Q4 cycle
after Q2Ø
39500 18C Reference Manual.book Page 15 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39520A-page 20-16 2000 Microchip Technology Inc.
20.3.7 Sleep Operation
In Master Mode, when the SLEEP instruction is executed, all module clocks are halted. The transmission/reception
that is in progress will remain in the current state until the device wakes from
sleep. After the device returns to normal mode, the module will continue to transmit/receive data.
In Slave Mode, the SPI transmit/receive Shift Register operates asynchronously to the device.
This allows the device to be placed in sleep mode, and data to be shifted into the SPI transmit/receive
Shift Register. When all 8 bits have been received, the MSSP interrupt flag bit will be
set. If the SSPIF is enabled, it will wake the device from sleep.
20.3.8 Effects of a Reset
A reset disables the MSSP module and terminates the current transfer.
20.3.9 Bus Mode Compatibility
Table 20-1 shows the compatibility between the standard SPI modes and the states of the CKP
and CKE control bits.
Table 20-1: SPI Bus Modes
There is also a SMP bit that controls when the data is sampled.
Table 20-2: Registers Associated with SPI Operation
Standard SPI Mode
Terminology
Control Bits State
CKP CKE
0, 0 0 1
0, 1 0 0
1, 0 1 1
1, 1 1 0
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Value on
POR,
BOR
Value on
all other
resets
INTCON GIE/
GIEH
PEIE/
GIEL
TMR0IE INT0IE RBIE TMR0IF INT0IF RBIF 0000 000x 0000 000u
PIR1 PSPIF (1) ADIF RCIF TXIF SSPIF CCP1IF TMR2IF TMR1IF 0000 0000 0000 0000
PIE1 PSPIE (1) ADIE RCIE TXIE SSPIE CCP1IE TMR2IE TMR1IE 0000 0000 0000 0000
IPR1 PSPIP (1) ADIP RCIP TXIP SSPIP CCP1IP TMR2IP TMR1IP 0000 0000 0000 0000
TRISC PORTC Data Direction Register 1111 1111 1111 1111
SSPBUF Synchronous Serial Port Receive Buffer/Transmit Register xxxx xxxx uuuu uuuu
SSPCON WCOL SSPOV SSPEN CKP SSPM3 SSPM2 SSPM1 SSPM0 0000 0000 0000 0000
TRISA — PORTA Data Direction Register --11 1111 --11 1111
SSPSTAT SMP CKE D/A P S R/W UA BF 0000 0000 0000 0000
Legend: x = unknown, u = unchanged, - = unimplemented read as '0'.
Shaded cells are not used by the MSSP in SPI mode.
Note 1: The PSPIF, PSPIE and PSPIP bits are reserved on the PIC18C2X2 devices. Always maintain these bits clear.
39500 18C Reference Manual.book Page 16 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39520A-page 20-17
Section 20. Master SSP
Master SSP
20
20.4 MSSP I2C Operation
The MSSP module in I2C mode fully implements all master and slave functions (including general
call support) and provides interrupts on Start and Stop bits in hardware to determine a free
bus (multi-master function). The MSSP module implements the standard mode specifications as
well as 7-bit and 10-bit addressing. Appendix A gives an overview of the I2C bus specification.
A "glitch" filter is on the SCL and SDA pins when the pin is an input. This filter operates in both
the 100 kHz and 400 kHz modes. In the 100 kHz mode, when these pins are an output, there is
a slew rate control of the pin that is independent of device frequency.
Figure 20-10: I2C Slave Mode Block Diagram
Figure 20-11: I2C Master Mode Block Diagram
Read Write
SSPSR reg
Match detect
SSPADD reg
Start and
Stop bit detect
SSPBUF reg
Internal
Data Bus
Address Match
Set, Reset
S, P bits
(SSPSTAT reg)
SCL
shift
clock
SDA MSb LSb
Read Write
SSPSR reg
Match detect
SSPADD reg
Start and Stop bit
detect / generate
SSPBUF reg
Internal
Data Bus
Address Match
Set/Clear S bit
Clear/Set P bit
(SSPSTAT reg)
SCL
shift
clock
SDA MSb LSb
Baud Rate Generator
7
SSPADD<6:0>
and
and Set SSPIF
39500 18C Reference Manual.book Page 17 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39520A-page 20-18 2000 Microchip Technology Inc.
Two pins are used for data transfer. These are the SCL pin, which is the clock, and the SDA pin,
which is the data. The SDA and SCL pins must be configured as inputs in the corresponding
TRIS registers when the I2C mode is enabled. The MSSP module functions are enabled by setting
the MSSP Enable bit, SSPEN (SSPCON register).The MSSP module has six registers for
I
2C operation. They are the:
• MSSP Control Register1 (SSPCON1)
• MSSP Control Register2 (SSPCON2)
• MSSP Status Register (SSPSTAT)
• Serial Receive/Transmit Buffer (SSPBUF)
• MSSP Shift Register (SSPSR) - Not directly accessible
• MSSP Address Register (SSPADD)
The SSPCON1 Register allows control of the I2C operation. Four mode selection bits
(SSPCON1<3:0>) allow one of the following I2C modes to be selected:
• I2C Slave Mode (7-bit address)
• I2C Slave Mode (10-bit address)
• I2C Master Mode, clock = OSC/4 (SSPADD +1)
• I2C Slave Mode (7-bit address), with Start and Stop bit interrupts enabled
• I2C Slave Mode (10-bit address), with Start and Stop bit interrupts enabled
• I2C Firmware controlled master operation, slave is idle
Before selecting any I2C mode, the SCL and SDA pins must be programmed to inputs by setting
the appropriate TRIS bits. Selecting an I2C mode, by setting the SSPEN bit, enables the SCL
and SDA pins to be used as the clock and data lines in I2C mode.
The SSPSTAT Register gives the status of the data transfer. This information includes detection
of a Start or Stop bit, specifies if the received byte was data or address, if the next byte is the
completion of 10-bit address, and if this will be a read or write data transfer.
The SSPBUF is the register to which transfer data is written to or read from. The SSPSR Register
shifts the data in or out of the device. In receive operations, the SSPBUF and SSPSR create a
double buffered receiver. This allows reception of the next byte to begin before reading the current
byte of received data. When the complete byte is received, it is transferred to the SSPBUF
Register and the SSPIF bit is set. If another complete byte is received before the SSPBUF Register
is read, a receiver overflow has occurred and the SSPOV bit (SSPCON1 register) is set and
the byte in the SSPSR is lost.
The SSPADD Register holds the slave address. In 10-bit mode, the user needs to write the high
byte of the address (1111 0 A9 A8 0). Following the high byte address match, the low byte of
the address needs to be loaded (A7:A0).
39500 18C Reference Manual.book Page 18 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39520A-page 20-19
Section 20. Master SSP
Master SSP
20
20.4.1 Slave Mode
In Slave Mode, the SCL and SDA pins must be configured as inputs. The MSSP module will override
the input state with the output data when required (slave-transmitter).
When an address is matched or the data transfer after an address match is received, the hardware
automatically generates the acknowledge (ACK) pulse, and loads the SSPBUF Register
with the received value currently in the SSPSR Register.
There are certain conditions that will cause the MSSP module not to give this ACK pulse. These
are if either (or both):
a) The buffer full bit, BF (SSPSTAT register), was set before the transfer was received.
b) The overflow bit, SSPOV (SSPCON1 register), was set before the transfer was received.
If the BF bit is set, the SSPSR Register value is not loaded into the SSPBUF, but the SSPIF and
SSPOV bits are set. Table 20-3 shows what happens when a data transfer byte is received, given
the status of the BF and SSPOV bits. The shaded cells show the condition where user software
did not properly clear the overflow condition. The BF bit is cleared by reading the SSPBUF register
while bit SSPOV is cleared through software.
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 requirement of the MSSP module is shown in
timing parameters 100 and 101 of the “Electrical Specifications” section.
39500 18C Reference Manual.book Page 19 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39520A-page 20-20 2000 Microchip Technology Inc.
20.4.1.1 Addressing
Once the MSSP module has been enabled, it waits for a Start condition to occur. Following the
Start condition, the 8 bits are shifted into the SSPSR Register. All incoming bits are sampled with
the rising edge of the clock (SCL) line. The value of register SSPSR<7:1> is compared to the
value of the SSPADD Register (bits 7:1). The address is compared on the falling edge of the
eighth clock (SCL) pulse. If the addresses match, and the BF and SSPOV bits are clear, the following
events occur:
a) The SSPSR Register value is loaded into the SSPBUF Register on the falling edge of the
eighth SCL pulse.
b) The buffer full bit, BF, is set on the falling edge of the eighth SCL pulse.
c) An ACK pulse is generated.
d) MSSP interrupt flag bit, SSPIF, is set (interrupt is generated if enabled) - on the falling
edge of the ninth SCL pulse.
In 10-bit address mode, two address bytes need to be received by the slave. The five Most Significant
bits (MSbs) of the first address byte specify if this is a 10-bit address. The R/W bit
(SSPSTAT<2>) must specify a write so the slave device will receive the second address byte.
For a 10-bit address the first byte would equal ‘1111 0 A9 A8 0’, where A9 and A8 are the two
MSbs of the address. The sequence of events for a 10-bit address is as follows (with steps 7- 9
for a slave-transmitter):
1. Receive first (high) byte of the address (the SSPIF, BF, and UA (SSPSTAT register) bits
are set).
2. Update the SSPADD Register with second (low) byte of the address (clears the UA bit and
releases the SCL line).
3. Read the SSPBUF Register (clears the BF bit) and clear flag bit SSPIF.
4. Receive second (low) byte of the address (the SSPIF, BF, and UA bits are set).
5. Update the SSPADD Register with the first (high) byte of the address. This will clear the
UA bit and release the SCL line.
6. Read the SSPBUF Register (clears the BF bit) and clear the SSPIF flag bit.
7. Receive repeated Start condition.
8. Receive first (high) byte of the address (the SSPIF and BF bits are set).
9. Read the SSPBUF Register (clears the BF bit) and clear the SSPIF flag bit.
Table 20-3: Data Transfer Received Byte Actions
Note: Following the Repeated Start condition (step 7) in 10-bit mode, the user only needs
to match the first 7-bit address. The user does not update the SSPADD for the second
half of the address.
Status Bits as Data
Transfer is Received
SSPSR → SSPBUF
Generate ACK
Pulse
Set bit SSPIF
(SSP Interrupt occurs
BF SSPOV if enabled)
0 0 Yes Yes Yes
1 0 No No Yes
1 1 No No Yes
0 1 Yes No Yes
Note: Shaded cells show the conditions where the user software did not properly clear
the overflow condition
39500 18C Reference Manual.book Page 20 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39520A-page 20-21
Section 20. Master SSP
Master SSP
20
20.4.1.2 Slave Reception
When the R/W bit of the address byte is clear and an address match occurs, the R/W bit of the
SSPSTAT Register is cleared. The received address is loaded into the SSPBUF Register.
When the address byte overflow condition exists, then no acknowledge (ACK) pulse is given. An
overflow condition is defined as either the BF bit (SSPSTAT register) is set or the SSPOV bit
(SSPCON1 register) is set.
An MSSP interrupt is generated for each data transfer byte. The SSPIF flag bit must be cleared
in software. The SSPSTAT Register is used to determine the status of the received byte.
Note: The SSPBUF will be loaded if the SSPOV bit is set and the BF flag bit is cleared. If
a read of the SSPBUF was performed, but the user did not clear the state of the
SSPOV bit before the next receive occurred. The ACK is not sent and the SSPBUF
is updated.
39500 18C Reference Manual.book Page 21 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39520A-page 20-22 2000 Microchip Technology Inc.
20.4.1.3 Slave Transmission
When the R/W bit of the incoming address byte is set and an address match occurs, the R/W bit
of the SSPSTAT Register is set. The received address is loaded into the SSPBUF Register. The
ACK pulse will be sent on the ninth bit, and the SCL pin is held low. The transmit data must be
loaded into the SSPBUF Register, which also loads the SSPSR Register and sets the BF bit.
Then the SCL pin should be enabled by setting the CKP bit (SSPCON1 register). The master
should monitor the SCL pin prior to asserting another clock pulse. The slave devices may be
holding off the master by stretching the clock. The eight data bits are shifted out on the falling
edge of the SCL input. This ensures that the SDA signal is valid during the SCL high time
(Figure 20-13). When all eight bits have been shifted out, the BF bit will be cleared.
An MSSP interrupt is generated for each data transfer byte. The SSPIF flag bit must be cleared
in software, and the SSPSTAT Register is used to determine the status of the byte transfer. The
SSPIF flag bit is set on the falling edge of the ninth clock pulse.
As a slave-transmitter, the ACK pulse from the master-receiver is latched on the rising edge of
the ninth SCL input pulse. If the SDA line was high (not ACK), then the data transfer is complete.
When the not ACK is latched by the slave, the slave logic is reset and the slave then monitors
for another occurrence of the Start bit. If the SDA line was low (ACK), the transmit data must be
loaded into the SSPBUF Register, which also loads the SSPSR Register and sets the BF bit.
Then the SCL pin should be enabled by setting the CKP bit.
Figure 20-12: I
2C Slave Mode Waveforms for Reception (7-bit Address)
Figure 20-13: I2C Slave Mode Waveforms for Transmission (7-bit Address)
5 76 8 9 P
D6D7 D5 D3D4 D2 D1 D0
S
A7 A6 A5 A4 A3 A2 A1SDA
SCL 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 23 4
Bus Master
terminates
transfer
Bit SSPOV is set because the SSPBUF Register is still full.
Cleared in software
SSPBUF Register is read
Receiving Data ACK Receiving Data
D6D7 D5 D3D4 D2 D1 D0 ACK
R/W=0 Receiving Address
SSPIF
BF (SSPSTAT<0>)
SSPOV (SSPCON1<6>)
Not ACK
ACK is not sent.
SDA
SCL
SSPIF
BF (SSPSTAT<0>)
CKP (SSPCON1<4>)
A7 A6 A5 A4 A3 A2 A1 ACK D7 D6 D5 D4 D3 D2 D1 D0
Receiving Address R/W = 1 Transmitting Data Not ACK
123456789 1234 56789 P
Cleared in software
SSPBUF is written in software From MSSP interrupt
service routine
Set bit after writing to SSPBUF
S Data in
sampled
SCL held low
while CPU responds to SSPIF
(the SSPBUF must be written-to
before the CKP bit can be set)
R/W = 0
39500 18C Reference Manual.book Page 22 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39520A-page 20-23
Section 20. Master SSP
Master SSP
20
Figure 20-14:
I
2C Slave Mode Waveform (Transmission 10-bit Address) SDA SCL SSPIF BF (SSPSTAT<0>) S 123 45 6 78 9 1 2345 67 89 12 34 5 7 8 9 P 1 1 1 1 0 A9 A8 A7 A6 A5 A4 A3 A2 A1 A0 1 1 1 1 0 A8 R/W=1 ACK ACK R/W = 0 ACK Receive First Byte of Address Cleared in software Master sends NACK A96 (PIR1<3>) Receive Second Byte of Address Cleared by hardware when SSPADD is updated UA (SSPSTAT<1>) Clock is held low until update of SSPADD has taken place UA is set indicating that the SSPADD needs to be updated UA is set indicating that SSPADD needs to be
updated
Cleared by hardware when
SSPADD is updated
SSPBUF is written with
contents of SSPSR
Dummy read of SSPBUF to clear BF flag
Receive First Byte of Address
12345 78 9
D7 D6 D5 D4 D3 D1
ACK
D2
6
Transmitting Data Byte
D0
Dummy read of SSPBUF
to clear BF flag
Sr
Cleared in software
Write of SSPBUF
initiates transmit
Cleared in software
Transmit is complete
clock to be released
CKP has to be set for
Bus Master
terminates
transfer
39500 18C Reference Manual.book Page 23 Monday, July 10, 2000 6:12 PM
DS39520A-page 20-24
PIC18C Reference Manual
2000 Microchip Technology Inc.
Figure 20-15: I
2C Slave Mode Waveform (Reception 10-bit Address) SDA SCL SSPIF BF (SSPSTAT<0>) S 1 234 56 7 89 1 2345 67 89 1 2345 789 P 1 1 1 1 0 A9 A8 A7 A6 A5 A4 A3 A2 A1 A0 D7 D6 D5 D4 D3 D1 D0 Receive Data Byte ACK R/W = 0 ACK Receive First Byte of Address Cleared in software Bus Master terminates transfer D2 6 (PIR1<3>) Receive Second Byte of Address Cleared by hardware when SSPADD is updated with UA (SSPSTAT<1>) Clock is held low until update of SSPADD has taken place UA is set indicating that the SSPADD needs to be
updated UA is set indicating that
SSPADD needs to be
updated
SSPBUF is written with
contents of SSPSR Dummy read of SSPBUF to clear BF flag
ACK
R/W = 1
Cleared in software
Dummy read of SSPBUF to clear BF flag Read of SSPBUF clears BF flag
Cleared by hardware when
SSPADD is updated with low byte of address
high byte of address
39500 18C Reference Manual.book Page 24 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39520A-page 20-25
Section 20. Master SSP
Master SSP
20
20.4.2 General Call Address Support
The addressing procedure for the I2C bus is such that the first byte after the Start condition usually
determines which device will be the slave addressed by the master. The exception is the general
call address, which can address all devices. When this address is used, all 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 address is recognized when the General Call Enable bit (GCEN) is set. Following
a Start bit detect, 8 bits are shifted into the SSPSR and the address is compared against the
SSPADD, and is also compared to the general call address, fixed in hardware.
If the general call address matches, the SSPSR is transferred to the SSPBUF, the BF flag bit is
set (during the eighth bit), and on the falling edge of the ninth bit (the ACK bit) the SSPIF interrupt
flag bit is set.
When the interrupt is serviced. The source for the interrupt can be checked by reading the contents
of the SSPBUF to determine if the address was device specific or a general call address.
In 10-bit address mode, SSPADD must be updated for the second half of the address to match
and the UA bit to be set.
If the general call address is sampled when the GCEN bit is set, then the second half of the
address is not necessary. The UA bit will not be set, and the slave (configured in 10-bit address
mode) will begin receiving data after the acknowledge (Figure 20-16).
Figure 20-16: Slave Mode General Call Address Sequence (7 or 10-bit Address Mode)
SDA
SCL
S
SSPIF
BF (SSPSTAT<0>)
SSPOV (SSPCON1<6>)
Cleared in software
SSPBUF is read
R/W = 0
ACK General Call Address
Address is compared to General Call Address
GCEN (SSPCON2<7>)
Receiving data ACK
1 2 34 56 78 91 2 34 56 789
D7 D6 D5 D4 D3 D2 D1 D0
after ACK, set interrupt
'0'
'1'
39500 18C Reference Manual.book Page 25 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39520A-page 20-26 2000 Microchip Technology Inc.
20.4.3 Sleep Operation
While in sleep mode, the I2C module can receive addresses or data. When an address match or
complete byte transfer occurs, the processor will wake-up from sleep (if the MSSP interrupt is
enabled).
20.4.4 Effect of a Reset
A reset disables the MSSP module and terminates the current transfer.
Table 20-4: Registers Associated with I2C Operation
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Value on
POR,
BOR
Value on all
other resets
INTCON GIE/
GIEH
PEIE/
GIEL
TMR0IE INT0IE RBIE TMR0IF INT0IF RBIF 0000 000x 0000 000u
PIR SSPIF, BCLIF (1) 0, 0 0, 0
PIE SSPIE, BCLIF (1) 0, 0 0, 0
SSPADD Synchronous Serial Port (I2C mode)
Address Register (Slave Mode)/Baud Rate Generator (Master Mode) 0000 0000 0000 0000
SSPBUF Synchronous Serial Port Receive Buffer/Transmit Register xxxx xxxx uuuu uuuu
SSPCON1 WCOL SSPOV SSPEN CKP SSPM3 SSPM2 SSPM1 SSPM0 0000 0000 0000 0000
SSPCON2 GCEN ACKSTAT ACKDT ACKEN RCEN PEN RSEN SEN 0000 0000 0000 0000
SSPSTAT SMP CKE D/A P S R/W UA BF 0000 0000 0000 0000
Legend: x = unknown, u = unchanged, - = unimplemented read as '0'.
Shaded cells are not used by the MSSP in I2C mode.
Note 1: The position of these bits is device dependent.
39500 18C Reference Manual.book Page 26 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39520A-page 20-27
Section 20. Master SSP
Master SSP
20
20.4.5 Master Mode
Master Mode of operation is supported by interrupt generation on the detection of the Start and
Stop conditions. The Stop (P) and Start (S) bits are cleared when a reset occurs or when the
MSSP module is disabled. Control of the I2C bus may be taken when the P bit is set, or the bus
is idle with both the S and P bits clear.
In Master Mode, the SCL and SDA lines are manipulated by the MSSP hardware.
The following events will cause SSP Interrupt Flag bit, SSPIF, to be set (SSP Interrupt if enabled):
• Start condition
• Stop condition
• Data transfer byte transmitted/received
• Acknowledge Transmit
• Repeated Start
Figure 20-17: MSSP Block Diagram (I
2C Master Mode)
Read Write
SSPSR
Start Bit, Stop Bit,
Start Bit Detect
SSPBUF
Internal
Data Bus
Set/Reset, S, P, WCOL (SSPSTAT)
Shift
Clock
MSb LSb
SDA
Acknowledge
Generate
Stop Bit Detect
Write Collision Detect
Clock Arbitration
State Counter for
End of XMIT/RCV
SCL
SCL In
Bus Collision
SDA In Receive Enable
Clock Cntl
Clock Arbitrate/WCOLDetect
(Hold Off Clock Source)
SSPADD<6:0>
Baud
Set SSPIF, BCLIF
Reset ACKSTAT, PEN (SSPCON2)
Rate
Generator
SSPM3:SSPM0
39500 18C Reference Manual.book Page 27 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39520A-page 20-28 2000 Microchip Technology Inc.
20.4.6 Multi-Master Mode
In Multi-Master Mode, the interrupt generation on the detection of the Start and Stop conditions
allows the determination of when the bus is free. The Stop (P) and Start (S) bits are cleared from
a reset or when the MSSP module is disabled. Control of the I2C bus may be taken when the P
bit (SSPSTAT register) is set, or the bus is idle with both the S and P bits clear. When the bus is
busy, enabling the MSSP Interrupt will generate the interrupt when the Stop condition occurs.
In multi-master operation, the SDA line must be monitored, for arbitration, to see if the signal level
is the expected output level. This check is performed in hardware, with the result placed in the
BCLIF bit.
The states where arbitration can be lost are:
• Address transfer
• Data transfer
• A Start condition
• A Repeated Start condition
• An Acknowledge condition
20.4.7 I2C Master Mode Support
Master Mode is enabled by setting and clearing the appropriate SSPM bits in SSPCON1 and by
setting the SSPEN bit. Once Master Mode is enabled, the user has six options.
1. Assert a Start condition on SDA and SCL.
2. Assert a Repeated Start condition on SDA and SCL.
3. Write to the SSPBUF Register initiating transmission of data/address.
4. Generate a Stop condition on SDA and SCL.
5. Configure the I2C port to receive data.
6. Generate an acknowledge condition at the end of a received byte of data.
Note: The MSSP Module when configured in I2C Master Mode does not allow queueing of
events. For instance: The user is not allowed to initiate a Start condition, and immediately
write the SSPBUF Register to imitate transmission before the Start condition
is complete. In this case the SSPBUF will not be written to, and the WCOL bit will be
set, indicating that this write to the SSPBUF did not occur.
39500 18C Reference Manual.book Page 28 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39520A-page 20-29
Section 20. Master SSP
Master SSP
20
20.4.7.1 I2
C Master Mode Operation
The master device generates all of the serial clock pulses and the Start and Stop conditions. A
transfer is ended with a Stop condition or with a Repeated Start condition. Since the Repeated
Start condition is also the beginning of the next serial transfer, the I2C bus will not be released.
In master transmitter mode, serial data is output through SDA, while SCL outputs the serial clock.
The first byte transmitted contains the slave address of the receiving device (7 bits), and the
Read/Write (R/W) bit. In this case, the R/W bit will be logic '0'. Serial data is transmitted 8 bits at
a time. After each byte is transmitted, an Acknowledge bit is received. Start and Stop conditions
are output to indicate the beginning and the end of a serial transfer.
In master receive mode, the first byte transmitted contains the slave address of the transmitting
device (7 bits), and the R/W bit. In this case, the R/W bit will be logic '1'. Thus, the first byte transmitted
is a 7-bit slave address followed by a '1' to indicate receive bit. Serial data is received via
the SDA pin, while the SCL pin outputs the serial clock. Serial data is received 8 bits at a time.
After each byte is received, an Acknowledge bit is transmitted. Start and Stop conditions indicate
the beginning and end of transmission.
The baud rate generator used for SPI mode operation is now used to set the SCL clock frequency
for either 100 kHz, 400 kHz, or 1 MHz I2C operation. The baud rate generator reload value is
contained in the lower 7 bits of the SSPADD Register. The baud rate generator will automatically
begin counting on a write to the SSPBUF. Once the given operation is complete (i.e., transmission
of the last data bit is followed by ACK), the internal clock will automatically stop counting and
the SCL pin will remain in its last state.
A typical transmit sequence would go as follows:
a) The user generates a Start condition by setting the Start enable bit, SEN (SSPCON2 register).
b) SSPIF is set. The MSSP module will wait the required start time before any other operation
takes place.
c) The user loads the SSPBUF with the address to transmit.
d) Address is shifted out the SDA pin until all 8 bits are transmitted.
e) The MSSP module shifts in the ACK bit from the slave device, and writes its value into the
SSPCON2 Register (SSPCON2 register).
f) The MSSP module generates an interrupt at the end of the ninth clock cycle by setting the
SSPIF bit.
g) The user loads the SSPBUF with eight bits of data.
h) DATA is shifted out the SDA pin until all 8 bits are transmitted.
i) The MSSP module shifts in the ACK bit from the slave device, and writes its value into the
SSPCON2 Register (SSPCON2 register).
j) The MSSP module generates an interrupt at the end of the ninth clock cycle by setting the
SSPIF bit.
k) The user generates a Stop condition by setting the Stop enable bit, PEN (SSPCON2 register).
l) Interrupt is generated once the Stop condition is complete.
39500 18C Reference Manual.book Page 29 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39520A-page 20-30 2000 Microchip Technology Inc.
20.4.8 Baud Rate Generator
In I2C Master Mode, the reload value for the BRG is located in the lower 7 bits of the SSPADD
Register (Figure 20-18). When the BRG is loaded with this value, the BRG counts down to 0 and
stops until another reload has taken place. The BRG count is decremented twice per instruction
cycle (TCY) on the Q2 and Q4 clocks. In I2C Master Mode, the BRG is reloaded automatically. If
clock arbitration is taking place for instance, the BRG will be reloaded when the SCL pin is sampled
high (Figure 20-19).
Figure 20-18: Baud Rate Generator Block Diagram
Figure 20-19: Baud Rate Generator Timing With Clock Arbitration
SSPM3:SSPM0
CLK BRG Down Counter FOSC/4
SSPADD<6:0>
SSPM3:SSPM0
SCL
Reload
Control
Reload
SDA
SCL
SCL de-asserted, but Slave holds
DX DX-1
BRG
SCL is sampled high, reload takes
place, and BRG starts its count
03h 02h 01h 00h (hold off) 03h 02h
reload
BRG
value
SCL low (Clock Arbitration)
SCL allowed to transition high
BRG decrements on
Q2 and Q4 cycles
39500 18C Reference Manual.book Page 30 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39520A-page 20-31
Section 20. Master SSP
Master SSP
20
20.4.9 I2C Master Mode Start Condition Timing
To initiate a Start condition, the user sets the Start condition enable bit, SEN (SSPCON2
register). If the SDA and SCL pins are sampled high, the baud rate generator is re-loaded with
the contents of SSPADD<6:0>, and starts its count. If the SCL and SDA pins are both sampled
high when the baud rate generator times out (TBRG), the SDA pin is driven low. The action of the
SDA pin being driven low while the SCL pin is high in the Start condition, and causes the S bit
(SSPSTAT register) to be set. Following this, the baud rate generator is reloaded with the
contents of SSPADD<6:0> and resumes its count. When the baud rate generator times out
(TBRG) the SEN bit (SSPCON2 register) will be automatically cleared by hardware, the baud rate
generator is suspended leaving the SDA line held low, and the Start condition is complete.
20.4.9.1 WCOL Status Flag
If the user writes the SSPBUF when an Start sequence is in progress, then WCOL is set and the
contents of the buffer are unchanged (the write doesn’t occur).
Figure 20-20: First Start Bit Timing
Note: If at the beginning of Start condition, the SDA and SCL pins are already sampled low,
or if during the Start condition the SCL pin is sampled low before the SDA pin is
driven low, a bus collision occurs. The Bus Collision Interrupt Flag, BCLIF, is set, the
Start condition is aborted, and the I2C module is reset into its idle state.
Note: Because queueing of events is not allowed, writing to the lower 5 bits of SSPCON2
is disabled until the Start condition is complete.
SDA
SCL
S
TBRG
1st Bit 2nd Bit
TBRG
SDA = 1, At completion of Start Bit, SCL = 1
TBRG Write to SSPBUF occurs here
hardware clears SEN Bit
TBRG
Write to SEN Bit occurs here Set S bit (SSPSTAT<3>)
and sets SSPIF Bit
39500 18C Reference Manual.book Page 31 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39520A-page 20-32 2000 Microchip Technology Inc.
Figure 20-21: Start Condition Flowchart
Idle Mode
SEN (SSPCON2<0> = 1)
Bus collision detected
Set BCLIF Bit SDA = 1?
Load BRG with
Yes
BRG
Rollover?
Force SDA = 0,
Load BRG with
SSPADD<6:0>,
No
Yes
Force SCL = 0,
Clear SEN bit,
Set S Bit
SSPADD<6:0>
SCL = 1?
SDA = 0?
No
Yes
BRG
rollover?
No
Clear SEN Bit
Start condition Done,
No
Yes
Reset BRG
SCL= 0?
No
Yes
SCL = 0? No
Yes
Reset BRG
Release SCL Bit
SSPEN = 1
SSPCON1<3:0> =1000
Set SSPIF bit
39500 18C Reference Manual.book Page 32 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39520A-page 20-33
Section 20. Master SSP
Master SSP
20
20.4.10 I2C Master Mode Repeated Start Condition Timing
A Repeated Start condition occurs when the RSEN bit (SSPCON2 register) is programmed high
and the I2C logic module is in the idle state. When the RSEN bit is set, the SCL pin is asserted
low. When the SCL pin is sampled low, the baud rate generator is loaded with the contents of
SSPADD<5:0>, and begins counting. The SDA pin is released (brought high) for one baud rate
generator count (TBRG). When the baud rate generator times out, if SDA is sampled high, the
SCL pin will be de-asserted (brought high). When the SCL pin is sampled high, the baud rate
generator is re-loaded with the contents of SSPADD<6:0> and begins counting. SDA and SCL
must be sampled high for one TBRG. This action is then followed by assertion of the SDA pin (SDA
= 0) for one TBRG while SCL is high. Following this, the RSEN bit (SSPCON2 register) will be
automatically cleared and the baud rate generator is not reloaded, leaving the SDA pin held low.
As soon as a Start condition is detected on the SDA and SCL pins, the S bit (SSPSTAT register)
will be set. The SSPIF bit will not be set until the baud rate generator has timed-out.
Immediately following the SSPIF bit getting set, the user may write the SSPBUF with the 7-bit
address in 7-bit mode, or the default first address in 10-bit mode. After the first eight bits are
transmitted and an ACK is received, the user may then transmit an additional eight bits of address
(10-bit mode) or eight bits of data (7-bit mode).
Note 1: If RSEN is programmed while any other event is in progress, it will not take effect.
Note 2: A bus collision during the Repeated Start condition occurs if:
• SDA is sampled low when SCL goes from low to high.
• SCL goes low before SDA is asserted low. This may indicate that another
master is attempting to transmit a data "1".
39500 18C Reference Manual.book Page 33 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39520A-page 20-34 2000 Microchip Technology Inc.
20.4.10.1 WCOL Status Flag
If the user writes the SSPBUF when a Repeated Start sequence is in progress, then WCOL is
set and the contents of the buffer are unchanged (the write doesn’t occur).
Figure 20-22: Repeat Start Condition Waveform
Note: Because queueing of events is not allowed, writing of the lower 5 bits of SSPCON2
is disabled until the Repeated Start condition is complete.
SDA
SCL
Sr = Repeated Start
Write to SSPCON2
Falling edge of ninth clock Write to SSPBUF occurs here
End of transmit
At completion of START Bit,
hardware clear RSEN bit
1st Bit
Set S (SSPSTAT<3>)
TBRG
TBRG
SDA = 1,
SDA = 1
SCL (no change)
SCL = 1
occurs here
TBRG TBRG TBRG
and sets SSPIF
39500 18C Reference Manual.book Page 34 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39520A-page 20-35
Section 20. Master SSP
Master SSP
20
Figure 20-23: Repeated Start Condition Flowchart (part 1 of 2)
Idle Mode,
SSPEN = 1,
Force SCL = 0
SCL = 0?
Release SDA pin,
Load BRG with
SCL = 1?
No
Yes
No
Yes
BRG
No
Yes
Release SCL pin
SSPCON1<3:0> = 1000
rollover?
SSPADD<6:0>
Load BRG with
SSPADD<6:0>
(Clock Arbitration)
A
B
C
SDA = 1?
No
Yes
Start
RSEN = 1
Bus Collision,
Set BCLIF,
Release SDA pin,
Clear RSEN
39500 18C Reference Manual.book Page 35 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39520A-page 20-36 2000 Microchip Technology Inc.
Figure 20-24: Repeated Start Condition Flowchart (part 2 of 2)
Force SDA = 0,
Load BRG with
SSPADD<6:0>
Yes
Repeated Start
Clear RSEN,
Yes
BRG
rollover?
BRG
rollover?
Yes
SDA = 0?
No
SCL = 1?
No
B
Set S
C A
No
No
Yes
Force SCL = 0,
Reset BRG
Set SSPIF
SCL = '0'?
Reset BRG
No
Yes
condition done,
39500 18C Reference Manual.book Page 36 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39520A-page 20-37
Section 20. Master SSP
Master SSP
20
20.4.11 I2C Master Mode Transmission
Transmission of a data byte, a 7-bit address, or the other half of a 10-bit address is accomplished
by simply writing a value to SSPBUF Register. This action will set the buffer full flag bit, BF, and
allow the baud rate generator to begin counting and start the next transmission. Each bit of
address/data will be shifted out onto the SDA pin after the falling edge of SCL is asserted (see
data hold time specification parameter 106 in the “Electrical Specifications” section). SCL is
held low for one baud rate generator roll over count (TBRG). Data should be valid before SCL is
released high (see data setup time specification parameter 107 in the “Electrical Specifications”
section). When the SCL pin is released high, it is held that way for TBRG, the data on the
SDA pin must remain stable for that duration and some hold time after the next falling edge of
SCL. After the eighth bit is shifted out (the falling edge of the eighth clock), the BF bit is cleared
and the master releases the SDA pin. 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.
The status of ACK is written into the ACKDT bit on the falling edge of the ninth clock. If the
master receives an acknowledge, the acknowledge status bit, ACKSTAT, is cleared. If not, the bit
is set. After the ninth clock, the SSPIF bit is set and the master clock (baud rate generator) is
suspended until the next data byte is loaded into the SSPBUF, leaving the SCL pin low and the
SDA pin unchanged (Figure 20-26).
After the write to the SSPBUF, each bit of address will be shifted out on the falling edge of SCL
until all seven address bits and the R/W bit are completed. On the falling edge of the eighth clock,
the master will de-assert the SDA pin allowing the slave to respond with an acknowledge. On the
falling edge of the ninth clock, the master will sample the SDA pin to see if the address was recognized
by a slave. The status of the ACK bit is loaded into the ACKSTAT status bit (SSPCON2
register). Following the falling edge of the ninth clock transmission of the address, the SSPIF is
set, the BF flag is cleared, and the baud rate generator is turned off until another write to the SSPBUF
takes place, holding SCL low and allowing SDA to float.
20.4.11.1 BF Status Flag
In transmit mode, the BF bit (SSPSTAT register) is set when the CPU writes to SSPBUF and is
cleared when all 8 bits are shifted out.
20.4.11.2 WCOL Status Flag
If the user writes the SSPBUF when a transmit is already in progress (i.e. SSPSR is still shifting
out a data byte), then WCOL is set and the contents of the buffer are unchanged (the write
doesn’t occur).
WCOL must be cleared in software.
20.4.11.3 ACKSTAT Status Flag
In transmit mode, the ACKSTAT bit (SSPCON2 register) is cleared when the slave has sent an
acknowledge (ACK = 0), and is set when the slave does not acknowledge (ACK = 1). A slave
sends an acknowledge when it has recognized its address (including a general call), or when the
slave has properly received its data.
39500 18C Reference Manual.book Page 37 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39520A-page 20-38 2000 Microchip Technology Inc.
Figure 20-25: Master Transmit Flowchart
Idle Mode
Num_Clocks = 0,
Release SDA so
Num_Clocks slave can drive ACK,
Load BRG with
SDA = Current Data bit
Yes
BRG
rollover?
BRG No
No
Yes
Force SCL = 0
= 8?
Yes
No
Yes
BRG
rollover?
No
Force SCL = 1,
Stop BRG
SCL = 1?
Load BRG with
count high time
Rollover?
No
Read SDA and place into
ACKSTAT bit (SSPCON2<6>)
Force SCL = 0,
SCL = 1?
SDA =
Data bit?
No
Yes
Yes
rollover?
No
Yes
Stop BRG,
Force SCL = 1
(Clock Arbitration)
(Clock Arbitration)
Num_Clocks
= Num_Clocks + 1
Bus collision detected
Set BCLIF, hold prescale off,
Yes
No
BF = 1
Force BF = 0
SSPADD<6:0>,
start BRG count,
Load BRG with
SSPADD<6:0>,
start BRG count
SSPADD<6:0>,
Load BRG with
count SCL high time
SSPADD<6:0>,
SDA =
Data bit?
Yes
No
Clear Transmit enable
SCL = 0?
No
Yes
Reset BRG
Write SSPBUF
Set SSPIF
39500 18C Reference Manual.book Page 38 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39520A-page 20-39
Section 20. Master SSP
Master SSP
20
Figure 20-26: I2C Master Mode Waveform (Transmission, 7 or 10-bit Address) SDA SCL SSPIF BF (SSPSTAT<0>) SEN A7 A6 A5 A4 A3 A2 A1 ACK = 0 D7 D6 D5 D4 D3 D2 D1 D0 ACK Transmitting data or second half Transmit Address to Slave R/W = 0 123456789 123456789 P Cleared in software service routine SSPBUF is written in software From SSP interrupt After Start condition, SEN bit cleared by hardware
S
SSPBUF written with 7-bit address and R/W.
Start transmit
SCL held low
while CPU
responds to SSPIF
SEN = 0
of 10-bit address
Write SSPCON2<0> SEN = 1
Start condition begins From Slave, clear ACKSTAT bit SSPCON2<6>
ACKSTAT in
SSPCON2 = 1
Cleared in software
SSPBUF written
PEN
Cleared in software
R/W
39500 18C Reference Manual.book Page 39 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39520A-page 20-40 2000 Microchip Technology Inc.
20.4.12 I2C Master Mode Reception
Master Mode reception is enabled by programming the receive enable bit, RCEN (SSPCON2
register).
The baud rate generator begins counting, and on each rollover, the state of the SCL pin changes
(high to low/low to high) and data is shifted into the SSPSR. After the falling edge of the eighth
clock, the receive enable flag is automatically cleared, the contents of the SSPSR are loaded into
the SSPBUF, the BF flag bit is set, the SSPIF flag bit is set, and the baud rate generator is suspended
from counting, holding SCL low. The MSSP is now in idle state, awaiting the next command.
When the buffer is read by the CPU, the BF flag bit is automatically cleared. The user can
then send an acknowledge bit at the end of reception by setting the acknowledge sequence
enable bit, ACKEN (SSPCON2 register).
20.4.12.1 BF Status Flag
In receive mode, the BF bit is set when an address or data byte is loaded into SSPBUF from
SSPSR. It is cleared when the SSPBUF Register is read.
20.4.12.2 SSPOV Status Flag
In receive mode, the SSPOV bit is set when 8 bits are received into the SSPSR, and the BF flag
bit is already set from a previous reception.
20.4.12.3 WCOL Status Flag
If the user writes the SSPBUF when a receive is already in progress (i.e., SSPSR is still shifting
in a data byte), then the WCOL bit is set and the contents of the buffer are unchanged (the write
doesn’t occur).
Note: The MSSP module must be in an idle state before the RCEN bit is set, or the RCEN
bit will be disregarded.
39500 18C Reference Manual.book Page 40 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39520A-page 20-41
Section 20. Master SSP
Master SSP
20
Figure 20-27: Master Receiver Flowchart
Idle Mode
Num_Clocks = 0,
Release SDA
Force SCL=0,
Yes
BRG No
rollover?
Release SCL
Yes
No SCL = 1?
Load BRG with
Yes
BRG No
rollover?
(Clock Arbitration)
Load BRG w/
start count
SSPADD<6:0>,
start count
Sample SDA pin,
Shift data into SSPSR
Num_Clocks
= Num_Clocks + 1
Yes
Num_Clocks
= 8?
No
Force SCL = 0,
Set SSPIF bit,
Set BF bit.
Move contents of SSPSR
into SSPBUF,
Clear RCEN
RCEN = 1
SSPADD<6:0>,
SCL = 0?
Yes
No
39500 18C Reference Manual.book Page 41 Monday, July 10, 2000 6:12 PM
DS39520A-page 20-42
PIC18C Reference Manual
2000 Microchip Technology Inc.
Figure 20-28: I2C Master Mode Waveform (Reception 7-Bit Address)
P 5 6 7 8 9
D7 D6 D5 D4 D3 D2 D1 D0
S
SDA A7 A6 A5 A4 A3 A2 A1
SCL 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1234
Bus Master
terminates
transfer
ACK
Receiving Data from Slave Receiving Data from Slave
ACK D7 D6 D5 D4 D3 D2 D1 D0
R/W = 1
Transmit Address to Slave
SSPIF
BF
ACK is not sent
Write to SSPCON2<0> (SEN = 1)
Write to SSPBUF occurs here
ACK from Slave
Master configured as a receiver
SSPCON2<3>, (RCEN = 1) PEN bit = 1
written here
Data shifted in on falling edge
Cleared in software
Start transmit
SEN = 0
SSPOV
SDA = 0, SCL = 1
(SSPSTAT<0>)
ACK
Last bit is shifted into SSPSR and
contents are unloaded into SSPBUF
Cleared in software
Cleared in software
Set SSPIF interrupt
at end of receive
Set P bit
(SSPSTAT<4>)
and SSPIF
Cleared in software
ACK from Master
Set SSPIF at end
Set SSPIF interrupt at end of acknowledge
sequence
Set SSPIF interrupt at end of acknowledge
sequence of receive
Set ACKEN, start acknowledge sequence
SSPOV is set because
SSPBUF is still full
SDA = ACKDT = 1
RCEN cleared
automatically RCEN = 1 start next receive
Write to SSPCON2<4>
to start acknowledge sequence
SDA = ACKDT (SSPCON2<5>) = 0
RCEN cleared automatically
responds to SSPIF
ACKEN
Begin Start condition
Cleared in software
SDA = ACKDT = 0
by programming
of CLK
while CPU
39500 18C Reference Manual.book Page 42 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39520A-page 20-43
Section 20. Master SSP
Master SSP
20
20.4.13 Acknowledge Sequence Timing
An acknowledge sequence is enabled by setting the acknowledge sequence enable bit, ACKEN
(SSPCON2 register). When this bit is set, the SCL pin is pulled low and the contents of the
acknowledge data bit is presented on the SDA pin. If the user wishes to generate an acknowledge,
then the ACKDT bit should be cleared. If not, the user should set the ACKDT bit before
starting an acknowledge sequence. The baud rate generator then counts for one rollover period
(TBRG), and the SCL pin is de-asserted (pulled high). When the SCL pin is sampled high (clock
arbitration), the baud rate generator counts for TBRG. The SCL pin is then pulled low. Following
this, the ACKEN bit is automatically cleared, the baud rate generator is turned off, and the MSSP
module then goes into idle mode (Figure 20-29).
20.4.13.1 WCOL Status Flag
If the user writes the SSPBUF when an acknowledge sequence is in progress, then WCOL is set
and the contents of the buffer are unchanged (the write doesn’t occur).
Figure 20-29: Acknowledge Sequence Waveform
SDA
SCL
Set SSPIF at the end
Acknowledge sequence starts here,
Write to SSPCON2 ACKEN bit automatically cleared
Cleared in
TBRG TBRG
of receive
ACK
8
ACKEN = 1, ACKDT = 0
D0
9
SSPIF
software
Set SSPIF at the end
of acknowledge sequence
Cleared in
software
Note: TBRG = one baud rate generator period.
39500 18C Reference Manual.book Page 43 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39520A-page 20-44 2000 Microchip Technology Inc.
Figure 20-30: Acknowledge Flowchart
Idle Mode
Force SCL = 0
Yes
No SCL = 0?
Drive ACKDT bit
Yes
No BRG
rollover?
(SSPCON2<5>)
onto SDA pin,
Load BRG with
SSPADD<6:0>,
start count
Force SCL = 1
Yes
No SCL = 1?
No ACKDT = 1?
Load BRG with
No
BRG
rollover?
SSPADD <6:0>,
start count
No
SDA = 1?
Bus collision detected,
Set BCLIF,
Yes
Force SCL = 0,
(Clock Arbitration)
Clear ACKEN
No
SCL = 0? Reset BRG Clear ACKEN
Set ACKEN
Release SCL,
Yes
Yes
Yes
Set SSPIF
39500 18C Reference Manual.book Page 44 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39520A-page 20-45
Section 20. Master SSP
Master SSP
20
20.4.14 Stop Condition Timing
A Stop bit is asserted on the SDA pin at the end of a receive/transmit by setting the Stop
sequence enable bit, PEN (SSPCON2 register). At the end of a receive/transmit, the SCL pin is
held low after the falling edge of the ninth clock. When the PEN bit is set, the master will assert
the SDA line low. When the SDA line is sampled low, the baud rate generator is reloaded and
counts down to 0. When the baud rate generator times out, the SCL pin will be brought high, and
one TBRG (baud rate generator rollover count) later, the SDA pin will be de-asserted. When the
SDA pin is sampled high while the SCL pin is high, the P bit (SSPSTAT register) is set. A TBRG
later, the PEN bit is cleared and the SSPIF bit is set (Figure 20-31).
Whenever the firmware decides to take control of the bus, it will first determine if the bus is busy
by checking the S and P bits in the SSPSTAT Register. If the bus is busy, then the CPU can be
interrupted (notified) when a Stop bit is detected (i.e., bus is free).
20.4.14.1 WCOL Status Flag
If the user writes the SSPBUF when a Stop sequence is in progress, then the WCOL bit is set
and the contents of the buffer are unchanged (the write doesn’t occur).
Figure 20-31: Stop Condition Receive or Transmit Mode
SCL
SDA
SDA asserted low before rising edge of clock
Write to SSPCON2
Set PEN
Falling edge of
SCL = 1 for TBRG, followed by SDA = 1 for TBRG
9th clock
SCL brought high after TBRG
TBRG TBRG
after SDA sampled high. P bit (SSPSTAT<4>) is set
TBRG
to setup STOP condition.
ACK
P
TBRG
PEN bit (SSPCON2<2>) is cleared by
hardware and the SSPIF bit is set
Note: TBRG = one baud rate generator period.
39500 18C Reference Manual.book Page 45 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39520A-page 20-46 2000 Microchip Technology Inc.
Figure 20-32: Stop Condition Flowchart
Idle Mode,
SSPEN = 1,
Force SDA = 0
SCL doesn’t change
SDA = 0?
De-assert SCL,
SCL = 1
SCL = 1?
No
Yes
Start BRG
No
Yes
BRG
SDA going from
0 to 1 while SCL = 1,
No
Yes
Set SSPIF,
Release SDA,
Start BRG
Stop condition done
SSPCON1<3:0>=1000
rollover?
BRG No
rollover?
Yes
P bit set?
No
Yes
Bus Collision detected,
Set BCLIF,
Clear PEN
Start BRG
No
Yes
BRG
rollover?
(Clock Arbitration)
PEN = 1
PEN cleared
39500 18C Reference Manual.book Page 46 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39520A-page 20-47
Section 20. Master SSP
Master SSP
20
20.4.15 Clock Arbitration
Clock arbitration occurs when the master, during any receive, transmit, or Repeated Start/Stop
condition de-asserts the SCL pin (SCL allowed to float high). When the SCL pin is allowed to float
high, the baud rate generator (BRG) is suspended from counting until the SCL pin is actually
sampled high. When the SCL pin is sampled high, the baud rate generator is reloaded with the
contents of SSPADD<6:0> and begins counting. This ensures that the SCL high time will always
be at least one BRG rollover count in the event that the clock is held low by an external device
(Figure 20-33).
Figure 20-33: Clock Arbitration Timing in Master Transmit Mode
20.4.15.1 Sleep Operation
While in sleep mode, the I2C module can receive addresses or data. When an address match or
complete byte transfer occurs, the processor will wake-up from sleep (if the MSSP interrupt is
enabled).
20.4.15.2 Effect of a Reset
A reset disables the MSSP module and terminates the current transfer.
SCL
SDA
BRG overflow,
Release the SCL pin,
If SCL = 1 Load BRG with
SSPADD<6:0>, and start count BRG overflow occurs,
Release SCL, slave device holds the SCL pin low. SCL = 1 BRG starts counting
clock high interval.
SCL line sampled once every machine cycle (TOSC • 4).
Hold off BRG until SCL is sampled high
TBRG TBRG TBRG
to measure high time interval
39500 18C Reference Manual.book Page 47 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39520A-page 20-48 2000 Microchip Technology Inc.
20.4.16 Multi-Master Communication, Bus Collision, and Bus Arbitration
Multi-Master Mode support is achieved by bus arbitration. When the master outputs address/data
bits onto the SDA pin, arbitration takes place when the master outputs a '1' on SDA by letting SDA
float high and another master asserts a '0'. When the SCL pin floats high, data should be stable.
If the expected data on SDA is a '1' and the data sampled on the SDA pin = '0', then a bus collision
has taken place. The master will set the Bus Collision Interrupt Flag, BCLIF and reset the I2C
port to its idle state. (Figure 20-34).
If a transmit was in progress when the bus collision occurred, the transmission is halted, the BF
flag is cleared, the SDA and SCL pins are de-asserted, and the SSPBUF can be written to. When
the user services the bus collision interrupt service routine, and if the I2C bus is free, the user
can resume communication by asserting a Start condition.
If a Start, Repeated Start, Stop, or Acknowledge condition was in progress when the bus collision
occurred, the condition is aborted, the SDA and SCL lines are de-asserted, and the respective
control bits in the SSPCON2 Register are cleared. When the user services the bus collision interrupt
service routine, and if the I2C bus is free, the user can resume communication by asserting
a Start condition.
The Master will continue to monitor the SDA and SCL pins, and if a Stop condition occurs, the
SSPIF bit will be set.
A write to the SSPBUF will start the transmission of data at the first data bit, regardless of where
the transmitter left off when bus collision occurred.
In multi-Master Mode, the interrupt generation on the detection of Start and Stop conditions
allows the determination of when the bus is free. Control of the I2C bus can be taken when the P
bit is set in the SSPSTAT Register, or the bus is idle and the S and P bits are cleared.
Figure 20-34: Bus Collision Timing for Transmit and Acknowledge
SDA
SCL
BCLIF
SDA released
SDA line pulled low
by another source
data doesn’t match what is driven
Bus collision has occurred
Set bus collision
interrupt (BCLIF)
by the Master.
by Master
Data changes
while SCL = 0
While the SCL pin is high
39500 18C Reference Manual.book Page 48 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39520A-page 20-49
Section 20. Master SSP
Master SSP
20
20.4.16.1 Bus Collision During a Start Condition
During a Start condition, a bus collision occurs if:
a) SDA or SCL pins are sampled low at the beginning of the Start condition (Figure 20-35).
b) SCL pins are sampled low before the SDA pin is asserted low (Figure 20-36).
During a Start condition both the SDA and the SCL pins are monitored.
If one of the following conditions exists:
• the SDA pin is already low
• or the SCL pin is already low,
Then, the following actions occur:
• the Start condition is aborted,
• the BCLIF bit is set,
• the MSSP module is reset to its idle state (Figure 20-35).
The Start condition begins with the SDA and SCL pins de-asserted. When the SDA pin is sampled
high, the baud rate generator is loaded from SSPADD<6:0> and counts down to O. If the
SCL pin is sampled low while SDA is high, a bus collision occurs, because it is assumed that
another master is attempting to drive a data '1' during the Start condition.
If the SDA pin is sampled low during this count, the BRG is reset and the SDA line is asserted
early (Figure 20-37). If however a '1' is sampled on the SDA pin, the SDA pin is asserted low at
the end of the BRG count. The baud rate generator is then reloaded and counts down to O. During
this time, if the SCL pins is sampled as '0', a bus collision does not occur. At the end of the
BRG count the SCL pin is asserted low.
Figure 20-35: Bus Collision During Start Condition (SDA only)
Note: The reason that bus collision is not a factor during a Start condition is that no two bus
masters can assert a Start condition at the exact same time. Therefore, one master
will always assert SDA before the other. This condition does not cause a bus collision
because the two masters must be allowed to arbitrate the first address following the
Start condition, and if the address is the same, arbitration must be allowed to continue
into the data portion, Repeated Start, or Stop conditions.
SDA
SCL
SEN
SDA sampled low before
SDA goes low before the SEN bit is set.
S bit and SSPIF set because SDA = 0, SCL = 1
SSP module reset into idle state
SEN cleared automatically because of bus collision.
S bit and SSPIF set because
Set SEN, enable Start
condition if SDA = 1, SCL=1
BCLIF
S
SSPIF
SDA = 0, SCL = 1
SSPIF and BCLIF are
cleared in software
SSPIF and BCLIF are
cleared in software
Set BCLIF,
START condition; Set BCLIF
39500 18C Reference Manual.book Page 49 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39520A-page 20-50 2000 Microchip Technology Inc.
Figure 20-36: Bus Collision During Start Condition (SCL = 0)
Figure 20-37: BRG Reset Due to SDA Arbitration During Start Condition
SDA
SCL
SEN Bus collision occurs, Set BCLIF
SCL = 0 before SDA = 0,
Set SEN, enable start
sequence if SDA = 1, SCL = 1
TBRG TBRG
SDA = 0, SCL = 1
BCLIF
S
SSPIF
Interrupt cleared
in software
Bus collision occurs, Set BCLIF
SCL = 0 before BRG time out,
'0' '0'
'0' '0'
SDA
SCL
SEN
Set S
Set SEN, enable START
sequence if SDA = 1, SCL = 1
Less than TBRG TBRG
SDA = 0, SCL = 1
BCLIF
S
SSPIF
s
Interrupts cleared
Set SSPIF in software
SDA = 0, SCL = 1
SDA pulled low by other Master.
Reset BRG and assert SDA
SCL pulled low after BRG
Timeout
Set SSPIF
'0'
39500 18C Reference Manual.book Page 50 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39520A-page 20-51
Section 20. Master SSP
Master SSP
20
20.4.16.2 Bus Collision During a Repeated Start Condition
During a Repeated Start condition, a bus collision occurs if:
a) A low level is sampled on SDA when SCL goes from low level to high level.
b) SCL goes low before SDA is asserted low, indicating that another master is attempting to
transmit a data ’1’.
When the user de-asserts SDA and the pin is allowed to float high, the BRG is loaded with
SSPADD<6:0> and counts down to 0. The SCL pin is then de-asserted, and when sampled high,
the SDA pin is sampled.
If SDA is low, a bus collision has occurred (i.e., another master, is attempting to transmit a data
’0’). If the SDA pin is sampled high, then the BRG is reloaded and begins counting. If the SDA
pin goes from high to low before the BRG times out, no bus collision occurs because no two masters
can assert SDA at exactly the same time, (Figure 20-38).
If the SCL pin goes from high to low before the BRG times out and the SDA pin has not already
been asserted, then a bus collision occurs. In this case, another master is attempting to transmit
a data ’1’ during the Repeated Start condition, (Figure 20-39).
If at the end of the BRG time-out, both the SCL and SDA pins are still high, the SDA pin is driven
low and the BRG is reloaded and begins counting. At the end of the count, regardless of the status
of the SCL pin, the SCL pin is driven low and the Repeated Start condition is complete.
Figure 20-38: Bus Collision During a Repeated Start Condition (Case 1)
Figure 20-39: Bus Collision During Repeated Start Condition (Case 2)
SDA
SCL
RSEN
BCLIF
S
SSPIF
Sample SDA when SCL goes high.
If SDA = 0, set BCLIF and release SDA and SCL
Cleared in software
'0'
'0'
SDA
SCL
BCLIF
RSEN
S
SSPIF
Interrupt cleared
in software
SCL pin goes low before SDA pin,
Set BCLIF, Release SDA and SCL pins
TBRG TBRG
'0'
39500 18C Reference Manual.book Page 51 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39520A-page 20-52 2000 Microchip Technology Inc.
20.4.16.3 Bus Collision During a Stop Condition
Bus collision occurs during a Stop condition if:
a) After the SDA pin has been de-asserted and allowed to float high, SDA is sampled low
after the BRG has timed out.
b) After the SCL pin is de-asserted, SCL is sampled low before SDA goes high.
The Stop condition begins with SDA asserted low. When SDA is sampled low, the SCL pin is
allow to float. When the pin is sampled high (clock arbitration), the baud rate generator is loaded
with SSPADD<6:0> and counts down to 0. After the BRG times out, SDA is sampled. If SDA is
sampled low, a bus collision has occurred. This is due to another master attempting to drive a
data '0' (Figure 20-40). If the SCL pin is sampled low before SDA is allowed to float high, a bus
collision occurs. This is another case of another master attempting to drive a data '0'
(Figure 20-41).
Figure 20-40: Bus Collision During a Stop Condition (Case 1)
Figure 20-41: Bus Collision During a Stop Condition (Case 2)
SDA
SCL
BCLIF
PEN
P
SSPIF
TBRG TBRG TBRG
SDA asserted low
SDA sampled
low after TBRG,
Set BCLIF
'0'
'0'
SDA
SCL
BCLIF
PEN
P
SSPIF
TBRG TBRG TBRG
Assert SDA SCL goes low before SDA goes high
Set BCLIF
'0'
'0'
39500 18C Reference Manual.book Page 52 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39520A-page 20-53
Section 20. Master SSP
Master SSP
20
20.4.17 Connection Considerations for I2C Bus
For standard-mode I2C bus devices, the values of resistors Rp and Rs in Figure 20-42 depend
on the following parameters:
• Supply voltage
• Bus capacitance
• Number of connected devices (input current + leakage current)
The supply voltage limits the minimum value of resistor Rp due to the specified minimum sink
current of 3 mA at VOLMAX = 0.4V for the specified output stages. For example, with a supply voltage
of VDD = 5V+10% and VOLMAX = 0.4V at 3 mA, RPMIN = (5.5-0.4)/0.003 = 1.7 kΩ. VDD as a
function of Rp is shown in Figure 20-42. The desired noise margin of 0.1VDD for the low level.
This limits the maximum value of Rs. Series resistors are optional, and used to improve ESD susceptibility.
The bus capacitance is the total capacitance of wire, connections, and pins. This capacitance
limits the maximum value of Rp due to the specified rise time (Figure 20-42).
The SMP bit is the slew rate control enabled bit. This bit is in the SSPSTAT Register, and controls
the slew rate of the I/O pins when in I2C mode (master or slave).
Figure 20-42: Sample Device Configuration for I2C Bus
RP RP
VDD + 10%
SDA
SCL
DEVICE
CB = 10 - 400 pF
RS RS
Note: I
2C devices with input levels related to VDD must have one common supply line
to which the pull up resistor is also connected.
39500 18C Reference Manual.book Page 53 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39520A-page 20-54 2000 Microchip Technology Inc.
20.4.18 Initialization
Example 20-2: SPI Master Mode Initialization
20.4.19 Master SSP Module / Basic SSP Module Compatibility
When changing from the SPI in the Mid-range Family Basic SSP module, the SSPSTAT Register
contains two additional control bits. These bits are:
• SMP, SPI data input sample phase
• CKE, SPI Clock Edge Select
To be compatible with the SPI of the Master SSP module, these bits must be appropriately configured.
If these bits are not at the states shown in Table 20-5, improper SPI communication may
occur.
Table 20-5: New bit States for Compatibility
CLRF STATUS ; Bank 0
CLRF SSPSTAT ; SMP = 0, CKE = 0, and
; clear status bits
BSF SSPSTAT, CKE ; CKE = 1
MOVLW 0x31 ; Set up SPI port, Master Mode, CLK/16,
MOVWF SSPCON ; Data xmit on falling edge
; (CKE=1 & CKP=1)
; Data sampled in middle
; (SMP=0 & Master Mode)
BSF PIE, SSPIE ; Enable SSP interrupt
BSF INTCON, GIE ; Enable, enabled interrupts
MOVLW DataByte ; Data to be Transmitted
; Could move data from RAM location
MOVWF SSPBUF ; Start Transmission
Basic SSP Module Master SSP Module
CKP CKP CKE SMP
1 100
0 000
39500 18C Reference Manual.book Page 54 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39520A-page 20-55
Section 20. Master SSP
Master SSP
20
20.5 Design Tips
Question 1: Using SPI mode, I do not seem able to talk to an SPI device.
Answer 1:
Ensure that you are using the correct SPI mode for that device. This SPI supports all 4 SPI
modes so you should be able to get it to function. Check the clock polarity and the clock phase.
Question 2: Using I2C mode, I write data to the SSPBUF Register, but the data did not
transmit.
Answer 2:
Ensure that you set the CKP bit to release the I2C clock.
39500 18C Reference Manual.book Page 55 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39520A-page 20-56 2000 Microchip Technology Inc.
20.6 Related Application Notes
This section lists application notes that are related to this section of the manual. These application
notes may not be written specifically for the Enhanced family (that is they may be written for
the Baseline, the Midrange, or High-end families), but the concepts are pertinent, and could be
used (with modification and possible limitations). The current application notes related to the
Master SSP modules are:
Title Application Note #
Use of the SSP Module in the I 2C Multi-Master Environment. AN578
Using Microchip 93 Series Serial EEPROMs with Microcontroller SPI Ports AN613
Interfacing PIC16C64/74 to Microchip SPI Serial EEPROM AN647
Interfacing a Microchip PIC16C92x to Microchip SPI Serial EEPROM AN668
Note: Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
http://www.microchip.com/10/faqs/codeex/
39500 18C Reference Manual.book Page 56 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39520A-page 20-57
Section 20. Master SSP
Master SSP
20
20.7 Revision History
Revision A
This is the initial released revision of the Enhanced MCU Master SSP module description.
39500 18C Reference Manual.book Page 57 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39520A-page 20-58 2000 Microchip Technology Inc.
39500 18C Reference Manual.book Page 58 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39521A-page 21-1
Addressable
USART
21
Section 21. Addressable USART
HIGHLIGHTS
This section of the manual contains the following major topics:
21.1 Introduction .................................................................................................................. 21-2
21.2 Control Registers ......................................................................................................... 21-3
21.3 USART Baud Rate Generator (BRG)........................................................................... 21-5
21.4 USART Asynchronous Mode ....................................................................................... 21-9
21.5 USART Synchronous Master Mode........................................................................... 21-18
21.6 USART Synchronous Slave Mode ............................................................................. 21-23
21.7 Initialization ................................................................................................................ 21-25
21.8 Design Tips ................................................................................................................ 21-26
21.9 Related Application Notes.......................................................................................... 21-27
21.10 Revision History ......................................................................................................... 21-28
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39521A-page 21-2 2000 Microchip Technology Inc.
21.1 Introduction
The Addressable Universal Synchronous Asynchronous Receiver Transmitter (Addressable
USART) module is one of the serial I/O modules available in the PIC18CXXX family (another is
the MSSP module). The Addressable USART can be configured as a full duplex asynchronous
system that can communicate with peripheral devices, such as CRT terminals and personal computers,
or it can be configured as a half duplex synchronous system that can communicate with
peripheral devices, such as A/D or D/A integrated circuits, Serial EEPROMs, etc.
The Addressable USART can be configured in the following modes:
• Asynchronous (full duplex)
• Synchronous - Master (half duplex)
• Synchronous - Slave (half duplex)
The SPEN bit (RCSTA register) and the TRIS bits, for the USART’s pins, need to be set in order
to configure the TX/CK and RX/DT pins for the Addressable USART.
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39521A-page 21-3
Section 21. Addressable USART
Addressable
USART
21
21.2 Control Registers
Register 21-1: TXSTA: Transmit Status and Control Register
R/W-0 R/W-0 R/W-0 R/W-0 U-0 R/W-0 R-1 R/W-0
CSRC TX9 TXEN SYNC — BRGH TRMT TX9D
bit 7 bit 0
bit 7 CSRC: Clock Source Select bit
When SYNC = 0 (Asynchronous mode)
Don’t care
When SYNC = 1 (Synchronous mode)
1 = Master mode (Clock generated internally from BRG)
0 = Slave mode (Clock from external source)
bit 6 TX9: 9-bit Transmit Enable bit
1 = Selects 9-bit transmission
0 = Selects 8-bit transmission
bit 5 TXEN: Transmit Enable bit
1 = Transmit enabled
0 = Transmit disabled
Note: The Receive Enable (SREN/CREN) bit overrides Transmit Enable (TXEN) bit in
SYNC mode.
bit 4 SYNC: Addressable USART Mode Select bit
1 = Synchronous mode
0 = Asynchronous mode
bit 3 Unimplemented: Read as '0'
bit 2 BRGH: High Baud Rate Select bit
When SYNC = 0 (Asynchronous mode)
1 = High speed
0 = Low speed
When SYNC = 1 (Synchronous mode)
Unused in this mode
bit 1 TRMT: Transmit Shift Register Status bit
1 = TSR empty
0 = TSR full
bit 0 TX9D: 9th bit of transmit data.
This bit can be used as an address/data bit or a parity bit.
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39521A-page 21-4 2000 Microchip Technology Inc.
Register 21-2: RCSTA: Receive Status and Control Register
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R-0 R-0 R-x
SPEN RX9 SREN CREN ADDEN FERR OERR RX9D
bit 7 bit 0
bit 7 SPEN: Serial Port Enable bit
1 = Serial port enabled (Configures RX/DT and TX/CK pins as serial port pins)
0 = Serial port disabled
bit 6 RX9: 9-bit Receive Enable bit
1 = Selects 9-bit reception
0 = Selects 8-bit reception
bit 5 SREN: Single Receive Enable bit
When SYNC = 0 (Asynchronous mode)
Don’t care
When SYNC = 1 (Synchronous mode) - master
1 = Enables single receive
0 = Disables single receive
This bit is cleared after reception of one byte is complete.
When SYNC = 1 (Synchronous mode) - slave
Unused in this mode
bit 4 CREN: Continuous Receive Enable bit
When SYNC = 0 (Asynchronous mode)
1 = Enables continuous receive
0 = Disables continuous receive
When SYNC = 1 (Synchronous mode)
1 = Enables continuous receive (CREN overrides SREN)
0 = Disables continuous receive
bit 3 ADDEN: Address Detect Enable bit
When SYNC = 0 (Asynchronous mode) with RX9 = 1 (9-bit receive enabled)
1 = Enables address detection, enable interrupt and loads of the receive buffer
when RSR<8> is set
0 = Disables address detection, all bytes are received, and ninth bit can be used as parity bit
When SYNC = 0 (Asynchronous mode) with RX9 = 0 (9-bit receive disabled)
Don’t care
When SYNC = 1 (Synchronous mode)
Don’t care
bit 2 FERR: Framing Error bit
1 = Framing error (Can be updated by reading RCREG register and receive next valid byte)
0 = No framing error
bit 1 OERR: Overrun Error bit
1 = Overrun error (Can be cleared by clearing bit CREN)
0 = No overrun error
bit 0 RX9D: 9th bit of received data. Can be address/data bit or a parity bit.
1 = Ninth received bit was ’1’
0 = Ninth received bit was ’0’
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39521A-page 21-5
Section 21. Addressable USART
Addressable
USART
21
21.3 USART Baud Rate Generator (BRG)
The BRG supports both the Asynchronous and Synchronous modes of the USART. It is a dedicated
8-bit baud rate generator. The SPBRG register controls the period of a free running 8-bit
timer. In Asynchronous mode, the BRGH bit (TXSTA<2>) also controls the baud rate. In Synchronous
mode, the BRGH bit is ignored. Table 21-1 shows the formula for computation of the baud
rate for different USART modes that only apply in master mode (internal clock).
Given the desired baud rate and FOSC, the nearest integer value for the SPBRG register can be
calculated using the formula in Table 21-1, where X equals the value in the SPBRG register (0 to
255). From this, the error in baud rate can be determined.
Table 21-1: Baud Rate Formula
Example 21-1 shows the calculation of the baud rate error for the following conditions:
FOSC = 16 MHz
Desired Baud Rate = 9600
BRGH = 0
SYNC = 0
Example 21-1:Calculating Baud Rate Error
It may be advantageous to use the high baud rate (BRGH = 1) even for slower baud clocks. This
is because the FOSC / (16(X + 1)) equation can reduce the baud rate error in some cases.
Writing a new value to the SPBRG register causes the BRG timer to be reset (or cleared). This
ensures the BRG does not wait for a timer overflow before outputting the new baud rate.
21.3.1 SAMPLING
The data on the RX/DT pin is sampled three times by a majority detect circuit to determine if a
high or a low level is present at the RX pin. See Section 21.4.4 for additional information.
Table 21-2: Registers Associated with Baud Rate Generator
SYNC BRGH = 0 (Low Speed) BRGH = 1 (High Speed)
0
1
(Asynchronous) Baud Rate = FOSC/(64(X+1))
(Synchronous) Baud Rate = FOSC/(4(X+1))
Baud Rate = FOSC/(16(X+1))
NA
X = value in SPBRG (0 to 255)
Desired Baud Rate = FOSC / (64 (X + 1))
Solving for X:
X = ( (FOSC / Desired Baud Rate) / 64 ) - 1
X = ((16000000 / 9600) / 64) - 1
X = [25.042] = 25
Calculated Baud Rate = 16000000 / (64 (25 + 1))
= 9615
Error = (Calculated Baud Rate - Desired Baud Rate)
Desired Baud Rate
= (9615 - 9600) / 9600
= 0.16%
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Value on:
POR,
BOR
Value on all
other resets
TXSTA CSRC TX9 TXEN SYNC — BRGH TRMT TX9D 0000 -010 0000 -010
RCSTA SPEN RX9 SREN CREN ADDEN FERR OERR RX9D 0000 0000x 0000 000x
SPBRG Baud Rate Generator Register 0000 0000 0000 0000
Legend: x = unknown, - = unimplemented read as '0'. Shaded cells are not used by the BRG.
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39521A-page 21-6 2000 Microchip Technology Inc.
Table 21-3: Baud Rates for Synchronous Mode
BAUD
RATE
(Kbps)
FOSC = 40 MHz SPBRG
value
(decimal)
33 MHz SPBRG
value
(decimal)
25 MHz SPBRG
value
(decimal)
20 MHz SPBRG
value
(decimal) KBAUD
%
ERROR KBAUD
%
ERROR KBAUD
%
ERROR KBAUD
%
ERROR
0.3 NA - - NA - - NA - - NA - -
1.2 NA - - NA - - NA - - NA - -
2.4 NA - - NA - - NA - - NA - -
9.6 NA - - NA - - NA - - NA - -
19.2 NA - - NA - - NA - - NA - -
76.8 76.92 +0.16 129 77.10 +0.39 106 77.16 +0.47 80 76.92 +0.16 64
96 96.15 +0.16 103 95.93 -0.07 85 96.15 +0.16 64 96.15 +0.16 51
300 303.03 +1.01 32 294.64 -1.79 27 297.62 -0.79 20 294.12 -1.96 16
500 500 0 19 485.30 -2.94 16 480.77 -3.85 12 500 0 9
HIGH 10000 - 0 8250 - 0 6250 - 0 5000 - 0
LOW 39.06 - 255 32.23 - 255 24.41 - 255 19.53 - 255
BAUD
RATE
(Kbps)
FOSC = 16 MHz SPBRG
value
(decimal)
10 MHz SPBRG
value
(decimal)
7.15909 MHz SPBRG
value
(decimal)
5.0688 MHz SPBRG
value
(decimal) KBAUD
%
ERROR KBAUD
%
ERROR KBAUD
%
ERROR KBAUD
%
ERROR
0.3 NA - - NA - - NA - - NA - -
1.2 NA - - NA - - NA - - NA - -
2.4 NA - - NA - - NA - - NA - -
9.6 NA - - NA - - 9.62 +0.23 185 9.60 0 131
19.2 19.23 +0.16 207 19.23 +0.16 129 19.24 +0.23 92 19.20 0 65
76.8 76.92 +0.16 51 75.76 -1.36 32 77.82 +1.32 22 74.54 -2.94 16
96 95.24 -0.79 41 96.15 +0.16 25 94.20 -1.88 18 97.48 +1.54 12
300 307.70 +2.56 12 312.50 +4.17 7 298.35 -0.57 5 316.80 +5.60 3
500 500 0 7 500 0 4 447.44 -10.51 3 422.40 -15.52 2
HIGH 4000 - 0 2500 - 0 1789.80 - 0 1267.20 - 0
LOW 15.63 - 255 9.77 - 255 6.99 - 255 4.95 - 255
BAUD
RATE
(Kbps)
FOSC = 4 MHz SPBRG
value
(decimal)
3.579545 MHz SPBRG
value
(decimal)
1 MHz SPBRG
value
(decimal)
32.768 kHz SPBRG
value
(decimal) KBAUD
%
ERROR KBAUD
%
ERROR KBAUD
%
ERROR KBAUD
%
ERROR
0.3 NA - - NA - - NA - - 0.30 +1.14 26
1.2 NA - - NA - - 1.20 +0.16 207 1.17 -2.48 6
2.4 NA - - NA - - 2.40 +0.16 103 2.73 +13.78 2
9.6 9.62 +0.16 103 9.62 +0.23 92 9.62 +0.16 25 8.20 -14.67 0
19.2 19.23 +0.16 51 19.04 -0.83 46 19.23 +0.16 12 NA - -
76.8 76.92 +0.16 12 74.57 -2.90 11 83.33 +8.51 2 NA - -
96 1000 +4.17 9 99.43 +3.57 8 83.33 -13.19 2 NA - -
300 333.33 +11.11 2 298.30 -0.57 2 250 -16.67 0 NA - -
500 500 0 1 447.44 -10.51 1 NA - - NA - -
HIGH 1000 - 0 894.89 - 0 250 - 0 8.20 - 0
LOW 3.91 - 255 3.50 - 255 0.98 - 255 0.03 - 255
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39521A-page 21-7
Section 21. Addressable USART
Addressable
USART
21
Table 21-4: Baud Rates for Asynchronous Mode (BRGH = 0)
BAUD
RATE
(Kbps)
FOSC = 40 MHz SPBRG
value
(decimal)
33 MHz SPBRG
value
(decimal)
25 MHz SPBRG
value
(decimal)
20 MHz SPBRG
value
(decimal) KBAUD
%
ERROR KBAUD
%
ERROR KBAUD
%
ERROR KBAUD
%
ERROR
0.3 NA - - NA - - NA - - NA - -
1.2 NA - - NA - - NA - - NA - -
2.4 NA - - 2.40 -0.07 214 2.40 -0.15 162 2.40 +0.16 129
9.6 9.62 +0.16 64 9.55 -0.54 53 9.53 -0.76 40 9.47 -1.36 32
19.2 18.94 -1.36 32 19.10 -0.54 26 19.53 +1.73 19 19.53 +1.73 15
76.8 78.13 +1.73 7 73.66 -4.09 6 78.13 +1.73 4 78.13 +1.73 3
96 89.29 -6.99 6 103.13 +7.42 4 97.66 +1.73 3 104.17 +8.51 2
300 312.50 +4.17 1 257.81 -14.06 1 NA - - 312.50 +4.17 0
500 625 +25.00 0 NA - - NA - - NA - -
HIGH 625 - 0 515.63 - 0 390.63 - 0 312.50 - 0
LOW 2.44 - 255 2.01 - 255 1.53 - 255 1.22 - 255
BAUD
RATE
(Kbps)
FOSC = 16 MHz SPBRG
value
(decimal)
10 MHz SPBRG
value
(decimal)
7.15909 MHz SPBRG
value
(decimal)
5.0688 MHz SPBRG
value
(decimal) KBAUD
%
ERROR KBAUD
%
ERROR KBAUD
%
ERROR KBAUD
%
ERROR
0.3 NA - - NA - - NA - - NA - -
1.2 1.20 +0.16 207 1.20 +0.16 129 1.20 +0.23 92 1.20 0 65
2.4 2.40 +0.16 103 2.40 +0.16 64 2.38 -0.83 46 2.40 0 32
9.6 9.62 +0.16 25 9.77 +1.73 15 9.32 -2.90 11 9.90 +3.13 7
19.2 19.23 +0.16 12 19.53 +1.73 7 18.64 -2.90 5 19.80 +3.13 3
76.8 83.33 +8.51 2 78.13 +1.73 1 111.86 +45.65 0 79.20 +3.13 0
96 83.33 -13.19 2 78.13 -18.62 1 NA - - NA - -
300 250 -16.67 0 156.25 -47.92 0 NA - - NA - -
500 NA - - NA - - NA - - NA - -
HIGH 250 - 0 156.25 - 0 111.86 - 0 79.20 - 0
LOW 0.98 - 255 0.61 - 255 0.44 - 255 0.31 - 255
BAUD
RATE
(Kbps)
FOSC = 4 MHz SPBRG
value
(decimal)
3.579545 MHz SPBRG
value
(decimal)
1 MHz SPBRG
value
(decimal)
32.768 kHz SPBRG
value
(decimal) KBAUD
%
ERROR KBAUD
%
ERROR KBAUD
%
ERROR KBAUD
%
ERROR
0.3 0.30 -0.16 207 0.30 +0.23 185 0.30 +0.16 51 0.26 -14.67 1
1.2 1.20 +1.67 51 1.19 -0.83 46 1.20 +0.16 12 NA - -
2.4 2.40 +1.67 25 2.43 +1.32 22 2.23 -6.99 6 NA - -
9.6 8.93 -6.99 6 9.32 -2.90 5 7.81 -18.62 1 NA - -
19.2 20.83 +8.51 2 18.64 -2.90 2 15.63 -18.62 0 NA - -
76.8 62.50 -18.62 0 55.93 -27.17 0 NA - - NA - -
96 NA - - NA - - NA - - NA - -
300 NA - - NA - - NA - - NA - -
500 NA - - NA - - NA - - NA - -
HIGH 62.50 - 0 55.93 - 0 15.63 - 0 0.51 - 0
LOW 0.24 - 255 0.22 - 255 0.06 - 255 0.002 - 255
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39521A-page 21-8 2000 Microchip Technology Inc.
Table 21-5: Baud Rates for Asynchronous Mode (BRGH = 1)
BAUD
RATE
(Kbps)
FOSC = 40 MHz SPBRG
value
(decimal)
33 MHz SPBRG
value
(decimal)
25 MHz SPBRG
value
(decimal)
20 MHz SPBRG
value
(decimal) KBAUD
%
ERROR KBAUD
%
ERROR KBAUD
%
ERROR KBAUD
%
ERROR
0.3 NA - - NA - - NA - - NA - -
1.2 NA - - NA - - NA - - NA - -
2.4 NA - - NA - - NA - - NA - -
9.6 NA - - 9.60 -0.07 214 9.59 -0.15 162 9.62 +0.16 129
19.2 19.23 +0.16 129 19.28 +0.39 106 19.30 +0.47 80 19.23 +0.16 64
76.8 75.76 -1.36 32 76.39 -0.54 26 78.13 +1.73 19 78.13 +1.73 15
96 96.15 +0.16 25 98.21 +2.31 20 97.66 +1.73 15 96.15 +0.16 12
300 312.50 +4.17 7 294.64 -1.79 6 312.50 +4.17 4 312.50 +4.17 3
500 500 0 4 515.63 +3.13 3 520.83 +4.17 2 416.67 -16.67 2
HIGH 2500 - 0 2062.50 - 0 1562.50 - 0 1250 - 0
LOW 9.77 - 255 8,06 - 255 6.10 - 255 4.88 - 255
BAUD
RATE
(Kbps)
FOSC = 16 MHz SPBRG
value
(decimal)
10 MHz SPBRG
value
(decimal)
7.15909 MHz SPBRG
value
(decimal)
5.0688 MHz SPBRG
value
(decimal) KBAUD
%
ERROR KBAUD
%
ERROR KBAUD
%
ERROR KBAUD
%
ERROR
0.3 NA - - NA - - NA - - NA - -
1.2 NA - - NA - - NA - - NA - -
2.4 NA - - NA - - 2.41 +0.23 185 2.40 0 131
9.6 9.62 +0.16 103 9.62 +0.16 64 9.52 -0.83 46 9.60 0 32
19.2 19.23 +0.16 51 18.94 -1.36 32 19.45 +1.32 22 18.64 -2.94 16
76.8 76.92 +0.16 12 78.13 +1.73 7 74.57 -2.90 5 79.20 +3.13 3
96 100 +4.17 9 89.29 -6.99 6 89.49 -6.78 4 105.60 +10.00 2
300 333.33 +11.11 2 312.50 +4.17 1 447.44 +49.15 0 316.80 +5.60 0
500 500 0 1 625 +25.00 0 447.44 -10.51 0 NA - -
HIGH 1000 - 0 625 - 0 447.44 - 0 316.80 - 0
LOW 3.91 - 255 2.44 - 255 1.75 - 255 1.24 - 255
BAUD
RATE
(Kbps)
FOSC = 4 MHz SPBRG
value
(decimal)
3.579545 MHz SPBRG
value
(decimal)
1 MHz SPBRG
value
(decimal)
32.768 kHz SPBRG
value
(decimal) KBAUD
%
ERROR KBAUD
%
ERROR KBAUD
%
ERROR KBAUD
%
ERROR
0.3 NA - - NA - - 0.30 +0.16 207 0.29 -2.48 6
1.2 1.20 +0.16 207 1.20 +0.23 185 1.20 +0.16 51 1.02 -14.67 1
2.4 2.40 +0.16 103 2.41 +0.23 92 2.40 +0.16 25 2.05 -14.67 0
9.6 9.62 +0.16 25 9.73 +1.32 22 8.93 -6.99 6 NA - -
19.2 19.23 +0.16 12 18.64 -2.90 11 20.83 +8.51 2 NA - -
76.8 NA - - 74.57 -2.90 2 62.50 -18.62 0 NA - -
96 NA - - 111.86 +16.52 1 NA - - NA - -
300 NA - - 223.72 -25.43 0 NA - - NA - -
500 NA - - NA - - NA - - NA - -
HIGH 250 - 0 55.93 - 0 62.50 - 0 2.05 - 0
LOW 0.98 - 255 0.22 - 255 0.24 - 255 0.008 - 255
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39521A-page 21-9
Section 21. Addressable USART
Addressable
USART
21
21.4 USART Asynchronous Mode
In this mode, the USART uses standard nonreturn-to-zero (NRZ) format (one start bit, eight or
nine data bits and one stop bit). The most common data format is 8 bits. An on-chip dedicated
8-bit baud rate generator can be used to derive standard baud rate frequencies from the oscillator.
The USART transmits and receives the LSb first. The USART’s transmitter and receiver are
functionally independent, but use the same data format and baud rate. The baud rate generator
produces a clock either x16 or x64 of the bit shift rate, depending on the BRGH bit (TXSTA register).
Parity is not supported by the hardware, but can be implemented in software (stored as
the ninth data bit). Asynchronous mode is stopped during SLEEP.
Asynchronous mode is selected by clearing the SYNC bit (TXSTA register).
The USART Asynchronous module consists of the following important elements:
• Baud Rate Generator
• Sampling Circuit
• Asynchronous Transmitter
• Asynchronous Receiver
21.4.1 USART Asynchronous Transmitter
The USART transmitter block diagram is shown in Figure 21-1. The heart of the transmitter is the
Transmit Shift Register (TSR). The shift register obtains its data from the transmit buffer, TXREG.
The TXREG register is loaded with data in software. The TSR register is not loaded until the
STOP bit has been transmitted from the previous load. As soon as the STOP bit is transmitted,
the TSR is loaded with new data from the TXREG register (if available). Once the TXREG register
transfers the data to the TSR register (occurs in one TCY), the TXREG register is empty and
the TXIF flag bit is set. This interrupt can be enabled/disabled by setting/clearing the TXIE enable
bit. The TXIF flag bit will be set, regardless of the state of the TXIE enable bit and cannot be
cleared in software. It will reset only when new data is loaded into the TXREG register. While the
TXIF flag bit indicated the status of the TXREG register, the TRMT bit (TXSTA register) shows
the status of the TSR register. The TRMT status bit is a read only bit, which is set when the TSR
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 TSR register is empty.
Transmission is enabled by setting the TXEN enable bit (TXSTA register). The actual transmission
will not occur until the TXREG register has been loaded with data and the Baud Rate Generator
(BRG) has produced a shift clock (Figure 21-1). The transmission can also be started by
first loading the TXREG register and then setting the TXEN enable bit. Normally when transmission
is first started, the TSR register is empty, so a transfer to the TXREG register will result in
an immediate transfer to TSR, resulting in an empty TXREG. A back-to-back transfer is thus possible
(Figure 21-3). Clearing the TXEN enable bit during a transmission will cause the transmission
to be aborted and will reset the transmitter. As a result, the TX/CK pin will revert to
hi-impedance.
In order to select 9-bit transmission the TX9 bit (TXSTA register) should be set and the ninth bit
should be written to the TX9D bit (TXSTA register). The ninth bit must be written before writing
the 8-bit data to the TXREG register. This is because a data write to the TXREG register can
result in an immediate transfer of the data to the TSR register (if the TSR is empty). In such a
case, an incorrect ninth data bit may be loaded in the TSR register.
Note 1: The TSR register is not mapped in data memory, so it is not available to the user.
2: When the TXEN bit is set, the TXIF flag bit will also be set since the transmit buffer
is not yet full (can move transmit data to the TXREG register).
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39521A-page 21-10 2000 Microchip Technology Inc.
Figure 21-1: USART Transmit Block Diagram
Steps to follow when setting up an Asynchronous Transmission:
1. Initialize the SPBRG register for the appropriate baud rate. If a high speed baud rate is
desired, set the BRGH bit. (Subsection 21.3 “USART Baud Rate Generator (BRG)” ).
2. Enable the asynchronous serial port by clearing the SYNC bit and setting the SPEN bit.
3. If interrupts are desired, then set the TXIE, GIE/GIEH and PEIE/GIEL bits. Specify the
interrupt priority if required.
4. If 9-bit transmission is desired, then set the TX9 bit (can be used as address/data bit).
5. Enable the transmission by setting the TXEN bit, which will also set the TXIF bit.
6. If 9-bit transmission is selected, the ninth bit should be loaded in the TX9D bit.
7. Load data to the TXREG register (starts transmission).
Figure 21-2: Asynchronous Transmission (8- or 9-bit Data)
TXIF
TXIE
Interrupt
TXEN Baud Rate CLK
SPBRG
Baud Rate Generator
TX9D
MSb LSb
Data Bus
TXREG register
TSR register
(8) 0
TX9
TRMT SPEN
TX/CK pin
Pin Buffer
and Control
8
• • •
8
WORD 1
Stop Bit
WORD 1
Transmit Shift Reg
Start Bit Bit 0 Bit 1 Bit 7/8
Write to TXREG
Word 1 BRG output
(shift clock)
TX/CK pin
TXIF bit
(Transmit buffer
reg. empty flag)
TRMT bit
(Transmit shift
reg. empty flag)
Write to TX9D
(required for 9-bit Word 1
transmissions)
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39521A-page 21-11
Section 21. Addressable USART
Addressable
USART
21
Figure 21-3: Asynchronous Transmission (Back to Back)
Table 21-6: Registers Associated with Asynchronous Transmission
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Value on
POR,
BOR
Value on
all other
Resets
INTCON GIE/GIEH PEIE/
GIEL
TMR0IE INT0IE RBIE TMR0IF INT0IF RBIF 0000 000x 0000 000u
PIRx TXIF (1) 0 0
PIEx TXIE (1) 0 0
IPRx TXIP (1) 0 0
RCSTA SPEN RX9 SREN CREN ADDEN FERR OERR RX9D 0000 000x 0000 000x
TXREG TX7 TX6 TX5 TX4 TX3 TX2 TX1 TX0 0000 0000 0000 0000
TXSTA CSRC TX9 TXEN SYNC — BRGH TRMT TX9D 0000 -010 0000 -010
SPBRG Baud Rate Generator Register 0000 0000 0000 0000
Legend: x = unknown, - = unimplemented locations read as '0'.
Shaded cells are not used for Asynchronous Transmission.
Note 1: The PSPIF, PSPIE and PSPIP bits are reserved on the PIC18C2X2 devices. Always maintain these bits
clear.
2: The position of this bit is device dependent.
Transmit Shift Reg.
Write to TXREG
BRG output
(shift clock)
TX/CK pin
TXIF bit
(interrupt reg. flag)
TRMT bit
(Transmit shift
reg. empty flag)
Word 1 Word 2
WORD 1 WORD 2
Start Bit Stop Bit Start Bit
Transmit Shift Reg.
WORD 1 WORD 2
Bit 0 Bit 1 Bit 7/8 Bit 0
Note: This timing diagram shows two consecutive transmissions.
39500 18C Reference Manual.book Page 11 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39521A-page 21-12 2000 Microchip Technology Inc.
21.4.2 USART Asynchronous Receiver
The receiver block diagram is shown in Figure 21-4. The data is received on the RX/DT pin and
drives the data recovery block. The data recovery block is actually a high speed shifter operating
at x16 times the baud rate, whereas the main receive serial shifter operates at the bit rate or at
FOSC. This mode would typically be used in RS-232 systems.
The USART module has a special provision for multi-processor communication. When the RX9
bit is set in the RCSTA register, 9-bits are received and the ninth bit is placed in the RX9D status
bit of the RSTA register. The port can be programmed such that when the stop bit is received,
the serial port interrupt will only be activated if the RX9D bit is set. This feature is enabled by
setting the ADDEN bit in the RCSTA register and can be used in a multi-processor system in the
following manner.
To transmit a block of data in a multi-processor system, the master processor must first send an
address byte that identifies the target slave. An address byte is identified by the RX9D bit being
a ‘1’ (instead of a ‘0’ for a data byte). If the ADDEN bit is set in the slave’s RCSTA register, all
data bytes will be ignored. However, if the ninth received bit is equal to a ‘1’, indicating that the
received byte is an address, the slave will be interrupted and the contents of the Receive Shift
Register (RSR) will be transferred into the receive buffer. This allows the slave to be interrupted
only by addresses, so that the slave can examine the received byte to see if it is addressed. The
addressed slave will then clear its ADDEN bit and prepare to receive data bytes from the master.
When the ADDEN bit is set, all data bytes are ignored. Following the STOP bit, the data will not
be loaded into the receive buffer and no interrupt will occur. If another byte is shifted into the
RSR register, the previous data byte will be lost.
The ADDEN bit will only take effect when the receiver is configured in 9-bit mode.
Once Asynchronous mode is selected, reception is enabled by setting the CREN bit.
The heart of the receiver is the Receive (serial) Shift Register (RSR). After sampling the RX/TX
pin for the STOP bit, the received data in the RSR is transferred to the RCREG register (if it is
empty). If the transfer is complete, the RCIF flag bit is set. The actual interrupt can be
enabled/disabled by setting/clearing the RCIE enable bit. The RCIF flag bit is a read only bit that
is cleared by the hardware. It is cleared when the RCREG register has been read and is empty.
The RCREG is a double-buffered register (i.e., it is a two-deep FIFO). It is possible for two bytes
of data to be received and transferred to the RCREG FIFO and a third byte begin shifting to the
RSR register. On the detection of the STOP bit of the third byte, if the RCREG register is still full,
overrun error bit, OERR, will be set. The word in the RSR will be lost. The RCREG register can
be read twice to retrieve the two bytes in the FIFO. The OERR bit has to be cleared in software.
This is done by resetting the receive logic (the CREN bit is cleared and then set). If the OERR
bit is set, transfers from the RSR register to the RCREG register are inhibited, so it is essential
to clear the OERR bit if it is set. Framing error bit, FERR, is set if a stop bit is detected as a low
level. The FERR bit and the 9th receive bit are buffered the same way as the receive data. Reading
the RCREG will load the RX9D and FERR bits with new values. Therefore, it is essential for
the user to read the RCSTA register before reading the next RCREG register, in order not to lose
the old (previous) information in the FERR and RX9D bits.
Figure 21-4 shows a block diagram for the receive of the Addressable USART.
39500 18C Reference Manual.book Page 12 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39521A-page 21-13
Section 21. Addressable USART
Addressable
USART
21
Figure 21-4: Addressable USART Receive Block Diagram
x64 Baud Rate CLK
SPBRG
Baud Rate Generator
RX/DT
Pin Buffer
and Control
SPEN
Data
Recovery
CREN
OERR FERR
MSb LSb RSR Register
RX9D RCREG Register FIFO
Interrupt RCIF
RCIE
Data Bus
8
÷ 64
÷ 16
or
Stop Start (8) 7 1 0
RX9
• • •
RX9
ADDEN
RX9
ADDEN
RSR<8>
Enable
Load of
Receive
Buffer
8
8
39500 18C Reference Manual.book Page 13 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39521A-page 21-14 2000 Microchip Technology Inc.
21.4.2.1 Asynchronous Receptions (no Address Detect)
Steps to follow when setting up an Asynchronous Reception:
1. Initialize the SPBRG register for the appropriate baud rate. If a high speed baud rate is
desired, set bit BRGH. (Subsection 21.3 “USART Baud Rate Generator (BRG)” ).
2. Enable the asynchronous serial port by clearing the SYNC bit and setting the SPEN bit.
3. If interrupts are desired, then set the RCIE bit and configure the RCIP, GIE/GIEH and
PEIE/GIEL bits, appropriately.
4. If 9-bit reception is desired, then set the RX9 bit.
5. Enable the reception by setting the CREN bit.
6. The RCIF flag bit will be set when reception is complete. An interrupt will be generated
depending on the configuration of the RCIE, RCIP, GIE/GIEH and PEIE/GIEL bits.
7. Read the RCSTA register to get the ninth bit (if enabled) and determine if any error
occurred during reception.
8. Read the 8-bit received data by reading the RCREG register.
9. If any error occurred, clear the error by clearing the CREN bit.
Figure 21-5: Asynchronous Reception (8- or 9-bit Data)
Start
bit bit0 bit1 bit7/8 bit0 Stop bit7/8 bit
Start
bit
Start
bit7/8 Stop bit
bit
RX (pin)
reg
Rcv buffer reg
Rcv shift
Read Rcv
buffer reg
RCREG
RCIF
(interrupt flag)
OERR bit
CREN
WORD 1
RCREG
WORD 2
RCREG
Stop
bit
Note: This timing diagram shows three words appearing on the RX input. The RCREG (receive buffer) is read after the third word,
causing the OERR (overrun) bit to be set.
39500 18C Reference Manual.book Page 14 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39521A-page 21-15
Section 21. Addressable USART
Addressable
USART
21
21.4.3 Setting up 9-bit mode with Address Detect
Address detect mode allows an Addressable USART node to ignore all data on the bus until a
new address byte is present. This reduces the interrupt overhead since not every byte will generate
an interrupt (only bytes that are directed to that node).
21.4.3.1 Transmit
Steps to follow when setting up an Asynchronous Transmission:
1. Initialize the SPBRG register for the appropriate baud rate. If a high speed baud rate is
desired, set the BRGH bit. (Subsection 21.3 “USART Baud Rate Generator (BRG)” ).
2. Enable the asynchronous serial port by clearing the SYNC bit and setting the SPEN bit.
3. If interrupts are desired, then set the TXIE, TXIP, GIE/GIEH and PEIE/GIEL bits.
4. If 9-bit transmission is desired, then set the TX9 bit (can be used as address/data bit).
5. Enable the transmission by setting the TXEN bit, which will also set the TXIF bit.
6. If 9-bit transmission is selected, set the TX9D bit for address, clear the TX9D bit for data,
set the TX9D bit for address and clear the TX9D bit for data.
7. Load data to the TXREG register (starts transmission).
21.4.3.2 Receive
Steps to follow when setting up an Asynchronous Reception with Address Detect enabled:
1. Initialize the SPBRG register for the appropriate baud rate. If a high speed baud rate is
desired, set bit BRGH.
2. Enable the asynchronous serial port by clearing bit SYNC and setting bit SPEN.
3. If interrupts are desired, then set the RCIE bit and configure the RCIP, GIE/GIEH and
PEIE/GIEL bits, appropriately.
4. Set bit RX9 to enable 9-bit reception.
5. Set ADDEN to enable address detect.
6. Enable the reception by setting enable bit CREN.
7. The RCIF flag bit will be set when reception is complete. An interrupt will be generated
depending on the configuration of the RCIE, RCIP, GIE/GIEH and PEIE/GIEL bits.
8. Read the RCSTA register to get the ninth bit and determine if any error occurred during
reception.
9. Read the 8-bit received data by reading the RCREG register, to determine if the device is
being addressed.
10. If any error occurred, clear the error by clearing enable bit CREN.
11. If the device has been addressed, clear the ADDEN bit to allow data bytes and address
bytes to be read into the receive buffer, and interrupt the CPU.
39500 18C Reference Manual.book Page 15 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39521A-page 21-16 2000 Microchip Technology Inc.
Figure 21-6: USART Receive Block Diagram
Figure 21-7: Asynchronous Reception with Address Detect
Figure 21-8: Asynchronous Reception with Address Byte First
x64 Baud Rate CLK
SPBRG
Baud Rate Generator
RX/DT
Pin Buffer
and Control
SPEN
Data
Recovery
CREN
OERR FERR
MSb RSR Register LSb
RX9D RCREG Register FIFO
Interrupt RCIF
RCIE
Data Bus
8
÷ 64
÷ 16
or
Stop (8) 7 1 0 Start
RX9
• • •
RX9
ADDEN
RX9
ADDEN
RSR<8>
Enable
Load of
Receive
Buffer
8
8
Start
bit bit0 bit1 bit8 bit0 Stop
bit
Start
bit bit8 Stop
bit
RX/DT (pin)
reg
Rcv buffer reg
Rcv shift
Read Rcv
buffer reg
RCREG
RCIF
(interrupt flag)
WORD 1
RCREG
Note: This timing diagram shows a data byte followed by an address byte. The data byte is not read into the RCREG (receive buffer)
Bit8 = 0, Data Byte Bit8 = 1, Address Byte
because ADDEN = 0.
Start
bit bit0 bit1 bit8 bit0 Stop
bit
Start
bit bit8 Stop
bit
RX/DT (pin)
reg
Rcv buffer reg
Rcv shift
Read Rcv
buffer reg
RCREG
RCIF
(interrupt flag)
WORD 1
RCREG Bit8 = 1, Address Byte Bit8 = 0, Data Byte
Note: This timing diagram shows an address byte followed by an data byte. The data byte is not read into the RCREG (receive buffer)
because ADDEN was not updated and still = 0.
39500 18C Reference Manual.book Page 16 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39521A-page 21-17
Section 21. Addressable USART
Addressable
USART
21
21.4.4 Sampling
The data on the RX/DT pin is sampled three times by a majority detect circuit to determine if a
high or a low level is present at the RX pin. Figure 21-9 shows the waveform for the sampling
circuit. The sampling operates the same regardless of the state of the BRGH bit, only the source
of the x16 clock is different.
Figure 21-9: RX Pin Sampling Scheme, BRGH = 0 or BRGH = 1
Table 21-7: Registers Associated with Asynchronous Reception
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Value on
POR,
BOR
Value on
all other
Resets
INTCON GIE/GIEH PEIE/GIEL TMR0IE INT0IE RBIE TMR0IF INT0IF RBIF 0000 000x 0000 000u
PIRx RCIF (1) 0 0
PIEx RCIE (1) 0 0
IPRx RCIP (1) 0 0
RCSTA SPEN RX9 SREN CREN ADDEN FERR OERR RX9D 0000 000x 0000 000x
RCREG RX7 RX6 RX5 RX4 RX3 RX2 RX1 RX0 0000 0000 0000 0000
TXSTA CSRC TX9 TXEN SYNC — BRGH TRMT TX9D 0000 -010 0000 -010
SPBRG Baud Rate Generator Register 0000 0000 0000 0000
Legend: x = unknown, - = unimplemented locations read as '0'.
Shaded cells are not used for Asynchronous Reception.
Note 1: The position of this bit is device dependent.
RX
baud CLK
x16 CLK
Start bit Bit0
Samples
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 1 2 3
Baud CLK for all but start bit
(RX/DT pin)
39500 18C Reference Manual.book Page 17 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39521A-page 21-18 2000 Microchip Technology Inc.
21.5 USART Synchronous Master Mode
In Synchronous Master mode, the data is transmitted in a half-duplex manner, (i.e., transmission
and reception do not occur at the same time). When transmitting data, the reception is inhibited
and vice versa. Synchronous mode is entered by setting the SYNC bit. In addition, the SPEN
enable bit is set in order to configure the TX/CK and RX/DT I/O pins to CK (clock) and DT (data)
lines respectively. The Master mode indicates that the processor transmits the master clock on
the CK line. The Master mode is entered by setting the CSRC bit.
21.5.1 USART Synchronous Master Transmission
The USART transmitter block diagram is shown in Figure 21-1. The heart of the transmitter is the
Transmit Shift Register (TSR). The shift register obtains its data from the read/write transmit
buffer register TXREG. The TXREG register is loaded with data in software. The TSR register is
not loaded until the last bit has been transmitted from the previous load. As soon as the last bit
is transmitted, the TSR is loaded with new data from the TXREG (if available). Once the TXREG
register transfers the data to the TSR register (occurs in one Tcycle), the TXREG is empty and
the TXIF interrupt flag bit is set. The interrupt can be enabled/disabled by setting/clearing the
TXIE enable bit. The TXIF flag bit will be set regardless of the state of the TXIE enable bit and
cannot be cleared in software. It will reset only when new data is loaded into the TXREG register.
While the TXIF flag bit indicates the status of the TXREG register, the TRMT bit shows the status
of the TSR register. The TRMT bit is a read only bit that is set when the TSR is empty. No interrupt
logic is tied to this bit, so the user has to poll this bit in order to determine if the TSR register is
empty. The TSR is not mapped in data memory, so it is not available to the user.
Transmission is enabled by setting the TXEN bit. The actual transmission will not occur until the
TXREG register has been loaded with data. The first data bit will be shifted out on the next available
rising edge of the clock on the CK line. Data out is stable at the falling edge of the synchronous
clock (Figure 21-10). The transmission can also be started by first loading the TXREG
register and then setting the TXEN bit. This is advantageous when slow baud rates are selected,
since the BRG is kept in RESET when the TXEN, CREN and SREN bits are clear. Setting the
TXEN bit will start the BRG, creating a shift clock immediately. Normally, when transmission is
first started, the TSR register is empty, so a transfer to the TXREG register will result in an immediate
transfer to TSR, resulting in an empty TXREG. Back-to-back transfers are possible.
Clearing the TXEN bit during a transmission will cause the transmission to be aborted and will
reset the transmitter. The DT and CK pins will revert to hi-impedance. If either of the CREN or
SREN bits are set during a transmission, the transmission is aborted and the DT pin reverts to a
hi-impedance state (for a reception). The CK pin will remain an output if the CSRC bit is set (internal
clock). The transmitter logic is not reset although it is disconnected from the pins. In order to
reset the transmitter, the user has to clear the TXEN bit. If the SREN bit is set (to interrupt an
on-going transmission and receive a single word), then after the single word is received, the
SREN bit will be cleared and the serial port will revert back to transmitting, since the TXEN bit is
still set. The DT line will immediately switch from hi-impedance receive mode to transmit and start
driving. To avoid this, the TXEN bit should be cleared.
In order to select 9-bit transmission, the TX9 bit should be set and the ninth bit should be written
to the TX9D bit. The ninth bit must be written before writing the 8-bit data to the TXREG register.
This is because a data write to the TXREG can result in an immediate transfer of the data to the
TSR register (if the TSR is empty). If the TSR was empty and the TXREG was written before writing
the “new” value to the TX9D bit, the “present” value of the TX9D bit is loaded.
39500 18C Reference Manual.book Page 18 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39521A-page 21-19
Section 21. Addressable USART
Addressable
USART
21
Steps to follow when setting up a Synchronous Master Transmission:
1. Initialize the SPBRG register for the appropriate baud rate. (Subsection 21.3 “USART
Baud Rate Generator (BRG)” ).
2. Enable the synchronous master serial port by setting the SYNC, SPEN and CSRC bits.
3. If interrupts are desired, then set the TXIE bit and configure the RCIP, GIE/GIEH and
PEIE/GIEL bits, appropriately.
4. If 9-bit transmission is desired, then set the TX9 bit.
5. Enable the transmission by setting the TXEN bit.
6. If 9-bit transmission is selected, the ninth bit should be loaded in the TX9D bit.
7. Start transmission by loading data to the TXREG register.
Table 21-8: Registers Associated with Synchronous Master Transmission
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Value on
POR,
BOR
Value on all
other
Resets
INTCON GIE/GIEH PEIE/
GIEL
TMR0IE INT0IE RBIE TMR0IF INT0IF RBIF 0000 000x 0000 000u
PIRx TXIF (1) 0 0
PIEx TXIE (1) 0 0
IPRx TXIP (1) 0 0
RCSTA SPEN RX9 SREN CREN ADDEN FERR OERR RX9D 0000 -00x 0000 -00x
TXREG TX7 TX6 TX5 TX4 TX3 TX2 TX1 TX0 0000 0000 0000 0000
TXSTA CSRC TX9 TXEN SYNC — BRGH TRMT TX9D 0000 -010 0000 -010
SPBRG Baud Rate Generator Register 0000 0000 0000 0000
Legend: x = unknown, — = unimplemented, read as '0'.
Shaded cells are not used for Synchronous Master Transmission.
Note 1: The position of this bit is device dependent.
39500 18C Reference Manual.book Page 19 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39521A-page 21-20 2000 Microchip Technology Inc.
Figure 21-10:Synchronous Transmission
Figure 21-11:Synchronous Transmission (Through TXEN)
Bit 0 Bit 1 Bit 7
WORD 1
Q1Q2 Q3Q4 Q1 Q2Q3 Q4Q1 Q2Q3 Q4Q1 Q2Q3 Q4Q1 Q2 Q3Q4 Q3Q4 Q1Q2 Q3Q4 Q1Q2 Q3Q4 Q1Q2 Q3 Q4Q1 Q2Q3 Q4Q1 Q2Q3 Q4Q1 Q2Q3 Q4
RX/DT pin Bit 2 Bit 0 Bit 1 Bit 7
TX/CK pin
Write to
TXREG reg
TRMT
TXEN bit '1' '1'
Note: Sync Master mode; SPBRG = '0'. Continuous transmission of two 8-bit words.
WORD 2
TRMT bit
Write word1 Write word2
TXIF bit
(Interrupt flag)
RX/DT pin
TX/CK pin
Write to
TXREG reg
TXIF bit
TRMT bit
bit0 bit1 bit2 bit6 bit7
TXEN bit
39500 18C Reference Manual.book Page 20 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39521A-page 21-21
Section 21. Addressable USART
Addressable
USART
21
21.5.1.1 USART Synchronous Master Reception
Once Synchronous mode is selected, reception is enabled by setting either the SREN or CREN
bits. Data is sampled on the RX/DT pin on the falling edge of the clock. If the SREN bit is set,
then only a single word is received. If the CREN bit is set, the reception is continuous until the
CREN bit is cleared. If both bits are set, then the CREN bit takes precedence. After clocking the
last serial data bit, the received data in the Receive Shift Register (RSR) is transferred to the
RCREG register (if it is empty). When the transfer is complete, the RCIF interrupt flag bit is set.
The actual interrupt can be enabled/disabled by setting/clearing the RCIE enable bit. The RCIF
flag bit is a read only bit that is cleared by the hardware. In this case, it is cleared when the
RCREG register has been read and is empty. The RCREG is a double buffered register (i.e., it
is a two-deep FIFO). It is possible for two bytes of data to be received and transferred to the
RCREG FIFO and a third byte to begin shifting into the RSR register. On the clocking of the last
bit of the third byte, if the RCREG register is still full, then the overrun error bit, OERR, is set and
the word in the RSR is lost. The RCREG register can be read twice to retrieve the two bytes in
the FIFO. The OERR bit has to be cleared in software (by clearing the CREN bit). If the OERR
bit is set, transfers from the RSR to the RCREG are inhibited, so it is essential to clear the OERR
bit if it is set. The 9th receive bit is buffered the same way as the receive data. Reading the
RCREG register will load the RX9D bit with a new value; therefore, it is essential for the user to
read the RCSTA register before reading RCREG in order to not lose the old (previous) information
in the RX9D bit.
Steps to follow when setting up a Synchronous Master Reception:
1. Initialize the SPBRG register for the appropriate baud rate. (Subsection 21.3 “USART
Baud Rate Generator (BRG)” )
2. Enable the synchronous master serial port by setting the SYNC, SPEN and CSRC bits.
3. Ensure that the CREN and SREN bits are clear.
4. If interrupts are desired, then set the RCIE bit and configure the RCIP, GIE/GIEH and
PEIE/GIEL bits, appropriately.
5. If 9-bit reception is desired, then set the RX9 bit.
6. If a single reception is required, set the SREN bit. For continuous reception, set the CREN
bit.
7. The RCIF bit will be set when reception is complete and an interrupt will be generated if
the RCIE bit is set.
8. Read the RCSTA register to get the ninth bit (if enabled) and determine if any error
occurred during reception.
9. Read the 8-bit received data by reading the RCREG register.
10. If any error occurred, clear the error by clearing the CREN bit.
Table 21-9: Registers Associated with Synchronous Master Reception
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Value on:
POR,
BOR
Value on all
other Resets
INTCON GIE/
GIEH
PEIE/
GIEL
TMR0IE INT0IE RBIE TMR0IF INT0IF RBIF 0000 000x 0000 000u
PIRx RCIF (1) 0 0
PIEx RCIE (1) 0 0
IPRx RCIP (1) 0 0
RCSTA SPEN RX9 SREN CREN ADDEN FERR OERR RX9D 0000 000x 0000 000x
RCREG RX7 RX6 RX5 RX4 RX3 RX2 RX1 RX0 0000 0000 0000 0000
TXSTA CSRC TX9 TXEN SYNC — BRGH TRMT TX9D 0000 -010 0000 -010
SPBRG Baud Rate Generator Register 0000 0000 0000 0000
Legend: x = unknown, - = unimplemented read as '0'.
Shaded cells are not used for Synchronous Master Reception.
Note 1: The position of this bit is device dependent.
39500 18C Reference Manual.book Page 21 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39521A-page 21-22 2000 Microchip Technology Inc.
Figure 21-12: Synchronous Reception (Master Mode, SREN)
CREN bit
RX/DT pin
TX/CK pin
Write to
SREN bit
SREN bit
RCIF bit
(interrupt)
Read
RXREG
Note: Timing diagram demonstrates SYNC Master mode with SREN = '1' and BRG = '0'.
Q2 Q1 Q2 Q3 Q4Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4
'0'
bit0 bit1 bit2 bit3 bit4 bit5 bit6 bit7
Q1 Q2 Q3 Q4
’0’
39500 18C Reference Manual.book Page 22 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39521A-page 21-23
Section 21. Addressable USART
Addressable
USART
21
21.6 USART Synchronous Slave Mode
Synchronous slave mode differs from the Master mode in the fact that the shift clock is supplied
externally at the TX/CK pin (instead of being supplied internally in Master mode). This allows the
device to transfer or receive data while in SLEEP mode. Slave mode is entered by clearing the
CSRC bit (TXSTA<7>).
21.6.1 USART Synchronous Slave Transmit
The operation of the Synchronous Master and Slave modes are identical, except in the case of
the SLEEP mode.
If two words are written to the TXREG and then the SLEEP instruction is executed, the following
will occur:
a) The first word will immediately transfer to the TSR register and transmit.
b) The second word will remain in TXREG register.
c) The TXIF flag bit will not be set.
d) When the first word has been shifted out of TSR, the TXREG register will transfer the second
word to the TSR and the TXIF flag bit will now be set.
e) If the TXIE enable bit is set, the interrupt will wake the chip from SLEEP and if the global
interrupt is enabled, the program will branch to the interrupt vector.
Steps to follow when setting up a Synchronous Slave Transmission:
1. Enable the synchronous slave serial port by setting the SYNC and SPEN bits and clearing
the CSRC bit.
2. Clear the CREN and SREN bits.
3. If interrupts are desired, then set the TXIE enable bit and configure the RCIP, GIE/GIEH
and PEIE/GIEL bits, appropriately.
4. If 9-bit transmission is desired, then set the TX9 bit.
5. Enable the transmission by setting the TXEN enable bit.
6. If 9-bit transmission is selected, the ninth bit should be loaded into the TX9D bit.
7. Start transmission by loading data to the TXREG register.
Table 21-10: Registers Associated with Synchronous Slave Transmission
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Value on:
POR,
BOR
Value on all
other Resets
INTCON GIE/
GIEH
PEIE/
GIEL
TMR0IE INT0IE RBIE TMR0IF INT0IF RBIF 0000 000x 0000 000u
PIRx TXIF (1) 0 0
PIEx TXIE (1) 0 0
IPRx TXIP (1) 0 0
RCSTA SPEN RX9 SREN CREN ADDEN FERR OERR RX9D 0000 000x 0000 000x
TXREG TX7 TX6 TX5 TX4 TX3 TX2 TX1 TX0 0000 0000 0000 0000
TXSTA CSRC TX9 TXEN SYNC — BRGH TRMT TX9D 0000 -010 0000 -010
SPBRG Baud Rate Generator Register 0000 0000 0000 0000
Legend: x = unknown, - = unimplemented read as '0'.
Shaded cells are not used for Synchronous Slave Transmission.
Note 1: The position of this bit is device dependent.
39500 18C Reference Manual.book Page 23 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39521A-page 21-24 2000 Microchip Technology Inc.
21.6.2 USART Synchronous Slave Reception
The operation of the Synchronous Master and Slave modes is identical, except in the case of the
SLEEP mode. Also, bit SREN is a "don't care" in Slave mode.
If receive is enabled, by setting the CREN bit prior to the SLEEP instruction, then a word may be
received during SLEEP. On completely receiving the word, the RSR register will transfer the data
to the RCREG register and if the RCIE enable bit bit is set, the interrupt generated will wake the
chip from SLEEP. If the global interrupt is enabled, the program will branch to the appropriate
interrupt vector.
Steps to follow when setting up a Synchronous Slave Reception:
1. Enable the synchronous master serial port by setting the SYNC and SPEN bits and clearing
the CSRC bit.
2. If interrupts are desired, then set the RCIE enable bit and configure the RCIP, GIE/GIEH
and PEIE/GIEL bits, appropriately.
3. If 9-bit reception is desired, then set the RX9 bit.
4. To enable reception, set the CREN enable bit.
5. The RCIF bit will be set when reception is complete and an interrupt will be generated, if
the RCIE bit is set.
6. Read the RCSTA register to get the ninth bit (if enabled) and determine if any error
occurred during reception.
7. Read the 8-bit received data by reading the RCREG register.
8. If any error occurred, clear the error by clearing the CREN bit.
Table 21-11: Registers Associated with Synchronous Slave Reception
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Value on:
POR,
BOR
Value on all
other Resets
INTCON GIE/
GIEH
PEIE/
GIEL
TMR0IE INT0IE RBIE TMR0IF INT0IF RBIF 0000 000x 0000 000u
PIRx RCIF (1) 0 0
PIEx RCIE (1) 0 0
IPRx RCIP (1) 0 0
RCSTA SPEN RX9 SREN CREN ADDEN FERR OERR RX9D 0000 000x 0000 000x
RCREG RX7 RX6 RX5 RX4 RX3 RX2 RX1 RX0 0000 0000 0000 0000
TXSTA CSRC TX9 TXEN SYNC — BRGH TRMT TX9D 0000 -010 0000 -010
SPBRG Baud Rate Generator Register 0000 0000 0000 0000
Legend: x = unknown, - = unimplemented read as '0'.
Shaded cells are not used for Synchronous Slave Reception.
Note 1: The position of this bit is device dependent.
39500 18C Reference Manual.book Page 24 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39521A-page 21-25
Section 21. Addressable USART
Addressable
USART
21
21.7 Initialization
Example 21-2 is an initialization routine for Asynchronous Transmitter/Receiver mode.
Example 21-3 is for the Synchronous mode. In both examples, the data is 8 bits, and the value
to load into the SPBRG register is dependent on the desired baud rate and the device frequency.
Example 21-4 is an initialization of the Addressable USART in 9-bit address detect mode.
Example 21-2: Asynchronous Transmitter/Receiver
Example 21-3: Synchronous Transmitter/Receiver
Example 21-4: Asynchronous 9-bit Transmitter/Receiver (Address Detect Enabled)
MOVLW baudrate ; Set Baudrate
MOVWF SPBRG
MOVLW 0x20 ; 8-bit transmit, transmitter enabled,
MOVWF TXSTA ; asynchronous mode, low speed mode
CLRF PIR1 ; Clear all iterrupt flags
; including AUSART TX & RX
BSF PIE1,TXIE ; Enable transmit interrupts
BSF PIE1,RCIE ; Enable receive interrupts
MOVLW 0x90 ; 8-bit receive, receiver enabled,
MOVWF RCSTA ; serial port enabled
MOVLW baudrate ; Set Baudrate
MOVWF SPBRG
MOVLW 0xB0 ; Synchronous Master,8-bit transmit,
MOVWF TXSTA ; transmitter enabled, low speed mode
CLRF PIR1 ; Clear all iterrupt flags
; including AUSART TX & RX
BSF PIE1,TXIE ; Enable transmit interrupts
BSF PIE1,RCIE ; Enable receive interrupts
MOVLW 0x90 ; 8-bit receive, receiver enabled,
MOVWF RCSTA ; continuous receive, serial port enabled
MOVLW baudrate ; Set Baudrate
MOVWF SPBRG
MOVLW 0x60 ; 9-bit transmit, transmitter enabled,
MOVWF TXSTA ; asynchronous mode, low speed mode
CLRF PIR1 ; Clear all iterrupt flags
; including AUSART TX & RX
BSF PIE1,TXIE ; Enable transmit interrupts
BSF PIE1,RCIE ; Enable receive interrupts
MOVLW 0xD8 ; 9-bit, Address Detect Enable
MOVWF RCSTA ; serial port enabled
39500 18C Reference Manual.book Page 25 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39521A-page 21-26 2000 Microchip Technology Inc.
21.8 Design Tips
Question 1: Using the Asynchronous mode I am getting a lot of transmission errors.
Answer 1:
The most common reasons are
1. You have incorrectly calculated the value to load in to the SPBRG register.
2. The sum of the baud errors for the transmitter and receiver is too high.
Question 2: The PICmicro device is not receiving the data transmitted even though
there are good levels on the Addressable USART pins.
Answer 2:
Ensure that the Address Detect Enable bit is at the desired setting.
39500 18C Reference Manual.book Page 26 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39521A-page 21-27
Section 21. Addressable USART
Addressable
USART
21
21.9 Related Application Notes
This section lists application notes that are related to this section of the manual. These application
notes may not be written specifically for the Enhanced family (that is, they may be written for
the Base-Line, the Mid-Range or High-End families), but the concepts are pertinent, and could
be used (with modification and possible limitations). The current application notes related to this
section are:
Title Application Note #
Serial Port Utilities AN547
Servo Control of a DC Brush Motor AN532
Brush-DC Servomotor Implementation using PIC17C756A AN718
Note: Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
http://www.microchip.com/10/faqs/codeex/
39500 18C Reference Manual.book Page 27 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39521A-page 21-28 2000 Microchip Technology Inc.
21.10 Revision History
Revision A
This is the initial released revision of the Enhanced MCU Addressable USART module description.
39500 18C Reference Manual.book Page 28 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39522A-page 22-1
CAN
22
Section 22. CAN
HIGHLIGHTS
This section of the manual contains the following major topics:
22.1 Introduction .................................................................................................................. 22-2
22.2 Control Registers for the CAN Module......................................................................... 22-3
22.3 CAN Overview ........................................................................................................... 22-28
22.4 CAN Bus Features ..................................................................................................... 22-32
22.5 CAN Module Implementation ..................................................................................... 22-33
22.6 Frame Types .............................................................................................................. 22-37
22.7 Modes of Operation ................................................................................................... 22-44
22.8 CAN Bus Initialization ................................................................................................ 22-48
22.9 Message Reception ................................................................................................... 22-49
22.10 Transmission .............................................................................................................. 22-60
22.11 Error Detection........................................................................................................... 22-69
22.12 Baud Rate Setting...................................................................................................... 22-71
22.13 Interrupts.................................................................................................................... 22-75
22.14 Timestamping ............................................................................................................ 22-77
22.15 CAN Module I/O......................................................................................................... 22-77
22.16 Design Tips ................................................................................................................ 22-78
22.17 Related Application Notes.......................................................................................... 22-79
22.18 Revision History ......................................................................................................... 22-80
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39522A-page 22-2 2000 Microchip Technology Inc.
22.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 22-1 shows an example CAN Bus network.
Figure 22-1: Example CAN Bus Network
MCP2510
SPI
MCP2510
INTERFACE
CAN
BUS
CAN
Transceiver
PICmicro
Controller
CAN
Transceiver
CAN
Transceiver
CAN
Transceiver
CAN
Transceiver
PICmicro
Controller
PIC18CXX8
with CAN
PIC18CXX8
with integrated
PIC18CXX8
with integrated
Microchip Microchip
CAN CAN
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39522A-page 22-3
Section 22. CAN
CAN
22
22.2 Control Registers for the CAN Module
There are many registers associated with the CAN module. Descriptions of these registers are
grouped into sections. These sections are:
• Control and Status Registers
• Transmit Buffer Registers
• Receive Buffer Registers
• Baud Rate Control Registers
• Interrupt Status and Control Registers
22.2.1 CAN Control and Status Registers
This section shows the CAN Control and Status registers.
Register 22-1: CANCON: CAN Control Register
R/W-1 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 U-0
REQOP2 REQOP1 REQOP0 ABAT WIN2 WIN1 WIN0 —
bit 7 bit 0
bit 7 - 5 REQOP2:REQOP0: Request CAN Operation mode bits
1xx = Request Configuration mode
011 = Request Listen Only mode
010 = Request Loopback mode
001 = Request Disable mode
000 = Request Normal mode
bit 4 ABAT: Abort All Pending Transmissions bit
1 = Abort All Pending Transmissions (in all transmit buffers)
0 = Transmissions proceeding as normal, or all Transmissions aborted
Note: This bit will automatically be cleared when all transmissions are aborted.
bit 3 - 1 WIN2:WIN0: Window Address bits
This selects which of the CAN buffers to switch into the access bank area. This allows access
to the buffer registers from any data memory bank. After a frame has caused an interrupt, the
ICODE2:ICODE0 bits can be copied to the WIN2:WIN0 bits to select the correct buffer.
111 = Receive Buffer 0
110 = Receive Buffer 0
101 = Receive Buffer 1
100 = Transmit Buffer 0
011 = Transmit Buffer 1
010 = Transmit Buffer 2
001 = Receive Buffer 0
000 = Receive Buffer 0
bit 0 Unimplemented: Read as ’0’
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39522A-page 22-4 2000 Microchip Technology Inc.
Register 22-2: CANSTAT: CAN Status Register
R-1 R-0 R-0 U-0 R-0 R-0 R-0 U-0
OPMODE2 OPMODE1 OPMODE0 — ICODE2 ICODE1 ICODE0 —
bit 7 bit 0
bit 7-5 OPMODE2:OPMODE0: Operation Mode Status bits
111 = Reserved
110 = Reserved
101 = Reserved
100 = Configuration mode
011 = Listen Only mode
010 = Loopback mode
001 = Disable mode
000 = Normal mode
Note: Before the device goes into SLEEP mode, select Disable Mode.
bit 4 Unimplemented: Read as ’0’
bit 3-1 ICODE2:ICODE0: Interrupt Code bits
When an interrupt occurs, a prioritized coded Interrupt value will be present in the
ICODE2:ICODE0 bits. These codes indicate the source of the interrupt. The ICODE2:ICODE0
bits can be copied to the WIN2:WIN0 bits to select the correct buffer to map into the Access
Bank area.
111 = Wake-up on Interrupt
110 = RXB0 Interrupt
101 = RXB1 Interrupt
100 = TXB0 Interrupt
011 = TXB1 Interrupt
010 = TXB2 Interrupt
001 = Error Interrupt
000 = No Interrupt
bit 0 Unimplemented: Read as ’0’
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39522A-page 22-5
Section 22. CAN
CAN
22
Register 22-3: COMSTAT: Communication Status Register
R/C-0 R/C-0 R-0 R-0 R-0 R-0 R-0 R-0
RX0OVFL RX1OVFL TXBO TXBP RXBP TXWARN RXWARN EWARN
bit 7 bit 0
bit 7 RX0OVFL: Receive Buffer 0 Overflow bit
1 = Receive Buffer 0 Overflowed
0 = Receive Buffer 0 has not overflowed.
bit 6 RX1OVFL: Receive Buffer 1 Overflow bit
1 = Receive Buffer 1 Overflowed
0 = Receive Buffer 1 has not overflowed
bit 5 TXB0: Transmitter Bus Off bit
1 = Transmit Error Counter > 255
0 = Transmit Error Counter ≤ 255
bit 4 TXBP: Transmitter Bus Passive bit
1 = Transmission Error Counter >127
0 = Transmission Error Counter ≤127
bit 3 RXBP: Receiver Bus Passive bit
1 = Receive Error Counter > 127
0 = Receive Error Counter ≤127
bit 2 TXWARN: Transmitter Warning bit
1 = Transmit Error Counter > 95
0 = Transmit Error Counter ≤ 95
bit 1 RXWARN: Receiver Warning bit
1 = Receive Error Counter > 95
0 = Receive Error Counter ≤ 95
bit 0 EWARN: Error Warning bit
This bit is a flag of the RXWARN and TXWARN bits
1 = The RXWARN or the TXWARN bits are set
0 = Neither the RXWARN or the TXWARN bits are set
Legend
R = Readable bit C = Clearable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39522A-page 22-6 2000 Microchip Technology Inc.
22.2.2 CAN Transmit Buffer Registers
This section describes the CAN Transmit Buffer Register and the associated Transmit Buffer
Control Registers.
Register 22-4: TXB0CON: Transmit Buffer 0 Control Register
TXB1CON: Transmit Buffer 1 Control Register
TXB2CON: Transmit Buffer 2 Control Register
U-0 R-0 R-0 R-0 R/W-0 U-0 R/W-0 R/W-0
— TXABT TXLARB TXERR TXREQ — TXPRI1 TXPRI0
bit 7 bit 0
bit 7 Unimplemented: Read as ’0’
bit 6 TXABT: Transmission Aborted Status bit
1 = Message was aborted
0 = Message completed transmission successfully
bit 5 TXLARB: Transmission Lost Arbitration Status bit
1 = Message lost arbitration while being sent
0 = Message did not lose arbitration while being sent
bit 4 TXERR: Transmission Error detected Status 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
bit 3 TXREQ: Transmit Request Status bit
1 = Requests sending a message. Clears the TXABT, TXLARB, and TXERR bits.
0 = Automatically cleared when the message is successfully sent
Note: Clearing this bit in software, while the bit is set will request a message abort.
bit 2 Unimplemented: Read as ’0’
bit 1:0 TXPRI1:TXPRI0: Transmit Priority bits
11 = Priority Level 3 (Highest Priority)
10 = Priority Level 2
01 = Priority Level 1
00 = Priority Level 0 (Lowest Priority)
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39522A-page 22-7
Section 22. CAN
CAN
22
Register 22-5: TXB0SIDH: Transmit Buffer 0 Standard Identifier High Byte Register
TXB1SIDH: Transmit Buffer 1 Standard Identifier High Byte Register
TXB2SIDH: Transmit Buffer 2 Standard Identifier High Byte Register
Register 22-6: TXB0SIDL: Transmit Buffer 0 Standard Identifier Low Byte Register
TXB1SIDL: Transmit Buffer 1 Standard Identifier Low Byte Register
TXB2SIDL: Transmit Buffer 2 Standard Identifier Low Byte Register
R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x
SID10 SID9 SID8 SID7 SID6 SID5 SID4 SID3
bit 7 bit 0
bit 7-0 SID10:SID3: Standard Identifier bits
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x
SID2 SID1 SID0 — EXIDEN — EID17 EID16
bit 7 bit 0
bit 7-5 SID2:SID0: Standard Identifier bits
bit 4 Unimplemented: Read as ’0’
bit 3 EXIDEN: Extended Identifier Enable bit
1 = Message will transmit Extended ID
0 = Message will transmit Standard ID
bit 2 Unimplemented: Read as ’0’
bit 1-0 EID17:EID16: Extended Identifier bits
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39522A-page 22-8 2000 Microchip Technology Inc.
Register 22-7: TXB0EIDH: Transmit Buffer 0 Extended Identifier High Byte Register
TXB1EIDH: Transmit Buffer 1 Extended Identifier High Byte Register
TXB2EIDH: Transmit Buffer 2 Extended Identifier High Byte Register
Register 22-8: TXB0EIDL: Transmit Buffer 0 Extended Identifier Low Byte Register
TXB1EIDL: Transmit Buffer 1 Extended Identifier Low Byte Register
TXB2EIDL: Transmit Buffer 2 Extended Identifier Low Byte Register
Register 22-9: TXB0Dm: Transmit Buffer 0 Data Field Byte m Register
TXB1Dm: Transmit Buffer 1 Data Field Byte m Register
TXB2Dm: Transmit Buffer 2 Data Field Byte m Register
R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x
EID15 EID14 EID13 EID12 EID11 EID10 EID9 EID8
bit 7 bit 0
bit 7-0 EID15:EID8: Extended Identifier bits EID15 to EID8
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x
EID7 EID6 EID5 EID4 EID3 EID2 EID1 EID0
bit 7 bit 0
bit 7-0 EID7:EID0: Extended Identifier bits EID7 to EID0
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x
TXBnDm7 TXBnDm6 TXBnDm5 TXBnDm4 TXBnDm3 TXBnDm2 TXBnDm1 TXBnDm0
bit 7 bit 0
bit 1-0 TXBnDm7:TXBnDm0: Transmit Buffer n Data Field Byte m bits (where 0 < n < 3 and 0 < m < 8)
Each Transmit Buffer has an array of registers. For example Transmit buffer 0 has 7 registers:
TXB0D1 to TXB0D7.
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39522A-page 22-9
Section 22. CAN
CAN
22
Register 22-10: TXB0DLC: Transmit Buffer 0 Data Length Code Register
TXB1DLC: Transmit Buffer 1 Data Length Code Register
TXB2DLC: Transmit Buffer 2 Data Length Code Register
Register 22-11: TXERRCNT: Transmit Error Count Register
U-0 R/W-x U-0 U-0 R/W-x R/W-x R/W-x R/W-x
— TXRTR — — DLC3 DLC2 DLC1 DLC0
bit 7 bit 0
bit 7 Unimplemented: Read as ’0’
bit 6 TXRTR: Transmission Frame Remote Transmission Request bit
1 = Transmitted Message will have TXRTR bit set
0 = Transmitted Message will have TXRTR bit cleared.
bit 5-4 Unimplemented: Read as ’0’
bit 3-0 DLC3:DLC0: Data Length Code bits
1111 = Reserved
1110 = Reserved
1101 = Reserved
1100 = Reserved
1011 = Reserved
1010 = Reserved
1001 = Reserved
1000 = Data Length = 8 bytes
0111 = Data Length = 7 bytes
0110 = Data Length = 6 bytes
0101 = Data Length = 5 bytes
0100 = Data Length = 4 bytes
0011 = Data Length = 3 bytes
0010 = Data Length = 2 bytes
0001 = Data Length = 1 bytes
0000 = Data Length = 0 bytes
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
TEC7 TEC6 TEC5 TEC4 TEC3 TEC2 TEC1 TEC0
bit 7 bit 0
bit 7-0 TEC7:TEC0: Transmit Error Counter bits
This register contains a value which is derived from the rate at which errors occur. When the
error count overflows, the bus off state occurs. When the bus has an occurrence of 11 consecutive
recessive bits, the counter value is cleared.
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39522A-page 22-10 2000 Microchip Technology Inc.
22.2.3 CAN Receive Buffer Registers
This section shows the Receive buffer registers with their associated control registers.
Register 22-12: RXB0CON: Receive Buffer 0 Control Register
R/C-0 R/W-0 R/W-0 U-0 R/W-0 R/W-0 R-0 R/W-0
RXFUL RXM1 RXM0 — RXRTRRO RX0DBEN JTOFF FILHIT0
bit 7 bit 0
bit 7 RXFUL: Receive Full status bit
1 = Receive buffer contains a valid received message
0 = Receive buffer is open to receive a new message
Note: This bit is set by the CAN module and should be cleared by software after the buffer
is read.
bit 6-5 RXM1:RXM0: Receive Buffer Mode bits
11 = Receive all messages (including those with errors)
10 = Receive only valid messages with extended identifier
01 = Receive only valid messages with standard identifier
00 = Receive all valid messages
bit 4 Unimplemented: Read as ’0’
bit 3 RXRTRRO: Receive Remote Transfer Request Read Only bit
1 = Remote Transfer Request
0 = No Remote Transfer Request
bit 2 RX0DBEN: Receive Buffer 0 Double Buffer Enable bit
1 = Receive Buffer 0 overflow will write to Receive Buffer 1
0 = No Receive Buffer 0 overflow to Receive Buffer 1
bit 1 JTOFF: Jump Table offset bit
1 = Allows Jump Table offset between 6 and 7
0 = Allows Jump Table offset between 1 and 0
bit 0 FILHIT0: Filter Hit bit
This bit indicates which acceptance filter enabled the message reception into receive buffer 0.
1 = Acceptance Filter 1 (RXF1)
0 = Acceptance Filter 0 (RXF0)
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
C = Clearable bit
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39522A-page 22-11
Section 22. CAN
CAN
22
Register 22-13: RXB1CON: Receive Buffer 1 Control Register
R/C-0 R/W-0 R/W-0 U-0 R-0 R-0 R-0 R-0
RXFUL RXM1 RXM0 — RXRTRRO FILHIT2 FILHIT1 FILHIT0
bit 7 bit 0
bit 7 RXFUL: Receive Full status bit
1 = Receive buffer contains a valid received message
0 = Receive buffer is open to receive a new message
Note: This bit is set by the CAN module and should be cleared by software after the buffer
is read.
bit 6-5 RXM1:RXM0: Receive Buffer Mode bits
11 = Receive all messages (including those with errors)
10 = Receive only valid messages with extended identifier
01 = Receive only valid messages with standard identifier
00 = Receive all valid messages
bit 4 Unimplemented: Read as ’0’
bit 3 RXRTRRO: Receive Remote Transfer Request bit (read only)
1 = Remote Transfer Request
0 = No Remote Transfer Request
bit 2-0 FILHIT2:FILHIT0: Filter Hit bits
These bits indicate which acceptance filter enabled the last message reception into Receive
Buffer 1
111 = Reserved
110 = Reserved
101 = Acceptance Filter 5 (RXF5)
100 = Acceptance Filter 4 (RXF4)
011 = Acceptance Filter 3 (RXF3)
010 = Acceptance Filter 2 (RXF2)
001 = Acceptance Filter 1 (RXF1) only possible when RX0DBEN bit is set
000 = Acceptance Filter 0 (RXF0) only possible when RX0DBEN bit is set
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
C = Clearable bit
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
39500 18C Reference Manual.book Page 11 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39522A-page 22-12 2000 Microchip Technology Inc.
Register 22-14: RXB0SIDH: Receive Buffer 0 Standard Identifier High Byte Register
RXB1SIDH: Receive Buffer 1 Standard Identifier High Byte Register
Register 22-15: RXB0SIDL: Receive Buffer 0 Standard Identifier Low Byte Register
RXB1SIDL: Receive Buffer 1 Standard Identifier Low Byte Register
R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x
SID10 SID9 SID8 SID7 SID6 SID5 SID4 SID3
bit 7 bit 0
bit 7-0 SID10:SID3: Standard Identifier bits
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
R/W-x R/W-x R/W-x R/W-x R/W-x U-0 R/W-x R/W-x
SID2 SID1 SID0 SRR EXID — EID17 EID16
bit 7 bit 0
bit 7-5 SID2:SID0: Standard Identifier bits SID2 to SID1
bit 4 SRR: Substitute Remove Request bit (only when EXID = ’1’)
1 = Remote Transfer Request Occurred
0 = No Remote Transfer Request Occurred
bit 3 EXID: Extended Identifier bit
1 = Received message is an Extended Data Frame
0 = Received message is a Standard Data Frame
bit 2 Unimplemented: Read as ’0’
bit 1-0 EID17:EID16: Extended Identifier bits EID17 to EID16
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
39500 18C Reference Manual.book Page 12 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39522A-page 22-13
Section 22. CAN
CAN
22
Register 22-16: RXB0EIDH: Receive Buffer 0 Extended Identifier High Byte Register
RXB1EIDH: Receive Buffer 1 Extended Identifier High Byte Register
Register 22-17: RXB0EIDL: Transmit Buffer 0 Extended Identifier Low Byte Register
RXB1EIDL: Transmit Buffer 1 Extended Identifier Low Byte Register
R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x
EID15 EID14 EID13 EID12 EID11 EID10 EID9 EID8
bit 7 bit 0
bit 7-0 EID15:EID8: Extended Identifier bits EID15 to EID8
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x
EID7 EID6 EID5 EID4 EID3 EID2 EID1 EID0
bit 7 bit 0
bit 7-0 EID7:EID0: Extended Identifier bits EID7 to EID0
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
39500 18C Reference Manual.book Page 13 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39522A-page 22-14 2000 Microchip Technology Inc.
Register 22-18: RXB0DLC: Receive Buffer 0 Data Length Code Register
RXB1DLC: Receive Buffer 1 Data Length Code Register
U-x R/W-x R-x R-x R-x R-x R-x R-x
— RXRTR RB1 RB0 DLC3 DLC2 DLC1 DLC0
bit 7 bit 0
bit 7 Unimplemented: Read as ’0’
bit 6 RXRTR: Receiver Remote Transmission Request bit
1 = Remote Transfer Request
0 = No Remote Transfer Request
bit 5 RB1: Reserved bit 1
Reserved by CAN Specification and read as ’0’
bit 4 RB0: Reserved bit 0
Reserved by CAN Specification and read as ’0’
bit 3-0 DLC3:DLC0: Data Length Code bits
1111 = Invalid
1110 = Invalid
1101 = Invalid
1100 = Invalid
1011 = Invalid
1010 = Invalid
1001 = Invalid
1000 = Data Length = 8 bytes
0111 = Data Length = 7 bytes
0110 = Data Length = 6 bytes
0101 = Data Length = 5 bytes
0100 = Data Length = 4 bytes
0011 = Data Length = 3 bytes
0010 = Data Length = 2 bytes
0001 = Data Length = 1 bytes
0000 = Data Length = 0 bytes
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
39500 18C Reference Manual.book Page 14 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39522A-page 22-15
Section 22. CAN
CAN
22
Register 22-19: RXB0Dm: Receive Buffer 0 Data Field Byte m Register
RXB1Dm: Receive Buffer 1 Data Field Byte m Register
Register 22-20: RXERRCNT: Receive Error Count Register
R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x
RXBnDm7 RXBnDm6 RXBnDm5 RXBnDm4 RXBnDm3 RXBnDm2 RXBnDm1 RXBnDm0
bit 7 bit 0
bit 7-0 RXBnDm7:RXBnDm0: Receive Buffer n Data Field Byte m bits (where 0 < n < 1 and 0 < m < 7)
Each Receive Buffer has an array of registers. For example Receive buffer 0 has 7 registers:
RXB0D1 to RXB0D7.
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
R-0 R-0 R-0 R-0 R-0 R-0 R-0 R-0
REC7 REC6 REC5 REC4 REC3 REC2 REC1 REC0
bit 7 bit 0
bit 7-0 REC7:REC0: Receive Error Counter bits
This register contains the number of errors that occurred for the Reception of this buffers message.
When the error count overflows, the bus off state occurs. When the bus has 256 occurrences of
11 consecutive recessive bits, the counter value is cleared.
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
39500 18C Reference Manual.book Page 15 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39522A-page 22-16 2000 Microchip Technology Inc.
22.2.4 Message Acceptance Filters
This subsection describes the Message Acceptance filters.
Register 22-21: RXF0SIDH: Receive Acceptance Filter 0 Std. Identifier Filter High Byte
RXF1SIDH: Receive Acceptance Filter 1 Std. Identifier Filter High Byte
RXF2SIDH: Receive Acceptance Filter 2 Std. Identifier Filter High Byte
RXF3SIDH: Receive Acceptance Filter 3 Std. Identifier Filter High Byte
RXF4SIDH: Receive Acceptance Filter 4 Std. Identifier Filter High Byte
RXF5SIDH: Receive Acceptance Filter 5 Std. Identifier Filter High Byte
Register 22-22: RXF0SIDL: Receive Acceptance Filter 0 Std. Identifier Filter Low Byte
RXF1SIDL: Receive Acceptance Filter 1 Std. Identifier Filter Low Byte
RXF2SIDL: Receive Acceptance Filter 2 Std. Identifier Filter Low Byte
RXF3SIDL: Receive Acceptance Filter 3 Std. Identifier Filter Low Byte
RXF4SIDL: Receive Acceptance Filter 4 Std. Identifier Filter Low Byte
RXF5SIDL:Receive Acceptance Filter 5 Std. Identifier Filter Low 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
SID10 SID9 SID8 SID7 SID6 SID5 SID4 SID3
bit 7 bit 0
bit 7-0 SID10:SID3: Standard Identifier Filter bits SID10 to SID3
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
R/W-x R/W-x R/W-x U-0 R/W-x U-0 R/W-x R/W-x
SID2 SID1 SID0 — EXIDEN — EID17 EID16
bit 7 bit 0
bit 7-5 SID2:SID0: Standard Identifier Filter bits SID2 to SID0
bit 4 Unimplemented: Read as ’0’
bit 3 EXIDEN: Extended Identifier Filter Enable bit
1 = Message will transmit Extended ID
0 = Message will not transmit Extended ID.
bit 2 Unimplemented: Read as ’0’
bit 1-0 EID17:EID16: Extended Identifier Filter bits EID17 to EID16
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
39500 18C Reference Manual.book Page 16 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39522A-page 22-17
Section 22. CAN
CAN
22
Register 22-23: RXF0EIDH: Receive Acceptance Filter 0 Extended Identifier High Byte
RXF1EIDH: Receive Acceptance Filter 1 Extended Identifier High Byte
RXF2EIDH: Receive Acceptance Filter 2 Extended Identifier High Byte
RXF3EIDH: Receive Acceptance Filter 3 Extended Identifier High Byte
RXF4EIDH: Receive Acceptance Filter 4 Extended Identifier High Byte
RXF5EIDH:Receive Acceptance Filter 5 Extended Identifier High Byte
Register 22-24: RXB0EIDL: Receive Buffer 0 Extended Identifier Low Byte Register
RXB1EIDL: Receive Buffer 1 Extended Identifier Low Byte Register
RXB2EIDL: Receive Buffer 2 Extended Identifier Low Byte Register
RXB3EIDL: Receive Buffer 3 Extended Identifier Low Byte Register
RXB4EIDL: Receive Buffer 4 Extended Identifier Low Byte Register
RXB5EIDL: Receive Buffer 5 Extended Identifier Low Byte Register
R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x
EID15 EID14 EID13 EID12 EID11 EID10 EID9 EID8
bit 7 bit 0
bit 7-0 EID15:EID8: Extended Identifier Filter bits EID15 to EID8
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x
EID7 EID6 EID5 EID4 EID3 EID2 EID1 EID0
bit 7 bit 0
bit 7-0 EID7:EID0: Extended Identifier Filterbits EID7 to EID0
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
39500 18C Reference Manual.book Page 17 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39522A-page 22-18 2000 Microchip Technology Inc.
Register 22-25: RXM0SIDH: Receive Acceptance Mask 0 Std. Identifier Mask High Byte
Register
RXM1SIDH: Receive Acceptance Mask 1 Std. Identifier Mask High Byte
Register
Register 22-26: RXM0SIDL: Receive Acceptance Mask 0 Std. Identifier Mask Low Byte
Register
RXM1SIDL: Receive Acceptance Mask 1 Std. Identifier Mask Low Byte
Register
R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x
SID10 SID9 SID8 SID7 SID6 SID5 SID4 SID3
bit 7 bit 0
bit 7-0 SID10:SID3: Standard Identifier Mask bits SID10 to SID3
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
R/W-x R/W-x R/W-x U-0 U-0 U-0 R/W-x R/W-x
SID2 SID1 SID0 — — — EID17 EID16
bit 7 bit 0
bit 7-5 SID2:SID0: Standard Identifier Mask bits SID2 to SID0
bit 4-2 Unimplemented: Read as ’0’
bit 1-0 EID17:EID16: Extended Identifier Mask bits EID17 to EID16
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
39500 18C Reference Manual.book Page 18 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39522A-page 22-19
Section 22. CAN
CAN
22
Register 22-27: RXM0EIDH: Receive Acceptance Mask 0 Extended Identifier Mask High
Byte Register
RXM1EIDH: Receive Acceptance Mask 1 Extended Identifier Mask High
Byte Register
Register 22-28: RXM0EIDL: Receive Acceptance Mask 0 Extended Identifier Mask Low
Byte Register
RXM1EIDL: Receive Acceptance Mask 1 Extended Identifier Mask Low
Byte Register
R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x
EID15 EID14 EID13 EID12 EID11 EID10 EID9 EID8
bit 7 bit 0
bit 1-0 EID15:EID8: Extended Identifier Mask bits EID15 to EID8
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x R/W-x
EID7 EID6 EID5 EID4 EID3 EID2 EID1 EID0
bit 7 bit 0
bit 1-0 EID7:EID0: Extended Identifier Mask bits EID7 to EID0
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
39500 18C Reference Manual.book Page 19 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39522A-page 22-20 2000 Microchip Technology Inc.
22.2.5 CAN Baud Rate Registers
This subsection describes the CAN baud rate registers.
Register 22-29: BRGCON1: Baud Rate Control Register 1
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
SJW1 SJW0 BRP5 BRP4 BRP3 BRP2 BRP1 BRP0
bit 7 bit 0
bit 7-6 SJW1:SJW0: Synchronized Jump Width bits
11 = Synchronization Jump Width Time = 4 x TQ
10 = Synchronization Jump Width Time = 3 x TQ
01 = Synchronization Jump Width Time = 2 x TQ
00 = Synchronization Jump Width Time = 1 x TQ
bit 5-0 BRP5:BRP0: Baud Rate Prescaler bits
11111 = TQ = (2 x 64)/FOSC
11110 = TQ = (2 x 63)/FOSC
:
:
00001 = TQ = (2 x 2)/FOSC
00000 = TQ = (2 x 1)/FOSC
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
Note: This register is only accessible in configuration mode (see Section 22.7.1).
39500 18C Reference Manual.book Page 20 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39522A-page 22-21
Section 22. CAN
CAN
22
Register 22-30: BRGCON2: Baud Rate Control Register 2
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
SEG2PHTS SAM SEG1PH2 SEG1PH1 SEG1PH0 PRSEG2 PRSEG1 PRSEG0
bit 7 bit 0
bit 7 SEG2PHTS: Phase Segment 2 Time Select bit
1 = Freely programmable
0 = Maximum of PHEG1 or Information Processing Time (IPT), 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 SEG1PH2:SEG1PH0: Phase segment 1 bits
111 = Phase segment 1 Time = 8 x TQ
110 = Phase segment 1 Time= 7 x TQ
101 = Phase segment 1 Time = 6 x TQ
100 = Phase segment 1 Time = 5 x TQ
011 = Phase segment 1 Time = 4 x TQ
010 = Phase segment 1 Time = 3 x TQ
001 = Phase segment 1 Time = 2 x TQ
000 = Phase segment 1 Time = 1 x TQ
bit 2-0 PRSEG2:PRSEG0: Propagation Time Select bits
111 = Propagation Time = 8 x TQ
110 = Propagation Time = 7 x TQ
101 = Propagation Time = 6 x TQ
100 = Propagation Time = 5 x TQ
011 = Propagation Time = 4 x TQ
010 = Propagation Time = 3 x TQ
001 = Propagation Time = 2 x TQ
000 = Propagation Time = 1 x TQ
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
Note: This register is only accessible in configuration mode (see Section 22.7.1).
39500 18C Reference Manual.book Page 21 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39522A-page 22-22 2000 Microchip Technology Inc.
Register 22-31: BRGCON3: Baud Rate Control Register 3
U-0 R/W-0 U-0 U-0 U-0 R/W-0 R/W-0 R/W-0
— WAKFIL — — — SEG2PH2 SEG2PH1 SEG2PH0
bit 7 bit 0
bit 7 Unimplemented: Read as ’0’
bit 6 WAKFIL: Selects CAN Bus Line Filter for Wake-up bit
1 = Use CAN bus line filter for wake-up
0 = CAN bus line filter is not used for wake-up
bit 5-3 Unimplemented: Read as ’0’
bit 2-0 SEG2PH2:SEG2PH0: Phase Segment 2 Time Select bits
111 = Phase Segment 2 Time = 8 x TQ
110 = Phase Segment 2 Time = 7 x TQ
101 = Phase Segment 2 Time = 6 x TQ
100 = Phase Segment 2 Time = 5 x TQ
011 = Phase Segment 2 Time = 4 x TQ
010 = Phase Segment 2 Time = 3 x TQ
001 = Phase Segment 2 Time = 2 x TQ
000 = Phase Segment 2 Time = 1 x TQ
Note: Ignored if SEG2PHTS bit is clear.
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
39500 18C Reference Manual.book Page 22 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39522A-page 22-23
Section 22. CAN
CAN
22
22.2.6 CAN Module I/O Control Register
This subsection describes the CAN Module I/O Control register.
Register 22-32: CIOCON: CAN I/O Control Register
R/W-0 R/W-0 R/W-0 R/W-0 U-0 U-0 U-0 U-0
TX1SRC TX1EN ENDRHI CANCAP — — — —
bit 7 bit 0
bit 7 TX1SRC: TX1 Pin Data Source
1 = TX1 pin will output the CAN clock
0 = TX1 pin will output TXD
bit 6 TX1EN: TX1 Pin Enable
1 = TX1 pin will output TXD or CAN clock
0 = TX1 pin will have digital I/O function
bit 5 ENDRHI: Enable Drive High
1 = TX0, TX1 pins will drive Vdd when recessive
0 = TX0, TX1 pins will tri-state when recessive
bit 4 CANCAP: CAN Message Receive Capture Enable
1 = Enable CAN capture
0 = Disable CAN capture
bit 3-0 Unimplemented: Read as ’0’
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
39500 18C Reference Manual.book Page 23 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39522A-page 22-24 2000 Microchip Technology Inc.
22.2.7 CAN Interrupt Registers
This subsection documents the CAN Registers which are associated to Interrupts.
Register 22-33: PIR3: Peripheral Interrupt Flag Register
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
IRXIF WAKIF ERRIF TXB2IF TXB1IF TXB0IF RXB1IF RXB0IF
bit 7 bit 0
bit 7 IRXIF: CAN Invalid Received message Interrupt Flag bit
1 = An invalid message has occurred on the CAN bus
0 = No invalid message on CAN bus
bit 6 WAKIF: CAN Bus Activity Wake-up Interrupt Flag bit
1 = Activity on CAN bus has occurred
0 = No activity on CAN bus
bit 5 ERRIF: CAN bus Error Interrupt Flag bit
1 = An error has occurred in the CAN module (multiple sources)
0 = No CAN module errors
bit 4 TXB2IF: CAN Transmit Buffer 2 Interrupt Flag bit
1 = Transmit Buffer 2 has completed transmission of a message, and may be re-loaded
0 = Transmit Buffer 2 has not completed transmission of a message
bit 3 TXB1IF: CAN Transmit Buffer 1 Interrupt Flag bit
1 = Transmit Buffer 1 has completed transmission of a message, and may be re-loaded
0 = Transmit Buffer 1 has not completed transmission of a message
bit 2 TXB0IF: CAN Transmit Buffer 0 Interrupt Flag bit
1 = Transmit Buffer 0 has completed transmission of a message, and may be re-loaded
0 = Transmit Buffer 0 has not completed transmission of a message
bit 1 RXB1IF: CAN Receive Buffer 1 Interrupt Flag bit
1 = Receive Buffer 1 has received a new message
0 = Receive Buffer 1 has not received a new message
bit 0 RXB0IF: CAN Receive Buffer 0 Interrupt Flag bit
1 = Receive Buffer 0 has received a new message
0 = Receive Buffer 0 has not received a new message
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
39500 18C Reference Manual.book Page 24 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39522A-page 22-25
Section 22. CAN
CAN
22
Register 22-34: PIE3: Peripheral Interrupt Enable Register
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
IRXIE WAKIE ERRIE TXB2IE TXB1IE TXB0IE RXB1IE RXB0IE
bit 7 bit 0
bit 7 IRXIE: CAN Invalid Received Message Interrupt Enable bit
1 = Enable invalid message received interrupt
0 = Disable invalid message received interrupt
bit 6 WAKIE: CAN Bus Activity Wake-up Interrupt Enable bit
1 = Enable Bus Activity Wake-up Interrupt
0 = Disable Bus Activity Wake-up Interrupt
bit 5 ERRIE: CAN Bus Error Interrupt Enable bit
1 = Enable CAN bus Error Interrupt
0 = Disable CAN bus Error Interrupt
bit 4 TXB2IE: CAN Transmit Buffer 2 Interrupt Enable bit
1 = Enable Transmit Buffer 2 Interrupt
0 = Disable Transmit Buffer 2 Interrupt
bit 3 TXB1IE: CAN Transmit Buffer 1 Interrupt Enable bit
1 = Enable Transmit Buffer 1 Interrupt
0 = Disable Transmit Buffer 1 Interrupt
bit 2 TXB0IE: CAN Transmit Buffer 0 Interrupt Enable bit
1 = Enable Transmit Buffer 0 Interrupt
0 = Disable Transmit Buffer 0 Interrupt
bit 1 RXB1IE: CAN Receive Buffer 1 Interrupt Enable bit
1 = Enable Receive Buffer 1 Interrupt
0 = Disable Receive Buffer 1 Interrupt
bit 0 RXB0IE: CAN Receive Buffer 0 Interrupt Enable bit
1 = Enable Receive Buffer 0 Interrupt
0 = Disable Receive Buffer 0 Interrupt
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
39500 18C Reference Manual.book Page 25 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39522A-page 22-26 2000 Microchip Technology Inc.
Register 22-35: IPR3: Peripheral Interrupt Priority Register
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
IRXIP WAKIP ERRIP TXB2IP TXB1IP TXB0IP RXB1IP RXB0IP
bit 7 bit 0
bit 7 IRXIP: CAN Invalid Received Message Interrupt Priority bit
1 = High Priority
0 = Low Priority
bit 6 WAKIP: CAN Bus Activity Wake-up Interrupt Priority bit
1 = High Priority
0 = Low Priority
bit 5 ERRIP: CAN Bus Error Interrupt Priority bit
1 = High Priority
0 = Low Priority
bit 4 TXB2IP: CAN Transmit Buffer 2 Interrupt Priority bit
1 = High Priority
0 = Low Priority
bit 3 TXB1IP: CAN Transmit Buffer 1 Interrupt Priority bit
1 = High Priority
0 = Low Priority
bit 2 TXB0IP: CAN Transmit Buffer 0 Interrupt Priority bit
1 = High Priority
0 = Low Priority
bit 1 RXB1IP: CAN Receive Buffer 1 Interrupt Priority bit
1 = High Priority
0 = Low Priority
bit 0 RXB0IP: CAN Receive Buffer 0 Interrupt Priority bit
1 = High Priority
0 = Low Priority
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
39500 18C Reference Manual.book Page 26 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39522A-page 22-27
Section 22. CAN
CAN
22
Table 22-1: CAN Controller Register Map
Address Register
Name
Address Register
Name
Address Register
Name
Address Register
Name
F7Fh — F5Fh — F3Fh — F1Fh RXM1EIDL
F7Eh — F5Eh CANSTATRO1 F3Eh CANSTATRO3 F1Eh RXM1EIDH
F7Dh — F5Dh RXB1D7 F3Dh TXB1D7 F1Dh RXM1SIDL
F7Ch — F5Ch RXB1D6 F3Ch TXB1D6 F1Ch RXM1SIDH
F7Bh — F5Bh RXB1D5 F3Bh TXB1D5 F1Bh RXM0EIDL
F7Ah — F5Ah RXB1D4 F3Ah TXB1D4 F1Ah RXM0EIDH
F79h — F59h RXB1D3 F39h TXB1D3 F19h RXM0SIDL
F78h — F58h RXB1D2 F38h TXB1D2 F18h RXM0SIDH
F77h — F57h RXB1D1 F37h TXB1D1 F17h RXF5EIDL
F76h TXERRCNT F56h RXB1D0 F36h TXB1D0 F16h RXF5EIDH
F75h RXERRCNT F55h RXB1DLC F35h TXB1DLC F15h RXF5SIDL
F74h COMSTAT F54h RXB1EIDH F34h TXB1EIDH F14h RXF5SIDH
F73h CIOCON F53h RXB1EIDL F33h TXB1EIDL F13h RXF4EIDL
F72h BRGCON3 F52h RXB1SIDL F32h TXB1SIDL F12h RXF4EIDH
F71h BRGCON2 F51h RXB1SIDH F31h TXB1SIDH F11h RXF4SIDL
F70h BRGCON1 F50h RXB1CON F30h TXB1CON F10h RXF4SIDH
F6Fh CANCON F4Fh — F2Fh — F0Fh RXF3EIDL
F6Eh CANSTAT F4Eh CANSTATRO2 F2Eh CANSTATRO4 F0Eh RXF3EIDH
F6Dh RXB0D7 F4Dh TXB0D7 F2Dh TXB2D7 F0Dh RXF3SIDL
F6Ch RXB0D6 F4Ch TXB0D6 F2Ch TXB2D6 F0Ch RXF3SIDH
F6Bh RXB0D5 F4Bh TXB0D5 F2Bh TXB2D5 F0Bh RXF2EIDL
F6Ah RXB0D4 F4Ah TXB0D4 F2Ah TXB2D4 F0Ah RXF2EIDH
F69h RXB0D3 F49h TXB0D3 F29h TXB2D3 F09h RXF2SIDL
F68h RXB0D2 F48h TXB0D2 F28h TXB2D2 F08h RXF2SIDH
F67h RXB0D1 F47h TXB0D1 F27h TXB2D1 F07h RXF1EIDL
F66h RXB0D0 F46h TXB0D0 F26h TXB2D0 F06h RXF1EIDH
F65h RXB0DLC F45h TXB0DLC F25h TXB2DLC F05h RXF1SIDL
F64h RXB0EIDL F44h TXB0EIDL F24h TXB2EIDL F04h RXF1SIDH
F63h RXB0EIDH F43h TXB0EIDH F23h TXB2EIDH F03h RXF0EIDH
F62h RXB0SIDL F42h TXB0SIDL F22h TXB2SIDL F02h RXF0EIDL
F61h RXB0SIDH F41h TXB0SIDH F21h TXB2SIDH F01h RXF0SIDL
F60h RXB0CON F40h TXB0CON F20h TXB2CON F00h RXF0SIDH
Note: The shaded addresses indicate the registers that are in the access RAM.
39500 18C Reference Manual.book Page 27 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39522A-page 22-28 2000 Microchip Technology Inc.
22.3 CAN Overview
The Controller Area Network (CAN) is a serial communications protocol which efficiently supports
distributed real-time control with a very high level of robustness. The Protocol is fully
defined by Robert Bosch GmbH, in the CAN Specification V2.0B from 1991.
Its domain of application ranges from high speed networks to low cost multiplex wiring. In automotive
electronics; (engine control units, sensors, anti-skid-systems, etc.) are connected using
CAN with bit rates up to 1 Mbit/sec. The CAN Network allows a cost effective replacement of the
wiring harnesses in the automobile. The robustness of the bus in noisy environments and the
ability to detect and recover from fault conditions makes the bus suitable for industrial control
applications such as DeviceNet, SDS and other fieldbus protocols.
CAN is an asynchronous serial bus system with one logical bus line. It has an open, linear bus
structure with equal bus nodes. A CAN bus consists of two or more nodes. The number of nodes
on the bus may be changed dynamically without disturbing the communication of other nodes.
This allows easy connection and disconnection of bus nodes (e.g. for addition of system function,
error recovery or bus monitoring).
The bus logic corresponds to a "wired-AND" mechanism, "Recessive" bits (mostly, but not necessarily
equivalent to the logic level “1”) are overwritten by "Dominant" bits (mostly logic level
"0"). As long as no bus node is sending a dominant bit, the bus line is in the recessive state, but
a dominant bit from any bus node generates the dominant bus state. Therefore, for the CAN bus
line, a medium must be chosen that is able to transmit the two possible bit states (dominant and
recessive). One of the most common and cheapest ways is to use a twisted wire pair. The bus
lines are then called "CANH" and "CANL", and may be connected directly to the nodes or via a
connector. There's no standard defined by CAN regarding the connector to be used. The twisted
wire pair is terminated by terminating resistors at each end of the bus line. The maximum bus
speed is 1 Mbit, which can be achieved with a bus length of up to 40 meters. For bus lengths
longer than 40 meters the bus speed must be reduced (a 1000 m bus can be realized with a
40 Kbit bus speed). For a bus length above 1000 meters special drivers should be used. At least
20 nodes may be connected without additional equipment. Due to the differential nature of transmission,
CAN is insensitive to EMI because both bus lines are affected in the same way which
leaves the differential signal unaffected. The bus lines can also be shielded to reduce the electromagnetic
emission of the bus itself, especially at high baud rates.
The binary data is coded corresponding to the NRZ code (Non-Return-to-Zero; low
level = dominant state; high level = recessive state). To ensure clock synchronization of all bus
nodes, bit-stuffing is used. This means that during the transmission of a message a maximum of
five consecutive bits may have the same polarity. Whenever five consecutive bits of the same
polarity have been transmitted, the transmitter will insert one additional bit of the opposite polarity
into the bit stream before transmitting further bits. The receiver also checks the number of bits
with the same polarity and removes the stuff bits from the bit stream (destuffing).
In the CAN protocol it is not bus nodes that are addressed, but the address information is contained
in the messages that are transmitted. This is done via an identifier (part of each message)
which identifies the message content (e.g. engine speed, oil temperature etc.,). The identifier
additionally indicates the priority of the message. The lower the binary value of the identifier, the
higher the priority of the message.
For bus arbitration, Carrier Sense Multiple Access/Collision Detection (CSMA/CD) with
Non-Destructive Arbitration (NDA) is used. If bus node A wants to transmit a message across the
network, it first checks that the bus is in the idle state ("Carrier Sense") i.e., no node is 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
39500 18C Reference Manual.book Page 28 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39522A-page 22-29
Section 22. CAN
CAN
22
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".
22.3.1 Standard CAN vs. Extended 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 ("Standard
lD") and the 18 bit Extended identifier ("Extended ID").
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.
22.3.2 Basic CAN vs. Full CAN
There is one more CAN characteristic concerning the interface between the CAN module and
the host CPU, dividing CAN chips into "Basic CAN" and "Full CAN" devices. This distinction is
not related to Standard vs. Extended CAN, which makes it possible to use both Basic and Full
CAN devices in the same network.
In the Basic CAN devices, only basic functions of the protocol are implemented in hardware, e.g.
the generation and the check of the bit stream. The decision, if a received message has to be
stored or not (acceptance filtering) and the whole message management has to be done by software,
i.e., by the host CPU. In addition, the CAN chip typically provides only one transmit buffer
and one or two receive buffers. So the host CPU load is quite high using Basic CAN modules,
and these devices can only be used at low baud rates and low bus loads with only a few different
messages. The advantages of Basic CAN are the small chip size leading to low costs of these
devices.
Full CAN devices implement 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 the messages objects can be programmed
in so 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.
39500 18C Reference Manual.book Page 29 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39522A-page 22-30 2000 Microchip Technology Inc.
22.3.3 ISO Model
The lSO/OSl Reference Model is used to define the layers of protocol of a communication system
as shown in Figure 22-2. At the highest end, the applications need to communicate between
each other. At the lowest end, some physical medium is used to provide electrical signaling.
The higher levels of the protocol are run by software. Within the CAN bus specification, there is
no definition of the type of message or the contents or meaning of the messages transferred.
These definitions are made in systems such as Volcano, the Volvo automotive CAN specification;
J1939, the U.S. heavy truck multiplex wiring specification; and Allen-Bradly DeviceNet and
Honeywell SDS, examples of industrial protocols.
The CAN bus module definition encompasses two levels of the overall protocol.
• The Data Link Layer
- The Logical Link Control (LLC) sub layer
- The Medium Access Control (MAC) sub layer
• The Physical Layer
- The Physical Signaling (PLS) sub layer
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 it is 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
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
so as to allow transmission medium and signal level implementations to be optimized for their
application. The most common example is defined in ISO11898 Road Vehicles multiplex wiring
specification.
39500 18C Reference Manual.book Page 30 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39522A-page 22-31
Section 22. CAN
CAN
22
Figure 22-2: CAN Bus in ISO/OSI Reference Model
OSI REFERENCE LAYERS
Presentation
Transport
Data Link Layer
LLC (Logical Link Control)
Acceptance Filtering
Overload Notification
Recovery Management
MAC (Medium Access Control)
Data Encapsulation/Decapsulation
Frame Coding (stuffing, destuffing)
Medium Access Management
Error Detection
Error Signalling
Acknowledgment
Serialization/Deserialization
Physical Layer
PLS (Physical Signalling)
Bit Encoding/Decoding
Bit Timing
Synchronization
PMA (Physical Medium Attachment)
Driver/Receiver Characteristics
MDI (Medium Dependent Interface)
Connectors
Fault
confinement
(MAC-LME)
Bus Failure
management
(PLS-LME)
Supervisor
Shaded Regions
Implemented by
the CAN Module
Has to be Implemented
in PICmicro Firmware
Session
Network
Application
CAN
Transceiver
Chip
Connector
39500 18C Reference Manual.book Page 31 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39522A-page 22-32 2000 Microchip Technology Inc.
22.4 CAN Bus Features
The CAN module is a communication controller implementing the CAN 2.0A/B protocol as
defined in the BOSCH specification. The module will support CAN 1.2, CAN 2.0A, CAN 2.0B
Passive, and CAN 2.0B Active versions of the protocol. The module implementation is a Full CAN
system.
The module features are as follows:
• Implementation of the CAN protocol CAN 1.2, CAN 2.0A and CAN 2.0B
• Standard and extended data frames
• Data length from 0 - 8 bytes
• Programmable bit rate up to 1 Mbit/sec
• Support for remote frames
• Double buffered receiver with two prioritized received message storage buffers
• 6 full (standard/extended identifier) acceptance filters, 2 associated with the high priority
receive buffer, and 4 associated with the low priority receive buffer
• 2 full acceptance filter masks, one each associated with the high and low priority receive
buffers
• Three transmit buffers with application specified prioritization and abort capability
• Programmable wake-up functionality with integrated low-pass filter
• Programmable loop-back mode and programmable state clocking supports self-test operation
• Signaling via interrupt capabilities for all CAN receiver and transmitter error states
• Programmable clock source
• Programmable link to timer module for time-stamping and network synchronization
• Low power SLEEP mode
39500 18C Reference Manual.book Page 32 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39522A-page 22-33
Section 22. CAN
CAN
22
22.5 CAN Module Implementation
This subsection will discuss the implementation of the CAN module and the supported frame formats.
22.5.1 Overview of the Module
The CAN bus module consists of a Protocol Engine and message buffering and control. The Protocol
Engine can best be understood by defining the types of data frames to be transmitted and
received by the module. These blocks are shown in Figure 22-3.
Figure 22-3: CAN Buffers and Protocol Engine Block Diagram
Acceptance Filter
RXF2
R
X
B
1
A
c
c
e
p
t
A
c
c
e
p
t
Identifier
Data Field Data Field
Identifier
Acceptance Mask
RXM1
Acceptance Filter
RXF3
Acceptance Filter
RXF4
Acceptance Filter
RXF5
M
A
B
Acceptance Mask
RXM0
Acceptance Filter
RXF0
Acceptance Filter
RXF1
R
X
B
0
MSGREQ
TXB2
TXABT
TXLARB
TXERR
MTXBUFF
MESSAGE
Message
Queue
Control Transmit Byte Sequencer MSGREQ
TXB1
TXABT
TXLARB
MSGREQ
TXERR
MTXBUFF
MESSAGE
TXB0
TXABT
TXLARB
TXERR
MTXBUFF
MESSAGE
Transmit Shift Receive Shift
Receive
Error
Transmit
Error
Protocol
RXERRCNT
TXERRCNT
Finite
State
Machine
Counter
Counter
Transmit
Logic
Bit
Timing
Logic
TX
CANRX
Bit Timing
Generator
PROTOCOL
ENGINE
BUFFERS
CRC Generator CRC Check
CANTX
39500 18C Reference Manual.book Page 33 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39522A-page 22-34 2000 Microchip Technology Inc.
22.5.1.1 Typical Connection
Figure 22-4 shows a typical connection between multiple CAN nodes with CAN bus terminators.
Figure 22-4: CAN Bus Connection with CAN Bus Terminators
22.5.2 CAN Protocol Engine
The CAN protocol engine combines several functional blocks, shown in Figure 22-5. These units
and the functions they provide are described below.
The heart of the engine is the Protocol Finite State Machine (FSM). This state machine
sequences through the messages on a bit by bit basis, changing states of the machine as various
fields of various frame types are transmitted or received. The framing messages in Section 22.6
show the states associated with each bit. The FSM is a sequencer controlling the sequential data
stream between the TX/RX Shift Register, the CRC Register, and the bus line. The FSM also
controls the Error Management Logic (EML) and the parallel data stream between the TX/RX
Shift Register and the buffers such that the processes of reception arbitration, transmission, and
error signaling are performed according to the CAN protocol. Note that the automatic retransmission
of messages on the bus line is handled by the FSM.
The data interface to the engine consists of byte wide transmit and receive data. Rather than
assembling and shifting an entire frame, the frames are broken into bytes. A receive or transmit
address from the Protocol FSM signifies which byte of the frame is current. For transmission, the
appropriate byte from the transmit buffer is selected and presented to the engine, which then
uses an 8 bit shift register to serialize the data. For reception, an 8 bit shift register assembles a
byte which is then loaded into the appropriate byte in the message assembly buffer.
The Cyclic Redundancy Check Register generates the Cyclic Redundancy Check (CRC) code
to be transmitted over the data bytes and checks the CRC code of incoming messages.
The Error Management Logic (EML) is responsible for the fault confinement of the CAN device.
Its counters, the Receive Error Counter and the Transmit Error Counter, are incremented and
decremented by commands from the Bit Stream Processor. According to the values of the error
counters, the CAN controller is set into the states error active, error passive or bus off.
The Bit Timing Logic (BTL) monitors the bus line input and handles the bus line related bit timing
according to the CAN protocol. The BTL synchronizes on a recessive to dominant busline transition
at Start of Frame (hard synchronization) and on any further recessive to dominant bus line
transition, if the CAN controller itself does not transmit a dominant bit (resynchronization). The
BTL also provides programmable time segments to compensate for the propagation delay time
and for phase shifts and in defining the position of the Sample Point in the bit time. The programming
of the BTL depends on the baud rate and on external physical delay times.
CAN
Node 1
CAN
Node 2
CAN
Node 3
CAN
Node 4
CAN
Node 5
CAN
Node n
Bus Terminator CAN BUS Bus Terminator
39500 18C Reference Manual.book Page 34 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39522A-page 22-35
Section 22. CAN
CAN
22
Figure 22-5: CAN Protocol Engine Block Diagram
Bit Timing Logic (BTL)
CRC <14:0>
Comparator
Receive Shift Transmit Shift
Sample <2:0>
Majority
Decision
StuffReg <5:0>
Comparator
Transmit Logic
Receive
Error Counter
Transmit
Error Counter
Protocol
FSM
CANRX
SAM
BusMon
Received Data Data to Transmit
CANTX
RXERRCNT
TXERRCNT
Interface to Standard Buffer
39500 18C Reference Manual.book Page 35 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39522A-page 22-36 2000 Microchip Technology Inc.
22.5.3 CAN Module Functionality
The CAN protocol engine handles all functions for receiving and transmitting messages on the
CAN bus. Messages are transmitted by first loading the appropriate data registers. Status and
errors can be checked by reading the appropriate registers. Any message detected on the CAN
bus is checked for errors and then matched against filters to see if it should be received and
stored in one of the 2 receive registers.
The CAN Module supports the following Frame types:
• Standard Data Frame
• Extended Data Frame
• Remote Frame
• Error Frame
• Overload Frame
• Interframe Space
Section 22.6 describes the Frames and their formats.
39500 18C Reference Manual.book Page 36 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39522A-page 22-37
Section 22. CAN
CAN
22
22.6 Frame Types
This chapter describes the CAN Frame types supported by the CAN module.
22.6.1 Standard Data Frame
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 22-6. 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 Identifier
Extension (IDE) bit 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
(0 - 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 End of Frame (EOF) field,
which consists of seven recessive bits (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.
22.6.1.1 Extended Data Frame
In the Extended CAN Data Frame, shown in Figure 22-7, 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
remaining 18 bits of the identifier ("lD-Extension") and the 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 significant)
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 lntermission) is constructed in the same way as for a Standard Data Frame.
39500 18C Reference Manual.book Page 37 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39522A-page 22-38 2000 Microchip Technology Inc.
22.6.1.2 Remote Frame
Normally data transmission is 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 2 differences between a Remote Frame and a Data Frame, shown in Figure 22-8. 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.
22.6.1.3 The Error Frame
An Error Frame is generated by any node that detects a bus error. An error frame, shown in
Figure 22-9, 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
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 bus master 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.
22.6.1.4 The Overload Frame
An Overload Frame, shown in Figure 22-10, has the same format as an Active Error Frame. An
Overload Frame, however can only be generated during lnterframe Space. This way, an Overload
Frame can be differentiated from an Error Frame (an Error Frame is sent during the transmission
of a message). The Overload Frame consists of 2 fields, an Overload Flag followed by an Overload
Delimiter. The Overload Flag consists of six dominant bits followed by Overload Flags generated
by other nodes (as for active error flag, again giving a maximum of twelve dominant bits).
The Overload Delimiter consists of eight recessive bits. An Overload Frame can be generated by
a node as a result of 2 conditions. First, the node detects a dominant bit during lnterframe Space
which is an illegal condition. Second, due to internal conditions, the node is not yet able to start
reception of the next message. A node may generate a maximum of 2 sequential Overload
Frames to delay the start of the next message.
22.6.1.5 The Interframe Space
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 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.
39500 18C Reference Manual.book Page 38 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39522A-page 22-39
Section 22. CAN
CAN
22
Figure 22-6: Standard Data Frame
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0
INT Suspend
Transmit
Bus Idle Any Frame
Inter-Frame Space
Start of Frame Data Frame or Remote Frame
3 8
0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
Start of Frame
Data Frame (number of bits = 44 + 8 N)
12
Arbitration Field
ID 10
11
ID3
ID0
Identifier
Message
Filtering
Stored in Buffers
RTR
IDE
RB0
DLC3
DLC0
6
4
Control
Field
Data
Length
Code
Reserved Bits
8N(≤ N ≤ 8)
Data Field
8 8
Stored in Transmit/Receive Buffers
Bit-Stuffing
16
CRC Field
15
CRC
7
End of
Frame
CRC Del
Acknowledgment
ACK Del 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 INT Suspend Transmit Bus Idle Any Frame Inter-Frame Space
Start of Frame Data Frame or Remote Frame
3 8
39500 18C Reference Manual.book Page 39 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39522A-page 22-40
2000 Microchip Technology Inc.
F
igu
r
e
2
2
-
7
:
E
x
t
e
n
d
e
d
D
a
t
a
F
o
r
m
a
t
1 1 1 1 1 0
Bus Idle
Start of Frame Data Frame or Remote Frame
0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
Start of FrameArbitration Field
32
11
ID10
ID3
ID0
IDE
Identifier
Message
Filtering
Stored in Buffers
SRR
EID17
EID0
RTR
RB1
RB0
DLC3
18
DLC0
6
Control
Field
4
Reserved bitsData Length Code Stored in Transmit/Receive Buffers
8 8
Data Frame (number of bits = 64 + 8 N)
8 N (N ≤ 8)
Data Field
1 1 1 1 1 1 1 1
16
CRC Field
15
CRC
CRC Del
Acknowledgment
ACK Del
End of
Frame
7
Bit-Stuffing
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0
INT Suspend
Transmit
Bus Idle Any Frame
Inter-Frame Space
Start of Frame Data Frame or Remote Frame 3 8
Extended Identifier
39500 18C Reference Manual.book Page 40 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39522A-page 22-41
Section 22. CAN
CAN
22
Figure 22-8: Remote Data Frame
Identifier
Message
Filtering
Stored in Buffers
Data
Length
Code
Reserved Bits
Bit-Stuffing
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0
INT Suspend
Transmit
Bus Idle Any Frame
Inter-Frame Space
Start of Frame Data Frame or Remote Frame
3 8
0 1 0 0 1 1 1 1 1 1 1 1 1
Start of Frame
Remote Frame (number of bits = 44)
12
Arbitration Field
ID 10
11
ID0
RTR
IDE
RB0
DLC3
DLC0
6
4
Control
Field
16
CRC Field
15
CRC
7
End of
Frame
CRC Del
Acknowledgment
ACK Del 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 INT Suspend Transmit Bus Idle Any Frame Inter-Frame Space
Start of Frame Data Frame or Remote Frame
3 8
39500 18C Reference Manual.book Page 41 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39522A-page 22-42 2000 Microchip Technology Inc.
Figure 22-9: Error Frame
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0
INT Suspend
Transmit
Bus Idle Any Frame
Inter-Frame Space
Start of Frame Data Frame or Remote Frame
3 8
0 0 0 0
Start of Frame
Interrupted Data Frame
12
Arbitration Field
ID 10
11
ID3
ID0
Identifier
Message
Filtering
RTR
IDE
RB0
DLC3
DLC0
6
4
Control
Field
Data
Length
Code
Reserved Bits
8N (≤ N ≤ 8)
Data Field
8 8
Bit-Stuffing
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0
INT Suspend
Transmit
Bus Idle Any Frame
Inter-Frame Space
Start of Frame Data Frame or Remote Frame
3 8
0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0
Data Frame or
Remote Frame
Error Frame
6
Error
Flag
≤ 6
Echo
Error
Flag
8
Error
Delimiter
Inter-Frame Space or
Overload Frame
39500 18C Reference Manual.book Page 42 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39522A-page 22-43
Section 22. CAN
CAN
22
F
i
g
ure 22
-10:
Over
l
oad
Frame 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0
INT Suspend
Transmit
Bus Idle Any Frame
Inter-Frame Space
Start of Frame Data Frame or Remote Frame 3 8
0 1 0 0 1 1 1 1 1 1 1 1 1
Start of Frame
Remote Frame (number of bits = 44)
12
Arbitration Field
ID 10
11
ID0
RTR
IDE
RB0
DLC3
DLC0
6
4
Control
Field
16
CRC Field
15
CRC
7
End of
Frame
CRC Del
Acknowledgment
ACK Del
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0
INT Suspend
Transmit
Bus Idle Any Frame
Inter-Frame Space
Start of Frame Data Frame or Remote Frame 3 8
0 0 0 0 0 0 0 1 1 1 1 1 1 1 1
Overload Frame
End of Frame or
Error Delimiter or
Overload Delimiter
6
Overload
Flag
Overload
Delimiter
8 Inter-Frame Space or Error Frame
39500 18C Reference Manual.book Page 43 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39522A-page 22-44 2000 Microchip Technology Inc.
22.7 Modes of Operation
The CAN Module can operate in one of several operation modes selected by the user. These
modes include:
• Initialization Mode
• Disable Mode
• Normal Operation Mode
• Listen Only Mode
• Loop Back Mode
• Error Recognition Mode (selected through CANRXM bits)
Modes are requested by setting the REQOP2:REQOP0 bits except the Error Recognition Mode,
which is requested through the CANRXM bits. Entry into a mode is acknowledged by monitoring
the OPMODE bits. The module will not change the mode and the OPMODE2:OPMODE0 bits
until a change in mode is acceptable, generally during bus idle time which is defined as at least
11 consecutive recessive bits.
22.7.1 Initialization Mode
In the initialization mode, the module will not transmit or receive. The error counters are cleared
and the interrupt flags remain unchanged. The programmer will have access to configuration registers
that are access restricted in other modes. The CAN bus configuration mode is explained
in Section 22.8.
39500 18C Reference Manual.book Page 44 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39522A-page 22-45
Section 22. CAN
CAN
22
22.7.2 Disable Mode
In Disable Mode, the module will not transmit or receive. The module has the ability to set the
WAKIF bit due to bus activity, however any pending interrupts will remain and the error counters
will retain their value.
If the REQOP2:REQOP0 bits = 001, the module will enter the module disable mode. This mode
is similar to disabling other peripheral modules by turning off the module enables. This causes
the module internal clock to stop unless the module is active (i.e., receiving or transmitting a message).
If the module is active, the module will wait for 11 recessive bits on the CAN bus, detect
that condition as an idle bus then accept the module disable command. When the
OPMODE2:OPMODE0 bits = 001, that indicates whether the module successfully went into
module disable mode (see Figure 22-11).
The WAKIF interrupt is the only module interrupt that is still active in the module disable mode.
If the WAKIE is set, the processor will receive an interrupt whenever the CAN bus detects a dominant
state, as occurs with a Start of Frame (SOF).
The I/O pins will revert to normal I/O function when the module is in the module disable mode.
Figure 22-11: Entering and Exiting Module Disable Mode
1 2 4 5
- Processor writes REQOP2:REQOP0 while module receiving/transmitting message. Module continues with CAN message.
- Module detects 11 recessive bits. Module acknowledges disable mode and sets OPMODE2:OPMODE0 bits. Module disables.
- Processor writes REQOP2:REQOP0 during CAN bus activity. Module waits for 11 recessive bits before accepting activate.
- Module detects 11 recessive bits. Module acknowledges normal mode and sets OPMODE2:OPMODE0 bits. Module activates.
OSC1
CAN BUS
CAN Module
Disabled
3
REQOP2:
OPMODE2:
001
000 001
000 000
000
- CAN bus message will set WAKIF bit. If WAKIE = ’1’, processor will vector to the interrupt address. CAN message ignored.
WAKIF
WAKIE
1
2
3
4
5
REQOP0
OPMODE0
39500 18C Reference Manual.book Page 45 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39522A-page 22-46 2000 Microchip Technology Inc.
22.7.2.1 SLEEP Mode
A CPU SLEEP instruction will stop the crystal oscillator and shut down all system clocks. The user
is responsible to take care that the module is not active when the CPU goes into SLEEP mode.
The pins will revert into normal I/O function, dependent on the value in the TRIS register.
The recommended procedure is to bring the module into disabled mode before the CPU SLEEP
instruction is executed.
Figure 22-12 illustrates the sequence of events when a CAN message is received during execution
of the SLEEP instruction.
Figure 22-12:SLEEP Interrupted By Message
2 3 4
- CAN bus activity sets WAKIF flag. If GIE = ’1’ processor will vector to interrupt address, bypassing SLEEP instruction.
- Processor attempts to execute SLEEP instruction. Since WAKIF = ’1’, WAKIE = ’1’ and GIE = ’0’
OSC1
CAN BUS
CAN Module
Disabled
REQOP2:
OPMODE2:
001
000 001
000 000
000
SLEEP
WAKIF
WAKIE
1
- Processor requests and receives module disable mode. Wake up interrupt enabled.
processor will execute NOP in place of SLEEP instruction. CAN message ignored.
- Processor requests and receives module normal mode. CAN activity resumes.
1
2
3
4
0 0
REQOP0
OPMODE0
39500 18C Reference Manual.book Page 46 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39522A-page 22-47
Section 22. CAN
CAN
22
22.7.2.2 Wake-up from SLEEP
Figure 22-13 depicts how the CAN module will execute the SLEEP instruction and how the module
wakes up on bus activity. Upon a Wake-up from SLEEP the WAKIF flag is set.
The module will monitor the RX line for activity while the MCU is in SLEEP mode.
If the module is in CPU SLEEP mode and the WAKIE wake-up interrupt enable is set, the module
will generate an interrupt, bringing up the CPU. Due to the delays in starting up the oscillator and
CPU, the message activity that caused the wake-up will be lost.
If the module is in CPU SLEEP mode and the WAKIE is not set, no interrupt will be generated
and the CPU and the module will continue to sleep.
If the CAN module is in disable mode, the module will wake-up and, depending on the condition
of the WAKIE bit, may generate an interrupt. It is expected that the module will correctly receive
the message that caused the wake-up from SLEEP mode.
The module can be programmed to apply a low-pass filter function to the RxCAN input line while
the module or the CPU is in SLEEP mode. This feature can be used to protect the module from
Wake-up due to short glitches on the CAN bus lines. Such glitches can result from electromagnetic
inference within noisy environments. The WAKFIL bit enables or disables the filter.
Figure 22-13:Processor SLEEP and CAN Bus Wake-up Interrupt
TOST
Processor in
SLEEP
2 3 4 5
- Processor executes SLEEP instruction.
- SOF of message wakes up processor. Oscillator start time begins. CAN message lost. WAKIF bit set.
- Processor completes oscillator start time. Processor resumes program or interrupt, based on GIE bits.
accepting CAN bus activity. CAN message lost.
- Module detects 11 recessive bits. Module will begin to receive messages and transmit any pending messages.
OSC1
CAN BUS
CAN Module
Disabled
REQOP2:
OPMODE2:
001
000 001
000 000
000
SLEEP
WAKIF
WAKIE
1
- Processor requests and receives module disable mode. Wake-up interrupt enabled.
Processor requests normal operating mode. Module waits for 11 recessive bits before
1
2
3
4
5
REQOP0
OPMODE0
39500 18C Reference Manual.book Page 47 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39522A-page 22-48 2000 Microchip Technology Inc.
22.7.3 Normal Operation Mode
Normal operating mode is selected when REQOP2:REQOP0 = 000. In this mode, the module is
activated, the I/O pins will assume the CAN bus functions. The module will transmit and receive
CAN bus messages as described in subsequent paragraphs.
22.7.4 Listen Only Mode
Listen only mode and loopback modes are special cases of normal operation mode to allow system
debug. If the listen only mode is activated, the module on the CAN bus is passive. The transmitter
buffers revert to Port I/O function. The receive pins remain input. For the receiver, no error
flags or acknowledge signals are sent. The error counters are deactivated in this state. The listen
only mode can be used for detecting the baud rate on the CAN bus. To use this, it is necessary
that there are at least two further nodes that communicate with each other. The baud rate can be
detected empirically by testing different values. This mode is also useful as a bus monitor without
influencing the data traffic.
22.7.5 Error Recognition Mode
The module can be set to ignore all errors and receive any message. The error recognition mode
is activated by setting the RXM1:RXM0 bits in the RXBnCON registers to 11. In this mode the
data which is in the message assembly buffer until the error time is copied in the receive buffer
and can be read via the CPU interface. In addition the data which was on the internal sampling
of the CAN bus at the error time and the state vector of the protocol state machine and the bit
counter CntCan are stored in registers and can be read.
22.7.6 Loop Back Mode
If the loopback mode is activated, the module will connect the internal transmit signal to the internal
receive signal at the module boundary. The transmit and receive pins revert to their Port I/O
function.
The transmitter will receive an acknowledge for its sent messages. Special hardware will generate
an acknowledge for the transmitter.
22.8 CAN Bus Initialization
After a RESET the CAN module is in the configuration mode (OPMODE2 is set). The error
counters are cleared and all registers contain the reset values. It should be ensured that the initialization
is performed before REQOP2 bit is cleared.
22.8.1 Initialization
The CAN module has to be initialized before the activation. This is only possible if the module is
in the configuration mode. The configuration mode is requested by setting REQOP2 bit. Only
when the status bit OPMODE2 has a high level, the initialization can be performed. Afterwards
the configuration registers and the acceptance mask registers and the acceptance filter registers
can be written. The module is activated by setting the control bits CFGREQ to zero.
The module will protect the user from accidentally violating the CAN protocol through programming
errors. All registers which control the configuration of the module can not be modified while
the module is on-line. The CAN module will not be allowed to enter the configuration mode while
a transmission is taking place. The CONFIG mode serves as a lock to protect the following registers.
• All Module Control Registers
• Configuration Registers
• Bus Timing Registers
• Identifier Acceptance Filter Registers
• Identifier Acceptance Mask Registers
39500 18C Reference Manual.book Page 48 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39522A-page 22-49
Section 22. CAN
CAN
22
22.9 Message Reception
This chapter describes the message reception.
22.9.1 Receive Buffers
The CAN bus module has 3 receive buffers. However, one of the receive buffers is always committed
to monitoring the bus for incoming messages. This buffer is called the message assembly
buffer, MAB. So there are 2 receive buffers visible, RXB0 and RXB1, that can essentially instantaneously
receive a complete message from the protocol engine. The CPU can be operating on
one while the other is available for reception or holding a previously received message.
The MAB holds the destuffed bit stream from the bus line to allow parallel access to the whole
data or Remote Frame for the acceptance match test and the parallel transfer of the frame to the
receive buffers. The MAB will assemble all messages received. These messages will be transferred
to the RXBn buffers only if the acceptance filter criterion are met. When a message is
received, the RXFUL bit will be set. This bit can only be set by the module when a message is
received. The bit is cleared by the CPU when it has completed processing the message in the
buffer. This bit provides a positive lockout to ensure that the CPU has finished with the message
buffer. If the RXnIE bit is set , an interrupt will be generated when a message is received.
There are 2 programmable acceptance filter masks associated with the receive buffers, one for
each buffer.
When the message is received, the FILHIT2:FILHIT0 bits (RXBnCON register) indicate the
acceptance criterion for the message. The number of the acceptance filter that enabled the
reception will be indicated as well as a status bit that indicates that the received message is a
remote transfer request.
39500 18C Reference Manual.book Page 49 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39522A-page 22-50 2000 Microchip Technology Inc.
22.9.1.1 Receive Buffer Priority
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 criticality 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 22-14 shows a block diagram of the receive buffer, while Figure 22-15 shows a flow
chart for receive operation.
Figure 22-14:The Receive Buffers
Acceptance Mask
RXM1
Acceptance Filter
RXF2
Acceptance Filter
RXF3
Acceptance Filter
RXF4
Acceptance Filter
RXF5
R
X
B
1
M
A
B
R
X
B
0
Acceptance Mask
RXM0
Acceptance Filter
RXF0
Acceptance Filter
RXF1
A
c
c
e
p A t c
c
e
p
t
Identifier
Data Field Data Field
Identifier
39500 18C Reference Manual.book Page 50 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39522A-page 22-51
Section 22. CAN
CAN
22
Figure 22-15:Receive Flowchart
Start
Detect
Start of
Message
?
Valid
Message
Received
?
Generate
Error
Message
Identifier meets
a filter criteria
?
Is
RXRDY=0
?
Go to Start
Move message into RXB0
Set RXRDY = 1
Set FILHIT<2:0>
Is
RXRDY=0
?
Move message into RXB1
Set RXRDY=1
Yes, meets criteria
for RXBO
Yes, meets criteria
for RXB1
No
Generate
Interrupt Yes
Yes
No No
Yes
Yes
No
No
Yes
Yes
Frame
The RXRDY bit determines if the
receive register is empty and
able to accept a new message.
No Yes
No
Generate Overrun Error:
Begin Loading Message into
Message Assembly Buffer (MAB)
was met
Is
RXIE=1
?
Does
RXIE=1
?
Is
RX0DBEN=1
?
The RX0DBEN bit determines
if RXB0 can roll over
into RXB1 if it is full.
Set RX0OVFL
Generate Overrun Error:
Set RX1OVFL
Does ERRIE=1 ?
No
Go to Start
Yes
Set FILHIT<0> No
according to which filter criteria
was met
Set CANSTAT<3:0> according
to which receive buffer the
message was loaded into
according to which filter criteria
39500 18C Reference Manual.book Page 51 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39522A-page 22-52 2000 Microchip Technology Inc.
22.9.2 Message Acceptance Filters
The message acceptance filters and masks are used to determine if a message in the message
assembly buffer should be loaded into either of the receive buffers. Once a valid message has
been received into the MAB, the identifier fields of the message are compared to the filter values.
If there is a match, that message will be loaded into the appropriate receive buffer. The filter
masks are used to determine which bits in the identifiers are examined with the filters. A truthtable
is shown in Table 22-2 that indicates how each bit in the identifier is compared to the masks
and filters to determine if the message should be loaded into a receive buffer. The mask bit
essentially determines which bits to apply the filter to. If any mask bit is set to a zero, then that
bit will automatically be accepted regardless of the filter bit.
Table 22-2: Filter/Mask Truth Table
The acceptance filter looks at incoming messages for the EXIDEN bit to determine how to compare
the identifiers. If the EXIDEN bit is clear, the message is a standard frame, and only filters
with the EXIDEN bit clear are compared. If the EXIDEN bit is set, the message is an extended
frame, and only filters with the EXIDEN bit set are compared. Configuring the RXM1:RXM0 bits
to 01 or 10 can override the EXIDEN bit.
As shown in the Receive Buffers Block Diagram, Figure 22-14, RXF0 and RXF1 filters with 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 coded into a portion of the RXBnCON
register. The RXB1CON register contains the FILHIT2:FILHIT0 bits. They are coded as
shown in Table 22-3.
Table 22-3: Acceptance Filter
Mask Bit n Filter Bit n Message
Identifier bit
Accept or
reject bit n
0x x Accept
10 0 Accept
10 1 Reject
11 0 Reject
11 1 Accept
Legend: x = 0 don’t care.
FILHIT2:FILHIT0 Acceptance
Filter Comment
000(1) RXF0 Only if RX0DBEN = 1
001(1) RXF1 Only if RX0DBEN = 1
010 RXF2 —
011 RXF3 —
100 RXF4 —
101 RXF5 —
Note 1: Is only valid if the RX0DBEN bit is set.
39500 18C Reference Manual.book Page 52 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39522A-page 22-53
Section 22. CAN
CAN
22
The coding of the RX0DBEN bit enables these 3 bits to be used similarly to the FILHIT bits and
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 RX0DBEN bit is clear, there are 6 codes corresponding to the 6 filters. If the RX0DBEN 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.
Figure 22-16 shows a block diagram of the message acceptance filters.
Figure 22-16:Message Acceptance Filter
Acceptance Filter Register Acceptance Mask Register
RxRqst
Message Assembly Buffer
RXFn0
RXFn1
RXFnn
RXMn0
RXMn1
RXMnn
Identifier
39500 18C Reference Manual.book Page 53 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39522A-page 22-54 2000 Microchip Technology Inc.
22.9.3 Receiver Overrun
An overrun condition occurs when the MAB has assembled a valid received message, the message
is accepted through the acceptance filters, however, the receive buffer associated with the
filter has not been designated as clear of the previous message.
The overrun error flag, RXnOVR and the EERIF bit will be set and the message in the MAB will
be discarded. While in the overrun situation, the module will stay synchronized with the CAN bus
and is able to transmit messages but will discard all incoming messages destined for the overrun
buffer.
If the RX0DBEN bit is clear, RXB1 and RXB0 operate independently. When this is the case, a
message intended for RXB0 will not be diverted into RXB1 if RXB0 contains an unread message
and the RX0OVFL bit will be set.
If the RX0DBEN bit is set, the overrun for RXB0 is handled differently. If a valid message is
received for RXB0 and RXFUL = 1 indicates that RXB0 is full and RXFUL = 0 indicates that
RXB1 is empty, the message for RXB0 will be loaded into RXB1. An overrun error will not be generated
for RXB0. If a valid message is received for RXB0 and RXFUL = 1 and RXFUL = 1 indicating
that both RXB0 and RXB1 are full the message will be lost and an overrun will be indicated
for RXB1.
If the RX0DBEN bit is clear, there are 6 codes corresponding to the 6 filters. If the RX0DBEN 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. These codes are given in Table 22-4.
Table 22-4: Buffer Reception and Overflow Truth Table
Message
Matches
Filter
0 or 1
Message
Matches
Filter
2,3,4,5
RXFUL0
Bit
RXFUL1
Bit
RX0DBEN
Bit Action Action
0 0 XX X None No message received
0 1 X0 X MAB → RXB1 Message for RXB1, RXB1 available
0 1 X1 X MAB discarded
RX1OVFL = 1
Message for RXB1, RXB1 full
1 0 0X X MAB → RXB0 Message for RXB0, RXB0 available
1 0 1X 0 MAB discarded
RX0OVFL = 1
Message for RXB0, RXB0 full,
RX0DBEN not enabled
1 0 10 1 MAB → RXB1 Message for RXB0, RXB0 full,
RX0DBEN enabled, RXB1 available
1 0 11 1 MAB discarded
RX1OVFL = 1
Message for RXB0, RXB0 full,
RX0DBEN enabled, RXB1 full
1 1 0X X MAB → RXB0 Message for RXB0 and RXB1, RXB0
available
1 1 1X 0 MAB discarded
RX0OVFL = 1
Message for RXB0 and RXB1, RXB0 full,
RX0DBEN not enabled
1 1 10 1 MAB → RXB1 Message for RXB0 and RXB1, RXB0 full,
RX0DBEN enabled, RXB1 available
1 1 11 1 MAB discarded
RX1OVFL = 1
Message for RXB0 and RXB1, RXB0 full,
RX0DBEN enabled, RXB1 full
Legend: X = Don’t care.
39500 18C Reference Manual.book Page 54 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39522A-page 22-55
Section 22. CAN
CAN
22
22.9.4 Effects of a RESET
Upon any RESET the CAN module has to be initialized. All registers are set according to the
reset values. The content of a received message is lost. The initialization is discussed in
Section 22.8.
22.9.5 Baud Rate Setting
All nodes on any particular CAN bus must have the same nominal bit rate. The Baud Rate is set
once during the initialization mode of the CAN module. After that the baud Rate is not changed
again. Section 22.12 explains the setting of the Baud Rate.
22.9.6 Receive Errors
The CAN module will detect the following receive errors:
• Cyclic Redundancy Check (CRC) Error
• Bit Stuffing Error
• Invalid message receive error.
These receive errors do not generate an interrupt. However, the receive error counter is incremented
by one in case one of these errors occur. The RXWARN bit indicates that the Receive
Error Counter has reached the CPU Warning limit of 96 and an interrupt is generated.
22.9.6.1 Cyclic Redundancy Check (CRC) Error
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.
22.9.6.2 Bit Stuffing Error
If in between Start of Frame and 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.
22.9.6.3 Invalid Message Received Error
If any type of error occurs during reception of a message, an error will be indicated by the IXRIF
bit. 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 occur, but an indicator
that an error has occurred on the CAN bus.
39500 18C Reference Manual.book Page 55 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39522A-page 22-56 2000 Microchip Technology Inc.
22.9.6.4 Rules for Modifying the Receive Error Counter
The Receive Error Counter is modified according to the following rules:
• When the receiver detects an error, the Receive Error Counter is incremented by 1, except
when the detected error was a Bit Error during the transmission of an Active Error Flag or
an Overload Flag.
• When the receiver detects a "dominant" bit as the first bit after sending an Error Flag the
Receive Error Counter will be incremented by 8.
• If a Receiver detects a Bit Error while sending an Active Error Flag or an Overload Flag the
Receive Error Counter is incremented by 8.
• Any Node tolerates up to 7 consecutive "dominant" bits after sending an Active Error Flag,
Passive Error Flag or an Overload Flag. After detecting the 14th consecutive "dominant" bit
(in case of an Active Error Flag or an Overload flag) or after detecting the 8th consecutive
"dominant" following a passive error flag, and after each sequence of additional eight consecutive
"dominant" bits every Transmitter increases its Transmission Error Counter and
every Receiver increases its Receive Error Counter by 8.
• After a successful reception of a message (reception without error up to the ACK slot and
the successful sending of the ACK bit), the Receive Error Counter is decreased by one, if
the Receive Error Counter was between 1 and 127. If the Receive Error Counter was 0 it
will stay 0. If the Receive Error Counter was greater than 127, it will change to a value
between 119 and 127.
22.9.7 Receive Interrupts
Several Interrupts are linked to the message reception. The receive interrupts can be broken up
into two separate groups:
• Receive Error Interrupts
• Receive interrupts
22.9.7.1 Receive Interrupt
A message has been successfully received and loaded into one of the receive buffers. This interrupt
is activated immediately after receiving the End of Frame (EOF) field. Reading the RXnIF
flag will indicate which receive buffer caused the interrupt. Figure 22-17 depicts when the receive
buffer interrupt flag RXnIF will be set.
22.9.7.2 Wake-up Interrupt
The Wake-up Interrupt sequences are described in Section 22.7.2.2.
39500 18C Reference Manual.book Page 56 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39522A-page 22-57
Section 22. CAN
CAN
22
Figure 22-17: Receive Buffer Interrupt Flag
SOF
ID10
ID9
ID8
ID7
ID6
ID5
ID4
ID3
ID2
ID1
RTR
IDE
RB0
DLC3
DLC2
STUFF
DLC1
DLC0
CRC14
CRC13
CRC12
CRC11
CRC10
CRC9
CRC8
CRC7
CRC6
CRC5
CRC4
CRC3
CRC2
CRC1
CRC0
CRCDEL
ACK SIST BIT
ACK DELIMITER
EOF
EOF
EOF
EOF
EOF
EOF
EOF
ID0
RECEIVE BUFFER
INTERRUPT FLAG
DATA
CAN BIT
TIMING
CAN BIT
NAMES
39500 18C Reference Manual.book Page 57 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39522A-page 22-58 2000 Microchip Technology Inc.
22.9.7.3 Receive Error Interrupts
A receive error interrupt will be indicated by the ERRIF bit. This bit shows that an error condition
occurred. The source of the error can be determined by checking the bits in the Communication
Status Register COMSTAT. 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.
22.9.7.3.1 Invalid Message Received Interrupt
If any type of error occurred during reception of the last message, an error will be indicated by
the IXRIF bit. 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 occur, but an indicator that an error has occurred on the CAN bus.
22.9.7.3.2 Receiver Overrun Interrupt
The RXnOVR bit indicates that an Overrun condition occurred. 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.
22.9.7.4 Receiver Warning Interrupt
The RXWARN bit indicates that the Receive Error Counter has reached the CPU Warning limit
of 96. When RXWARN 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 RXWARN 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 RXWARN bit.
22.9.7.5 Receiver Error Passive
The RXBP bit 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 RXBP bit transitions from a 0 to
a 1, it will cause the Error Interrupt Flag to become set. The RXBP bit cannot be manually
cleared, as it should remain an indicator that the Bus is in Error State Passive. The RXBP 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 RXBP bit.
22.9.8 Receive Modes
The RXM1:RXM0 bits will set special receive modes. Normally, these bits are set to 00 to enable
reception of all valid messages as accepted by the acceptance filters. In this case, the determination
of whether or not to receive standard or extended messages is determined by the EXIDEN
bit in the Acceptance Filter Registers. If the RXM1:RXM0 bits are set to 01 or 10, the receiver will
accept only messages with standard or extended identifiers respectively. If an acceptance filter
has the EXIDEN bit such that it does not correspond with the RXM1:RXM0 mode, that acceptance
filter is rendered useless. These 2 modes of RXM1:RXM0 bits can be used in systems
where it is known that only standard or extended messages will be on the bus. If the RXM1:RXM0
bits are set to 11, the buffer will receive all messages regardless of the values of the acceptance
filters. Also, if a message has an error before the End of Frame, that portion of the message
assembled in the Message Assembly Buffer (MAB) before the error frame will be loaded into the
buffer. This mode may have some value in debugging a CAN system.
39500 18C Reference Manual.book Page 58 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39522A-page 22-59
Section 22. CAN
CAN
22
22.9.8.1 Listen Only Mode
If the receive only mode is activated, the module on the CAN bus is passive. That means that no
error flags or acknowledge signals are sent. The error counters are deactivated in this state. The
receive only mode can be used for detecting the baud rate on the CAN bus. For this it is necessary
that there are at least two further nodes, which communicate with each other. The baud rate
can be detected empirically by testing different values. This mode is also useful as a bus monitor
without influencing the data traffic.
22.9.8.2 Error Recognition Mode
The module can be set to ignore all errors and receive any message. The error recognition mode
is activated by configuring the RXM1:RXM0 bits (RXBnCON registers) = ’11’. In this mode the
data which is in the message assembly buffer until the error time is copied in the receive buffer
and can be read via the CPU interface.
39500 18C Reference Manual.book Page 59 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39522A-page 22-60 2000 Microchip Technology Inc.
22.10 Transmission
This subsection describes how the CAN module is used for receiving CAN messages.
22.10.1 Real Time Communication and Transmit Message Buffering
For an application to effectively transmit messages in real time, the CAN nodes must be able to
dominate and hold the bus assuming that nodes messages are of a high enough priority to win
arbitration on the bus. If a node only has 1 transmission buffer, it must transmit a message, then
release the bus while the CPU reloads the buffer. If a node has two transmission buffers, one
buffer could be transmitting while the second buffer is being reloaded. However, the CPU would
need to maintain tight tracking of the bus activity to ensure that the second buffer is reloaded
before the first message completes.
Typical applications require three transmit message buffers. Having three buffers, one buffer can
be transmitting, the second buffer can be ready to transmit as soon as the first is complete, and
the third can be reloaded by the CPU. This eases the burden of the software to maintain synchronization
with the bus (see Figure 22-18).
Additionally, having three buffers allows some degree of prioritizing of the outgoing messages.
For example, the application software may have a message enqueued in the second buffer while
it is working on the third buffer. The application may require that the message going into the third
buffer is of higher importance than the one already enqueued. If only 2 buffers are available, the
enqueued message would have to be deleted and replaced with the third. The process of deleting
the message may mean losing control of the bus. With 3 buffers, both the second and the
third message can be enqueued, and the module can be instructed that the third message is
higher priority than the second. The third message will be the next one sent followed by the second.
22.10.2 Transmit Message Buffers
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 TXBnIF bit will be set and the TXREQ bit 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 TXBnSIDH and TXBnSIDL
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 TXBnEIDm registers are loaded and the EXIDEN
bit is set.
Prior to sending the message, the user must initialize the TXIE bit to enable or disable an interrupt
when the message is sent. The user must also initialize the transmit priority. Figure 22-18
shows a block diagram of the transmit buffers.
Figure 22-18:Transmit Buffers TXREQ
TXB0
TXABT
TXLARB
TXERR
TXBUFE
MESSAGE
Message
Queue
Control Transmit Byte Sequencer TXREQ
TXB1
TXABT
TXLARB
TXERR
TXBUFE
MESSAGE
TXREQ
TXB2
TXABT
TXLARB
TXERR
TXBUFE
MESSAGE
39500 18C Reference Manual.book Page 60 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39522A-page 22-61
Section 22. CAN
CAN
22
22.10.3 Transmit Message Priority
Transmit priority is a prioritization within each node of the pending transmittable messages. Prior
to sending the SOF (Start of Frame), the priorities of all buffers ready for transmission are compared.
The transmit buffer with the highest priority will be sent first. For example, if transmit buffer
0 has a higher priority setting than transmit buffer 1, buffer 0 will be sent first. If two buffers have
the same priority setting, the buffer with the highest address will be sent. For example, if transmit
buffer 1 has the same priority setting as transmit buffer 0, buffer 1 will be sent first. There are 4
levels of transmit priority. If TXPRI1:TXPRI0 for a particular message buffer is set to 11, that
buffer has the highest priority. If TXPRI1:TXPRI0 for a particular message buffer is set to 10 or
01, that buffer has an intermediate priority. If TXPRI1:TXPRI0 for a particular message buffer is
00, that buffer has the lowest priority.
22.10.4 Message Transmission
To initiate transmitting the message, the TXREQ bit must be set. The CAN bus module resolves
any timing conflicts between setting of the TXREQ bit and the SOF time, ensuring that if the priority
was changed, it is resolved correctly before SOF. When TXREQ is set the TXABT, TXLARB
and TXERR flag bits will be cleared.
Setting TXREQ bit does not actually start a message transmission, it flags a message buffer as
enqueued for transmission. Transmission will start when the module detects an available bus for
SOF. The module will then begin transmission on the message which has been determined to
have the highest priority.
If the transmission completes successfully on the first try, the TXREQ bit will clear and an interrupt
will be generated if TXIE was set.
If the message fails to transmit, one of the other condition flags will be set, the TXREQ bit will
remain set indicating that the message is still pending for transmission. If the message tried to
transmit but encountered an error condition, the TXERR bit will be set. In this case, the error condition
can also cause an interrupt. If the message tried to transmit but lost arbitration, the
TXLARB bit will be set. In this case, no interrupt is available to signal the loss of arbitration.
22.10.5 Transmit Message Aborting
The system can also abort a message by clearing the TXREQ bit associated with each message
buffer. Setting the ABAT bit will request an abort of all pending messages. If the message has
not yet started transmission, or if the message started but is interrupted by loss of arbitration or
an error; the abort will be processed. The abort is indicated when the module sets the TXABT bit,
and the TXnIF flag is not automatically set.
39500 18C Reference Manual.book Page 61 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39522A-page 22-62 2000 Microchip Technology Inc.
Figure 22-19:Transmit Flowchart
Start
Is
CAN bus available
to start transmission
No
Examine TXPRI <1:0> to
Are any
TXREQ
?
bits = 1
The message transmission sequence begins when
the device determines that the TXREQ for any of the
transmit registers has been set.
Clear: TXABT, TXLARB,
and TXERR
Yes
?
Does
TXREQ=0
ABAT =1
Clearing the TXREQ bit while it is set, or setting
the ABAT bit before the message has started
transmission will abort the message.
No
Begin transmission (SOF)
Abort Transmission:
Was
message transmitted
successfully?
No
Yes
Set TXREQ=0
Is
TXIE=1? Generate
Interrupt
Yes
Yes
Set TXABT=1
Set
Set
TXERR=1
Yes
No
Determine Highest Priority Message
No
?
Does
TXLARB=1?
The TXIE bit determines if an interrupt
should be generated when a
message is successfully transmitted.
END
Does
TXREQ=0
or TXABT =1
?
Yes
No
TXBUFE=1
Yes
A message can also be
aborted if a message error or
lost arbitration condition
occurred during transmission.
Arbitration lost during
transmission
39500 18C Reference Manual.book Page 62 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39522A-page 22-63
Section 22. CAN
CAN
22
22.10.6 Transmit Boundary Conditions
The module handles transmit commands which are not necessarily synchronized to the CAN bus
message framing time.
22.10.6.1 Clearing TXREQ bit as a Message Starts
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.
22.10.6.2 Setting TXABT bit as a Message Starts
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.
22.10.6.3 Clearing TXREQ bit as a Message Completes
The TXREQ bit can be cleared when a message is just about to successfully complete transmission.
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.
22.10.6.4 Setting TXABT bit as a Message Completes
The boundary conditions are the same as clearing the TXREQ bit.
22.10.6.5 Clearing TXREQ bit as a Message Loses Transmission
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.
22.10.6.6 Setting TXABT bit as a Message Loses Transmission
The boundary conditions are the same as clearing the TXREQ bit.
39500 18C Reference Manual.book Page 63 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39522A-page 22-64 2000 Microchip Technology Inc.
22.10.7 Effects of a RESET
Upon any RESET the CAN module has to be initialized. All registers are set according to the
reset values. The content of a received message is lost. The initialization is discussed in
Section 22.8.
22.10.8 Baud Rate Setting
All nodes on any particular CAN bus must have the same nominal bit rate. The baud rate is set
once during the initialization phase of the CAN module. After that, the baud rate is not changed
again. Section 22.12 explains the setting of the Baud Rate.
22.10.9 Transmit Message Aborting
The system can also abort a message by clearing the TXREQ bit associated with each message
buffer. Setting the ABAT bit will request an abort of all pending messages (see Figure 22-21). A
queued message is aborted by clearing the TXREQ bit. Aborting a queued message is illustrated
in Figure 22-20. If the message has not yet started transmission, or if the message started but is
interrupted by loss of arbitration or an error; the abort will be processed. The abort is indicated
when the module sets the TXABT bits. If the message has started to transmit, it will attempt to
transmit the current message fully (see Figure 22-22). If the current message is transmitted fully,
and is not lost to arbitration or an error, the TXABT bit will not be set, because the message was
transmitted successfully. Likewise, if a message is being transmitted during an abort request, and
the message is lost to arbitration (see Figure 22-23) or an error, the message will not be re-transmitted,
and the TXABT bit will be set, indicating that the message was successfully aborted.
Figure 22-20:Abort Queued Message
1 2
- Processor sets TXREQ while module receiving/transmitting message. Module continues with CAN message.
- Processor clears TXREQ while module looking for 11 recessive bits.
CAN BUS
3
TXREQ
- Another module takes the available transmit slot.
CANTX0
TXIF
TXABT
Module aborts pending transmission, sets TXABT bit in 2 clocks.
1
2
3
39500 18C Reference Manual.book Page 64 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39522A-page 22-65
Section 22. CAN
CAN
22
Figure 22-21:Abort All Messages
Figure 22-22:Failed Abort During Transmission
1 2
- Processor sets TXREQ while module receiving/transmitting message. Module continues with CAN message.
- Processor sets ABAT while module looking for 11 recessive bits. Module clears TXREQ bits.
CAN BUS
3
TXREQ
- Another module takes the available transmit slot.
CANTX0
TXIF
TXABT
ABAT
Module aborts pending transmission, sets TXABT bit.
1
2
3
1 2
- Processor sets TXREQ while module receiving/transmitting message. Module continues with CAN message.
- Module detects 11 recessive bits. Module begins transmission of queued message.
CAN BUS
TXREQ
- Processor clears TXREQ requesting message abort. Abort cannot be acknowledged.
CANTX0
TXIF
TXABT
3 4
- At successful completion of transmission, TXREQ bit remains clear and TXIF bit set. TXABT remains clear.
1
2
3
4
39500 18C Reference Manual.book Page 65 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39522A-page 22-66 2000 Microchip Technology Inc.
Figure 22-23:Loss of Arbitration During Transmission
22.10.10 Transmission Errors
The CAN module will detect the following transmission errors:
• Acknowledge Error
• Form Error
• Bit Error
These transmission errors will not necessarily generate an interrupt but are indicated by the
transmission error counter. However, each of these errors will cause the transmission error
counter to be incremented by one. Once the value of the error counter exceeds the value of 96,
the ERRIF and the TXWARN bit are set. Once the value of the error counter exceeds the value
of 96 an interrupt is generated and the TXWARN bit in the error flag register is set.
An example transmission error is illustrated in Figure 22-24.
Figure 22-24:Error During Transmission
1 2 4 5
- Processor sets TXREQ while module inactive. TXLARB bit cleared.
- Module in inactive state. Module begins transmission of queued message.
- Module waits for 11 recessive bits before re-trying transmission of queued message.
- At successful completion of transmission, TXREQ bit cleared and TXIF bit set.
CAN BUS
3
TXREQ
- Message loses arbitration. Module releases bus and sets TXLARB bit.
CANTX0
TXIF
TXLARB
1
2
3
4
5
1 2 4 5
- Processor sets TXREQ while module inactive. TXERR bit is cleared.
- Module in inactive state. Module begins transmission of queued message.
- Module waits for 11 recessive bits before re-trying transmission of queued message.
- At successful completion of transmission, TXREQ bit cleared and TXIF bit set.
CAN BUS
3
TXREQ
- Module detects error during transmission, releases bus and sets TXERR bit.
CANTX0
TXIF
TXERR
1
2
3
4
5
39500 18C Reference Manual.book Page 66 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39522A-page 22-67
Section 22. CAN
CAN
22
22.10.10.1 Acknowledge Error
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.
22.10.10.2 Form Error
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.
22.10.10.3 Bit Error
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.
22.10.10.4 Rules for Modifying the Transmit Error Counter
The Transmit Error Counter is modified according to the following rules:
• When the Transmitter sends an error flag the Transmit Error Counter is increased by 8 with
the following exceptions. In these two exceptions, the Transmit Error Counter is not
changed.
- If the transmitter is "error passive" and detects an acknowledgment error because of
not detecting a "dominant" ACK, and does not detect a "dominant" bit while sending a
Passive Error Flag.
- If the Transmitter sends an Error Flag because of a bit-stuffing Error occurred during
arbitration whereby the Stuffbit is located before the RTR bit, and should have been
"recessive", and has been sent as "recessive" but monitored as "dominant".
• If a Transmitter detects a Bit Error while sending an Active Error Flag or an Overload Flag
the Transmit Error Counter is increased by 8.
• Any Node tolerates up to 7 consecutive "dominant" bits after sending an Active Error Flag,
Passive Error Flag or an Overload Flag. After detecting the 14th consecutive "dominant" bit
(in case of an Active Error Flag or an Overload flag) or after detecting the 8th consecutive
"dominant" following a passive error flag, and after each sequence of eight additional consecutive
"dominant" bits, every Transmitter increases its Transmission Error Counter and
every Receiver increases its Receive Error Counter by 8.
• After the successful transmission of a message (getting an acknowledge and no error until
End of Frame is finished) the Transmit Error Counter is decreased by one unless it was
already 0.
39500 18C Reference Manual.book Page 67 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39522A-page 22-68 2000 Microchip Technology Inc.
22.10.11 Transmission Interrupts
There are several interrupts linked to the message transmission. The transmission interrupts can
be broken up into two groups:
• Transmission interrupts
• Transmission error interrupts
22.10.11.1 Transmit Interrupt
At least one of the three transmit buffers is empty (not scheduled) and can be loaded to schedule
a message for transmission. Reading the TXIF flags will indicate which transmit buffer is available
and caused the interrupt.
22.10.11.2 Transmission Error Interrupts
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
Communication Status register COMSTAT. The flags in this register are related to receive and
transmit errors. The following subsequences will show which flags are linked to the transmit
errors.
22.10.11.3 Transmitter Warning Interrupt
The TXWARN bit 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 TXWARN 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 TXWARN 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 TXWARN bit.
22.10.11.4 Transmitter Error Passive
The TXEP bit 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 from a 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 State Passive. 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.
22.10.11.5 Bus Off Interrupt
The TXBO bit 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.
39500 18C Reference Manual.book Page 68 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39522A-page 22-69
Section 22. CAN
CAN
22
22.11 Error Detection
The CAN protocol provides sophisticated error detection mechanisms. The following errors can
be detected. These errors are either receive or transmit errors.
Receive errors are:
• Cyclic Redundancy Check (CRC) Error (see Section 22.9.6.1)
• Bit Stuffing Bit Error (see Section 22.9.6.2)
• lnvalid Message Received Error (see Section 22.9.6.2)
The transmit errors are
• Acknowledge Error (see Section 22.10.10.1)
• Form Error (see Section 22.10.10.2)
• Bit Error (see Section 22.10.10.3)
22.11.1 Error States
Detected errors are made public to all other nodes via Error Frames. The transmission of the
erroneous message is aborted and the frame is repeated as soon as possible. Furthermore, each
CAN node is in one of the three error states "error active", "error passive" or "bus off" according
to the value of the internal error counters. The error-active state is the usual state where the bus
node can transmit messages and active Error Frames (made of dominant bits) without any
restrictions. In the error-passive state, messages and passive Error Frames (made of recessive
bits) may be transmitted. The bus-off state makes it temporarily impossible for the station to participate
in the bus communication. During this state, messages can neither be received nor transmitted.
22.11.2 Error Modes and Error Counters
The CAN controller contains the two error counters Receive Error Counter (RXERRCNT) and
Transmit Error Counter (TXERRCNT). The values of both counters can be read by the CPU.
These counters are incremented or decremented according to the CAN bus specification.
The CAN controller is error active if both error counters are below the error passive limit of 128.
It is error passive if at least one of the error counters equals or exceeds 128. It goes bus off if the
Transmit Error Counter equals or exceeds the bus off limit of 256. The device remains in this
state, until the bus off recovery sequence is finished, which is 128 consecutive 11 recessive bit
times. Additionally, there is a error state warning flag bit, EWARN, which is set if at least one of
the error counters equals or exceeds the error warning limit of 96. EWARN is reset if both error
counters are less than the error warning limit.
39500 18C Reference Manual.book Page 69 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39522A-page 22-70 2000 Microchip Technology Inc.
Figure 22-25:Error Modes
22.11.3 Error Flag Register
The values in the error flag register indicate which error(s) caused the Error Interrupt Flag. The
RXXOVR Error Flags have a different function than the other Error Flag bits in this register. The
RXXOVR bits must be cleared in order to clear the ERRIF interrupt flag. The other Error Flag bits
in this register will cause the ERRIF interrupt flag to become set as the value of the Transmit and
Receive Error Counters crosses a specific threshold. Clearing the ERRIF interrupt flag in these
cases will allow the interrupt service routine to be exited without recursive interrupt occurring. It
may be desirable to disable specific interrupts after they have occurred once to stop the device
from interrupting repeatedly as the Error Counter moves up and down in the vicinity of a threshold
value.
Bus
Off
Error
Active
Error
Passive
RXERRCNT > 127 or
TXERRCNT > 127
RXERRCNT < 127 or
TXERRCNT < 127
TXERRCNT > 255
128 occurrences of
11 consecutive
"recessive" bits
Reset
39500 18C Reference Manual.book Page 70 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39522A-page 22-71
Section 22. CAN
CAN
22
22.12 Baud Rate Setting
All nodes on any particular CAN bus must have the same nominal bit rate. The CAN bus uses
NRZ coding which does not encode a clock. Therefore the receivers independent clock must be
recovered by the receiving nodes and synchronized to the transmitters clock.
In order to set the baud rate the following bits have to be initialized:
• Synchronization Jump Width (see Section 22.12.6.2)
• Baud rate prescaler (see Section 22.12.2)
• Phase segments (see Section 22.12.4)
• Length determination of Phase segment 2 (see Section 22.12.4)
• Sample Point (see Section 22.12.5)
• Propagation segment bits (see Section 22.12.3)
22.12.1 Bit Timing
As oscillators and transmission time may vary from node to node, the receiver must have some
type of PLL synchronized to data transmission edges to synchronize and maintain the receiver
clock. Since the data is NRZ coded, it is necessary to include bit-stuffing to ensure that an edge
occurs at least every 6 bit times, to maintain the Digital Phase Lock Loop (DPLL) synchronization.
Bus timing functions executed within the bit time frame, such as synchronization to the local oscillator,
network transmission delay compensation, and sample point positioning, are defined by the
programmable bit timing logic of the DPLL.
All controllers on the CAN bus must have the same baud rate and bit length. However, different
controllers are not required to have the same master oscillator clock. At different clock frequencies
of the individual controllers, the baud rate has to be adjusted by adjusting the number of time
quanta in each segment.
The Nominal Bit Time can be thought of as being divided into separate non-overlapping time segments.
These segments are shown in Figure 22-26.
• Synchronization segment (Sync Seg)
• Propagation time segment (Prop Seg)
• Phase buffer segment 1 (Phase1 Seg)
• Phase buffer segment 2 (Phase2 Seg)
The time segments and also the nominal bit time are made up of integer units of time called time
quanta or TQ. By definition, the Nominal Bit Time has a minimum of 8 TQ and a maximum of
25 TQ. Also, by definition the minimum nominal bit time is 1 usec, corresponding to a maximum
1 MHz bit rate.
Figure 22-26:CAN Bit Timing
Input Signal
Sync Prop
Segment
Phase
Segment 1
Phase
Segment 2 Sync
Sample Point
TQ
39500 18C Reference Manual.book Page 71 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39522A-page 22-72 2000 Microchip Technology Inc.
22.12.2 Prescaler Setting
There is a programmable prescaler, with integral values ranging at least from 1 to 64, in addition
to a fixed divide by 2 for clock generation. The Time Quanta (TQ) is a fixed unit of time derived
from the oscillator period. Time quanta is defined as:
Equation 22-1:Time Quanta for Clock Generation
Example 22-1:Calculation for Fosc = 16 MHz
Example 22-2:Calculation for Fosc = 32 MHz
Example 22-3:Calculation for Fosc = 32 MHz and 25 TQ
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.
22.12.3 Propagation Segment
This part of the bit time is used to compensate physical delay times within the network. These
delay times consist of the signal propagation time on the bus line and the internal delay time of
the nodes. The delay is calculated as the round trip from transmitter to receiver as twice the signal's
propagation time on the bus line, the input comparator delay, and the output driver delay.
The Propagation Segment can be programmed from 1 TQ to 8 TQ by setting the
PRSE2:PRSEG0 bits.
22.12.4 Phase Segments
The phase segments are used to optimally locate the sampling of the received bit within the
transmitted bit time. The sampling point is between Phase1 Segment and Phase2 Segment.
These segments are lengthened or shortened by resynchronization. The end of the Phase1 Segment
determines the sampling point within a bit period. The segment is programmable from 1 TQ
to 8 TQ. Phase2 Segment provides delay to the next transmitted data transition. The segment is
programmable from 1 TQ to 8 TQ or it may be defined to be equal to the greater of Phase1 Segment
or the Information Processing Time. The phase segment 1 is initialized by setting bits
SEG1PH2:SEG1PH0, and phase segment 2 is initialized by setting SEG2PH2:SEG2PH0.
TQ 2 ( ) BaudRate + 1 TOSC = ⋅ ⋅
Where Baud Rate is the binary value of BRP <5:0>
If FOSC = 16 MHz, BRP5:BRP0 = 00h, and Nominal Bit Time = 8 TQ; then TQ = 125 nsec
and Nominal Bit Rate = 1 MHz
If FOSC = 32 MHz, BRP5:BRP0 = 01h, and Nominal Bit Time = 8 TQ; then TQ = 125 nsec
and Nominal Bit Rate = 1 MHz
If FOSC = 32 MHz, BRP5:BRP0 = 3Fh, and Nominal Bit Time = 25 TQ; then TQ = 4 usec
and Nominal Bit Rate = 10 kHz
39500 18C Reference Manual.book Page 72 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39522A-page 22-73
Section 22. CAN
CAN
22
22.12.5 Sample Point
The sample point is the point of time at which the bus level is read and interpreted as the Value
of that respective bit. The location is at the end of Phase Segment 1. If the bit timing is slow and
contains many TQ, it is possible to specify multiple sampling of the bus line at the sample point.
The level determined by the CAN bus then corresponds to the result from the majority decision
of three values. The majority samples are taken at the sample point and twice before with a distance
of TQ/2. The CAN module allows to chose between sampling three times at the same point
or once at the same point. This is done by setting or clearing the SAM bit (BRG2CON register).
22.12.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.
22.12.6.1 Hard Synchronization
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 resynchronization
within that bit time.
22.12.6.2 Resynchronization
As a result of resynchronization Phase Segment 1 may be lengthened or Phase Segment 2 may
be shortened. The amount of lengthening or shortening (SJW1:SJW0) of the phase buffer segment
has an upper bound given by the resynchronization jump width bits. The value of the synchronization
jump width will be added to Phase Segment 1 or subtracted from Phase Segment
2. The resynchronization jump width is programmable between 1 TQ and 4 TQ.
Clocking information will only be derived from transitions of recessive to dominant bus states.
The property that only a fixed maximum number of successive bits have the same value ensures
resynchronizing a bus unit to the bit stream during a frame (e.g. bit-stuffing).
The Phase Error of an edge is given by the position of the edge relative to Synchronous Segment,
measured in Time Quanta. The Phase Error is defined in magnitude of TQ as follows:
• e = 0 if the edge lies within Synchronous Segment.
• e > 0 if the edge lies before the Sample Point.
• e < 0 if the edge lies after the Sample Point of the previous bit.
If the magnitude of the phase error is less than or equal to the programmed value of the resynchronization
jump width, the effect of a resynchronization is the same as that of a hard synchronization,
If the magnitude of the phase error is larger than the resynchronization jump width, and if the
phase error is positive, then Phase Segment 1 is lengthened by an amount equal to the
resynchronization jump width.
If the magnitude of the phase error is larger than the resynchronization jump width, and if the
phase error is negative, then Phase Segment 2 is shortened by an amount equal to the
resynchronization jump width.
39500 18C Reference Manual.book Page 73 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39522A-page 22-74 2000 Microchip Technology Inc.
Figure 22-27:Lengthening a Bit Period
Figure 22-28:Shortening a Bit Period
22.12.7 Programming Time Segments
Some requirements for programming of the time segments:
Propagation Segment + Phase1 Segment > = Phase2 Segment
Phase2 Segment > Synchronous Jump Width
Example 22-4:Segment Time
Typically, the sampling of the bit should take place at about 60 - 70% of the bit time, depending
on the system parameters.
Synchronous Segment = 1 TQ; Propagation Segment = 2 TQ; So setting Phase Segment
1=7TQ would place the sample at 10 TQ after the transition. This would leave 6 TQ for Phase
Segment 2.
Since Phase Segment 2 is 6, by the rules, the SJW1:SJW0 bits could be set to the maximum of
4 TQ. However, normally a large synchronization jump width is only necessary when the clock
generation of the different nodes is inaccurate or unstable, such as using ceramic resonators. So
a synchronization jump width of 1 is typically enough.
Input Signal
Sync Propagation
Segment
Phase
Segment 1
Phase
Segment 2 ≤ sjw
Sample Nominal Actual Bit
Point Bit Length Length
TQ
Input Signal
Sync Propagation
Segment
Phase
Segment 1
Phase
Segment 2 ≤ sjw
Sample Actual Nominal
Bit Length
TQ
Point Bit Length
CAN Baud Rate = 125 kHz
TOSC = 50 nsec
bit time = 16 TQ
FOSC = 20 MHz
Then:
BRP5:BRP0 = 04h, → TQ = 500 nsec
For:
125 kHz
39500 18C Reference Manual.book Page 74 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39522A-page 22-75
Section 22. CAN
CAN
22
22.13 Interrupts
The module has several sources of interrupts. Each of these interrupts can be individually
enabled or disabled. A PIR register contains interrupt flags. A PIE register contains the enables
for the 8 main interrupts. A special set of read-only bits in the CANSTAT register
(ICODE2:ICODE0) can be used in combination with a jump table for efficient handling of interrupts.
All interrupts have one source, with the exception of the Error Interrupt. Any of the Error Interrupt
sources can set the Error Interrupt Flag. The source of the Error Interrupt can be determined by
reading the Communication Status (COMSTAT) register.
The interrupts can be broken up into two categories: receive and transmit interrupts.
The receive related interrupts are:
• Receive Interrupt (see Section 22.9.7.1)
• Wake-up Interrupt (see Section 22.9.7.2)
• Receiver Overrun Interrupt (see Section 22.9.7.3.2)
• Receiver Warning Interrupt (see Section 22.9.7.4)
• Receiver Error Passive Interrupt (Section 22.9.7.5)
The Transmit related interrupts are
• Transmit interrupt (see Section 22.10.11.1)
• Transmitter Warning Interrupt (Section 22.10.11.3)
• Transmitter Error Passive Interrupt (see Section 22.10.11.4)
• Bus Off Interrupt (see Section 22.10.11.5)
22.13.1 Interrupt Acknowledge
Interrupts are directly associated with one or more status flags in either a PIR or COMSTAT registers.
Interrupts are pending as long as one of the corresponding flags is set. The flags in the
registers must be reset within the interrupt handler in order to handshake the interrupt. A flag can
not be cleared if the respective condition still prevails, with the exception being interrupts that are
caused by a certain value being reached in one of the Error Counter Registers.
39500 18C Reference Manual.book Page 75 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39522A-page 22-76 2000 Microchip Technology Inc.
22.13.2 The ICODE Bits
The ICODE2:ICODE0 bits are a set of read-only bits designed for efficient handling of interrupts
via a jump table. The ICODE2:ICODE0 bits can only display one interrupt at a time because the
interrupt bits are multiplexed into this register. Therefore, the pending interrupt with the highest
priority and enabled interrupt is reflected in the ICODE2:ICODE0 bits. Once the highest priority
interrupt flag has been cleared, the next highest priority interrupt code is reflected in the
ICODE2:ICODE0 bits. An interrupt code for a corresponding interrupt can only be displayed if
both its interrupt flag and interrupt enable are set. Table 22-5 describes the operation of the
ICODE2:ICODE0 bits.
Table 22-5: ICODE Bits Decode Table
ICODE2:ICODE0 Boolean Expression
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
111 ERR•TX0•TX1•TX2•RX0•RX1•WAK
Legend: ERR = ERRIF • ERRIE
TX0 = TX0IF • TX0IE
TX1 = TX1IF • TX1IE
TX2 = TX2IF • TX2IE
RX0 = RX0IF • RX0IE
RX1 = RX1IF • RX1IE
WAK = WAKIF • WAKIE
39500 18C Reference Manual.book Page 76 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39522A-page 22-77
Section 22. CAN
CAN
22
22.14 Timestamping
The CAN module will generate a signal that can be selected to a timer capture input whenever a
valid frame has been accepted. Because the CAN specification defines a frame to be valid if no
errors occurred before the EOF field has been transmitted successfully, the timer signal will be
generated right after the EOF. A pulse of one bit time is generated.
22.15 CAN Module I/O
The CAN bus module communicates on up to 3 I/O pins. There are 1 or 2 transmit pins and 1
receive pin. These pins are multiplexed with normal digital I/O functions of the device. The
CIOCON register controls the functions of the I/O pins.
When the module is in the configuration mode, module disable mode or loopback mode, the I/O
pins revert to a Port I/O function.
When the module is active, the TX0 pin is always dedicated to the CAN output function. If a single
ended driver is needed, then only the TX0 pin is required. If a differential driver is required, then
the TX1 pin must be enabled by setting the TX1EN bit. If the bus requires an active pull-up on
the line, the ENDRHI bit should be cleared.
The TRIS bits associated with the transmit pins are overridden by the CAN bus modes. If the
CAN module expects an output to be driving, it will be regardless of the state of the TRIS bit associated
with that pin.
The output buffers for the TX0 and TX1 pin are designed such that the rise and fall rate of the
output signal is approximately equal as is necessary for differential drive.
The module can receive the CAN input on one digital input line.
39500 18C Reference Manual.book Page 77 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39522A-page 22-78 2000 Microchip Technology Inc.
22.16 Design Tips
Question 1: My CAN module does not seem to work after a RESET.
Answer 1:
Ensure that you reinitialize your CAN bus module. After a RESET, the CAN bus module will automatically
go into the initialization mode.
Question 2: I constantly get a Receive error warning interrupt.
Answer 2:
Ensure that your CAN module is set up correctly. Check if the Baud rate is set correctly.
39500 18C Reference Manual.book Page 78 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39522A-page 22-79
Section 22. CAN
CAN
22
22.17 Related Application Notes
This subsection lists application notes that are related to this subsection of the manual. These
application notes may not be written for the Mid-range family (that is they may be written for the
Baseline, or the High-end), but the concepts are pertinent, and could be used (with modification
and possible limitations). The current application notes related to this section are:
Title Application Note #
An Introduction to the CAN Protocol AN713
Note: Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
http://www.microchip.com/10/faqs/codeex/
39500 18C Reference Manual.book Page 79 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39522A-page 22-80 2000 Microchip Technology Inc.
22.18 Revision History
Revision A
This is the initial released revision of this document.
39500 18C Reference Manual.book Page 80 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39523A-page 23-1
Comparator
Voltage Reference
23
Section 23. Comparator Voltage Reference
HIGHLIGHTS
This section of the manual contains the following major topics:
23.1 Introduction .................................................................................................................. 23-2
23.2 Control Register ........................................................................................................... 23-3
23.3 Configuring the Voltage Reference .............................................................................. 23-4
23.4 Voltage Reference Accuracy/Error............................................................................... 23-5
23.5 Operation During SLEEP ............................................................................................. 23-5
23.6 Effects of a RESET ...................................................................................................... 23-5
23.7 Connection Considerations.......................................................................................... 23-6
23.8 Initialization .................................................................................................................. 23-7
23.9 Design Tips .................................................................................................................. 23-8
23.10 Related Application Notes............................................................................................ 23-9
23.11 Revision History ......................................................................................................... 23-10
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39523A-page 23-2 2000 Microchip Technology Inc.
23.1 Introduction
This Voltage Reference module is typically used in conjunction with the Comparator module. The
Comparator module’s inputs do not require very large drive, and therefore the drive capability of
this Voltage Reference is limited.
The Voltage Reference is a 16-tap resistor ladder network that provides a selectable Voltage Reference.
The resistor ladder is segmented to provide two ranges of VREF values and has a
power-down function to conserve power when the reference is not being used. The VRCON register
controls the operation of the reference (shown in Register 23-1). The block diagram is given
in Figure 23-1. Within each range, the 16 steps are monotonic (i.e., each increasing code will
result in an increasing output).
Figure 23-1: Voltage Reference Block Diagram
Table 23-1: Typical Voltage Reference with VDD = 5.0V
VR3:VR0
VREF
VRR = 1 VRR = 0
0000 0.00 V 1.25 V
0001 0.21 V 1.41 V
0010 0.42 V 1.56 V
0011 0.63 V 1.72 V
0100 0.83 V 1.88 V
0101 1.04 V 2.03 V
0110 1.25 V 2.19 V
0111 1.46 V 2.34 V
1000 1.67 V 2.50 V
1001 1.88 V 2.66 V
1010 2.08 V 2.81 V
1011 2.29 V 2.97 V
1100 2.50 V 3.13 V
1101 2.71 V 3.28 V
1110 2.92 V 3.44 V
1111 3.13 V 3.59 V
Note 1: See parameter D312 in the "Electrical Specifications" section of the device data sheet.
8R VRR (1)
VR3
VR0
16-1 Analog MUX (From VRCON<3:0>)
8R (1) R (1) R (1) R (1) R
VREN (1)
VREF
16 Stages
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39523A-page 23-3
Section 23. Comparator Voltage Reference
Comparator
Voltage Reference
23
23.2 Control Register
The Voltage Reference Control register (VRCON) is shown in Register 23-1.
Register 23-1: VRCON Register
R/W-0 R/W-0 R/W-0 U-0 R/W-0 R/W-0 R/W-0 R/W-0
VREN VROEN VRR — VR3 VR2 VR1 VR0
bit 7 bit 0
bit 7 VREN: VREF Enable
1=VREF circuit powered on
0=VREF circuit powered down
bit 6 VROEN: VREF Output Enable
1=VREF is internally connected to Comparator module’s VREF. This voltage level is also
output on the VREF pin
0=VREF is not connected to the Comparator module. This voltage is disconnected from the
VREF pin
bit 5 VRR: VREF Range Selection
1 = 0V to 0.75 VDD, with VDD/24 step size
0 = 0.25 VDD to 0.75 VDD, with VDD/32 step size
bit 4 Unimplemented: Read as '0'
bit 3:0 VR3:VR0: VREF Value Selection 0 ≤ VR3:VR0 ≤ 15
When VRR = 1:
VREF = (VR<3:0> / 24) • VDD
When VRR = 0:
VREF = 1/4 * VDD + (VR3:VR0 / 32) • VDD
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39523A-page 23-4 2000 Microchip Technology Inc.
23.3 Configuring the Voltage Reference
The Voltage Reference can output 16 distinct voltage levels for each range.
The equations used to calculate the output of the Voltage Reference are as follows:
if VRR = 1: VREF = (VR3:VR0 / 24) x VDD
if VRR = 0: VREF = (VDD x 1/4) + (VR3:VR0 / 32) x VDD
The settling time of the Voltage Reference must be considered when changing the VREF output.
Example 23-1 shows an example of how to configure the Voltage Reference for an output voltage
of 1.25V with VDD = 5.0V.
Generally the VREF and VDD of the system will be known and you need to determine the value to
load into VR3:VR0. Equation 23-1 shows how to calculate the VR3:VR0 value. There will be
some error since VR3:VR0 can only be an integer, and the VREF and VDD levels must be chosen
so that the result is not greater then 15.
Equation 23-1: Calculating VR3:VR0
VREF
VDD VR3:VR0 = X 24
When VRR = 1
VREF - VDD/4
VDD VR3:VR0 = X 32
When VRR = 0
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39523A-page 23-5
Section 23. Comparator Voltage Reference
Comparator
Voltage Reference
23
23.4 Voltage Reference Accuracy/Error
The full range of VSS to VDD cannot be realized due to the construction of the module. The transistors
on the top and bottom of the resistor ladder network (Figure 23-1) keep VREF from
approaching VSS or VDD. The Voltage Reference is VDD derived and therefore, the VREF output
changes with fluctuations in VDD. The absolute accuracy of the Voltage Reference can be found
in the Electrical Specifications parameter D311.
23.5 Operation During SLEEP
When the device wakes up from SLEEP through an interrupt or a Watchdog Timer time-out, the
contents of the VRCON register are not affected. To minimize current consumption in SLEEP
mode, the Voltage Reference should be disabled.
23.6 Effects of a RESET
A device RESET disables the Voltage Reference by clearing the VREN bit (VRCON<7>). This
RESET also disconnects the reference from the VREF pin by clearing the VROEN bit
(VRCON<6>) and selects the high voltage range by clearing the VRR bit (VRCON<5>). The
VREF value select bits, VRCON<3:0>, are also cleared.
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39523A-page 23-6 2000 Microchip Technology Inc.
23.7 Connection Considerations
The Voltage Reference Module operates independently of the Comparator module. The output
of the reference generator may be connected to the VREF pin if the corresponding TRIS bit is set
and the VROEN bit (VRCON<6>) is set. Enabling the Voltage Reference output onto the VREF
pin with an input signal present will increase current consumption. Configuring the VREF as a digital
output with VREF enabled will also increase current consumption.
The VREF pin can be used as a simple D/A output with limited drive capability. Due to the limited
drive capability, a buffer must be used in conjunction with the Voltage Reference output for external
connections to VREF. Figure 23-2 shows an example buffering technique.
Figure 23-2: Voltage Reference Output Buffer Example
VREF Output +
– • •
VREF Module
R (1)
ANx
Note 1: R is the Voltage Reference Output Impedance and is dependent upon
the Voltage Reference Configuration (the VR3:VR0 bits and the VRR bit).
PIC18CXXX
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39523A-page 23-7
Section 23. Comparator Voltage Reference
Comparator
Voltage Reference
23
23.8 Initialization
Example 23-1 shows a program sequence to configure the Voltage Reference, comparator module,
and PORT pins.
Example 23-1: Voltage Reference Configuration
MOVLW 0x02 ; 4 Inputs Muxed to 2 comparators
MOVWF CMCON ;
MOVLW PORTxout ; Select PORTx pins
MOVWF TRISx ; to be output
MOVLW 0xA6 ; enable VREF
MOVWF VRCON ; low range set VR3:VR0 = 6
CALL DELAY10 ; 10 µs delay
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39523A-page 23-8 2000 Microchip Technology Inc.
23.9 Design Tips
Question 1: My VREF is not what I expect.
Answer 1:
Any variation of the device VDD will translate directly onto the VREF pin. Also ensure that you have
correctly calculated (specified) the VDD divider which generates the VREF.
Question 2: I am connecting VREF into a low impedance circuit, and the VREF is not at
the expected level.
Answer 2:
The Voltage Reference module is not intended to drive large loads. A buffer must be used
between the PICmicro’s VREF pin and the load.
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39523A-page 23-9
Section 23. Comparator Voltage Reference
Comparator
Voltage Reference
23
23.10 Related Application Notes
This section lists application notes that are related to this section of the manual. These application
notes may not be written specifically for the Enhanced MCU family (that is they may be written
for the Base-Line, Mid-Range, or High-End families), but the concepts are pertinent, and
could be used (with modification and possible limitations). The current application notes related
to Voltage Reference are:
Title Application Note #
Resistance and Capacitance Meter using a PIC16C622 AN611
Note: Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
http://www.microchip.com/10/faqs/codeex/
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39523A-page 23-10 2000 Microchip Technology Inc.
23.11 Revision History
Revision A
This is the initial released revision of the Voltage Reference description.
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39525A-page 24-1
Comparator
24
Section 24. Comparator
HIGHLIGHTS
This section of the manual contains the following major topics:
24.1 Introduction .................................................................................................................. 24-2
24.2 Control Register ........................................................................................................... 24-3
24.3 Comparator Configuration............................................................................................ 24-4
24.4 Comparator Operation ................................................................................................. 24-6
24.5 Comparator Reference................................................................................................. 24-6
24.6 Comparator Response Time........................................................................................ 24-8
24.7 Comparator Outputs .................................................................................................... 24-8
24.8 Comparator Interrupts.................................................................................................. 24-9
24.9 Comparator Operation During SLEEP ......................................................................... 24-9
24.10 Effects of a RESET ...................................................................................................... 24-9
24.11 Analog Input Connection Considerations................................................................... 24-10
24.12 Initialization ................................................................................................................ 24-11
24.13 Design Tips ................................................................................................................ 24-12
24.14 Related Application Notes.......................................................................................... 24-13
24.15 Revision History ......................................................................................................... 24-14
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39525A-page 24-2 2000 Microchip Technology Inc.
24.1 Introduction
The comparator module contains two analog comparators. The inputs to the comparators are
multiplexed with the I/O pins. The on-chip Voltage Reference (see the “Comparator Voltage
Reference” section) can also be an input to the comparators.
The CMCON register, shown in Register 24-1, controls the comparator input and output multiplexers.
A block diagram of the comparator is shown in Figure 24-1.
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39525A-page 24-3
Section 24. Comparator
Comparator
24
24.2 Control Register
The Comparator Control register (CMCON) is shown in Register 24-1.
Register 24-1: CMCON Register
R-0 R-0 R-0 R-0 R/W-0 R/W-0 R/W-0 R/W-0
C2OUT C1OUT C2INV C1INV CIS CM2 CM1 CM0
bit 7 bit 0
bit 7 C2OUT: Comparator2 Output State bit
This bit indicates the output state of comparator 2.
1 = C2 VIN+ > C2 VIN–
0 = C2 VIN+ < C2 VIN–
bit 6 C1OUT: Comparator1 Output State bit
This bit indicates the output state of comparator 1.
1 = C1 VIN+ > C1 VIN–
0 = C1 VIN+ < C1 VIN–
bit 5 C2INV: Comparator2 Inverted Output State bit
1 = Invert the state of C2 output
0 = State of C2 output is not inverted
bit 4 C1INV: Comparator1 Inverted Output State bit
1 = Invert the state of C1 output
0 = State of C1 output is not inverted
bit 3 CIS: Comparator Input Switch bit
This bit selects which analog inputs are used as the input to the comparator.
When CM2:CM0: = 001:
1 = C1 VIN– connects to ANx3
0 = C1 VIN– connects to ANx0
When CM2:CM0 = 010:
1 = C1 VIN– connects to ANx3
C2 VIN– connects to ANx2
0 = C1 VIN– connects to ANx0
C2 VIN– connects to ANx1
bit 2:0 CM2:CM0: Comparator Mode Select bits
This bit selects the configuration of the two comparators with the comparator input pins and the
“Comparator Voltage Reference”.
See Figure 24-1 to select the CM2:CM0 state for the desired mode. The use of ANx0 through
ANx3 indicates that there are four analog inputs used with the comparator module. The actual
analog inputs connected to the comparator inputs will be device dependent.
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39525A-page 24-4 2000 Microchip Technology Inc.
24.3 Comparator Configuration
There are eight modes of operation for the comparators. The CMCON register is used to select
the mode. Figure 24-1 shows the eight possible modes. The TRIS register controls the data
direction of the comparator I/O pins for each mode. If the comparator mode is changed, the comparator
output level may not be valid for the new mode for the delay specified in the electrical
specifications of the device.
Note: Comparator interrupts should be disabled during a comparator mode change,
otherwise a false interrupt may occur.
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39525A-page 24-5
Section 24. Comparator
Comparator
24
Figure 24-1: Comparator I/O Operating Modes
C1
VINVIN+
Off (Read as '0')
Comparators Reset (POR Default Value)
A
A
CM2:CM0 = 000
C2
VINVIN+
Off (Read as '0')
A
A
C1
VINVIN+
C1OUT
Two Independent Comparators
A
A
CM2:CM0 = 010
C2
VINVIN+
C2OUT
A
A
C1
VINVIN+
C1OUT
Two Common Reference Comparators
A
A
CM2:CM0 = 100
C2
VINVIN+
C2OUT
A
D
C1
VINVIN+
Off (Read as '0')
One Independent Comparator
D
D
CM2:CM0 = 001
C1
VINVIN+
C1OUT
A
A
C1
VINVIN+
Off (Read as '0')
Comparators Off
D
D
CM2:CM0 = 111
C2
VINVIN+
Off (Read as '0')
D
D
C1
VINVIN+
C1OUT
Four Inputs Multiplexed to Two Comparators
A
A
CM2:CM0 = 110
C2
VINVIN+
C2OUT
A
A
From VREF Module
CIS = 0
CIS = 1
CIS = 0
CIS = 1
C1
VINVIN+
C1OUT
Two Common Reference Comparators with Outputs
A
A
CM2:CM0 = 101
C2
VINVIN+
C2OUT
A
D
C2OUT
Three Inputs Multiplexed to Two Comparators
CM2:CM0 = 011
ANx0
ANx3
ANx1
ANx2
ANx0
ANx3
ANx1
ANx2
ANx0
ANx3
ANx1
ANx2
ANx0
ANx3
ANx1
ANx2
ANx0
ANx3
ANx1
ANx2
ANx0
ANx3
ANx1
ANx2
ANx0
ANx3
ANx1
ANx2
C1OUT
C1OUT
C1
VINVIN+
C1OUT
A
A
C2
VINVIN+
C2OUT
A
A
C2OUT
ANx0
ANx3
ANx1
ANx2
C1OUT
A = Analog Input, port reads as zeros always.
D = Digital Input.
CIS (CMCON<3>) is the Comparator Input Switch.
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39525A-page 24-6 2000 Microchip Technology Inc.
24.4 Comparator Operation
A single comparator is shown in Figure 24-2 along with the relationship between the analog input
levels and the digital output. When the analog input at VIN+ is less than the analog input VIN–,
the output of the comparator is a digital low level. When the analog input at VIN+ is greater than
the analog input VIN–, the output of the comparator is a digital high level. The shaded areas of
the output of the comparator (shown in Figure 24-2) represent the uncertainty due to input offsets
and response time.
24.5 Comparator Reference
An external or internal reference signal may be used depending on the comparator operating
mode. The analog signal that is present at VIN– is compared to the signal at VIN+, and the digital
output of the comparator is adjusted accordingly (Figure 24-2).
Figure 24-2: Single Comparator
–
VIN+ +
VIN–
Output
VIN–
VIN+
utput
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39525A-page 24-7
Section 24. Comparator
Comparator
24
24.5.1 External Reference Signal
When external voltage references are used, the comparator module can be configured to have
the comparators operate from the same or different reference sources. The reference signal
must be between VSS and VDD, and can be applied to either pin of the comparator(s).
24.5.2 Internal Reference Signal
The comparator module also allows the selection of an internally generated voltage reference for
the comparators. The “Comparator Voltage Reference” section contains a detailed description
of the Voltage Reference Module that provides this signal. The internal reference signal is used
when the comparators are in mode CM2:CM0 = 110 (Figure 24-1). In this mode, the internal voltage
reference is applied to the VIN+ input of both comparators.
The internal voltage reference may be used in any comparator mode. The voltage reference is
output to the VREF pin. Any comparator input pin may be connected externally to the VREF pin.
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39525A-page 24-8 2000 Microchip Technology Inc.
24.6 Comparator Response Time
Response time is the minimum time, after selecting a new reference voltage or input source,
before the comparator output is guaranteed to have a valid level. If the internal reference is
changed, the maximum settling time of the internal voltage reference must be considered when
using the comparator outputs. Otherwise the maximum response time of the comparators should
be used.
24.7 Comparator Outputs
The comparator outputs are read through the CMCON register. These bits are read only. The
comparator outputs may also be directly output to the I/O pins. When CM2:CM0 = 011, multiplexors
in the output path of the I/O pins will switch and the output of each pin will be the unsynchronized
output of the comparator. The uncertainty of each of the comparators is related to the
input offset voltage and the response time given in the specifications. Figure 24-3 shows the
comparator output block diagram.
The TRIS bits will still function as the output enable/disable for the I/O pins while in this mode.
Figure 24-3: Comparator Output Block Diagram
Note 1: When reading the Port register, all pins configured as analog inputs will read as a
‘0’. Pins configured as digital inputs will convert an analog input according to the
Schmitt Trigger input specification.
2: Analog levels on any pin that is defined as a digital input may cause the input buffer
to consume more current than is specified.
Q D
EN
To I/O pin
Bus
Data
RD CMCON
Set
MULTIPLEX
CMIF
bit
+ -
Q D
EN
CL
Port Pins
RD CMCON
RESET
From
Other
Comparator
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39525A-page 24-9
Section 24. Comparator
Comparator
24
24.8 Comparator Interrupts
The comparator interrupt flag is set whenever the comparators value changes relative to the last
value loaded into CMxOUT bits. Software will need to maintain information about the status of
the output bits, as read from CMCON<7:6>, to determine the actual change that has occurred.
The CMIF bit is the comparator interrupt flag. The CMIF bit must be cleared. Since it is also possible
to set this bit, a simulated interrupt may be initiated.
The CMIE bit, the PEIE/GIEL bit, and the GIE/GIEH bit must be set to enable the interrupt. If any
of these bits are clear, an interrupt from the comparator module will not occur, though the CMIF
bit will still be set if an interrupt condition occurs. Table 24-1 shows the state of the comparator
interrupt bits to enable an interrupt to vector to the interrupt vector address. If these conditions
are not met, the comparator module will set the CMIF bit, but the program execution will not go
to the interrupt vector address.
The user, in the interrupt service routine, can clear the interrupt in the following manner:
a) Any read or write of the CMCON register. This will load the CMCON register with the new
value with the CMxOUT bits.
b) Clear the CMIF flag bit.
An interrupt condition will continue to set the CMIF flag bit. Reading CMCON will end the interrupt
condition, and allow the CMIF flag bit to be cleared.
Table 24-1: How State of Interrupt Control Bits Determine Action After Comparator Trip
(CMIF is Set)
24.9 Comparator Operation During SLEEP
When a comparator is active and the device is placed in SLEEP mode, the comparator remains
active and the interrupt is functional if enabled. This interrupt will wake-up the device from SLEEP
mode when enabled. While the comparator is powered up, each comparator that is operational
will consume additional current as shown in the comparator specifications. To minimize power
consumption while in SLEEP mode, turn off the comparators (CM2:CM0 = 111), before entering
SLEEP. If the device wakes up from SLEEP, the contents of the CMCON register are not affected.
24.10 Effects of a RESET
A device RESET forces the CMCON register to its reset state. This forces the comparator module
to be in the comparator reset mode, CM2:CM0 = 000. This ensures that all potential inputs
are analog inputs. Device current is minimized when analog inputs are present at RESET time.
The comparators will be powered down disabled during the RESET interval.
GIE GIEH PEIE GIEL CMIE IPEN CMIP Comment
1 — 1 — 1 0 — CMIF set
Branch to ISR
x — x — 0 0 — CMIF set
x — 0 — x 0 — CMIF set
0 — x — x 0 — CMIF set
— x — 1 11 0 CMIF set
Branch to ISR
— 1 — x 11 1 CMIF set
Branch to ISR
— x — x 0 1 x CMIF set
— x — 0 x 1 0 CMIF set
— x 0 — x 1 1 CMIF set
— 0 x — x 1 1 CMIF set
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39525A-page 24-10 2000 Microchip Technology Inc.
24.11 Analog Input Connection Considerations
A simplified circuit for an analog input is shown in Figure 24-4. Since the analog pins are connected
to a digital output, they have reverse biased diodes to VDD and VSS. The analog input
therefore, must be between VSS and VDD. If the input voltage deviates from this range by more
than 0.6V in either direction, one of the diodes is forward biased and a latch-up may occur. A
maximum source impedance of 10 kΩ is recommended for the analog sources.
Figure 24-4: Analog Input Model
Table 24-2: Registers Associated with Comparator Module
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Value on
POR,
BOR
Value on
All Other
Resets
CMCON C2OUT C1OUT — — CIS CM2 CM1 CM0 00-- 0000 00-- 0000
VRCON VREN VROE VRR — VR3 VR2 VR1 VR0 000- 0000 000- 0000
INTCON GIE/GIEH PEIE/GIEL TMR0IE INT0IE RBIE TMR0IF INT0IF RBIF 0000 000x 0000 000x
PIR CMIF (1) 0 0
PIE CMIE (1) 0 0
IPE CMIP (1) 0 0
Legend: x = unknown, - = unimplemented locations read as '0'.
Shaded cells are not used for Comparator Module.
Note 1: The position of this bit is device dependent.
VAIN
RS
AIN
CPIN
5 pF
VDD
VT = 0.6V
VT = 0.6V
RC < 10k
ILEAKAGE
±500 nA
VSS
Legend
CPIN = Input Capacitance
VT = Threshold Voltage
ILEAKAGE = Leakage Current at the pin due to various junctions
RIC = Interconnect Resistance
RS = Source Impedance
VA = Analog Voltage
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39525A-page 24-11
Section 24. Comparator
Comparator
24
24.12 Initialization
The code in Example 24-1 depicts example steps required to configure the comparator module.
The Port registers (PORTx, LATx, and TRISx) need to be configured appropriately depending on
the mode selected. For CM2:CM0 = 100, the I/O multiplied with ANx0, ANx1, and ANx2 needs
to be configured for analog inputs. Other I/O may be digital.
Example 24-1: Initializing Comparator Module
FLAG_REG EQU 0x020
;
CLRF FLAG_REG ; Init flag register
CLRF PORTx ; Init the desired port
MOVF CMCON, W ;
ANDLW 0xC0 ; Mask comparator bits
IORWF FLAG_REG,F ; Store bits in flag register
MOVLW 0x04 ; Init comparator mode
MOVWF CMCON ; CM<2:0> = 100
MOVLW PORTxDIR ; Initialize data direction of the ANx0, ANx1,
MOVWF TRISx ; and ANx2. Set as inputs, other I/O
; on port as desired (either inputs or outputs)
CALL DELAY10 ; 10us delay
MOVF CMCON, F ; Read CMCON to end change condition
BCF PIR1,CMIF ; Clear pending interrupts
BSF PIE1,CMIE ; Enable comparator interrupts
BSF INTCON,PEIE ; Enable peripheral interrupts
BSF INTCON,GIE ; Global interrupt enable
39500 18C Reference Manual.book Page 11 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39525A-page 24-12 2000 Microchip Technology Inc.
24.13 Design Tips
Question 1: My program appears to lock up.
Answer 1:
You may be getting stuck in an infinite loop with the comparator interrupt service routine if you
did not follow the proper sequence to clear the CMIF flag bit. First, you must read the CMCON
register and then you can clear the CMIF flag bit.
39500 18C Reference Manual.book Page 12 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39525A-page 24-13
Section 24. Comparator
Comparator
24
24.14 Related Application Notes
This section lists application notes that are related to this section of the manual. These application
notes may not be written specifically for the Enhanced MCU family (that is they may be written
for the Base-Line, Mid-Range, or High-End families), but the concepts are pertinent, and
could be used (with modification and possible limitations). The current application notes related
to the comparator module are:
Title Application Note #
Resistance and Capacitance Meter using a PIC16C622 AN611
Note: Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
http://www.microchip.com/10/faqs/codeex/
39500 18C Reference Manual.book Page 13 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39525A-page 24-14 2000 Microchip Technology Inc.
24.15 Revision History
Revision A
This is the initial released revision of the Comparator module description.
39500 18C Reference Manual.book Page 14 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39526A-page 25-1
Compatible 10-bit
A/D Converter
25
Section 25. Compatible 10-bit A/D Converter
HIGHLIGHTS
This section of the manual contains the following major topics:
25.1 Introduction .................................................................................................................. 25-2
25.2 Control Register ........................................................................................................... 25-4
25.3 Operation ..................................................................................................................... 25-7
25.4 A/D Acquisition Requirements ..................................................................................... 25-8
25.5 Selecting the A/D Conversion Clock .......................................................................... 25-10
25.6 Configuring Analog Port Pins..................................................................................... 25-11
25.7 A/D Conversions ........................................................................................................ 25-12
25.8 Operation During SLEEP ........................................................................................... 25-16
25.9 Effects of a RESET .................................................................................................... 25-16
25.10 A/D Accuracy/Error .................................................................................................... 25-17
25.11 Connection Considerations........................................................................................ 25-18
25.12 Transfer Function ....................................................................................................... 25-18
25.13 Initialization ................................................................................................................ 25-19
25.14 Design Tips ................................................................................................................ 25-20
25.15 Related Application Notes.......................................................................................... 25-21
25.16 Revision History ......................................................................................................... 25-22
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39526A-page 25-2 2000 Microchip Technology Inc.
25.1 Introduction
The compatible analog-to-digital (A/D) converter module is software compatible with the Standard
10-bit A/D converter and can have up to sixteen analog inputs.
The analog input charges a sample and hold capacitor. The output of the sample and hold capacitor
is the input into the converter. The converter then generates a digital result of this analog level
via successive approximation. This A/D conversion of the analog input signal results in a corresponding
10-bit digital number.
The analog reference voltages (positive and negative supply) are software selectable to either
the device’s supply voltages (AVDD, AVss) or the voltage level on the AN3/VREF+ and AN2/VREFpins.
The A/D converter has the unique feature of being able to convert while the device is in SLEEP
mode.
The A/D module has four registers. These registers are:
• A/D Result High Register (ADRESH)
• A/D Result Low Register (ADRESL)
• A/D Control Register0 (ADCON0)
• A/D Control Register1 (ADCON1)
The ADCON0 register, shown in Register 25-1, controls the operation of the A/D module. The
ADCON1 register, shown in Register 25-2, configures the functions of the port pins. The port pins
can be configured as analog inputs (AN3 and AN2 can also be the voltage references) or as digital
I/O.
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39526A-page 25-3
Section 25. Compatible 10-bit A/D Converter
Compatible 10-bit
A/D Converter
25
Figure 25-1: Compatible 10-bit A/D Block Diagram
(Input voltage)
VAIN
VREF-
(Reference
voltage)
AVDD
PCFG0
CHS3:CHS0
AN7
AN6
AN5
AN4
AN3
AN2
AN1
AN0
0111
0110
0101
0100
0011
0010
0001
0000
A/D
Converter
AN11
AN10
AN9
AN8
1011
1010
1001
1000
VREF+
AVSS
AN12 1100
AN13 1101
AN14 1110
AN15 1111
Note: Not all 16 input channels may be implemented on every device. Unimplemented selections
are reserved and must not be selected.
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39526A-page 25-4 2000 Microchip Technology Inc.
25.2 Control Register
ADCON0 (Register 25-1) is used to select the clock and the analog channel. ADCON1
(Register 25-2) configures the port logic to either analog or digital inputs and the format of the
result.
Register 25-1: ADCON0 Register
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
ADCS1 ADCS0 CHS2 CHS1 CHS0 GO/DONE CHS3 ADON
bit 7 bit 0
bit 7-6: ADCS1:ADCS0: A/D Conversion Clock Select bits (shown in bold)
Three bits are required to select the A/D clock source. These bits are ADCS2:ADCS0.
000 = FOSC/2
001 = FOSC/8
010 = FOSC/32
011 = FRC (clock derived from the internal A/D RC oscillator)
100 = FOSC/4
101 = FOSC/16
110 = FOSC/64
111 = FRC (clock derived from the internal A/D RC oscillator)
Note: The ADCS2 bit is located in the ADCON1 register.
bit 5-3: CHS2:CHS0: Analog Channel Select bits
There are four bits that select the A/D channel. These are CHS3:CHS0.
0000 = channel 0, (AN0)
0001 = channel 1, (AN1)
0010 = channel 2, (AN2)
0011 = channel 3, (AN3)
0100 = channel 4, (AN4)
0101 = channel 5, (AN5)
0110 = channel 6, (AN6)
0111 = channel 7, (AN7)
1000 = channel 8, (AN8)
1001 = channel 8, (AN9)
1010 = channel 10, (AN10)
1011 = channel 11, (AN11)
1100 = channel 12, (AN12)
1101 = channel 13, (AN13)
1110 = channel 14, (AN14)
1111 = channel 15, (AN15)
Note: For devices that do not implement the full 16 A/D channels, the unimplemented
selections are reserved. Do not select any unimplemented channel.
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39526A-page 25-5
Section 25. Compatible 10-bit A/D Converter
Compatible 10-bit
A/D Converter
25
bit 2: GO/DONE: A/D Conversion Status bit
When ADON = 1
1 = A/D conversion in progress. Setting this bit starts an A/D conversion cycle.
This bit is automatically cleared by hardware when the A/D conversion is completed.
0 = A/D conversion not in progress
bit 1: CHS3: Analog Channel Select bit
The CHS2:CHS0 bits are located in positions bit 5 to bit 3. See the CHS2:CHS0 description for
operational details.
bit 0: ADON: A/D On bit
1 = A/D converter module is powered up
0 = A/D converter module is shut off and consumes no operating current
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39526A-page 25-6 2000 Microchip Technology Inc.
Register 25-2: ADCON1 Register
R/W-0 R/W-0 U-0 U-0 R/W-0 R/W-0 R/W-0 R/W-0
ADFM ADCS2 — — PCFG3 PCFG2 PCFG1 PCFG0
bit 7 bit 0
bit 7: ADFM: A/D Result Format Select (also see Figure 25-6)
1 = Right justified. 6 Most Significant bits of ADRESH are read as ’0’.
0 = Left justified. 6 Least Significant bits of ADRESL are read as ’0’.
bit 6: ADCS2: A/D Conversion Clock Select bits (shown in bold)
Three bits are required to select the A/D clock source. These bits are ADCS2:ADCS0.
000 = FOSC/2
001 = FOSC/8
010 = FOSC/32
011 = FRC (clock derived from the internal A/D RC oscillator)
100 = FOSC/4
101 = FOSC/16
110 = FOSC/64
111 = FRC (clock derived from the internal A/D RC oscillator)
Note: The ADCS1:ADCS0 bits are located in the ADCON0 register.
bit 5-4: Unimplemented: Read as '0'
bit 3-0: PCFG3:PCFG0: A/D Port Configuration Control bits
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
A = Analog input D = Digital I/O
Ch/Ref = # of analog input channels / # of A/D voltage references
PCFG AN7 AN6 AN5 AN4 AN3 AN2 AN1 AN0 VREF+ VREF- CH/REF
0000 A A A A A A A A AVDD AVSS 8/0
0001 A A A AVREF+ A A A AN3 AVSS 7/1
0010 D D D A A A A A AVDD AVSS 5/0
0011 D D D AVREF+ A A A AN3 AVSS 4/1
0100 D D D D A D A A AVDD AVSS 3/0
0101 D D D DVREF+ D A A AN3 AVSS 2/1
011x DDDD D D DD — — 0/0
1000 A A A AVREF+ VREF- A A AN3 AN2 6 / 2
1001 D D A A A A A A AVDD AVSS 6/0
1010 D D A AVREF+ A A A AN3 AVSS 5/1
1011 D D A AVREF+ VREF- A A AN3 AN2 4 / 2
1100 D D D AVREF+ VREF- A A AN3 AN2 3 / 2
1101 D D D DVREF+ VREF- A A AN3 AN2 2 / 2
1110 D D D D D D D A AVDD AVSS 1/0
1111 D D D DVREF+ VREF- D A AN3 AN2 1 / 2
Note 1: On any device RESET, the port pins that are multiplexed with analog functions
(ANx) are forced to be an analog input.
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39526A-page 25-7
Section 25. Compatible 10-bit A/D Converter
Compatible 10-bit
A/D Converter
25
25.3 Operation
The ADRESH:ADRESL registers contain the 10-bit result of the A/D conversion. When the A/D
conversion is complete, the result is loaded into this A/D result register pair (ADRESH:ADRESL),
the GO/DONE bit (ADCON0) is cleared, and A/D interrupt flag bit, ADIF, is set. The block diagram
of the A/D module is shown in Figure 25-1.
After the A/D module has been configured, the signal on the selected channel must be acquired
before the conversion is started. The analog input channels must have their corresponding TRIS
bits selected as inputs. To determine acquisition time, see Subsection 25.4 “A/D Acquisition
Requirements.” After this acquisition time has elapsed, the A/D conversion can be started. The
following steps should be followed for doing an A/D conversion:
1. Configure the A/D module:
• Configure analog pins, voltage reference, and digital I/O (ADCON1)
• Select A/D input channel (ADCON0)
• Select A/D conversion clock (ADCON0)
• Turn on A/D module (ADCON0)
2. Configure A/D interrupt (if desired):
• Clear the ADIF bit
• Set the ADIE bit
• Set/Clear the ADIP bit
• Set the GIE/GIEH or PEIE/GIEL bit
3. Wait the required acquisition time.
4. Start conversion:
• Set the GO/DONE bit (ADCON0)
5. Wait for the A/D conversion to complete, by either:
• Polling for the GO/DONE bit to be cleared or the ADIF bit to be set, or
• Waiting for the A/D interrupt
6. Read A/D Result register pair (ADRESH:ADRESL): clear the ADIF bit, if required.
7. For next conversion, go to step 1 or step 2 as required.
Figure 25-2 shows the conversion sequence and the terms that are used. Acquisition time is the
time that the A/D module’s holding capacitor is connected to the external voltage level. When the
GO bit is set, the conversion time of 12 TAD is started. The sum of these two times is the sampling
time. There is a minimum acquisition time to ensure that the holding capacitor is charged to a
level that will give the desired accuracy for the A/D conversion.
Figure 25-2: A/D Conversion Sequence
Acquisition Time A/D Conversion Time
A/D Sample Time
When A/D holding capacitor starts to charge.
After A/D conversion, or when new A/D channel is selected.
When A/D conversion is started (setting the GO bit).
A/D conversion complete,
result is loaded in ADRES register.
Holding capacitor begins acquiring
voltage level on selected channel;
ADIF bit is set.
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39526A-page 25-8 2000 Microchip Technology Inc.
25.4 A/D Acquisition Requirements
For the A/D converter to meet its specified accuracy, the charge holding capacitor (CHOLD) must
be allowed to fully charge to the input channel voltage level. The analog input model is shown in
Figure 25-3. The source impedance (RS) and the internal sampling switch (RSS) impedance
directly affect the time required to charge the capacitor CHOLD. The sampling switch (RSS) impedance
varies over the device voltage (VDD), Figure 25-3. The source impedance affects the offset
voltage at the analog input (due to pin leakage current). The maximum recommended impedance
for analog sources is 2.5 kΩ. As the impedance is decreased, the acquisition time may
be decreased. After the analog input channel is selected (changed), this acquisition must pass
before the conversion can be started.
To calculate the minimum acquisition time, Equation 25-1 may be used. This equation assumes
that 1/2 LSb error is used (1024 steps for the A/D). The 1/2 LSb error is the maximum error
allowed for the A/D to meet its specified resolution.
Equation 25-1: Acquisition Time
Equation 25-2: A/D Minimum Charging Time
Example 25-1 shows the calculation of the minimum required acquisition time TACQ.
This calculation is based on the following application system assumptions.
CHOLD = 120 pF
RS = 2.5 kΩ
Conversion Error ≤ 1/2 LSb
VDD = 5V → RSS =7kΩ (see graph in Figure 25-3)
Temperature = 50°
C (system max.)
VHOLD = 0V @ time = 0
Example 25-1: Calculating the Minimum Required Acquisition Time (Case 1)
Note: When the conversion is started, the holding compacitor is disconnected from the
input pin.
TACQ equals Amplifier Settling Time (TAMP) plus
Holding Capacitor Charging Time (TC) plus
Temperature Coefficient (TCOFF)
TACQ = TAMP + TC + TCOFF
VHOLD = (VREF - (VREF/2048)) • (1 - e(-TC/CHOLD(RIC + RSS + RS)))
or
Tc = -(120 pF)(1 kΩ + RSS + RS) ln(1/2047)
TACQ = TAMP + TC + TCOFF
Temperature coefficient is only required for temperatures > 25°C.
TACQ = 2 µs + Tc + [(Temp - 25°C)(0.05 µs/°C)]
TC = -CHOLD (RIC + RSS + RS) ln(1/2047)
-120 pF (1 kΩ +7kΩ + 2.5 kΩ) ln(0.0004885)
-120 pF (10.5 kΩ) ln(0.0004885)
-1.26 µs (-7.6241)
9.61 µs
TACQ = 2 µs + 9.61µs + [(50°C - 25°C)(0.05 µs/°C)]
11.61 µs + 1.25 µs
12.86 µs
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39526A-page 25-9
Section 25. Compatible 10-bit A/D Converter
Compatible 10-bit
A/D Converter
25
Now to get an idea what happens to the acquisition time when the source impedance is a minimal
value (RS = 50 Ω). Example 25-2 shows the same conditions as in Example 25-1 with only the
source impedance changed to the minimal value.
Example 25-2: Calculating the Minimum Required Acquisition Time (Case 2)
Figure 25-3: Analog Input Model
TACQ = TAMP + TC + TCOFF
Temperature coefficient is only required for temperatures > 25°C.
TACQ = 2 µs + Tc + [(Temp - 25°C)(0.05 µs/°C)]
TC = -Chold (Ric + Rss + Rs) ln(1/2047)
-120 pF (1 kΩ +7kΩ + 50 Ω) ln(0.0004885)
-120 pF (8050 Ω) ln(0.0004885)
-0.966 µs (-7.6241)
7.36 µs
TACQ = 2 µs + 16.47 µs + [(50°C - 25°C)(0.05 µs/°C)]
9.36 µs + 1.25 µs
10.61 µs
Note 1: The reference voltage (VREF) has no effect on the equation, since it cancels itself
out.
2: The charge holding capacitor (Chold) is not discharged after each conversion.
3: The maximum recommended impedance for analog sources is 2.5 kΩ. This is
required to meet the pin leakage specification.
4: After a conversion has completed, a 2 TAD delay must complete before acquisition
can begin again. During this time the holding capacitor is not connected to the
selected A/D input channel.
VAIN Cpin
Rs ANx
5 pF
VDD
VT = 0.6V
VT = 0.6V I leakage
RIC ≤ 1k
Sampling
Switch
SS RSS
CHOLD = 120 pF
Vss
6V
Sampling Switch
5V
4V
3V
2V
5 6 7 8 9 10 11
( kΩ )
VDD
± 500 nA
Legend
CPIN
VT
ILEAKAGE
RIC
SS
CHOLD
= Input Capacitance
= Threshold Voltage
= Leakage Current at the pin due to
= Interconnect Resistance
= Sampling Switch
= Sample/Hold Capacitance (from DAC)
various junctions
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39526A-page 25-10 2000 Microchip Technology Inc.
25.5 Selecting the A/D Conversion Clock
The A/D conversion time per bit is defined as TAD. The A/D conversion requires 11.5TAD per
10-bit conversion. The source of the A/D conversion clock is software selectable. The seven possible
options for TAD are:
• 2TOSC
• 4TOSC
• 8TOSC
• 16TOSC
• 32TOSC
• 64TOSC
• Internal A/D RC oscillator
For correct A/D conversions, the A/D conversion clock (TAD) must be selected to ensure a minimum
TAD time of 1.6 µs as shown in Electrical Specifications parameter 130.
Table 25-1 and Table 25-2 show the resultant TAD times derived from the device operating frequencies
and the selected A/D clock source.
Table 25-1: TAD vs. Device Operating Frequencies (for Standard, C, Devices)
Table 25-2: TAD vs. Device Operating Frequencies (for Extended, LC, Devices)
AD Clock Source (TAD) Device Frequency
Operation ADCS2:ADCS0 20 MHz 5 MHz 1.25 MHz 333.33 kHz
2TOSC 000 100 ns (2) 400 ns (2) 1.6 µs 6 µs
4TOSC 100 200 ns (2) 800 ns (2) 3.2 µs 12 µs
8TOSC 001 400 ns (2) 1.6 µs 6.4 µs 24 µs (3)
16TOSC 101 800 ns (2) 3.2 µs 12.8 µs 48 µs (3)
32TOSC 010 1.6 µs 6.4 µs 25.6 µs (3) 96 µs (3)
64TOSC 110 3.2 µs 12.8 µs 51.2 µs (3) 192 µs (3)
RC 011 2-6 µs (1,4) 2-6 µs (1,4) 2-6 µs (1,4) 2-6 µs (1)
Legend: Shaded cells are outside of recommended range.
Note 1: The RC source has a typical TAD of 4 µs.
2: These values violate the minimum required TAD.
3: For faster conversion times, the selection of another clock source is recommended.
4: For device frequencies above 1 MHz, the device must be in SLEEP for the entire
conversion, or the A/D accuracy may be out of specification.
AD Clock Source (TAD) Device Frequency
Operation ADCS2:ADCS0 4 MHz 2 MHz 1.25 MHz 333.33 kHz
2TOSC 000 500 ns (2) 1.0 µs (2) 1.6 µs (2) 6 µs
4TOSC 100 1.0 µs (2) 2.0 µs (2) 3.2 µs (2) 12 µs
8TOSC 001 2.0 µs (2) 4.0 µs 6.4 µs 24 µs (3)
16TOSC 101 4.0 µs (2) 8.0 µs 12.8 µs 48 µs (3)
32TOSC 010 8.0 µs 16.0 µs 25.6 µs (3) 96 µs (3)
64TOSC 110 16.0 µs 32.0 µs 51.2 µs (3) 192 µs (3)
RC 011 3-9 µs (1,4) 3-9 µs (1,4) 3-9 µs (1,4) 3-9 µs (1)
Legend: Shaded cells are outside of recommended range.
Note 1: The RC source has a typical TAD of 6 µs.
2: These values violate the minimum required TAD.
3: For faster conversion times, the selection of another clock source is recommended.
4: For device frequencies above 1 MHz, the device must be in SLEEP for the entire
conversion, or the A/D accuracy may be out of specification.
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39526A-page 25-11
Section 25. Compatible 10-bit A/D Converter
Compatible 10-bit
A/D Converter
25
25.6 Configuring Analog Port Pins
The ADCON1 and TRIS registers control the operation of the A/D port pins. The port pins that
are desired as analog inputs must have their corresponding TRIS bits set (input). If the TRIS bit
is cleared (output), the digital output level (VOH or VOL) will be converted. After a device RESET,
pins that are multiplexed with analog inputs will be configured as an analog input. The corresponding
TRIS bit will be set.
The A/D operation is independent of the state of the CHS2:CHS0 bits and the TRIS bits.
Note 1: When reading the port register, any pin configured as an analog input channel will
read as cleared (a low level). Pins configured as digital inputs, will convert an analog
input. Analog levels on a digitally configured input will not affect the conversion
accuracy.
2: Analog levels on any pin that is defined as a digital input (including the AN7:AN0
pins), may cause the input buffer to consume current that is out of the devices specification.
39500 18C Reference Manual.book Page 11 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39526A-page 25-12 2000 Microchip Technology Inc.
25.7 A/D Conversions
Example 25-3 shows how to perform an A/D conversion. The port pins are configured as analog
inputs. The analog references (VREF+ and VREF-) are the device AVDD and AVSS. The A/D interrupt
is enabled, and the A/D conversion clock is FRC. The conversion is performed on the AN0
pin (channel 0). The result of the conversion is left justified.
Clearing the GO/DONE bit during a conversion will abort the current conversion. The A/D result
register pair will NOT be updated with the partially completed A/D conversion sample. That is,
the ADRESH:ADRESL registers will continue to contain the value of the last completed conversion
(or the last value written to the ADRESH:ADRESL registers). After the A/D conversion is
aborted, a 2TAD wait is required before the next acquisition is started. After this 2TAD wait, acquisition
on the selected channel is automatically started.
Example 25-3: A/D Conversion
Figure 25-4: A/D Conversion TAD Cycles
Note: The GO/DONE bit should NOT be set in the same instruction that turns on the A/D,
due to the required acquisition time.
CLRF ADCON1 ; Configure A/D inputs,
; result is left justified
BSF IPR1, ADIP ; High priority
BSF PIE1, ADIE ; Enable A/D interrupts
MOVLW 0xC1 ; RC Clock, A/D is on,
MOVWF ADCON0 ; Channel 0 is selected
BCF PIR1, ADIF ; Clear A/D interrupt flag bit
BSF INTCON, PEIE ; Enable peripheral interrupts
BSF INTCON, GIE ; Enable all interrupts
;
; Ensure that the required sampling time for the selected input
; channel has elapsed. Then the conversion may be started.
;
BSF ADCON0, GO ; Start A/D Conversion
: ; The ADIF bit will be set and the
: ; GO/DONE bit is cleared upon
: ; completion of the A/D Conversion.
TAD1 TAD2 TAD3 TAD4 TAD5 TAD6 TAD7 TAD8 TAD11
Set GO bit
Holding capacitor is disconnected from analog input (typically 100 ns)
holding capacitor is connected to analog input.
b9 b8 b7 b6 b5 b4 b3 b2
TAD9 TAD10
b1 b0
Tcy - TAD
GO bit is cleared,
Next Q4: ADRES is loaded,
ADIF bit is set,
Conversion Starts
b0
39500 18C Reference Manual.book Page 12 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39526A-page 25-13
Section 25. Compatible 10-bit A/D Converter
Compatible 10-bit
A/D Converter
25
Figure 25-5: Flowchart of A/D Operation
Acquire
ADON = 0
ADON = 0?
GO = 0?
A/D Clock
GO = 0,
ADIF = 0
Abort Conversion
SLEEP Power-down A/D Wait 2TAD
Wake-up
Yes
No
Yes
No
No
Yes
Finish Conversion
GO = 0,
ADIF = 1
No
Yes
Finish Conversion
GO = 0,
ADIF = 1
Wait 2TAD
Stay in SLEEP
Selected Channel
= RC?
SLEEP
No
Yes
Instruction?
Start of A/D Conversion Delayed
1 Instruction Cycle
From SLEEP?
Power-down A/D
Yes
No
Wait 2TAD
Finish Conversion
GO = 0,
ADIF = 1
SLEEP
Instruction?
39500 18C Reference Manual.book Page 13 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39526A-page 25-14 2000 Microchip Technology Inc.
25.7.1 Faster Conversion - Lower Resolution Trade-off
Not all applications require a result with 10-bits of resolution, but may instead require a faster
conversion time. The A/D module allows users to make the trade-off of conversion speed to resolution.
Regardless of the resolution required, the acquisition time is the same. To speed up the
conversion, the clock source of the A/D module may be switched so that the TAD time violates
the minimum specified time (see electrical specification parameter 130). Once the TAD time violates
the minimum specified time, all the following A/D result bits are not valid (see A/D Conversion
Timing in the Electrical Specifications section). The clock sources may only be switched
between the three oscillator versions (cannot be switched from/to RC). The equation to determine
the time before the oscillator can be switched is as follows:
Since the TAD is based from the device oscillator, the user must use some method (a timer, software
loop, etc.) to determine when the A/D oscillator may be changed. Example 25-4 shows a
comparison of time required for a conversion with 4-bits of resolution, versus the 10-bit resolution
conversion. The example is for devices operating at 20 MHz (the A/D clock is programmed for
32TOSC), and assumes that immediately after 6TAD, the A/D clock is programmed for 2TOSC.
The 2TOSC violates the minimum TAD time since the last 6 bits will not be converted to correct
values.
Example 25-4: 4-bit vs. 10-bit Conversion Times
Equation 25-3: Resolution/Speed Conversion Trade-off
Freq.
(MHz)(1)
Resolution
4-bit 10-bit
TAD 40 1.6 µs 1.6 µs
TOSC 40 25 ns 25 ns
TAD + N • TAD + (11 - N)(2TOSC) 40 8.5 µs 17.7 µs
Note 1: A minimum TAD time of 1.6 µs is required.
2: If the full 10-bit conversion is required, the A/D clock source should not be changed.
Conversion time = TAD + N • TAD + (11 - N)(2TOSC)
Where: N = number of bits of resolution required
39500 18C Reference Manual.book Page 14 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39526A-page 25-15
Section 25. Compatible 10-bit A/D Converter
Compatible 10-bit
A/D Converter
25
25.7.2 A/D Result Registers
The ADRESH:ADRESL register pair is the location where the 10-bit A/D result is loaded at the
completion of the A/D conversion. This register pair is 16-bits wide. The A/D module gives the
flexibility to left or right justify the 10-bit result in the 16-bit result register. The A/D Format Select
bit (ADFM) controls this justification. Figure 25-6 shows the operation of the A/D result justification.
The extra bits are loaded with ‘0’s’. When the A/D module is disabled these registers may
be used as two general purpose 8-bit registers.
Figure 25-6: A/D Result Justification
10-bit Result
ADRESH ADRESL
ADFM = 0
7 2107 0
10-bits
RESULT
ADRESH ADRESL
10-bits
7 0765 0
RESULT
ADFM = 1
Right Justified Left Justified
0000 00 0000 00
39500 18C Reference Manual.book Page 15 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39526A-page 25-16 2000 Microchip Technology Inc.
25.8 Operation During SLEEP
The A/D module can operate during SLEEP mode. This requires that the A/D clock source be set
to RC (ADCS2:ADCS0 = x11). When the RC clock source is selected, the A/D module waits one
instruction cycle before starting the conversion. This allows the SLEEP instruction to be executed,
which eliminates all internal digital switching noise from the conversion. When the conversion is
completed, the GO/DONE bit will be cleared and the result is loaded into the ADRESH:ADRESL
registers. If the A/D interrupt is enabled, the device will wake-up from SLEEP. If the A/D interrupt
is not enabled, the A/D module will be turned off, although the ADON bit will remain set.
When the A/D clock source is another clock option (not RC), a SLEEP instruction will cause the
present conversion to be aborted and the A/D module to be turned off (to conserve power),
though the ADON bit will remain set.
Turning off the A/D places the A/D module in its lowest current consumption state.
25.9 Effects of a RESET
A device RESET forces all registers to their RESET state. This forces the A/D module to be
turned off, and any conversion is aborted. All pins that are multiplexed with analog inputs will be
configured as an analog input. The corresponding TRIS bits will be set.
The value that is in the ADRESH:ADRESL registers is not initialized from a Power-on Reset. The
ADRESH:ADRESL registers will contain unknown data after a Power-on Reset.
Note: For the A/D module to operate in SLEEP, the A/D clock source must be set to RC
(ADCS2:ADCS0 = x11). To allow the conversion to occur during SLEEP, ensure the
SLEEP instruction immediately follows the instruction that sets the GO/DONE bit.
39500 18C Reference Manual.book Page 16 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39526A-page 25-17
Section 25. Compatible 10-bit A/D Converter
Compatible 10-bit
A/D Converter
25
25.10 A/D Accuracy/Error
In systems where the device frequency is low, use of the A/D RC clock is preferred. At moderate
to high frequencies, TAD should be derived from the device oscillator.
For a given range of analog inputs, the output digital code will be the same. This is due to the
quantization of the analog input to a digital code. Quantization error is typically ± 1/2 LSb and is
inherent in the analog to digital conversion process. The only way to reduce quantization error is
to increase the resolution of the A/D converter.
Offset error measures the first actual transition of a code versus the first ideal transition of a code.
Offset error shifts the entire transfer function. Offset error can be calibrated out of a system or
introduced into a system, through the interaction of the total leakage current and source impedance
at the analog input.
Gain error measures the maximum deviation of the last actual transition and the last ideal transition,
adjusted for offset error. This error appears as a change in slope of the transfer function.
The difference in gain error to full scale error, is that full scale does not take offset error into
account. Gain error can be calibrated out in software.
Linearity error refers to the uniformity of the code changes. Linearity errors cannot be calibrated
out of the system. Integral non-linearity error measures the actual code transition versus the ideal
code transition, adjusted by the gain error for each code.
Differential non-linearity measures the maximum actual code width versus the ideal code width.
This measure is unadjusted.
The maximum pin leakage current is specified in Electrical Specifications parameter D060.
TAD must not violate the minimum and should be minimized to reduce inaccuracies due to noise
and sampling capacitor bleed off.
In systems where the device will enter SLEEP mode after the start of the A/D conversion, the RC
clock source selection is required. In this mode, the digital noise from the modules in SLEEP are
stopped. This method gives high accuracy.
39500 18C Reference Manual.book Page 17 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39526A-page 25-18 2000 Microchip Technology Inc.
25.11 Connection Considerations
If the input voltage exceeds the rail values (VSS or VDD) by greater than 0.3V, then the accuracy
of the conversion is out of specification.
An external RC filter is sometimes added for anti-aliasing of the input signal. The R component
should be selected to ensure that the total source impedance is kept under the 2.5 kΩ recommended
specification. Any external components connected (via hi-impedance) to an analog
input pin (capacitor, zener diode, etc.) should have very little leakage current at the pin.
25.12 Transfer Function
The ideal transfer function of the A/D converter is as follows: the first transition occurs when the
analog input voltage (VAIN) is 1 LSb (or Analog VREF / 1024) (Figure 25-7).
Figure 25-7: A/D Transfer Function Digital code output
3FEh
003h
002h
001h
000h
0.5 LSb
1 LSb
1.5 LSb
2 LSb
2.5 LSb
1022 LSb
1022.5 LSb
3 LSb
Analog input voltage
3FFh
1023 LSb
1023.5 LSb
39500 18C Reference Manual.book Page 18 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39526A-page 25-19
Section 25. Compatible 10-bit A/D Converter
Compatible 10-bit
A/D Converter
25
25.13 Initialization
Example 25-5 shows an initialization of the A/D module.
Example 25-5: A/D Initialization
CLRF ADCON1 ; Configure A/D inputs
BSF PIE1, ADIE ; Enable A/D interrupts
BSF IPR1, ADIP ; High Priority
MOVLW 0xC1 ; RC Clock, A/D is on,
MOVWF ADCON0 ; Channel 0 is selected
MOVLW 0x4E ; Left Justified, AN0 is analog
MOVWF ADCON1 ; Vref comes from AVDD and AVSS
BCF PIR1, ADIF ; Clear A/D interrupt flag bit
BSF INTCON, PEIE ; Enable peripheral interrupts
BSF INTCON, GIE ; Enable all interrupts
;
; Ensure that the required sampling time for the selected input
; channel has elapsed. Then the conversion may be started.
;
BSF ADCON0, GO ; Start A/D Conversion
: ; The ADIF bit will be set and the
: ; GO/DONE bit is cleared upon
: ; completion of the A/D conversion.
39500 18C Reference Manual.book Page 19 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39526A-page 25-20 2000 Microchip Technology Inc.
25.14 Design Tips
Question 1: I find that the Analog to Digital Converter result is not always accurate.
What can I do to improve accuracy?
Answer 1:
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
ADCON0 and should be between 1.6 and 6 µs. 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. See the device
data sheet for device specific information.
2. Often the source impedance of the analog signal is high (greater than 1 kOhms), so the
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 120 pF internal holding capacitor.
3. In systems where the device frequency is low, use of the A/D clock derived from the device
oscillator is preferred...this reduces, to a large extent, the effects of digital switching noise.
In systems where the device will enter SLEEP mode after start of A/D conversion, the RC
clock source selection is required.This method gives the highest accuracy.
Question 2: After starting an A/D conversion may I change the input channel (for my
next conversion)?
Answer 2:
After the holding capacitor is disconnected from the input channel, typically 100 ns after the GO
bit is set, the input channel may be changed.
Question 3: Do you know of a good reference on A/D’s?
Answer 3:
A good reference for understanding A/D conversions is the “Analog-Digital Conversion Handbook”
third edition, published by Prentice Hall (ISBN 0-13-03-2848-0).
Question 4: I migrated my code from a PIC18CXX8 device with 10-bit A/D to another
device with a 10-bit A/D (such as a PIC18CXX2) and the A/D does not seem
to operate the same. What’s going on?
Answer 4:
The 10-bit A/D on the PIC18CXX2 device is the compatible 10-bit A/D module. This module has
its ADCON bits in the same locations as the PICmicro’s Mid-Range 10-bit A/D module. The standard
PIC18CXXX 10-bit A/D module (as found on the PIC18CXX8 device) has optimized the bit
locations to ease configuration of the module.
39500 18C Reference Manual.book Page 20 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39526A-page 25-21
Section 25. Compatible 10-bit A/D Converter
Compatible 10-bit
A/D Converter
25
25.15 Related Application Notes
This section lists application notes that are related to this section of the manual. These application
notes may not be written specifically for the Enhanced family (that is they may be written for
the Base-Line, the Mid-Range, or High-End families), but the concepts are pertinent, and could
be used (with modification and possible limitations). The current application notes related to the
10-bit A/D module are:
Title Application Note #
Using the Analog to Digital Converter AN546
Four Channel Digital Voltmeter with Display and Keyboard AN557
Note: Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
http://www.microchip.com/10/faqs/codeex/
39500 18C Reference Manual.book Page 21 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39526A-page 25-22 2000 Microchip Technology Inc.
25.16 Revision History
Revision A
This is the initial released revision of the Enhanced MCU Compatible 10-bit A/D module description.
39500 18C Reference Manual.book Page 22 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39527A-page 26-1
10-bit
A/D Converter
26
Section 26. 10-bit A/D Converter
HIGHLIGHTS
This section of the manual contains the following major topics:
26.1 Introduction .................................................................................................................. 26-2
26.2 Control Register ........................................................................................................... 26-4
26.3 Operation ..................................................................................................................... 26-7
26.4 A/D Acquisition Requirements ..................................................................................... 26-8
26.5 Selecting the A/D Conversion Clock .......................................................................... 26-10
26.6 Configuring Analog Port Pins..................................................................................... 26-11
26.7 A/D Conversions ........................................................................................................ 26-12
26.8 Operation During SLEEP ........................................................................................... 26-16
26.9 Effects of a RESET .................................................................................................... 26-16
26.10 A/D Accuracy/Error .................................................................................................... 26-17
26.11 Connection Considerations........................................................................................ 26-18
26.12 Transfer Function ....................................................................................................... 26-18
26.13 Initialization ................................................................................................................ 26-19
26.14 Design Tips ................................................................................................................ 26-20
26.15 Related Application Notes.......................................................................................... 26-21
26.16 Revision History ......................................................................................................... 26-22
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39527A-page 26-2 2000 Microchip Technology Inc.
26.1 Introduction
The 10-bit Analog-to-Digital (A/D) Converter module can have up to sixteen analog inputs.
The analog input charges a sample and hold capacitor. The output of the sample and hold capacitor
is the input into the converter. The converter then generates a digital result of this analog level
via successive approximation. This A/D conversion of the analog input signal results in a corresponding
10-bit digital number.
The analog reference voltages (positive and negative supply) are software selectable to either
the device’s supply voltages (AVDD, AVss) or the voltage level on the AN3/VREF+ and AN2/VREFpins.
The A/D converter has the unique feature of being able to convert while the device is in SLEEP
mode.
The A/D module has five registers. These registers are:
• A/D Result High Register (ADRESH)
• A/D Result Low Register (ADRESL)
• A/D Control Register0 (ADCON0)
• A/D Control Register1 (ADCON1)
• A/D Control Register2 (ADCON2)
The ADCON0 register, shown in Register 26-1, selects the input channel of the A/D module. The
ADCON1 register, shown in Register 26-2, configures the functions of the port pins and the Voltage
Reference for the A/D module. The port pins can be configured as analog inputs (AN3 and
AN2 can also be the Voltage References) or as digital I/O. ADCON2 selects the A/D conversion
clock source and the format of the A/D result.
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39527A-page 26-3
Section 26. 10-bit A/D Converter
10-bit
A/D Converter
26
Figure 26-1: 10-bit A/D Block Diagram
(Input voltage)
VAIN
VREF-
(Reference
Voltage)
AVDD
PCFG0
CHS3:CHS0
AN7
AN6
AN5
AN4
AN3
AN2
AN1
AN0
0111
0110
0101
0100
0011
0010
0001
0000
A/D
Converter
AN11
AN10
AN9
AN8
1011
1010
1001
1000
VREF+
AVSS
AN12 1100
AN13 1101
AN14 1110
AN15 1111
Note: Not all 16 input channels may be implemented on every device. Unimplemented selections
are reserved and must not be selected.
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39527A-page 26-4 2000 Microchip Technology Inc.
26.2 Control Register
ADCON0 (Register 26-1) is used to select the analog channel. ADCON1 (Register 26-2) configures
the port logic to either analog or digital inputs and the voltage reference source for the A/D.
ADCON2 (Register 26-3) selects the source of the A/D clock and the justification of the result.
Register 26-1: ADCON0 Register
U-0 U-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
— — CHS3 CHS2 CHS1 CHS0 GO/DONE ADON
bit 7 bit 0
bit 7-6: Unimplemented: Read as ’0’
bit 5-2: CHS3:CHS0: Analog Channel Select bits
0000 = channel 0, (AN0)
0001 = channel 1, (AN1)
0010 = channel 2, (AN2)
0011 = channel 3, (AN3)
0100 = channel 4, (AN4)
0101 = channel 5, (AN5)
0110 = channel 6, (AN6)
0111 = channel 7, (AN7)
1000 = channel 8, (AN8)
1001 = channel 8, (AN9)
1010 = channel 10, (AN10)
1011 = channel 11, (AN11)
1100 = channel 12, (AN12)
1101 = channel 13, (AN13)
1110 = channel 14, (AN14)
1111 = channel 15, (AN15)
bit 1: GO/DONE: A/D Conversion Status bit
1 = A/D conversion in progress. Setting this bit starts an A/D conversion cycle.
This bit is automatically cleared by hardware when the A/D conversion is completed.
0 = A/D conversion not in progress
bit 0: ADON: A/D On bit
1 = A/D converter module is operating
0 = A/D converter module is shut off and consumes no operating current
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39527A-page 26-5
Section 26. 10-bit A/D Converter
10-bit
A/D Converter
26
Register 26-2: ADCON1 Register
U-0 U-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
— — VCFG1 VCFG0 PCFG3 PCFG2 PCFG1 PCFG0
bit 7 bit 0
bit 7-6: Unimplemented: Read as ’0’
bit 5-4: VCFG1:VCFG0: Voltage Reference Configuration bits
bit 3-0: PCFG3:PCFG0: A/D Port Configuration Control bits (1)
A = Analog input D = Digital I/O
Note 1: Selection of an unimplemented channel produces a result of 0xFFF.
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
A/D VREFH A/D VREFL
00 AVDD AVSS
01 External VREF+ AVSS
10 AVDD External VREF11
External VREF+ External VREFAN15
AN14 AN13 AN12 AN11 AN10 AN9 AN8 AN7 AN6 AN5 AN4 AN3 AN2 AN1 AN0
0000 AAAAAAAAAAAAAAAA
0001 DDAAAAAAAAAAAAAA
0010 DDDAAAAAAAAAAAAA
0011 DDDDAAAAAAAAAAAA
0100 DDDDDAAAAAAAAAAA
0101 DDDDDDAAAAAAAAAA
0110 DDDDDDDAAAAAAAAA
0111 DDDDDDDDAAAAAAAA
1000 DDDDDDDDDAAAAAAA
1001 DDDDDDDDDDAAAAAA
1010 DDDDDDDDDDDAAAAA
1011 DDDDDDDDDDDDAAAA
1100 DDDDDDDDDDDDDAAA
1101 DDDDDDDDDDDDDDAA
1110 DDDDDDDDDDDDDDDA
1111 DDDDDDDDDDDDDDDD
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39527A-page 26-6 2000 Microchip Technology Inc.
Register 26-3: ADCON2 Register
R/W-0 U-0 U-0 U-0 U-0 R/W-0 R/W-0 R/W-0
ADFM — — — — ADCS2 ADCS1 ADCS0
bit 7 bit 0
bit 7: ADFM: A/D Result Format Select bit
1 = Right justified
0 = Left justified
bit 6-3: Unimplemented: Read as ’0’
bit 2-0: ADCS2:ADCS0: A/D Conversion Clock Select bits
000 = FOSC/2
001 = FOSC/8
010 = FOSC/32
011 = FRC (clock derived from an internal RC oscillator, 1 MHz maximum frequency)
100 = FOSC/4
101 = FOSC/16
110 = FOSC/64
111 = FRC (clock derived from an RC oscillator, 1 MHz maximum frequency)
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39527A-page 26-7
Section 26. 10-bit A/D Converter
10-bit
A/D Converter
26
26.3 Operation
The ADRESH:ADRESL registers contain the 10-bit result of the A/D conversion. When the A/D
conversion is complete, the result is loaded into this A/D result register pair (ADRESH:ADRESL),
the GO/DONE bit (ADCON0 register) is cleared, and A/D interrupt flag bit, ADIF, is set. The block
diagram of the A/D module is shown in Figure 26-1.
After the A/D module has been configured, the signal on the selected channel must be acquired
before the conversion is started. The analog input channels must have their corresponding TRIS
bits selected as inputs. To determine acquisition time, see Subsection 26.4 “A/D Acquisition
Requirements.” After this acquisition time has elapsed, the A/D conversion can be started. The
following steps should be followed for doing an A/D conversion:
1. Configure the A/D module:
• Configure analog pins, Voltage Reference, and digital I/O (ADCON1)
• Select A/D input channel (ADCON0)
• Select A/D conversion clock (ADCON0)
• Turn on A/D module (ADCON0)
2. Configure A/D interrupt (if desired):
• Clear the ADIF bit
• Set the ADIE bit
• Set/Clear the ADIP bit
• Set the GIE/GIEH or PEIE/GIEL bit
3. Wait the required acquisition time.
4. Start conversion:
• Set the GO/DONE bit (ADCON0)
5. Wait for the A/D conversion to complete, by either:
• Polling for the GO/DONE bit to be cleared or the ADIF bit to be set, or
• Waiting for the A/D interrupt
6. Read A/D Result register pair (ADRESH:ADRESL): clear the ADIF bit, if required.
7. For next conversion, go to step 1 or step 2 as required.
Figure 26-2 shows the conversion sequence, and the terms that are used. Acquisition time is the
time that the A/D module’s holding capacitor is connected to the external voltage level. When the
GO bit is set, the conversion time of 12 TAD is started. The sum of these two times is the sampling
time. There is a minimum acquisition time to ensure that the holding capacitor is charged to a
level that will give the desired accuracy for the A/D conversion.
Figure 26-2: A/D Conversion Sequence
Acquisition Time A/D Conversion Time
A/D Sample Time
When A/D holding capacitor starts to charge.
After A/D conversion, or when new A/D channel is selected.
When A/D conversion is started (setting the GO bit).
A/D conversion complete,
result is loaded in ADRES register.
Holding capacitor begins acquiring
voltage level on selected channel;
ADIF bit is set.
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39527A-page 26-8 2000 Microchip Technology Inc.
26.4 A/D Acquisition Requirements
For the A/D converter to meet its specified accuracy, the charge holding capacitor (CHOLD) must
be allowed to fully charge to the input channel voltage level. The analog input model is shown in
Figure 26-3. The source impedance (RS) and the internal sampling switch (RSS) impedance
directly affect the time required to charge the capacitor CHOLD. The sampling switch (RSS) impedance
varies over the device voltage (VDD), Figure 26-3. The source impedance affects the offset
voltage at the analog input (due to pin leakage current). The maximum recommended impedance
for analog sources is 2.5 kΩ. As the impedance is decreased, the acquisition time may
be decreased. After the analog input channel is selected (changed), this acquisition must pass
before the conversion can be started.
To calculate the minimum acquisition time, Equation 26-1 may be used. This equation assumes
that 1/2 LSb error is used (1024 steps for the A/D). The 1/2 LSb error is the maximum error
allowed for the A/D to meet its specified resolution.
Equation 26-1: Acquisition Time
Equation 26-2: A/D Minimum Charging Time
Example 26-1 shows the calculation of the minimum required acquisition time TACQ.
This calculation is based on the following application system assumptions.
CHOLD = 120 pF
RS = 2.5 kΩ
Conversion Error ≤ 1/2 LSb
VDD = 5V → RSS =7kΩ (see graph in Figure 26-3)
Temperature = 50°
C (system max.)
VHOLD = 0V @ time = 0
Example 26-1: Calculating the Minimum Required Acquisition Time (Case 1)
Note: When the conversion is started, the holding capacitor is disconnected from the input
pin.
TACQ equals Amplifier Settling Time (TAMP) plus
Holding Capacitor Charging Time (TC) plus
Temperature Coefficient (TCOFF)
TACQ = TAMP + TC + TCOFF
VHOLD = (VREF - (VREF/2048)) • (1 - e(-TC/CHOLD(RIC + RSS + RS)))
or
Tc = -(120 pF)(1 kΩ + RSS + RS) ln(1/2047)
TACQ = TAMP + TC + TCOFF
Temperature coefficient is only required for temperatures > 25°C.
TACQ = 2 µs + Tc + [(Temp - 25°C)(0.05 µs/°C)]
TC = -CHOLD (RIC + RSS + RS) ln(1/2047)
-120 pF (1 kΩ +7kΩ + 2.5 kΩ) ln(0.0004885)
-120 pF (10.5 kΩ) ln(0.0004885)
-1.26 µs (-7.6241)
9.61 µs
TACQ = 2 µs + 9.61µs + [(50°C - 25°C)(0.05 µs/°C)]
11.61 µs + 1.25 µs
12.86 µs
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39527A-page 26-9
Section 26. 10-bit A/D Converter
10-bit
A/D Converter
26
Now to get an idea what happens to the acquisition time when the source impedance is a minimal
value (RS = 50 Ω). Example 26-2 shows the same conditions as in Example 26-1 with only the
source impedance changed to the minimal value.
Example 26-2: Calculating the Minimum Required Acquisition Time (Case 2)
Figure 26-3: Analog Input Model
TACQ = TAMP + TC + TCOFF
Temperature coefficient is only required for temperatures > 25°C.
TACQ = 2 µs + Tc + [(Temp - 25°C)(0.05 µs/°C)]
TC = -Chold (Ric + Rss + Rs) ln(1/2047)
-120 pF (1 kΩ +7kΩ + 50 Ω) ln(0.0004885)
-120 pF (8050 Ω) ln(0.0004885)
-0.966 µs (-7.6241)
7.36 µs
TACQ = 2 µs + 16.47 µs + [(50°C - 25°C)(0.05 µs/°C)]
9.36 µs + 1.25 µs
10.61 µs
Note 1: The reference voltage (VREF) has no effect on the equation, since it cancels itself
out.
2: The charge holding capacitor (CHOLD) is not discharged after each conversion.
3: The maximum recommended impedance for analog sources is 2.5 kΩ. This is
required to meet the pin leakage specification.
4: After a conversion has completed, a 2 TAD delay must complete before acquisition
can begin again. During this time the holding capacitor is not connected to the
selected A/D input channel.
VAIN Cpin
Rs ANx
5 pF
VDD
VT = 0.6V
VT = 0.6V I leakage
RIC ≤ 1k
Sampling
Switch
SS RSS
CHOLD = 120 pF
Vss
6V
Sampling Switch
5V
4V
3V
2V
5 6 7 8 9 10 11
( kΩ )
VDD
± 500 nA
Legend
CPIN
VT
ILEAKAGE
RIC
SS
CHOLD
= Input Capacitance
= Threshold Voltage
= Leakage Current at the pin due to
= Interconnect Resistance
= Sampling Switch
= Sample/hold capacitance (from DAC)
various junctions
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39527A-page 26-10 2000 Microchip Technology Inc.
26.5 Selecting the A/D Conversion Clock
The A/D conversion time per bit is defined as TAD. The A/D conversion requires 11.5TAD per
10-bit conversion. The source of the A/D conversion clock is software selectable. The seven possible
options for TAD are:
• 2TOSC
• 4TOSC
• 8TOSC
• 16TOSC
• 32TOSC
• 64TOSC
• Internal A/D RC oscillator
For correct A/D conversions, the A/D conversion clock (TAD) must be selected to ensure a minimum
TAD time of 1.6 µs as shown in Electrical Specifications parameter 130.
Table 26-1 and Table 26-2 show the resultant TAD times derived from the device operating frequencies
and the selected A/D clock source.
Table 26-1: TAD vs. Device Operating Frequencies (for Standard, C, Devices)
Table 26-2: TAD vs. Device Operating Frequencies (for Extended, LC, Devices)
AD Clock Source (TAD) Device Frequency
Operation ADCS2:ADCS0 20 MHz 5 MHz 1.25 MHz 333.33 kHz
2TOSC 000 100 ns (2) 400 ns (2) 1.6 µs 6 µs
4TOSC 100 200 ns (2) 800 ns (2) 3.2 µs 12 µs
8TOSC 001 400 ns (2) 1.6 µs 6.4 µs 24 µs (3)
16TOSC 101 800 ns (2) 3.2 µs 12.8 µs 48 µs (3)
32TOSC 010 1.6 µs 6.4 µs 25.6 µs (3) 96 µs (3)
64TOSC 110 3.2 µs 12.8 µs 51.2 µs (3) 192 µs (3)
RC 011 2-6 µs (1,4) 2-6 µs (1,4) 2-6 µs (1,4) 2-6 µs (1)
Legend: Shaded cells are outside of recommended range.
Note 1: The RC source has a typical TAD of 4 µs.
2: These values violate the minimum required TAD.
3: For faster conversion times, the selection of another clock source is recommended.
4: For device frequencies above 1 MHz, the device must be in SLEEP for the entire
conversion, or the A/D accuracy may be out of specification.
AD Clock Source (TAD) Device Frequency
Operation ADCS2:ADCS0 4 MHz 2 MHz 1.25 MHz 333.33 kHz
2TOSC 000 500 ns (2) 1.0 µs (2) 1.6 µs (2) 6 µs
4TOSC 100 1.0 µs (2) 2.0 µs (2) 3.2 µs (2) 12 µs
8TOSC 001 2.0 µs (2) 4.0 µs 6.4 µs 24 µs (3)
16TOSC 101 4.0 µs 8.0 µs 12.8 µs 48 µs (3)
32TOSC 010 8.0 µs 16.0 µs 25.6 µs (3) 96 µs (3)
64TOSC 110 16.0 µs 32.0 µs 51.2 µs (3) 192 µs (3)
RC 011 3-9 µs (1,4) 3-9 µs (1,4) 3-9 µs (1,4) 3-9 µs (1)
Legend: Shaded cells are outside of recommended range.
Note 1: The RC source has a typical TAD of 6 µs.
2: These values violate the minimum required TAD.
3: For faster conversion times, the selection of another clock source is recommended.
4: For device frequencies above 1 MHz, the device must be in SLEEP for the entire
conversion, or the A/D accuracy may be out of specification.
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39527A-page 26-11
Section 26. 10-bit A/D Converter
10-bit
A/D Converter
26
26.6 Configuring Analog Port Pins
The ADCON1 and TRIS registers control the operation of the A/D port pins. The port pins that
are desired as analog inputs must have their corresponding TRIS bits set (input). If the TRIS bit
is cleared (output), the digital output level (VOH or VOL) will be converted. After a device RESET,
pins that are multiplexed with analog inputs will be configured as an analog input. The corresponding
TRIS bit will be set.
The A/D operation is independent of the state of the CHS2:CHS0 bits and the TRIS bits.
Note 1: When reading the port register, any pin configured as an analog input channel will
read as cleared (a low level). Pins configured as digital inputs, will convert an analog
input. Analog levels on a digitally configured input will not affect the conversion
accuracy.
2: Analog levels on any pin that is defined as a digital input (including the AN7:AN0
pins), may cause the input buffer to consume current that is out of the devices specification.
39500 18C Reference Manual.book Page 11 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39527A-page 26-12 2000 Microchip Technology Inc.
26.7 A/D Conversions
Example 26-3 shows how to perform an A/D conversion. The port pins are configured as analog
inputs. The analog references (VREF+ and VREF-) are the device AVDD and AVSS. The A/D interrupt
is enabled, and the A/D conversion clock is FRC. The conversion is performed on the AN0
pin (channel 0). The result of the conversion is left justified.
Clearing the GO/DONE bit during a conversion will abort the current conversion. The A/D result
register pair will NOT be updated with the partially completed A/D conversion sample. That is,
the ADRESH:ADRESL registers will continue to contain the value of the last completed conversion
(or the last value written to the ADRESH:ADRESL registers). After the A/D conversion is
aborted, a 2TAD wait is required before the next acquisition is started. After this 2TAD wait, acquisition
on the selected channel is automatically started.
Example 26-3: A/D Conversion
Figure 26-4: A/D Conversion TAD Cycles
Note: The GO/DONE bit should NOT be set in the instruction that turns on the A/D, due
to the required acquisition time.
CLRF ADCON1 ; Configure A/D inputs,
; result is left justified
BSF IPR1, ADIP ; High Priority.
BSF PIE1, ADIE ; Enable A/D interrupts
MOVLW 0xC1 ; RC Clock, A/D is on,
MOVWF ADCON0 ; Channel 0 is selected
BCF PIR1, ADIF ; Clear A/D interrupt flag bit
BSF INTCON, PEIE ; Enable peripheral interrupts
BSF INTCON, GIE ; Enable all interrupts
;
; Ensure that the required sampling time for the selected input
; channel has elapsed. Then the conversion may be started.
;
BSF ADCON0, GO ; Start A/D Conversion
: ; The ADIF bit will be set and the
: ; GO/DONE bit is cleared upon
: ; completion of the A/D Conversion.
TAD1 TAD2 TAD3 TAD4 TAD5 TAD6 TAD7 TAD8 TAD11
Set GO bit
Holding capacitor is disconnected from analog input (typically 100 ns)
holding capacitor is connected to analog input.
b9 b8 b7 b6 b5 b4 b3 b2
TAD9 TAD10
b1 b0
Tcy - TAD
GO bit is cleared,
Next Q4: ADRES is loaded,
ADIF bit is set,
Conversion Starts
b0
39500 18C Reference Manual.book Page 12 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39527A-page 26-13
Section 26. 10-bit A/D Converter
10-bit
A/D Converter
26
Figure 26-5: Flowchart of A/D Operation
Acquire
ADON = 0
ADON = 0?
GO = 0?
A/D Clock
GO = 0,
ADIF = 0
Abort Conversion
SLEEP Power-down A/D Wait 2TAD
Wake-up
Yes
No
Yes
No
No
Yes
Finish Conversion
GO = 0,
ADIF = 1
No
Yes
Finish Conversion
GO = 0,
ADIF = 1
Wait 2TAD
Stay in SLEEP
Selected Channel
= RC?
SLEEP
No
Yes
Instruction?
Start of A/D Conversion Delayed
1 Instruction Cycle
From SLEEP?
Power-down A/D
Yes
No
Wait 2TAD
Finish Conversion
GO = 0,
ADIF = 1
SLEEP
Instruction?
39500 18C Reference Manual.book Page 13 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39527A-page 26-14 2000 Microchip Technology Inc.
26.7.1 Faster Conversion - Lower Resolution Trade-off
Not all applications require a result with 10-bits of resolution, but may instead require a faster
conversion time. The A/D module allows users to make the trade-off of conversion speed to resolution.
Regardless of the resolution required, the acquisition time is the same. To speed up the
conversion, the clock source of the A/D module may be switched so that the TAD time violates
the minimum specified time (Electrical Specifications parameter 130). Once the TAD time violates
the minimum specified time, all the following A/D result bits are not valid (see A/D Conversion
Timing in the Electrical Specifications section). The clock sources may only be switched between
the three oscillator versions (cannot be switched from/to RC). The equation to determine the time
before the oscillator can be switched is as follows:
Since the TAD is based from the device oscillator, the user must use some method (a timer, software
loop, etc.) to determine when the A/D oscillator may be changed. Example 26-4 shows a
comparison of time required for a conversion with 4-bits of resolution, versus the 10-bit resolution
conversion. The example is for devices operating at 20 MHz (the A/D clock is programmed for
32TOSC), and assumes that immediately after 6TAD, the A/D clock is programmed for 2TOSC.
The 2TOSC violates the minimum TAD time since the last 6 bits will not be converted to correct
values.
Example 26-4: 4-bit vs. 10-bit Conversion Times
Equation 26-3: Resolution/Speed Conversion Trade-off
Freq.
(MHz)(1)
Resolution
4-bit 10-bit
TAD 40 1.6 µs 1.6 µs
TOSC 40 25 ns 25 ns
TAD + N • TAD + (11 - N)(2TOSC) 40 8.5 µs 17.7 µs
Note 1: A minimum TAD time of 1.6 µs is required.
2: If the full 10-bit conversion is required, the A/D clock source should not be changed.
Conversion time = TAD + N • TAD + (11 - N)(2TOSC)
Where: N = number of bits of resolution required
39500 18C Reference Manual.book Page 14 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39527A-page 26-15
Section 26. 10-bit A/D Converter
10-bit
A/D Converter
26
26.7.2 A/D Result Registers
The ADRESH:ADRESL register pair is the location where the 10-bit A/D result is loaded at the
completion of the A/D conversion. This register pair is 16-bits wide. The A/D module gives the
flexibility to left or right justify the 10-bit result in the 16-bit result register. The A/D Format Select
bit (ADFM) controls this justification. Figure 26-6 shows the operation of the A/D result justification.
The extra bits are loaded with ‘0’s’. When the A/D module is disabled, these registers may
be used as two general purpose 8-bit registers.
Figure 26-6: A/D Result Justification
10-bit Result
ADRESH ADRESL
ADFM = 0
7 2107 0
10-bits
RESULT
ADRESH ADRESL
10-bits
7 0765 0
RESULT
ADFM = 1
Right Justified Left Justified
0000 00 0000 00
39500 18C Reference Manual.book Page 15 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39527A-page 26-16 2000 Microchip Technology Inc.
26.8 Operation During SLEEP
The A/D module can operate during SLEEP mode. This requires that the A/D clock source be set
to RC (ADCS2:ADCS0 = x11). When the RC clock source is selected, the A/D module waits one
instruction cycle before starting the conversion. This allows the SLEEP instruction to be executed,
which eliminates all internal digital switching noise from the conversion. When the conversion is
completed, the GO/DONE bit will be cleared and the result is loaded into the ADRESH:ADRESL
registers. If the A/D interrupt is enabled, the device will wake-up from SLEEP. If the A/D interrupt
is not enabled, the A/D module will be turned off, although the ADON bit will remain set.
When the A/D clock source is another clock option (not RC), a SLEEP instruction will cause the
present conversion to be aborted and the A/D module to be turned off (to conserve power),
though the ADON bit will remain set.
Turning off the A/D places the A/D module in its lowest current consumption state.
26.9 Effects of a RESET
A device RESET forces all registers to their RESET state. This forces the A/D module to be
turned off, and any conversion is aborted. All pins that are multiplexed with analog inputs will be
configured as an analog input. The corresponding TRIS bits will be set.
The value that is in the ADRESH:ADRESL registers is not initialized from a Power-on Reset. The
ADRESH:ADRESL registers will contain unknown data after a Power-on Reset.
Note: For the A/D module to operate in SLEEP, the A/D clock source must be set to RC
(ADCS2:ADCS0 = x11). To allow the conversion to occur during SLEEP, ensure the
SLEEP instruction immediately follows the instruction that sets the GO/DONE bit.
39500 18C Reference Manual.book Page 16 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39527A-page 26-17
Section 26. 10-bit A/D Converter
10-bit
A/D Converter
26
26.10 A/D Accuracy/Error
In systems where the device frequency is low, use of the A/D RC clock is preferred. At moderate
to high frequencies, TAD should be derived from the device oscillator.
For a given range of analog inputs, the output digital code will be the same. This is due to the
quantization of the analog input to a digital code. Quantization error is typically ± 1/2 LSb and is
inherent in the analog to digital conversion process. The only way to reduce quantization error is
to increase the resolution of the A/D converter.
Offset error measures the first actual transition of a code versus the first ideal transition of a code.
Offset error shifts the entire transfer function. Offset error can be calibrated out of a system or
introduced into a system, through the interaction of the total leakage current and source impedance
at the analog input.
Gain error measures the maximum deviation of the last actual transition and the last ideal transition,
adjusted for offset error. This error appears as a change in slope of the transfer function.
The difference in gain error to full scale error, is that full scale does not take offset error into
account. Gain error can be calibrated out in software.
Linearity error refers to the uniformity of the code changes. Linearity errors cannot be calibrated
out of the system. Integral non-linearity error measures the actual code transition versus the ideal
code transition, adjusted by the gain error for each code.
Differential non-linearity measures the maximum actual code width versus the ideal code width.
This measure is unadjusted.
The maximum pin leakage current is specified in Electrical Specifications parameter D060.
TAD must not violate the minimum and should be minimized to reduce inaccuracies due to noise
and sampling capacitor bleed off.
In systems where the device will enter SLEEP mode after the start of the A/D conversion, the RC
clock source selection is required. In this mode, the digital noise from the modules in SLEEP are
stopped. This method gives high accuracy.
39500 18C Reference Manual.book Page 17 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39527A-page 26-18 2000 Microchip Technology Inc.
26.11 Connection Considerations
If the input voltage exceeds the rail values (VSS or VDD) by greater than 0.3V, then the accuracy
of the conversion is out of specification.
An external RC filter is sometimes added for anti-aliasing of the input signal. The R component
should be selected to ensure that the total source impedance is kept under the 2.5 kΩ recommended
specification. Any external components connected (via hi-impedance) to an analog
input pin (capacitor, zener diode, etc.) should have very little leakage current at the pin.
26.12 Transfer Function
The ideal transfer function of the A/D converter is as follows: the first transition occurs when the
analog input voltage (VAIN) is 1 LSb (or Analog VREF / 1024) (Figure 26-7).
Figure 26-7: A/D Transfer Function Digital Code Output
3FEh
003h
002h
001h
000h
0.5 LSb
1 LSb
1.5 LSb
2 LSb
2.5 LSb
1022 LSb
1022.5 LSb
3 LSb
Analog Input Voltage
3FFh
1023 LSb
1023.5 LSb
39500 18C Reference Manual.book Page 18 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39527A-page 26-19
Section 26. 10-bit A/D Converter
10-bit
A/D Converter
26
26.13 Initialization
Example 26-5 shows an initialization of the A/D module.
Example 26-5: A/D Initialization
CLRF ADCON1 ; Configure A/D inputs
BSF PIE1, ADIE ; Enable A/D interrupts
BSF IPR1, ADIP ; High Priority
MOVLW 0xC1 ; RC Clock, A/D is on,
MOVWF ADCON0 ; Channel 0 is selected
MOVLW 0x4E ; Left Justified, AN0 is analog
MOVWF ADCON1 ; Vref comes from AVDD and AVSS
BCF PIR1, ADIF ; Clear A/D interrupt flag bit
BSF INTCON, PEIE ; Enable peripheral interrupts
BSF INTCON, GIE ; Enable all interrupts
;
; Ensure that the required sampling time for the selected input
; channel has elapsed. Then the conversion may be started.
;
BSF ADCON0, GO ; Start A/D Conversion
: ; The ADIF bit will be set and the
: ; GO/DONE bit is cleared upon
: ; completion of the A/D conversion.
39500 18C Reference Manual.book Page 19 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39527A-page 26-20 2000 Microchip Technology Inc.
26.14 Design Tips
Question 1: I find that the Analog to Digital Converter result is not always accurate.
What can I do to improve accuracy?
Answer 1:
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
ADCON0 and should be between 1.6 and 6 µs. 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. See the device
data sheet for device specific information.
2. Often the source impedance of the analog signal is high (greater than 1 kOhms), so the
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 120 pF internal holding capacitor.
3. In systems where the device frequency is low, use of the A/D clock derived from the device
oscillator is preferred...this reduces, to a large extent, the effects of digital switching noise.
In systems where the device will enter SLEEP mode after start of A/D conversion, the RC
clock source selection is required.This method gives the highest accuracy.
Question 2: After starting an A/D conversion may I change the input channel (for my
next conversion)?
Answer 2:
After the holding capacitor is disconnected from the input channel, typically 100 ns after the GO
bit is set, the input channel may be changed.
Question 3: Do you know of a good reference on A/D’s?
Answer 3:
A good reference for understanding A/D conversions is the “Analog-Digital Conversion Handbook”
third edition, published by Prentice Hall (ISBN 0-13-03-2848-0).
Question 4: I migrated my code from a PIC18CXX2 device with 10-bit A/D to another
device with a 10-bit A/D (such as a PIC18CXX8) and the A/D does not seem
to operate the same. What’s going on?
Answer 4:
The 10-bit A/D on the PIC18CXX2 device is the compatible 10-bit A/D module. This module has
its ADCON bits in the same locations as the PICmicros Mid-Range 10-bit A/D module. The standard
PIC18CXXX 10-bit A/D module (as found on the PIC18CXX8 device) has optimized the bit
locations to ease configuration of the module.
39500 18C Reference Manual.book Page 20 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39527A-page 26-21
Section 26. 10-bit A/D Converter
10-bit
A/D Converter
26
26.15 Related Application Notes
This section lists application notes that are related to this section of the manual. These application
notes may not be written specifically for the Enhanced family (that is they may be written for
the Base-Line, the Mid-Range, or High-End families), but the concepts are pertinent, and could
be used (with modification and possible limitations). The current application notes related to the
10-bit A/D module are:
Title Application Note #
Using the Analog to Digital Converter AN546
Four Channel Digital Voltmeter with Display and Keyboard AN557
Note: Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
http://www.microchip.com/10/faqs/codeex/
39500 18C Reference Manual.book Page 21 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39527A-page 26-22 2000 Microchip Technology Inc.
26.16 Revision History
Revision A
This is the initial released revision of the Enhanced MCU Compatible 10-bit A/D module description.
39500 18C Reference Manual.book Page 22 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39528A-page 27-1
Low
Voltage Detectr
27
Section 27. Low Voltage Detect
HIGHLIGHTS
This section of the manual contains the following major topics:
27.1 Introduction .................................................................................................................. 27-2
27.2 Control Register ........................................................................................................... 27-4
27.3 Operation ..................................................................................................................... 27-5
27.4 Operation During SLEEP ............................................................................................. 27-6
27.5 Effects of a RESET ...................................................................................................... 27-6
27.6 Initialization .................................................................................................................. 27-7
27.7 Design Tips .................................................................................................................. 27-8
27.8 Related Application Notes............................................................................................ 27-9
27.9 Revision History ......................................................................................................... 27-10
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39528A-page 27-2 2000 Microchip Technology Inc.
27.1 Introduction
In many applications, the ability to determine if the device voltage (VDD) is below a specified
voltage level is a desirable feature. A window of operation for the application can be created
where the application software can do "housekeeping tasks" before the device voltage exits the
valid operating range. This can be done using the Low Voltage Detect module.
This module is software programmable circuitry, where a device voltage trip point can be specified.
When the voltage of the device becomes lower than the specified point, an interrupt flag is
set. If the interrupt is enabled, the program execution will branch to the interrupt vector address,
and the software can then respond to that interrupt source.
The Low Voltage Detect circuitry is completely under software control. This allows the circuitry
to be "turned off" by the software, which minimizes the current consumption for the device.
Figure 27-1 shows a possible application voltage curve (typically for batteries). Over time the
device voltage decreases. When the device voltage equals voltage VA, 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 have shut down 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.
Figure 27-1: Typical Low Voltage Detect Application
Time
Voltage
VA
VB
TA
VA = LVD trip point
VB = Minimum valid device
operating voltage
Legend
TB
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39528A-page 27-3
Section 27. Low Voltage Detect
Low
Voltage Detect
27
Figure 27-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
crosses the set point (is lower then), the LVDIF bit is set.
Each node in the resister divider represents a “trip point” voltage.
The “trip point” voltage is the minimum supply voltage level at which the device can operate
before the LVD module asserts an interrupt. When the supply voltage is equal to the trip point,
the voltage tapped off of the resistor array is equal to the voltage generated by the internal voltage
reference module. The comparator then generates an interrupt signal setting the LVDIF bit.
This voltage is software programmable to any one of 16 values (see Figure 27-2). The trip point
is selected by programming the LVDL3:LVDL0 bits (LVDCON<3:0>).
Figure 27-2: Low Voltage Detect (LVD) Block Diagram
VDD
LVDIF
16 to 1 MUX
LVDEN
LVD Control
Register
Internally generated
reference voltage
LVDIN
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39528A-page 27-4 2000 Microchip Technology Inc.
27.2 Control Register
The Low Voltage Detect Control register controls the operation of the Low Voltage Detect circuitry.
Register 27-1: LVDCON Register
U-0 U-0 R-0 R/W-0 R/W-0 R/W-1 R/W-0 R/W-1
— — IRVST LVDEN LVDL3 LVDL2 LVDL1 LVDL0
bit 7 bit 0
bit 7:6 Unimplemented: Read as '0'
bit 5 IRVST: Internal Reference Voltage Stable Flag bit
1 = Indicates that the Low Voltage Detect logic will generate the interrupt flag at the specified
voltage range.
0 = Indicates that the Low Voltage Detect logic will not generate the interrupt flag at the
specified voltage range, and LVD interrupt should not be enabled
bit 4 LVDEN: Low-voltage Detect Power Enable bit
1 = Enables LVD, powers up LVD circuit
0 = Disables LVD, powers down LVD circuit
bit 3:0 LVDL3:LVDL0: Low Voltage Detection Limit bits
The following shows the typical limits for the low voltage detect circuitry. Refer to the device data
sheet electrical specifications for the actual tested limit.
1111 = External analog input is used (input comes from the LVDIN pin)
1110 = 4.5V min - 4.77V max.
1101 = 4.2V min - 4.45V max.
1100 = 4.0V min - 4.24V max.
1011 = 3.8V min - 4.03V max.
1010 = 3.6V min - 3.82V max.
1001 = 3.5V min - 3.71V max.
1000 = 3.3V min - 3.50V max.
0111 = 3.0V min - 3.18V max.
0110 = 2.8V min - 2.97V max.
0101 = 2.7V min - 2.86V max.
0100 = 2.5V min - 2.65V max.
0011 = 2.4V min - 2.54V max.
0010 = 2.2V min - 2.33V max.
0001 = 2.0V min - 2.12V max.
0000 = 1.8V min - 1.91V max.
Note 1: LVDL3:LVDL0 modes which result in a trip point below the valid operating voltage of
the device are not tested.
2: See the “Electrical Specifications” section, parameter 32 in the Device Data
Sheet for tested limits.
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39528A-page 27-5
Section 27. Low Voltage Detect
Low
Voltage Detect
27
27.3 Operation
The LVD module is useful to add robustness into the application. The device can monitor the
state of the device voltage. When the device voltage enters the voltage window near the lower
limit of the valid operating voltage range, the device can save values to ensure a "clean" shutdown
through the brown-out.
Depending on the power source for the device voltage, the voltage normally decreases 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.
Each time that the LVD module is enabled, the circuitry requires some time to stabilize. After the
circuitry has stabilized, all status flags may be cleared. The module will then indicate the proper
state of the system.
Steps to setup the LVD module:
1. Write the value to the LVDL3:LVDL0 bits (LVDCON register) which selects the desired
LVD Trip Point.
2. Ensure that LVD interrupts are disabled (the LVDIE bit is cleared or the GIE bit is cleared).
3. Enable the LVD module (set the LVDEN bit in the LVDCON register).
4. Wait for the LVD module to stabilize (the IRVST bit to become set).
5. Clear the LVD interrupt flag which may have falsely become set while the LVD module stabilized
(clear the LVDIF bit).
6. Enable the LVD interrupt (set the LVDIE and the GIE bits).
Figure 27-3 shows some waveforms that the LVD module may be used to detect.
Figure 27-3: Low Voltage Detect Waveforms
Note: The system design should be done to 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.
.
VLVD
VDD
LVDIF
VLVD
VDD
Enable LVD
Internally Generated 50 ms
LVDIF may not be set
Enable LVD
50 ms
LVDIF
LVDIF cleared in software
LVDIF cleared in software
LVDIF cleared in software,
CASE 1:
CASE 2:
LVDIF remains set since LVD condition still exists
Reference stable
Internally Generated
Reference stable
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39528A-page 27-6 2000 Microchip Technology Inc.
27.3.1 Reference Voltage Set Point
The internal reference voltage of the LVD module may be used by other internal circuitry (e.g.,
the programmable Brown-out Reset). If these circuits are disabled (lower power consumption),
the reference voltage circuit requires stabilization time before a low voltage condition can be
reliably detected. This time is specified in electrical specification parameter # 36. The low-voltage
interrupt flag will not be enabled until a stable reference voltage is reached. Refer to the
timing diagram in Figure 27-3.
27.3.2 Current Consumption
When the module is enabled the LVD comparator and voltage divider are enabled and will consume
static current. The voltage divider can be tapped from multiple places in the resistor array.
Total current consumption when enabled is specified in electrical specification parameter D022B
(typically < 50 µA).
27.4 Operation During SLEEP
When enabled, the LVD circuitry continues to operate during SLEEP. If the device voltage
crosses the trip point, the LVDIF bit will be set and the device will wake-up from SLEEP. Device
execution will continue from the interrupt vector address, if interrupts have been globally
enabled.
27.5 Effects of a RESET
A device RESET forces all registers to their RESET state. This forces the LVD module to be
turned off.
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39528A-page 27-7
Section 27. Low Voltage Detect
Low
Voltage Detect
27
27.6 Initialization
Example 27-1 shows an initialization of the LVD module.
Example 27-1: LVD Initialization
MOVLW 0x14 ; Enable LVD, Trip point = 2.5V
MOVWF LVDCON ;
LVD_STABLE
BTFSS LVDCON, IRVST ; Has LVD circuitry stabilized?
GOTO LVD_STABLE ; NO, Wait longer
BCF PIR, LVDIF ; YES, clear LVD interrupt flag
BSF PIE, LVDIE ; Enable LVD interrupt
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39528A-page 27-8 2000 Microchip Technology Inc.
27.7 Design Tips
Question 1: The LVD circuitry seems to be generating random interrupts?
Answer 1:
Ensure that the LVD circuitry is stable before enabling the LVD interrupt. This is done by monitoring
the IRVST bit. Once the IRVST bit is set, the LVDIF bit should be cleared and then the
LVDIE bit may be set.
Question 2: How can I reduce the current consumption of the module?
Answer 2:
Low Voltage Detect is used to monitor the device voltage. The power source is normally a battery
that ramps down slowly. This means that the LVD circuity can be disabled for most of the time,
and only enabled occasionally to do the device voltage check.
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39528A-page 27-9
Section 27. Low Voltage Detect
Low
Voltage Detect
27
27.8 Related Application Notes
This section lists application notes that are related to this section of the manual. These application
notes may not be written specifically for the Enhanced family (that is they may be written for
the Base-Line, the Mid-Range, or High-End families), but the concepts are pertinent, and could
be used (with modification and possible limitations). The current application notes related to the
LVD module are:
Title Application Note #
No related application notes at this time
Note: Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
http://www.microchip.com/10/faqs/codeex/
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39528A-page 27-10 2000 Microchip Technology Inc.
27.9 Revision History
Revision A
This is the initial released revision of the Enhanced MCU Low Voltage Detect module description.
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39529A-page 28-1
and Sleep Mode
Watchdog Timer
28
Section 28. WDT and SLEEP Mode
HIGHLIGHTS
This section of the manual contains the following major topics:
28.1 Introduction .................................................................................................................. 28-2
28.2 Control Register ........................................................................................................... 28-3
28.3 Watchdog Timer (WDT) Operation .............................................................................. 28-4
28.4 SLEEP (Power-Down) Mode........................................................................................ 28-5
28.5 Initialization ................................................................................................................ 28-11
28.6 Design Tips ................................................................................................................ 28-12
28.7 Related Application Notes.......................................................................................... 28-13
28.8 Revision History ......................................................................................................... 28-14
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39529A-page 28-2 2000 Microchip Technology Inc.
28.1 Introduction
The Watchdog Timer and SLEEP functions are two functions that can enhance the system.
The Watchdog Timer may be used to return to operating mode, or to cause a controller RESET
if the program begins to behave erratically. This enhances the overall operation of the system.
The Watchdog Timer (WDT) is a free running on-chip RC oscillator that does not require any
external components. The block diagram is shown in Figure 28-1. This RC oscillator is separate
from the device RC oscillator of the OSC1/CLKI pin. This means that the WDT will run, even if
the clock on the OSC1/CLKI and OSC2/CLKO pins has been stopped, for example, by execution
of a SLEEP instruction.
The Watchdog Timer (WDT) is enabled/disabled by a device configuration bit. If the WDT is
enabled, software execution may not disable this function. When the WDTEN configuration bit is
cleared, the SWDTEN bit enables/disables the operation of the WDT.
Figure 28-1: Watchdog Timer Block Diagram
The SLEEP function halts controller activity and reduces current consumption to a minimum. The
SLEEP mode is a reduced power state, where it is possible to halt almost all activity in the controller.
In this mode, power consumption is very low, allowing for long term operation from battery
powered applications. Normal operation may be resumed when any of several interrupts occur,
the WDT times out, or a RESET occurs.
WDT Timer Postscaler
WDTEN
8 - to - 1 MUX WDTPS<2:0>
WDT
Time-out
8
SWDTEN bit
Configuration bit
Note: WDTPS2:WDTPS0 are bits in a configuration register.
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39529A-page 28-3
Section 28. Watchdog Timer and SLEEP Mode
and Sleep Mode
Watchdog Timer
28
28.2 Control Register
Register 28-1 shows the WDTCON register. This is a readable and writable register that contains
the SWDTEN control bit. If the WDT enable configuration bit has been cleared, this software controlled
bit enables or disables the WDT.
Register 28-1: WDTCON Register
U-0 U-0 U-0 U-0 U-0 U-0 U-0 R/W-0
— — — — — — — SWDTEN
bit 7 bit 0
bit 7:1 Unimplemented: Read as ’0’
bit 0 SWDTEN: Software Controlled Watchdog Timer Enable bit
1 = Watchdog Timer is on
0 = Watchdog Timer is turned off if the WDTEN configuration bit is ’0’
Legend
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39529A-page 28-4 2000 Microchip Technology Inc.
28.3 Watchdog Timer (WDT) Operation
During normal operation, a WDT time-out generates a device RESET. If the device is in SLEEP
mode, a WDT time-out causes the device to wake-up and continue with normal operation. This
is known as a WDT wake-up.
The WDT can be permanently enabled by setting the WDTEN configuration bit. If the WDT configuration
bit disables the WDT, then software can be used to enable/disable the WDT through
setting/clearing the SWDTEN bit.
28.3.1 WDT Period
The WDT has a nominal time-out period of 18 ms with no postscaler (see the “Electrical Specifications”
section, parameter 31). The time-out period varies with temperature, VDD and process
variations from part to part (see DC parameters in the “Electrical Specifications” section).
If longer time-outs are desired, a postscaler with a division ratio of up to 1:128 can be assigned
to the WDT. Thus, time-out periods of up to 2.3 seconds can be realized.
The postscaler assignment is specified at time of device programming through the device configuration
bits.
The CLRWDT and SLEEP instructions clear the WDT counter and the WDT postscaler which prevents
it from timing out and generating a device RESET.
When a CLRWDT instruction is executed and the prescaler is assigned to the WDT, the prescaler
count will be cleared, but the prescaler assignment is not changed.
The TO bit in the RCON register will be cleared upon a Watchdog Timer time-out (WDT Reset
and WDT wake-up).
28.3.2 Clearing the WDT Counter
The CLRWDT instruction will force the count value of the WDT counter to ’0’. When the WDT is
disabled (WDTEN configuration bit = ’0’ and SWDTEN is clear), the WDT counter is forced to ’0’
and the internal WDT clock source is disabled. Then, when the WDT is enabled (setting the
SWDTEN bit when previously cleared), the WDT counter starts from a value of ’0’.
28.3.3 WDT Considerations
It should also be taken in account that under worst case conditions (VDD = Minimum, Temperature
= Maximum, WDT postscaler = Maximum), it may take several seconds before a WDT
time-out occurs.
28.3.4 Effects of a RESET
When a device RESET occurs, the Watchdog Timer counter and postscaler counter are cleared
and the TO bit is set.
Table 28-1: Summary of Watchdog Timer Registers
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
CONFIG2H — — — — WDTPS2 WDTPS1 WDTPS0 WDTEN
WDTCON — — — — — — — SWDTEN
RCON IPEN LWRT — RI TO PD POR BOR
Legend: Shaded cells are not used by the Watchdog Timer.
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39529A-page 28-5
Section 28. Watchdog Timer and SLEEP Mode
and Sleep Mode
Watchdog Timer
28
28.4 SLEEP (Power-Down) Mode
SLEEP (Power-down) mode is the lowest current consumption state and is entered by executing
a SLEEP instruction. The device oscillator is turned off, so no system clocks are occurring in the
device.
If enabled, the Watchdog Timer will be cleared but keeps running, the PD bit in the RCON register
is cleared, the TO bit is set, and the oscillator driver is turned off. The I/O ports maintain the status
they had before the SLEEP instruction was executed (driving high, low, or hi-impedance).
For lowest current consumption in this mode, all I/O pins should be either at VDD or VSS, with no
external circuitry drawing current from the I/O pin and modules that are specified to have a delta
SLEEP current, should be disabled. I/O pins that are hi-impedance inputs should be pulled high
or low externally, to avoid switching currents caused by floating inputs. The contribution from
on-chip pull-ups on PORTB should be considered.
During SLEEP, the MCLR pin must be at a valid high level.
Some features of the device consume a delta current. These are enabled/disabled by device
configuration bits. These features include the Watchdog Timer (WDT), LVD, and Brown-out
Reset (BOR) circuitry modules.
28.4.1 Wake-up from SLEEP
There are several ways to wake the controller from SLEEP. The WDT can wake-up the controller
when it times out. A RESET will wake the controller and cause the program to restart, and interrupts
(from peripherals or external sources) will wake the controller from SLEEP.
The device can wake-up from SLEEP through one of the following events:
1. Any device RESET, such as MCLR pin = VIL, VDD = VBOR (if enabled).
2. Watchdog Timer Wake-up (if WDT was enabled).
3. Any peripheral module which can set its interrupt flag while in SLEEP, such as:
- An external INT pin
- Change on Port pin
- Comparators
- A/D
- Timer1
- Timer3
- LVD
- MSSP
- Capture
- PSP read or write
- CCP1
- CCP2
- Addressable USART
- PORTB Interrupt on Change
- External Interrupts
- Parallel Slave Port
- Voltage Reference (bandgap)
- WDT
The first event will RESET the device upon wake-up. However, the latter two events will wake
the device and then resume program execution. The TO and PD bits in the RCON register can
be used to determine the cause of device RESET. The PD bit, which is set on power-up, is
cleared when SLEEP is invoked. The TO bit is cleared if WDT time-out occurred (and caused a
wake-up).
When the SLEEP instruction is being executed, the next instruction (PC + 2) is pre-fetched. For
the device to wake-up through an interrupt event, the corresponding interrupt enable bit must be
set (enabled). Wake-up is regardless of the state of the GIE bit. If the GIE bit is clear (disabled),
the device continues execution at the instruction after the SLEEP instruction. If the GIE bit is set
(enabled), the device executes the instruction after the SLEEP instruction and then branches to
the interrupt address. In cases where the execution of the instruction following SLEEP is not
desirable, the user should have a NOP after the SLEEP instruction.
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39529A-page 28-6 2000 Microchip Technology Inc.
28.4.2 Wake-up Using Interrupts
When interrupts are globally disabled (GIE cleared) and any interrupt source has both its interrupt
enable bit and interrupt flag bit set, one of the following events will occur:
• If an interrupt condition (interrupt flag bit and interrupt enable bits are set) occurs before the
execution of a SLEEP instruction, the SLEEP instruction will complete as a NOP. Therefore,
the WDT and WDT postscaler will not be cleared, the TO bit will not be set and PD bit will
not be cleared.
• If the interrupt condition occurs during or after the execution of a SLEEP instruction, the
device will immediately wake-up from SLEEP. The SLEEP instruction will be completely
executed before the wake-up. Therefore, the WDT and WDT postscaler will be cleared, the
TO bit will be set and the PD bit will be cleared.
Even if the flag bits were checked before executing a SLEEP instruction, it may be possible for
flag bits to become set before the SLEEP instruction completes. To determine whether a SLEEP
instruction executed, test the PD bit. If the PD bit is set, the SLEEP instruction was executed as
a NOP.
To ensure that the WDT is clear, a CLRWDT instruction should be executed before a SLEEP
instruction.
Figure 28-2: Wake-up from SLEEP Through Interrupt
Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4
OSC1
CLKOUT(4)
INT pin
INTF flag
(INTCON<1>)
GIE bit
(INTCON<7>)
INSTRUCTION FLOW
PC
Instruction
fetched
Instruction
executed
PC PC+2 PC+4
Inst(PC) = SLEEP
Inst(PC - 1)
Inst(PC + 2)
SLEEP
Processor in
SLEEP
Interrupt Latency(3)
Inst(PC + 4)
Inst(PC + 2)
Inst(INT_addr) Inst(INT_addr + 1)
Dummy cycle Inst(INT_addr)
PC+4 INT_addr INT_addr + 1
Dummy cycle
TOST(2)
PC+4
Note 1: XT, HS or LP oscillator mode assumed.
2: TOST = 1024TOSC (drawing not to scale). This delay will not occur for RC and EC osc modes.
3: GIE = '1' assumed. In this case, after wake-up, the processor jumps to the interrupt routine. If GIE = '0', execution will
continue in-line.
4: CLKOUT is not available in these osc modes, but shown here for timing reference.
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39529A-page 28-7
Section 28. Watchdog Timer and SLEEP Mode
and Sleep Mode
Watchdog Timer
28
Interrupt sources can wake the controller from SLEEP without actually causing an interrupt. The
interrupt source must have its interrupt enable flag set, but GIE does not need to be set. If GIE
is clear, the controller will wake without vectoring to an interrupt. If GIE is set, the controller will
vector to an interrupt.
If interrupt priority is not used, all interrupt priority bits are set. If interrupt priority is used (any
interrupt priority bit is cleared), GIEH controls high priority interrupts and GIEL controls low priority
interrupts. Table 28-2 shows the response to the interrupt flag bits depending on the state
of the interrupt enable and priority bits.
Table 28-2: SLEEP Mode, Interrupt Enable Bits, and Interrupt Results
Interrupt Source GIE/GIEH PEIE/GIEL Interrupt
Priority
Peripheral
Interrupt Flag
Response to
Interrupt
Any interrupt source
that operates during
SLEEP
X X X 0 SLEEP
10 0
low priority
1 wake
01 1
high priority
1 wake
0 0 X 1 wake
1 0 1 1 High priority
vector followed
1 1 0 1 Low priority
vector followed
Legend: X is don’t care.
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39529A-page 28-8 2000 Microchip Technology Inc.
28.4.3 Effects of SLEEP Mode on the On-Chip Oscillator
When the device executes a SLEEP instruction, the Watchdog Timer and prescaler counter are
cleared (if the WDT is enabled), the on-chip clocks and oscillator are turned off and the controller
is held at the beginning of an instruction cycle (Q1 state). With the oscillator off, the OSC1 and
OSC2 signals will stop oscillating. Since all the transistor switching currents have been removed,
SLEEP mode achieves the lowest current consumption of the device (only leakage currents).
Enabling any on-chip feature that will operate during SLEEP will increase the current consumed
during SLEEP. The user can wake from SLEEP through external RESET, Brown-out Reset (if
enabled), external interrupt, Watchdog Timer time-out or a peripheral interrupt.
Table 28-3: Oscillator Selections, SLEEP Mode, and Waking from SLEEP
OSC
Mode OSC1 Pin in SLEEP OSC2 Pin in SLEEP Waking Delays OSC1 in Run OSC2 in Run
RC Floating, pulled high At logic low None R and C set
frequency
CLKO (4Tosc)
RCIO Floating, pulled high Configured as I/O pin None R and C set
frequency
Configured as
I/O pin
LP At quiescent voltage
level
At quiescent voltage
level
TOST (1) XTAL/res XTAL/res
XT At quiescent voltage
level
At quiescent voltage
level
TOST (1) XTAL/res XTAL/res
HS At quiescent voltage
level
At quiescent voltage
level
TOST (1) XTAL/res XTAL/res
HS
w/PLL
At quiescent voltage
level
At quiescent voltage
level
TOST (1) + TPLL (2) XTAL/res XTAL/res
EC Driven by external clock
source
At logic low None Driven by external
clock source
CLKO (4TOSC)
ECIO Driven by external clock
source
Configured as I/O pin None Driven by external
clock source
Configured as
I/O pin
Note 1: OST (Oscillator Start-up Timer) counts 1024 oscillator cycles before allowing controller clocks to resume.
This provides time for the oscillator to start-up and stabilize.
2: A TPLL delay is required to allow the PLL to lock to the oscillator frequency.
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39529A-page 28-9
Section 28. Watchdog Timer and SLEEP Mode
and Sleep Mode
Watchdog Timer
28
28.4.4 Wake-up Delays
Several factors affect how much time the controller requires to return to operating mode from
SLEEP. These include oscillator mode and the use of the PLL.
The Oscillator Start-up Timer, OST, counts 1024 oscillator cycles to allow the oscillator to start-up
and stabilize before allowing system clocks to resume. The OST is not enabled for RC and EC
oscillator modes.
28.4.4.1 Oscillator With PLL Enabled Time-out Sequence After Wake-up
The Oscillator Start-up Timer (OST) provides a 1024 oscillator cycle delay after a wake-up from
SLEEP has occurred. 1024 oscillator cycles are not a sufficient amount of time to allow the PLL
to lock at high frequencies. An additional TPLL time is required to allow the PLL to lock before
allowing system clocks to resume.
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39529A-page 28-10 2000 Microchip Technology Inc.
28.4.5 Peripheral Module Operation During SLEEP
Table 28-4 gives an overview of which devices operate during SLEEP. For further details, refer to
the individual sections in this reference manual.
Table 28-4: Peripheral Modules Active in SLEEP Mode
28.4.6 Effects of a WDT Time-out
If the WDT has been enabled, either by the WDTEN configuration bit (=’1’) or by the SWDTEN
bit being set, the WDT will wake-up the controller from SLEEP mode and clear the TO bit.
28.4.7 Effects of a Device RESET
When MCLR is asserted, TO is set and PD is clear. All other bits in RCON are unchanged. The
controller will resume code execution at the RESET vector address.
Peripheral Module
Operates
During
SLEEP?
Mode of Operation Wakes from SLEEP?
Timer1, Timer3 Yes External clock/U.S.C.G.,
Asynchronous Counter mode
Yes
A/D Yes A/D clock = RC clock Yes
CCP1, CCP2 Yes Only capture available. Yes, do not rely on capture value
MSSP Yes I
2C – Non-master modes
SPI – Slave mode
Yes
Yes
Addressable USART Yes Synchronous slave mode Yes
PORTB Interrupt on
Change
Yes All Yes
External Interrupts Yes All Yes
Parallel Slave Port Yes All Yes
LVD Yes All Yes
Volt Reference (bandgap) Yes If required to support LVD, and A/D No
WDT Yes All Yes
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39529A-page 28-11
Section 28. Watchdog Timer and SLEEP Mode
and Sleep Mode
Watchdog Timer
28
28.5 Initialization
No initialization code at this time.
39500 18C Reference Manual.book Page 11 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39529A-page 28-12 2000 Microchip Technology Inc.
28.6 Design Tips
Question 1: My system voltage drops and then returns to the specified device voltage
range. The device is not operating correctly and the WDT does not reset
and return the device to proper operation.
Answer 1:
The WDT was not designed to be a recovery from a brown-out condition. It was designed to
recover from errant software operation (the device remaining in the specified operating ranges).
If your system can be subjected to brown-outs, either the on-chip brown-out circuitry should be
enabled or an external brown-out circuit should be implemented.
Question 2: Device RESETS even though I do the CLRWDT instruction in my loop.
Answer 2:
Make sure that the loop with the CLRWDT instruction meets the minimum specification of the WDT
(not the typical).
Question 3: Device never gets out of RESETS.
Answer 3:
On power-up, you must take into account the Oscillator Start-up time (Tost). Sometimes it helps
to put the CLRWDT instruction at the beginning of the loop, since this start-up time may be variable.
39500 18C Reference Manual.book Page 12 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39529A-page 28-13
Section 28. Watchdog Timer and SLEEP Mode
and Sleep Mode
Watchdog Timer
28
28.7 Related Application Notes
This section lists application notes that are related to this section of the manual. These application
notes may not be written specifically for the Enhanced family (that is, they may be written for
the Base-Line, the Mid-Range or High-End families), but the concepts are pertinent and could be
used (with modification and possible limitations). The current application notes related to the
WDT and SLEEP Mode are:
Title Application Note #
Power-up Trouble Shooting AN607
Note: Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
http://www.microchip.com/10/faqs/codeex/
39500 18C Reference Manual.book Page 13 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39529A-page 28-14 2000 Microchip Technology Inc.
28.8 Revision History
Revision A
This is the initial released revision of the Enhanced MCU Watchdog Timer and SLEEP mode
description.
39500 18C Reference Manual.book Page 14 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39530A-page 29-1
Device
Configuration Bits
29
Section 29. Device Configuration Bits
HIGHLIGHTS
This section of the manual contains the following major topics:
29.1 Introduction .................................................................................................................. 29-2
29.2 Configuration Word Bits ............................................................................................... 29-3
29.3 Program Verification/Code Protection ........................................................................ 29-10
29.4 ID Locations ............................................................................................................... 29-11
29.5 Device ID ................................................................................................................... 29-11
29.6 Design Tips ................................................................................................................ 29-12
29.7 Related Application Notes.......................................................................................... 29-13
29.8 Revision History ......................................................................................................... 29-14
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39530A-page 29-2 2000 Microchip Technology Inc.
29.1 Introduction
The device configuration bits allow each user to customize certain aspects of the device to the
needs of the application. When the device powers up, the state of these bits determines the
modes that the device uses. Section 29.2 “Configuration Word Bits” discusses the configuration
bits and the modes to which they can be configured. These bits are mapped in program
memory locations starting at address 300000h. These locations are accessible during normal
device operation.
The configuration bits can be programmed (read as '0') or left unprogrammed (read as '1') to
select various device configurations. The ability to change these settings once they have been
programmed depends on the memory technology and the package type. This is discussed
below:
• Read Only Memory (ROM) devices: These bits are specified at time of ROM code submittal;
once the device is masked, these bits can not be changed (would require a new mask
code).
• One Time Programmable (OTP) devices: Once the bit is programmed (’0’), it may not be
changed.
• Windowed EPROM devices: Once these bits are programmed (’0’), the device must be UV
erased to return the configuration word to the erased state. UV erasing the device also
erases the program memory. Window devices are for debugging purposes.
• FLASH devices: These bits may be erased and reprogrammed.
Note: Microchip does not recommend code-protecting windowed devices.
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39530A-page 29-3
Section 29. Device Configuration Bits
Device
Configuration Bits
29
29.2 Configuration Word Bits
These configuration bits specify some of the device modes and are programmed by a device programmer,
or by using the In-Circuit Serial ProgrammingTM (ICSP) feature of the Enhanced Architecture
devices. The placement of these configuration bits is automatically handled when you
select the device in your device programmer. The desired state of the configuration bits may be
specified in the source code (dependent on the language tool used), or through the programming
interface. After the device has been programmed, the application software may read the configuration
bit values through the Table read instructions. For additional information, please refer to
the Programming Specification of the device.
Note 1: Always ensure that your device programmer has the same device selected as you
are programming.
2: Microchip recommends that the desired configuration bit states be embedded into
the application source code. This is easily done in the MPASM assembler by the use
of the CONFIG directive. See Subsection 29.2.1 “MPASM’s CONFIG Directive.”
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39530A-page 29-4 2000 Microchip Technology Inc.
Register 29-1: Configuration Bits
P/R-u
Bit placement is device dependent
A19DIS: Disable A19:A16 Drivers bit
This bit disables the A19:A16 address lines of the system bus so that these pins may be used
as general purpose I/O.
1 = Drivers enabled
0 = Drivers disabled
A15DIS: Disable AD15:AD12 Drivers bit
This bit disables the AD15:AD12 address lines of the system bus so that these pins may be
used as general purpose I/O. The AD15:AD12 address lines may only be disabled when the
system bus is configured for 8-bit data (BW16 = ’0’).
When BW16 = ’1’
1 = Drivers enabled (state of A15DIS is ignored)
0 = Drivers enabled (state of A15DIS is ignored)
When BW16 = ’0’
1 = Drivers enabled
0 = Drivers disabled
A11DIS: Disable AD11:AD8 Drivers bit
This bit disables the AD11:AD8 address lines of the system bus so that these pins may be used
as general purpose I/O. The AD11:AD8 address lines may only be disabled when the system
bus is configured for 8-bit data (BW16 = ’0’).
When BW16 = ’1’
1 = Drivers enabled (state of A11DIS is ignored)
0 = Drivers enabled (state of A11DIS is ignored)
When BW16 = ’0’
1 = Drivers enabled
0 = Drivers disabled
BADIS: Byte Address BA0 Disable bit
1 = Drivers enabled
0 = Drivers disabled
BSDIS: Byte Select UB,LB Disable bit
1 = Drivers enabled
0 = Drivers disabled
BOREN: Brown-out Reset Enable bit
1 = Brown-out Reset enabled
0 = Brown-out Reset disabled
BORV1:BORV0: Brown-out Reset Voltage bits
These bits specify the trip point for the Brown-out Reset circuitry. The values shown below are
for a typical device. Please refer to the device data sheet “Electrical Specifications” section
for the tested range.
11 = VBOR set to 2.5V or 1.8V (device dependent)
10 = VBOR set to 2.7V
01 = VBOR set to 4.2V
00 = VBOR set to 4.5V
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39530A-page 29-5
Section 29. Device Configuration Bits
Device
Configuration Bits
29
BW16: 16-bit Bus Width bit
This bit specifies the data width of the system bus.
1 = System Bus has 16-bit data bus
0 = System Bus has 8-bit data bus
CCP2MX: CCP2 Mux bit
1 = CCP2 input/output is multiplexed with an I/O
0 = CCP2 input/output is multiplexed with a different I/O
CP: Code Protection bits (apply when in Code Protected Microcontroller Mode)
1 = Program memory code protection off
0 = All of program memory code protected
DP: Data EEPROM Memory Code Protection bit
1 = Code protection off
0 = Data EEPROM memory is code protected
Note: This bit is used when a ROM program memory device or a ROMless device has
Data EEPROM memory.
FOSC2:FOSC0: Oscillator Selection bits
111 = RC oscillator w/ OSC2 configured as I/O
110 = HS oscillator with PLL enabled/clock frequency = (4 x FOSC1)
101 = EC oscillator w/ OSC2 configured as I/O
100 = EC oscillator w/ OSC2 configured as divide by 4 clock output
011 = RC oscillator
010 = HS oscillator
001 = XT oscillator
000 = LP oscillator
OSCSEN: Oscillator System Clock Switch Enable bit
1 = Oscillator system clock switch option is disabled (main oscillator is source)
0 = Oscillator system clock switch option is enabled (oscillator switching is enabled)
PM1:PM0: Processor Mode Select bits
These bits select the processor operating mode for the device. The processor operating mode
specifies how the program memory is mapped (internal/external) and the default configuration
of the system bus pins.
11 = Microprocessor mode
10 = Microcontroller mode
01 = Reserved
00 = Extended microcontroller mode
PWRTEN: Power-up Timer Enable bit
1 = PWRT disabled
0 = PWRT enabled
STVREN: Stack Full/Underflow Reset Enable bit
1 = Stack Full/Underflow will cause RESET
0 = Stack Full/Underflow will not cause RESET
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39530A-page 29-6 2000 Microchip Technology Inc.
WAIT: System Bus Wait bit
This bit is used to enable wait states for table reads and table writes to external memory on the
system bus
1 = Wait selections unavailable, device will not wait
0 = Wait programmed by WAIT1 and WAIT0 bit in MEMCON register
WDIS: Write Select WRH, WRL Disable bit
1 = Drivers enabled
0 = Drivers disabled
WDTPS2:WDTPS0: Watchdog Timer Postscale Select bits
111 = 1:1
110 = 1:2
101 = 1:4
100 = 1:8
011 = 1:16
010 = 1:32
001 = 1:64
000 = 1:128
WDTEN: Watchdog Timer Enable bit
1 = WDT enabled
0 = WDT disabled (control is placed on the SWDTEN bit, in register WDTCON)
Legend
R = Readable bit P = Programmable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR reset ’1’ = bit is set ’0’ = bit is cleared x = bit is unknown
Note 1: The position of the configuration bits is device dependent. Please refer to the device
programming specification for bit placement. You are not required to know the configuration
bit positions when using a Microchip device programmer. This is
addressed by either the configuration direction of the software tool or MPLAB’s user
interface.
2: In ROMless devices, some of the system bus configuration bits are hardwired into
a set configuration. Other bits may be placed in protected SFR locations which can
only be modified after properly writing to the CMLK1:CMLK0 bits.
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39530A-page 29-7
Section 29. Device Configuration Bits
Device
Configuration Bits
29
29.2.1 MPASM’s CONFIG Directive
Microchip’s assembler, MPASM, has a nice feature (directives) that allows you to specify the
device configuration in the source code file. This ensures that when programming a device for
an application, the required configuration is also programmed. This minimizes the risk of programming
the wrong device configuration and then wondering why it no longer works in the application
(unexpected operation).
Example 29-1 shows a template for using the CONFIG directive.
Example 29-1: Using the CONFIG Directive, a Source File Template
The symbols currently in the Microchip Device Header files make using the CONFIG directive
straight forward. These are shown in Table 29-1. The symbols available for your device are listed
in the Microchip Include file for that device.
LIST p = p18C452 ; List Directive,
; Revision History
;
#INCLUDE ; Microchip Device Header File
;
#INCLUDE ; File which includes my standard macros
#INCLUDE ; File which includes macros specific
; to this application
;
; Specify Device Configuration Bits for
; Program Configuration Registers 0 through 6
__CONFIG _CONFIG0, CP_OFF_0
__CONFIG _CONFIG1, LPSCEN_OFF_1 & RCRA6_OSC_1
__CONFIG _CONFIG2, BORV_25_2 & BOREN_ON_2 & PWRTEN_OFF_2
__CONFIG _CONFIG3, WDPS_128_3 & WDT_ON_3
__CONFIG _CONFIG5, CCP2MX_ON_5
__CONFIG _CONFIG6, SVTREN_ON_6
;
org 0x00 ; Start of Program Memory
RESET_ADDR : ; First instruction to execute after a reset
end
Note: As long as the correct device is specified (in the LIST and INCLUDE file directives),
the correct polarity of all bits is ensured.
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39530A-page 29-8 2000 Microchip Technology Inc.
Table 29-1: _CONFIG Directive Symbols (from Microchip Header Files) (1)
Feature Configuration
Byte Symbols Comment
Oscillators _CONFIG1H
_LP_OSC_1 LP mode for device
_XT_OSC_1 XT mode for device
_HS_OSC_1 HS mode for device oscillator
_RC_OSC_1 RC mode for device oscillator
_RCIO_OSC_1 RC mode for device oscillator
with clockout configured as I/O pin
_EC_OSC_1 EC (external clock) mode for
device oscillator
_ECIO_OSC_1
EC (external clock) mode for
device oscillator with clockout
configured as I/O pin
_HS4_OSC_1 HS mode with 4 x PLL
for device oscillator
_HSPLL_OSC_1 HS mode with 4 x PLL for device
oscillator (4)
Oscillator
Switch _CONFIG1H _LPSCEN_ON_1 Oscillator switch enabled
_LPSCEN_OFF_1 Oscillator switch disabled
Code Protect _CONFIG1L _CP_ON_0 Code Protect enabled
_CP_OFF_0 Code Protect disabled
Watchdog
Timer _CONFIG2H _WDT_ON_3 Watchdog Timer enabled
_WDT_OFF_3 Watchdog Timer disabled
Watchdog
Timer
Postscale
Assignment
_CONFIG2H
_WDTPS_128_3 WDT prescaler set to 1:128
_WDTPS_64_3 WDT prescaler set to 1:64
_WDTPS_32_3 WDT prescaler set to 1:32
_WDTPS_16_3 WDT prescaler set to 1:16
_WDTPS_8_3 WDT prescaler set to 1:8
_WDTPS_4_3 WDT prescaler set to 1:4
_WDTPS_2_3 WDT prescaler set to 1:2
_WDTPS_1_3 WDT prescaler set to 1:1
Power-up
Timer _CONFIG2L _PWRTEN_ON_2 Power-up Timer enabled
_PWRTEN_OFF_2 Power-up Timer disabled
Brown-out
Reset _CONFIG2L _BOREN_ON_2 Brown-out Reset enabled
_BOREN_OFF_2 Brown-out Reset disabled
BOR
Trip-Point
Voltage
_CONFIG2L
_BORV_18_2 BOR trip point = 1.8V min (2, 3)
_BORV_25_2 BOR trip point = 2.5V min (2, 3)
_BORV_27_2 BOR trip point = 2.7V min (3)
_BORV_42_2 BOR trip point = 4.2V min (3)
_BORV_45_2 BOR trip point = 4.5V min (3)
Note 1: Not all configuration bit symbols may be available on any one device. Please refer to
the Microchip include file of that device for available symbols.
2: The option for a 1.8V or 2.5V BOR trip point is device dependent. Only one of these
symbols will be available in the Microchip supplied header file.
3: These are the trip points for a typical device. Other trip points (symbols) may be specified
for the device.
4: Symbol obsoleted and may not be available in header file.
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39530A-page 29-9
Section 29. Device Configuration Bits
Device
Configuration Bits
29
CCP2 pin
Multiplex _CONFIG3H _CCP2MX_ON_5 CCP2 out multiplexer enabled
_CCP2MX_OFF_5 CCP2 out multiplexer disabled
Processor
Mode _CONFIG3L
_MP_MODE_4 Microprocessor mode
_MC_MODE_4 Microcontroller mode
_XMC_MODE_4 Extended Microcontroller mode
External Data
Bus Wait _CONFIG3L _WAIT_ON_4 Wait on external data bus enabled
_WAIT_OFF_4 Wait on external data bus disabled
System Bus
A19 Disable _CONFIG4H _A19DIS_ON_7 System bus A19 disabled
_A19DIS_OFF_7 System bus A19 enabled
System Bus
A15 Disable _CONFIG4H _A15DIS_ON_7 System bus A15 disabled
_A15DIS_OFF_7 System bus A15 enabled
System Bus
A11 Disable _CONFIG4H _A11DIS_ON_7 System bus A11 disabled
_A11DIS_OFF_7 System bus A11 enabled
Byte Address
BA0 Disable _CONFIG4H _BADIS_ON_7 Byte Address BA0 disabled
_BADIS_OFF_7 Byte Address BA0 enabled
Byte Select
Disable _CONFIG4H _BSDIS_ON_7 Byte Select disabled
_BSDIS_OFF_7 Byte Select enabled
Write Select
Disable _CONFIG4H _WDIS_ON_7 Write Select disabled
_WDIS_OFF_7 Write Select enabled
Stack
Full/Overflow _CONFIG4L _STVREN_ON_6 Stack full/overflow rest enabled
_STVREN_OFF_6 Stack full/overflow rest disabled
Code Protect
Data
EEPROM
TBD
_DP_ON Data EEPROM protect enabled
_DP_OFF Data EEPROM protect disabled
Note 1: Not all configuration bit symbols may be available on any one device. Please refer to
the Microchip include file of that device for available symbols.
2: The option for a 1.8V or 2.5V BOR trip point is device dependent. Only one of these
symbols will be available in the Microchip supplied header file.
Table 29-1: _CONFIG Directive Symbols (from Microchip Header Files) (1) (Continued)
Feature Configuration
Byte Symbols Comment
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39530A-page 29-10 2000 Microchip Technology Inc.
29.3 Program Verification/Code Protection
If the code protection bit(s) have not been programmed, the on-chip program memory can be
read out for verification purposes.
29.3.1 ROM Devices
When a ROM device also has Data EEPROM memory, an additional code protect configuration
bit may be implemented. The program memory configuration bit is submitted as part of the ROM
code submittal. The Data EEPROM memory code protect configuration bit will be an EEPROM
bit. When ROM devices complete testing, the EEPROM data memory code protect bit will be programmed
to the same state as the program memory code protect bit. That is, Data EEPROM
code protect is off when program memory code protect is off and Data EEPROM code protect is
on for all other selections.
In applications where the device is code protected and the Data EEPROM needs to be programmed
before the application can be released, the Data EEPROM memory must have the
entire Data EEPROM memory erased. The device programming specification details the steps
to do this. Microchip device programmers implement the specified sequence. Once this
sequence is complete, the Data EEPROM memory code protect is disabled. This allows the
desired data to be programmed into the device. After programming the Data EEPROM memory
array, the Data EEPROM memory code protect configuration bit should be programmed as
desired.
Note: Microchip does not recommend code protecting windowed devices.
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39530A-page 29-11
Section 29. Device Configuration Bits
Device
Configuration Bits
29
29.4 ID Locations
Five memory locations (200000h - 200004h) are designated as ID locations where the user can
store checksum or other code-identification numbers. These locations are accessible during normal
execution through the TBLRD instruction, or during program/verify. The ID locations can be
read when the device is code protected.
29.5 Device ID
One memory location (two bytes) (3FFFFEh-3FFFFFh) is designated as the Device ID location.
The value at this location is specified by Microchip and is useful in determining the device.
Device ID bits can be used by a device programmer to retrieve information about what device is
being programmed and what the revision of the device is.
The Device ID can be accessed by a TBLRD instruction or via serial program/verify. The Device
ID can be read when the part is code protected.
The 5 LSbs are the device revision information, and the remaining 11 bits contain the device ID
number. This is shown in Table 29-2.
Table 29-2: Device ID Registers
Register Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
DEVID2 DEV10 DEV9 DEV8 DEV7 DEV6 DEV5 DEV4 DEV3
DEVID1 DEV2 DEV1 DEV0 REV4 REV3 REV2 REV1 REV0
39500 18C Reference Manual.book Page 11 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39530A-page 29-12 2000 Microchip Technology Inc.
29.6 Design Tips
Question 1: I have a JW device and I can no longer program it (reads scrambled data or
all '0's). What’s wrong with the device?
Answer 1:
Nothing. You probably code protected the device. If this is the case, the device is no longer
usable. See Section 29.3 “Program Verification/Code Protection” for more details.
Question 2: In converting from a PIC16C74 to a PIC18C452, my application no longer
works.
Answer 2:
1. Did you re-assemble the source file specifying the PIC18C452 in the INCLUDE file and
LIST directives? The use of the CONFIG directive is highly recommended.
2. On the device programmer, did you specify the PIC18C452, and were all the configuration
bits as desired?
Question 3: When I erase the device, the program memory is blank but the configuration
word is not yet erased.
Answer 3:
That is by design. Also remember that Microchip does not recommend code protecting windowed
devices.
39500 18C Reference Manual.book Page 12 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39530A-page 29-13
Section 29. Device Configuration Bits
Device
Configuration Bits
29
29.7 Related Application Notes
This section lists application notes that are related to this section of the manual. These application
notes may not be written specifically for the Enhanced MCU family (that is, they may be written
for the Base-Line, Mid-Range or High-End families), but the concepts are pertinent, and could
be used (with modification and possible limitations). The current application notes related to Configuration
Word are:
Title Application Note #
No related Application Notes at this time.
Note: Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
http://www.microchip.com/10/faqs/codeex/
39500 18C Reference Manual.book Page 13 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39530A-page 29-14 2000 Microchip Technology Inc.
29.8 Revision History
Revision A
This is the initial released revision of the Configuration Word description.
39500 18C Reference Manual.book Page 14 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39531A-page 30-1
ICSP
30
Section 30. In-Circuit Serial Programming™ (ICSP™)
HIGHLIGHTS
This section of the manual contains the following major topics:
30.1 Introduction .................................................................................................................. 30-2
30.2 Entering In-Circuit Serial Programming Mode ............................................................. 30-3
30.3 Application Circuit ........................................................................................................ 30-4
30.4 Programmer ................................................................................................................. 30-6
30.5 Programming Environment .......................................................................................... 30-6
30.6 Other Benefits .............................................................................................................. 30-7
30.7 Field Programming of PICmicro OTP MCUs................................................................ 30-8
30.8 Field Programming of FLASH PICmicro MCUs ......................................................... 30-10
30.9 Design Tips ................................................................................................................ 30-12
30.10 Related Application Notes.......................................................................................... 30-13
30.11 Revision History ......................................................................................................... 30-14
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39531A-page 30-2 2000 Microchip Technology Inc.
30.1 Introduction
All Enhanced MCU devices can be In-Circuit Serial Programmed (ICSP™) while in the end application
circuit. This is simply done with two lines for clock and data, and three other lines for
power, ground and the programming voltage.
In-Circuit Serial Programming (ICSP™) is a great way to reduce your inventory overhead and
time-to-market for your product. By assembling your product with a blank Microchip microcontroller
(MCU), you can stock one design. When an order has been placed, these units can be
programmed with the latest revision of firmware, tested and shipped in a very short time. This
method also reduces scrapped inventory due to old firmware revisions. This type of manufacturing
system can also facilitate quick turnarounds on custom orders for your product.
Most people would think to use ICSP with PICmicro® OTP MCUs only on an assembly line where
the device is programmed once. However, there is a method by which an OTP device can be
programmed several times depending on the size of the firmware. This method, explained in
Section 30.7, provides a way to field upgrade your firmware in a way similar to EEPROM- or
FLASH-based devices.
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39531A-page 30-3
Section 30. ICSP
ICSP
30
30.2 Entering In-Circuit Serial Programming Mode
The device is placed into a program/verify mode by holding the CLOCK (typically on the RB6 pin)
and DATA (typically on the RB7 pin) pins low, while raising the MCLR (VPP) pin from VIL to VIHH
(see programming specification) and having VDD at the programming voltage. Both the CLOCK
and DATA pins are Schmitt Trigger inputs in this mode. When in I/O mode and RB7 is driving
data, it is a CMOS output driver.
After RESET, to place the device into programming/verify mode, the program counter (PC) is at
location 00h. A command is then supplied to the device. Some commands then specify that
16-bits of program data are then supplied to or read from the device, depending on whether the
command was a load or a read. For complete details of serial programming, please refer to the
device specific Programming Specifications.
During the In-Circuit Serial Programming Mode, the WDT circuitry is disabled from generating a
device RESET.
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39531A-page 30-4 2000 Microchip Technology Inc.
30.3 Application Circuit
The application circuit must be designed to allow all the programming signals to be directly connected
to the PICmicro MCU. Figure 30-1 shows a typical circuit that is a starting point when
designing with ICSP. The application must compensate for the following:
1. Isolation of the MCLR/VPP pin from the rest of the circuit
2. Loading of pins CLOCK and DATA
3. Capacitance on each of the VDD, MCLR/VPP, CLOCK and DATA pins
4. Minimum and maximum operating voltage for VDD
5. PICmicro oscillator
30.3.1 Isolation of the MCLR/VPP Pin from the Rest of the Circuit
The MCLR/VPP pin is normally connected to an RC circuit. The pull-up resistor is tied to VDD and
a capacitor is tied to ground. This circuit can affect the operation of ICSP depending on the size
of the capacitor, since the VPP voltage must be isolated from the rest of the circuit . The resistor
(R1) should be greater than 10kΩ to provide isolation between VDD and VPP. It is, therefore, recommended
that the circuit in Figure 30-1 be used when an RC is connected to MCLR/VPP.
Another consideration with MCLR/VPP is that when the PICmicro device is programmed, this pin
is driven to approximately 13V and also to ground. Therefore, the application circuit must be isolated
from this voltage provided by the programmer.
30.3.2 Loading of Pins CLOCK and DATA
The CLOCK and DATA pins are used by the PICmicro MCU for serial programming. CLOCK is
driven by the programmer. DATA is a bi-directional pin that is driven by the programmer when
programming, and driven by the MCU when verifying. These pins must be isolated from the rest
of the application circuit so as not to affect the signals during programming. You must take into
consideration the output impedance of the programmer when isolating CLOCK and DATA from
the rest of the circuit. This isolation circuit must account for CLOCK being an input on the MCU
and for DATA being bi-directional (can be driven by both the MCU and the programmer). For
instance, PRO MATE® II has an output impedance of 1kΩ. If the design permits, these pins
should not be used by the application. This is not the case with most applications, so it is recommended
that the designer evaluate whether these signals need to be buffered. As a designer,
you must consider what type of circuitry is connected to CLOCK and DATA and then make a decision
on how to isolate these pins. Figure 30-1 does not show any circuitry to isolate CLOCK and
DATA on the application circuit, because this is very application dependent.
To simplify this interface, the optimal usage of these I/O pins in the application are (in order):
1. Dedicate the CLOCK/DATA pins for the ICSP interface (not connected to other circuitry).
2. Use these pins as outputs with minimal loading on the signal line.
3. Use isolation circuitry so these signals can be driven to the ICSP specifications.
Figure 30-1: Typical In-Circuit Serial Programming (ICSP) Application Circuit
Application PCB
PIC18CXXX
MCLR/VPP
VDD
VSS
DATA
CLOCK
VDD/VPP VDD
To application circuit
Isolation circuits
R2 ICSP Connector
R1
C1
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39531A-page 30-5
Section 30. ICSP
ICSP
30
30.3.3 Capacitance on Each of the VDD, MCLR/VPP, CLOCK and DATA Pins
The total capacitance on the programming pins affects the rise rates of these signals as they are
driven out of the programmer. Typical circuits use several hundred microfarads of capacitance
on VDD, which helps to dampen noise and ripple. However, this capacitance requires a fairly
strong driver in the programmer to meet the rise rate timings for VDD. Most programmers are
designed to simply program the MCU itself and don’t have strong enough drivers to power the
application circuit. One solution is to use a driver board between the programmer and the application
circuit. The driver board requires a separate power supply that is capable of driving the
VPP and VDD pins with the correct rise rates and should also provide enough current to power
the application circuit. CLOCK and DATA are not buffered on this schematic, but may require
buffering depending upon the application. A sample driver board schematic is shown in
Figure 30-2.
30.3.4 Minimum and Maximum Operating Voltage for VDD
The Microchip programming specification states that the device should be programmed at 5V.
Special considerations must be made if your application circuit operates at 3V only. These considerations
may include totally isolating the MCU during programming. Another consideration is
the device must be verified at the minimum and maximum voltages at which the application circuit
will be operating. For instance, a battery operated system may operate from three 1.5V cells
giving an operating voltage range of 2.7V to 4.5V. The programmer must program the device at
5V and must verify the program memory contents at both 2.7V and 4.5V to ensure that proper
programming margins have been achieved. This ensures the PICmicro MCU operation over the
voltage range of the system.
30.3.5 PICmicro Oscillator
The final consideration deals with the oscillator circuit on the application board. The voltage on
MCLR/VPP must rise to the specified program mode entry voltage before the device executes
any code. The crystal modes available on the device are not affected by this, because the Oscillator
Start-up Timer waits for 1024 oscillations before any code is executed. However, RC or EC
oscillators do not require any start-up time; therefore, the Oscillator Start-up Timer is not used.
The programmer must drive MCLR/VPP to the program mode entry voltage before the RC or EC
oscillator toggles four times. If the RC or EC oscillator toggles four or more times, the program
counter will be incremented to some value X. When the device enters programming mode, the
program counter will not be zero and the programmer will start programming your code at an offset
of X. There are several alternatives that can compensate for a slow rise rate on MCLR/VPP.
The first method is to not populate the resistor (R1) in Figure 30-1, program the device, and then
insert the resistor (R1). The other method is to have the programming interface drive the OSC1
pin of the PICmicro MCU to ground while programming. This will prevent any oscillations from
occurring during programming.
Connecting the application circuit to the programmer is dependent on the programming environment.
Refer to Section 30.5 "Programming Environment" for more details.
Note: The driver board design MUST be tested in the user's application to determine the
effects of the application circuit on the programming signals timing. Changes may
be required if the application places a significant load on the VDD, VPP, CLOCK or
DATA pins.
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39531A-page 30-6 2000 Microchip Technology Inc.
30.4 Programmer
PIC18CXXX MCUs only use serial programming and, therefore, all programmers supporting
these devices will support ICSP. One area of consideration with the programmer is the drive
capability. As discussed before, it must be able to provide the specified rise rates on the ICSP
signals and also provide enough current to power the application circuit. Figure 30-2 shows an
example driver board. This driver schematic does not show any buffer circuitry for CLOCK and
DATA. It is recommended that an evaluation be performed to determine if buffering is required.
Another consideration with the programmer is what VDD levels are used to verify the memory
contents of the device. For instance, the PRO MATE II verifies program memory at the minimum
and maximum VDD levels for the specified device and is, therefore, considered a production quality
programmer. On the other hand, the PICSTART® Plus only verifies at 5V and is for prototyping
use only. The Microchip programming specifications state that the program memory contents
should be verified at both the minimum and maximum VDD levels that the application circuit will
be operating. This implies that the application circuit must be able to handle the varying VDD voltages.
There are also several third party programmers that are available. You should select a programmer
based on the features it has and how it fits into your programming environment. The Microchip
Development Systems Ordering Guide (DS30177) provides detailed information on all our
development tools. The Microchip Third Party Guide (DS00104) provides information on all of
our third party tool developers. Please consult these two references when selecting a programmer.
Many options exist, including serial or parallel PC host connection, stand-alone operation,
and single or gang programmers. Some of the third party developers include Advanced Transdata
Corporation, BP Microsystems, Data I/O, Emulation Technology, and Logical Devices.
30.5 Programming Environment
The programming environment affects the type of programmer used, the programmer cable
length and the application circuit interface. Some programmers are well suited for a manual
assembly line, while others are desirable for an automated assembly line. You may want to
choose a gang programmer to program multiple systems at a time.
The physical distance between the programmer and the application circuit affects the load capacitance
on each of the programming signals. This directly affects the drive strength needed to provide
the correct signal rise rates and current. This programming cable must also be as short as
possible and properly terminated and shielded, or the programming signals may be corrupted by
ringing or noise.
Finally, the application circuit interface to the programmer depends on the size constraints of the
application circuit itself and the assembly line. A simple header can be used to interface the application
circuit to the programmer. This might be more desirable for a manual assembly line where
a technician plugs the programmer cable into the board. A different method uses spring loaded
test pins (commonly referred to as pogo pins). The application circuit has pads on the board for
each of the programming signals, and there is a fixture that has pogo pins in the corresponding
configuration. The application circuit or fixture is moved into position, such that the pogo pins
come into contact with the board. This method might be more suitable for an automated assembly
line.
After taking into consideration the various points with the application circuit, the programmer and
the programming environment, anyone can build a high quality, reliable manufacturing line based
on ICSP.
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39531A-page 30-7
Section 30. ICSP
ICSP
30
30.6 Other Benefits
ICSP provides other benefits, such as calibration and serialization.
If program memory permits, it would be cheaper and more reliable, to store calibration constants
in program memory instead of using an external serial EEPROM. For example, if your system
has a thermistor that can vary from one system to another, storing some calibration information
in a table format allows the microcontroller to compensate (in software) for external component
tolerances. System cost can be reduced without affecting the required performance of the system
by using software calibration techniques. But how does this relate to ICSP? The PICmicro
MCU has already been programmed with firmware that performs a calibration cycle. The calibration
data is transferred to a calibration fixture. When all calibration data has been transferred, the
fixture places the PICmicro MCU in programming mode and programs the PICmicro MCU with
the calibration data. Application note AN656, "In-Circuit Serial Programming of Calibration
Parameters Using a PICmicro Microcontroller," shows exactly how to implement this type of calibration
data programming.
The other benefit of ICSP is serialization. Each individual system can be programmed with a
unique or random serial number. One such application of a unique serial number would be for
security systems. A typical system might use DIP switches to set the serial number. Instead, this
number can be burned into program memory, thus reducing the overall system cost and lowering
the risk of tampering.
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39531A-page 30-8 2000 Microchip Technology Inc.
30.7 Field Programming of PICmicro OTP MCUs
An OTP device is not normally capable of being reprogrammed, but the PICmicro architecture
gives you this flexibility, provided the size of your firmware is at least half that of the desired
device, and the device is not code protected. If your target device does not have enough program
memory, Microchip provides a wide spectrum of devices from 0.5K to 16K word program memory
with the same set of peripheral features that will help meet the criteria.
The Enhanced MCU devices have three vectors; RESET and two interrupt vector addresses.
When the PICmicro device encounters a RESET or interrupt condition, the code located at one
of these locations in program memory is executed.
For an example of reprogramming an OTP device, we will use an example from our Mid-Range
family. This technology is applicable to all EPROM based PICmicro devices. The first listing of
Example 30-1 shows the code that is first programmed into the PICmicro device. The second listing
of Example 30-1 shows the code that is programmed into the PICmicro device for the second
time.
Example 30-1 shows that to program the device a second time, the memory location 0x0000
(originally goto Main (0x2808)), is reprogrammed to all 0’s. This happens to be a NOP instruction.
This location cannot be reprogrammed to the new opcode (0x2860), because the bits that
are 0’s cannot be reprogrammed to 1’s. Only bits that are 1’s can be reprogrammed to 0’s. The
next memory location, 0x0001, was originally blank (all 1’s) and now becomes a goto Main
(0x2860). When a RESET condition occurs, the MCU executes the instruction at location
0x0000, which is the NOP (a completely benign instruction), and then executes the goto Main
to start the execution of code. The example also shows that all program memory locations after
0x005A are blank in the original program, so that the second time the PICmicro device is programmed,
the revised code can be programmed at these locations. The same descriptions can
be given for the interrupt vector locations.
Now your one-time programmable Enhanced MCU is exhibiting EEPROM- or FLASH-like
qualities.
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39531A-page 30-9
Section 30. ICSP
ICSP
30
Example 30-1: Programming Cycle Listing Files
First Program Cycle Second Program Cycle
_________________________________________________________________________________________
Prog Opcode Assembly | Prog Opcode Assembly
Mem Instruction | Mem Instruction
-----------------------------------------------------------------------------------------
0000 2808 goto Main ;Main loop | 0000 0000 nop
0001 3FFF ; at 0x0008 | 0001 2860 goto Main; Main now
0002 3FFF | 0002 3FFF ; at 0x0060
0003 3FFF | 0003 3FFF
0004 2848 goto ISR ; ISR at | 0004 0000 nop
0005 3FFF ; 0x0048 | 0005 28A8 goto ISR ; ISR now at
0006 3FFF | 0006 3FFF ; 0x00A8
0007 3FFF | 0007 3FFF
0008 1683 bsf STATUS,RP0 | 0008 1683 bsf STATUS,RP0
0009 3007 movlw 0x07 | 0009 3007 movlw 0x07
000A 009F movwf ADCON1 | 000A 009F movwf ADCON1
. |.
. |.
. |.
0048 1C0C btfss PIR1,RBIF | 0048 1C0C btfss PIR1,RBIF
0049 284E goto EndISR | 0049 284E goto EndISR
004A 1806 btfsc PORTB,0 | 004A 1806 btfsc PORTB,0
. |.
. |.
. |.
0060 3FFF | 0060 1683 bsf STATUS,RP0
0061 3FFF | 0061 3005 movlw 0x05
0062 3FFF | 0062 009F movwf ADCON1
. |.
. |.
. |.
00A8 3FFF | 00A8 1C0C btfss PIR1,RBIF
00A9 3FFF | 00A9 28AE goto EndISR
00AA 3FFF | 00AA 1806 btfsc PORTB,0
. |.
. |.
. |.
-----------------------------------------------------------------------------------------
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39531A-page 30-10 2000 Microchip Technology Inc.
30.8 Field Programming of FLASH PICmicro MCUs
With the ICSP interface circuitry already in place, FLASH-based PICmicro MCUs can be easily
reprogrammed in the field. These FLASH devices allow you to reprogram them even if they are
code protected. A portable ICSP programming station might consist of a laptop computer and
programmer. The technician plugs the ICSP interface cable into the application circuit and downloads
the new firmware into the device. The next thing you know, the system is up and running
without those annoying “bugs.” Another instance would be that you want to add an additional feature
to your system. All of your current inventory can be converted to the new firmware, and field
upgrades can be performed to bring your installed base of systems up to the latest revision of
firmware.
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39531A-page 30-11
Section 30. ICSP
ICSP
30
Figure 30-2: Example Driver Board Schematic C6 0.1 PRB6 PVDD 2 3
1 14
7
U2A
74HC126
5 6
4
U2B
74HC126
R3
1
CLOCK
+8V
PVDD
R6
100
R7
100
3
2 1Q1
2N2907
1 2
3
Q3
2N2222
12
13
14
U1D
TLE2144A
R5
100
C7
0.001 VDD
3
2 1
4
11
U1A
TLE2144A
C3
0.1
+15V
R1
5.1k
R8
100
3
2 1Q2
2N2907
R4
1
PVPP
9 8
10 U2C 74HC126
12 11
13 U2D 74HC126
DATA
CLOCK
PVPP
PVDD
1
2
3
4
5
JP3
HEADER
+15V
R2
5.1k
R9
100 1 2
3
Q4
2N2222
10
9 8
U1C
TLE2144A
R10
100
C8
0.001
DATA
VPP
VPP
VDD
1
2
3
4
5
JP1
HEADER
5
6 7
U1B
TLE2144A
CLOCK
1 +15V 2
JP2
HEADER
C5
0.1
VIN 1
GND
3
VOUT 2
VR1
LM7808
C9
100
+15V
C4
0.1
+8V
Note: All resistors are in Ohms,
all capacitors are in µF.
39500 18C Reference Manual.book Page 11 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39531A-page 30-12 2000 Microchip Technology Inc.
30.9 Design Tips
Question 1: When I try to do ICSP, the entire program is shifted (offset) in the device
program memory.
Answer 1:
If the MCLR pin does not rise fast enough, while the device’s voltage is in the valid operating
range, the internal Program Counter (PC) can increment. This means that the PC is no longer
pointing to the address that you expected. The exact location depends on the number of device
clocks that occurred in the valid operating region of the device.
Question 2: I am using a PRO MATE II with a socket that I designed to bring the programming
signal to my application board. Sometimes when I try to do ICSP,
the program memory is programmed wrong.
Answer 2:
The voltages / timings may be violated at the device. This could be due to the:
• Application board circuitry
• Cable length from programmer to target
• Large capacitance on VDD that affects levels / timings
39500 18C Reference Manual.book Page 12 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39531A-page 30-13
Section 30. ICSP
ICSP
30
30.10 Related Application Notes
This section lists application notes that are related to this section of the manual. These application
notes may not be written specifically for the Enhanced family (that is, they may be written for
the Base-Line, the Mid-Range or High-End families), but the concepts are pertinent, and could
be used (with modification and possible limitations). The current application notes related to
In-Circuit Serial Programming are:
Title Application Note #
In-Circuit Serial Programming of Calibration Parameters using a
PICmicro® Microcontroller AN656
In-Circuit Serial Programming Guide DS30277
Note: Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
http://www.microchip.com/10/faqs/codeex/
39500 18C Reference Manual.book Page 13 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39531A-page 30-14 2000 Microchip Technology Inc.
30.11 Revision History
Revision A
This is the initial released revision of the Enhanced MCU In-Circuit Serial Programming module
description.
39500 18C Reference Manual.book Page 14 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-1
Instruction Set
31
Section 31. Instruction Set
HIGHLIGHTS
This section of the manual contains the following major topics:
31.1 Introduction .................................................................................................................. 31-2
31.2 Data Memory Map ....................................................................................................... 31-3
31.3 Instruction Formats ...................................................................................................... 31-9
31.4 Special Function Registers as Source/Destination .................................................... 31-12
31.5 Fast Register Stack.................................................................................................... 31-13
31.6 Q Cycle Activity.......................................................................................................... 31-13
31.7 Instruction Descriptions ............................................................................................. 31-14
31.8 Design Tips .............................................................................................................. 31-136
31.9 Related Application Notes........................................................................................ 31-137
31.10 Revision History ....................................................................................................... 31-138
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-2 2000 Microchip Technology Inc.
31.1 Introduction
The PIC18CXXX instruction set adds many enhancements to the previous PICmicro instruction
sets, while maintaining an easy migration from these PICmicro instruction sets. Most instructions
are a single program memory word (16-bits), but to address customer requests, some new
instructions have been added that require two program memory locations. The Instruction Set
Summary, shown in Table 31-1, lists the instructions recognized by the Microchip assembler
(MPASM). Table 31-2 gives the instruction description conventions.
Each instruction is divided into an OPCODE that specifies the instruction type and one or more
operands which further specify the operation of the instruction.
The instruction set is highly orthogonal and is grouped into four basic categories:
• Byte-oriented operations
• Bit-oriented operations
• Literal operations
• Control operations
Most byte-oriented instructions have three operands:
1. The File Register (specified by the value of ’f’)
2. The destination of the result (specified by the value of ’d’)
3. The accessed memory (specified by the value of ’a’)
'f' represents a File Register Designator and 'd' represents a Destination Designator. The File
Register Designator specifies which File Register is to be used by the instruction. The access
indicator ’a’ specifies if the BSR selects the bank or if the access bank is used.
The destination designator specifies where the result of the operation is to be placed. If 'd' is zero,
the result is placed in the WREG Register. If 'd' is one, the result is placed in the File Register
specified in the instruction.
All bit-oriented instructions have three operands:
1. The File Register (specified by the value of ’f’)
2. The bit in the File Register (specified by the value of ’b’)
3. The accessed memory (specified by the value of ’a’)
'b' represents a bit field designator that selects the number of the bit affected by the operation,
while 'f' represents the number of the file in which the bit is located. The access indicator ’a’ specifies
if the BSR selects the bank or if the access bank is used.
The literal instructions may use some of the following operands:
• A literal value to be loaded into a File Register (specified by the value of ’k’)
• The desired FSR Register to load the literal value into (specified by the value of ’f’)
• No operand required (specified by the value of ’—’)
The control instructions may use some of the following operands:
• A program memory address (specified by the value of ’n’)
• The mode of the CALL or RETURN instructions (specified by the value of ’s’)
• The mode of the Table Read and Table Write instructions (specified by the value of
’m’)
• No operand required (specified by the value of ’—’)
All instructions are a single word except for three double word instructions. These three instructions
were made double word instructions so that all the required information is available in these
32 bits. In the second word, the 4-MSb’s, are ’1’s. If this second word is executed as an instruction
(by itself), it will execute as a NOP.
All single word instructions are executed in a single instruction cycle, unless a conditional test is
true or the program counter is changed as a result of the instruction. In these cases, the execution
takes two instruction cycles with the additional instruction cycle(s) executed as a NOP.
The double word instructions (that do not modify the PC) execute in two instruction cycles.
One instruction cycle consists of four oscillator periods. Thus, for an oscillator frequency of
4 MHz, the normal instruction execution time is 1 µs. If a conditional test is true or the program
counter is changed as a result of an instruction, the instruction execution time is 2 µs. Two word
branch instructions (if true) would take 3 µs.
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-3
Section 31. Instruction Set
Instruction Set
31
31.2 Data Memory Map
The Data Memory Map has 16 banks of 256 bytes. The Instruction Set and architecture allows
operations across all banks (such as MOVFF). A Segment of Bank 0 and a segment of Bank 15
comprise the access bank. See Section 31.2.1 for description of the access bank.
Figure 31-1: The Data Memory Map and the Access Bank
31.2.1 Access Bank
The access bank is an architectural enhancement that is very useful for C compiler code
optimization. The techniques used by the C compiler may also be useful for programs written in
assembly.
This data memory region can be used for
• Intermediate computational values
• Local variables of subroutine
• Faster context saving/switching of variables
• Common variables
• Faster evaluation/control of SFRs (no banking)
The access bank is comprised of 2 segments: Segment 0 and Segment 1. Segment 0 is the RAM
that is mapped in Bank 0. Segment 1 is the SFRs that are mapped in Bank 15. Each Segment
can be of different sizes. The sum of RAM mapped by Segment 0 and Segment 1 is 256 bytes.
When forced in the access bank (a = ’0’), the last address in Segment 0 is followed by the first
address in Segment 1. Segment 1 maps the Special Function Registers so that these registers
can be accessed without any software overhead. This is useful for testing status flags and modifying
control bits.
Bank 0
Bank 1
Bank 14
Bank 15
BSR<3:0> Data Memory Map
= 0000b
= 0001b
= 1110b
= 1111b
00h
FFh
00h
FFh
Access Bank
When the instructions ’a’ bit = 0,
The BSR is ignored and this Access Bank is
used.
The Segment 0 General Purpose RAM is from
Bank 0.
The Segment 1 Special Function Registers is
from Bank 15.
When a = 1,
the BSR is used to specify the RAM
location that the instruction uses.
Bank n Segment 0
Segment 1
Segment 1
Segment 0
Device Dependent
Segment Boundary
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-4 2000 Microchip Technology Inc.
Example 31-1 shows how registers are affected depending on the value of the access bit. Register
MYREG has an 8-bit address. This address specifies the location in the specified bank to
perform the operation. The specified bank is either the bank specified by the Bank Select Register
(BSR) (when a = 1), or the access bank (when a = 0).
Example 31-1:Operation of Destination and Access Bits
;
; The following symbols are defined in the Microchip supplied
; device header file:
;
; For destination bit:
; F = 1 ; Result is placed in File Register
; W = 0 ; Result is placed in WREG Register
;
; For access bit:
; B = 1 ; Register used specified by BSR Bank Register
; A = 0 ; Register used is in Access Bank
;
; MYREG is a register with an 8-bit address value between 0h and FFh.
; For this example we will assign MYREG to bank 5, though it could
; be in any (or all) banks.
;
MOVLB 5 ; BSR points to RAM bank 5
;
; Contents of
; Addr(MYREG) in
; MYREG access bank WREG
; Starting Value 0x7F 0x5A x
;
DECF MYREG, F, B ; 0x7E --- ---
DECF MYREG, F, A ; --- 0x59 ---
;
DECF MYREG, W, B ; --- --- 0x7D
DECF MYREG, W, A ; --- --- 0x58
Note: If the register is specified with the full 12-bit address, the assembler will automatically
force the access bit to a ’0’ (when the address is in the access RAM area) or a
’1’ (for all other addresses).
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-5
Section 31. Instruction Set
Instruction Set
31
The common assembler usage should be that all RAM and SFR addresses are 12-bit. This
means that the assembler can determine from the address of the register, whether the access
bit needs to be set or cleared. Example 31-2 shows this, as well as forcing the use of the access
bank.
Example 31-2:Code
;
; The following symbols are defined in the Microchip supplied
; device header file:
;
; For destination bit:
; F = 1 ; Result is placed in File Register
; W = 0 ; Result is placed in WREG Register
;
; For access bit:
; B = 1 ; Register used specified by BSR Bank Register
; A = 0 ; Register used is in Access Bank
;
; Register Name Address
; Loop_CNTR 0x000
; MYREG 0x524
; SFR1 0xA9F
;
MOVLB 5 ; BSR points to RAM bank 5
; Addr 24
; a-bit MYREG Loop_CNTR SFR1 WREG Bank0
; Starting Value --- 0x7F 0x7F 0x7F x 0xA9
;
DECF Loop_CNTR, F ; 0 --- 0x7E --- --- ---
DECF MYREG, F ; 1 0x7E --- --- --- ---
DECF SFR1, F ; 0 --- --- 0x7E --- ---
;
;
DECF Loop_CNTR, W ; 0 --- --- --- 0x7D ---
DECF MYREG, W ; 1 --- --- --- 0x7D ---
DECF SFR1, W ; 0 --- --- --- 0x7D ---
INCF MYREG, F, A ; 0 --- --- --- --- 0xAA
INCF MYREG, W, A ; 0 --- --- --- 0x7F ---
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-6 2000 Microchip Technology Inc.
Table 31-1: PIC18CXXX Instruction Set Summary
Mnemonic,
Operands Description Cycles
16-Bit Instruction Word Status
Affected Notes
MSb LSb
BYTE-ORIENTED FILE REGISTER OPERATIONS
ADDWF
ADDWFC
ANDWF
CLRF
COMF
CPFSEQ
CPFSGT
CPFSLT
DECF
DECFSZ
DCFSNZ
INCF
INCFSZ
INFSNZ
IORWF
MOVF
MOVFF
MOVWF
MULWF
NEGF
RLCF
RLNCF
RRCF
RRNCF
SETF
SUBFWB
SUBWF
SUBWFB
SWAPF
TSTFSZ
XORWF
f, d, a
f, d, a
f, d, a
f, a
f, d, a
f, a
f, a
f, a
f, d, a
f, d, a
f, d, a
f, d, a
f, d, a
f, d, a
f, d, a
f, d, a
fs, fd
f, a
f, a
f, a
f, d, a
f, d, a
f, d, a
f, d, a
f, a
f, d, a
f, d, a
f, d, a
f, d, a
f, a
f, d, a
Add WREG and f
Add WREG and Carry bit to f
AND WREG with f
Clear f
Complement f
Compare f with WREG, skip =
Compare f with WREG, skip >
Compare f with WREG, skip <
Decrement f
Decrement f, Skip if 0
Decrement f, Skip if Not 0
Increment f
Increment f, Skip if 0
Increment f, Skip if Not 0
Inclusive OR WREG with f
Move f
Move fs (source) to 1st word
fd (destination) 2nd word
Move WREG to f
Multiply WREG with f
Negate f
Rotate Left f through Carry
Rotate Left f (No Carry)
Rotate Right f through Carry
Rotate Right f (No Carry)
Set f
Subtract f from WREG with
borrow
Subtract WREG from f
Subtract WREG from f with
borrow
Swap nibbles in f
Test f, skip if 0
Exclusive OR WREG with f
1
1
1
1
1
1 (2 or 3)
1 (2 or 3)
1 (2 or 3)
1
1 (2 or 3)
1 (2 or 3)
1
1 (2 or 3)
1 (2 or 3)
1
1
2
1
1
1
1
1
1
1
1
1
1
1
1
1 (2 or 3)
1
0010
0010
0001
0110
0001
0110
0110
0110
0000
0010
0100
0010
0011
0100
0001
0101
1100
1111
0110
0000
0110
0011
0100
0011
0100
0110
0101
0101
0101
0011
0110
0001
01da
00da
01da
101a
11da
001a
010a
000a
01da
11da
11da
10da
11da
10da
00da
00da
ffff
ffff
111a
001a
110a
01da
01da
00da
00da
100a
01da
11da
10da
10da
011a
10da
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
C, DC, Z, OV, N
C, DC, Z, OV, N
Z, N
Z
Z, N
None
None
None
C, DC, Z, OV, N
None
None
C, DC, Z, OV, N
None
None
Z, N
Z, N
None
None
None
C, DC, Z, OV, N
C, Z, N
Z, N
C, Z, N
Z, N
None
C, DC, Z, OV, N
C, DC, Z, OV, N
C, DC, Z, OV, N
None
None
Z, N
1, 2, 3
1, 2, 3
1,2, 3
2, 3
1, 2, 3
4
4
2
1, 2, 3, 4
1, 2, 3, 4
1, 2
1, 2, 3, 4
1, 2, 4
1, 2
1, 2
1, 2
2
2
1, 2
1, 2
1, 2
1, 2
1, 2
2
1, 2
1, 2
1, 2
1, 2, 4
2
BIT-ORIENTED FILE REGISTER OPERATIONS
BCF
BSF
BTFSC
BTFSS
BTG
f, b, a
f, b, a
f, b, a
f, b, a
f, d, a
Bit Clear f
Bit Set f
Bit Test f, Skip if Clear
Bit Test f, Skip if Set
Bit Toggle f
1
1
1 (2 or 3)
1 (2 or 3)
1
1001
1000
1011
1010
0111
bbba
bbba
bbba
bbba
bbba
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
None
None
None
None
None
1, 2
1, 2
3, 4
3, 4
1, 2
Note 1: When a PORT Register is modified as a function of itself (e.g., MOVF PORTB, 1, 0), the value used will be
that value present on the pins themselves. For example, if the data latch is '1' for a pin configured as input and
is driven low by an external device, the data will be written back with a '0'.
2: If this instruction is executed on the TMR0 Register (and, where applicable, d = 1), the prescaler will be cleared
if assigned.
3: If Program Counter (PC) is modified or a conditional test is true, the instruction requires two cycles. The second
cycle is executed as a NOP.
4: Some instructions are 2 word instructions. The second word of these instructions will be executed as a NOP,
unless the first word of the instruction retrieves the information embedded in these 16-bits. This ensures that all
program memory locations have a valid instruction.
5: If the table write starts the write cycle to internal program memory, the write continues until terminated.
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-7
Section 31. Instruction Set
Instruction Set
31
CONTROL OPERATIONS
BC
BN
BNC
BNN
BNOV
BNZ
BOV
BRA
BZ
CALL
CLRWDT
DAW
GOTO
NOP
NOP
POP
PUSH
RCALL
RESET
RETFIE
RETLW
RETURN
SLEEP
n
n
n
n
n
n
n
n
n
n, s
—
—
n
—
—
—
—
n
s
k
s
—
Branch if Carry
Branch if Negative
Branch if Not Carry
Branch if Not Negative
Branch if Not Overflow
Branch if Not Zero
Branch if Overflow
Branch Unconditionally
Branch if Zero
Call subroutine 1st word
2nd word
Clear Watchdog Timer
Decimal Adjust WREG
Go to address 1st word
2nd word
No Operation
No Operation
Pop top of return stack (TOS)
Push top of return stack (TOS)
Relative Call
Software device RESET
Return from interrupt enable
Return with literal in WREG
Return from Subroutine
Go into standby mode
1 (2)
1 (2)
1 (2)
1 (2)
1 (2)
1 (2)
1 (2)
2
1 (2)
2
1
1
2
1
1
1
1
2
1
2
2
2
1
1110
1110
1110
1110
1110
1110
1110
1101
1110
1110
1111
0000
0000
1110
1111
0000
1111
0000
0000
1101
0000
0000
0000
0000
0000
0010
0110
0011
0111
0101
0001
0100
0nnn
0000
110s
kkkk
0000
0000
1111
kkkk
0000
xxxx
0000
0000
1nnn
0000
0000
1100
0000
0000
nnnn
nnnn
nnnn
nnnn
nnnn
nnnn
nnnn
nnnn
nnnn
kkkk
kkkk
0000
0000
kkkk
kkkk
0000
xxxx
0000
0000
nnnn
1111
0001
kkkk
0001
0000
nnnn
nnnn
nnnn
nnnn
nnnn
nnnn
nnnn
nnnn
nnnn
kkkk
kkkk
0100
0111
kkkk
kkkk
0000
xxxx
0110
0101
nnnn
1111
000s
kkkk
001s
0011
None
None
None
None
None
None
None
None
None
None
TO, PD
C
None
None
None
None
None
None
All
GIE/GIEH,
PEIE/GIEL
None
None
TO, PD
4
Table 31-1: PIC18CXXX Instruction Set Summary (Continued)
Mnemonic,
Operands Description Cycles
16-Bit Instruction Word Status
Affected Notes
MSb LSb
Note 1: When a PORT Register is modified as a function of itself (e.g., MOVF PORTB, 1, 0), the value used will be
that value present on the pins themselves. For example, if the data latch is '1' for a pin configured as input and
is driven low by an external device, the data will be written back with a '0'.
2: If this instruction is executed on the TMR0 Register (and, where applicable, d = 1), the prescaler will be cleared
if assigned.
3: If Program Counter (PC) is modified or a conditional test is true, the instruction requires two cycles. The second
cycle is executed as a NOP.
4: Some instructions are 2 word instructions. The second word of these instructions will be executed as a NOP,
unless the first word of the instruction retrieves the information embedded in these 16-bits. This ensures that all
program memory locations have a valid instruction.
5: If the table write starts the write cycle to internal program memory, the write continues until terminated.
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-8 2000 Microchip Technology Inc.
LITERAL OPERATIONS
ADDLW
ANDLW
IORLW
LFSR
MOVLB
MOVLW
MULLW
RETLW
SUBLW
XORLW
k
k
k
f, k
k
k
k
k
k
k
Add literal and WREG
AND literal with WREG
Inclusive OR literal with WREG
Move literal (12-bit) 1st word
to FSRx 2nd word
Move literal to BSR<3:0>
Move literal to WREG
Multiply literal with WREG
Return with literal in WREG
Subtract WREG from literal
Exclusive OR literal with WREG
1
1
1
2
1
1
1
2
1
1
0000
0000
0000
1110
1111
0000
0000
0000
0000
0000
0000
1111
1011
1001
1110
0000
0001
1110
1101
1100
1000
1010
kkkk
kkkk
kkkk
00ff
kkkk
0000
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
C, DC, Z, OV, N
Z, N
Z, N
None
None
None
None
None
C, DC, Z, OV, N
Z, N
DATA MEMORY ↔ PROGRAM MEMORY OPERATIONS
TBLRD*
TBLRD*+
TBLRD*-
TBLRD+*
TBLWT*
TBLWT*+
TBLWT*-
TBLWT+*
Table Read
Table Read with post-increment
Table Read with post-decrement
Table Read with pre-increment
Table Write
Table Write with post-increment
Table Write with post-decrement
Table Write with pre-increment
2
2
2
2
2 (5)
2 (5)
2 (5)
2 (5)
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
1000
1001
1010
1011
1100
1101
1110
1111
None
None
None
None
None
None
None
None
Table 31-1: PIC18CXXX Instruction Set Summary (Continued)
Mnemonic,
Operands Description Cycles
16-Bit Instruction Word Status
Affected Notes
MSb LSb
Note 1: When a PORT Register is modified as a function of itself (e.g., MOVF PORTB, 1, 0), the value used will be
that value present on the pins themselves. For example, if the data latch is '1' for a pin configured as input and
is driven low by an external device, the data will be written back with a '0'.
2: If this instruction is executed on the TMR0 Register (and, where applicable, d = 1), the prescaler will be cleared
if assigned.
3: If Program Counter (PC) is modified or a conditional test is true, the instruction requires two cycles. The second
cycle is executed as a NOP.
4: Some instructions are 2 word instructions. The second word of these instructions will be executed as a NOP,
unless the first word of the instruction retrieves the information embedded in these 16-bits. This ensures that all
program memory locations have a valid instruction.
5: If the table write starts the write cycle to internal program memory, the write continues until terminated.
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-9
Section 31. Instruction Set
Instruction Set
31
31.3 Instruction Formats
Figure 31-2 shows the three general formats that the instructions can have. As can be seen from
the general format of the instructions, the opcode portion of the instruction word varies from 3-bits
to 6-bits of information. This is what allows the Enhanced Instruction Set to have 75 instructions.
All instruction examples use the following format to represent a hexadecimal number:
0xhh
where h signifies a hexadecimal digit.
To represent a binary number:
00000100b
where b is a binary string identifier.
Figure 31-2: General Format for Instructions
Note: Any unused opcode is Reserved. Use of any reserved opcode may cause unexpected
operation.
Byte-oriented File Register operations
15 10 9 8 7 0
d = 0 for result destination to be WREG Register
OPCODE d a f (FILE #)
d = 1 for result destination to be File Register (f)
a = 0 to force Access Bank
Bit-oriented File Register operations
15 12 11 9 8 7 0
OPCODE b (BIT #) a f (FILE #)
b = 3-bit position of bit in File Register (f)
Literal operations
15 8 7 0
OPCODE k (literal)
k = 8-bit immediate value
Byte to Byte move operations (2-word)
15 12 11 0
OPCODE f (Source FILE #)
CALL, GOTO, and Branch operations
15 8 7 0
OPCODE n<7:0> (literal)
n = 20-bit immediate value
a = 1 for BSR to select bank
f = 8-bit File Register address
a = 0 to force Access Bank
a = 1 for BSR to select bank
f = 8-bit File Register address
15 12 11 0
1111 n<19:8> (literal)
15 12 11 0
1111 f (Destination FILE #)
f = 12-bit File Register address
Control operations
Example Instruction
ADDWF MYREG, W, B
MOVFF MYREG1, MYREG2
BSF MYREG, bit, B
MOVLW 0x7F
GOTO label
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-10 2000 Microchip Technology Inc.
Table 31-2: Instruction Description Conventions
Field Description
a RAM access bit
a = 0: RAM location in access bank (BSR Register is ignored)
a = 1: RAM bank is specified by BSR Register
bbb Bit address within an 8-bit File Register (0 to 7)
BSR Bank Select Register. Used to select the current RAM bank.
d Destination select bit;
d = 0: store result in WREG,
d = 1: store result in File Register f.
dest Destination either the WREG Register or the specified register file location
f 8-bit Register file address (0x00 to 0xFF)
fs 12-bit Register file address (0x000 to 0xFFF). This is the source address.
fd 12-bit Register file address (0x000 to 0xFFF). This is the destination address.
k Literal field, constant data or label (may be either an 8-bit, 12-bit or a 20-bit value)
label Label name
mm The mode of the TBLPTR Register for the Table Read and Table Write instructions
Only used with Table Read and Table Write instructions:
* No Change to Register (such as TBLPTR with Table reads and writes)
*+ Post-Increment Register (such as TBLPTR with Table reads and writes)
*- Post-Decrement Register (such as TBLPTR with Table reads and writes)
+* Pre-Increment Register (such as TBLPTR with Table reads and writes)
n The relative address (2’s complement number) for relative branch instructions, or
the direct address for Call/Branch and Return instructions
PRODH Product of Multiply high byte
PRODL Product of Multiply low byte
s Fast Call / Return mode select bit.
s = 0: do not update into/from Shadow Registers
s = 1: certain registers loaded into/from Shadow Registers
u Unused or Unchanged
WREG Working Register (accumulator)
x Don't care (0 or 1)
The assembler will generate code with x = 0. It is the recommended form of use for
compatibility with all Microchip software tools.
TBLPTR 21-bit Table Pointer (points to a Program Memory location)
TABLAT 8-bit Table Latch
TOS Top of Stack
INDF Any one of the indirect addressing registers, such as INDF0, INDF1, or INDF2
FSR Any one of the file select register pairs, such as FSR0H:FSR0L, FSR1H:FSR1L, or
FSR2H:FSR2L
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-11
Section 31. Instruction Set
Instruction Set
31
Table 31-3: Indirect Addressing Symbols
PC Program Counter
PCL Program Counter Low Byte
PCH Program Counter High Byte
PCLATH Program Counter High Byte Latch
PCLATU Program Counter Upper Byte Latch
GIE Global Interrupt Enable bit
WDT Watchdog Timer
TO Time-out bit
PD Power-down bit
C,DC,
Z,OV,N
ALU status bits Carry, Digit Carry, Zero, Overflow, Negative
[ ] Optional
( ) Contents of
→ Assigned to
< > Register bit field
∈ In the set of
italics User defined term (font is courier)
Field Description
*FSRn Selects INDFn Register
*FSRn++ Selects POSTINCn Register
*FSRn-- Selects POSTDECn Register
*(++FSRn) Selects PREINCn Register
*(FSRn+W) Selects PLUSWn Register
Table 31-2: Instruction Description Conventions (Continued)
Field Description
39500 18C Reference Manual.book Page 11 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-12 2000 Microchip Technology Inc.
31.4 Special Function Registers as Source/Destination
The Section 31. Instruction Set’s Orthogonal Instruction Set allows read and write of all File Registers,
including Special Function Registers. The user should be aware of some special situations
which are explained in the following subsections.
31.4.1 STATUS Register as Destination
If an instruction writes to the STATUS Register, the Z, C, DC, OV, and N bits may be set or cleared
as a result of the instruction and overwrite the original data bits. For example, executing CLRF
STATUS will clear Register STATUS, and then set the Z bit leaving 0000 0100b in the register.
31.4.2 Bit Manipulation
All bit manipulation instructions will first read the entire register, operate on the selected bit and
then write the result back to (read-modify-write (R-M-W)) the specified register. The user should
keep this in mind when operating on some Special Function Registers, such as the Port Pin Register.
31.4.3 PCL as Source or Destination
Read, write or read-modify-write (R-M-W) on PCL may have the following results:
Read PCL: PCL → destination ; Reading PCL causes the following
PCH → PCLATH
PCU → PCLATU
Write PCL: 8-bit destination value → PCL ; Writing PCL causes the following
PCLATH → PCH
PCLATU → PCU
Read-Modify-Write: PCL→ ALU operand ; R-M-W of PCL causes the following
PCH → PCLATH
PCU → PCLATU
; PCL data is modified
8-bit result → PCL ; result is written back to PCL
PCLATH → PCH
PCLATU → PCU
Where PCH = program counter high byte (not an addressable register),
PCLATH = Program counter high holding latch,
PCU = program counter upper byte (not an addressable register),
PCLATU = Program counter upper holding latch,
destination = Register file ’f’.
Note: Status bits that are manipulated by the device (including the interrupt flag bits) are
set or cleared in the Q1 cycle, so there is no issue with executing R-M-W instructions
on registers that contain these bits.
39500 18C Reference Manual.book Page 12 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-13
Section 31. Instruction Set
Instruction Set
31
31.5 Fast Register Stack
At times it is desirable to be able to quickly access and return from a function. This function may
be called as a subroutine, or an interrupt routine of the device. To reduce the overhead for
accessing/returning from these functions, the architecture has the ability to save three key registers
in a one deep Register Stack. These registers are:
• WREG Register
• BSR (Bank Select Register) Register
• STATUS Register
The two events that cause these registers to be loaded onto the Fast Register Stack are:
• A fast call (CALL K, fast)(where the fast bit is set (’1’))
• Any interrupt occurs
These Fast Stack Registers are not accessible for reading or writing. When doing the return from
these subroutine, the values can be restored into their registers executing the fast return:
• RETFIE fast (where the fast bit is set (’1’))
• RETURN fast (where the fast bit is set (’1’))
When s (fast) = ’0’, the Fast Register Stack is not used, when s (fast) = ’1’, the Fast Register
Stack is used.
31.6 Q Cycle Activity
Each instruction cycle (Tcy) is comprised of four Q clocks (also called Q cycles). These are
referred to as Q1, Q2, Q3, or Q4. The Q cycles provide the timing/designation for the Decode,
Read, Process Data, Write etc., of each instruction cycle. The Figure 31-3 shows the relationship
of the Q cycles to the instruction cycle.
The four Q cycles that make up an instruction cycle (Tcy) can be generalized as:
Q1: Instruction Decode Cycle or forced No Operation
Q2: Instruction Read Cycle or No Operation
Q3: Process the Data
Q4: Instruction Write Cycle or No Operation
Some actions occur on the edge between the end of one Q cycle and the start of the next Q cycle.
An example would be a Q2-Q3 action. This action occurs on the clock edge between the end of
Q2 cycle and the beginning of the Q3 cycle.
The clock source for the Q cycle is normally the device oscillator clock (TOSC). But the clock
source is software selectable. So the Q cycle may be independent of the device oscillator cycle
(TOSC).
In the full description of each instruction, the detailed Q cycle operation for the instruction will be
shown.
Figure 31-3: Q Cycle Activity
Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4
Tcy1 Tcy2 Tcy3
TOSC
39500 18C Reference Manual.book Page 13 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-14 2000 Microchip Technology Inc.
31.7 Instruction Descriptions
ADDLW Add Literal to WREG
Syntax: [ label ] ADDLW k
Operands: 0 ≤ k ≤ 255
Operation: (WREG) + k → WREG
Status Affected: C, DC, Z, OV, N
Encoding: 0000 1111 kkkk kkkk
Description: The eight bit literal ’k’ is added to the contents of the WREG and the result
is placed in the WREG.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
literal 'k'
Process
data
Write to
WREG
Register
Example1 ADDLW 0x19 ; Add 19h to value in WREG
Before Instruction
WREG = 0x18
C, DC, Z, OV, N = x
After Instruction
WREG = 0x31
C =0
DC = 1
Z =0
OV = 0
N =0
Example 2 ADDLW MYREG ; Add the value of the
; address for MYREG Register
; to WREG
Before Instruction
WREG = 0x60
Address of MYREG † = 0x37
† MYREG is a symbol for a data memory location
C, DC, Z, OV, N = x
After Instruction
WREG = 0x97
C =0
DC = 0
Z =0
OV = 1
N =1
39500 18C Reference Manual.book Page 14 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-15
Section 31. Instruction Set
Instruction Set
31
Example 3 ADDLW HIGH (LU_TABLE) ; Add high byte of address
; LU_TABLE to WREG
Before Instruction
WREG = 0x10
Address of LU_TABLE † = 0x9375
† LU_TABLE is a label for an address in program memory
C, DC, Z, OV, N = x
After Instruction
WREG = 0xA3
C =0
DC = 0
Z =0
OV = 0
N =1
Example 4 ADDLW PCL ; Add value of the address
; of Program Counter Low
; byte (PCL) to WREG
Before Instruction
WREG = 0x02
Address of PCL † = 0xFF8 (only low 8-bits are used)
† PCL is the symbol for the Program Counter low byte location
C, DC, Z, OV, N = x
After Instruction
WREG = 0xFA
C =0
DC = 0
Z =0
OV = 0
N =0
Example 5 ADDLW Offset ; Add the value of symbol
; Offset to WREG
Before Instruction
WREG = 0x10
Offset = 0x02
C, DC, Z, OV, N = x
After Instruction
WREG = 0x12
Offset = 0x02
C =0
DC = 0
Z =0
OV = 0
N =0
39500 18C Reference Manual.book Page 15 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-16 2000 Microchip Technology Inc.
ADDWF Add WREG and f
Syntax: [ label ] ADDWF f, d, a
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (WREG) + (f) → destination
Status Affected: C, DC, Z, OV, N
Encoding: 0010 01da ffff ffff
Description: Add the contents of the WREG Register to the contents of Register 'f'.
The ’d’ bit selects the destination for the operation.
If 'd' is 1; the result is stored back in the File Register 'f'.
If 'd' is 0; the result is stored in the WREG Register.
The ’a’ bit selects which bank is accessed for the operation.
If ’a’ is 1; the bank specified by the BSR Register is used.
If ’a’ is 0; the access bank is used.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
Register 'f'
Process
data
Write to
destination
Example 1 ADDWF FSR0L, 1, 1 ; Add value in WREG to
; value in the
; FSR0H:FSR0L Register
Case 1: Before Instruction
WREG = 0x17
FSR0H:FSR0L = 0x2C2
C, DC, Z, OV, N = x
After Instruction
WREG = 0x17
FSR0H:FSR0L = 0x2D9
C =0
DC = 0
Z =0
OV = 0
N =1
Case 2: Before Instruction
WREG = 0x17
FSR0H:FSR0L = 0x2FF
C, DC, Z, OV, N = x
After Instruction
WREG = 0x17
FSR0H:FSR0L = 0x316
C =0
DC = 0
Z =0
OV = 0
N =0
39500 18C Reference Manual.book Page 16 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-17
Section 31. Instruction Set
Instruction Set
31
Example 2 ADDWF INDF0, 1, 1 ; Add value in WREG to
; value in the register
; pointed to (addressed)
; by the FSR0H:FSR0L
; Register
Before Instruction
WREG = 0x17
FSR0H:FSR0L = 0x6C2
Contents of Address (FSR0) = 0x20
C, DC, Z, OV, N = x
After Instruction
WREG = 0x17
FSR0H:FSR0L = 0x6C2
Contents of Address (FSR0) = 0x37
C =0
DC = 0
Z =0
OV = 0
N =0
Example 3 ADDWF INDF0, 1, 0 ; Add value in WREG to
; value in the register
; pointed to (addressed)
; by the FSR0H:FSR0L
; Register
Before Instruction
WREG = 0x17
FSR0H:FSR0L = 0x0C2
Contents of Address (FSR0) = 0x20
C, DC, Z, OV, N = x
After Instruction
WREG = 0x17
FSR0H:FSR0L = 0x0C2
Contents of Address (FSR0) = 0x37
C =0
DC = 0
Z =0
OV = 0
N =0
39500 18C Reference Manual.book Page 17 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-18 2000 Microchip Technology Inc.
Example 4 ADDWF PCL, 1, 1 ; Add the value in WREG to
; the current value in the
; low byte of the program
; counter (PCL)
Case 1: Before Instruction
WREG = 0x10
PCL = 0x37
C, DC, Z, OV, N = x
After Instruction
WREG = 0x10
PCL = 0x47
C =0
DC = 0
Z =0
OV = 0
N =0
Case 2: Before Instruction
WREG = 0x10
PCL = 0xF7
PCH = 0x08
C, DC, Z, OV, N = x
After Instruction
WREG = 0x10
PCL = 0x07
PCH = 0x08
C =1
DC = 0
Z =0
OV = 0
N =0
39500 18C Reference Manual.book Page 18 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-19
Section 31. Instruction Set
Instruction Set
31
Example 5 ADDWF MYREG, 1 ; Add the value in WREG to
; the current value in
; MYREG
; (assembler determines
; that MYREG requires
; access bit to be set)
Case 1: Before Instruction
BSR = 0x01
WREG = 0x10
MYREG = 0x37
C, DC, Z, OV, N = x
After Instruction
BSR = 0x01
WREG = 0x10
MYREG = 0x47
C =0
DC = 0
Z =0
OV = 0
N =0
; In Bank 1
; In Bank 1
Case 2: Before Instruction
BSR = 0x01
WREG = 0x10
MYREG = 0xF7
C, DC, Z, OV, N = x
After Instruction
BSR = 0x01
WREG = 0x10
MYREG = 0x07
C =1
DC = 0
Z =0
OV = 0
N =0
; In Bank 1
; In Bank 1
39500 18C Reference Manual.book Page 19 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-20 2000 Microchip Technology Inc.
ADDWFC Add WREG and Carry bit to f
Syntax: [ label ] ADDWF f, d, a
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (WREG) + (f) + (C) → destination
Status Affected: C, DC, Z, OV, N
Encoding: 0010 00da ffff ffff
Description: Add the contents of the WREG Register and the Carry bit to the contents of
Register 'f'.
The ’d’ bit selects the destination for the operation.
If 'd' is 1; the result is stored back in the File Register 'f'.
If 'd' is 0; the result is stored in the WREG Register.
The ’a’ bit selects which bank is accessed for the operation.
If ’a’ is 1; the bank specified by the BSR Register is used.
If ’a’ is 0; the access bank is used.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
Register 'f'
Process
data
Write to
destination
Example 1 ADDWFC FSR0L, 0, 1 ; Add WREG, C bit, and FSR0L
; value (Destination WREG)
Case 1: Before Instruction
WREG = 0x17
FSR0H:FSR0L = 0x9C2
C =0
DC, Z, OV, N = x
After Instruction
WREG = 0xD9
FSR0H:FSR0L = 0x9C2
C =0
DC = 0
Z =0
OV = 0
N =1
Case 2: Before Instruction
WREG = 0x17
FSR0H:FSR0L = 0x7C2
C =1
DC, Z, OV, N = x
After Instruction
WREG = 0xDA
FSR0H:FSR0L = 0x7C2
C =0
DC = 0
Z =0
OV = 0
N =1
39500 18C Reference Manual.book Page 20 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-21
Section 31. Instruction Set
Instruction Set
31
Example 2 ADDWFC INDF0, 1, 1 ; Add WREG and the Carry
; bit to the value pointed
; to by the FSR0H:FSR0L
; (Destination: File
; Register)
Before Instruction
WREG = 0x17
FSR0H:FSR0L = 0x0C2
Contents of Address (FSR0H:FSR0L) = 0x20
C =0
DC, Z, OV, N = x
After Instruction
WREG = 0x17
FSR0H:FSR0L = 0x0C2
Contents of Address (FSR0H:FSR0L) = 0x37
C =0
DC = 0
Z =0
OV = 0
N =0
Example 3 ADDWFC PCL, 1, 1 ; Add WREG and the Carry
; bit to the PCL Register
Case 1: Before Instruction
WREG = 0x10
PCL = 0x38
C =0
DC, Z, OV, N = x
After Instruction
WREG = 0x10
PCL = 0x48
C =0
DC = 0
Z =0
OV = 0
N =0
Case 2: Before Instruction
WREG = 0x10
PCL = 0xF8
PCH = 0x08
C =0
DC, Z, OV, N = x
After Instruction
WREG = 0x10
PCL = 0x08
PCH = 0x08
C =1
DC = 0
Z =0
OV = 0
N =0
39500 18C Reference Manual.book Page 21 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-22 2000 Microchip Technology Inc.
ANDLW AND Literal with WREG
Syntax: [ label ] ANDLW k
Operands: 0 ≤ k ≤ 255
Operation: (WREG).AND. (k) → W
Status Affected: Z, N
Encoding: 0000 1011 kkkk kkkk
Description: The contents of WREG Register are AND’d with the eight bit literal 'k'. The
result is placed in the WREG Register.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
literal 'k'
Process
data
Write to
WREG
Register
Example 1 ANDLW 0x5F ; And constant to WREG
Before Instruction
WREG = 0xA3
Z, N = x
After Instruction
WREG = 0x03
Z =0
N =0
; 0101 1111 (0x5F)
; 1010 0011 (0xA3)
;---------- ------
; 0000 0011 (0x03)
Example 2 ANDLW MYREG ; And address of MYREG
; to WREG
Before Instruction
WREG = 0xA3
Address of MYREG † = 0x37
Z, N = x
† MYREG is a symbol for a
data memory location
After Instruction
WREG = 0x23
Z =0
N =0
; 0011 0111 (0x37)
; 1010 0011 (0xA3)
;---------- ------
; 0010 0011 (0x23)
39500 18C Reference Manual.book Page 22 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-23
Section 31. Instruction Set
Instruction Set
31
Example 3 ANDLW HIGH
(LU_TABLE)
; And the high byte of
; address LU_TABLE
; with WREG
Before Instruction
WREG = 0xA3
Address of LU_TABLE †
= 0x9375
Z, N = x
† LU_TABLE is a label for an
address in program memory
After Instruction
WREG = 0x83
Z =0
N =1
; 1010 0011 (0xA3)
; 1001 0011 (0x93)
;---------- ------
; 1000 0011 (0x83)
Example 4 ANDLW LOW (LU_TABLE); And the low byte of
; address LU_TABLE
; with WREG
Before Instruction
WREG = 0xA3
Address of LU_TABLE †
= 0x9375
Z, N = x
† LU_TABLE is a label for an
address in program memory
After Instruction
WREG = 0x21
Z =0
N =0
; 1010 0011 (0xA3)
; 0111 0101 (0x75)
;---------- ------
; 0010 0001 (0x21)
39500 18C Reference Manual.book Page 23 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-24 2000 Microchip Technology Inc.
ANDWF AND WREG with f
Syntax: [ label ] ANDWF f, d, a
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (WREG).AND. (f) → destination
Status Affected: Z, N
Encoding: 0001 01da ffff ffff
Description: The contents of the WREG Register are AND’d with the contents of Register
'f'.
The ’d’ bit selects the destination for the operation.
If 'd' is 1; the result is stored back in the File Register 'f'.
If 'd' is 0; the result is stored in the WREG Register.
The ’a’ bit selects which bank is accessed for the operation.
If ’a’ is 1; the bank specified by the BSR Register is used.
If ’a’ is 0; the access bank is used.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
Register 'f'
Process
data
Write to
destination
Example 1 ANDWF REG1, 1, 1 ; And WREG with REG1
Before Instruction
WREG = 0x17
REG1 = 0xC2
Z, N = x
After Instruction
WREG = 0x17
REG1 = 0x02
Z =0
N =0
; 0001 0111 (0x17)
; 1100 0010 (0xC2)
;---------- ------
; 0000 0010 (0x02)
Example 2 ANDWF REG1, 0, 1 ; And WREG with REG1
; (destination WREG)
Before Instruction
WREG = 0x17
REG1 = 0xC2
Z, N = x
After Instruction
WREG = 0x02
REG1 = 0xC2
Z =0
N =0
; 0001 0111 (0x17)
; 1100 0010 (0xC2)
;---------- ------
; 0000 0010 (0x02)
39500 18C Reference Manual.book Page 24 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-25
Section 31. Instruction Set
Instruction Set
31
Example 3 ANDWF INDF0, 1, 1 ; And WREG with value pointed
; by FSR0H:FSR0L (FSR0)
Case 1: Before Instruction
WREG = 0x17
FSR0H:FSR0L
= 0xFC2
Contents of Address
(FSR0) = 0x5A
Z, N = x
After Instruction
WREG = 0x17
FSR0H:FSR0L
= 0xFC2
Contents of Address
(FSR0) = 0x12
Z =0
N =0
; 0001 0111 (0x17)
; 0101 1010 (0x5A)
;---------- ------
; 0001 0010 (0x12)
Case 2: Before Instruction
WREG = 0x00
FSR0H:FSR0L
= 0x4C2
Contents of Address
(FSR0) = 0x5A
Z, N = x
After Instruction
WREG = 0x00
FSR0H:FSR0L
= 0x4C2
Contents of Address
(FSR0) = 0x00
Z =1
N =0
; 0000 0000 (0x00)
; 0101 1010 (0x5A)
;---------- ------
; 0000 0000 (0x00)
39500 18C Reference Manual.book Page 25 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-26 2000 Microchip Technology Inc.
BC Branch if Carry
Syntax: [ label ] BC n
Operands: -128 ≤ f ≤ 127
Operation: If carry bit is ’1’
(PC + 2) + 2n → PC
Status Affected: None
Encoding: 1110 0010 nnnn nnnn
Description: If the Carry bit is ’1’, then the program will branch.
The 2’s complement number ’2n’ (the offset) is added to the PC. Since the
PC will have incremented to fetch the next instruction, the new address will
be (PC+2)+2n. This instruction is then a two-cycle instruction.
Words: 1
Cycles: 1 (2)
Q Cycle Activity:
If Branch
Q1 Q2 Q3 Q4
Decode Read
literal 'n'
Process
data
Write to
PC
No
operation
No
operation
No
operation
No
operation
If No Branch
Q1 Q2 Q3 Q4
Decode Read
literal 'n'
Process
data
No
operation
Example 1 HERE
NOT_C
C_CODE
BC
•
•
GOTO
•
•
C_CODE
MORE_CODE
;
; If C bit is not set
; execute this code.
;
; else if C bit is set
; this code will execute
Case 1: Before Instruction
PC = address HERE
C =0
After Instruction
PC = address NOT_C
Case 2: Before Instruction
PC = address HERE
C =1
After Instruction
PC = address C_CODE
39500 18C Reference Manual.book Page 26 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-27
Section 31. Instruction Set
Instruction Set
31
Example 2 HERE
NO_C
PLUS0
PLUS1
PLUS2
PLUS3
PLUS4
PLUS5
PLUS6
BC
GOTO
•
•
•
•
•
•
•
$ + OFFSET
PROCESS_CODE
; If carry bit is set,
; branch to HERE+OFFSET
Case 1: Before Instruction
PC = address HERE
C =0
After Instruction
PC = address NO_C
Case 2: Before Instruction
PC = address HERE
C =1
After Instruction
PC = address HERE + OFFSET
Example 3 MIN6
MIN5
MIN4
MIN3
MIN2
MIN1
MIN0
HERE
NO_C
•
•
•
•
•
•
•
BC
GOTO
$ - OFFSET
PROCESS_CODE
; If carry bit is set,
; branch to HERE-OFFSET
Case 1: Before Instruction
PC = address HERE
C =0
After Instruction
PC = address NO_C
Case 2: Before Instruction
PC = address HERE
C =1
After Instruction
PC = address HERE - OFFSET
Note: Assembler will convert the specified address label into the offset to be used.
39500 18C Reference Manual.book Page 27 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-28 2000 Microchip Technology Inc.
BCF Bit Clear f
Syntax: [ label ] BCF f, b, a
Operands: 0 ≤ f ≤ 255
0 ≤ b ≤ 7
a ∈ [0,1]
Operation: 0 → f
Status Affected: None
Encoding: 1001 bbba ffff ffff
Description: Bit 'b' in Register 'f' of the specified bank is cleared.
The ’a’ bit selects which bank is accessed for the operation.
If ’a’ is 1; the bank specified by the BSR Register is used.
If ’a’ is 0; the access bank is used.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
Register 'f'
Process
data
Write
Register 'f'
Example 1 BCF MYREG, 7, 1 ; Clear bit 7 in Register
; MYREG
Before Instruction
MYREG = 0xC7
After Instruction
MYREG = 0x47
; 1100 0111
; 0100 0111
39500 18C Reference Manual.book Page 28 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-29
Section 31. Instruction Set
Instruction Set
31
Example 2 BCF INDF0, 3, 0 ; Clear bit 7 in the register
; pointed to by the FSR0
; (FSR0H:FSR0L) Register
Before Instruction
FSR0 = 0x3C2
Contents of Address
(FSR0) = 0x2F
After Instruction
FSR0 = 0x3C2
Contents of Address
(FSR0) = 0x27
; 0010 1111
; 0010 0111
39500 18C Reference Manual.book Page 29 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-30 2000 Microchip Technology Inc.
BN Branch if Negative
Syntax: [ label ] BN n
Operands: -128 ≤ f ≤ 127
Operation: If negative bit is ’1’
(PC + 2) + 2n → PC
Status Affected: None
Encoding: 1110 0110 nnnn nnnn
Description: If the Negative bit is ’1’, then the program will branch.
The 2’s complement number ’2n’ (the offset) is added to the PC. Since the
PC will have incremented to fetch the next instruction, the new address will
be (PC+2)+2n. This instruction is then a two-cycle instruction.
Words: 1
Cycles: 1 (2)
Q Cycle Activity:
If Branch
Q1 Q2 Q3 Q4
Decode Read
literal 'n'
Process
data
Write to
PC
No
operation
No
operation
No
operation
No
operation
If No Branch
Q1 Q2 Q3 Q4
Decode Read
literal 'n'
Process
data
No
operation
Example 1 HERE
NOT_N
N_CODE
BN
•
•
GOTO
•
•
N_CODE
MORE_CODE
; If N bit is not set
; execute this code.
;
;
; else if N bit is set
; this code will execute
Case 1: Before Instruction
PC = address HERE
N =0
After Instruction
PC = address NOT_N
Case 2: Before Instruction
PC = address HERE
N =1
After Instruction
PC = address N_CODE
39500 18C Reference Manual.book Page 30 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-31
Section 31. Instruction Set
Instruction Set
31
Example 2 HERE
NOT_N
PLUS0
PLUS1
PLUS2
PLUS3
PLUS4
PLUS5
PLUS6
BN
GOTO
•
•
•
•
•
•
•
$ + OFFSET
PROCESS_CODE
; If negative bit is set,
; branch to HERE + OFFSET
Case 1: Before Instruction
PC = address HERE
N =0
After Instruction
PC = address NOT_N
Case 2: Before Instruction
PC = address HERE
N =1
After Instruction
PC = address HERE + OFFSET
Example 3 MIN6
MIN5
MIN4
MIN3
MIN2
MIN1
MIN0
HERE
NO_N
•
•
•
•
•
•
•
BN
GOTO $ - OFFSET
PROCESS_CODE
; If negative bit is set,
; branch to HERE - OFFSET
Case 1: Before Instruction
PC = address HERE
N =0
After Instruction
PC = address NO_N
Case 2: Before Instruction
PC = address HERE
N =1
After Instruction
PC = address HERE - OFFSET
Note: Assembler will convert the specified address label into the offset to be used.
39500 18C Reference Manual.book Page 31 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-32 2000 Microchip Technology Inc.
BNC Branch if Not Carry
Syntax: [ label ] BNC n
Operands: -128 ≤ f ≤ 127
Operation: If carry bit is ’0’
(PC + 2) + 2n → PC
Status Affected: None
Encoding: 1110 0011 nnnn nnnn
Description: If the Carry bit is ’0’, then the program will branch.
The 2’s complement number ’2n’ (the offset) is added to the PC. Since the
PC will have incremented to fetch the next instruction, the new address will
be (PC+2)+2n. This instruction is then a two-cycle instruction.
Words: 1
Cycles: 1 (2)
Q Cycle Activity:
If Branch
Q1 Q2 Q3 Q4
Decode Read
literal 'n'
Process
data
Write to
PC
No
operation
No
operation
No
operation
No
operation
If No Branch
Q1 Q2 Q3 Q4
Decode Read
literal 'n'
Process
data
No
operation
Example 1 HERE
CARRY
NC_CODE
BNC
•
•
GOTO
•
•
NC_CODE
MORE_CODE
; If C bit is set
; execute this code.
;
;
; else if C bit is clear
; this code will execute
Case 1: Before Instruction
PC = address HERE
C =0
After Instruction
PC = address NC_CODE
Case 2: Before Instruction
PC = address HERE
C =1
After Instruction
PC = address CARRY
39500 18C Reference Manual.book Page 32 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-33
Section 31. Instruction Set
Instruction Set
31
Example 2 HERE
CARRY
PLUS0
PLUS1
PLUS2
PLUS3
PLUS4
PLUS5
PLUS6
BNC
GOTO
•
•
•
•
•
•
•
$ + OFFSET
PROCESS_CODE
; If carry bit is clear,
; branch to HERE + OFFSET
Case 1: Before Instruction
PC = address HERE
C =0
After Instruction
PC = address HERE + OFFSET
Case 2: Before Instruction
PC = address HERE
C =1
After Instruction
PC = address CARRY
Example 3 MIN6
MIN5
MIN4
MIN3
MIN2
MIN1
MIN0
HERE
CARRY
•
•
•
•
•
•
•
BNC
GOTO
$ - OFFSET
PROCESS_CODE
; If carry bit is clear,
; branch to HERE - OFFSET
Case 1: Before Instruction
PC = address HERE
C =0
After Instruction
PC = address HERE - OFFSET
Case 2: Before Instruction
PC = address HERE
C =1
After Instruction
PC = address CARRY
Note: Assembler will convert the specified address label into the offset to be used.
39500 18C Reference Manual.book Page 33 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-34 2000 Microchip Technology Inc.
BNN Branch if Not Negative
Syntax: [ label ] BNN n
Operands: -128 ≤ f ≤ 127
Operation: If negative bit is ’0’
(PC + 2) + 2n → PC
Status Affected: None
Encoding: 1110 0111 nnnn nnnn
Description: If the Negative bit is ’0’, then the program will branch.
The 2’s complement number ’2n’ (the offset) is added to the PC. Since the
PC will have incremented to fetch the next instruction, the new address will
be (PC+2)+2n. This instruction is then a two-cycle instruction.
Words: 1
Cycles: 1 (2)
Q Cycle Activity:
If Branch
Q1 Q2 Q3 Q4
Decode Read
literal 'n'
Process
data
Write to
PC
No
operation
No
operation
No
operation
No
operation
If No Branch
Q1 Q2 Q3 Q4
Decode Read
literal 'n'
Process
data
No
operation
Example 1 HERE
NEG
POS_CODE
BNN
•
•
GOTO
•
•
POS_CODE
MORE_CODE
; If N bit is set
; execute this code.
;
;
; else if N bit is clear
; this code will execute
Case 1: Before Instruction
PC = address HERE
N =0
After Instruction
PC = address POS_CODE
Case 2: Before Instruction
PC = address HERE
N =1
After Instruction
PC = address NEG
39500 18C Reference Manual.book Page 34 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-35
Section 31. Instruction Set
Instruction Set
31
Example 2 HERE
NEG
PLUS0
PLUS1
PLUS2
PLUS3
PLUS4
PLUS5
PLUS6
BNN
GOTO
•
•
•
•
•
•
•
$ + OFFSET
PROCESS_CODE
; If negative bit is clear,
; branch to HERE + OFFSET
Case 1: Before Instruction
PC = address HERE
N =0
After Instruction
PC = address HERE + OFFSET
Case 2: Before Instruction
PC = address HERE
N =1
After Instruction
PC = address NEG
Example 3 MIN6
MIN5
MIN4
MIN3
MIN2
MIN1
MIN0
HERE
NEG
•
•
•
•
•
•
•
BNN
GOTO
$ - OFFSET
PROCESS_CODE
; If negative bit is clear,
; branch to HERE - OFFSET
Case 1: Before Instruction
PC = address HERE
N =0
After Instruction
PC = address HERE - OFFSET
Case 2: Before Instruction
PC = address HERE
N =1
After Instruction
PC = address NEG
Note: Assembler will convert the specified address label into the offset to be used.
39500 18C Reference Manual.book Page 35 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-36 2000 Microchip Technology Inc.
BNOV Branch if Not Overflow
Syntax: [ label ] BNOV n
Operands: -128 ≤ f ≤ 127
Operation: If overflow bit is ’0’
(PC + 2) + 2n → PC
Status Affected: None
Encoding: 1110 0101 nnnn nnnn
Description: If the Overflow bit is ’0’, then the program will branch.
The 2’s complement number ’2n’ (the offset) is added to the PC. Since the
PC will have incremented to fetch the next instruction, the new address will
be (PC+2)+2n. This instruction is then a two-cycle instruction.
Words: 1
Cycles: 1 (2)
Q Cycle Activity:
If Branch
Q1 Q2 Q3 Q4
Decode Read
literal 'n'
Process
data
Write to
PC
No
operation
No
operation
No
operation
No
operation
If No Branch
Q1 Q2 Q3 Q4
Decode Read
literal 'n'
Process
data
No
operation
Example 1 HERE
OVFL
NOV_CODE
BNOV
•
•
GOTO
•
•
NOV_CODE
MORE_CODE
; If overflow bit is set
; execute this code.
;
;
; else if overflow bit is
; clear this code will
; execute
Case 1: Before Instruction
PC = address HERE
OV = 0
After Instruction
PC = address NOV_CODE
Case 2: Before Instruction
PC = address HERE
OV = 1
After Instruction
PC = address OVFL
39500 18C Reference Manual.book Page 36 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-37
Section 31. Instruction Set
Instruction Set
31
Example 2 HERE
OVFL
PLUS0
PLUS1
PLUS2
PLUS3
PLUS4
PLUS5
PLUS6
BNOV
GOTO
•
•
•
•
•
•
•
$ + OFFSET
PROCESS_CODE
; If overflow bit is clear,
; branch to HERE + OFFSET
Case 1: Before Instruction
PC = address HERE
OV = 0
After Instruction
PC = address HERE + OFFSET
Case 2: Before Instruction
PC = address HERE
OV = 1
After Instruction
PC = address OVFL
Example 3 MIN6
MIN5
MIN4
MIN3
MIN2
MIN1
MIN0
HERE
OVFL
•
•
•
•
•
•
•
BNOV
GOTO
$ - OFFSET
PROCESS_CODE
; If overflow bit is clear,
; branch to HERE - OFFSET
Case 1: Before Instruction
PC = address HERE
OV = 0
After Instruction
PC = address HERE - OFFSET
Case 2: Before Instruction
PC = address HERE
OV = 1
After Instruction
PC = address OVFL
Note: Assembler will convert the specified address label into the offset to be used.
39500 18C Reference Manual.book Page 37 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-38 2000 Microchip Technology Inc.
BNZ Branch if Not Zero
Syntax: [ label ] BNZ n
Operands: -128 ≤ f ≤ 127
Operation: If zero bit is ’0’
(PC + 2) + 2n → PC
Status Affected: None
Encoding: 1110 0001 nnnn nnnn
Description: If the Zero bit is ’0’, then the program will branch.
The 2’s complement number ’2n’ (the offset) is added to the PC. Since the
PC will have incremented to fetch the next instruction, the new address will
be (PC+2)+2n. This instruction is then a two-cycle instruction.
Words: 1
Cycles: 1 (2)
Q Cycle Activity:
If Branch
Q1 Q2 Q3 Q4
Decode Read
literal 'n'
Process
data
Write to
PC
No
operation
No
operation
No
operation
No
operation
If No Branch
Q1 Q2 Q3 Q4
Decode Read
literal 'n'
Process
data
No
operation
Example 1 HERE
ZERO
Z_CODE
BNZ
•
•
GOTO
•
•
Z_CODE
MORE_CODE
; If Z bit is set
; execute this code.
;
;
; else if Z bit is clear
; this code will execute
Case 1: Before Instruction
PC = address HERE
Z =0
After Instruction
PC = address Z_CODE
Case 2: Before Instruction
PC = address HERE
Z =1
After Instruction
PC = address ZERO
39500 18C Reference Manual.book Page 38 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-39
Section 31. Instruction Set
Instruction Set
31
Example 2 HERE
ZERO
PLUS0
PLUS1
PLUS2
PLUS3
PLUS4
PLUS5
PLUS6
BNZ
GOTO
•
•
•
•
•
•
•
$ + OFFSET
PROCESS_CODE
; If zero bit is clear,
; branch to HERE + OFFSET
Case 1: Before Instruction
PC = address HERE
Z =0
After Instruction
PC = address HERE + OFFSET
Case 2: Before Instruction
PC = address HERE
Z =1
After Instruction
PC = address ZERO
Example 3 MIN6
MIN5
MIN4
MIN3
MIN2
MIN1
MIN0
HERE
ZERO
•
•
•
•
•
•
•
BNZ
GOTO
$ - OFFSET
PROCESS_CODE
; If zero bit is clear,
; branch to HERE - OFFSET
Case 1: Before Instruction
PC = address HERE
Z =0
After Instruction
PC = address HERE - OFFSET
Case 2: Before Instruction
PC = address HERE
Z =1
After Instruction
PC = address ZERO
Note: Assembler will convert the specified address label into the offset to be used.
39500 18C Reference Manual.book Page 39 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-40 2000 Microchip Technology Inc.
BOV Branch if Overflow
Syntax: [ label ] BOV n
Operands: -128 ≤ f ≤ 127
Operation: If overflow bit is ’1’
(PC + 2) + 2n → PC
Status Affected: None
Encoding: 1110 0100 nnnn nnnn
Description: If the Overflow bit is ’1’, then the program will branch.
The 2’s complement number ’2n’ (the offset) is added to the PC. Since the
PC will have incremented to fetch the next instruction, the new address will
be (PC+2)+2n. This instruction is then a two-cycle instruction.
Words: 1
Cycles: 1 (2)
Q Cycle Activity:
If Branch
Q1 Q2 Q3 Q4
Decode Read
literal 'n'
Process
data
Write to
PC
No
operation
No
operation
No
operation
No
operation
If No Branch
Q1 Q2 Q3 Q4
Decode Read
literal 'n'
Process
data
No
operation
Example 1 HERE
OVFL
OV_CODE
BOV
•
•
GOTO
•
•
OV_CODE
MORE_CODE
; If OV bit is clear
; execute this code.
;
;
; else if OV bit is set
; this code will execute
Case 1: Before Instruction
PC = address HERE
OV = 0
After Instruction
PC = address OVFL
Case 2: Before Instruction
PC = address HERE
OV = 1
After Instruction
PC = address OV_CODE
39500 18C Reference Manual.book Page 40 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-41
Section 31. Instruction Set
Instruction Set
31
Example 2 HERE
OVFL
PLUS0
PLUS1
PLUS2
PLUS3
PLUS4
PLUS5
PLUS6
BOV
GOTO
•
•
•
•
•
•
•
$ + OFFSET
PROCESS_CODE
; If overflow bit is set,
; branch to HERE + OFFSET
Case 1: Before Instruction
PC = address HERE
OV = 0
After Instruction
PC = address OVFL
Case 2: Before Instruction
PC = address HERE
OV = 1
After Instruction
PC = address HERE + OFFSET
Example 3 MIN6
MIN5
MIN4
MIN3
MIN2
MIN1
MIN0
HERE
OVFL
•
•
•
•
•
•
•
BOV
GOTO
$ - OFFSET
PROCESS_CODE
; If OV bit is set,
; branch to HERE - OFFSET
Case 1: Before Instruction
PC = address HERE
OV = 0
After Instruction
PC = address OVFL
Case 2: Before Instruction
PC = address HERE
OV = 1
After Instruction
PC = address HERE - OFFSET
Note: Assembler will convert the specified address label into the offset to be used.
39500 18C Reference Manual.book Page 41 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-42 2000 Microchip Technology Inc.
BRA Branch Unconditional
Syntax: [ label ] BRA n
Operands: -1024 ≤ f ≤ 1023
Operation: (PC + 2) + 2n → PC
Status Affected: None
Encoding: 1101 0nnn nnnn nnnn
Description: The 2’s complement number ’2n’ (the offset) is added to the PC. Since the
PC will have incremented to fetch the next instruction, the new address will
be (PC+2)+2n. This instruction is a two-cycle instruction.
Words: 1
Cycles: 2
Q Cycle Activity:
If Branch
Q1 Q2 Q3 Q4
Decode Read
literal 'n'
Process
data
Write to
PC
No
operation
No
operation
No
operation
No
operation
If No Branch
Q1 Q2 Q3 Q4
Decode Read
literal 'n'
Process
data
No
operation
Example 1 HERE
THERE
BRA
•
•
•
•
THERE ; Branch to a program memory
; location (THERE)
; this location must be
; < 1023 locations forward
Before Instruction
PC = address HERE
After Instruction
PC = address THERE
39500 18C Reference Manual.book Page 42 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-43
Section 31. Instruction Set
Instruction Set
31
Example 2 THERE
HERE
•
•
•
•
BRA THERE
; Branch to a program memory
; location (THERE)
; this location must be
; < 1024 locations backward
Before Instruction
PC = address HERE
After Instruction
PC = address THERE
Example 3 HERE BRA $ ; Branch to program memory
; location (HERE).
; Infinite Loop
Before Instruction
PC = address HERE
After Instruction
PC = address HERE
Note: Assembler will convert the specified address label into the offset to be used.
39500 18C Reference Manual.book Page 43 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-44 2000 Microchip Technology Inc.
BSF Bit Set f
Syntax: [ label ] BSF f, b, a
Operands: 0 ≤ f ≤ 255
0 ≤ b ≤ 7
a ∈ [0,1]
Operation: 1 → f
Status Affected: None
Encoding: 1000 bbba ffff ffff
Description: Bit 'b' in Register 'f' is set.
The ’a’ bit selects which bank is accessed for the operation.
If ’a’ is 1; the bank specified by the BSR Register is used.
If ’a’ is 0; the access bank is used.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
Register 'f'
Process
data
Write
Register 'f'
Example 1 BSF FLAG_REG, 7 ; Set bit 7 in Register
; FLAG_REG
; (assembler determines
; that FLAG_REG requires
; access bit to be set)
Before Instruction
FLAG_REG = 0x0A
After Instruction
FLAG_REG = 0x8A
; 0000 1010
; 1000 1010
Example 2 BSF INDF0, 3, 0 ; Set bit 3 in the register
; pointed to by the FSR0
; (FSR0H:FSR0L) Register
Before Instruction
WREG = 0x17
FSR0 = 0x0C2
Contents of Address
(FSR0)= 0x20
After Instruction
WREG = 0x17
FSR0 = 0x0C2
Contents of Address
(FSR0) = 0x28
; 0010 0000
; 0010 1000
39500 18C Reference Manual.book Page 44 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-45
Section 31. Instruction Set
Instruction Set
31
BTFSC Bit Test File, Skip if Clear
Syntax: [ label ] BTFSC f, b, a
Operands: 0 ≤ f ≤ 255
0 ≤ b ≤ 7
a ∈ [0,1]
Operation: Skip if (f) = 0
Status Affected: None
Encoding: 1011 bbba ffff ffff
Description: If bit 'b' in Register 'f' is '0' then the next instruction is skipped.
If bit 'b' is '0' then the next instruction (fetched during the current instruction
execution) is discarded, and a NOP is executed instead, making this a
2-cycle instruction.
The ’a’ bit selects which bank is accessed for the operation.
If ’a’ is 1; the bank specified by the BSR Register is used.
If ’a’ is 0; the access bank is used.
Words: 1
Cycles: 1 (2 or 3)
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
Register 'f'
Process
data
No
operation
If skip (2nd cycle):
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
If skip and followed by a two word instruction:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
Example 1 HERE
FALSE
TRUE
BTFSC
GOTO
•
•
•
FLAG, 4, 1
PROCESS_CODE
; Test bit 4 of Register
; FLAG, and skip if
; clear
Case 1: Before Instruction
PC = address HERE
FLAG = xxx0 xxxx
After Instruction
Since FLAG<4> = 0
PC = address TRUE
Case 2: Before Instruction
PC = address HERE
FLAG = xxx1 xxxx
After Instruction
Since FLAG<4> = 1
PC = address FALSE
39500 18C Reference Manual.book Page 45 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-46 2000 Microchip Technology Inc.
BTFSS Bit Test File, Skip if Set
Syntax: [ label ] BTFSS f, b, a
Operands: 0 ≤ f ≤ 255
0 ≤ b<7
a ∈ [0,1]
Operation: Skip if (f) = 1
Status Affected: None
Encoding: 1010 bbba ffff ffff
Description: If bit 'b' in Register 'f' is '1' then the next instruction is skipped.
If bit 'b' is '1', then the next instruction (fetched during the current instruction
execution) is discarded and a NOP is executed instead, making this a
2-cycle instruction.
The ’a’ bit selects which bank is accessed for the operation.
If ’a’ is 1; the bank specified by the BSR Register is used.
If ’a’ is 0; the access bank is used.
Words: 1
Cycles: 1 (2 or 3)
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
Register 'f'
Process
data
No
operation
If skip (2nd cycle):
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
If skip and followed by a two word instruction:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
Example 1 HERE
FALSE
TRUE
BTFSS
GOTO
•
•
•
FLAG, 4, 0
PROCESS_CODE
; Test bit 4 of Register
; FLAG, and skip if set
Case 1: Before Instruction
PC = address HERE
FLAG = xxx0 xxxx
After Instruction
Since FLAG<4> = 0
PC = address FALSE
Case 2: Before Instruction
PC = address HERE
FLAG = xxx1 xxxx
After Instruction
Since FLAG<4> = 1
PC = address TRUE
39500 18C Reference Manual.book Page 46 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-47
Section 31. Instruction Set
Instruction Set
31
BTG Bit Toggle f
Syntax: [ label ] BTG f, b, a
Operands: 0 ≤ f ≤ 255
0 ≤ b ≤ 7
a ∈ [0,1]
Operation: (f) → f
Status Affected: None
Encoding: 0111 bbba ffff ffff
Description: Bit 'b' in Register 'f' is toggled.
The ’a’ bit selects which bank is accessed for the operation.
If ’a’ is 1; the bank specified by the BSR Register is used.
If ’a’ is 0; the access bank is used.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
Register 'f'
Process
data
Write
Register 'f'
Example 1 BTG LATC, 7, 1 ; Toggle the value of bit 7
; in the LATC Register
Before Instruction
LATC = 0x0A
After Instruction
LATC = 0x8A
; 0000 1010
; 1000 1010
Example 2 BTG INDF0, 3, 1 ; Toggle the value of bit 3
; in the register pointed to
; by the value in the FSR0
; (FSR0H:FSR0L) Register
Before Instruction
FSR0 = 0xAC2
Contents of Address
(FSR0)= 0x20
After Instruction
FSR0 = 0xAC2
Contents of Address
(FSR0)= 0x28
; 0010 0000
; 0010 1000
39500 18C Reference Manual.book Page 47 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-48 2000 Microchip Technology Inc.
BZ Branch if Zero
Syntax: [ label ] BZ n
Operands: -128 ≤ f ≤ 127
Operation: If zero bit is ’1’
(PC + 2) + 2n → PC
Status Affected: None
Encoding: 1110 0000 nnnn nnnn
Description: If the Zero bit is ’1’, then the program will branch.
The 2’s complement number ’2n’ (the offset) is added to the PC. Since the
PC will have incremented to fetch the next instruction, the new address will
be PC+2+2n. This instruction is then a two-cycle instruction.
Words: 1
Cycles: 1 (2)
Q Cycle Activity:
If Branch
Q1 Q2 Q3 Q4
Decode Read
literal 'n'
Process
data
Write to
PC
No
operation
No
operation
No
operation
No
operation
If No Branch
Q1 Q2 Q3 Q4
Decode Read
literal 'n'
Process
data
No
operation
Example 1 HERE
ZERO
Z_CODE
BZ
•
•
GOTO
•
•
Z_CODE
MORE_CODE
; If zero bit is clear
; execute this code.
;
;
; else if zero bit is set
; this code will execute
Case 1: Before Instruction
PC = address HERE
Z =0
After Instruction
PC = address ZERO
Case 2: Before Instruction
PC = address HERE
Z =1
After Instruction
PC = address Z_CODE
39500 18C Reference Manual.book Page 48 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-49
Section 31. Instruction Set
Instruction Set
31
Example 2 HERE
NZERO
PLUS0
PLUS1
PLUS2
PLUS3
PLUS4
PLUS5
PLUS6
BZ
GOTO
•
•
•
•
•
•
•
$ + OFFSET
PROCESS_CODE
; If zero bit is set,
; branch to HERE + OFFSET
Case 1: Before Instruction
PC = address HERE
Z =0
After Instruction
PC = address NZERO
Case 2: Before Instruction
PC = address HERE
Z =1
After Instruction
PC = address HERE + OFFSET
Example 3 MIN6
MIN5
MIN4
MIN3
MIN2
MIN1
MIN0
HERE
NZERO
•
•
•
•
•
•
•
BZ
GOTO
$ - OFFSET
PROCESS_CODE
; If zero bit is set,
; branch to HERE - OFFSET
Case 1: Before Instruction
PC = address HERE
Z =0
After Instruction
PC = address NZERO
Case 2: Before Instruction
PC = address HERE
Z =1
After Instruction
PC = address HERE - OFFSET
Note: Assembler will convert the specified address label into the offset to be used.
39500 18C Reference Manual.book Page 49 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-50 2000 Microchip Technology Inc.
CALL Call Subroutine
Syntax: [ label ] CALL k, s
Operands: 0 ≤ k ≤ 1048575
s ∈ [0,1]
Operation: (PC)+ 4 → TOS,
k → PC<20:1>,
0 → PC<0>,
if s = 1
(WREG) → WREGS,
(STATUS) → STATUSS,
(BSR) → BSRS
Status Affected: None
Encoding:
1st word (k<7:0>)
2nd word (k<19:8>)
1110
1111
110s
k19kkk
k7kkk
kkkk
kkkk0
kkkk8
Description: Subroutine call of entire 2M byte memory range. First, return address (PC+
4) is pushed onto the return stack (20-bits wide).
If ’s’ = 1, the WREG, STATUS and BSR Registers are also pushed into
their respective Shadow Registers, WREGS, STATUSS and BSRS.
If 's' = 0, no update occurs.
Then the 20-bit value ’k’ is loaded into PC<20:1>. CALL is a two-cycle
instruction.
Words: 2
Cycles: 2
Q Cycle Activity:
1st cycle:
Q1 Q2 Q3 Q4
Decode Read
literal 'k'
Process
data
No
operation
2nd cycle:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
39500 18C Reference Manual.book Page 50 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-51
Section 31. Instruction Set
Instruction Set
31
Example 1 HERE CALL THERE, 1 ; Call subroutine THERE.
; This is a fast call so
; the BSR, WREG, and STATUS
; Registers are forced onto
; the Fast Register Stack
Before Instruction
PC = Address HERE
After Instruction
TOS = Address HERE+4
PC = Address THERE
WREGS = WREG
BSRS = BSR
STATUSS = STATUS
Example 2 HERE CALL THERE, 0 ; Call subroutine THERE.
; This is NOT a fast call
Before Instruction
PC = Address HERE
WREGS = 0x45
BSRS = 0x29
STATUSS = 0x01
After Instruction
TOS = Address HERE+4
PC = Address THERE
WREGS = 0x45 (unchanged)
BSRS = 0x29 (unchanged)
STATUSS = 0x01 (unchanged)
39500 18C Reference Manual.book Page 51 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-52 2000 Microchip Technology Inc.
CLRF Clear f
Syntax: [ label ] CLRF f, a
Operands: 0 ≤ f ≤ 255
a ∈ [0,1]
Operation: 00h → f
1 → Z
Status Affected: Z
Encoding: 0110 101a ffff ffff
Description: The contents of Register 'f' are cleared and the Z bit is set.
The ’a’ bit selects which bank is accessed for the operation.
If ’a’ is 1; the bank specified by the BSR Register is used.
If ’a’ is 0; the access bank is used.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
Register 'f'
Process
data
Write
Register 'f'
Example 1 CLRF FLAG_REG, 1 ; Clear Register FLAG_REG
Before Instruction
FLAG_REG = 0x5A
Z =x
After Instruction
FLAG_REG = 0x00
Z =1
Example 2 CLRF INDF0, 1 ; Clear the register pointed
; to by the FSR0
; (FSR0H:FSR0L) Register
Before Instruction
FSR0 = 0x0C2
Contents of Address
(FSR0) = 0xAA
Z =x
After Instruction
FSR0 = 0x0C2
Contents of Address
(FSR0) = 0x00
Z =1
39500 18C Reference Manual.book Page 52 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-53
Section 31. Instruction Set
Instruction Set
31
CLRWDT Clear Watchdog Timer
Syntax: [ label ] CLRWDT
Operands: None
Operation: 00h → WDT
0 → WDT prescaler count,
1 → TO
1 → PD
Status Affected: TO, PD
Encoding: 0000 0000 0000 0100
Description: CLRWDT instruction clears the Watchdog Timer. It also clears the
postscaler count of the WDT. Status bits TO and PD are set.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode No
operation
Process
data
Clear
WDT
Counter
Example CLRWDT ; Clear the Watchdog
; Timer count value
Before Instruction
WDT counter = x
WDT postscaler
count = 0
WDT postscaler = 1:128
TO = x
PD = x
After Instruction
WDT counter = 0x00
WDT postscaler
count = 0
WDT postscaler = 1:128
TO = 1
PD = 1
Note: The CLRWDT instruction does not affect the assignment of the WDT postscaler.
39500 18C Reference Manual.book Page 53 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-54 2000 Microchip Technology Inc.
COMF Complement f
Syntax: [ label ] COMF f, d, a
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (f) → destination
Status Affected: Z, N
Encoding: 0001 11da ffff ffff
Description: The contents of Register 'f' are 1’s complemented.
The ’d’ bit selects the destination for the operation.
If 'd' is 1; the result is stored back in the File Register 'f'.
If 'd' is 0; the result is stored in the WREG Register.
The ’a’ bit selects which bank is accessed for the operation.
If ’a’ is 1; the bank specified by the BSR Register is used.
If ’a’ is 0; the access bank is used.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
Register 'f'
Process
data
Write to
destination
Example 1 COMF REG1, 0, 1 ; Complement the value in
; Register REG1 and place the
; result in the WREG Register
Case 1: Before Instruction
REG1 = 0x13
Z, N = x
After Instruction
REG1 = 0x13
WREG = 0xEC
Z =0
N =1
; 0001 0011
; 1110 1100
Case 2: Before Instruction
REG1 = 0xFF
Z, N = x
After Instruction
REG1 = 0xFF
WREG = 0x00
Z =1
N =0
; 1111 1111
; 0000 0000
Case 3: Before Instruction
REG1 = 0x00
Z, N = x
After Instruction
REG1 = 0x00
WREG = 0xFF
Z =0
N =1
; 0000 0000
; 1111 1111
39500 18C Reference Manual.book Page 54 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-55
Section 31. Instruction Set
Instruction Set
31
Example 2 COMF INDF0, 1, 1 ; Complement the value in the
; register pointed to by the
; FSR0 (FSR0H:FSR0L)
; Register, placing the
; result in that register
Before Instruction
FSR0 = 0xFC2
Contents of Address
(FSR0) = 0xAA
Z, N = x
After Instruction
FSR0 = 0xFC2
Contents of Address
(FSR0) = 0x55
Z =0
N =0
; 1010 1010
; 0101 0101
Example 3 COMF REG1, 1, 1 ; Complement the value in
; Register REG1 and place the
; result in Register REG1
Before Instruction
REG1 = 0xFF
Z, N = x
After Instruction
REG1 = 0x00
Z =1
N =0
; 1111 1111
; 0000 0000
39500 18C Reference Manual.book Page 55 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-56 2000 Microchip Technology Inc.
CPFSEQ Compare f with WREG, Skip if Equal (f = WREG)
Syntax: [ label ] CPFSEQ f, a
Operands: 0 ≤ f ≤ 255
a ∈ [0,1]
Operation: (f) - (WREG)
skip if (f) = (WREG)
Status Affected: None
Encoding: 0110 001a ffff ffff
Description: Compares the contents of Register 'f' to the contents of WREG Register by
performing an unsigned subtraction.
If 'f' = WREG then the fetched instruction is discarded and a NOP is executed
instead, making this a two-cycle instruction.
The ’a’ bit selects which bank is accessed for the operation.
If ’a’ is 1; the bank specified by the BSR Register is used.
If ’a’ is 0; the access bank is used.
Words: 1
Cycles: 1 (2 or 3)
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
Register 'f'
Process
data
No
operation
If skip (2nd cycle):
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
If skip and followed by a two word instruction:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
39500 18C Reference Manual.book Page 56 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-57
Section 31. Instruction Set
Instruction Set
31
Example HERE
NEQUAL
EQUAL
CPFSEQ
GOTO
•
•
•
FLAG, 1
PROCESS_CODE
; Compare the value in
; Register FLAG to the
; WREG Register and skip
; the next program memory
; location if they are
; equal
Case 1: Before Instruction
PC = address HERE
FLAG = 0x5A
WREG = 0x5A
After Instruction
PC = address EQUAL
; FLAG - WREG = 0x00
; The two values were
; Equal
Case 2: Before Instruction
PC = address HERE
FLAG = 0xA5
WREG = 0x5A
After Instruction
PC = address NEQUAL
; FLAG - WREG = 0x4B
; The two values were
; Not Equal
39500 18C Reference Manual.book Page 57 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-58 2000 Microchip Technology Inc.
CPFSGT Compare f with WREG, Skip if Greater Than (f > WREG)
Syntax: [ label ] CPFSGT f, a
Operands: 0 ≤ f ≤ 255
a ∈ [0,1]
Operation: (f) - (WREG)
skip if (f) > (WREG); (unsigned comparison)
Status Affected: None
Encoding: 0110 010a ffff ffff
Description: Compares the contents of data memory location 'f' to the contents of
WREG Register by performing an unsigned subtraction.
If 'f' > WREG then the fetched instruction is discarded and a NOP is executed
instead, making this a two-cycle instruction.
The ’a’ bit selects which bank is accessed for the operation.
If ’a’ is 1; the bank specified by the BSR Register is used.
If ’a’ is 0; the access bank is used.
Words: 1
Cycles: 1 (2 or 3)
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
Register 'f'
Process
data
No
operation
If skip (2nd cycle):
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
If skip and followed by a two word instruction:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
39500 18C Reference Manual.book Page 58 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-59
Section 31. Instruction Set
Instruction Set
31
Example HERE
NGT
GT
CPFSGT
GOTO
•
•
•
FLAG, 1
PROCESS_CODE
; Compare the value in
; Register FLAG to the
; WREG Register and skip
; the next program memory
; location if
; FLAG > WREG
Case 1: Before Instruction
PC = address HERE
FLAG = 0x5A
WREG = 0x5A
After Instruction
PC = address NGT
; FLAG - WREG = 0x00
; The two values were
; Equal (Not Greater Than)
Case 2: Before Instruction
PC = address HERE
FLAG = 0xA5
WREG = 0x5A
After Instruction
PC = address GT
; FLAG - WREG = 0x4B
; FLAG > WREG, Skip
; the next instruction
39500 18C Reference Manual.book Page 59 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-60 2000 Microchip Technology Inc.
CPFSLT Compare f with WREG, Skip if Less Than (f < WREG)
Syntax: [ label ] CPFSLT f, a
Operands: 0 ≤ f ≤ 255
a ∈ [0,1]
Operation: (f) - (WREG); (unsigned comparison)
skip if (f) < (WREG)
Status Affected: None
Encoding: 0110 000a ffff ffff
Description: Compares the contents of data memory location 'f' to the contents of
WREG Register by performing an unsigned subtraction.
If 'f' < WREG then the fetched instruction is discarded and an NOP is executed
instead making this a two-cycle instruction.
The ’a’ bit selects which bank is accessed for the operation.
If ’a’ is 1; the bank specified by the BSR Register is used.
If ’a’ is 0; the access bank is used.
Words: 1
Cycles: 1 (2 or 3)
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
Register 'f'
Process
data
No
operation
If skip (2nd cycle):
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
If skip and followed by a two word instruction:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
39500 18C Reference Manual.book Page 60 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-61
Section 31. Instruction Set
Instruction Set
31
Example HERE
NLT
LT
CPFSLT
GOTO
•
•
•
FLAG, 1
PROCESS_CODE
; Compare the value in
; Register FLAG to the
; WREG Register and skip
; the next program memory
; location if
; FLAG < WREG
Case 1: Before Instruction
PC = address HERE
FLAG = 0x5A
WREG = 0x5A
After Instruction
PC = address NLT
; FLAG - WREG = 0x00
; the two values were
; Equal (Not less than)
Case 2: Before Instruction
PC = address HERE
FLAG = 0x5A
WREG = 0xA5
After Instruction
PC = address LT
; FLAG - WREG = 0x4B
; FLAG < WREG, Skip
; the next instruction
39500 18C Reference Manual.book Page 61 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-62 2000 Microchip Technology Inc.
DAW Decimal Adjust WREG Register
Syntax: [ label ] DAW
Operands: None
Operation: If [WREG<3:0> >9] or [DC = 1] then
(WREG<3:0>) + 6 → WREG<3:0>;
else
(WREG<3:0>) → WREG<3:0>;
If [WREG<7:4> >9] or [C = 1] then
(WREG<7:4>) + 6 → WREG<7:4>;
else
(WREG<7:4>) → WREG<7:4>;
Status Affected: C
Encoding: 0000 0000 0000 0111
Description: DAW adjusts the eight bit value in WREG resulting from the earlier addition
of two variables (each in packed BCD format) and produces a correct
packed BCD result.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
Register
REG
Process
data
Write to
REG
39500 18C Reference Manual.book Page 62 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-63
Section 31. Instruction Set
Instruction Set
31
Example HERE DAW ; Decimal Adjust WREG
Case 1: Before Instruction
WREG = 0x0F
C =x
After Instruction
WREG = 0x15
C =0
; 0x0F is 15 decimal
Case 2: Before Instruction
WREG = 0x68
C =x
After Instruction
PC = 0x04
C =1
; 0x68 is 104 decimal
; Carry to indicate
; decimal rollover
Case 3: Before Instruction
WREG = C6
C =x
After Instruction
PC = 98
C =1
;
; 0xC6 is 198 decimal
; Carry to indicate
; decimal rollover
39500 18C Reference Manual.book Page 63 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-64 2000 Microchip Technology Inc.
DECF Decrement f
Syntax: [ label ] DECF f, d, a
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (f) - 1 → destination
Status Affected: C, DC, Z, OV, N
Encoding: 0000 01da ffff ffff
Description: Decrement the contents of Register 'f'.
The ’d’ bit selects the destination for the operation.
If 'd' is 1; the result is stored back in the File Register 'f'.
If 'd' is 0; the result is stored in the WREG Register.
The ’a’ bit selects which bank is accessed for the operation.
If ’a’ is 1; the bank specified by the BSR Register is used.
If ’a’ is 0; the access bank is used.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
Register 'f'
Process
data
Write to
destination
Example 1 DECF CNT, 1, 1 ; Decrement Register CNT
Before Instruction
CNT = 0x01
C, DC, OV, N = x
Z =0
After Instruction
CNT = 0x00
C =0
DC = 0
Z =1
OV = 0
N =0
39500 18C Reference Manual.book Page 64 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-65
Section 31. Instruction Set
Instruction Set
31
Example 2 DECF INDF0, 1, 1 ; Decrement the register
; pointed to by the FSR
; (FSR0H:FSR0L) Register
Before Instruction
FSR0 = 0x1C2
Contents of Address
(FSR0) = 0x01
C, DC, OV, N = x
Z =0
After Instruction
FSR0 = 0x1C2
Contents of Address
(FSR0) = 0x00
C =0
DC = 0
Z =1
OV = 0
N =0
Example 3 DECF CNT, 0, 1 ; Decrement Register CNT
; WREG is destination
Before Instruction
CNT = 0x10
WREG = x
Z =0
After Instruction
CNT = 0x10
WREG = 0x0F
C =0
DC = 1
Z =0
OV = 0
N =0
39500 18C Reference Manual.book Page 65 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-66 2000 Microchip Technology Inc.
DECFSZ Decrement f, Skip if 0
Syntax: [ label ] DECFSZ f, d, a
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]]
a ∈ [0,1]
Operation: (f) - 1 → destination; skip if result = 0
Status Affected: None
Encoding: 0010 11da ffff ffff
Description: The contents of Register 'f' are decremented. If the result is 0, then the
next instruction (fetched during the current instruction execution) is discarded
and a NOP is executed instead, making this a 2 cycle instruction.
The ’d’ bit selects the destination for the operation.
If 'd' is 1; the result is stored back in the File Register 'f'.
If 'd' is 0; the result is stored in the WREG Register.
The ’a’ bit selects which bank is accessed for the operation.
If ’a’ is 1; the bank specified by the BSR Register is used.
If ’a’ is 0; the access bank is used.
Words: 1
Cycles: 1 (2 or 3)
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
Register 'f'
Process
data
Write to
destination
If skip (2nd cycle):
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
If skip and followed by 2 word instruction
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
39500 18C Reference Manual.book Page 66 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-67
Section 31. Instruction Set
Instruction Set
31
Example HERE
CONTINUE
DECFSZ
GOTO
•
•
CNT, 1, 1
LOOP
; Decrement Register CNT,
; if CNT then equals 0
; skip the next
; instruction
Case 1: Before Instruction
PC = address HERE
CNT = 0x01
After Instruction
CNT = 0x00
PC = address CONTINUE
Case 2: Before Instruction
PC = address HERE
CNT = 0x02
After Instruction
CNT = 0x01
PC = address HERE + 2
39500 18C Reference Manual.book Page 67 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-68 2000 Microchip Technology Inc.
DCFSNZ Decrement f, Skip if Not 0
Syntax: [ label ] DCFSNZ f, d, a
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]]
a ∈ [0,1]
Operation: (f) - 1 → destination; skip if result ≠ 0
Status Affected: None
Encoding: 0100 11da ffff ffff
Description: The contents of Register 'f' are decremented. If the result is not 0, then
the next instruction (fetched during the current instruction execution) is
discarded and a NOP is executed instead, making this a 2-cycle instruction.
The ’d’ bit selects the destination for the operation.
If 'd' is 1; the result is stored back in the File Register 'f'.
If 'd' is 0; the result is stored in the WREG Register.
The ’a’ bit selects which bank is accessed for the operation.
If ’a’ is 1; the bank specified by the BSR Register is used.
If ’a’ is 0; the access bank is used.
Words: 1
Cycles: 1 (2 or 3)
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
Register 'f'
Process
data
Write to
destination
If skip (2nd cycle):
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
If skip and followed by 2 word instruction
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
39500 18C Reference Manual.book Page 68 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-69
Section 31. Instruction Set
Instruction Set
31
Example HERE
CONTINUE
DCFSNZ
GOTO
•
•
CNT, 1, 1
LOOP
; Decrement Register CNT,
; if CNT does not equal 0
; skip the next instruction
Case 1: Before Instruction
PC = address HERE
CNT = 0x01
After Instruction
CNT = 0x00
PC = address HERE + 2
Case 2: Before Instruction
PC = address HERE
CNT = 0x02
After Instruction
CNT = 0x01
PC = address CONTINUE
39500 18C Reference Manual.book Page 69 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-70 2000 Microchip Technology Inc.
GOTO Unconditional Branch
Syntax: [ label ] GOTO k
Operands: 0 ≤ k ≤ 1048575
Operation: k → PC<20:1>
0 → PC<0>,
Status Affected: None
Encoding:
1st word (k<7:0>)
2nd word (k<19:8>)
1110
1111
1111
k19kkk
k7kkk
kkkk
kkkk0
kkkk8
Description: GOTO allows an unconditional branch anywhere within the entire 2M byte
memory range. The 20-bit immediate value ’k’ is loaded into PC<20:1>.
GOTO is always a two-cycle instruction.
Words: 2
Cycles: 2
Q Cycle Activity:
1st cycle:
Q1 Q2 Q3 Q4
Decode Read
literal
'k'<7:0>
Process
data
No
operation
2nd cycle:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
39500 18C Reference Manual.book Page 70 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-71
Section 31. Instruction Set
Instruction Set
31
Example 1 HERE GOTO THERE ; Goto address THERE
After Instruction
PC = Address THERE
Example 2 HERE GOTO $-2 ; GOTO address HERE - 2
After Instruction
PC = Address HERE -2
Example 3 HERE GOTO $ ; GOTO address HERE
; (infinite loop)
After Instruction
PC = Address HERE
Example 4 HERE GOTO HERE ; GOTO address HERE
; (infinite loop)
After Instruction
PC = Address HERE
39500 18C Reference Manual.book Page 71 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-72 2000 Microchip Technology Inc.
INCF Increment f
Syntax: [ label ] INCF f, d, a
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (f) + 1 → destination
Status Affected: C, DC, Z, OV, N
Encoding: 0010 10da ffff ffff
Description: The contents of Register 'f' are incremented.
The ’d’ bit selects the destination for the operation.
If 'd' is 1; the result is stored back in the File Register 'f'.
If 'd' is 0; the result is stored in the WREG Register.
The ’a’ bit selects which bank is accessed for the operation.
If ’a’ is 1; the bank specified by the BSR Register is used.
If ’a’ is 0; the access bank is used.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
Register 'f'
Process
data
Write to
destination
Example 1 INCF CNT,1, 1 ; Increment Register CNT
Before Instruction
CNT = 0xFF
C, DC, Z, OV, N = x
After Instruction
CNT = 0x00
C =1
DC = 1
Z =1
OV = 0
N =0
; 1111 1111
; 0000 0000
39500 18C Reference Manual.book Page 72 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-73
Section 31. Instruction Set
Instruction Set
31
Example 2 INCF INDF0, 1, 1 ; Increment Register
; indirectly
; (FSR0 (FSR0H:FSR0L) points
; to address to increment)
Before Instruction
FSR0 = 0x0C2
Contents of Address
(FSR0) = 0xFF
C, DC, Z, OV, N = x
After Instruction
FSR0 = 0x0C2
Contents of Address
(FSR0) = 0x00
C =1
DC = 1
Z =1
OV = 0
N =0
; 1111 1111
; 0000 0000
Example 3 INCF CNT, 0, 1 ; Increment Register CNT
; place result in WREG
Before Instruction
CNT = 0x10
WREG = x
C, DC, OV, N = x
Z =0
After Instruction
CNT = 0x10
WREG = 0x11
C =0
DC = 0
Z =0
OV = 0
N =0
; 0001 0000
; 0001 0001
39500 18C Reference Manual.book Page 73 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-74 2000 Microchip Technology Inc.
INCFSZ Increment f, Skip if 0
Syntax: [ label ] INCFSZ f, d, a
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (f) + 1 → destination, skip if result = 0
Status Affected: None
Encoding: 0011 11da ffff ffff
Description: The contents of Register 'f' are incremented. If the result is 0, then the next
instruction (fetched during the current instruction execution) is discarded
and a NOP is executed instead, making this a 2-cycle instruction.
The ’d’ bit selects the destination for the operation.
If 'd' is 1; the result is stored back in the File Register 'f'.
If 'd' is 0; the result is stored in the WREG Register.
The ’a’ bit selects which bank is accessed for the operation.
If ’a’ is 1; the bank specified by the BSR Register is used.
If ’a’ is 0; the access bank is used.
Words: 1
Cycles: 1 (2 or 3)
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
Register 'f'
Process
data
Write to
destination
If skip (2nd cycle):
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
If skip and followed by 2 word instruction
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
39500 18C Reference Manual.book Page 74 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-75
Section 31. Instruction Set
Instruction Set
31
Example 1 HERE
NZERO
ZERO
INCFSZ
GOTO
•
•
CNT, 1, 1
LOOP
; Increment Register CNT,
; if CNT then equals 0
; skip the next
; instruction
Case 1: Before Instruction
PC = address HERE
CNT = 0xFF
After Instruction
CNT = 0x00
PC = address ZERO
Case 2: Before Instruction
PC = address HERE
CNT = 0x00
After Instruction
CNT = 0x01
PC = address NZERO
Example 2 HERE
NZERO
ZERO
INCFSZ
GOTO
•
•
•
CNT, 1, 0
LOOP
; Increment Register CNT,
; if CNT equals 0
; skip the next
; instruction
Case 1: Before Instruction
PC = address HERE
CNT = 0xFF ; In access bank
After Instruction
CNT = 0x00
PC = address ZERO
Case 2: Before Instruction
PC = address HERE
CNT = 0x00 ; In access bank
After Instruction
CNT = 0x01
PC = address NZERO
39500 18C Reference Manual.book Page 75 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-76 2000 Microchip Technology Inc.
INFSNZ Increment f, Skip if Not 0
Syntax: [ label ] INFSNZ f, d, a
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (f) + 1 → destination, skip if result ≠ 0
Status Affected: None
Encoding: 0100 10da ffff ffff
Description: The contents of Register 'f' are incremented. If the result is not 0, then the
next instruction (fetched during the current instruction execution) is discarded
and a NOP is executed instead, making this a 2-cycle instruction.
The ’d’ bit selects the destination for the operation.
If 'd' is 1; the result is stored back in the File Register 'f'.
If 'd' is 0; the result is stored in the WREG Register.
The ’a’ bit selects which bank is accessed for the operation.
If ’a’ is 1; the bank specified by the BSR Register is used.
If ’a’ is 0; the access bank is used.
Words: 1
Cycles: 1 (2 or 3)
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
Register 'f'
Process
data
Write to
destination
If skip (2nd cycle):
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
If skip and followed by 2 word instruction
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
39500 18C Reference Manual.book Page 76 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-77
Section 31. Instruction Set
Instruction Set
31
Example 1 HERE
ZERO
NZERO
INFSNZ
GOTO
•
•
CNT, 1, 1
LOOP
; Increment Register CNT,
; if CNT does not equal 0
; skip the next instruction
Case 1: Before Instruction
PC = address HERE
CNT = 0xFF
After Instruction
CNT = 0x00
PC = address ZERO
Case 2: Before Instruction
PC = address HERE
CNT = 0x00
After Instruction
CNT = 0x01
PC = address NZERO
Example 2 HERE
ZERO
NZERO
INFSNZ
GOTO
•
•
•
CNT, 1, 0
LOOP
; Increment Register CNT,
; if CNT does not equal 0
; skip the next instruction
Case 1: Before Instruction
PC = address HERE
CNT = 0xFF ; In access bank
After Instruction
CNT = 0x00
PC = address ZERO
Case 2: Before Instruction
PC = address HERE
CNT = 0x00 ; In access bank
After Instruction
CNT = 0x01
PC = address NZERO
39500 18C Reference Manual.book Page 77 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-78 2000 Microchip Technology Inc.
IORLW Inclusive OR Literal with WREG
Syntax: [ label ] IORLW k
Operands: 0 ≤ k ≤ 255
Operation: (WREG).OR. k → WREG
Status Affected: Z, N
Encoding: 0000 1001 kkkk kkkk
Description: The contents of the WREG Register is OR’d with the eight bit literal 'k'. The
result is placed in the WREG Register.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
literal 'k'
Process
data
Write to
WREG
Register
Example 1 IORLW 0x35 ; bit wise OR 35h with the
; WREG Register
Before Instruction
WREG = 0x9A
Z, N = x
After Instruction
WREG = 0xBF
Z =0
N =1
; 0011 0101 (35h)
; 1001 1010
; 1011 1111
Example 2 IORLW MYREG ; bit wise OR the value of
; the address of Register
; MYREG with the WREG
; Register
Before Instruction
WREG = 0x9A
Address of MYREG †
= 0x37
† MYREG is a symbol for a
data memory location
Z, N = x
After Instruction
WREG = 0xBF
Z =0
N =1
;
; 1001 1010
;
; 0011 0111
; 1011 1111
39500 18C Reference Manual.book Page 78 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-79
Section 31. Instruction Set
Instruction Set
31
Example 3 IORLW HIGH (LU_TABLE) ; bit wise OR the value of
; the high byte of address
; LU_TABLE with the WREG
; Register
Before Instruction
WREG = 0x9A
Address of LU_TABLE †
= 0x9375
† LU_TABLE is a label for an
address in program memory
Z, N = x
After Instruction
WREG = 0x9B
Z =0
N =1
; 1001 1010
; 1001 0011 (93h)
; 1001 1011
Example 4 IORLW 0x00 ; bit wise OR 00h with the
; WREG Register
Before Instruction
WREG = 0x00
Z, N = x
After Instruction
WREG = 0x00
Z =1
N =0
; 0000 0000 (literal)
; 0000 0000
; 0000 0000
39500 18C Reference Manual.book Page 79 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-80 2000 Microchip Technology Inc.
IORWF Inclusive OR WREG with f
Syntax: [ label ] IORWF f, d, a
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (WREG).OR. (f) → destination
Status Affected: Z, N
Encoding: 0001 00da ffff ffff
Description: Inclusive OR the WREG Register with the contents of Register 'f'.
The ’d’ bit selects the destination for the operation.
If 'd' is 1; the result is stored back in the File Register 'f'.
If 'd' is 0; the result is stored in the WREG Register.
The ’a’ bit selects which bank is accessed for the operation.
If ’a’ is 1; the bank specified by the BSR Register is used.
If ’a’ is 0; the access bank is used.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
Register 'f'
Process
data
Write to
destination
Example 1 IORWF INDF0, 1, 1 ; Comment
Before Instruction
WREG = 0x17
FSR0 = 0xDC2
Contents of Address
(FSR0) = 0x30
Z, N = x
After Instruction
WREG = 0x17
FSR0 = 0xDC2
Contents of Address
(FSR0) = 0x37
Z =0
N =0
; 0001 0111
; 0011 0000
; 0011 0111
39500 18C Reference Manual.book Page 80 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-81
Section 31. Instruction Set
Instruction Set
31
Example 2 IORWF RESULT, 1, 1 ; bit wise OR the WREG
; Register with the
; Register RESULT.
Case 1: Before Instruction
RESULT = 0x13
WREG = 0x91
Z, N = x
After Instruction
RESULT = 0x93
WREG = 0x91
Z =0
N =1
; 0001 0011
; 1001 0001
; 1001 0011
Case 2: Before Instruction
RESULT = 0x00
WREG = 0x00
Z, N = x
After Instruction
RESULT = 0x00
WREG = 0x00
Z =1
N =0
; 0000 0000
; 0000 0000
; 0000 0000
Example 3 IORWF RESULT, 1, 0 ; bit wise OR the WREG
; Register with the
; register in the Access
; bank at address of RESULT
; Register.
Case 1: Before Instruction
RESULT = 0x13
(RESULT) in access bank
= 0xC8
WREG = 0x91
Z, N = x
After Instruction
RESULT = 0x13
(RESULT) in access bank
= 0xD9
WREG = 0x91
Z =0
N =1
; 1100 1000
; 1001 0001
; 1101 1001
Case 2: Before Instruction
RESULT = 0x00
(RESULT) in access bank
= 0x11
WREG = 0x00
Z, N = x
After Instruction
RESULT = 0x00
(RESULT) in access bank
= 0x11
WREG = 0x00
Z =0
N =0
; 0001 0001
; 0000 0000
; 0001 0001
39500 18C Reference Manual.book Page 81 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-82 2000 Microchip Technology Inc.
LFSR Load 12-bit Literal to FSR
Syntax: [ label ] LFSR f, k
Operands: 0 ≤ f ≤ 2
0 ≤ k ≤ 4095
Operation: k → FSRx
Status Affected: None
Encoding:
1st word
2nd word
1110
1111
1110
0000
00ff
k7kkk
k11kkk8
kkkk0
Description: The 12-bit literal 'k' is loaded into the File Select Register (FSR Register)
pointed to by 'f':
f = 00 → FSR0
f = 01 → FSR1
f = 10 → FSR2
f = 11 → Reserved
Words: 2
Cycles: 2
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
literal
k11:k8
Process
data
Write to
FSRxH
Register
k11:k8
Decode Read
literal k7:k0
Process
data
Write to
FSRxL
Register
k7:k0
Example 1 LFSR 2, 0x123 ; Load the 12-bit FSR2 with
; 123h
Before Instruction
FSR0H = 0x05
FSR0L = 0xA5
FSR1H = 0x05
FSR1L = 0xA5
FSR2H = 0x05
FSR2L = 0xA5
After Instruction
FSR0H = 0x05
FSR0L = 0xA5
FSR1H = 0x05
FSR1L = 0xA5
FSR2H = 0x01
FSR2L = 0x23
39500 18C Reference Manual.book Page 82 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-83
Section 31. Instruction Set
Instruction Set
31
Example 2 LFSR 0, 0xFE3 ; Load the 12-bit FSR0 with
; FE3h
Before Instruction
FSR0H = 0x05
FSR0L = 0xA5
FSR1H = 0x05
FSR1L = 0xA5
FSR2H = 0x05
FSR2L = 0xA5
After Instruction
FSR0H = 0x0F
FSR0L = 0xE3
FSR1H = 0x05
FSR1L = 0xA5
FSR2H = 0x05
FSR2L = 0xA5
Example 3 LFSR 1, 0xFE3 ; Load the 12-bit FSR1 with
; FE3h
Before Instruction
FSR0H = 0x05
FSR0L = 0xA5
FSR1H = 0x05
FSR1L = 0xA5
FSR2H = 0x05
FSR2L = 0xA5
After Instruction
FSR0H = 0x05
FSR0L = 0xA5
FSR1H = 0x0F
FSR1L = 0xE3
FSR2H = 0x05
FSR2L = 0xA5
39500 18C Reference Manual.book Page 83 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-84 2000 Microchip Technology Inc.
MOVF Move f
Syntax: [ label ] MOVF f, d, a
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: f → destination
Status Affected: Z, N
Encoding: 0101 00da ffff ffff
Description: The contents of Register 'f' is moved to a destination dependent upon the
status of the ’d’ and ’a’ bits.
The ’d’ bit selects the destination for the operation.
If 'd' is 1; the result is stored back in the File Register 'f'.
If 'd' is 0; the result is stored in the WREG Register.
The ’a’ bit selects which bank is accessed for the operation.
If ’a’ is 1; the bank specified by the BSR Register is used.
If ’a’ is 0; the access bank is used.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
literal 'k'
Process
data
Write to
WREG
Register
Example 1 MOVF MYREG, 0, 1 ; Copy the contents of
; Register MYREG to the WREG
; Register
Before Instruction
MYREG = 0x22
WREG = 0xFF
Z, N = x
After Instruction
MYREG = 0x22
WREG = 0x22
Z =0
N =0
Example 2 MOVF MYREG, 1, 1 ; Copy the contents of
; Register MYREG to itself
; (affects the status bits)
Before Instruction
MYREG = 0x00
WREG = 0x10
Z, N = x
After Instruction
MYREG = 0x00
WREG = 0x10
Z =1
N =0
39500 18C Reference Manual.book Page 84 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-85
Section 31. Instruction Set
Instruction Set
31
Example 3 MOVF MYREG, 1, 0 ; Copy the contents of
; Register MYREG in the
; access bank to itself
; (affects the status bits)
Case 1: Before Instruction
MYREG = 0x00
WREG = 0x10
Z, N = x
After Instruction
MYREG = 0x00
WREG = 0x10
Z =1
N =0
; In access bank
; In access bank
Case 2: Before Instruction
MYREG = 0x80
WREG = 0x10
Z, N = x
After Instruction
MYREG = 0x80
WREG = 0x10
Z =0
N =1
; In access bank
; In access bank
39500 18C Reference Manual.book Page 85 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-86 2000 Microchip Technology Inc.
MOVFF Move f to f
Syntax: [ label ] MOVFF fs, fd
Operands: 0 ≤ fs ≤ 4095
0 ≤ fd ≤ 4095
Operation: (fs) → fd
Status Affected: None
Encoding:
1st word (source)
2nd word
(destination)
1100
1111
ffff
ffff
ffff
ffff
ffff
ffff
Description: The contents of Source Register 'f
s' are moved to Destination Register 'fd'.
Location of source 'fs' can be anywhere in the 4096 byte data space (000h
to FFFh), and location of destination 'fd' can also be anywhere from 000h to
FFFh.
MOVFF is particularly useful for transferring a data memory location to a
Peripheral Register (such as the transmit buffer or an I/O port) without
affecting the WREG Register.
Note: The MOVFF instruction cannot use the PCL, TOSU, TOSH, and
TOSL as the Destination Register
Words: 2
Cycles: 2
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
Source
Register f
Process
data
No
operation
Decode No
operation
No
operation
Write to
destination
Register f
Example 1 MOVFF REG1, REG2 ; Copy the contents of
; Register REG1 to Register
; REG2
Before Instruction
REG1 = 0x33
REG2 = 0x11
After Instruction
REG1 = 0x33
REG2 = 0x33
Example 2 MOVFF REG2, REG1 ; Copy the contents of
; Register REG2 to Register
; REG1
Before Instruction
REG1 = 0x33
REG2 = 0x11
After Instruction
REG1 = 0x11
REG2 = 0x11
39500 18C Reference Manual.book Page 86 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-87
Section 31. Instruction Set
Instruction Set
31
MOVLB Move Literal to low nibble in BSR
Syntax: [ label ] MOVLB k
Operands: 0 ≤ k ≤ 15
Operation: k → BSR<3:0>
Status Affected: None
Encoding: 0000 0001 0000 kkkk
Description: The 4-bit literal 'k' is loaded into the Bank Select Register (BSR).
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
literal 'k'
Process
data
Write
literal ’k’
to BSR
Example 1 MOVLB 5 ; Modify Least Significant
; nibble of BSR Register
; to value 5
Before Instruction
BSR = 0x02
After Instruction
BSR = 0x05
Example 2 MOVLB 9 ; Modify Least Significant
; nibble of BSR Register
; to value 9
Before Instruction
BSR = 0x0F
After Instruction
BSR = 0x09
39500 18C Reference Manual.book Page 87 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-88 2000 Microchip Technology Inc.
MOVLW Move Literal to WREG
Syntax: [ label ] MOVLW k
Operands: 0 ≤ k ≤ 255
Operation: k → WREG
Status Affected: None
Encoding: 0000 1110 kkkk kkkk
Description: The eight bit literal 'k' is loaded into WREG Register.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
literal 'k'
Process
data
Write to
WREG
Register
Example 1 MOVLW 0x5A ; Load the WREG Register
; with the value 5Ah
Before Instruction
WREG = x
After Instruction
WREG = 0x5A
Example 2 MOVLW MYREG ; Load the WREG Register
; with the value of the
; address of MYREG
Before Instruction
WREG = 0x10
Address of MYREG † = 0x37
† MYREG is a symbol for a data memory location
After Instruction
WREG = 0x37
Example 3 MOVLW HIGH (LU_TABLE) ; Load the WREG Register
; with the value of the high
; byte of address LU_TABLE
Before Instruction
WREG = 0x10
Address of LU_TABLE † = 0x9375
† LU_TABLE is a label for an address in program memory
After Instruction
WREG = 0x93
39500 18C Reference Manual.book Page 88 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-89
Section 31. Instruction Set
Instruction Set
31
MOVWF Move WREG to f
Syntax: [ label ] MOVWF f, a
Operands: 0 ≤ f ≤ 255
a ∈ [0,1]
Operation: (WREG) → f
Status Affected: None
Encoding: 0110 111a ffff ffff
Description: Move data from WREG Register to Register 'f'.
The ’a’ bit selects which bank is accessed for the operation.
If ’a’ is 1; the bank specified by the BSR Register is used.
If ’a’ is 0; the access bank is used.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
WREG
Register
Process
data
Write
Register 'f'
Example 1 MOVWF OPTION_REG, 1; Copy the value in the WREG
; Register to the
; OPTION_REG Register
Before Instruction
OPTION_REG = 0xFF
WREG = 0x4F
After Instruction
OPTION_REG = 0x4F
WREG = 0x4F
Example 2 MOVWF INDF0, 1 ; Copy the value in the WREG
; Register to the
; FSR0 (FSR0H:FSR0L)
; Register
Before Instruction
WREG = 0x17
FSR0 = 0x5C2
Contents of Address (FSR0) = 0x00
After Instruction
WREG = 0x17
FSR0 = 0x5C2
Contents of Address (FSR0) = 0x17
39500 18C Reference Manual.book Page 89 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-90 2000 Microchip Technology Inc.
MULLW Multiply Literal with WREG
Syntax: [ label ] MULLW k
Operands: 0 ≤ k ≤ 255
Operation: (WREG) x k → PRODH:PRODL
Status Affected: None
Encoding: 0000 1101 kkkk kkkk
Description: An unsigned multiplication is carried out between the contents of WREG
and the 8-bit literal 'k'. The 16-bit result is placed in PRODH:PRODL Register
Pair. PRODH contains the high byte.
WREG is unchanged.
None of the status flags are affected.
Neither an overflow nor carry is possible in this operation. A zero result is
possible but not detected.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
literal 'k'
Process
data
Write
Registers
PRODH:
PRODL
Example 1 MULLW 0xC4 ; Multiply the WREG Register
; with the constant value
; C4h
Before Instruction
WREG = 0xE2
PRODH = x
PRODL = x
After Instruction
WREG = 0xE2
PRODH = 0xAD
PRODL = 0x08
Example 2 MULLW FACTOR ; Multiply the WREG Register
; with the constant value
; FACTOR
Before Instruction
FACTOR = 0xC4
WREG = 0xE2
PRODH = x
PRODL = x
After Instruction
WREG = 0xE2
PRODH = 0xAD
PRODL = 0x08
39500 18C Reference Manual.book Page 90 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-91
Section 31. Instruction Set
Instruction Set
31
MULWF Multiply WREG with f
Syntax: [ label ] MULWF f, a
Operands: 0 ≤ f ≤ 255
a ∈ [0,1]
Operation: (WREG) x (f) → PRODH:PRODL
Status Affected: None
Encoding: 0000 001a ffff ffff
Description: An unsigned multiplication is carried out between the contents of WREG
and the value in Register File Location 'f'. The 16-bit result is placed in the
PRODH:PRODL Register Pair. PRODH contains the high byte.
Both WREG and 'f' are unchanged.
None of the status flags are affected.
Neither an overflow nor carry is possible in this operation. A zero result is
possible but not detected.
The ’a’ bit selects which bank is accessed for the operation.
If ’a’ is 1; the bank specified by the BSR Register is used.
If ’a’ is 0; the access bank is used.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
Register 'f'
Process
data
Write
Registers
PRODH:
PRODL
Example MULWF MYREG, 1 ; Multiple the WREG
; Register with the value
; in MYREG Register
Before Instruction
WREG = 0xE2
MYREG = 0xB5
PRODH = x
PRODL = x
After Instruction
WREG = 0xE2
MYREG = 0xB5
PRODH = 0x9F
PRODL = 0xCA
39500 18C Reference Manual.book Page 91 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-92 2000 Microchip Technology Inc.
NEGF Negate f
Syntax: [ label ] NEGF f, a
Operands: 0 ≤ f ≤ 255
a ∈ [0,1]
Operation: ( f )+1 → (f)
Status Affected: C, DC, Z, OV, N
Encoding: 0110 110a ffff ffff
Description: Location ’f’ is negated using two’s complement. The result is placed in the
data memory location 'f'.
The ’a’ bit selects which bank is accessed for the operation.
If ’a’ is 1; the bank specified by the BSR Register is used.
If ’a’ is 0; the access bank is used.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
Register 'f'
Process
data
Write
Register ’f’
Example 1 NEGF MYREG, 1 ; 2’s complement the value in
; MYREG
Case 1: Before Instruction
MYREG = 0x3A
C, DC, Z, OV, N = x
After Instruction
MYREG = 0xC6
C =0
DC = 0
Z =0
OV = 0
N =1
; 0011 1010
; 1100 0110
Case 2: Before Instruction
MYREG = 0xB0
C, DC, Z, OV, N = x
After Instruction
MYREG = 0x50
C =0
DC = 1
Z =0
OV = 0
N =0
; 1011 0000
; 0101 0000
Case 3: Before Instruction
MYREG = 0x00
C, DC, Z, OV, N = x
After Instruction
MYREG = 0x00
C =1
DC = 1
Z =1
OV = 0
N =0
; 0000 0000
; 0000 0000
39500 18C Reference Manual.book Page 92 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-93
Section 31. Instruction Set
Instruction Set
31
NOP No Operation
Syntax: [ label ] NOP
Operands: None
Operation: No operation
Status Affected: None
Encoding:
Default
Used with 2 word
instructions
0000
1111
0000
xxxx
0000
xxxx
0000
xxxx
Description: No operation.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode No
operation
No
operation
No
operation
Example HERE NOP ; This instruction cycle
; does nothing
; (No Operation)
Before Instruction
PC = address HERE
After Instruction
PC = address HERE + 2
39500 18C Reference Manual.book Page 93 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-94 2000 Microchip Technology Inc.
POP POP Top of Return Stack
Syntax: [ label ] POP
Operands: None
Operation: (TOS) → bit bucket
Status Affected: None
Encoding: 0000 0000 0000 0110
Description: The Top of Stack (TOS) value is pulled off the return stack and is discarded.
The TOS value then becomes the previous value that was pushed onto the
return stack.
This instruction is provided to enable the user to manage the return stack to
incorporate a software stack.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode No
operation
No
operation
POP TOS
value
Example HERE POP ; Modify the Top of Stack
; (TOS). The TOS points to
; what was one level down
Before Instruction
TOS = 0x0031A2
Stack (1 level down) = 0x014332
After Instruction
TOS = 0x014332
PC = HERE + 2
39500 18C Reference Manual.book Page 94 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-95
Section 31. Instruction Set
Instruction Set
31
PUSH PUSH Top of Return Stack
Syntax: [ label ] PUSH
Operands: None
Operation: PC → (TOS)
Status Affected: None
Encoding: 0000 0000 0000 0101
Description: The previous Top of Stack (TOS) value is pushed down on the stack. The
PC is pushed onto the top of the return stack.
This instruction is provided to enable the user to manage the return stack to
incorporate a software stack.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode PUSH PC
onto return
stack
No
operation
No
operation
Example HERE PUSH ; PUSH current Program
; Counter value onto the
; hardware stack
Before Instruction
PC = 0x000124
TOS = 0x00345A
After Instruction
PC = 0x000126
TOS = 0x000124
Stack (1 level down)
= 0x00345A
39500 18C Reference Manual.book Page 95 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-96 2000 Microchip Technology Inc.
RCALL Relative Call
Syntax: [ label ] RCALL n
Operands: -1024 ≤ n ≤ 1023
Operation: (PC + 2) → TOS,
(PC + 2) + 2n → PC
Status Affected: None
Encoding: 1101 1nnn nnnn nnnn
Description: Subroutine call with a jump up to 1K from the current location. First, the
return address (PC+2) is pushed onto the stack. Then the 2’s complement
number ’2n’ is added to the PC. Since the PC will have incremented to fetch
the next instruction, the new address will be PC+2+2n. This instruction is a
two-cycle instruction.
Words: 1
Cycles: 2
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
literal ’n’,
Push PC
to stack
Process
Data
Write to
PC
No
operation
No
operation
No
operation
No
operation
Example 1 HERE RCALL Sub1 ; Call a program memory
; location (Sub1)
; this location must be
; < 1024 locations forward or
; > 1025 locations backward
Before Instruction
PC = Address (HERE)
TOS = 0x0031A2
After Instruction
PC = Address (Sub1)
TOS = Address (HERE + 2)
Stack (1 level down)
= 0x0031A2
Example 2 HERE
PLUS0
PLUS1
PLUS2
PLUS3
PLUS4
PLUS5
PLUS6
RCALL
•
•
•
•
•
•
•
$ + OFFSET ; Call to HERE+OFFSET
Before Instruction
PC = address HERE
After Instruction
PC = address HERE + OFFSET
39500 18C Reference Manual.book Page 96 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-97
Section 31. Instruction Set
Instruction Set
31
Example 3 MIN6
MIN5
MIN4
MIN3
MIN2
MIN1
MIN0
HERE
NEXT
•
•
•
•
•
•
•
RCALL $ - OFFSET
; Call to HERE-OFFSET
Before Instruction
PC = address HERE
After Instruction
PC = address HERE - OFFSET
39500 18C Reference Manual.book Page 97 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-98 2000 Microchip Technology Inc.
RESET Reset Device
Syntax: [ label ] RESET
Operands: None
Operation: Force all registers and flag bits
that are affected by a MCLR reset
to their reset condition.
Status Affected: All
Encoding: 0000 0000 1111 1111
Description: This instruction provides a way to execute a software reset.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode No
operation
No
operation
Start
reset
39500 18C Reference Manual.book Page 98 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-99
Section 31. Instruction Set
Instruction Set
31
Example HERE RESET ; Do a software reset
Before Instruction
PC = address HERE
C, DC, Z, OV, N = x
After Instruction
PC = 0x000000
SFRs = See reset section
GPRs = u (unchanged)
39500 18C Reference Manual.book Page 99 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-100 2000 Microchip Technology Inc.
RETFIE Return from Interrupt
Syntax: [ label ] RETFIE s
Operands: s ∈ [0,1]
Operation: (TOS) → PC,
if IPEN = 0 (compatibility mode)
1 → GIE
if IPEN = 1
GIEH GEIL
1 11 → Invalid
1 01 → GIEL
0 11 → GIEH
0 01 → GIEH
if s = 1
(WREGS) → WREG
(STATUSS) → STATUS
(BSRS) → BSR
if s = 0
(WREGS) → unchanged
(STATUSS) → unchanged
(BSRS) → unchanged
In both cases PCLATU, PCLATH are unchanged.
Status Affected: GIE/GIEH,PEIE/GIEL
Encoding: 0000 0000 0001 000s
Description: Return from Interrupt. Stack is popped and Top of Stack (TOS) is loaded
into the PC. Interrupts are enabled by setting either the high or low priority
global interrupt enable bits (GIEH or GIEL).
If ’s’ = 1, the contents of the Shadow Registers WREGS, STATUSS and
BSRS are loaded into their corresponding registers, WREG, STATUS
and BSR.
If ’s’ = 0, no update of these registers occurs (default).
Words: 1
Cycles: 2
Q Cycle Activity:
1st cycle:
Q1 Q2 Q3 Q4
Decode No
operation
Set GIEH
or GIEL
POP PC
from stack
2nd cycle:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
39500 18C Reference Manual.book Page 100 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-101
Section 31. Instruction Set
Instruction Set
31
Example 1 HERE RETFIE 0 ; Return from interrupt,
; enable interrupts
Before Instruction
PC = address HERE
GIE/GIEH, PEIE/GIEL = x
WREG = x
BSR = x
STATUS = x
After Instruction
PC = TOS
GIE/GIEH, PEIE/GIEL = 1
WREG = unchanged
BSR = unchanged
STATUS = unchanged
Example 2 HERE RETFIE 1 ; Return from interrupt,
; enable interrupts.
; This is a fast return so
; the BSR, WREG, and STATUS
; Registers are restored
; with the values in the
; Fast Register Stack
Before Instruction
PC = address HERE
GIE/GIEH, PEIE/GIEL = x
WREG = x
BSR = x
STATUS = x
After Instruction
PC = TOS
GIE/GIEH, PEIE/GIEL = 1
WREG = WREGS
BSR = BSRS
STATUS = STATUSS
39500 18C Reference Manual.book Page 101 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-102 2000 Microchip Technology Inc.
RETLW Return with Literal in W
Syntax: [ label ] RETLW k
Operands: 0 ≤ k ≤ 255
Operation: k → WREG;
TOS → PC
PCLATU and PCLATH are unchanged
Status Affected: None
Encoding: 0000 1100 kkkk kkkk
Description: The WREG Register is loaded with the eight bit literal 'k'. The program
counter is loaded from the Top of Stack (the return address). The upper and
high address latches (PCLATU:PCLATH) remain unchanged. This is a twocycle
instruction.
Words: 1
Cycles: 2
Q Cycle Activity:
1st cycle:
Q1 Q2 Q3 Q4
Decode Read
literal 'k'
Process
data
POP PC
from stack,
write to
WREG
2nd cycle:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
39500 18C Reference Manual.book Page 102 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-103
Section 31. Instruction Set
Instruction Set
31
Example HERE
TABLE
CALL
•
•
•
ADDWF
RETLW
RETLW
•
•
•
RETLW
TABLE
PC
k1
k2
kn
; WREG contains table offset
; value WREG now has table
; value
; WREG = offset
; Begin table,
; Return with constant in WREG
; End of table
Before Instruction
WREG = x
After Instruction
WREG = value of kx
PC = TOS = Address HERE + 2
39500 18C Reference Manual.book Page 103 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-104 2000 Microchip Technology Inc.
RETURN Return from Subroutine
Syntax: [ label ] RETURN s
Operands: s ∈ [0,1]
Operation: (TOS) → PC
if s = 1
(WREGS) → WREG
(STATUSS) → STATUS
(BSRS) → BSR
if s = 0
(WREGS) → unchanged
(STATUSS) → unchanged
(BSRS) → unchanged
In both cases PCLATU and PCLATH are unchanged
Status Affected: None
Encoding: 0000 0000 0001 001s
Description: Return from subroutine. The stack is popped and the Top of Stack
(TOS) is loaded into the program counter.
If ’s’ = 1, the contents of the Shadow Registers WREGS, STATUSS and
BSRS are loaded into their corresponding registers, WREG, STATUS
and BSR.
If ’s’ = 0, no update of these registers occurs (default).
Words: 1
Cycles: 2
Q Cycle Activity:
1st cycle:
Q1 Q2 Q3 Q4
Decode No
operation
Process
data
POP PC
from stack
2nd cycle:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
Example 1 HERE RETURN 0 ; Return from subroutine.
Before Instruction
PC = address HERE
WREG = x
BSR = x
STATUS = x
After Instruction
PC = TOS
WREG = unchanged
BSR = unchanged
STATUS = unchanged
39500 18C Reference Manual.book Page 104 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-105
Section 31. Instruction Set
Instruction Set
31
Example 2 HERE RETURN 1 ; Return from subroutine.
; This is a fast return so
; the BSR, WREG, and STATUS
; Registers are restored
; with the values in the
; Fast Register Stack
Before Instruction
PC = address HERE
WREG = x
BSR = x
STATUS = x
After Instruction
PC = TOS
WREG = WREGS
BSR = BSRS
STATUS = STATUSS
39500 18C Reference Manual.book Page 105 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-106 2000 Microchip Technology Inc.
RLCF Rotate Left f through Carry
Syntax: [ label ] RLCF f, d, a
Operands: 0 ≤ f ≤ 127
d ∈ [0,1]
a ∈ [0,1]
Operation: See description below
Status Affected: C, Z, N
Encoding: 0011 01da ffff ffff
Description: The contents of Register 'f' are rotated one bit to the left through the Carry
Flag.
The ’d’ bit selects the destination for the operation.
If 'd' is 1; the result is stored back in the File Register 'f'.
If 'd' is 0; the result is stored in the WREG Register.
The ’a’ bit selects which bank is accessed for the operation.
If ’a’ is 1; the bank specified by the BSR Register is used.
If ’a’ is 0; the access bank is used.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
Register 'f'
Process
data
Write to
destination
C Register f
Example 1 RLCF REG1, 0, 1 ; Rotate the value in REG1
; 1 bit position left and
; the carry bit loads into
; bit 0. Then place the
; result in the WREG
; Register
Before Instruction
REG1 = 1110 0110
C = 0
Z, N = x
After Instruction
REG1 = 1110 0110
WREG = 1100 1100
C = 1
Z = 0
N = 1
39500 18C Reference Manual.book Page 106 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-107
Section 31. Instruction Set
Instruction Set
31
Example 2 RLF INDF0, 1, 1 ; Rotate the value in the
; register pointed by the
; FSR0 (FSR0H:FSR0L)
; Register 1 bit position
; left and place the result
; back into that register
; Carry loads into bit 0
Case 1: Before Instruction
FSR0 = 0x0C2
Contents of Address
(FSR0) = 0011 1010
C = 1
Z, N = x
After Instruction
FSR0 = 0x0C2
Contents of Address
(FSR0) = 0111 0101
C = 0
Z = 0
N = 0
Case 2: Before Instruction
FSR0 = 0x0C2
Contents of Address
(FSR0) = 1011 1001
C = 0
Z, N = x
After Instruction
FSR0 = 0x0C2
Contents of Address
(FSR0) = 0111 0010
C = 1
Z = 0
N = 0
39500 18C Reference Manual.book Page 107 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-108 2000 Microchip Technology Inc.
RLNCF Rotate Left f (No Carry)
Syntax: [ label ] RLNCF f, d, a
Operands: 0 ≤ f ≤ 127
d ∈ [0,1]
a ∈ [0,1]
Operation: See description below
Status Affected: Z, N
Encoding: 0100 01da ffff ffff
Description: The contents of Register 'f' are rotated one bit to the left. The Carry Flag
bit is not affected.
The ’d’ bit selects the destination for the operation.
If 'd' is 1; the result is stored back in the File Register 'f'.
If 'd' is 0; the result is stored in the WREG Register.
The ’a’ bit selects which bank is accessed for the operation.
If ’a’ is 1; the bank specified by the BSR Register is used.
If ’a’ is 0; the access bank is used.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
Register 'f'
Process
data
Write to
destination
Example 1 RLNCF REG1, 0, 1 ; Rotate the value in REG1
; 1 bit position left and
; bit 7 loads into bit 0.
; Then place the result in
; the WREG Register
Before Instruction
REG1 = 1110 0110
Z, N = x
After Instruction
REG1 = 1110 0110
WREG = 1100 1101
Z = 0
N = 1
Register f
39500 18C Reference Manual.book Page 108 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-109
Section 31. Instruction Set
Instruction Set
31
Example 2 RLNCF INDF0, 1, 1 ; Rotate the value in the
; register pointed by the
; FSR0 (FSR0H:FSR0L)
; Register 1 bit position left
; and place the result in the
; back into that register.
; bit 7 loads into bit 0.
Case 1: Before Instruction
FSR0 = 0x1C2
Contents of Address
(FSR0) = 0011 1010
Z, N = x
After Instruction
FSR0 = 0x1C2
Contents of Address
(FSR0) = 0111 0100
Z = 0
N = 0
Case 2: Before Instruction
FSR0 = 0x1C2
Contents of Address
(FSR0) = 1011 1001
Z, N = x
After Instruction
FSR0 = 0x1C2
Contents of Address
(FSR0) = 0111 0011
Z = 0
N = 0
39500 18C Reference Manual.book Page 109 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-110 2000 Microchip Technology Inc.
RRCF Rotate Right f through Carry
Syntax: [ label ] RRCF f, d, a
Operands: 0 ≤ f ≤ 127
d ∈ [0,1]
a ∈ [0,1]
Operation: See description below
Status Affected: C, Z, N
Encoding: 0011 00da ffff ffff
Description: The contents of Register 'f' are rotated one bit to the right through the Carry
Flag.
The ’d’ bit selects the destination for the operation.
If 'd' is 1; the result is stored back in the File Register 'f'.
If 'd' is 0; the result is stored in the WREG Register.
The ’a’ bit selects which bank is accessed for the operation.
If ’a’ is 1; the bank specified by the BSR Register is used.
If ’a’ is 0; the access bank is used.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
Register 'f'
Process
data
Write to
destination
C Register f
Example 1 RRCF REG1, 0, 1 ; Rotate the value in REG1
; 1 bit position right and
; the carry bit loads into
; bit 7. Then place the
; result in the WREG
; Register
Before Instruction
REG1 = 1110 0110
WREG = xxxx xxxx
C = 0
Z, N = x
After Instruction
REG1 = 1110 0110
WREG = 0111 0011
C = 0
Z = 0
N = 0
39500 18C Reference Manual.book Page 110 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-111
Section 31. Instruction Set
Instruction Set
31
Example 2 RRCF INDF0, 1, 1 ; Rotate the value in the
; register pointed by the
; FSR0 (FSR0H:FSR0L)
; Register 1 bit position
; right and place the result
; in the back into that
; register.
; Carry loads into bit 7.
Case 1: Before Instruction
FSR0 = 0x2C2
Contents of Address
(FSR0) = 0011 1010
C =1
Z, N = x
After Instruction
FSR0 = 0x2C2
Contents of Address
(FSR0) = 1001 1101
C =0
Z = 0
N = 1
Case 2: Before Instruction
FSR0 = 0x2C2
Contents of Address
(FSR0) = 0011 1001
C =0
Z, N = x
After Instruction
FSR0 = 0x2C2
Contents of Address
(FSR0) = 0001 1100
C =1
Z =0
N =0
39500 18C Reference Manual.book Page 111 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-112 2000 Microchip Technology Inc.
RRNCF Rotate Right f (No Carry)
Syntax: [ label ] RRNCF f, d, a
Operands: 0 ≤ f ≤ 127
d ∈ [0,1]
a ∈ [0,1]
Operation: See description below
Status Affected: Z, N
Encoding: 0100 00da ffff ffff
Description: The contents of Register 'f' are rotated one bit to the right. The Carry Flag
bit is not affected.
The ’d’ bit selects the destination for the operation.
If 'd' is 1; the result is stored back in the File Register 'f'.
If 'd' is 0; the result is stored in the WREG Register.
The ’a’ bit selects which bank is accessed for the operation.
If ’a’ is 1; the bank specified by the BSR Register is used.
If ’a’ is 0; the access bank is used.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
Register 'f'
Process
data
Write to
destination
Example 1 RRNCF REG1, 0, 1 ; Rotate the value in REG1
; 1 bit position right and
; bit 0 loads into bit 7.
; Then place the result in
; the WREG Register
Before Instruction
REG1 = 1110 0110
WREG = x
Z, N = 1
After Instruction
REG1 = 1110 0110
WREG = 0111 0011
Z =0
N =0
Register f
39500 18C Reference Manual.book Page 112 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-113
Section 31. Instruction Set
Instruction Set
31
Example 2 RRNCF INDF0, 1, 1 ; Rotate the value in the
; register pointed by the
; FSR (FSR0H:FSR0L)
; Register 1 bit
; position right and place
; the result back into
; that register.
; bit 0 loads into bit 7.
Case 1: Before Instruction
FSR0 = 0x3C2
Contents of Address
(FSR0) = 0011 1010
Z, N = x
After Instruction
FSR0 = 0x3C2
Contents of Address
(FSR0) = 0001 1101
Z =0
N =0
Case 2: Before Instruction
FSR0 = 0x3C2
Contents of Address
(FSR0) = 0011 1001
Z, N = x
After Instruction
FSR0 = 0x3C2
Contents of Address
(FSR0) = 1001 1100
Z =0
N =1
39500 18C Reference Manual.book Page 113 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-114 2000 Microchip Technology Inc.
SETF Set f
Syntax: [ label ] SETF f, a
Operands: 0 ≤ f ≤ 255
a ∈ [0,1]
Operation: FFh → f
Status Affected: None
Encoding: 0110 100a ffff ffff
Description: The contents of the specified register are set.
The ’a’ bit selects which bank is accessed for the operation.
If ’a’ is 1; the bank specified by the BSR Register is used.
If ’a’ is 0; the access bank is used.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
Register 'f'
Process
data
Write
Register 'f'
Example 1 SETF FLAG_REG, 1 ; Set all the bits in
; Register FLAG_REG
Before Instruction
FLAG_REG = 0x5A
After Instruction
FLAG_REG = 0xFF
Example 2 SETF INDF0, 1 ; Set all the bits in the
; register pointed to by the
; FSR (FSR0H:FSR0L) Register
Before Instruction
FSR0 = 0x4C2
Contents of Address
(FSR0) = 0xAA
After Instruction
FSR0 = 0x4C2
Contents of Address
(FSR0) = 0xFF
39500 18C Reference Manual.book Page 114 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-115
Section 31. Instruction Set
Instruction Set
31
SLEEP Enter SLEEP mode
Syntax: [ label ] SLEEP
Operands: None
Operation: 00h → WDT,
0 → WDT prescaler count,
1 → TO,
0 → PD
Status Affected: TO, PD
Encoding: 0000 0000 0000 0011
Description: The power-down status bit, PD is cleared. Time-out status bit, TO is set.
Watchdog Timer and its prescaler count are cleared.
The processor is put into SLEEP mode with the oscillator stopped.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode No
operation
No
operation
Go to
sleep
Example: SLEEP ; Turn off the device
; oscillator. This is the
; lowest power mode
Before Instruction
TO = ?
PD = ?
After Instruction
TO = 1 †
PD = 0
† If WDT causes wake-up, this bit is cleared
Note: The SLEEP instruction does not affect the assignment of the WDT prescaler.
39500 18C Reference Manual.book Page 115 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-116 2000 Microchip Technology Inc.
SUBFWB Subtract f from WREG with borrow
Syntax: [ label ] SUBFWB f, d, a
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (WREG) – (f) – (C) → destination
Status Affected: C, DC, Z, OV, N
Encoding: 0101 01da ffff ffff
Description: Subtract Register 'f' and carry flag (borrow) from W (2’s complement
method).
The ’d’ bit selects the destination for the operation.
If 'd' is 1; the result is stored back in the File Register 'f'.
If 'd' is 0; the result is stored in the WREG Register.
The ’a’ bit selects which bank is accessed for the operation.
If ’a’ is 1; the bank specified by the BSR Register is used.
If ’a’ is 0; the access bank is used.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
Register ’f’
Process
data
Write to
destination
Example 1 SUBFWB MYREG, 1, 1 ; WREG - MYREG - borrow bit
Before Instruction
MYREG = 0x37
WREG = 0x10
C, DC, Z, OV, N = x
C =0
After Instruction
MYREG = 0xA8
WREG = 0x10
C =0
DC = 0
Z =0
OV = 0
N =1
; result is negative
39500 18C Reference Manual.book Page 116 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-117
Section 31. Instruction Set
Instruction Set
31
Example 2: SUBFWB MYREG, 1, 1 ; WREG - MYREG - borrow bit
Case 1: Before Instruction
MYREG = 0x03
WREG = 0x02
C =1
DC, Z, OV, N = x
After Instruction
MYREG = 0xFF
WREG = 0x02
C =0
DC = 0
Z =0
OV = 0
N =1 ; result is negative
Case 2: Before Instruction
MYREG = 0x02
WREG = 0x02
C =1
DC, Z, OV, N = x
After Instruction
MYREG = 0x00
WREG = 0x02
C =1
DC = 1
Z =1
OV = 0
N =0
; result is zero
Case 3: Before Instruction
MYREG = 0x01
WREG = 0x03
C =1
DC, Z, OV, N = x
After Instruction
MYREG = 0x02
WREG = 0x03
C =1
DC = 1
Z =0
OV = 0
N =0
; result is positive
39500 18C Reference Manual.book Page 117 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-118 2000 Microchip Technology Inc.
SUBLW Subtract W from Literal
Syntax: [ label ] SUBLW k
Operands: 0 ≤ k ≤ 255
Operation: k - (WREG) → WREG
Status Affected: C, DC, Z, OV, N
Encoding: 0000 1000 kkkk kkkk
Description: The WREG Register is subtracted (2’s complement method) from the eight
bit literal 'k'. The result is placed in the WREG Register.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
literal 'k'
Process
data
Write to
WREG
Register
Example 1 SUBLW OFFSET ; Subtract the value in
; WREG from the constant
; OFFSET
Before Instruction
WREG = 0x37
OFFSET = 0x10
C, DC, Z, OV, N = x
After Instruction
WREG = 0xD9
C =0
DC = 0
Z =0
OV = 0
N =1
; result is negative
39500 18C Reference Manual.book Page 118 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-119
Section 31. Instruction Set
Instruction Set
31
Example 2: SUBLW 0x02 ; Subtract WREG Register
; from 2h
Case 1: Before Instruction
WREG = 0x01
C, DC, Z, OV, N = x
After Instruction
WREG = 0x01
C =1
DC = 1
Z =0
OV = 0
N =0
; result is positive
Case 2: Before Instruction
WREG = 0x02
C, DC, Z, OV, N = x
After Instruction
WREG = 0x00
C =1
DC = 1
Z =1
OV = 0
N =0
; result is zero
Case 3: Before Instruction
WREG = 0x03
C, DC, Z, OV, N = x
After Instruction
WREG =
0xFF
C =0
DC = 0
Z =0
OV = 0
N =1
; result is negative
39500 18C Reference Manual.book Page 119 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-120 2000 Microchip Technology Inc.
SUBWF Subtract W from f
Syntax: [ label ] SUBWF f, d, a
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (f) - (WREG) → destination
Status Affected: C, DC, Z, OV, N
Encoding: 0101 11da ffff ffff
Description: Subtract (2’s complement method) WREG Register from Register 'f'.
The ’d’ bit selects the destination for the operation.
If 'd' is 1; the result is stored back in the File Register 'f'.
If 'd' is 0; the result is stored in the WREG Register.
The ’a’ bit selects which bank is accessed for the operation.
If ’a’ is 1; the bank specified by the BSR Register is used.
If ’a’ is 0; the access bank is used.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
Register 'f'
Process
data
Write to
destination
Example 1: SUBWF REG1, 1, 1 ; Subtract the value in the
; WREG Register from REG1,
; placing the result in REG1
Case 1: Before Instruction
REG1 = 3
WREG = 2
C, DC, Z, OV, N = x
After Instruction
REG1 = 1
WREG = 2
C =1
DC = 1
Z =0
OV = 0
N =0
; result is positive
39500 18C Reference Manual.book Page 120 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-121
Section 31. Instruction Set
Instruction Set
31
Case 2: Before Instruction
REG1 = 2
WREG = 2
C, DC, Z, OV, N = x
After Instruction
REG1 = 0
WREG = 2
C =1
DC = 1
Z =1
OV = 0
N =0
; result is zero
Case 3: Before Instruction
REG1 = 1
WREG = 2
C, DC, Z, OV, N = x
After Instruction
REG1 = 0xFF
WREG = 2
C =0
DC = 0
Z =0
OV = 0
N =1
; result is negative
39500 18C Reference Manual.book Page 121 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-122 2000 Microchip Technology Inc.
SUBWFB Subtract W from f with Borrow
Syntax: [ label ] SUBWFB f, d, a
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (f) - (WREG) - (C) → destination
Status Affected: C, DC, Z, OV, N
Encoding: 0101 10da ffff ffff
Description: Subtract (2’s complement method) WREG Register from Register 'f' with
borrow.
The ’d’ bit selects the destination for the operation.
If 'd' is 1; the result is stored back in the File Register 'f'.
If 'd' is 0; the result is stored in the WREG Register.
The ’a’ bit selects which bank is accessed for the operation.
If ’a’ is 1; the bank specified by the BSR Register is used.
If ’a’ is 0; the access bank is used.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
Register 'f'
Process
data
Write to
destination
Example 1: SUBWF REG1, 1, 1 ; Subtract the value in the
; WREG Register from REG1,
; placing the result in REG1
Case 1: Before Instruction
REG1 = 3
WREG = 2
C =1
DC, Z, OV, N = x
After Instruction
REG1 = 1
WREG = 2
C =1
DC = 1
Z =0
OV = 0
N =0
; result is positive
39500 18C Reference Manual.book Page 122 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-123
Section 31. Instruction Set
Instruction Set
31
Case 2: Before Instruction
REG1 = 2
WREG = 2
C =1
DC, Z, OV, N = x
After Instruction
REG1 = 0
WREG = 2
C =1
DC = 1
Z =1
OV = 0
N =0
; result is zero
Case 3: Before Instruction
REG1 = 1
WREG = 2
C =1
DC, Z, OV, N = x
After Instruction
REG1 = 0xFF
WREG = 2
C =0
DC = 0
Z =0
OV = 0
N =1
; result is negative
39500 18C Reference Manual.book Page 123 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-124 2000 Microchip Technology Inc.
SWAPF Swap Nibbles in f
Syntax: [ label ] SWAPF f, d, a
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (f<3:0>) → destination<7:4>,
(f<7:4>) → destination<3:0>
Status Affected: None
Encoding: 0011 10da ffff ffff
Description: The upper and lower nibbles of Register 'f' are exchanged.
The ’d’ bit selects the destination for the operation.
If 'd' is 1; the result is stored back in the File Register 'f'.
If 'd' is 0; the result is stored in the WREG Register.
The ’a’ bit selects which bank is accessed for the operation.
If ’a’ is 1; the bank specified by the BSR Register is used.
If ’a’ is 0; the access bank is used.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
Register 'f'
Process
data
Write to
destination
Example 1 SWAPF REG1, 0, 1 ; Swap the high and low
; nibble of Register REG1
; and place the result in
; the WREG Register
Before Instruction
REG1 = 0xA5
WREG = x
After Instruction
REG1 = 0xA5
WREG = 0x5A
39500 18C Reference Manual.book Page 124 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-125
Section 31. Instruction Set
Instruction Set
31
Example 2 SWAPF INDF0, 1, 1 ; Swap the high and low
; nibble of register pointed
; to by the FSR
; (FSR0H:FSR0L) Register,
; placing the result back
; into that register
Before Instruction
FSR0 = 0x5C2
Contents of Address
(FSR0) = 0x20
After Instruction
FSR0 = 0x5C2
Contents of Address
(FSR0) = 0x02
Example 3 SWAPF REG1, 1, 1 ; Swap the high and low
; nibble of Register REG1
; placing the result back
; into that register
Before Instruction
REG1 = 0xA5
After Instruction
REG1 = 0x5A
39500 18C Reference Manual.book Page 125 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-126 2000 Microchip Technology Inc.
TBLRD Table Read
Syntax: [ label ] TBLRD[*, *+, *-, or +*]
Operands: 0 ≤ m ≤ 3
Operation: if TBLRD *,
(Prog Mem (TBLPTR)) → TABLAT;
TBLPTR - No Change;
if TBLRD *+,
(Prog Mem (TBLPTR)) → TABLAT;
(TBLPTR) +1 → TBLPTR;
if TBLRD *-,
(Prog Mem (TBLPTR)) → TABLAT;
(TBLPTR) -1 → TBLPTR;
if TBLRD +*,
(TBLPTR) +1 → TBLPTR;
(Prog Mem (TBLPTR)) → TABLAT;
Status Affected: None
Encoding: 0000 0000 0000 10mm * → mm = 00
*+ → mm = 01
*- → mm = 10
+* → mm = 11
Description: This instruction is used to read the contents of Program Memory. To
address the program memory a pointer called Table Pointer (TBLPTR) is
used.
The TBLPTR (a 21-bit pointer) points to each byte in the program memory.
TBLPTR has a 2 Mbyte address range. The LSb of the TBLPTR selects
which byte of the program memory location to access.
TBLPTR[0] = 0: Least Significant byte of Program Memory Word
TBLPTR[0] = 1: Most Significant byte of Program Memory Word
The Program Memory word address is the same as the TBLPTR address,
except that the LSb of TBLPTR (TBLPTR[0]) is always forced to ’0’.
The TBLRD instruction can modify the value of TBLPTR as follows:
• no change
• post-increment
• post-decrement
• pre-increment
Words: 1
Cycles: 2
Q Cycle Activity:
1st cycle:
Q1 Q2 Q3 Q4
Decode No
operation
No
operation
No
operation
2nd cycle:
No
operation
No
operation
(Table
Pointer on
Address
bus)
No
operation
No
operation
(OE goes
low)
39500 18C Reference Manual.book Page 126 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-127
Section 31. Instruction Set
Instruction Set
31
Example 31-3:Program Memory Contents for Examples
Word Address
(points to low byte)
Data Word Word Address
(points to low byte)
Data Word
MSb LSb MSb LSb
0x00A356 0x12 0x34 0x000000 0x01 0x00
0x00A358 0x56 0x28 0x000002 0x03 0x02
0x00A35A 0xAA 0x55 0x000004 0x05 0x04
0x00A35C 0xFF 0xFE 0x000006 0x07 0x06
0x00A35E 0xB1 0x00 0x000008 0x08 0x07
Example 1 TBLRD*+ ; Read byte addressed by
; TBLPTR, then increment
; TBLPTR
Before Instruction
TABLAT = x
TBLPTR = 0x00A356
Contents of Address (TBLPTR)= 0x34
After Instruction
TABLAT = 0x34
TBLPTR = 0x00A357
Example 2 TBLRD+* ; Increment TBLPTR, then
; Read byte addressed by
; TBLPTR
Before Instruction
TABLAT = x
TBLPTR = 0x00A357
Contents of Address (TBLPTR)= 0x12
Contents of Address (TBLPTR + 1)= 0x28
After Instruction
TABLAT = 0x28
TBLPTR = 0x00A358
Example 3 TBLRD*- ; Read byte addressed by
; TBLPTR, then decrement
; TBLPTR
Before Instruction
TABLAT = x
TBLPTR = 0x00A357
Contents of Address (TBLPTR)= 0x12
After Instruction
TABLAT = 0x12
TBLPTR = 0x00A356
Example 4 TBLRD* ; Read byte addressed by
; TBLPTR. TBLPTR is unchanged
Before Instruction
TABLAT = x
TBLPTR = 0x00A357
Contents of Address (TBLPTR)= 0x12
After Instruction
TABLAT = 0x12
TBLPTR = 0x00A357
39500 18C Reference Manual.book Page 127 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-128 2000 Microchip Technology Inc.
TBLWT Table Write
Syntax: [ label ] TBLWT[*, *+, *-, +*]
Operands: 0 ≤ m ≤ 3
Operation: if TBLWT*,
(TABLAT) → Prog Mem (TBLPTR) or Holding Register1;
TBLPTR - No Change;
if TBLWT*+,
(TABLAT) → Prog Mem (TBLPTR) or Holding Register1;
(TBLPTR) +1 → TBLPTR;
if TBLWT*-,
(TABLAT) → Prog Mem (TBLPTR) or Holding Register1;
(TBLPTR) -1 → TBLPTR;
if TBLWT+*,
(TBLPTR) +1 → TBLPTR;
(TABLAT) → Prog Mem (TBLPTR) or Holding Register1;
Note 1: The use of a Holding Register(s) is device specific. Please refer
to the Device Data Sheet for information on the operation of the
TBLWT instruction with the Program Memory.
Status Affected: None
Encoding: 0000 0000 0000 11mm * → mm = 00
*+ → mm = 01
*- → mm = 10
+* → mm = 11
Description: This instruction is used to program the contents of Program Memory. To
address the program memory a pointer called Table Pointer (TBLPTR) is
used.
The TBLPTR (a 21-bit pointer) points to each byte in the program memory.
TBLPTR has a 2 MBtye address range. The LSb of the TBLPTR selects
which byte of the program memory location to access.
TBLPTR[0] = 0: Least Significant byte of Program Memory Word
TBLPTR[0] = 1: Most Significant byte of Program Memory Word
The Program Memory word address is the same as the TBLPTR address,
except that the LSb of TBLPTR (TBLPTR[0]) is always forced to ’0’.
The TBLWT instruction can modify the value of TBLPTR as follows:
• no change
• post-increment
• post-decrement
• pre-increment
Words: 1
Cycles: 2 (many if long write to internal program memory)
Q Cycle Activity:
1st cycle:
Q1 Q2 Q3 Q4
Decode No
operation
No
operation
No
operation
2nd cycle:
No
operation
No
operation
(Table Pointer
on Address
bus)
No
operation
No
operation
(Table Latch on
Address bus,
WR goes low)
39500 18C Reference Manual.book Page 128 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-129
Section 31. Instruction Set
Instruction Set
31
Example 31-4:Program Memory Contents for Examples
Word Address
(points to low byte)
Original
Data Word
(before)
Example 1
Data Word
(after)
Example 2
Data Word
(after)
Example 3
Data Word
(after)
Example 4
Data Word
(after)
MSb LSb MSb LSb MSb LSb MSb LSb MSb LSb
0x00A356 0x12 0x34 0x12 0x55 0x12 0x34 0xAA 0x34 0x12 0x34
0x00A358 0x56 0x28 0x56 0x28 0x56 0xAA 0x56 0x28 0x5A 0x28
0x00A35A 0xAA 0x55 0xAA 0x55 0xAA 0x55 0xAA 0x55 0xAA 0x55
TABLAT 0x55 0xAA 0xAA 0x5A
Example 1 TBLWT*+ ; Write byte addressed by
; TBLPTR, then increment TBLPTR
Before Instruction
TABLAT = 0x55
TBLPTR = 0x00A356
Contents of (TBLPTR) = 0x34
After Instruction
TBLPTR = 0x00A357
Contents of (TBLPTR) = 0x55
Example 2 TBLWT+* ; Increment TBLPTR, then Write
; byte addressed by TBLPTR
Before Instruction
TABLAT = 0xAA
TBLPTR = 0x00A357
Contents of (TBLPTR) = 0x12
Contents of (TBLPTR + 1) = 0x28
After Instruction
TBLPTR = 0x00A358
Contents of (TBLPTR) = 0x12
Contents of (TBLPTR + 1) = 0xAA
Example 3 TBLWT*- ; Write byte addressed by
; TBLPTR, then decrement TBLPTR
Before Instruction
TABLAT = 0xAA
TBLPTR = 0x00A357
Contents of (TBLPTR) = 0x12
After Instruction
TBLPTR = 0x00A356
Contents of (TBLPTR) = 0xAA
Example 4 TBLWT* ; Write byte addressed by
; TBLPTR. TBLPTR is unchanged
Before Instruction
TABLAT = 0x5A
TBLPTR = 0x00A359
Contents of (TBLPTR) = 0x56
After Instruction
TBLPTR = 0x00A359
Contents of (TBLPTR) = 0x5A
39500 18C Reference Manual.book Page 129 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-130 2000 Microchip Technology Inc.
TSTFSZ Test f, Skip if 0
Syntax: [ label ] TSTFSZ f, a
Operands: 0 ≤ f ≤ 255
a ∈ [0,1]
Operation: Skip if (f) = 0
Status Affected: None
Encoding: 0110 011a ffff ffff
Description: If Register 'f' = 0, the next instruction fetched is discarded and a NOP is
executed (two NOPs if the fetched instruction is a two-cycle instruction).
The ’a’ bit selects which bank is accessed for the operation.
If ’a’ is 1; the bank specified by the BSR Register is used.
If ’a’ is 0; the access bank is used.
Words: 1
Cycles: 1 (2 or 3)
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
Register 'f'
Process
data
Write to
destination
If skip (2nd cycle):
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
If skip and followed by a two word instruction:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
Example 1A HERE
NZERO
ZERO
TSTFSZ
•
•
REG1, 1 ; If Register REG1 is zero
; then skip the next
; program memory address
Before Instruction
REG1 = 0xAF
PC = Address (HERE)
After Instruction
PC = Address (NZERO)
39500 18C Reference Manual.book Page 130 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-131
Section 31. Instruction Set
Instruction Set
31
Example 2 HERE
NZERO
ZERO
TSTFSZ
•
•
REG1, 1 ; If Register REG1 is zero
; then skip the next
; program memory address
Before Instruction
REG1 = 0x00
PC = Address (HERE)
After Instruction
PC = Address (ZERO)
Example 3 HERE
NZERO
ZERO
TSTFSZ
•
•
REG1, 0 ; If Register REG1 is zero
; then skip the next
; program memory address
Case 1 Before Instruction
REG1 = 0xAF
Address of REG1 = 0x9A, Bank 3
0x9A, Bank 15 = 0x00
PC = Address (HERE)
After Instruction
PC = Address (ZERO)
Case 2 Before Instruction
REG1 = 0x00
Address of REG1 = 0x9A, Bank 3
0x9A, Bank 15 = 0xAF
PC = Address (HERE)
After Instruction
PC = Address (NZERO)
Example 4 HERE
NZERO
ZERO
TSTFSZ
•
•
INDF0, 1 ; If Register pointed to by
; FSR0 (FSR0H:FSR0L) is
; zero, then skip the next
; program memory address
Case 1 Before Instruction
FSR0 = 0x6C2
Contents of Address
(FSR0) = 0xAF
PC = Address (HERE)
After Instruction
FSR0 = 0x6C2
Contents of Address
(FSR0) = 0xAF
PC = Address (NZERO)
Case 2 Before Instruction
FSR0 = 0x6C2
Contents of Address (FSR0) = 0x00
PC = Address (HERE)
After Instruction
FSR0 = 0x6C2
Contents of Address (FSR0) = 0x00
PC = Address (ZERO)
39500 18C Reference Manual.book Page 131 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-132 2000 Microchip Technology Inc.
XORLW Exclusive OR Literal with W
Syntax: [ label] XORLW k
Operands: 0 ≤ k ≤ 255
Operation: (WREG).XOR. k → W
Status Affected: Z, N
Encoding: 0000 1010 kkkk kkkk
Description: The contents of the WREG Register are XOR’ed with the eight bit literal 'k'.
The result is placed in the WREG Register.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
literal 'k'
Process
data
Write to
WREG
Register
Example 1 XORLW 0xAF ; Exclusive OR the value
; in WREG with AFh
Before Instruction
WREG = 0xB5
Z, N = x
; 1011 0101 (0xB5)
; 1010 1111 (0xAF)
After Instruction ; --------- ------
WREG = 0x1A
Z =0
N =0
; 0001 1010 (0x1A)
Example 2 XORLW MYREG ; Exclusive OR the value
; in WREG with the address
; of MYREG
Before Instruction
WREG = 0xAF
Address of MYREG †
= 0x37
Z, N = x
† MYREG is a symbol for a
data memory location
After Instruction
WREG = 0x98
Z =0
N =1
; 1010 1111
;
; 0011 0111
; ---- ----
; 1001 1000
39500 18C Reference Manual.book Page 132 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-133
Section 31. Instruction Set
Instruction Set
31
Example 3 XORLW HIGH (LU_TABLE) ; Exclusive OR the value
; in WREG with the high
; byte of the address of
; LU_TABLE
Before Instruction
WREG = 0xAF
Address of LU_TABLE †
= 0x9375
Z, N = x
† LU_TABLE is a label for an
address in program memory
After Instruction
WREG = 0x3C
Z =0
N =0
;
; 1010 1111
;
; 1001 0011
; ---- ----
;
;
;
; 0011 1100
39500 18C Reference Manual.book Page 133 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-134 2000 Microchip Technology Inc.
XORWF Exclusive OR W with f
Syntax: [ label ] XORWF f, d, a
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (WREG).XOR. (f) → destination
Status Affected: Z, N
Encoding: 0001 10da ffff ffff
Description: Exclusive OR the contents of the WREG Register with Register 'f'.
The ’d’ bit selects the destination for the operation.
If 'd' is 1; the result is stored back in the File Register 'f'.
If 'd' is 0; the result is stored in the WREG Register.
The ’a’ bit selects which bank is accessed for the operation.
If ’a’ is 1; the bank specified by the BSR Register is used.
If ’a’ is 0; the access bank is used.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
Register 'f'
Process
data
Write to
destination
Example 1 XORWF REG1, 1, 1 ; Exclusive OR the value
; in WREG with the value in
; REG1
Before Instruction
REG1 = 0xAF
WREG = 0xB5
Z, N = x
; 1010 1111 (0xAF)
; 1011 0101 (0xB5)
; --------- ------
After Instruction
REG1 = 0x1A
WREG = 0xB5
Z =0
N =0
; 0001 1010 (0x1A)
39500 18C Reference Manual.book Page 134 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-135
Section 31. Instruction Set
Instruction Set
31
Example 2 XORWF REG1, 0, 1 ; Exclusive OR the value
; in WREG with the value in
; REG1. Place result in
; WREG
Before Instruction
REG1 = 0xAF
WREG = 0xB5
Z, N = x
; 1010 1111 (0xAF)
; 1011 0101 (0xB5)
; --------- ------
After Instruction
REG1 = 0xAF
WREG = 0x1A
Z =0
N =0
;
; 0001 1010 (0x1A)
Example 3 XORWF INDF0, 1, 1 ; Exclusive OR the value
; in WREG with the value
; pointed to by the FSR0
; (FSR0H:FSR0L) Register
Before Instruction
WREG = 0xB5
FSR0 = 0x7C2
Contents of Address
(FSR0) = 0xAF
Z, N = x
After Instruction
WREG = 0xB5
FSR0 = 0x7C2
Contents of Address
(FSR0) = 0x1A
Z =0
N =0
;
; 1011 0101
;
;
; 1010 1111
;
;
;
;
;
; 0001 1010
;
;
Example 4 XORWF REG1, 1, 0 ; Exclusive OR the value
; in WREG with the value
; at address REG1 in the
; access bank. Place
; result in access bank
Before Instruction
WREG = 0xF8
REG1 = 0x01
Contents of Address
(REG1) in access bank
= 0xAA
Z, N = x
After Instruction
WREG = 0xF8
REG1 = 0x01
Contents of Address
(REG1) in access bank
= 0x52
Z =0
N =0
;
; 1111 1000
; 0000 0001
;
;
; 1010 1010
;
;
;
;
;
;
; 0101 0010
;
;
39500 18C Reference Manual.book Page 135 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-136 2000 Microchip Technology Inc.
31.8 Design Tips
Question 1: I have seen references to “Read-Modify-Write” instructions in your data
sheet, but I do not know what that is. Can you explain what it is and why I
need to know this?
Answer 1:
An easy example of a Read-Modify-Write (or R-M-W) instruction is the bit clear instruction BCF.
You might think that the processor just clears the bit, which on a port output pin would clear the
pin. What actually happens is the whole port (or register) is first read, THEN the bit is cleared,
then the new modified value is written back to the port (or register). Actually, any instruction that
depends on a value currently in the register is going to be a Read-Modify-Write instruction. This
includes ADDWF, SUBWF, BCF, BSF, INCF, XORWF, etc... Instructions that do not depend
on the current register value, like MOVWF, CLRF, and so on are not R-M-W instructions.
One situation where you would want to consider the affects of a R-M-W instruction is a port that
is continuously changed from input to output and back. For example, say you have TRISB set to
all outputs, and write all ones to the PORTB Register, all of the PORTB pins will go high. Now,
say you turn pin RB3 into an input, which happens to go low. A BCF PORTB,6 is then executed
to drive pin RB6 low. If you then turn RB3 back into an output, it will now drive low, even though
the last value you put there was a one. What happened was that the BCF of the other pin (RB6)
caused the whole port to be read, including the zero on RB3 when it was an input. Then, bit 6
was changed as requested, but since RB3 was read as a zero, zero will also be placed back into
that port latch, overwriting the one that was there before. When the pin is turned back into an
output, the new value was reflected. Try using the LATx register instead of the PORTx register
for this read-modify-write operation.
Question 2: When I perform a BCF, other pins get cleared in the port. Why?
Answer 2:
There are a few possibilities, two are:
1. Another case where a R-M-W instruction may seem to change other pin values unexpectedly
can be illustrated as follows: Suppose you make PORTC all outputs and drive the
pins low. On each of the port pins is an LED connected to ground, such that a high output
lights it. Across each LED is a 100 µF capacitor. Let's also suppose that the processor is
running very fast, say 20 MHz. Now if you go down the port setting each pin in order; BSF
PORTC,0 then BSF PORTC,1 then BSF PORTC,2 and so on, you may see that only the
last pin was set, and only the last LED actually turns on. This is because the capacitors
take a while to charge. As each pin was set, the pin before it was not charged yet and so
was read as a zero. This zero is written back out to the port latch (R-M-W, remember)
which clears the bit you just tried to set the instruction before. This is usually only a concern
at high speeds and for successive port operations, but it can happen, so take it into
consideration.
2. If this is on a PIC16C7X device, you may not have configured the I/O pins properly in the
ADCON1 Register. If a pin is configured for analog input, any read of that pin will read a
zero, regardless of the voltage on the pin. This is an exception to the normal rule that the
pin state is always read. You can still configure an analog pin as an output in the TRIS
Register, and drive the pin high or low by writing to it, but you will always read a zero.
Therefore, if you execute a Read-Modify-Write instruction (see previous question), all
analog pins are read as zero, and those not directly modified by the instruction will be written
back to the port latch as zero. A pin configured as analog is expected to have values
that may be neither high nor low to a digital pin, or floating. Floating inputs on digital pins
are a no-no, and can lead to high current draw in the input buffer, so the input buffer is
disabled.
39500 18C Reference Manual.book Page 136 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39532A-page 31-137
Section 31. Instruction Set
Instruction Set
31
31.9 Related Application Notes
This section lists application notes that are related to this section of the manual. These application
notes may not be written specifically for the Enhanced family (that is they may be written for
the Baseline, the Mid-Range, or High-End families), but the concepts are pertinent, and could be
used (with modification and possible limitations). The current application notes related to the
Instruction Set are:
Title Application Note #
No related Application Notes at this time.
Note: Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
http://www.microchip.com/10/faqs/codeex/
39500 18C Reference Manual.book Page 137 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39532A-page 31-138 2000 Microchip Technology Inc.
31.10 Revision History
Revision A
This is the initial released revision of the Enhanced MCU Instruction Set description.
39500 18C Reference Manual.book Page 138 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39533A-page 32-1
Electrical
Specifications
32
Section 32. Electrical Specifications
HIGHLIGHTS
32.1 Introduction .................................................................................................................. 32-2
32.2 Absolute Maximums..................................................................................................... 32-3
32.3 Voltage vs Frequency Graph........................................................................................ 32-4
32.4 Device Voltage Specifications ...................................................................................... 32-6
32.5 Device Current Specifications...................................................................................... 32-7
32.6 Input Threshold Levels............................................................................................... 32-10
32.7 I/O Current Specifications .......................................................................................... 32-11
32.8 Output Drive Levels.................................................................................................... 32-12
32.9 I/O Capacitive Loading............................................................................................... 32-13
32.10 Low Voltage Detect (LVD) .......................................................................................... 32-14
32.11 EPROM/FLASH/Data EEPROM ................................................................................ 32-15
32.12 Comparators and Voltage Reference......................................................................... 32-16
32.13 Timing Parameter Symbology.................................................................................... 32-18
32.14 Example External Clock Timing Waveforms and Requirements................................ 32-19
32.15 Example Phase Lock Loop (PLL) Timing Waveforms and Requirements ................. 32-20
32.16 Example Power-up and RESET Timing Waveforms and Requirements.................... 32-22
32.17 Example Timer0 and Timer1 Timing Waveforms and Requirements......................... 32-23
32.18 Example CCP Timing Waveforms and Requirements ............................................... 32-24
32.19 Example Parallel Slave Port (PSP) Timing Waveforms and Requirements ............... 32-25
32.20 Example SSP and Master SSP SPI Mode Timing Waveforms and Requirements.... 32-26
32.21 Example SSP I2C Mode Timing Waveforms and Requirements................................ 32-30
32.22 Example Master SSP I2C Mode Timing Waveforms and Requirements.................... 32-32
32.23 Example USART/SCI Timing Waveforms and Requirements.................................... 32-34
32.24 CAN Specifications .................................................................................................... 32-35
32.25 Example 8-bit A/D Timing Waveforms and Requirements ......................................... 32-36
32.26 Example 10-bit A/D Timing Waveforms and Requirements ....................................... 32-38
32.27 Design Tips ................................................................................................................ 32-40
32.28 Related Application Notes.......................................................................................... 32-41
32.29 Revision History ......................................................................................................... 32-42
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39533A-page 32-2 2000 Microchip Technology Inc.
32.1 Introduction
This section is intended to present the electrical specifications that may be specified in a particular
device data sheet and their meaning. This section is NOT intended to give the values of
these specifications. For the device specific values you must refer to the device’s data sheet. All
values shown in this section should be considered as Example Values.
In the description of the device and the functional modules (previous sections), there have been
references to electrical specification parameters. These references have been hyperlinked in the
electronic version to aid in the use of this manual.
Throughout this section, certain terms will be used. Table 32-1 shows the conventions that will
be used.
Table 32-1: Term Conventions
Note: Before starting any design, Microchip HIGHLY recommends that you acquire the
most recent copy of the device data sheet and review the electrical specifications to
ensure that they will meet your requirements.
Term Description
PIC18CXXX(1) For EPROM Program Memory devices tested to standard voltage
range
PIC18LCXXX(1) For EPROM Program Memory devices tested to extended voltage
range
PIC18FXXX(1) For FLASH Program Memory devices tested to standard voltage
range
PIC18LFXXX(1) For FLASH Program Memory devices tested to extended voltage
range
PIC18CRXXX(1) For ROM Program Memory devices tested to standard voltage range
PIC18LCRXXX(1) For ROM Program Memory devices tested to extended voltage range
LP osc For devices configured with the LP device oscillator selected
XT osc For devices configured with the XT device oscillator selected
HS osc For devices configured with the HS device oscillator selected
HS+PLL osc For devices configured with the HS+PLL device oscillator selected
RC osc For devices configured with the RC device oscillator selected
RCIO osc For devices configured with the RCIO device oscillator selected
EC osc For devices configured with the EC device oscillator selected
ECIO osc For devices configured with the ECIO device oscillator selected
Commercial For devices with the commercial temperature range grading
(0°C ≤ TA ≤ +70°C)
Industrial For devices with the industrial temperature range grading
(-40°C ≤ TA ≤ +85°C)
Extended For devices with the extended temperature range grading
(-40°C ≤ TA ≤ +125°C)
Note 1: In Electrical Specification examples, we will use PIC18CXXX for the standard voltage
range devices and PIC18LCXXX for the extended voltage range devices.
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39533A-page 32-3
Section 32. Electrical Specifications
Electrical
Specifications
32
32.2 Absolute Maximums
The Absolute Maximum Ratings specify the worst case conditions that can be applied to the
device. These ratings are not meant as operational specifications. Stresses above the listed values
may cause damage to the device. Specifications are not always stand-alone, that is, the
specification may have other requirements as well.
An example of this is the “maximum current sourced/sunk by any I/O pin”. The number of I/O pins
that can be sinking/sourcing current, at any one time, is dependent upon the maximum current
sunk/source by the port(s) (combined) and the maximum current into the VDD pin or out of the
VSS pin. In this example, the physical reason is the Power and Ground bus width to the I/O ports
and internal logic. If these specifications are exceeded, then electromigration may occur on these
Power and Ground buses. Over time, electromigration would cause these buses to open (be disconnected
from the pin) and, therefore, cause the logic attached to these buses to stop operating.
So, exceeding the absolute specifications may cause device reliability issues.
Input Clamp Current is defined as the current through the diode to VSS/VDD if pin voltage exceeds
specification.
Example Absolute Maximum Ratings †
Ambient temperature under bias............................................................................ -55 to +125°C
Storage temperature .......................................................................................... -65°C to +150°C
Voltage on any pin with respect to VSS (except VDD, MCLR, and RA4)..... -0.3V to (VDD + 0.3V)
Voltage on VDD with respect to VSS ........................................................................ -0.3 to +7.5V
Voltage on MCLR with respect to VSS (2) ................................................................. 0 to +13.25V
Voltage on RA4 with respect to Vss ............................................................................. 0 to +8.5V
Total power dissipation (1) .................................................................................................... 1.0W
Maximum current out of VSS pin ...................................................................................... 300 mA
Maximum current into VDD pin ......................................................................................... 250 mA
Input clamp current, IIK (VI < 0 or VI > VDD).................................................................... ± 20 mA
Output clamp current, IOK (VO < 0 or VO > VDD) ............................................................. ± 20 mA
Maximum output current sunk by any I/O pin..................................................................... 25 mA
Maximum output current sourced by any I/O pin ............................................................... 25 mA
Maximum current sunk by PORTA, PORTB, and PORTE (combined)............................. 200 mA
Maximum current sourced by PORTA, PORTB, and PORTE (combined) ....................... 200 mA
Maximum current sunk by PORTC and PORTD (combined) ........................................... 200 mA
Maximum current sourced by PORTC and PORTD (combined)...................................... 200 mA
Maximum current sunk by PORTF and PORTG (combined) ........................................... 100 mA
Maximum current sourced by PORTF and PORTG (combined) ...................................... 100 mA
Note 1: Power dissipation is calculated as follows:
Pdis = VDD x {IDD - IOH} + {(VDD - VOH)xIOH} + (VOlxIOL)
2: Voltage spikes below VSS at the MCLR/VPP pin, inducing currents greater than
80 mA, may cause latch-up. Thus, a series resistor of 50-100Ω should be used when
applying a “low” level to the MCLR/VPP pin, rather than pulling this pin directly to VSS.
† NOTICE: Stresses above those listed under “Absolute Maximum Ratings” may cause permanent
damage to the device. This is a stress rating only and functional operation of the
device at those or any other conditions above those indicated in the operation listings of this
specification is not implied. Exposure to maximum rating conditions for extended periods may
affect device reliability.
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39533A-page 32-4 2000 Microchip Technology Inc.
32.3 Voltage vs Frequency Graph
Windowed devices are superset devices with all oscillator configurations tested to the specification
ranges of the C and LC devices. The temperature range that the device is tested to should
be considered commercial, though at a later time, they may be tested to industrial or extended
temperature levels.
Figure 32-1 and Figure 32-2 show proposed voltage vs frequency graphs for the C and LC
devices.
Battery applications usually require an extended voltage range. Devices marked LC have an
extended voltage range.
Note: Devices that are designated Engineering Sample are tested to the current engineering
test program at time of the device testing. There is no implied warranty that these
devices have been tested to any or all specifications in the Device Data Sheet.
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39533A-page 32-5
Section 32. Electrical Specifications
Electrical
Specifications
32
The voltage vs frequency graphs show what is the maximum frequency of operation for a given
voltage. Figure 32-1 is for a C device, while Figure 32-2 is for an LC device. Notice that for
Figure 32-2, there is a slope from 6MHz to 40 MHz. An equation is given in the figure which will
allow you to calculate the maximum frequency of operation for a given voltage.
Figure 32-1: Example PIC18CXXX Voltage Frequency Graph
Figure 32-2: Example PIC18LCXXX Voltage Frequency Graph
Frequency
Voltage
6.0 V
5.5 V
4.5 V
4.0 V
2.0 V
40 MHz
5.0 V
3.5 V
3.0 V
2.5 V
PIC18CXXX
4.2V
Frequency
Voltage
6.0 V
5.5 V
4.5 V
4.0 V
2.0 V
40 MHz
5.0 V
3.5 V
3.0 V
2.5 V
PIC18LCXXX
FMAX = (20.0 MHz/V) (VDDAPPMIN - 2.5 V) + 6 MHz
6 MHz
4.2V
Note: VDDAPPMIN is the minimum voltage of the PICmicro® device in the application.
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39533A-page 32-6 2000 Microchip Technology Inc.
32.4 Device Voltage Specifications
These specifications relate to the device VDD, power-up, and function.
Supply Voltage is the voltage level that must be applied to the device VDD pins for the proper
functional operation.
RAM Data Retention Voltage is the minimum level that the device voltage may be at and still
retain the RAM’s data value.
VDD Start Voltage to ensure the internal Power-on Reset signal, is the level that VDD must start
from, to ensure that the POR circuitry will operate properly.
VDD Rise Rate to ensure internal Power-on Reset signal, is the minimum slope that VDD must
rise to cause the POR circuitry to trip.
Brown-out Reset Voltage is the voltage range where the brown-out circuitry may trip. When the
BOR circuitry trips, the device will either be in Brown-out Reset, or has just come out of
Brown-out Reset.
Table 32-2: Example DC Characteristics
DC CHARACTERISTICS
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
-40°C ≤ TA ≤ +125°C for extended
Param
No.
Symbol Characteristic Min Typ† Max Units Conditions
VDD Supply Voltage
D001 PIC18CXXX 4.2 — 5.5 V
PIC18LCXXX 2.5 — 5.5 V HS, XT, RC and LP osc mode
D002 VDR RAM Data Retention
Voltage (1)
1.5 — — V
D003 VPOR VDD Start Voltage to
ensure internal
Power-on Reset signal
— — 0.7 V See section on Power-on Reset for details
D004 SVDD VDD Rise Rate to
ensure internal
Power-on Reset signal
0.05 — — V/ms See section on Power-on Reset for details
VBOR Brown-out Reset
Voltage
D005 BORV1:BORV0 = 11 1.8 — 1.91 V For PIC18LCxxx VDDMIN = 1.8V
BORV1:BORV0 = 11 2.5 — 2.66 For PIC18LCxxx VDDMIN > 1.8V
BORV1:BORV0 = 10 2.7 — 2.86
BORV1:BORV0 = 01 4.2 — 4.46
BORV1:BORV0 = 00 4.5 — 4.78
D007 VBHYS Brown-out Hysteresis 30 — 100 mV
Note 1: This is the limit to which VDD can be lowered in SLEEP mode or during a device RESET without losing RAM
data.
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39533A-page 32-7
Section 32. Electrical Specifications
Electrical
Specifications
32
32.5 Device Current Specifications
IDD is referred to as supply current and is the current (I) consumed by the device when in operating
mode. This test is taken with all I/O as inputs, either pulled high or low. That is, there are
no floating inputs, nor are any pins driving an output (with a load).
IPD is referred to as power-down current and is the current (I) consumed by the device when in
SLEEP mode (power-down), referred to as power-down current. These tests are taken with all
I/O as inputs, either pulled high or low. That is, there are no floating inputs, nor are any pins driving
an output (with a load), weak pull-ups are disabled.
A device may have certain features and modules that can operate while the device is in SLEEP
mode. Some of these modules are:
• Watchdog Timer (WDT)
• Low Voltage Detect (LVD)
• Brown-out Reset (BOR) circuitry
• Timer1 Oscillator
• Analog to Digital converter
• Comparators
• Voltage Reference
• CAN Module
When all features are disabled, the device will consume the lowest possible current (the leakage
current). If any of these features are operating while the device is in SLEEP, a higher current will
occur. The difference in current between the lowest power mode (everything off) and only that
one feature enabled (such as the WDT), is what we call the Module Differential Current. If more
then one feature is enabled, then the expected current can easily be calculated as: the base current
(everything disabled and in SLEEP mode) plus all Module Differential Currents (delta currents).
Example 32-1 shows an example of calculating the typical currents for a device at 5V, with
the WDT and Timer1 oscillator enabled.
Example 32-1: IPD Calculations with WDT and Timer1 Oscillator Enabled (@ 5V)
Note: Some modules (such as the Brown-out Reset and Low Voltage Detect) use a common
resource (an internal reference voltage generator). This resource may consume
a significant percentage of the total modules current when enabled. Since 2
modules are using this, the total current will be less then the calculation.
Base Current 14 nA ; Device leakage current
WDT Delta Current 14 µA ; 14 µA - 14 nA = 14 µA
TMR1 Delta Current 22 µA ; 22 µA - 14 nA = 22 µA
Total SLEEP Current 36 µA ;
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39533A-page 32-8 2000 Microchip Technology Inc.
Table 32-3: Example DC Characteristics
DC CHARACTERISTICS
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
-40°C ≤ TA ≤ +125°C for extended
Param
No.
Symbol Characteristic Min Typ Max Units Conditions
D010
IDD Supply Current (2,4)
— — 4 µA XT, RC, RCIO osc configurations
FOSC = 4 MHz, VDD = 4.2V
D010A — — 48 mA LP osc configuration
FOSC = 32 kHz, VDD = 4.2V
D010C — — 45 mA EC, ECIO osc configurations,
Fosc = 40 MHz, VDD = 5.5V
D013 — — 50 mA HS osc configurations
Fosc = 25 MHz, VDD = 5.5V
D013 — — 50 mA HS4 osc configuration
Fosc = 10 MHz, VDD = 5.5V
D014
—
—
—
—
48
TBD
µA
µA
OSCB osc configuration
FOSC = 32 kHz, VDD = 4.2V
FOSC = 32 kHz, VDD = 4.2V, 25°C
IPD Power-down Current (3)
D020 —
—
<1
—
TBD
36
µA
µA
VDD = 4.2V, -40°C to +85°C
VDD = 5.5V, -40°C to +85°C
D020A — — TBD µA VDD = 4.2V, 25°C
D021B —
—
—
—
TBD
42
µA
µA
VDD = 4.2V, -40°C to +125°C
VDD = 5.5V, -40°C to +125°C
Legend: Shading of rows is to assist in readability of the table.
Note 1: Not applicable.
2: The supply current is mainly a function of the operating voltage and frequency. Other factors, such as I/O pin
loading and switching rate, oscillator type, internal code execution pattern and temperature, also have an
impact on the current consumption.
The test conditions for all IDD measurements in active operation mode are:
OSC1 = external square wave, from rail to rail; all I/O pins set to inputs, pulled to VDD
MCLR = VDD; WDT enabled/disabled as specified.
3: The power-down current in SLEEP mode does not depend on the oscillator type. Power-down current is
measured with the part in SLEEP mode, with all I/O pins set to inputs, tied to VDD or VSS, and all features
that add delta current disabled (such as WDT, Timer1 Oscillator, ...).
4: For RC osc configuration, current through REXT is not included. The current through the resistor can be estimated
by the formula Ir = VDD/2REXT (mA) with REXT in kOhm.
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39533A-page 32-9
Section 32. Electrical Specifications
Electrical
Specifications
32
Module Differential
Current
D022 ∆IWDT Watchdog Timer —
—
—
—
—
—
—
—
—
—
25
TBD
TBD
12
TBD
µA
µA
µA
µA
µA
VDD = 5.5V, -40°C to +85°C
VDD = 5.5V, -40°C to +125°C
VDD = 4.2V, 25°C
VDD = 2.5V
VDD = 2.5V, +25°C
D022A ∆IBOR Brown-out Reset —
—
—
—
—
—
—
—
—
—
50
TBD
TBD
12
TBD
µA
µA
µA
µA
µA
VDD = 5.5V, -40°C to +85°C
VDD = 5.5V, -40°C to +125°C
VDD = 4.2V, 25°C
VDD = 2.5V
VDD = 2.5V, +25°C
D022B ∆ILVD Low Voltage Detect —
—
—
—
—
—
—
—
—
—
TBD
TBD
TBD
50
TBD
µA
µA
µA
µA
µA
VDD = 4.2V, -40°C to +85°C
VDD = 4.2V, -40°C to +125°C
VDD = 4.2V, +25°C
VDD = 2.5V
VDD = 2.5V, +25°C
D022C ∆IDDC A/D Converter Current —
—
—
—
—
—
—
—
—
—
TBD
TBD
TBD
TBD
TBD
µA
µA
µA
µA
µA
VDD = 5.5V, -40°C to +85°C
VDD = 5.5V, -40°C to +125°C
VDD = 4.2V, 25°C
VDD = 2.5V
VDD = 2.5V, +25°C
D025 ∆IOSCB Timer1 Oscillator —
—
—
—
—
—
—
—
—
—
TBD
TBD
TBD
3
TBD
µA
µA
µA
µA
µA
VDD = 4.2V, -40°C to +85°C
VDD = 4.2V, -40°C to +125°C
VDD = 4.2V, 25°C
VDD = 2.5V
VDD = 2.5V, +25°C
Table 32-3: Example DC Characteristics (Continued)
DC CHARACTERISTICS
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
-40°C ≤ TA ≤ +125°C for extended
Param
No.
Symbol Characteristic Min Typ Max Units Conditions
Legend: Shading of rows is to assist in readability of the table.
Note 1: Not applicable.
2: The supply current is mainly a function of the operating voltage and frequency. Other factors, such as I/O pin
loading and switching rate, oscillator type, internal code execution pattern and temperature, also have an
impact on the current consumption.
The test conditions for all IDD measurements in active operation mode are:
OSC1 = external square wave, from rail to rail; all I/O pins set to inputs, pulled to VDD
MCLR = VDD; WDT enabled/disabled as specified.
3: The power-down current in SLEEP mode does not depend on the oscillator type. Power-down current is
measured with the part in SLEEP mode, with all I/O pins set to inputs, tied to VDD or VSS, and all features
that add delta current disabled (such as WDT, Timer1 Oscillator, ...).
4: For RC osc configuration, current through REXT is not included. The current through the resistor can be estimated
by the formula Ir = VDD/2REXT (mA) with REXT in kOhm.
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39533A-page 32-10 2000 Microchip Technology Inc.
32.6 Input Threshold Levels
The Input Low Voltage (VIL) is the maximum voltage level that will be read as a logic ’0’. An input
may not read a ’0’ at a voltage level above this. All designs should be to the specification, since
device to device (and to a much lesser extent pin to pin) variations will cause this level to vary.
The Input High Voltage (VIH) is the minimum voltage level that will be read as a logic ’1’. An input
may not read a ’1’ at a voltage level below this. All designs should be to the specification, since
device to device (and to a much lesser extent pin to pin) variations will cause this level to vary.
The I/O pins with TTL levels are shown with two specifications. One is the industry standard TTL
specification, which is specified for the voltage range of 4.5V to 5.5V. The other specifies operation
over the entire voltage range of the device. The better of these two specifications may be
used in the design (see Note 2 in Table 32-4).
Table 32-4: Example DC Characteristics
DC CHARACTERISTICS
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
-40°C ≤ TA ≤ +125°C for extended
Operating voltage VDD range as described in DC spec
Table 32-2.
Param
No.
Symbol Characteristic Min Max Units Conditions
VIL Input Low Voltage
I/O ports:
D030 with TTL buffer VSS 0.15VDD V For entire VDD range (2)
D030A — 0.8 V 4.5V ≤ VDD ≤ 5.5V (2)
D031 with Schmitt Trigger buffer
RC3 and RC4
VSS
VSS
0.2VDD
0.3VDD
V
V
D032 MCLR VSS 0.2VDD V
D032A OSC1 (in XT, HS and LP modes)
and T1OSI
VSS 0.3VDD V
D033 OSC1 (in RC mode) (1) VSS 0.2VDD V
VIH Input High Voltage
I/O ports:
D040 with TTL buffer 0.25VDD
+ 0.8V
VDD V For entire VDD range (2)
D040A 2.0 VDD V 4.5V ≤ VDD ≤ 5.5V (2)
D041 with Schmitt Trigger buffer
RC3 and RC4
0.8VDD
0.7VDD
VDD
VDD
V
V
D042 MCLR 0.8VDD VDD V
D042A OSC1 (in XT, HS and LP modes)
and T1OSI
0.7VDD VDD V
D043 OSC1 (RC mode) (1) 0.9VDD VDD V
D050 VHYS Hysteresis of Schmitt Trigger Inputs TBD TBD V
Note 1: In RC oscillator configuration, the OSC1/CLKIN pin is a Schmitt Trigger input. It is not recommended that
the PICmicro be driven with an external clock while in RC mode.
2: The better of the two specifications may be used. For VIL, this would be the higher voltage and for VIH, this
would be the lower voltage.
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39533A-page 32-11
Section 32. Electrical Specifications
Electrical
Specifications
32
32.7 I/O Current Specifications
The PORT Weak Pull-up Current is the additional current consumed when the weak pull-ups
are enabled.
Leakage Currents are the currents that the device consumes, since the devices are manufactured
in the real world and do not adhere to their ideal characteristics. Ideally, there should be no
current on an input, but due to the real world, there is always some parasitic path that consumes
negligible current.
Table 32-5: Example DC Characteristics
DC CHARACTERISTICS
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial and
-40°C ≤ TA ≤ +125°C for extended
Operating voltage VDD range as described in DC spec Table 32-2.
Param
No.
Symbol Characteristic Min Max Units Conditions
IIL Input Leakage Current (2,3)
D060 I/O ports — ±1 µA Vss ≤ VPIN ≤ VDD,
Pin at hi-impedance
D061 MCLR — ±5 µA Vss ≤ VPIN ≤ VDD
D063 OSC1 — ±5 µA Vss ≤ VPIN ≤ VDD
Weak Pull-up Current
D070 IPURB PORTB weak pull-up current 50 400 µA VDD = 5V, VPIN = VSS
Note 1: Not applicable.
2: The leakage current on the MCLR pin is strongly dependent on the applied voltage level. The specified
levels represent normal operating conditions. Higher leakage current may be measured at different input
voltages.
3: Negative current is defined as current sourced by the pin.
39500 18C Reference Manual.book Page 11 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39533A-page 32-12 2000 Microchip Technology Inc.
32.8 Output Drive Levels
The Output Low Voltage (VOL) is the pin’s output voltage for a low level. The VOL of an I/O pin
is dependent on the current sunk by that pin. If an I/O pin is shorted to VDD, no matter the drive
capability of the I/O pin, a low level would not be reached (and the device would consume excessive
drive current). The VOL is the output voltage that the I/O pin will drive, given the I/O does not
need to sink more then the IOL current (at the specified device voltage), as specified in the conditions
portion of the specification.
The Output High Voltage (VOH) is the pin’s output voltage for a high level. The VOH of an I/O pin
is dependent on the current sourced by that pin. If an I/O pin is shorted to VSS, no matter the drive
capability of the I/O pin, a high level would not be reached (and the device would consume excessive
drive current). The VOH is the output voltage that the I/O pin will drive, given the I/O does not
need to source more then the IOH current (at the specified device voltage), as specified in the
conditions portion of the specification.
Table 32-6: Example DC Characteristics
DC CHARACTERISTICS
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial and
-40°C ≤ TA ≤ +125°C for extended
Operating voltage VDD range as described in DC spec Table 32-2.
Param
No.
Symbol Characteristic Min Max Units Conditions
VOL Output Low Voltage
D080 I/O ports — 0.6 V IOL = 8.5 mA, VDD = 4.5V,
-40°C to +85°C
D080A — 0.6 V IOL = 7.0 mA, VDD = 4.5V,
-40°C to +125°C
D083 OSC2/CLKOUT
(RC mode)
— 0.6 V IOL = 1.6 mA, VDD = 4.5V,
-40°C to +85°C
D083A — 0.6 V IOL = 1.2 mA, VDD = 4.5V,
-40°C to +125°C
VOH Output High Voltage (1)
D090 I/O ports VDD - 0.7 — V IOH = -3.0 mA, VDD = 4.5V,
-40°C to +85°C
D090A VDD - 0.7 — V IOH = -2.5 mA, VDD = 4.5V,
-40°C to +125°C
D092 OSC2/CLKOUT
(RC mode)
VDD - 0.7 — V IOH = -1.3 mA, VDD = 4.5V,
-40°C to +85°C
D092A VDD - 0.7 — V IOH = -1.0 mA, VDD = 4.5V,
-40°C to +125°C
D150 VOD Open-drain High Voltage — 7.5 V RA4 pin
Note 1: Negative current is defined as current sourced by the pin.
39500 18C Reference Manual.book Page 12 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39533A-page 32-13
Section 32. Electrical Specifications
Electrical
Specifications
32
32.9 I/O Capacitive Loading
These loadings affect the specifications for the timing specifications. If the loading in your application
is different, then you will need to determine how this will affect the characteristics of the
device in your system. Capacitances less then these specifications should not have an effect on
a system.
Table 32-7: Example DC Characteristics
DC CHARACTERISTICS
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial and
-40°C ≤ TA ≤ +125°C for extended
Operating voltage VDD range as described in DC spec Table 32-2.
Param
No.
Symbol Characteristic Min Typ† Max Units Conditions
Capacitive Loading Specs
on Output Pins
D101 CIO All I/O pins and OSC2
(in RC mode)
— — 50 pF To meet the Timing Specifications
of the Device
D102 CB SCL, SDA — — 400 pF In I2C mode
39500 18C Reference Manual.book Page 13 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39533A-page 32-14 2000 Microchip Technology Inc.
32.10 Low Voltage Detect (LVD)
Low Voltage Detect is internal circuitry which will set a flag when the device voltage crosses the
specified trip point.
Figure 32-3: Low-Voltage Detect Characteristics
Table 32-8: Example Low Voltage Detect Requirements
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial and
-40°C ≤ TA ≤ +125°C for extended
Operating voltage VDD range as described in DC spec Table 32-2.
Param
No. Symbol Characteristic Min Max Units Conditions
D420 VLVD LVD Voltage LVDL3:LVDL0 = 0100 2.5 2.66 V
LVDL3:LVDL0 = 0101 2.7 2.86 V
LVDL3:LVDL0 = 0110 2.8 2.98 V
LVDL3:LVDL0 = 0111 3.0 3.2 V
LVDL3:LVDL0 = 1000 3.3 3.52 V
LVDL3:LVDL0 = 1001 3.5 3.72 V
LVDL3:LVDL0 = 1010 3.6 3.84 V
LVDL3:LVDL0 = 1011 3.8 4.04 V
LVDL3:LVDL0 = 1100 4.0 4.26 V
LVDL3:LVDL0 = 1101 4.2 4.46 V
LVDL3:LVDL0 = 1110 4.5 4.78 V
VLVD
LVDIF
VDD
(LVDIF set by hardware)
(LVDIF can be
cleared in software)
39500 18C Reference Manual.book Page 14 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39533A-page 32-15
Section 32. Electrical Specifications
Electrical
Specifications
32
32.11 EPROM/FLASH/Data EEPROM
Table 32-9 shows the specifications for programming of the internal EPROM program memory.
Table 32-10 shows the specifications of the FLASH program memory and Data EEPROM.
Table 32-9: Example Program Memory Programming Requirements
Table 32-10: Example Data EEPROM/Flash Characteristics
DC CHARACTERISTICS
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +40°C
Operating voltage VDD range as described in DC spec Table 32-2.
Param.
No. Sym Characteristic Min Max Units Conditions
Internal Program Memory
Programming Specs (1)
D110
D111
D112
D113
D114
D115
VPP
VDDP
IPP
IDDP
TPROG
TERASE
Voltage on MCLR/VPP pin
Supply voltage during
programming
Current into MCLR/VPP pin
Supply current during
programming
Programming pulse width
EPROM erase time
Device operation ≤ 3V
Device operation ≥ 3V
12.75
4.75
—
—
100
4
TBD
13.25
5.25
50
30
1000
—
—
V
V
mA
mA
µs
hrs
hrs
(Note 2)
Terminated via internal/external
interrupt or a RESET
See Table 32-3
See Table 32-3
Note 1: These specifications are for the programming of the on-chip program memory EEPROM through the use of
the table write instructions. The complete programming specifications can be found in: PIC18CXXX Programming
Specifications (Literature number DS39028).
2: The MCLR/VPP pin may be kept in this range at times other than programming, but is not recommended.
DC CHARACTERISTICS
Standard Operating Conditions (unless otherwise stated)
Operating temperature 0°C ≤ TA ≤ +70°C for commercial,
-40°C ≤ TA ≤ +85°C for industrial and
-40°C ≤ TA ≤ +125°C for extended
Operating voltage VDD range as described in DC spec Table 32-2.
Param
No. Symbol Characteristic Min Typ† Max Units Conditions
Data EEPROM Memory
D120 ED Endurance 1M 10M — E/W 25°C at 5V
D121 VDRW VDD for read/write VMIN — VMAX V VMIN = Minimum operating voltage
VMAX = Maximum operating voltage
D122 TDEW Erase/Write cycle time — — 10 ms
Program Flash Memory
D130 EP Endurance 100 1000 — E/W
D131 VPR VDD for read VMIN — VMAX V VMIN = Minimum operating voltage
VMAX = Maximum operating voltage
D132 VPEW VDD for erase/write 4.5 — 5.5 V
D133 TPEW Erase/Write cycle time — — 10 ms
† Data in “Typ” column is at 5.0V, 25°C unless otherwise stated. These parameters are for design guidance
only and are not tested.
Legend: E/W means Erase/Write cycles.
39500 18C Reference Manual.book Page 15 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39533A-page 32-16 2000 Microchip Technology Inc.
32.12 Comparators and Voltage Reference
Table 32-11: Example Comparator Characteristics
Table 32-12: Example Voltage Reference Characteristics
DC CHARACTERISTICS
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial and
-40°C ≤ TA ≤ +125°C for extended
Operating voltage VDD range as described in DC spec Table 32-2.
Param
No. Symbol Characteristics Min Max Units Comments
D300 VIOFF Input offset voltage — ± 10 mV
D301 VICM Input common mode voltage 0 VDD - 1.5 V
D302 CMRR Common Mode Rejection Ratio 35 — db
300 TRESP Response Time (1) PIC18CXXX — 400 ns
300A PIC18LCXXX — 600 ns
301 TMC2OV Comparator Mode Change to Output
Valid
— 10 µs
Note 1: Response time measured with one comparator input at (VDD - 1.5)/2, while the other input transitions from
VSS to VDD.
DC CHARACTERISTICS
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial and
-40°C ≤ TA ≤ +125°C for extended
Operating voltage VDD range as described in DC spec Table 32-2.
Param
No. Symbol Characteristics Min Typ Max Units Comments
D310 VRES Resolution VDD/24 — VDD/32 V
D311 VRAA Absolute Accuracy —
—
—
—
1/4
1/2
LSb
LSb
Low Range (VRR = 1)
High Range (VRR = 0)
D312 VRUR Unit Resistor Value (R) — 2k — Ω
310 TSET Settling Time (1) — — 10 µs
Note 1: Settling time measured while VRR = 1 and VR3:VR0 transitions from 0000 to 1111.
39500 18C Reference Manual.book Page 16 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39533A-page 32-17
Section 32. Electrical Specifications
Electrical
Specifications
32
Table 32-13: Example Fixed Voltage Reference Characteristics
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial and
-40°C ≤ TA ≤ +125°C for extended
Operating voltage VDD range as described in DC spec Table 32-2.
Param
No. Symbol Characteristic Min Typ Max Units Conditions
D400 VRL Output Voltage 2.0 2.048 2.1 V VDD ≥ 2.5V
VRH 4.0 4.096 4.2 V VDD ≥ 4.5V
D402 TCVOUT Ouput Voltage Drift — 15 50 ppm/°C (Note 1)
D403 En Output Noise Voltage — TBD — µVp-p 0.1 Hz to 10 Hz
— TBD — 10 Hz to 10 kHz
D404 IVREFSO External Load Source — — 5 mA
D405 IVREFSI External Load Sink — — -5 mA
D406 Load Regulation — — TBD
mV/mA
Isource = 0 mA to
5 mA
— — TBD Isink = 0 mA to
5 mA
D407 Line Regulation — — 50 µV/V
D401A VRL Quiescent Supply Current — 30 50 µA VRH, BOR, and LVD
disabled. No load on
VRL.
D401B VRH Quiescent Supply Current — 30 50 µA VRL, BOR, and LVD
disabled. No load on
VRH.
39500 18C Reference Manual.book Page 17 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39533A-page 32-18 2000 Microchip Technology Inc.
32.13 Timing Parameter Symbology
The timing parameter symbols have been created with one of the following formats:
Figure 32-4: Example Load Conditions
1. TppS2ppS 3. TCC:ST (I2C specifications only)
2. TppS 4. Ts (I2
C specifications only)
T
F Frequency T Time
Lowercase letters (pp) and their meanings:
pp
cc CCP1 osc OSC1
ck CLKOUT rd RD
cs CS rw RD or WR
di SDI sc SCK
do SDO ss SS
dt Data in t0 T0CKI
io I/O port t1 T1CKI
mc MCLR wr WR
Uppercase letters and their meanings:
S
F Fall P Period
H High R Rise
I Invalid (Hi-impedance) V Valid
L Low Z Hi-impedance
I
2
C only
AA Output Access High High
BUF Bus free Low Low
TCC:ST (I2C specifications only)
CC
HD Hold SU Setup
ST
DAT DATA input hold STO STOP condition
STA START condition
VDD/2
CL
RL
Pin Pin
VSS VSS
CL
RL = 464Ω
CL = 50 pF for all pins except OSC2/CLKOUT
(works for I/O pin multiplexed on to OSC2/CLKOUT)
Load Condition 1 Load Condition 2
39500 18C Reference Manual.book Page 18 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39533A-page 32-19
Section 32. Electrical Specifications
Electrical
Specifications
32
32.14 Example External Clock Timing Waveforms and Requirements
Figure 32-5: Example External Clock Timing Waveforms
Table 32-14: Example External Clock Timing Requirements
Param.
No. Symbol Characteristic Min Max Units Conditions
1A Fosc External CLKIN Frequency (1) DC 4 MHz XT osc
DC 40 MHz HS osc
4 10 MHz HS4 osc
DC
DC
40
40
kHz
MHz
LP osc
EC
Oscillator Frequency (1) DC 4 MHz RC osc
0.1 4 MHz XT osc
4 25 MHz HS osc
4 10 MHz HS4 osc
5 200 kHz LP osc mode
1 Tosc External CLKIN Period (1) 250 — ns XT and RC osc
40 — ns HS osc
100 — ns HS4 osc
5
5
—
—
µs
ns
LP osc
EC
Oscillator Period (1) 250 — ns RC osc
250 10,000 ns XT osc
100
40
10,000
100
ns
ns
HS osc
HS4 osc
5 — µs LP osc
2 TCY Instruction Cycle Time (1) 100 — ns TCY = 4/FOSC
3 TosL,
TosH
External Clock in (OSC1)
High or Low Time 30 — ns XT osc
2.5 — µs LP osc
10 — ns HS osc
4 TosR,
TosF
External Clock in (OSC1)
Rise or Fall Time
— 20 ns XT osc
— 50 ns LP osc
— 7.5 ns HS osc
Note 1: Instruction cycle period (TCY) equals four times the input oscillator time-base period. All specified values are
based on characterization data for that particular oscillator type under standard operating conditions with
the device executing code. Exceeding these specified limits may result in an unstable oscillator operation
and/or higher than expected current consumption. All devices are tested to operate at "min." values with an
external clock applied to the OSC1/CLKIN pin.
When an external clock input is used, the "Max." cycle time limit is "DC" (no clock) for all devices.
OSC1
CLKOUT
Q4 Q1 Q2 Q3 Q4 Q1
1
2
3 3 4 4
39500 18C Reference Manual.book Page 19 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39533A-page 32-20 2000 Microchip Technology Inc.
32.15 Example Phase Lock Loop (PLL) Timing Waveforms and Requirements
Table 32-15: Example PLL Clock Timing Specification (VDD = 4.2V - 5.5V)
Param
No. Symbol Characteristic Min Max Units Conditions
7 TPLL PLL Start-up Time
(Lock Time)
— 2 ms
∆CLK CLKOUT Stability (Jitter) using PLL -2 +2 %
39500 18C Reference Manual.book Page 20 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39533A-page 32-21
Section 32. Electrical Specifications
Electrical
Specifications
32
Figure 32-6: Example CLKOUT and I/O Timing Waveforms
Table 32-16: Example CLKOUT and I/O Timing Requirements
Param.
No. Symbol Characteristic Min Typ Max Units Conditions
10 TosH2ckL OSC1↑ to CLKOUT↓ — 75 200 ns (Note 1)
11 TosH2ckH OSC1↑ to CLKOUT↑ — 75 200 ns (Note 1)
12 TckR CLKOUT rise time — 35 100 ns (Note 1)
13 TckF CLKOUT fall time — 35 100 ns (Note 1)
14 TckL2ioV CLKOUT ↓ to Port out valid — — 0.5TCY + 20 ns (Note 1)
15 TioV2ckH Port in valid before CLKOUT ↑ 0.25TCY + 25 — — ns (Note 1)
16 TckH2ioI Port in hold after CLKOUT ↑ 0 — — ns (Note 1)
17 TosH2ioV OSC1↑ (Q1 cycle) to Port out valid — 50 150 ns
18 TosH2ioI OSC1↑ (Q2 cycle) to
Port input invalid
(I/O in hold time)
PIC18CXXX 100 — — ns
18A PIC18LCXXX 200 — — ns
19 TioV2osH Port input valid to OSC1↑
(I/O in setup time)
0 — — ns
20 TioR Port output rise time PIC18CXXX — 10 25 ns
20A PIC18LCXXX — — 60 ns
21 TioF Port output fall time PIC18CXXX — 10 25 ns
21A PIC18LCXXX — — 60 ns
22†† Tinp INT pin high or low time TCY — — ns
23†† Trbp RB<7:4> change INT high or low time TCY — — ns
24†† Trcp RC<7:4> change INT high or low time 20 ns
†† These parameters are asynchronous events not related to any internal clock edges.
Note 1: Measurements are taken in RC Mode where CLKOUT output is 4 x TOSC.
Note: Refer to Figure 32-4 for load conditions.
OSC1
CLKOUT
I/O Pin
(input)
I/O Pin
(output)
Q4 Q1 Q2 Q3
10
13
14
17
20, 21
19 18
15
11
12
16
old value new value
39500 18C Reference Manual.book Page 21 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39533A-page 32-22 2000 Microchip Technology Inc.
32.16 Example Power-up and RESET Timing Waveforms and Requirements
Figure 32-7: Example RESET, Watchdog Timer, Oscillator Start-up Timer and Power-up Timer Timing Waveforms
Figure 32-8: Brown-out Reset Timing
Table 32-17: Example RESET, Watchdog Timer, Oscillator Start-up Timer, Brown-out Reset, and Power-up
Timer Requirements
Param.
No. Symbol Characteristic Min Typ Max Units Conditions
30 TmcL MCLR Pulse Width (low) 2 — — µs
31 TWDT Watchdog Timer Time-out
Period (No Prescaler)
7 18 33 ms
32 TOST Oscillation Start-up Timer Period 1024TOSC — 1024TOSC ns TOSC = OSC1 period
33 TPWRT Power up Timer Period 28 72 132 ms
34 TIOZ I/O Hi-impedance from MCLR
Low or Watchdog Timer Reset
— 2 — µs
35 TBOR Brown-out Reset Pulse Width 200 — — µs VDD ≤ VBOR (See D005)
36 TIVRST Time for Internal Reference
Voltage to become stable
— 20 50 µs
VDD
MCLR
Internal
POR
PWRT
Time-out
OSC
Time-out
Internal
RESET
Watchdog
Timer
RESET
33
32
30
31
34
I/O Pins
34
Note: Refer to Figure 32-4 for load conditions.
VDD
VBOR
35
VBGAP = 1.2V
VIRVST
Enable Internal Reference Voltage
Internal Reference Voltage stable 36
39500 18C Reference Manual.book Page 22 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39533A-page 32-23
Section 32. Electrical Specifications
Electrical
Specifications
32
32.17 Example Timer0 and Timer1 Timing Waveforms and Requirements
Figure 32-9: Example Timer0 and Timer1 External Clock Timings Waveforms
Table 32-18: Example Timer0 and Timer1 External Clock Requirements
Param
No. Symbol Characteristic Min Max Units Conditions
40 Tt0H T0CKI High Pulse Width No Prescaler 0.5TCY + 20 — ns
With Prescaler 10 — ns
41 Tt0L T0CKI Low Pulse Width No Prescaler 0.5TCY + 20 — ns
With Prescaler 10 — ns
42 Tt0P T0CKI Period No Prescaler TCY + 10 — ns
With Prescaler Greater of:
20 ns or TCY + 40
N
— ns N = prescale
value
(1, 2, 4,..., 256)
45 Tt1H T1CKI
High
Time
Synchronous, no prescaler 0.5TCY + 20 — ns
Synchronous,
with prescaler
PIC18CXXX 10 — ns
PIC18LCXXX 25 — ns
Asynchronous PIC18CXXX 30 — ns
PIC18LCXXX 50 — ns
46 Tt1L T1CKI
Low
Time
Synchronous, no prescaler 0.5TCY + 5 — ns
Synchronous,
with prescaler
PIC18CXXX 10 — ns
PIC18LCXXX 25 — ns
Asynchronous PIC18CXXX 30 — ns
PIC18LCXXX TBD TBD
47 Tt1P T1CKI
Input
Period
Synchronous Greater of:
20 ns or TCY + 40
N
— ns N = prescale
value
(1, 2, 4, 8)
Asynchronous 60 — ns
Ft1 T1CKI oscillator input frequency range DC 50 kHz
48 Tcke2tmrI Delay from external T1CKI clock edge to
timer increment
2Tosc 7Tosc ns
Note: Refer to Figure 32-4 for load conditions.
46
47
45
48
41
42
40
T0CKI
T1OSO/T1CKI
TMR0 or
TMR1
39500 18C Reference Manual.book Page 23 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39533A-page 32-24 2000 Microchip Technology Inc.
32.18 Example CCP Timing Waveforms and Requirements
Figure 32-10: Example Capture/Compare/PWM Timings Waveforms
Table 32-19: Example Capture/Compare/PWM Requirements
Param.
No. Symbol Characteristic Min Max Units Conditions
50 TccL CCPx input low
time
No Prescaler 0.5TCY + 20 — ns
With
Prescaler
PIC18CXXX 10 — ns
PIC18LCXXX 20 — ns
51 TccH CCPx input
high time
No Prescaler 0.5TCY + 20 — ns
With
Prescaler
PIC18CXXX 10 — ns
PIC18LCXXX 20 — ns
52 TccP CCPx input period 3TCY + 40
N
— ns N = prescale
value (1, 4 or 16)
53 TccR CCPx output rise time PIC18CXXX — 25 ns
PIC18LCXXX — 45 ns
54 TccF CCPx output fall time PIC18CXXX — 25 ns
PIC18LCXXX — 45 ns
Note: Refer to Figure 32-4 for load conditions.
(Capture Mode)
50 51
52
53 54
CCPx
CCPx
(Compare or PWM Mode)
39500 18C Reference Manual.book Page 24 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39533A-page 32-25
Section 32. Electrical Specifications
Electrical
Specifications
32
32.19 Example Parallel Slave Port (PSP) Timing Waveforms and Requirements
Figure 32-11: Example Parallel Slave Port Timing Waveforms
Table 32-20: Example Parallel Slave Port Requirements
Param.
No. Symbol Characteristic Min Max Units Conditions
62 TdtV2wrH Data-in valid before WR↑ or CS↑
(setup time)
20
25
—
—
ns
ns Extended Temp range
63 TwrH2dtI WR↑ or CS↑ to data-in invalid
(hold time)
PIC18CXXX 20 — ns
PIC18LCXXX 35 — ns
64 TrdL2dtV RD↓ and CS↓ to data-out valid —
—
80
90
ns
ns Extended Temp range
65 TrdH2dtI RD↑ or CS↓ to data-out invalid 10 30 ns
66 TibfINH Inhibit of the IBF flag bit being cleared from
WR↑ or CS↑
— 3TCY ns
Note: Refer to Figure 32-4 for load conditions.
RE2/CS
RE0/RD
RE1/WR
RD<7:0>
62
63
64
65
39500 18C Reference Manual.book Page 25 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39533A-page 32-26 2000 Microchip Technology Inc.
32.20 Example SSP and Master SSP SPI Mode Timing Waveforms and Requirements
Figure 32-12: Example SPI Master Mode Timing (CKE = 0)
Table 32-21: Example SPI Mode Requirements (Master Mode, CKE = 0)
Param.
No. Symbol Characteristic Min Max Units Conditions
70 TssL2scH,
TssL2scL
SS↓ to SCK↓ or SCK↑ input TCY — ns
71 TscH SCK input high time
(slave mode)
Continuous 1.25TCY + 30 — ns
71A Single Byte 40 — ns (Note 1)
72 TscL SCK input low time
(slave mode)
Continuous 1.25TCY + 30 — ns
72A Single Byte 40 — ns (Note 1)
73 TdiV2scH,
TdiV2scL
Setup time of SDI data input to SCK edge 100 — ns
73A TB2B Last clock edge of Byte1 to the 1st clock edge
of Byte2
1.5TCY + 40 — ns (Note 2)
74 TscH2diL,
TscL2diL
Hold time of SDI data input to SCK edge 100 — ns
75 TdoR SDO data output rise time PIC18CXXX — 25 ns
PIC18LCXXX — 45 ns
76 TdoF SDO data output fall time — 25 ns
78 TscR SCK output rise time
(master mode)
PIC18CXXX — 25 ns
PIC18LCXXX — 45 ns
79 TscF SCK output fall time (master mode) — 25 ns
80 TscH2doV,
TscL2doV
SDO data output valid after
SCK edge
PIC18CXXX — 50 ns
PIC18LCXXX — 100 ns
Note 1: Requires the use of Parameter # 73A.
2: Only if Parameter #s 71A and 72A are used.
SS
SCK
(CKP = 0)
SCK
(CKP = 1)
SDO
SDI
70
71 72
73
74
75, 76
79 78 80
78 79
MSb LSb BIT6 - - - - - -1
MSb IN BIT6 - - - -1 LSb IN
Note: Refer to Figure 32-4 for load conditions.
39500 18C Reference Manual.book Page 26 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39533A-page 32-27
Section 32. Electrical Specifications
Electrical
Specifications
32
Figure 32-13: Example SPI Master Mode Timing (CKE = 1)
Table 32-22: Example SPI Mode Requirements (Master Mode, CKE = 1)
Param.
No. Symbol Characteristic Min Max Units Conditions
71 TscH SCK input high time
(slave mode)
Continuous 1.25TCY + 30 — ns
71A Single Byte 40 — ns (Note 1)
72 TscL SCK input low time
(slave mode)
Continuous 1.25TCY + 30 — ns
72A Single Byte 40 — ns (Note 1)
73 TdiV2scH,
TdiV2scL
Setup time of SDI data input to SCK edge 100 — ns
73A TB2B Last clock edge of Byte1 to the 1st clock edge
of Byte2
1.5TCY + 40 — ns (Note 2)
74 TscH2diL,
TscL2diL
Hold time of SDI data input to SCK edge 100 — ns
75 TdoR SDO data output rise time PIC18CXXX — 25 ns
PIC18LCXXX — 45 ns
76 TdoF SDO data output fall time — 25 ns
78 TscR SCK output rise time
(master mode)
PIC18CXXX — 25 ns
PIC18LCXXX — 45 ns
79 TscF SCK output fall time (master mode) — 25 ns
80 TscH2doV,
TscL2doV
SDO data output valid after
SCK edge
PIC18CXXX — 50 ns
PIC18LCXXX — 100 ns
81 TdoV2scH,
TdoV2scL
SDO data output setup to SCK edge TCY — ns
Note 1: Requires the use of Parameter # 73A.
2: Only if Parameter #s 71A and 72A are used.
SS
SCK
(CKP = 0)
SCK
(CKP = 1)
SDO
SDI
81
71 72
74
75, 76
78
80
MSb
79
73
MSb IN
BIT6 - - - - - -1
BIT6 - - - -1 LSb IN
LSb
Note: Refer to Figure 32-4 for load conditions.
39500 18C Reference Manual.book Page 27 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39533A-page 32-28 2000 Microchip Technology Inc.
Figure 32-14: Example SPI Slave Mode Timing (CKE = 0)
Table 32-23: Example SPI Mode Requirements (Slave Mode Timing (CKE = 0)
Param.
No. Symbol Characteristic Min Max Units Conditions
70 TssL2scH,
TssL2scL
SS↓ to SCK↓ or SCK↑ input TCY — ns
71 TscH SCK input high time
(slave mode)
Continuous 1.25TCY + 30 — ns
71A Single Byte 40 — ns (Note 1)
72 TscL SCK input low time
(slave mode)
Continuous 1.25TCY + 30 — ns
72A Single Byte 40 — ns (Note 1)
73 TdiV2scH,
TdiV2scL
Setup time of SDI data input to SCK edge 100 — ns
73A TB2B Last clock edge of Byte1 to the 1st clock edge
of Byte2
1.5TCY + 40 — ns (Note 2)
74 TscH2diL,
TscL2diL
Hold time of SDI data input to SCK edge 100 — ns
75 TdoR SDO data output rise time PIC18CXXX — 25 ns
PIC18LCXXX — 45 ns
76 TdoF SDO data output fall time — 25 ns
77 TssH2doZ SS↑ to SDO output hi-impedance 10 50 ns
78 TscR SCK output rise time
(master mode)
PIC18CXXX — 25 ns
PIC18LCXXX — 45 ns
79 TscF SCK output fall time (master mode) — 25 ns
80 TscH2doV,
TscL2doV
SDO data output valid after
SCK edge
PIC18CXXX — 50 ns
PIC18LCXXX — 100 ns
83 TscH2ssH,
TscL2ssH
SS ↑ after SCK edge 1.5TCY + 40 — ns
Note 1: Requires the use of Parameter # 73A.
2: Only if Parameter #s 71A and 72A are used.
SS
SCK
(CKP = 0)
SCK
(CKP = 1)
SDO
SDI
70
71 72
73
74
75, 76 77
79 78 80
78 79
SDI
MSb LSb BIT6 - - - - - -1
MSb IN BIT6 - - - -1 LSb IN
83
Note: Refer to Figure 32-4 for load conditions.
39500 18C Reference Manual.book Page 28 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39533A-page 32-29
Section 32. Electrical Specifications
Electrical
Specifications
32
Figure 32-15: Example SPI Slave Mode Timing (CKE = 1)
Table 32-24: Example SPI Slave Mode Mode Requirements (CKE = 1)
Param.
No. Symbol Characteristic Min Max Units Conditions
70 TssL2scH,
TssL2scL
SS↓ to SCK↓ or SCK↑ input TCY — ns
71 TscH SCK input high time
(slave mode)
Continuous 1.25TCY + 30 — ns
71A Single Byte 40 — ns (Note 1)
72 TscL SCK input low time
(slave mode)
Continuous 1.25TCY + 30 — ns
72A Single Byte 40 — ns (Note 1)
73A TB2B Last clock edge of Byte1 to the 1st clock edge
of Byte2
1.5TCY + 40 — ns (Note 2)
74 TscH2diL,
TscL2diL
Hold time of SDI data input to SCK edge 100 — ns
75 TdoR SDO data output rise time PIC18CXXX — 25 ns
PIC18LCXXX — 45 ns
76 TdoF SDO data output fall time — 25 ns
77 TssH2doZ SS↑ to SDO output hi-impedance 10 50 ns
78 TscR SCK output rise time
(master mode)
PIC18CXXX — 25 ns
PIC18LCXXX — 45 ns
79 TscF SCK output fall time (master mode) — 25 ns
80 TscH2doV,
TscL2doV
SDO data output valid after
SCK edge
PIC18CXXX — 50 ns
PIC18LCXXX — 100 ns
82 TssL2doV SDO data output valid after
SS↓ edge
PIC18CXXX — 50 ns
PIC18LCXXX — 100 ns
83 TscH2ssH,
TscL2ssH
SS ↑ after SCK edge 1.5TCY + 40 — ns
Note 1: Requires the use of Parameter # 73A.
2: Only if Parameter #s 71A and 72A are used.
SS
SCK
(CKP = 0)
SCK
(CKP = 1)
SDO
SDI
70
71 72
82
74
75, 76
MSb BIT6 - - - - - -1 LSb
77
MSb IN BIT6 - - - -1 LSb IN
80
83
Note: Refer to Figure 32-4 for load conditions.
39500 18C Reference Manual.book Page 29 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39533A-page 32-30 2000 Microchip Technology Inc.
32.21 Example SSP I2C Mode Timing Waveforms and Requirements
Figure 32-16: Example SSP I2C Bus Start/Stop Bits Timing Waveforms
Table 32-25: Example SSP I2C Bus Start/Stop Bits Requirements (Slave Mode)
Param.
No. Symbol Characteristic Min Max Units Conditions
90 TSU:STA START condition 100 kHz mode 4700 — ns Only relevant for repeated
Setup time 400 kHz mode 600 — START condition
91 THD:STA START condition 100 kHz mode 4000 — ns After this period the first
Hold time 400 kHz mode 600 — clock pulse is generated
92 TSU:STO STOP condition 100 kHz mode 4700 — ns
Setup time 400 kHz mode 600 —
93 THD:STO STOP condition 100 kHz mode 4000 — ns
Hold time 400 kHz mode 600 —
Note: Refer to Figure 32-4 for load conditions.
91 93
SCL
SDA
START
Condition
STOP
Condition
90 92
39500 18C Reference Manual.book Page 30 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39533A-page 32-31
Section 32. Electrical Specifications
Electrical
Specifications
32
Figure 32-17: Example SSP I2
C Bus Data Timing Waveforms
Table 32-26: Example SSP I2C bus Data Requirements (Slave Mode)
Param.
No. Symbol Characteristic Min Max Units Conditions
100 THIGH Clock high time 100 kHz mode 4.0 — µs PIC18CXXX must operate
at a minimum of 1.5 MHz
400 kHz mode 0.6 — µs PIC18CXXX must operate
at a minimum of 10 MHz
SSP Module 1.5TCY — ns
101 TLOW Clock low time 100 kHz mode 4.7 — µs PIC18CXXX must operate
at a minimum of 1.5 MHz
400 kHz mode 1.3 — µs PIC18CXXX must operate
at a minimum of 10 MHz
SSP Module 1.5TCY — ns
102 TR SDA and SCL rise
time
100 kHz mode — 1000 ns
400 kHz mode 20 + 0.1Cb 300 ns Cb is specified to be from
10 to 400 pF
103 TF SDA and SCL fall
time
100 kHz mode — 300 ns
400 kHz mode 20 + 0.1Cb 300 ns Cb is specified to be from
10 to 400 pF
90 TSU:STA START condition
setup time
100 kHz mode 4.7 — µs Only relevant for repeated
400 kHz mode 0.6 — µs START condition
91 THD:STA START condition
hold time
100 kHz mode 4.0 — µs After this period the first
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 time
100 kHz mode 4.7 — µs
400 kHz mode 0.6 — µs
109 TAA Output valid from
clock
100 kHz mode — 3500 ns (Note 1)
400 kHz mode — — ns
110 TBUF Bus free time 100 kHz mode 4.7 — µs Time the bus must be free
before a new transmission
can start
400 kHz mode 1.3 — µs
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.
90 91 92
100
101
103
106 107
109 109 110
102
SCL
SDA
In
SDA
Out
Note: Refer to Figure 32-4 for load conditions.
39500 18C Reference Manual.book Page 31 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39533A-page 32-32 2000 Microchip Technology Inc.
32.22 Example Master SSP I2C Mode Timing Waveforms and Requirements
Figure 32-18: Example Master SSP I2C Bus Start/Stop Bits Timing Waveforms
Table 32-27: Example Master SSP I2C Bus Start/Stop Bits Requirements
Param.
No. Symbol Characteristic Min Max Units Conditions
90 TSU:STA START condition 100 kHz mode 2(TOSC)(BRG + 1) § —
ns
Only relevant for
repeated START
condition
Setup time 400 kHz mode 2(TOSC)(BRG + 1) § —
1 MHz mode (1) 2(TOSC)(BRG + 1) § —
91 THD:STA START condition 100 kHz mode 2(TOSC)(BRG + 1) § —
ns
After this period the
first clock pulse is
generated
Hold time 400 kHz mode 2(TOSC)(BRG + 1) § —
1 MHz mode (1) 2(TOSC)(BRG + 1) § —
92 TSU:STO STOP condition 100 kHz mode 2(TOSC)(BRG + 1) § —
Setup time 400 kHz mode 2(TOSC)(BRG + 1) § — ns
1 MHz mode (1) 2(TOSC)(BRG + 1) § —
93 THD:STO STOP condition 100 kHz mode 2(TOSC)(BRG + 1) § —
Hold time 400 kHz mode 2(TOSC)(BRG + 1) § — ns
1 MHz mode (1) 2(TOSC)(BRG + 1) § —
§ For the value required by the I2C specification, please refer to Figure A-11 of the “Appendix.”
Note 1: Maximum pin capacitance = 10 pF for all I2C pins.
Note: Refer to Figure 32-4 for load conditions.
91 93
SCL
SDA
START
Condition
STOP
Condition
90 92
39500 18C Reference Manual.book Page 32 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39533A-page 32-33
Section 32. Electrical Specifications
Electrical
Specifications
32
Figure 32-19: Example Master SSP I2C Bus Data Timing
Table 32-28: Example Master SSP I2C Bus Data Requirements
Param.
No. Symbol Characteristic Min Max Units Conditions
100 THIGH Clock high time 100 kHz mode 2(TOSC)(BRG + 1) § — ms
400 kHz mode 2(TOSC)(BRG + 1) § — ms
1 MHz mode (1) 2(TOSC)(BRG + 1) § — ms
101 TLOW Clock low time 100 kHz mode 2(TOSC)(BRG + 1) § — ms
400 kHz mode 2(TOSC)(BRG + 1) § — ms
1 MHz mode (1) 2(TOSC)(BRG + 1) § — ms
102 TR SDA and SCL
rise time
100 kHz mode — 1000 ns Cb is specified to be from
400 kHz mode 20 + 0.1Cb 300 ns 10 to 400 pF
1 MHz mode (1) — 300 ns
103 TF SDA and SCL
fall time
100 kHz mode — 300 ns Cb is specified to be from
400 kHz mode 20 + 0.1Cb 300 ns 10 to 400 pF
1 MHz mode (1) — 100 ns
90 TSU:STA START condition
setup time
100 kHz mode 2(TOSC)(BRG + 1) § — ms Only relevant for
repeated START
condition
400 kHz mode 2(TOSC)(BRG + 1) § — ms
1 MHz mode (1) 2(TOSC)(BRG + 1) § — ms
91 THD:STA START condition
hold time
100 kHz mode 2(TOSC)(BRG + 1) § — ms After this period the first
400 kHz mode 2(TOSC)(BRG + 1) § — ms clock pulse is generated
1 MHz mode (1) 2(TOSC)(BRG + 1) § — ms
106 THD:DAT Data input
hold time
100 kHz mode 0 — ns
400 kHz mode 0 0.9 ms
1 MHz mode (1) TBD — ns
107 TSU:DAT Data input
setup time
100 kHz mode 250 — ns (Note 2)
400 kHz mode 100 — ns
1 MHz mode (1) TBD — ns
92 TSU:STO STOP condition
setup time
100 kHz mode 2(TOSC)(BRG + 1) § — ms
400 kHz mode 2(TOSC)(BRG + 1) § — ms
1 MHz mode (1) 2(TOSC)(BRG + 1) § — ms
109 TAA Output valid from
clock
100 kHz mode — 3500 ns
400 kHz mode — 1000 ns
1 MHz mode (1) — — ns
110 TBUF Bus free time 100 kHz mode 4.7 ‡ — ms Time the bus must be
free before a new transmission
can start
400 kHz mode 1.3 ‡ — ms
1 MHz mode (1) TBD — ms
D102 Cb Bus capacitive loading — 400 pF
§ For the value required by the I2C specification, please refer to Figure A-11 of the “Appendix.”
Note 1: Maximum pin capacitance = 10 pF for all I2C pins.
2: A fast-mode I2C-bus device can be used in a standard-mode I2C-bus system, but parameter 107 ≥ 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. Parameter 102.+ parameter 107 = 1000 + 250 = 1250 ns (for 100 kHz-mode) before the SCL
line is released.
90 91 92
100
101
103
106 107
109 109 110
102
SCL
SDA
In
SDA
Out
Note: Refer to Figure 32-4 for load conditions.
39500 18C Reference Manual.book Page 33 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39533A-page 32-34 2000 Microchip Technology Inc.
32.23 Example USART/SCI Timing Waveforms and Requirements
Figure 32-20: Example USART Synchronous Transmission (Master/Slave) Timing Waveforms
Table 32-29: Example USART Synchronous Transmission Requirements
Figure 32-21: Example USART Synchronous Receive (Master/Slave) Timing Waveforms
Table 32-30: Example USART Synchronous Receive Requirements
Param.
No. Symbol Characteristic Min Max Units Conditions
120 TckH2dtV SYNC XMIT (MASTER & SLAVE)
Clock high to data out valid PIC18CXXX — 40 ns
PIC18LCXXX — 100 ns
121 Tckrf Clock out rise time and fall time
(Master Mode)
PIC18CXXX — 20 ns
PIC18LCXXX — 50 ns
122 Tdtrf Data out rise time and fall time PIC18CXXX — 20 ns
PIC18LCXXX — 50 ns
Param.
No. Symbol Characteristic Min Max Units Conditions
125 TdtV2ckl SYNC RCV (MASTER & SLAVE)
Data hold before CK ↓ (DT hold time) 10 — ns
126 TckL2dtl Data hold after CK ↓ (DT hold time) 15 — ns
Note: Refer to Figure 32-4 for load conditions.
121
121
122
TX/CK Pin
RX/DT Pin
120
Note: Refer to Figure 32-4 for load conditions.
125
126
TX/CK pin
RX/DT pin
39500 18C Reference Manual.book Page 34 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39533A-page 32-35
Section 32. Electrical Specifications
Electrical
Specifications
32
32.24 CAN Specifications
Figure 32-22: Example CAN Timing Waveforms
Table 32-31: Example CAN Timing
Param.
No. Symbol Characteristic Min Typ † Max Units Conditions
20
20A
TioR Port output rise time (1) PIC18CXXX — 10 25 ns
PIC18LCXXX — — 60 ns
21
21A
TioF Port output fall time (1) PIC18CXXX — 10 25 ns
PIC18LCXXX — — 60 ns
500 Tcanclk2ioV CANCLK ↓ or CANCLK ↑
to Port out valid
-20 — 20 ns
501 TrxcanL Wake-up noise filter 50 — — ns
† These parameters are asynchronous events not related to any internal clock edges.
Note 1: The CAN Clock is driven by the I/O pin drivers, so it has the same timing specification.
Note: Refer to Figure 32-4 for load conditions.
13
14
20, 21
12
Bit A Bit B Bit C
CANTX0 Pin
(output)
CANTX1 Pin
(TX1SRL = 1)
(TX1EN = 1)
(ENDRHI = 1)
39500 18C Reference Manual.book Page 35 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39533A-page 32-36 2000 Microchip Technology Inc.
32.25 Example 8-bit A/D Timing Waveforms and Requirements
Table 32-32: Example 8-bit A/D Converter Characteristics
Param
No. Symbol Characteristic Min Typ Max Units Conditions
A01 NR Resolution (2) —
—
—
—
8
8
bits
bits
VREF = VDD ≥ 3.0V
VREF = VDD = 2.5V
A02 EABS Total Absolute error (2) —
—
—
—
<±1
TBD
LSb
LSb
VREF = VDD ≥ 3.0V
VREF = VDD = 2.5V
A03 EIL Integral linearity error (2) —
—
—
—
<±1
TBD
LSb
LSb
VREF = VDD ≥ 3.0V
VREF = VDD = 2.5V
A04 EDL Differential linearity error (2) —
—
—
—
<±1
TBD
LSb
LSb
VREF = VDD ≥ 3.0V
VREF = VDD = 2.5V
A05 EFS Full scale error (2) —
—
—
—
<±1
TBD
LSb
LSb
VREF = VDD ≥ 3.0V
VREF = VDD = 2.5V
A06 EOFF Offset error (2) —
—
—
—
<±1
TBD
LSb
LSb
VREF = VDD ≥ 3.0V
VREF = VDD = 2.5V
A10 — Monotonicity guaranteed (3) — VSS ≤ VAIN ≤ VREF
A20 VREF Reference voltage 0V — AVDD V VREF delta when changing
voltage levels on VREF
inputs
A20A (VREFH - VREFL) 3.0V — AVDD V Absolute minimum electrical
specification to ensure
10-bit accuracy
A21 VREF+ Reference voltage high AVSS + 3.0 AVDD + 0.3 V
A22 VREF- Reference voltage low AVSS - 0.3 AVDD - 3.0 V
A25 VAIN Analog input voltage AVSS - 0.3 — AVREF + 0.3 V
A30 ZAIN Impedance of analog
voltage source
— — 10.0 kΩ
A40 IAD A/D
conversion
current (VDD)
PIC18CXXX — 180 — µA Average current consumption
when A/D is on (1) PIC18LCXXX — 90 — µA
A50 IREF VREF input current (2) 10 — 1000 µA During VAIN acquisition.
Based on differential of
VHOLD to VAIN to charge
CHOLD. See the A/D
Converter section.
— — 10 µA During A/D Conversion
cycle
Note 1: When A/D is off, it will not consume any current other than minor leakage current.
The power-down current spec includes any such leakage from the A/D module.
VREF current is from RA3 pin or VDD pin, whichever is selected as reference input.
2: VSS ≤ VAIN ≤ VREF
3: The A/D conversion result either increases or remains constant as the analog input increases.
39500 18C Reference Manual.book Page 36 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39533A-page 32-37
Section 32. Electrical Specifications
Electrical
Specifications
32
Figure 32-23: Example 8-bit A/D Conversion Timing Waveforms
Table 32-33: Example 8-bit A/D Conversion Requirements
Param
No. Symbol Characteristic Min Max Units Conditions
130 TAD A/D clock period PIC18CXXX 1.6 — µs TOSC based, VREF ≥ 3.0V
PIC18LCXXX 2.0 — µs TOSC based, VREF full range
PIC18CXXX 2.0 6.0 µs A/D RC Mode
PIC18LCXXX 3.0 9.0 µs A/D RC Mode
131 TCNV Conversion time
(not including S/H time) (1)
11 11 TAD
132 TACQ Acquisition time Note 2 — µs
134 TGO Q4 to A/D clock start 2TOSC 2TOSC — If the A/D clock source is
selected as RC, a time of TCY
is added before the A/D clock
starts. This allows the SLEEP
instruction to be executed.
135 TSWC Switching Time from convert → sample 1 1 TAD
136 TAMP Amplifier settling time (2) 1 (5) — µs This may be used if the “new”
input voltage has not changed
by more than 1LSb (i.e., 5 (20)
mV @ 5.12V) from the last
sampled voltage (as stated on
CHOLD).
Note 1: ADRES register may be read on the following TCY cycle.
2: See the A/D Converter section for minimum requirements.
131
130
132
BSF ADCON0, GO
Q4
A/D CLK
A/D DATA
ADRES
ADIF
GO
SAMPLE
OLD_DATA
SAMPLING STOPPED
DONE
NEW_DATA
(TOSC/2) (1)
7 6 5432 10
Note 1: If the A/D clock source is selected as RC, a time of TCY is added before the A/D clock starts. This
allows the SLEEP instruction to be executed.
1 TCY
39500 18C Reference Manual.book Page 37 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39533A-page 32-38 2000 Microchip Technology Inc.
32.26 Example 10-bit A/D Timing Waveforms and Requirements
Table 32-34: Example 10-bit A/D Converter Characteristics
Param
No. Symbol Characteristic Min Typ Max Units Conditions
A01 NR Resolution —
—
—
—
10
TBD
bit
bit
VREF = VDD ≥ 3.0V
VREF = VDD < 3.0V
A03 EIL Integral linearity error —
—
—
—
< ±1
TBD
LSb
LSb
VREF = VDD ≥ 3.0V
VREF = VDD < 3.0V
A04 EDL Differential linearity error —
—
—
—
< ±1
TBD
LSb
LSb
VREF = VDD ≥ 3.0V
VREF = VDD < 3.0V
A05 EFS Full scale error —
—
—
—
< ±1
TBD
LSb
LSb
VREF = VDD ≥ 3.0V
VREF = VDD < 3.0V
A06 EOFF Offset error —
—
—
—
< ±1
TBD
LSb
LSb
VREF = VDD ≥ 3.0V
VREF = VDD < 3.0V
A10 — Monotonicity guaranteed (3) — VSS ≤ VAIN ≤ VREF
A20 VREF Reference voltage
(VREFH - VREFL)
0V — — V
A20A 3V — — V For 10-bit resolution
A21 VREFH Reference voltage High AVSS — AVDD + 0.3V V
A22 VREFL Reference voltage Low AVSS - 0.3V — AVDD V
A25 VAIN Analog input voltage AVSS - 0.3V — VREF + 0.3V V
A30 ZAIN Recommended impedance of
analog voltage source
— — 10.0 kΩ
A40 IAD A/D conversion
current (VDD)
PIC18CXXX — 180 — µA Average current
consumption when
A/D is on (1)
PIC18LCXXX — 90 — µA
A50 IREF VREF input current (Note 2) 10
—
—
—
1000
10
µA
µA
During VAIN acquisition.
Based on differential of
VHOLD to VAIN. To charge
CHOLD see the “10-bit
A/D Converter” section.
During A/D conversion
cycle.
Note 1: When A/D is off, it will not consume any current other than minor leakage current. The power-down current
spec includes any such leakage from the A/D module.
VREF current is from RG0 and RG1 pins or AVDD and AVSS pins, whichever is selected as reference input.
2: VSS ≤ VAIN ≤ VREF.
3: The A/D conversion result either increases or remains constant as the analog input increases.
39500 18C Reference Manual.book Page 38 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39533A-page 32-39
Section 32. Electrical Specifications
Electrical
Specifications
32
Figure 32-24: Example 10-bit A/D Conversion Timing Waveforms
Table 32-35: Example 10-bit A/D Conversion Requirements
Param
No. Symbol Characteristic Min Max Units Conditions
130 TAD A/D clock period PIC18CXXX 1.6 20 (5) µs TOSC based, VREF ≥ 3.0V
PIC18LCXXX 3.0 20 (5) µs TOSC based, VREF full range
PIC18CXXX 2.0 6.0 µs A/D RC Mode
PIC18LCXXX 3.0 9.0 µs A/D RC Mode
131 TCNV Conversion time
(not including acquisition time) (1)
11 § 12 § TAD
132 TACQ Acquisition time (3) 15
10
—
—
µs
µs
-40°C ≤ Temp ≤ 125°C
0°C ≤ Temp ≤ 125°C
135 TSWC Switching Time from convert → sample — Note 4
136 TAMP Amplifier settling time (2) 1 — µs This may be used if the
“new” input voltage has not
changed by more than 1LSb
(i.e., 5 mV @ 5.12V) from
the last sampled voltage (as
stated on CHOLD).
Note 1: ADRES register may be read on the following TCY cycle.
2: See the “10-bit A/D Converter” section for minimum conditions when input voltage has changed more than
1 LSb.
3: The time for the holding capacitor to acquire the “New” input voltage when the voltage changes full scale
after the conversion (AVDD to AVSS, or AVSS to AVDD). The source impedance (RS) on the input channels is
50 Ω.
4: On the next Q4 cycle of the device clock.
5: The time of the A/D clock period is dependent on the device frequency and the TAD clock divider.
131
130
132
BSF ADCON0, GO
Q4
A/D CLK
A/D DATA
ADRES
ADIF
GO
SAMPLE
OLD_DATA
SAMPLING STOPPED
DONE
NEW_DATA
(Note 2)
9 87 2 1 0
Note 1: If the A/D clock source is selected as RC, a time of TCY is added before the A/D clock starts.
This allows the SLEEP instruction to be executed.
2: This is a minimal RC delay (typically 100 nS), which also disconnects the holding capacitor from the
analog input.
... ...
TCY
39500 18C Reference Manual.book Page 39 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39533A-page 32-40 2000 Microchip Technology Inc.
32.27 Design Tips
No related design tips at this time.
39500 18C Reference Manual.book Page 40 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39533A-page 32-41
Section 32. Electrical Specifications
Electrical
Specifications
32
32.28 Related Application Notes
This section lists application notes that are related to this section of the manual. These application
notes may not be written specifically for the Enhanced MCU family (that is, they may be written
for the Base-Line, the Mid-Range, or High-End families), but the concepts are pertinent, and
could be used (with modification and possible limitations). The current application notes related
to the Electrical Specifications are:
Title Application Note #
No related Application Notes at this time.
Note: Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
http://www.microchip.com/10/faqs/codeex/
39500 18C Reference Manual.book Page 41 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39533A-page 32-42 2000 Microchip Technology Inc.
32.29 Revision History
Revision A
This is the initial released revision of the Electrical Specifications description.
39500 18C Reference Manual.book Page 42 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39534A-page 33-1
Device
Characteristics
33
Section 33. Device Characteristics
HIGHLIGHTS
33.1 Introduction .................................................................................................................. 33-2
33.2 Characterization vs. Electrical Specification ................................................................ 33-2
33.3 DC and AC Characteristics Graphs and Tables ........................................................... 33-2
33.4 Revision History ......................................................................................................... 33-26
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39534A-page 33-2 2000 Microchip Technology Inc.
33.1 Introduction
Microchip Technology Inc. provides characterization information on the devices that it manufactures.
This information becomes available after the devices have undergone a complete characterization
and the data has been analyzed. This data is taken on both device testers and on
bench setups. The characterization data gives the designer a better understanding of the device
characteristics, to better judge the acceptability of the device to the application.
33.2 Characterization vs. Electrical Specification
The difference between this information and the Electrical specifications can be classified as
what the user should expect the devices to do vs. what Microchip tests the devices to do. The
characterization graphs and tables provided are for design guidance and are not tested nor guaranteed.
There may be differences between what the characterization shows as the limits vs. that which
is tested, as shown in the Electrical Specification section. This results from capabilities of the
production tester equipment, plus whatever guard band that may be necessary.
33.3 DC and AC Characteristics Graphs and Tables
Each table gives specific information that may be useful design information. These values are
taken under fixed circumstances. Measurements taken in your application may not lead to the
same values if your circumstances are not the same.
In some graphs or tables the data presented are outside specified operating range (i.e., outside
specified VDD range). This is for information only and devices will operate properly only within the
specified range.
Note: The data presented in the device Data Sheet Characterization section is a statistical
summary of data collected on units from different lots over a period of time and
matrix samples. 'Typical' represents the mean of the distribution at, 25°C, while
'max' or 'min' represents (mean +3σ) and (mean -3σ) respectively, where σ is standard
deviation.
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39534A-page 33-3
Section 33. Device Characteristics
Device
Characteristics
33
33.3.1 IPD vs. VDD
IPD is the current (I) that the device consumes when the device is in SLEEP mode (power-down),
referred to as Power-down Current. These tests are taken with all I/O as inputs, either pulled high
or low. That is, there are no floating inputs, nor are any pins driving an output (with a load).
The characterization shows graphs for both the Watchdog Timer (WDT) disabled and enabled.
This is required since the WDT requires an on-chip RC oscillator which consumes additional current.
The device may have certain features and modules that can operate while the device is in SLEEP
mode. Some of these modules are:
• Watchdog Timer (WDT)
• Brown-out Reset (BOR) circuitry
• Timer1
• Analog to Digital converter
• LCD module
• Comparators
• Voltage Reference
If these features are operating while the device is in SLEEP mode, a higher current will be consumed.
When all features are disabled, the device will consume the lowest possible current (the
leakage current). If more then one feature is enabled, then the expected current can easily be
calculated as the base current (everything disabled and in SLEEP mode), plus all delta currents.
Example 33-1 shows an example of calculating the typical currents for a device at 5V, with the
WDT and Timer1 oscillator enabled.
Example 33-1: IPD Calculations with WDT and Timer1 Oscillator Enabled (@ 5V)
Base Current 14 nA ; Device leakage current
WDT Delta Current 14 µA ; 14 µA - 14 nA = 14 µA
Timer1 Delta Current 22 µA ; 22 µA - 14 nA = 22 µA
Total SLEEP Current 36 µA ;
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39534A-page 33-4 2000 Microchip Technology Inc.
Figure 33-1: Example Typical IPD vs. VDD (WDT Disabled, RC Mode)
Figure 33-2: Example Maximum IPD vs. VDD (WDT Disabled, RC Mode)
35
30
25
20
15
10
5
0
2.5 3.0 3.5 4.0 4.5 5.0 5.5
IPD (nA)
VDD (Volts)
IPD (µA)
VDD (Volts)
10.000
1.000
0.100
0.010
0.001
2.5 3.0 3.5 4.0 4.5 5.0 5.5
85°C
70°C
25°C
0°C
-40°C
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39534A-page 33-5
Section 33. Device Characteristics
Device
Characteristics
33
Figure 33-3: Example Typical IPD vs. VDD @ 25°C (WDT Enabled, RC Mode)
Figure 33-4: Example Maximum IPD vs. VDD (WDT Enabled, RC Mode)
25
20
15
10
5
0
2.5 3.0 3.5 4.0 4.5 5.0 5.5
IPD (µA)
VDD (Volts)
35
30
25
20
15
10
5
0
2.5 3.0 3.5 4.0 4.5 5.0 5.5
IPD (µA)
VDD (Volts)
-40°C
0°C
70°C
85°C
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39534A-page 33-6 2000 Microchip Technology Inc.
Figure 33-5: Example Typical IPD vs. VDD Brown-out Detect Enabled (RC Mode)
Figure 33-6: Example Maximum IPD vs. VDD Brown-out Detect Enabled
(85°C to -40°C, RC Mode)
The shaded region represents the built-in hysteresis of the Brown-out Reset circuitry.
2.5 3.0 3.5 4.0 4.5 5.0 5.5
1400
1200
1000
800
600
400
200
0
VDD (Volts)
IPD (µA)
Device in
Brown-out
Device NOT in
Brown-out Reset
Reset
The shaded region represents the built-in hysteresis of the Brown-out Reset circuitry.
2.5 3.0 3.5 4.0 4.5 5.0 5.5
1400
1200
1000
800
600
400
200
0
VDD (Volts)
IPD (µA)
4.3
1600
Device NOT in
Brown-out Reset
Device in
Brown-out
Reset
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39534A-page 33-7
Section 33. Device Characteristics
Device
Characteristics
33
Figure 33-7: Example Typical IPD vs. Timer1 Enabled
(32 kHz, RC0/RC1 = 33 pF/33 pF, RC Mode)
Figure 33-8: Example Maximum IPD vs. Timer1 Enabled
(32 kHz, RC0/RC1 = 33 pF/33 pF, -40°C to 85°C, RC Mode)
30
25
20
15
10
5
0
2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (Volts)
IPD (µA)
30
25
20
15
10
5
0
2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (Volts)
IPD (µA)
35
40
45
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39534A-page 33-8 2000 Microchip Technology Inc.
33.3.2 IDD vs. Frequency
IDD is the current (I) that the device consumes when the device is in operating mode. This test is
taken with all I/O as inputs, either pulled high or low. That is, there are no floating inputs, nor are
any pins driving an output (with a load).
The IDD vs. Frequency charts measure the results on a Microchip automated bench setup, called
the DCS (Data Collection System). The DCS accurately reflects the device and specified component
values, that is, it does not add stray capacitance or current.
33.3.2.1 RC Measurements
For the RC measurement, the DCS selects a resistor and capacitor value and then, varies the
voltage over the specified range. As the voltage is changed, the frequency of operation changes.
For a fixed RC, as VDD increases, the frequency increases. After the measurement at this RC
has been taken, the RC value is changed and the measurements are taken again. Each point on
the graph corresponds to a device voltage, resistor value (R), and capacitor value (C).
Figure 33-9: Example Typical IDD vs. Frequency (RC Mode @ 22 pF, 25°C)
2000
1800
1600
1400
1200
800
1000
600
400
200
0
0.0 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5
Frequency (MHz)
IDD (µA)
Shaded area is
5.5V
5.0V
4.5V
4.0V
3.5V
3.0V
2.5V
beyond recommended range. ‡ R=5kΩ
† R = 10 kΩ
‡
†
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39534A-page 33-9
Section 33. Device Characteristics
Device
Characteristics
33
Figure 33-10: Example Maximum IDD vs. Frequency (RC Mode @ 22 pF, -40°C to 85°C)
Figure 33-11: Example Typical IDD vs. Frequency (RC Mode @ 100 pF, 25°C)
2000
1800
1600
1400
1200
800
1000
600
400
200
0
0.0 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5
Frequency (MHz)
IDD (µA)
Shaded area is
5.5V
5.0V
4.5V
4.0V
3.5V
3.0V
2.5V
beyond recommended range.
1600
1400
1200
1000
800
600
400
200
0
0 200 400 600 800 1000 1200 1400 1600 1800
Frequency (kHz)
IDD (µA)
5.5V
5.0V
4.5V
4.0V
3.5V
3.0V
2.5V
Shaded area is
beyond recommended range.
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39534A-page 33-10 2000 Microchip Technology Inc.
Figure 33-12: Example Maximum IDD vs. Frequency (RC Mode @ 100 pF, -40°C to 85°C)
Figure 33-13: Example Typical IDD vs. Frequency (RC Mode @ 300 pF, 25°C)
1600
1400
1200
1000
800
600
400
200
0
0 200 400 600 800 1000 1200 1400 1600 1800
Frequency (kHz)
IDD (µA)
5.5V
5.0V
4.5V
4.0V
3.5V
3.0V
2.5V
Shaded area is
beyond recommended range.
1200
1000
800
600
400
200
0
0 100 200 300 400 500 600 700
Frequency (kHz)
IDD (µA)
5.5V
5.0V
4.5V
4.0V
3.5V
3.0V
2.5V
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39534A-page 33-11
Section 33. Device Characteristics
Device
Characteristics
33
Figure 33-14: Example Maximum IDD vs. Frequency (RC Mode @ 300 pF, -40°C to 85°C)
Figure 33-15:Example Typical IDD vs. Capacitance @ 500 kHz (RC Mode)
1200
1000
800
600
400
200
0
0 100 200 300 400 500 600 700
Frequency (kHz)
IDD (µA)
5.5V
5.0V
4.5V
4.0V
3.5V
3.0V
2.5V
Capacitance (pF)
600
IDD (µA)
500
400
300
200
100
0
20 pF 100 pF 300 pF
5.0V
4.0V
3.0V
39500 18C Reference Manual.book Page 11 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39534A-page 33-12 2000 Microchip Technology Inc.
33.3.2.2 Crystal Oscillator Measurements
On the Data Collection System, there are several crystals. For this test, a crystal is multiplexed
into the device circuit and the crystal’s capacitance values can be varied. The capacitance and
voltage values are varied to determine the best characteristics (current, oscillator waveform and
oscillator start-up), and then the currents are measured over voltage. The next crystal oscillator
is then switched in and the procedure is repeated.
Figure 33-16: Example Typical IDD vs. Frequency (LP Mode, 25°C)
Figure 33-17: Example Maximum IDD vs. Frequency (LP Mode, -40°C to 85°C)
120
100
80
60
40
20
0
0 50 100 150 200
Frequency (kHz)
IDD (µA)
5.5V
5.0V
4.5V
4.0V
3.5V
3.0V
2.5V
120
100
80
60
40
20
0
0 50 100 150 200
Frequency (kHz)
IDD (µA)
140
5.5V
5.0V
4.5V
4.0V
3.5V
3.0V
2.5V
39500 18C Reference Manual.book Page 12 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39534A-page 33-13
Section 33. Device Characteristics
Device
Characteristics
33
Figure 33-18: Example Typical IDD vs. Frequency (XT Mode, 25°C)
Figure 33-19: Example Maximum IDD vs. Frequency (XT Mode, -40°C to 85°C)
1200
1000
800
600
400
200
0
0.0 0.4
Frequency (MHz)
IDD (µA) 1400
1600
1800
0.8 1.2 1.6 2.0 2.4 2.8 3.2 3.6 4.0
5.5V
5.0V
4.5V
4.0V
3.5V
3.0V
2.5V
1200
1000
800
600
400
200
0
0.0 0.4
Frequency (MHz)
IDD (µA)
1400
1600
1800
0.8 1.2 1.6 2.0 2.4 2.8 3.2 3.6 4.0
5.5V
5.0V
4.5V
4.0V
3.5V
3.0V
2.5V
39500 18C Reference Manual.book Page 13 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39534A-page 33-14 2000 Microchip Technology Inc.
Figure 33-20: Example Typical IDD vs. Frequency (HS Mode, 25°C)
Figure 33-21: Example Maximum IDD vs. Frequency (HS Mode, -40°C to 85°C)
7.0
6.0
5.0
4.0
3.0
2.0
1.0
0.0
1 2 4 6 8 10 12 14 16 18 20
Frequency (MHz)
IDD (mA)
5.5V
5.0V
4.5V
4.0V
7.0
6.0
5.0
4.0
3.0
2.0
1.0
0.0
1 2 4 6 8 10 12 14 16 18 20
Frequency (MHz)
IDD (mA)
5.5V
5.0V
4.5V
4.0V
39500 18C Reference Manual.book Page 14 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39534A-page 33-15
Section 33. Device Characteristics
Device
Characteristics
33
33.3.3 RC Oscillator Frequency
These tables show the effects of the RC oscillator frequency as the device voltage varies. In
these measurements, a capacitor and resistor value are selected and then, the frequency of the
RC is measured, as the device voltage varies. The table shows the typical frequency for a R and
C value at 5V, as well as the variation from this frequency that can be expected, due to device
processing.
Figure 33-22: Example Typical RC Oscillator Frequency vs. VDD
Figure 33-23: Example Typical RC Oscillator Frequency vs. VDD
2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (Volts)
6.0
5.5
5.0
4.5
4.0
3.5
3.0
2.5
2.0
1.5
1.0
0.5
0.0
Fosc (MHz)
CEXT = 22 pF, T = 25°C
R = 100k
R = 10k
R = 5k
Shaded area is beyond recommended range.
2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (Volts)
2.4
2.2
2.0
1.8
1.6
1.4
1.2
1.0
0.8
0.6
0.4
0.2
0.0
Fosc (MHz)
CEXT = 100 pF, T = 25°C
R = 100k
R = 10k
R = 5k
R = 3.3k
39500 18C Reference Manual.book Page 15 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39534A-page 33-16 2000 Microchip Technology Inc.
Figure 33-24: Example Typical RC Oscillator Frequency vs. VDD
Table 33-1: Example RC Oscillator Frequencies
CEXT REXT
Average
Fosc @ 5V, 25°C
22 pF 5k 4.12 MHz ± 1.4%
10k 2.35 MHz ± 1.4%
100k 268 kHz ± 1.1%
100 pF 3.3k 1.80 MHz ± 1.0%
5k 1.27 MHz ± 1.0%
10k 688 kHz ± 1.2%
100k 77.2 kHz ± 1.0%
300 pF 3.3k 707 kHz ± 1.4%
5k 501 kHz ± 1.2%
10k 269 kHz ± 1.6%
100k 28.3 kHz ± 1.1%
The percentage variation indicated here is part to part variation due to normal process distribution.
The variation indicated is ±3 standard deviation from average value for VDD = 5V.
2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (Volts)
1000
900
800
700
600
500
400
300
200
100
0
Fosc (kHz)
CEXT = 300 pF, T = 25°C
R = 100k
R = 10k
R = 5k
R = 3.3k
39500 18C Reference Manual.book Page 16 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39534A-page 33-17
Section 33. Device Characteristics
Device
Characteristics
33
33.3.4 Oscillator Transconductance
Transconductance of the oscillator indicates the gain of the oscillator. As the transconductance
increases, the gain of the oscillator circuit increases, which causes the current consumption of
the oscillator circuit to increase. Also, as the transconductance increases, the maximum frequency
that the oscillator circuit can support also increases, or the start-up time of the oscillator
decreases.
Figure 33-25: Example Transconductance (gm) of HS Oscillator vs. VDD
Figure 33-26: Example Transconductance (gm) of LP Oscillator vs. VDD
4.0
3.0 3.5 4.0 4.5 5.0 5.5
gm (mA/V)
VDD (Volts)
3.5
3.0
2.5
2.0
1.5
1.0
0.5
0.0
Typ 25°C
Min 85°C
Max -40°C
110
100
90
80
70
60
50
40
30
20
10
0
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
gm (mA/V)
VDD (Volts)
Typ 25°C
Min 85°C
Max -40°C
39500 18C Reference Manual.book Page 17 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39534A-page 33-18 2000 Microchip Technology Inc.
Figure 33-27: Example Transconductance (gm) of XT Oscillator vs. VDD
1000
900
800
700
600
500
400
300
200
100
0
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
gm (mA/V)
VDD (Volts)
Typ 25°C
Min 85°C
Shaded area is beyond recommended range.
Max -40°C
39500 18C Reference Manual.book Page 18 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39534A-page 33-19
Section 33. Device Characteristics
Device
Characteristics
33
33.3.5 Crystal Start-up Time
These graphs show the start-up time that one should expect to see at the specified voltage level,
for a given crystal/capacitor combination.
Figure 33-28: Example Typical XTAL Start-up Time vs. VDD (LP Mode, 25°C)
Figure 33-29: Example Typical XTAL Start-up Time vs. VDD (HS Mode, 25°C)
3.5
3.0
2.5
2.0
1.5
1.0
0.5
0.0
2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (Volts)
Start-up Time (Seconds)
32 kHz, 33 pF/33 pF
200 kHz, 15 pF/15 pF
7
6
5
4
3
2
1
4.0 4.5 5.0 5.5
VDD (Volts)
Start-up Time (ms)
20 MHz, 33 pF/33 pF
8 MHz, 33 pF/33 pF
8 MHz, 15 pF/15 pF
20 MHz, 15 pF/15 pF
39500 18C Reference Manual.book Page 19 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39534A-page 33-20 2000 Microchip Technology Inc.
Figure 33-30: Example Typical XTAL Start-up Time vs. VDD (XT Mode, 25°C)
70
60
50
40
30
20
10
0
2.5 4.0 5.0 5.5 3.0 3.5 4.5
VDD (Volts)
Start-up Time (ms)
200 kHz, 68 pF/68 pF
200 kHz, 47 pF/47 pF
1 MHz, 15 pF/15 pF
4 MHz, 15 pF/15 pF
39500 18C Reference Manual.book Page 20 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39534A-page 33-21
Section 33. Device Characteristics
Device
Characteristics
33
Figure 33-31: Example VTH (Input Threshold Trip Point Voltage) of I/O Pins vs. VDD
Figure 33-32: Example VIH, VIL of MCLR, T0CKI and OSC1 (in RC Mode) vs. VDD
2.00
1.80
1.60
1.40
1.20
1.00
2.5 3.0 3.5 4.0 4.5 5.0
VDD (Volts)
0.80
0.60
5.5
Typ (+25°C)
VTH (Volts)
3.5
3.0
2.5
2.0
1.5
1.0
2.5 3.0 3.5 4.0 4.5 5.0
VDD (Volts)
0.5
0.0
5.5
VIH, VIL (Volts)
4.0
4.5
VIH min (–40°C to +85°C)
VIH max (–40°C to +85°C)
VIH typ +25°C
VIL min (–40°C to +85°C)
VIL max (–40°C to +85°C)
VIL typ +25°C
Note: These input pins have Schmitt Trigger input buffers.
39500 18C Reference Manual.book Page 21 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39534A-page 33-22 2000 Microchip Technology Inc.
Figure 33-33: Example VTH (Input Threshold Trip Point Voltage) of OSC1 Input (in XT, HS, and LP modes) vs.
VDD
Figure 33-34: Example WDT Timer Time-out Period vs. VDD
2.4
2.2
2.0
1.8
1.6
1.4
2.5 3.0 3.5 4.0 4.5 5.0
VDD (Volts)
1.2
1.0
5.5
Typ (+25°C)
VTH (Volts)
2.6
2.8
3.0
3.2
3.4
45
40
35
30
25
20
2.5 3.0 3.5 4.0 4.5 5.0
VDD (Volts)
15
10
5.5
50
2.0
WDT period (ms)
Typ +125°C
Typ +85°C
Typ +25°C
Typ –40°C
39500 18C Reference Manual.book Page 22 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39534A-page 33-23
Section 33. Device Characteristics
Device
Characteristics
33
Figure 33-35: Example IOH vs. VOH, VDD =3V
Figure 33-36: Example IOH vs. VOH, VDD =5V
0
–5
–10
–15
–20
–25
0 0.5 1.0 1.5 2.0 2.5
VOH (Volts)
IOH (mA)
Min +85°C
3.0
Typ +25°C
Max –40°C
0
–10
–20
–30
–40
1.5 2.0 2.5 3.0 3.5 4.0
VOH (Volts)
IOH (mA)
Typ –40°C
4.5 5.0
Typ +85°C
Typ +125°C
Typ +25°C
39500 18C Reference Manual.book Page 23 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39534A-page 33-24 2000 Microchip Technology Inc.
Figure 33-37: Example IOL vs. VOL, VDD =3V
Figure 33-38: Example IOL vs. VOL, VDD =5V
45
40
35
30
25
20
15
10
5
0
0.0 0.5 1.0 1.5 2.0 2.5
VOL (Volts)
IOL (mA)
Min +85°C
Max –40°C
Typ +25°C
3.0
90
80
70
60
50
40
30
20
10
0
0.0 0.5 1.0 1.5 2.0 2.5
VOL (Volts)
IOL (mA)
Min +85°C
Max –40°C
Typ +25°C
3.0
39500 18C Reference Manual.book Page 24 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39534A-page 33-25
Section 33. Device Characteristics
Device
Characteristics
33
33.3.6 Tested Crystals and Their Capacitor Values
This table shows the crystal frequency and manufacturer that was used for every test in this section,
as well as the capacitor values/ranges that exhibited the best characteristics.
Table 33-2: Example Capacitor Selection for Crystal Oscillators
33.3.7 Example EPROM Memory Erase Times
The UV erase time of an EPROM cell depends on the geometry size of the EPROM cell and the
manufacturing technology. Table 33-3 shows some of the expected erase times for each different
device.
Table 33-3: Example of Typical EPROM Erase Time Recommendations
Osc Type Crystal Frequency Capacitor Range
C1
Capacitor Range
C2
LP 32 kHz 33 pF 33 pF
200 kHz 15 pF 15 pF
XT 200 kHz 47-68 pF 47-68 pF
1 MHz 15 pF 15 pF
4 MHz 15 pF 15 pF
HS 4 MHz 15 pF 15 pF
8 MHz 15-33 pF 15-33 pF
20 MHz 15-33 pF 15-33 pF
Note: Higher capacitance increases the stability of the oscillator but also increases the start-up time.
These values are for design guidance only. Rs may be required in HS mode, as well as XT
mode, to avoid overdriving crystals with low drive level specification. Since each crystal has
its own characteristics, the user should consult the crystal manufacturer for appropriate values
of external components or verify oscillator performance.
Crystals Used:
32 kHz Epson C-001R32.768K-A ± 20 PPM
200 kHz STD XTL 200.000KHz ± 20 PPM
1 MHz ECS ECS-10-13-1 ± 50 PPM
4 MHz ECS ECS-40-20-1 ± 50 PPM
8 MHz EPSON CA-301 8.000M-C ± 30 PPM
20 MHz EPSON CA-301 20.000M-C ± 30 PPM
Example
Device
Wavelength
(Angstroms)
Intensity
(µW/cm2)
Distance from UV
Lamp (inches)
Typical Time (1)
(minutes)
1 2537 12,000 1 60
Note 1: If these criteria are not met, the erase times will be different.
2: Refer to the device data sheet for the typical erase times for a device.
39500 18C Reference Manual.book Page 25 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39534A-page 33-26 2000 Microchip Technology Inc.
33.4 Revision History
Revision A
This is the initial released revision of the Device Characteristics description.
39500 18C Reference Manual.book Page 26 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39535A-page 34-1
Development
Tools
34
Section 34. Development Tools
HIGHLIGHTS
This section of the manual contains the following major topics:
34.1 Introduction .................................................................................................................. 34-2
34.2 The Integrated Development Environment (IDE) ......................................................... 34-3
34.3 MPLAB® Software Language Support ........................................................................ 34-6
34.4 MPLAB-SIM Simulator Software.................................................................................. 34-8
34.5 MPLAB® Emulator Hardware Support ........................................................................ 34-9
34.8 MPLAB Programmer Support .................................................................................... 34-10
34.9 Supplemental Tools.................................................................................................... 34-11
34.10 Development Boards.................................................................................................. 34-12
34.11 Development Tools for Other Microchip Products ...................................................... 34-14
34.12 Related Application Notes.......................................................................................... 34-15
34.13 Revision History ......................................................................................................... 34-16
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39535A-page 34-2 2000 Microchip Technology Inc.
34.1 Introduction
Microchip offers a wide range of integrated development tools to ease the application development
process. These tools can be broken down into the core development tools and the supplemental
tools.
The core tools are as follows:
• MPLAB Integrated Development Environment, including full featured editor
• Language Products
- MPASM Assembler
- MPLAB-CXX C Compiler
-MPLAB-C17
-MPLAB-C18
- MPLINK/MPLIB Linker Librarian
• MPLAB-SIM Software Simulator
• Real-Time In-Circuit Emulators
- MPLAB-ICE Real-Time Emulator In-Circuit
- ICEPIC Low-Cost Emulator with Breakpoint debug capabilities
• In-Circuit Debugger
- MPLAB-ICD for 16F877
• Device Programmers
- PRO MATE II Universal Programmer
- PICSTART Plus Entry-Level Development Programmer
• Development Boards
- PICDEM-1 Low-Cost Demonstration Board
- PICDEM-2 Low-Cost Demonstration Board
- PICDEM-3 Low-Cost Demonstration Board
- PICDEM-17 Low-Cost Demonstration Board
- PICDEM-14A Low-Cost Demonstration Board
The minimum configuration of MPLAB is the Integrated Development Environment (IDE), the
assembler (MPASM), and the software simulator (MPLAB-SIM). Other tools are added to MPLAB
as they are installed. This gives a common platform for the design activity, from the writing and
assembling of the source code, through the simulation/emulation, to the programming of prototype
devices.
In addition to Microchip, there are many third party vendors. Microchip’s Third Party Handbook
gives an overview of the manufactures and their tools.
Note: The most current version may be downloaded from Microchip’s web site for free.
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39535A-page 34-3
Section 34. Development Tools
Development
Tools
34
34.2 The Integrated Development Environment (IDE)
The core set of development tools operate under the IDE umbrella. The IDE is called MPLAB.
This gives a consistent look and feel to all the development tools so that minimal learning of the
new tool interface is required. The MPLAB IDE integrates all the following aspects of development:
• Source code editing
• Project management
• Machine code generation (from assembly or “C”)
• Device simulation
• Device emulation
• Device programming
MPLAB is a PC based Windows® application. It has been extensively tested using Windows 95
and recommended in either of these operating environments:
• Windows 2000
• Windows NT 4.0
• Windows 98
• Windows 95
• Windows 3.X
This comprehensive tool suite allows the complete development of a project without leaving the
MPLAB environment.
Windows is a registered trademark of Microsoft Corporation.
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39535A-page 34-4 2000 Microchip Technology Inc.
34.2.1 MPLAB
The MPLAB IDE Software brings an ease of software development previously unseen in the 8-bit
microcontroller market. MPLAB is a Windows based application that contains:
• A full featured editor
• Four operating modes
- editor
- simulator
- emulator
- programmer
• A project manager
• Customizable tool bar and key mapping
• A status bar with project information
• Extensive on-line help
MPLAB allows you to:
• Edit your source files. This includes:
- MPASM assembly language
- MPLAB-CXX ‘C’ language
• One touch assemble (or compile) and download to PIC16/17 tools
(automatically updates all project information)
• Debug using:
- source files
- absolute listing file
- program memory
• Run up to four MPLAB-ICE emulators on the same PC
• Run or Single-step
- program memory
- source file
- absolute listing
Microchip’s simulator, MPLAB-SIM, operates under the same platform as the MPLAB-ICE emulator.
This allows the user to learn a single tool set which functions equivalently for both the simulator
and the full featured emulator.
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39535A-page 34-5
Section 34. Development Tools
Development
Tools
34
Figure 34-1 shows a typical MPLAB desktop with an open project. Some of the highlights are:
• Tool bars, multiple choices and user configurable
• Status, mode information, and button help on footer bar
• Multiple windows, such as
- Source code
- Source listing (most useful for ‘C’ programs)
- Register file window (RAM)
- Watch windows (to look at specific register)
- Stop watch window for time/cycle calculations
• Programmer support (in this case PRO MATE pull down menu)
Figure 34-1: MPLAB Project Window
Note: This screen shot may not look exactly like the currently released MPLAB version.
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39535A-page 34-6 2000 Microchip Technology Inc.
34.3 MPLAB® Software Language Support
To make the PICmicro device operate as desired in the application, a software program needs
to be written for the microcontroller. This software program needs to be written in one of the programming
languages for the device. Currently MPLAB supports two of Microchip’s language
products:
• Microchip Assembler (MPASM)
• Microchip ‘C’ Compiler (MPLAB-CXX)
• Other language products that support Common Object Description (COD) may also work
with MPLAB
34.3.1 Assembler (MPASM)
The MPASM Universal Macro Assembler is a PC-hosted symbolic assembler. It supports all
Microchip microcontroller families.
MPASM offers full featured Macro capabilities, conditional assembly, and several source and listing
formats. It generates various object code formats to support Microchip's development tools
as well as third party programmers.
MPASM allow full symbolic debugging from the Microchip Universal Emulator System
(MPLAB-ICE).
MPASM has the following features to assist in developing software for specific use applications.
• Provides translation of Assembler source code to object code for all Microchip microcontrollers.
• Macro assembly capability.
• Produces all the files (Object, Listing, Symbol, and Special) required for symbolic debug
with Microchip’s emulator systems.
• Supports Hex (default), Decimal and Octal source and listing formats.
MPASM provides a rich directive language to support programming of the PICmicro. Directives
are helpful in making the development of your assemble source code shorter and more maintainable.
34.3.2 C Compilers
The MPLAB-CXX is a complete ‘C’ compiler for Microchip’s PICmicro family of microcontrollers.
The compiler provides powerful integration capabilities and ease of use not found with other
compilers.
For easier source level debugging, the compiler provides symbol information that is compatible
with the MPLAB IDE memory display, Watch windows, and File register windows.
34.3.2.1 MPLAB-C17 C Compiler
The MPLAB-C17 Code Development System is a complete ANSI ‘C’ compiler and integrated
development environment for Microchip’s PIC17CXXX family of microcontrollers. This compiler
provides powerful integration capabilities and ease of use not found with other compilers.
For easier source level debugging, the compiler provides symbol information that is compatible
with the MPLAB IDE memory display.
34.3.2.2 MPLAB-C18 C Compiler
The MPLAB-C18 Code Development System is a complete ANSI ‘C’ compiler and integrated
development environment for Microchip’s PIC18CXXX family of microcontrollers. This compiler
provides powerful integration capabilities and ease of use not found with other compilers.
For easier source level debugging, the compiler provides symbol information that is compatible
with the MPLAB IDE memory display.
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39535A-page 34-7
Section 34. Development Tools
Development
Tools
34
34.3.3 MPLINK Linker
MPLINK is a linker for the Microchip C compiler, MPLAB-CXX, and the Microchip relocatable
assembler, MPASM. MPLINK is a relocatable linker for MPASM and MPLAB-C17 and
MPLAB-C18. It can link relocatable objects from assembly or C source files along with precompiled
libraries using directives from a linker script.
MPLINK allows you to produce modular, re-usable code with MPLAB-CXX and MPASM. Control
over the linking process is accomplished through a linker “script” file and with command line
options. MPLINK ensures that all symbolic references are resolved and that code and data fit into
the available PICmicro device.
MPLINK combines multiple input object modules generated by MPLAB-CXX or MPASM, into a
single executable file. The actual addresses of data and the location of functions will be assigned
when MPLINK is executed. This means that you will instruct MPLINK to place code and data
somewhere within the named regions of memory, not to specific physical locations.
Once the linker knows about the ROM and RAM memory regions available in the target PICmicro
device and it analyzes all the input files, it will try to fit the application’s routines into ROM and
assign it’s data variables into available RAM. If there is too much code or too many variables to
fit, MPLINK will give an error message.
MPLINK also provides flexibility for specifying that certain blocks of data memory are re-usable,
so that different routines (which never call each other and don’t depend on this data to be
retained between execution) can share limited RAM space.
MPLINK features include:
• MPLINK works with MPASM and MPLAB-C17 and MPLAB-C18.
• MPLINK allows all memory areas to be defined as sections to provide link-time flexibility.
34.3.4 MPLIB Librarian
MPLIB is a librarian for use with COFF object modules, created using either MPASM,
MPASMWIN, or MPLAB-CXX or later. MPLIB is a librarian for pre-compiled code to be used with
MPLINK. When a routine from a library is called from another source file, only the modules that
contain that routine will be linked in with the application. This allows large libraries to be used
efficiently in many different applications.
MPLIB manages the creation and modification of library files. A library file is a collection of object
modules that are stored in a single file. There are several reasons for creating library files:
• Libraries make linking easier. Since library files can contain many object files, the name of
a library file can be used instead of the names of many separate object files when linking.
• Libraries help keep code small. Since a linker only uses the required object files contained
in a library, not all object files which are contained in the library necessarily wind up in the
linker’s output module.
• Libraries make projects more maintainable. If a library is included in a project, the addition
or removal of calls to that library will not require a change to the link process.
• Libraries help convey the purpose of a group of object modules. Since libraries can group
together several related object modules, the purpose of a library file is usually more understandable
that the purpose of its individual object modules. For example, the purpose of a
file named “math.lib” is more apparent that the purpose of 'power.o', 'ceiling.o', and 'floor.o'.
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39535A-page 34-8 2000 Microchip Technology Inc.
34.4 MPLAB-SIM Simulator Software
The software simulator is a no-cost tool with which to evaluate Microchip’s products and designs.
The use of the simulator greatly helps debug software, particularly algorithms. Depending on the
complexity of a design project, a time/cost benefit should be looked at comparing the simulator
with an emulator.
For projects that have multiple engineers in the development, the simulator in conjunction with
an emulator, can keep costs down and will allow speedy debug of the tough problems.
MPLAB-SIM Simulator simulates the PICmicro series microcontrollers on an instruction level. On
any given instruction, the user may examine or modify any of the data areas or provide external
stimulus to any of the pins. The input/output radix can be set by the user and the execution can
be performed in; single step, execute until break, or in a trace mode.
MPLAB-SIM supports symbolic debugging using MPLAB-CXX, and MPASM. The Software Simulator
offers the low cost flexibility to develop and debug code outside of the laboratory environment
making it an excellent multi-project software development tool.
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39535A-page 34-9
Section 34. Development Tools
Development
Tools
34
34.5 MPLAB® Emulator Hardware Support
Microchip offers two emulators, a high-end version (MPLAB-ICE) and a low-cost version
(ICEPIC). Both versions offer a very good price/feature value, and the selection of which emulator
should depend on the feature set that you wish. For people looking at doing several projects
with Microchip devices (or using the high-end devices), the use of MPLAB-ICE may offset the
additional investment, through time savings achieved with the sophisticated breakpoint and trace
capabilities.
34.6 MPLAB® High Performance Universal In-Circuit Emulator with MPLAB IDE
The MPLAB-ICE Universal In-Circuit Emulator is intended to provide the product development
engineer with a complete microcontroller design tool set for PICmicro microcontrollers (MCUs).
Software control of MPLAB-ICE is provided by the MPLAB Integrated Development Environment
(IDE), which allows editing, “make” and download, and source debugging from a single environment.
Interchangeable target probes allow the system to be easily re-configured for emulation of different
processors. The universal architecture of the MPLAB-ICE allows expansion to support all
new Microchip microcontrollers.
The MPLAB-ICE Emulator System has been designed as a real-time emulation system with
advanced features that are generally found on more expensive development tools.
A CE compliant version of MPLAB-ICE is available for European Union (EU) countries.
34.6.1 ICEPIC: Low-Cost PIC16CXXX In-Circuit Emulator
ICEPIC is a low-cost in-circuit emulator solution for the Microchip Base-line and Mid-Range families
of 8-bit OTP microcontrollers.
ICEPIC features real-time emulation. ICEPIC is available under the MPLAB environment.
ICEPIC is designed by Neosoft Inc. and is manufactured under license by RF Solutions. Other
emulator solutions may be available directly from RF solutions.
34.7 MPLAB-ICD In-Circuit Debugger
Microchip’s In-Circuit Debugger, MPLAB-ICD, is a powerful, low-cost run-time development tool.
This tool is based on the FLASH PIC16F877 and can be used to develop for this and other PICmicro
microcontrollers from the PIC16CXXX family (see TB033 for more information).
MPLAB-ICD utilizes the In-Circuit Debugging capability built into the PIC16F87X. This feature,
along with Microchip’s In-Circuit Serial Programming protocol, offers cost-effective in-circuit
FLASH programming and debugging from the graphical user interface of the MPLAB Integrated
Development Environment. This enables 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. The MPLAB-ICD is also a programmer for the flash PIC16F87X family.
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39535A-page 34-10 2000 Microchip Technology Inc.
34.8 MPLAB Programmer Support
Microchip offers two levels of device programmer support. For most bench setups the PICSTART
Plus is sufficient. When true system qualification is done, the PRO MATE II should be the minimum
used, due to the validation of program memory at VDD min and VDD max for maximum reliability
34.8.1 PRO MATE® II: Universal Device Programmer
The PRO MATE II Universal Programmer is a full-featured programmer capable of operating in
stand-alone mode as well as PC-hosted mode. PRO MATE II operates under MPLAB or as a
DOS command driven program.
The PRO MATE II has programmable VDD and VPP supplies which allows it to verify programmed
memory at VDD min and VDD max for maximum reliability. It has an LCD display for error messages,
keys to enter commands and a modular detachable socket assembly to support various
package types. In stand-alone mode, the PRO MATE II can read, verify, or program Base-Line,
Mid-Range, and High-End devices. It can also set configuration and code-protect bits in this
mode. The PRO MATE II programmer also supports Microchip’s Serial EEPROM and KEELOQ®
Security devices.
A separate In-Circuit Serial Programming (ICSP) module is available for volume programming in
a manufacturing environment. See the Programming module documentation for specific application
requirements.
34.8.2 PICSTART® Plus Low-Cost Development Kit
The PICSTART Plus programmer is an easy-to-use, low-cost development programmer. It connects
to the PC via one of the COM (RS-232) ports. MPLAB Integrated Development Environment
software makes using the programmer simple and efficient. PICSTART Plus is not
recommended for production programming, since it does not perform memory verification at
VDDMIN and VDDMAX.
PICSTART Plus supports all Base-Line, Mid-Range, and High-End devices. For devices with up
to more than 40 pins, an adapter socket is required. DIP packages are the form factor that are
directly supported. Other package types may be supported with adapter sockets.
Note: The use of a PICSTART Plus Programmer is not recommended for ICSP. If ICSP is
required, the use of the PRO MATE II Universal Programmer with the associated
socket module is the recommended Microchip solution.
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39535A-page 34-11
Section 34. Development Tools
Development
Tools
34
34.9 Supplemental Tools
Microchip endeavors to provide a broad range of solutions to our customers. These tools are
considered supplemental tools and may be available directly from Microchip or from another vendor.
A comprehensive listing of alternate tool providers is contained in the Third Party Guide.
34.9.1 Third Party Guide
Looking for something else? Microchip strongly encourages and supports it’s Third Parties.
Microchip publishes the “Third Party Guide”. It is an extensive volume that provides:
• Company
• Product
• Contact Information
• Consultants
For over 100 companies and 200 products. These products include Emulators, Device Programmers,
Gang Programmers, Language Products, and other tool solutions.
39500 18C Reference Manual.book Page 11 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39535A-page 34-12 2000 Microchip Technology Inc.
34.10 Development Boards
Development boards give a quick start on a circuit that demonstrates the capabilities of a particular
device. The device program can then be modified for your own evaluation of the device functionality
and operation.
34.10.1 PICDEM-1 Low-Cost PIC16/17 Demonstration Board
The PICDEM-1 is a simple board which demonstrates the capabilities of several of Microchip’s
microcontrollers. The microcontrollers supported are:
• PIC16C5X (PIC16C54 to PIC16C58A)
• PIC16C61
• PIC16C62X
• PIC16C71
• PIC16C710
• PIC16C711
• PIC16C8X
• PIC17C42A
• PIC17C43
• PIC17C44
All necessary hardware and software is included to run basic demo programs. The users can program
the sample microcontrollers provided with the PICDEM-1 board, on a PRO MATE II or
PICSTART Plus programmer, and easily test firmware. The user can also connect the
PICDEM-1 board to the MPLAB-ICE emulator and download the firmware to the emulator for
testing. Additional prototype area is available to build additional hardware. Some of the features
include an RS-232 interface, a potentiometer for simulated analog input, push-button switches
and eight LEDs connected to PORTB.
34.10.2 PICDEM-2 Low-Cost PIC16CXXX Demonstration Board
The PICDEM-2 is a simple demonstration board that supports the following microcontrollers:
• PIC16C62
• PIC16C63
• PIC16C64
• PIC16C65
• PIC16C66
• PIC16C67
• PIC16C72
• PIC16C73
• PIC16C74
• PIC16C76
• PIC16C77
All the necessary hardware and software is included to run the basic demonstration programs.
The user can program the sample microcontrollers provided with the PICDEM-2
board, on a PRO MATE II programmer or PICSTART Plus, and easily test firmware. The
MPLAB-ICE emulator may also be used with the PICDEM-2 board to test firmware. Additional
prototype area has been provided for additional hardware. Some of the features include a
RS-232 interface, push-button switches, a potentiometer for simulated analog input, a Serial
EEPROM to demonstrate usage of the I2C bus and separate headers for connection to an LCD
module and a keypad.
39500 18C Reference Manual.book Page 12 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39535A-page 34-13
Section 34. Development Tools
Development
Tools
34
34.10.3 PICDEM-3 Low-Cost PIC16CXXX Demonstration Board
The PICDEM-3 is a simple demonstration board that supports the PIC16C923 and PIC16C924
in the PLCC package. It will also support future 44-pin PLCC microcontrollers that have an
LCD Module. All the necessary hardware and software is included to run the basic demonstration
programs. The user can program the sample microcontrollers, provided with
the PICDEM-3 board, on a PRO MATE II programmer or PICSTART Plus with an adapter
socket, and easily test firmware. The MPLAB-ICE emulator may also be used with the PICDEM-3
board to test firmware. Additional prototype area has been provided for adding hardware. Some
of the features include an RS-232 interface, push-button switches, a potentiometer for simulated
analog input, a thermistor and separate headers for connection to an external LCD module and
a keypad. Also provided on the PICDEM-3 board is an LCD panel, with 4 commons and 12 segments,
that is capable of displaying time, temperature and day of the week. The PICDEM-3 provides
an additional RS-232 interface and Windows 3.1 software for showing the de-multiplexed
LCD signals on a PC. A simple serial interface allows the user to construct a hardware
de-multiplexer for the LCD signals.
34.10.4 PICDEM-14A Low-Cost PIC14C000 Demonstration Board
The PICDEM-14A demo board is a general purpose platform which is provided to help evaluate
the PIC14C000 mixed signal microcontroller. The board runs a PIC14C000 measuring the voltage
of a potentiometer and the on-chip temperature sensor. The voltages are then calibrated to
the internal bandgap voltage reference. The voltage and temperature data are then transmitted
to the RS-232 port. This data can be displayed using a terminal emulation program, such as Windows
Terminal. This demo board also includes peripherals that allow users to display data on an
LCD panel, read from and write to a serial EEPROM, and prototype custom circuitry to interface
to the microcontroller.
34.10.5 PICDEM-17
The PICDEM-17 is an evaluation board that demonstrates the capabilities of several Microchip
microcontrollers, including PIC17C752, PIC17C756, PIC17C762, and PIC17C766. All necessary
hardware is included to run basic demo programs, which are supplied on a 3.5-inch disk. A
programmed sample is included, and the user may erase it and program it with the other sample
programs using the PRO MATE II or PICSTART Plus device programmers and easily debug and
test sample code. In addition, PICDEM-17 supports down-loading of programs to and executing
out of external FLASH memory on board. The PICDEM-17 is also usable with the MPLAB-ICE
emulator, and all of the sample programs can be run and modified using that emulator. Additionally,
a generous prototype area is available for user hardware.
39500 18C Reference Manual.book Page 13 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39535A-page 34-14 2000 Microchip Technology Inc.
34.11 Development Tools for Other Microchip Products
34.11.1 SEEVAL Evaluation and Programming System
The SEEVAL Serial EEPROM Designer’s Kit supports all Microchip 2-wire and 3-wire Serial
EEPROMs. The kit includes everything necessary to read, write, erase or program special features
of any Microchip SEEPROM product including Smart SerialsTM and secure serials. The
Total EnduranceTM Disk is included to aid in trade-off analysis and reliability calculations. The
total endurance kit can significantly reduce time-to-market and results in a more optimized
system.
34.11.2 KEELOQ Evaluation and Programming Tools
KEELOQ evaluation and programming tools supports Microchip’s HCS Secure Data Products.
The HCS evaluation kit includes an LCD display to show changing codes, a decoder to decode
transmissions, and a programming interface to program test transmitters.
39500 18C Reference Manual.book Page 14 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39535A-page 34-15
Section 34. Development Tools
Development
Tools
34
34.12 Related Application Notes
This section lists application notes that are related to this section of the manual. These application
notes may not be written specifically for the Enhanced MCU family (that is they may be written
for the Base-Line, Mid-Range, or the High-End), but the concepts are pertinent, and could be
used (with modification and possible limitations). The current application notes related to Microchip’s
development tools are:
Title Application Note #
No related application notes at this time.
Note: Several of the tools have tutorials which may be helpful in learning the tools. Please
refer to the specific tool’s documentation for tutorial availability.
Note: Please visit the Microchip Web site for additional software code examples. These
code examples are stand alone examples to assist in the understanding of the
PIC18CXXX. The web address for these examples is:
http://www.microchip.com/10/faqs/codeex/
39500 18C Reference Manual.book Page 15 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39535A-page 34-16 2000 Microchip Technology Inc.
34.13 Revision History
Revision A
This is the initial released revision of Microchip’s development tools description.
39500 18C Reference Manual.book Page 16 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39536A-page 35-1
Code
Development
35
Section 35. Code Development
HIGHLIGHTS
This section of the manual contains the following major topics:
35.1 Overview ...................................................................................................................... 35-2
35.2 Good Practice .............................................................................................................. 35-3
35.3 Diagnostic Code Techniques ....................................................................................... 35-5
35.4 Example Scenario and Implementation ....................................................................... 35-6
35.5 Implications of Using a High Level Language (HLL) .................................................... 35-7
35.6 Revision History ........................................................................................................... 35-8
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39536A-page 35-2 2000 Microchip Technology Inc.
35.1 Overview
This section covers some good programming practice as well as some diagnostic techniques that
can be used in both the development stage, and the production release to help diagnose unexpected
operation in the field. The advantage of including diagnostic code is that the device continually
displays its status and the operational flow of the program.
These suggestions only scratch the surface of the possible techniques and good programming
practices. Future revisions of this section will add additional suggestions on good programming
practice and diagnostic techniques.
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39536A-page 35-3
Section 35. Code Development
Code
Development
35
35.2 Good Practice
The following are some recommended programming practices. These will help ensure consistent
program operation based on the stimulus supplied to the application software.
35.2.1 Use of Symbolic Code
Microchip supplies header files which use the register and bit name symbols specified in the
device data sheets. The use of these symbols aids in several facets of software development.
First, symbolic code makes the source file easier to read since the names relate to a function (as
opposed to register addresses and bit positions). Example 35-1 shows two implementations. The
first, though technically correct, is more difficult to follow then the second implementation. Also,
the second allows for easier migration between devices (and PICmicro families) since any
remapping of bit positions and register locations can automatically be handled by the software
tool.
Example 35-1:Hard Coding vs. Symbolic Code
35.2.2 Initialization of Data Memory
All Data Memory locations (SFRs and GPRs) should be initialized after a RESET. This will ensure
that they are at a known state when the application code accesses each location, and ensures
consistent operation
When all data memory is not initialized, there is a possibility that the application software will read
a location that is an indeterminate value. This may cause unexpected results from the application
software. This issue is sometimes highlighted when development moves from a windowed
device (where the window was not covered) to an OTP package.
BCF 0xD8, 0, 0 ; Clear the carry bit
: ;
BCF STATUS, C ; Clear the carry bit
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39536A-page 35-4 2000 Microchip Technology Inc.
35.2.3 Trap for Unexpected Conditions
Sometimes the application software will test only for the expected conditions. This is typically
seen in the Interrupt Service Routine where only the expected sources for an interrupt are tested
for. Example 35-2 shows a typical way that the conditions are tested, while Example 35-3 shows
a more robust version. The TrapRoutine may do more then just loop waiting for a RESET. It
could output a code on an I/O pin to indicate that this unexpected condition occurred.
Example 35-2:Typical ISR Code
Example 35-3:Recommended ISR Code (with Trap)
35.2.4 Filling Unused Locations
In most application programs, not all program memory locations are used. These unprogrammed
locations (0xFFFF) execute as a NOP instruction. Since program execution is never intended to
go to one of these locations, the program should trap any occurrence of this. A good way to handle
this is to “fill” all unprogrammed locations with a branch which goes to its own program memory
location. With this, the WDT must be enabled to cause a device RESET and restart program
execution.
The Microchip Assembler supplies a directive to do this. This directive is the “fill” directive.
ORG ISRVectorAddress ; Address for Interrupt Service
; Routine
ISRH BTFSS PIR1, ADIF ; A/D Interrupt?
GOTO ADRoutine ; Yes, do A/D stuff
BTFSS PIR1, RCIF ; AUSART Receive Interrupt?
GOTO ReceiveRoutine ; Yes, do Receive stuff
CCPRoutine ; Since not other interrupt sources
: ; must be CCP interrupt
ORG ISRVectorAddress ; Address for Interrupt Service
; Routine
ISRH BTFSS PIR1, ADIF ; A/D Interrupt?
GOTO ADRoutine ; Yes, do A/D stuff
BTFSS PIR1, RCIF ; AUSART Receive Interrupt?
GOTO ReceiveRoutine ; Yes, do Receive stuff
BTFSS PIR1, CCPIF ; CCP Interrupt?
GOTO CCPRoutine ; Yes, do CCP stuff
TrapRoutine ; Should NEVER get here
GOTO TrapRoutine ; If we do, loop forever and
; wait for WDT reset
Note: Remember that the CLRWDT instruction should have a minimum number of occurrences
in the program and that the maximum time between the CLRWDT instructions
must NOT be greater than the minimum WDT time-out period, multiplied by the
selected prescaler.
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39536A-page 35-5
Section 35. Code Development
Code
Development
35
35.3 Diagnostic Code Techniques
This section describes diagnostic code that can be embedded into the application code to help
track the operation of the application software. Typically some mechanism is required to make
the information available to the external world. This can be from a serial port (such as the Addressable
USART module) or from extra I/O pins not used by the application.
35.3.1 Function Sequence
Have the diagnostic code output a unique code (value) for each function that the program enters.
This allows the flow of the program to be monitored from outside the device (with a logic analyzer)
and assist in determining if there is some unexpected condition that is causing code to execute
in the observed sequence.
35.3.2 Stack Depth
A counter can be implemented that is incremented in each function that is called and each time
that the program counter is at an interrupt vector address. The counter is then decremented at
the end of the function or interrupt service routine. The value of the stack can then be output to
indicate if the stack depth is out of its normal range (minimum and maximum).
35.3.3 A/D Operation
Visibility into the operation of the A/D can help validate the operation. Monitoring if the acquisition
time is the expected time delay, as well as the result generated by the module. Achieving the A/D
result accuracy depends on may factors, some internal and many external. The major internal
factor is that there is a sufficient amount of time once the input channel is selected, until the conversion
is started. This is called the acquisition time (TACQ).
35.3.3.1 A/D Acquisition Time
Use an I/O pin to indicate when the acquisition of the channel starts (toggle high) until the conversion
is started (toggle high). If the input channel is changed force the I/O to toggle high. The
last two I/O toggles before the A/D result is available, is acquisition time that the A/D had for that
selected channel.
35.3.3.2 A/D Result
Output the result so that you can determine if the program execution flow can be attributed to the
result from the A/D converter.
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39536A-page 35-6 2000 Microchip Technology Inc.
35.4 Example Scenario and Implementation
In this example application, one I/O port is not implemented. This means that there are eight I/O
pins available to indicate the operational status of the PICmicro device and the flow of the application
software. Let’s say that the code implements 57 functions, the A/D is used and Addressable
USART are used.
Six bits (Code5:Code0) are required to uniquely specify the 57 functions. After each function gets
a code, an additional 7 codes are available. Table 35-1 shows how these codes could be defined,
while Table 35-2 shows how the diagnostic output port could be defined.
Table 35-1: Definitions of Additional Codes
Table 35-2: PORT Function assignment
So, as the device exits RESET, the PORT = ‘1111 11xx’ where the xx indicates the source of the
device RESET. Then the code for the main function is output on Rx7:Rx2 and Rx1:Rx0 = ‘00’. As
each function gets called, the stack depth is output. This requires that the code Rx7:Rx2 = ‘1111
11’ is output, then the stack depth counter is moved to the PORT. The code for the entered function
is then output.
After the A/D is enabled and acquisition of the selected channel begins, the Rx1 pin is toggled
high. Each event that causes the input to start a new acquisition time should cause the Rx1 pin
to toggle. These events include:
• Selection of a new input channel
• The completion of an A/D conversion
• Disabling and then re-enabling the A/D module
When an A/D conversion completes or the addressable USART receives a byte, the appropriate
code is output on the PORT and then the value is output.
6-bit Code Definition
1111 11 Next Byte out is stack depth
1111 10 Next Byte out is A/D Result High Byte
1111 01 Next Byte out is Addressable USART received byte
1111 00 Next Byte out is A/D Result Low Byte
0000 00 Device has exited a device RESET. Rx1:Rx0 can be used to indicate the
source of the RESET.
Pin Normal Mode
Mode after
“Additional Codes”
displayed
RESET
Rx7 Code5
Byte value for the
indicated function
0
Rx6 Code4 0
Rx5 Code3 0
Rx4 Code2 0
Rx3 Code1 0
Rx2 Code0 0
Rx1 Toggle for Start
of acquisition
4 codes
available to
indicate source
of RESET
Rx0 Toggle for Stop
of acquisition
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39536A-page 35-7
Section 35. Code Development
Code
Development
35
35.5 Implications of Using a High Level Language (HLL)
The use of a High Level Language, such as a C compiler, speeds the development cycle but can
increase the difficulty in the use of diagnostic code. When writing at the high level, functions may
be defined, but how the C compilers will implement those functions is hidden from the user. If the
function is used only once, the C complier may put that code in-line or use a GOTO to branch to
the function and a GOTO to return from the function. In both these implementations, the stack is
not affected. Also, if the function is called many times, but is small, it may be put inline. This again
will not affect the stack used. These techniques used by the compiler may lead to efficient code
generation, but may add to the difficulty in adding diagnostic code.
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39536A-page 35-8 2000 Microchip Technology Inc.
35.6 Revision History
Revision A
This is the initial released revision for the Code Development with a PICmicro device description.
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39537A-page 36-1
Appendix
36
Section 36. Appendix
APPENDIX A: I2C OVERVIEW
This appendix provides an overview of the Inter-Integrated Circuit (I2C™) bus, with Subsection
A.2 “Addressing I2C Devices” discussing the operation of the SSP modules in I2C mode.
The I2C bus is a two-wire serial interface. The original specification, or standard mode, is for data
transfers of up to 100 Kbps. An enhanced specification, or fast mode (400 Kbps) is supported.
Standard and Fast mode devices will operate when attached to the same bus, if the bus operates
at the speed of the slower device.
The I2C interface employs a comprehensive protocol to ensure reliable transmission and reception
of data. When transmitting data, one device is the “master” which initiates transfer on the bus
and generates the clock signals to permit that transfer, while the other device(s) acts as the
“slave.” All portions of the slave protocol are implemented in the SSP module’s hardware, except
general call support, while portions of the master protocol need to be addressed in the
PIC16CXX software. The MSSP module supports the full implementation of the I2
C master protocol,
the general call address, and data transfers up to 1 Mbps. The 1 Mbps data transfers are
supported by some of Microchips Serial EEPROMs. Table A-1 defines some of the I2C bus terminology.
In the I2C interface protocol each device has an address. When a master wishes to initiate a data
transfer, it first transmits the address of the device that it wishes to “talk” to. All devices “listen” to
see if this is their address. Within this address, a bit specifies if the master wishes to
read-from/write-to the slave device. The master and slave are always in opposite modes (transmitter/receiver)
of operation during a data transfer. That is, they can be thought of as operating
in either of these two relations:
• Master-transmitter and Slave-receiver
• Slave-transmitter and Master-receiver
In both cases the master generates the clock signal.
The output stages of the clock (SCL) and data (SDA) lines must have an open-drain or open-collector
in order to perform the wired-AND function of the bus. External pull-up resistors are used
to ensure a high level when no device is pulling the line down. The number of devices that may
be attached to the I2C bus is limited only by the maximum bus loading specification of 400 pF
and addressing capability.
I
2C is a trademark of Philips Corporation.
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39537A-page 36-2 2000 Microchip Technology Inc.
A.1 Initiating and Terminating Data Transfer
During times of no data transfer (idle time), both the clock line (SCL) and the data line (SDA) are
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.
Figure A-1: Start and Stop Conditions
SDA
SCL S P
START
Condition
Change
of Data
Allowed
Change
of Data
Allowed
STOP
Condition
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39537A-page 36-3
Section 36. Appendix
Appendix
36
Table A-1: I2
C Bus Terminology
Term Description
Transmitter The device that sends the data to the bus.
Receiver The device that receives the data from the bus.
Master The device which initiates the transfer, generates the clock and terminates
the transfer.
Slave The device addressed by a master.
Multi-master More than one master device in a system. These masters can attempt to
control the bus at the same time without corrupting the message.
Arbitration Procedure that ensures that only one of the master devices will control the
bus. This ensure that the transfer data does not get corrupted.
Synchronization Procedure where the clock signals of two or more devices are synchronized.
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39537A-page 36-4 2000 Microchip Technology Inc.
A.2 Addressing I2C Devices
There are two address formats. The simplest is the 7-bit address format with a R/W bit
(Figure A-2). The more complex is the 10-bit address with a R/W bit (Figure A-3). For 10-bit
address format, two bytes must be transmitted. The first five bits specify this to be a 10-bit
address format. The 1st transmitted byte has 5 bits which specify a 10-bit address, the two MSbs
of the address, and the R/W bit. The second byte is the remaining 8 bits of the address.
Figure A-2: 7-bit Address Format
Figure A-3: I2C 10-bit Address Format
S R/W ACK
Sent by
Slave
Slave Address
S
R/W Read/Write pulse
MSb LSb
START Condition
ACK Acknowledge
S 1 1 1 1 0 A9 A8R/W ACK A7 A6 A5 A4 A3 A2 A1 A0 ACK
Sent By Slave
= 0 for write
S
R/W
ACK
- START Condition
- Read/Write Pulse
- Acknowledge
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39537A-page 36-5
Section 36. Appendix
Appendix
36
A.3 Transfer Acknowledge
All data must be transmitted per byte, with no limit to the number of bytes transmitted per data
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).
Figure A-4: Slave-Receiver Acknowledge
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.
Figure A-5: Data Transfer Wait State
S
Data
Output by
Transmitter
Data
Output by
Receiver
SCL from
Master
START
Condition
Clock Pulse for
Acknowledgment
not acknowledge
acknowledge
1 2 8 9
1 2 7 8 9 123 • 8 9 P
SDA
SCL S
START
Condition Address R/W ACK Wait
State
Data ACK
MSb Acknowledgment
Signal from Receiver
Acknowledgment
Signal from Receiver Byte Complete
Interrupt with Receiver
Clock Line Held Low while
Interrupts are Serviced
STOP
Condition
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39537A-page 36-6 2000 Microchip Technology Inc.
Figure A-6 and Figure A-7 show Master-transmitter and Master-receiver data transfer
sequences.
Figure A-6: Master-Transmitter Sequence
Figure A-7: Master-Receiver Sequence
For 7-bit address:
S
Slave Address
(Code + A9:A8)
S R/W A1 Slave Address
(A7:A0)
A2 Data A Data P
A master transmitter addresses a slave receiver
with a 10-bit address.
A/A
Slave Address R/W A Data A Data A/A P
'0' (write) data transferred
(n bytes - acknowledge)
A master transmitter addresses a slave receiver with a
7-bit address. The transfer direction is not changed.
From master to slave
From slave to master
A = acknowledge (SDA low)
A = not acknowledge (SDA high)
S = START Condition
P = STOP Condition
(write)
For 10-bit address:
For 7-bit address:
S
Slave Address
(Code + A9:A8)
S R/W A1 Slave Address
(A7:A0)
A2
A master transmitter addresses a slave receiver
with a 10-bit address.
Slave Address R/W A Data A Data A P
'1' (read) data transferred
(n bytes - acknowledge)
A master reads a slave immediately after the first byte.
From master to slave
From slave to master
A = acknowledge (SDA low)
A = not acknowledge (SDA high)
S = START Condition
P = STOP Condition
(write)
For 10-bit address:
Slave Address
(Code + A9:A8)
Sr R/W A3 A Data A P Data
(read)
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39537A-page 36-7
Section 36. Appendix
Appendix
36
When a master does not wish to relinquish the bus (which occurs by generating a STOP condition),
a repeated START condition (Sr) must be generated. This condition is identical to the
START condition (SDA goes high-to-low while SCL is high), but occurs after a data transfer
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 shown in Figure A-8.
Figure A-8: Combined Format
Combined format:
S
Combined format - A master addresses a slave with a 10-bit address, then transmits
Slave Address R/W A Data A/A Sr P
(read) Sr = repeated
Transfer direction of data and acknowledgment bits depends on R/W bits.
From master to slave
From slave to master
A = acknowledge (SDA low)
A = not acknowledge (SDA high)
S = START Condition
P = STOP Condition
Slave Address
(Code + A9:A8)
Sr R/W A
(write)
data to this slave and reads data from this slave.
Slave Address
(A7:A0)
Data Sr Slave Address
(Code + A9:A8)
A A Data A/A R/W A Data A A Data P
(read)
Slave Address R/W A Data A/A
START Condition
(write) Direction of transfer
may change at this point
(read or write)
(n bytes + acknowledge)
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39537A-page 36-8 2000 Microchip Technology Inc.
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.
Figure A-9: Multi-Master Arbitration (Two Masters)
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.
Transmitter 1 Loses Arbitration
DATA 1 SDA
DATA 1
DATA 2
SDA
SCL
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39537A-page 36-9
Section 36. Appendix
Appendix
36
A.4.2 Clock Synchronization
Clock synchronization occurs after the devices have started arbitration. This is performed using
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.
Figure A-10:Clock Synchronization
CLK 1
CLK 2
SCL
Wait
State
Start Counting
High Period
Counter
Reset
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39537A-page 36-10 2000 Microchip Technology Inc.
Table A-2 and Table A-3 show the specifications of a compliant I2
C bus. The column titled Microchip
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.
Figure A-11: I2C Bus Start/Stop Bits Timing Specification
Table A-2: I2C Bus Start/Stop Bits Timing Specification
Figure A-12: I2C Bus Data Timing Specification
Microchip
Parameter
No.
Sym Characteristic Min Typ Max Units Conditions
90 TSU:STA START condition 100 kHz mode 4700 — — ns Only relevant for
repeated START condition
Setup time 400 kHz mode 600 — —
91 THD:STA START condition 100 kHz mode 4000 — — ns After this period the first
Hold time 400 kHz mode 600 — — clock pulse is generated
92 TSU:STO STOP condition 100 kHz mode 4700 — — ns
Setup time 400 kHz mode 600 — —
93 THD:STO STOP condition 100 kHz mode 4000 — — ns
Hold time 400 kHz mode 600 — —
91 93
SCL
SDA
START
Condition
STOP
Condition
90 92
90
91 92
100
101
103
106
107
109 109
110
102
SCL
SDA
In
SDA
Out MSb
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39537A-page 36-11
Section 36. Appendix
Appendix
36
Table A-3: I2
C Bus Data Timing Specification
Microchip
Parameter
No.
Sym Characteristic Min Max Units Conditions
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 time
100 kHz mode — 1000 ns
400 kHz mode 20 +
0.1Cb
300 ns Cb is specified to be from
10 to 400 pF
103 TF SDA and SCL fall
time
100 kHz mode — 300 ns
400 kHz mode 20 +
0.1Cb
300 ns Cb is specified to be from
10 to 400 pF
90 TSU:STA START condition
setup time
100 kHz mode 4.7 — µs Only relevant for repeated
400 kHz mode 0.6 — µs START condition
91 THD:STA START condition
hold time
100 kHz mode 4.0 — µs After this period the first
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 time
100 kHz mode 4.7 — µs
400 kHz mode 0.6 — µs
109 TAA Output valid from
clock
100 kHz mode — 3500 ns Note 1
400 kHz mode — 1000 ns
110 TBUF Bus free time 100 kHz mode 4.7 — µs Time the bus must be free
before a new transmission
can start
400 kHz mode 1.3 — µs
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.
39500 18C Reference Manual.book Page 11 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39537A-page 36-12 2000 Microchip Technology Inc.
APPENDIX B: CAN OVERVIEW
This appendix provides an overview of the Controller Area Network (CAN) bus. The CAN Section
of this reference manual discusses the implementation of the CAN protocol in that hardware
module.
Not available at this time.
39500 18C Reference Manual.book Page 12 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39537A-page 36-13
Section 36. Appendix
Appendix
36
APPENDIX C: MODULE BLOCK DIAGRAMS AND REGISTERS
This appendix summarizes the block diagrams of the major circuits.
Not available at this time.
39500 18C Reference Manual.book Page 13 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39537A-page 36-14 2000 Microchip Technology Inc.
APPENDIX D: REGISTER DEFINITIONS
This appendix summarizes the register definitions.
Not available at this time.
39500 18C Reference Manual.book Page 14 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39537A-page 36-15
Section 36. Appendix
Appendix
36
APPENDIX E: MIGRATION TIPS
This appendix gives an overview of some things that need to be taken into account when migrating
code from other PICmicro families to the PIC18CXXX. For additional information, please also
refer to the following application notes:
• AN716
• AN726
Three major changes Timer0 has from the mid-range family are:
1. The Timer0 no longer shares the prescaler with the Watchdog Timer.
2. Timer0 has 16-bit as well as 8-bit capability.
3. Timer0 can now be turned off.
The default state for Timer0 is an 8-bit counter for downward compatibility with the mid-range
Timer0.
The prescaler is no longer shared between the Timer0 module and the Watchdog Timer. Each
have their own separate prescalers.
Thus, a prescaler assignment for the Timer0 has no effect on the Watchdog Timer, and
vice-versa.
T1OSCEN bit is now OSCEN.
The program space is implemented as a single contiguous block, as compared to Microchip’s
mid-range and high-end controllers that divided the program memory into pages.
If interrupt priority is not used, all interrupts are treated as high priority, and function the same
way as in mid-range and high-end controllers.
If interrupt priority is not used (all interrupt priority bits are set), GIE and PEIE/GIEL function the
same as mid-range and high-end controllers.
Look-up tables are implemented two ways in the 18CXXX devices. The Computed Goto is compatible
with the PIC16CXXX and PIC17CXXX parts. Code written for those devices will run on
the PIC18CXXX devices with little or no change.
Table reads are implemented on the PIC17CXXX and PIC18CXXX devices. However, table
operations on the PIC18CXXX work differently than on the PIC17CXXX.
Note: The Timer0 prescaler is not shared with the watchdog as a postscaler. The Watchdog
Timer has its own dedicated postscaler. The control bits and prescaler select
bits are implemented as EPROM configuration bits.
Note: To achieve a 1:1 prescaler assignment for the TMR0 register, turn off the TMR0
prescaler (PSA is cleared).
39500 18C Reference Manual.book Page 15 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39537A-page 36-16 2000 Microchip Technology Inc.
E.1 Differences to the Mid-Range CCP module
The CCP1 and CCP2 modules function exactly as the modules of the mid-range devices with
two exceptions:
1. The time base used for capture and compare of the CCP module can come from either
Timer1 or Timer3. The default time base for both CCP modules when configured as a capture
or compare mode is Timer1. Timer3 can be selected by configuring the Timer3
T3CCPx control bits in the Timer3 control register.
2. A toggle on compare mode has been added to the CCP modules.
E.1.1 Compatibility to PIC16CXX Interrupts
When the IPE bit in the RCON register is clear, the GIE/GIEH bit (INTCON<7>) is the global interrupt
enable for all interrupts. The PEIE/GIEL bit (INTCON<6>) is still used to enable peripheral
interrupts. The high priority interrupt vector is the same as the PIC16CXX interrupt vector and
returns will work the same way. ISR code written for the PIC16CXX devices run unchanged as
long as IPE=0.
39500 18C Reference Manual.book Page 16 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39537A-page 36-17
Section 36. Appendix
Appendix
36
E.2 Instruction Set Comparison
Table E-1 shows all the PIC18CXXX instructions and if that instruction is available in the other
families (PIC17CXXX, PIC16CXX, or PIC16C5XX). Some instructions may be available, but
have slightly different characteristics. Attached are notes regarding any major differences.
Table E-1: PIC18CXXX Instruction Set Comparison
BYTE-ORIENTED FILE REGISTER OPERATIONS
PIC18CXXX Instruction Set PIC17CXX PIC16CXX PIC16C5X
ADDWF Yes Yes Yes
ADDWFC Yes — —
ANDWF Yes Yes Yes
CLRF Yes (Note 1) Yes Yes
COMF Yes Yes Yes
CPFSEQ Yes — —
CPFSGT Yes — —
CPFSLT Yes — —
DAW Yes (Note 5) — —
DCFSNZ Yes — —
DECF Yes Yes Yes
DECFSZ Yes Yes Yes
INCF Yes Yes Yes
INCFSZ Yes Yes Yes
INFSNZ Yes — —
IORWF Yes Yes Yes
MOVF — Yes Yes
MOVFF — ——
MOVWF Yes Yes Yes
MULWF Yes — —
NEGF Yes (Note 6) — —
NOP Yes Yes Yes
Note 1: CLRF and SETF instructions do not have ’s’ bit that exists in the PIC17CXX instructions.
2: CLRW does not exist as an instruction, but since the WREG is mapped in address space, WREG can be
cleared using the CLRF instruction.
3: The RLCF and RRCF instructions are functionally identical to the PIC16CXX instructions RLF and RRF.
4: CALL and GOTO instructions are now 2-word instructions.
5: DAW always has the WREG as the destination. The PIC17CXX can also have a file as the destination.
6: NEGW is replaced by NEGF with the file register always being the destination.
7: The mnemonics for 17CXX instructions TABLRD and TABLWT are changed to TBLRD and TBLWT, respectively,
and these instructions are special instructions which only exchange data between the TABLAT and
the program memory.
8: The lower nibble of the Bank Select Register (BSR) now specifies which bank of RAM is selected.
39500 18C Reference Manual.book Page 17 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39537A-page 36-18 2000 Microchip Technology Inc.
BYTE-ORIENTED FILE REGISTER OPERATIONS (Continued)
Instruction Set PIC17CXX PIC16CXX PIC16C5X
RLCF Yes Yes (Note 3) Yes (Note 3)
RLNCF Yes — —
RRCF Yes Yes (Note 3) Yes (Note 3)
RRNCF Yes — —
SETF Yes (Note 1) — —
SUBFWB — ——
SUBWF Yes Yes Yes
SUBWFB Yes — —
SWAPF Yes Yes Yes
TABLRD Yes (Note 7) — —
TABLWT Yes (Note 7) — —
TSTFSZ Yes — —
XORWF Yes Yes Yes
BIT-ORIENTED FILE REGISTER OPERATIONS
Instruction Set PIC17CXX PIC16CXX PIC16C5X
BCF Yes Yes Yes
BSF Yes Yes Yes
BTFSC Yes Yes Yes
BTFSS Yes Yes Yes
BTG Yes — —
Note 1: CLRF and SETF instructions do not have ’s’ bit that exists in the PIC17CXX instructions.
2: CLRW does not exist as an instruction, but since the WREG is mapped in address space, WREG can be
cleared using the CLRF instruction.
3: The RLCF and RRCF instructions are functionally identical to the PIC16CXX instructions RLF and RRF.
4: CALL and GOTO instructions are now 2-word instructions.
5: DAW always has the WREG as the destination. The PIC17CXX can also have a file as the destination.
6: NEGW is replaced by NEGF with the file register always being the destination.
7: The mnemonics for 17CXX instructions TABLRD and TABLWT are changed to TBLRD and TBLWT, respectively,
and these instructions are special instructions which only exchange data between the TABLAT and
the program memory.
8: The lower nibble of the Bank Select Register (BSR) now specifies which bank of RAM is selected.
39500 18C Reference Manual.book Page 18 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39537A-page 36-19
Section 36. Appendix
Appendix
36
CONTROL OPERATIONS
Instruction Set PIC17CXX PIC16CXX PIC16C5X
BC — ——
BN — ——
BNC — ——
BNN — ——
BNV — ——
BNZ — ——
BRA — ——
BV — ——
BZ — ——
CALL (Note 4) Yes Yes Yes
CLRWDT Yes Yes Yes
GOTO (Note 4) Yes Yes Yes
POP — ——
PUSH — ——
RCALL — ——
RESET — ——
RETFIE Yes Yes
RETURN Yes Yes Yes
SLEEP Yes Yes Yes
LITERAL OPERATIONS
Instruction Set PIC17CXX PIC16CXX PIC16C5X
ADDLW Yes Yes Yes
ANDLW Yes Yes Yes
IORLW Yes Yes Yes
LFSR — ——
MOVLB Yes (Note 8) — —
MOVLW Yes Yes Yes
MULLW Yes — —
RETLW Yes Yes Yes
SUBLW Yes Yes Yes
XORLW Yes Yes Yes
Note 1: CLRF and SETF instructions do not have ’s’ bit that exists in the PIC17CXX instructions.
2: CLRW does not exist as an instruction, but since the WREG is mapped in address space, WREG can be
cleared using the CLRF instruction.
3: The RLCF and RRCF instructions are functionally identical to the PIC16CXX instructions RLF and RRF.
4: CALL and GOTO instructions are now 2-word instructions.
5: DAW always has the WREG as the destination. The PIC17CXX can also have a file as the destination.
6: NEGW is replaced by NEGF with the file register always being the destination.
7: The mnemonics for 17CXX instructions TABLRD and TABLWT are changed to TBLRD and TBLWT, respectively,
and these instructions are special instructions which only exchange data between the TABLAT and
the program memory.
8: The lower nibble of the Bank Select Register (BSR) now specifies which bank of RAM is selected.
39500 18C Reference Manual.book Page 19 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39537A-page 36-20 2000 Microchip Technology Inc.
Table E-2 shows the instructions that are used in the other PICmicro families, but are not used in
the PIC18CXXX instruction set.
Table E-2: Instructions Not Implemented or Modified From PIC18CXXX
BYTE-ORIENTED FILE REGISTER OPERATIONS
Instruction PIC17CXX PIC16CXX PIC16C5X Comment
CLRW — Yes (Note 1) — = CLRF WREG
DAW Yes (Note 6) — —
MOVFP Yes (Note 7) — — = MOVFF REG1, REG2
MOVPF Yes (Note 7) — — = MOVFF REG2, REG1
NEGW Yes (Note 3) — —
RLF — Yes (Note 4) Yes (Note 4)
RRF — Yes (Note 4) Yes (Note 4)
TLRD Yes — —
TLWT Yes — —
CONTROL OPERATIONS
Instruction PIC17CXX PIC16CXX PIC16C5X
CALL Yes (Note 2) Yes (Note 2) Yes (Note 2)
GOTO Yes (Note 2) Yes (Note 2) Yes (Note 2)
LCALL Yes — —
MOVLR Yes — —
OPTION — — (Note 5) Yes
TRIS — — (Note 5) Yes
LITERAL OPERATIONS
Instruction PIC17CXX PIC16CXX PIC16C5X
MOVLR Yes — —
Note 1: CLRW does not exist as an instruction, but since the WREG is mapped in address space, WREG can be
cleared using the CLRF instruction.
2: CALL and GOTO instructions are now 2-word instructions.
3: NEGW is replaced by NEGF with the file register always being the destination.
4: The mnemonics for RLF and RRF have been changed to RLCF and RRCF, respectively, but the functionality
is identical.
5: This instruction is not recommended in PIC16CXX devices.
6: The PIC17CXX may also specify the file as the destination.
7: When migrating software the MOVFF instruction can be used.
39500 18C Reference Manual.book Page 20 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39537A-page 36-21
Section 36. Appendix
Appendix
36
APPENDIX F: ASCII CHARACTER SET
The PICmicro assembler recognizes the ASCII characters shown in Table F-1.
Table F-1: ASCII Character Set (7-bit Code)
Least
Significant
nibble (LSn)
Most Significant nibble (MSn)
0
(0)
1
(16)
2
(32)
3
(48)
4
(64)
5
(80)
6
(96)
7
(112)
0 NUL DLE SP 0 @ P ’ p
1 SOH DC1 ! 1 A Q a q
2 STX DC2 " 2 B R b r
3 ETX DC3 # 3 C S c s
4 EOT DC4 $ 4 D T d t
5 ENQ NAK % 5 E U e u
6 ACK SYN & 6 F V f v
7 BEL ETB ’ 7 GWg w
8 BS CAN ( 8 H X h x
9 HT EM ) 9 I Y i y
A LF SUB * : J Z j z
B VT ESC + ; K [ k {
C FF FS , < L \ l |
D CR GS — =M ] m}
E SO RS . > N ^ n ~
F SI US / ? O _ o DEL
Note: To obtain the decimal value, add the decimal most significant nibble (MSn) to the decimal least significant
nibble (LSn).
39500 18C Reference Manual.book Page 21 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39537A-page 36-22 2000 Microchip Technology Inc.
APPENDIX G: COMMON SOCKET PINOUTS
This appendix shows the pinouts for some of the standard sockets that are commonly used in
prototype and production applications. You may use these pinouts when you wiretap your breadboard
with a socket. These diagrams will make constructing, debugging, and troubleshooting
with the Picmicro families quicker and easier.
These figures shown in this appendix are for sockets that correspond to the following package
types:
PLCC-to-PGA sockets
• 28-pin PLCC/CLCC
• 44-pin PLCC/CLCC
• 68-pin PLCC/CLCC
DIP sockets
• 18-pin
• 28-pin
• 40-pin
SOIC sockets
• 18-pin
• 28-pin
39500 18C Reference Manual.book Page 22 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39537A-page 36-23
Section 36. Appendix
Appendix
36
Figure G-1: DIP Packages Pinouts (Bottom View )
1
2
3
4
5
6
7
8
9
18
17
16
15
14
13
12
11
10
18-pin
1
2
3
4
5
6
7
8
9
10
11
12
13
14
28
27
26
25
24
23
22
21
20
19
18
17
16
15
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
40
39
38
37
36
35
34
33
32
31
30
29
28
27
26
25
24
23
22
21
28-pin
40-pin
Bottom
View
Bottom
View
Bottom
View
39500 18C Reference Manual.book Page 23 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39537A-page 36-24 2000 Microchip Technology Inc.
Figure G-2: PGA Package Pinout (Bottom View) for LCC Packages
26 28
25 27 1 3 6 5
2 4
23 24
21 22
19 20 17 15
16 14
13
12
11
10 9
18
8 7
28-pin
42 44
39 43 1 3 5 7
2 4
35
31
29 27 25 23
24 22
21
18
17
15
26
11
33 13
37 9
41
36
32
30
34
38
8
19
16
12
14
10
28
6
20
40
44-pin
Bottom
View
Bottom
View
39500 18C Reference Manual.book Page 24 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39537A-page 36-25
Section 36. Appendix
Appendix
36
Figure G-2: PGA Package Pinout (Bottom View) for LCC Packages (Continued)
61 63
62 64 66 2
12
65 67
35 27
25
23
24
21 20
18
17
15
41 37 33
38 36 34 32 30
8
19
14
13
28
6
22
4
16
1
44
3 579
60 68 11 10
31 29
40
39
42
43
45
46 47
48 49
50 51
52 53
54 55
56 57
58 59
26
68-pin
39500 18C Reference Manual.book Page 25 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39537A-page 36-26 2000 Microchip Technology Inc.
Figure G-2: PGA Package Pinout (Bottom View) for LCC Packages (Continued)
75 77
76 78 80 2
79 83
41 33
25
23
24
21 20
18
17
15
47 43 39
44 42 38 36 40
8
19
14
27
6
22
4
16
1
54
3579
74 84 10 13
37 35
46
45
48
49
50
56 57
58 59
60 61
62 63
64 65
66 67
68 69
26
84-pin
Bottom
View
11
12
29 28
31 30
34 32
51
52
53
55
70 71
72 73
82
81
39500 18C Reference Manual.book Page 26 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39537A-page 36-27
Section 36. Appendix
Appendix
36
Figure G-3: SOIC Socket Pinouts (Bottom View)
18
16
14
12
10
2
4
1
17
15
11
13
5
9
8
3
6
7
28
27
25
21
23
24
20
26
22
19
15
17
1
2
4
8
6
5
9
3
7
18
16
10
14
12
11
13
18-pin
28-pin
Bottom
View
Bottom
View
39500 18C Reference Manual.book Page 27 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39537A-page 36-28 2000 Microchip Technology Inc.
APPENDIX H: REVISION HISTORY
Revision A
This is the initial released revision of the Enhanced MCU Reference Guide Appendix.
39500 18C Reference Manual.book Page 28 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39538A-page 37-1
Glossary
37
Section 37. Glossary
A
A/D
See description under "Analog to Digital (A/D)".
Access RAM
This is a region of data memory RAM that can be accessed regardless of the currently selected
bank. This allows special function registers to be accessed by the instruction without changing
the currently selected bank. Access RAM also contains some General Purpose Registers
(GPRs). This is useful for the saving of required variables during context switching (such as during
an interrupt).
Acquisition Time (TACQ)
This is related to Analog to Digital (A/D) converters. This is the time that the PIC18CXXX A/D’s
holding capacitor acquires the analog input voltage level connected to it. When the GO bit is set,
the analog input is disconnected from the holding capacitor and the A/D conversion is started.
ALU
Arithmetical Logical Unit. Device logic that is responsible for the mathematical (add, subtract, ...),
logical (and, or, ...), and shifting operation.
Analog to Digital (A/D)
The conversion of an analog input voltage to a ratiometric digital equivalent value.
Assembly Language
A symbolic language that describes the binary machine code in a readable form.
AUSART
Addressable Universal Synchronous Asynchronous Receiver Transmitter. This module can
either operate as a full duplex asynchronous communications port, or a half duplex synchronous
communications port. When operating in the asynchronous mode, the USART can be interfaced
to a PC’s serial port.
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39538A-page 37-2 2000 Microchip Technology Inc.
B
Bank
This is a method of addressing Data Memory. Since enhanced devices have 8-bits for direct
addressing, instructions can address up to 256 bytes. To allow more data memory to be present
on a device, data memory is partitioned into contiguous banks of 256 bytes each. To select the
desired bank, the bank selection register (BSR) needs to be appropriately configured. 16 banks
can be implemented.
Baud
Generally this is how the communication speed of serial ports is described. Equivalent to bits per
second (bps).
BCD
See description under "Binary Coded Decimal (BCD)".
Binary Coded Decimal (BCD)
Each 4-bit nibble expresses a digit from 0-9. Usually two digits are contained in a byte yielding a
range of 0 - 99.
BOR
See description under "Brown-out Reset (BOR)".
Brown-out
A condition where the supply voltage of the device temporarily falls below the specified minimum
operation point. This can occur when a load is switched on and causes the system/device voltage
to drop.
Brown-out Reset (BOR)
Circuitry which will force the device to the RESET state if the device’s power supply voltage falls
below a specified voltage level. Some devices have an internal BOR circuit, while other devices
would require an external circuit to be created.
Bus width
This is the number of bits of information that a bus carries. For the Data Memory, the bus width
is 8-bits. For enhanced devices the Program Memory bus width is 16-bits.
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39538A-page 37-3
Section 37. Glossary
Glossary
37
C
Capture
A function of the CCP module in which the value of a timer/counter is “captured” into a holding
register module when a predetermined event occurs.
CCP
Capture, Compare, Pulse Width Modulation (PWM). The CCP module can be configured to operate
as an input capture, or a timer compare, or a PWM output.
Compare
A function of the CCP module in which the device will perform an action when a timer’s register
value matches the value in the compare register.
Compare Register
A 16-bit register that contains a value that is compared to the 16-bit TMR1 register. The compare
function triggers when the counter matches the contents of the compare register.
Capture Register
A 16-bit register that is loaded with the value of the 16-bit TMR1 register when a capture event
occurs.
Configuration Word
This is a non-volatile memory location that specifies the characteristics that the device will have
for operation (such as oscillator mode, WDT enable, start-up timer enables). These characteristics
can be specified at the time of device programming. For EPROM memory devices, as long
as the bit is a '1', it may at a later time be programmed as a '0'. The device must be erased for a
'0' to be returned to a '1'.
Conversion Time (Tconv)
This is related to Analog to Digital (A/D) converters. This is the time that the PIC18CXXX A/D’s
converter requires to convert the analog voltage level on the holding capacitor to a digital value.
CPU
Central Processing Unit. Decodes the instructions, and determines the operands and operations
that are needed for program execution. Arithmetic, logical, or shift operations are passed to the
ALU.
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39538A-page 37-4 2000 Microchip Technology Inc.
D
D/A
See description under "Digital to Analog".
DAC
Digital to analog converter.
Data Bus
The bus which is used to transfer data to and from the data memory.
Data EEPROM
Data Electrically Erasable Programmable Read Only Memory. This memory is capable of being
programmed and re-programmed by the CPU to ensure that in the case of a power loss, critical
values/variables are retained in the non-volatile memory.
Data Memory
The memory that is on the Data Bus. This memory is volatile (SRAM) and contains both the Special
Function Registers and General Purpose Registers.
Direct Addressing
When the Data Memory Address is contained in the Instruction. The execution of this type of
instruction will always access the data at the embedded address.
Digital to Analog
The conversion of a digital value to an equivalent ratiometric analog voltage.
E
EEPROM
Electrically Erasable Programmable Read Only Memory. This memory has the capability to be
programmed and erased in-circuit.
EPROM
Electrically Programmable Read Only Memory. This memory has the capability to be programmed
in-circuit. Erasing requires that the program memory be exposed to UV light.
EXTRC
External Resistor-Capacitor (RC). Some devices have a device oscillator option that allows the
clock to come from an external RC. This is the same as RC mode on some devices.
F
FLASH Memory
This memory has the capability to be programmed and erased in-circuit. Program Memory technology
that is almost functionally equivalent to Program EEPROM Memory.
FOSC
Frequency of the device oscillator.
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39538A-page 37-5
Section 37. Glossary
Glossary
37
G
GIO
General Input/Output.
GPIO
General Purpose Input/Output.
GPR
General Purpose Register (RAM). A portion of the data memory that can be used to store the
program’s dynamic variables.
H
Harvard Architecture
In this architecture, the Program Memory and Data Memory buses are separated. This allows
concurrent accesses to Data Memory and Program Memory, which increases the performance
of the device. All PICmicro devices implement a Harvard Architecture.
Holding Capacitor
This is a capacitor in the Analog to Digital (A/D) module which “holds” an analog input level once
a conversion is started. During acquisition, the holding capacitor is charged/discharged by the
voltage level on the analog input pin. Once the conversion is started, the holding capacitor is disconnected
from the analog input and “holds” this voltage for the A/D conversion.
HS
High Speed. One of the device oscillator modes. The oscillator circuit is tuned to support the high
frequency operation. Currently this allows for operation from 4 MHz to 25 MHz.
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39538A-page 37-6 2000 Microchip Technology Inc.
I
I
2C
Inter-Integrated Circuit. This is a two wire communication interface. This feature is one of the
modes of the "SSP" and "MSSP" modules.
Indirect Addressing
When the Data Memory Address is not contained in the Instruction, the instruction operates on
the INDF address, which causes the Data Memory Address to be the value in the FSR register.
The execution of the instruction will always access the data at the address pointed to by the FSR
register.
Instruction Bus
The bus which is used to transfer instruction words from the program memory to the CPU.
Instruction Fetch
Due to the Harvard architecture, when one instruction is to be executed, the next location in program
memory is “fetched” and ready to be decoded as soon as the currently executing instruction
is completed.
Instruction Cycle
The events for an instruction to execute. There are four events which can generally be described
as: Decode, Read, Execute, and Write. Not all events will be done by all instructions. To see the
operations during the instruction cycle, please look at the description of each instruction. Four
external clocks (Tosc) make one instruction cycle (TCY).
Interrupt
A signal to the CPU that causes the program flow to be forced to the Interrupt Vector Address
(04h in program memory). Before the program flow is changed, the contents of the Program
Counter (PC) are forced onto the hardware stack, so that program execution may return to the
interrupted point.
INTRC
Internal Resistor-Capacitor (RC). Some devices have a device oscillator option that allows the
clock to come from an internal RC combination.
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39538A-page 37-7
Section 37. Glossary
Glossary
37
L
LCD
Liquid Crystal Display. Useful for giving visual status of a system. This may require the specification
of custom LCD glass.
LED
Light Emitting Diode. Useful for giving visual status of a system.
Literal
This is a constant value that is embedded in an instruction word.
Long Word Instruction
An instruction word that embeds all the required information (opcode and data) into a single
word. This ensures that every instruction is accessed and executed in a single instruction cycle.
LP
One of the device oscillator modes. Used for low frequency operation which allows the oscillator
to be tuned for low power consumption. Operation is up to 200 kHz.
LSb
Least Significant Bit.
LSB
Least Significant Byte.
M
Machine cycle
This is a concept where the device clock is divided down to a unit time. For PICmicro devices,
this unit time is 4 times the device oscillator (4TOSC), also known as TCY.
MSb
Most Significant Bit.
MSB
Most Significant Byte.
MSSP
Master Synchronous Serial Port. The MSSP has two operational functions. The first is a "Serial
Peripheral Interface (SPI)" and the second is the Inter-Integrated Circuit ("I2
C"). The I2C function
supports both master and slave functions in hardware.
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39538A-page 37-8 2000 Microchip Technology Inc.
N
Non-Return to Zero (NRZ)
Two-level encoding used to transmit data over a communications medium. A bit value of '1' indicates
a high voltage signal. A bit value of '0' indicates a low voltage signal. The data line defaults
to a high level.
NRZ
See description under "Non-Return to Zero (NRZ)".
O
Opcode
The portion of the 16-bit instruction word that specifies the operation that needs to occur. The
opcode is of variable length depending on the instruction that needs to be executed. The opcode
varies from 4-bits to 8-bits. The remainder of the instruction word contains program or data memory
information.
Oscillator Start-up Timer (OST)
This timer counts 1024 crystal/resonator oscillator clock cycles before releasing the internal
RESET signal.
OST
See description under "Oscillator Start-up Timer (OST)".
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39538A-page 37-9
Section 37. Glossary
Glossary
37
P
Pages
Method of addressing the Program Memory. Mid-range devices have 11-bit addressing for CALL
and GOTO instructions, which gives these instructions a 2-Kword reach. To allow more program
memory to be present on a device, program memory is partitioned into contiguous pages, where
each page is 2-Kwords. To select the desired page, the page selection bits (PCLATCH<5:4>)
need to be appropriately configured. Since there are presently 2 page selection bits, 4 pages can
be implemented. The enhanced devices do not have paging. PIC16CXXX code migrates to the
PIC18CXXX without modification (with respect to paging). Optimization may be implemented.
Parallel Slave Port (PSP)
A parallel communication port which is used to interface to a microprocessor’s 8-bit data bus.
POP
A term used to refer to the action of restoring information from a stack (software and/or hardware).
See "Serial Peripheral Interface (SPI)".
Postscaler
A circuit that slows the rate of the interrupt generation (or WDT Reset) from a counter/timer by
dividing it down.
Power-on Reset (POR)
Circuitry which determines if the device power supply voltage rose from a powered down level
(0V). If the device power supply voltage is rising from ground, a device RESET occurs and the
PWRT is started.
Power-up Timer (PWRT)
A timer which holds the internal RESET signal low for a timed delay to allow the device voltage
to reach the valid operating voltage range. Once the timer times out, the OST circuitry is enabled
(for all crystal/resonator device oscillator modes).
Prescaler
A circuit that slows the rate of a clocking source to a counter/timer.
Program Bus
The bus used to transfer instruction words from the program memory to the CPU.
Program Counter
A register which specifies the address in program memory that contains the next instruction to
execute.
Program Memory
Any memory that is on the program memory bus. Static variables may be contained in program
memory, such as tables.
PSP
See description under "Parallel Slave Port (PSP)".
Pulse Width Modulation (PWM)
A serial signal in which the information is contained in the width of a (high) pulse of a constant
frequency signal. A PWM output, from the CCP module, of the same duty cycle requires no software
overhead.
PUSH
A term used to refer to the action of saving information onto a stack (software and/or hardware).
See "Serial Peripheral Interface (SPI)".
PWM
See description under "Pulse Width Modulation (PWM)".
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39538A-page 37-10 2000 Microchip Technology Inc.
Q
Q-cycles
This is the same as a device oscillator cycle. There are 4 Q-cycles for each instruction cycle.
R
RC
Resistor-Capacitor. The default configuration for the device oscillator. This allows a
“Real-Cheap” implementation for the device clock source. This clock source does not supply an
accurate time-base.
Read-Modify-Write
This is where a register is read, then modified, and then written back to the original register. This
may be done in one instruction cycle or multiple instruction cycles.
Register File
This is the Data Memory. Contains the SFRs and GPRs.
ROM
Read Only Memory. Memory that is fixed and cannot be modified.
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39538A-page 37-11
Section 37. Glossary
Glossary
37
S
Sampling Time
Sampling time is the complete time to get an A/D result. It includes the acquisition time and the
conversion time.
Serial Peripheral Interface (SPI)
This is one of the modes of the "SSP" and "MSSP" modules. This is typically a 3-wire interface,
with a data out line, a data in line, and a clock line. Since the clock is present, this is a synchronous
interface.
SFR
Special Function Register. These registers contain the control bits and status information for the
device.
Single Cycle Instruction
An instruction that executes in a “single” machine cycle (TCY).
SLEEP
This is a low power mode of the device, where the device’s oscillator circuitry is disabled. This
reduces the current the device consumes. Certain peripherals may be placed into modes where
they continue to operate.
Special Function Registers (SFR)
These registers contain the control bits and status information for the device.
SPI
See description under "Serial Peripheral Interface (SPI)".
SSP
Synchronous Serial Port. The SSP has two operational functions. The first is a "Serial Peripheral
Interface (SPI)"and the second is the Inter-Integrated Circuit ("I2
C"). The I2C function supports
the slave function in hardware and has additional status information to support a software
implemented master.
Stack
A portion of the CPU that retains the return address for program execution. The stack gets loaded
with the value in the Program Counter when a CALL instruction is executed or if an interrupt
occurs.
39500 18C Reference Manual.book Page 11 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39538A-page 37-12 2000 Microchip Technology Inc.
T
TAD
In the A/D Converter, the time for a single bit of the analog voltage to be converted to a digital
value.
TCY
The time for an instruction to complete. This time is equal to Fosc/4 and is divided into four
Q-cycles.
Tosc
The time for the single period of the device oscillator.
U
USART
Universal Synchronous Asynchronous Receiver Transmitter. This module can either operate as
a full duplex asynchronous communications port, or a half duplex synchronous communications
port. When operating in the asynchronous mode, the USART can be interfaced to a PC’s serial
port.
39500 18C Reference Manual.book Page 12 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39538A-page 37-13
Section 37. Glossary
Glossary
37
V
Voltage Reference (VREF)
A voltage level that can be used as a reference point for A/D conversions (AVDD and AVSS) or the
trip point for comparators.
von Neumann Architecture
In this architecture the Program Memory and Data Memory are contained in the same area and
use the same bus. This means that accesses to the program memory and data memory must
occur sequentially, which affects the performance of the device.
W
W Register
See description under "Working Register (WREG)".
Watchdog Timer (WDT)
Used to increase the robustness of a design by recovering from software flows that were not
expected in the design of the product or from other system related issues. The Watchdog Timer
causes a RESET if it is not cleared prior to overflow. The clock source for a PICmicro device is
an on-chip RC oscillator which enhances system reliability.
WDT
Watchdog Timer.
Working Register (WREG)
Can also be thought of as the accumulator of the device. Also used as an operand in conjunction
with the ALU during two operand instructions.
X
XT
One of the device oscillator modes. Used for operation from 100 kHz to 4 MHz.
39500 18C Reference Manual.book Page 13 Monday, July 10, 2000 6:12 PM
PIC18C Reference Manual
DS39538A-page 37-14 2000 Microchip Technology Inc.
37.1 Revision History
Revision A
This is the initial released revision of the Glossary.
39500 18C Reference Manual.book Page 14 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39540A-page 36-1
Source Code
Source Code
APPENDIX I: SOURCE CODE
; Software License Agreement
;
; The software supplied herewith by Microchip Technology Incorporated
; (the “Company”) for its PICmicro® Microcontroller is intended and
; supplied to you, the Company’s customer, for use solely and
; exclusively on Microchip PICmicro Microcontroller products. The
; software is owned by the Company and/or its supplier, and is
; protected under applicable copyright laws. All rights are reserved.
; Any use in violation of the foregoing restrictions may subject the
; user to criminal sanctions under applicable laws, as well as to
; civil liability for the breach of the terms and conditions of this
; license.
;
; THIS SOFTWARE IS PROVIDED IN AN “AS IS” CONDITION. NO WARRANTIES,
; WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT NOT LIMITED
; TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
; PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. THE COMPANY SHALL NOT,
; IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL OR
; CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.
;
;***********************************************************
; PIC18CXX2 EXAMPLE CODE FOR PICDEM-2
;
; TITLE: USART Demo Demonstration
; FILENAME: usart.asm
; REVISION HISTORY: A 5/13/00 jb format change
; HARDWARE: PICDEM-2 board
; FREQUENCY: 4MHz
:
;************************************************************
Software License Agreement
The software supplied herewith by Microchip Technology Incorporated (the “Company”) for its PICmicro® Microcontroller is
intended and supplied to you, the Company’s customer, for use solely and exclusively on Microchip PICmicro Microcontroller products.
The software is owned by the Company and/or its supplier, and is protected under applicable copyright laws. All rights are reserved.
Any use in violation of the foregoing restrictions may subject the user to criminal sanctions under applicable laws, as well as to civil
liability for the breach of the terms and conditions of this license.
THIS SOFTWARE IS PROVIDED IN AN “AS IS” CONDITION. NO WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATUTORY,
INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE APPLY TO THIS SOFTWARE. THE COMPANY SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR
SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.
39500 18C Reference Manual.book Page 1 Monday, July 10, 2000 6:12 PM
DS39540A-page 36-2
PIC18C Reference Manual
2000 Microchip Technology Inc.
; This program demonstrates basic functionality of the USART.
;
; Port B is connected to 8 LEDs.
; When the PIC18C452 receives a word of data from
; the USART, the value is displayed on the LEDs and
; is retransmitted to the host computer.
;
; Set terminal program to 9600 baud, 1 stop bit, no parity
list p=18c452; set processor type
list n=0; supress page breaks in list file
include
;************************************************************
; Reset and Interrupt Vectors
org 00000h; Reset Vector
gotoStart
org 00008h; Interrupt vector
gotoIntVector
;************************************************************
; Program begins here
org 00020h; Beginning of program EPROM
Start
clrfLATB; Clear PORTB output latches
clrfTRISB ; Config PORTB as all outputs
bcf TRISC,6; Make RC6 an output
movlw19h; 9600 baud @4MHz
movwfSPBRG
bsf TXSTA,TXEN; Enable transmit
bsf TXSTA,BRGH; Select high baud rate
bsf RCSTA,SPEN; Enable Serial Port
bsf RCSTA,CREN; Enable continuous reception
bcf PIR1,RCIF; Clear RCIF Interrupt Flag
bsf PIE1,RCIE; Set RCIE Interrupt Enable
bsf INTCON,PEIE; Enable peripheral interrupts
bsf INTCON,GIE; Enable global interrupts
;************************************************************
; Main loop
39500 18C Reference Manual.book Page 2 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39540A-page 36-3
Source Code
Source Code
Main
gotoMain; loop to self doing nothing
;************************************************************
; Interrupt Service Routine
IntVector
; save context (WREG and STATUS registers) if needed.
btfssPIR1,RCIF; Did USART cause interrupt?
gotoOtherInt; No, some other interrupt
movlw06h; Mask out unwanted bits
andwfRCSTA,W; Check for errors
btfssSTATUS,Z; Was either error status bit set?
gotoRcvError; Found error, flag it
movfRCREG,W; Get input data
movwfLATB; Display on LEDs
movwfTXREG; Echo character back
gotoISREnd; go to end of ISR, restore context, return
RcvError
bcf RCSTA,CREN; Clear receiver status
bsf RCSTA,CREN
movlw0FFh; Light all LEDs
movwfPORTB
gotoISREnd; go to end of ISR, restore context, return
OtherInt
goto$ ; Find cause of interrupt and service it before returning from
; interrupt. If not, the same interrupt will re-occur as soon
; as execution returns to interrupted program.
ISREnd
; Restore context if needed.
retfie
end
39500 18C Reference Manual.book Page 3 Monday, July 10, 2000 6:12 PM
DS39540A-page 36-4
PIC18C Reference Manual
2000 Microchip Technology Inc.
;
; Software License Agreement
;
; The software supplied herewith by Microchip Technology Incorporated
; (the “Company”) for its PICmicro® Microcontroller is intended and
; supplied to you, the Company’s customer, for use solely and
; exclusively on Microchip PICmicro Microcontroller products. The
; software is owned by the Company and/or its supplier, and is
; protected under applicable copyright laws. All rights are reserved.
; Any use in violation of the foregoing restrictions may subject the
; user to criminal sanctions under applicable laws, as well as to
; civil liability for the breach of the terms and conditions of this
; license.
;
; THIS SOFTWARE IS PROVIDED IN AN “AS IS” CONDITION. NO WARRANTIES,
; WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT NOT LIMITED
; TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
; PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. THE COMPANY SHALL NOT,
; IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL OR
; CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.
;
;************************************************************
; PIC18CXX2 EXAMPLE CODE FOR PICDEM-2
;
; TITLE:Button Press Demonstration
; FILENAME: bttn.asm
; REVISION HISTORY: A 5/13/00 jb format change
; HARDWARE: PICDEM-2 board
; FREQUENCY: 4MHz
:
;************************************************************
; This program demonstrates how to read a push-button and control LED's.
;
; Port B is connected to 8 LEDs.
; RA4 is connected to a switch (S2).
; This program increments a file register count every time S2 is pressed.
; The value of count is displayed on the LEDs connected to Port B.
; The LEDs should increment in a binary manner each time S2 is pressed.
list p=18c452
#include
;************************************************************
; variables
Countequ0x000
39500 18C Reference Manual.book Page 4 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39540A-page 36-5
Source Code
Source Code
;************************************************************
; reset vectors
org 00000h; Reset Vector
gotoStart
;************************************************************
;program code starts here
org 00020h; Beginning of program EPROM
Start
clrfLATB; Clear PORTB output latch
clrfTRISB; Make PORTB pins all outputs
clrfCount; Clear Count
Loop
btfscPORTA,4; Has S2 been pressed? (Normally high, goes low when pressed.)
gotoLoop; No, check again
IncCount
incfCount,F; Increment Count
movffCount,LATB; move Count to PORTB
Debounce
btfssPORTA,4; Has key been released?
gotoDebounce; No, wait some more
gotoLoop; yes, wait for next key press
END ; directive indicates end of code
39500 18C Reference Manual.book Page 5 Monday, July 10, 2000 6:12 PM
DS39540A-page 36-6
PIC18C Reference Manual
2000 Microchip Technology Inc.
;
; Software License Agreement
;
; The software supplied herewith by Microchip Technology Incorporated
; (the “Company”) for its PICmicro® Microcontroller is intended and
; supplied to you, the Company’s customer, for use solely and
; exclusively on Microchip PICmicro Microcontroller products. The
; software is owned by the Company and/or its supplier, and is
; protected under applicable copyright laws. All rights are reserved.
; Any use in violation of the foregoing restrictions may subject the
; user to criminal sanctions under applicable laws, as well as to
; civil liability for the breach of the terms and conditions of this
; license.
;
; THIS SOFTWARE IS PROVIDED IN AN “AS IS” CONDITION. NO WARRANTIES,
; WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT NOT LIMITED
; TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
; PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. THE COMPANY SHALL NOT,
; IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL OR
; CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.
;
;************************************************************
; PIC18CXX2 EXAMPLE CODE FOR PICDEM-2
;
; TITLE:I2C hardware interface PICmicro to serial EEPROM
; FILENAME: i2c.asm
; REVISION HISTORY: A 5/13/00 jb format change
; HARDWARE: PICDEM-2 board
; FREQUENCY: 4MHz
:
;************************************************************
; This program uses the advanced features of the PIC18C452, specifically
; full hardware support for master mode I2C
;
; This program loads EEPROM address 0x00 to 0xFF with 0x00 to 0xFF
; (each location contains its own address).
:
; Each location is then read out, and compared to what is expected.
; The data is displayed on the LEDS. If the data is wrong,
; the TX LED will flash briefly before proceeding to the next address.
;
; Revised Version(05-05-99).
; Note: 1) All timing is based on a reference crystal frequency of 4MHz
; which is equivalent to an instruction cycle time of 1 usec.
; 2) Address and literal values are read in hexidecimal unless
; otherwise specified.
; 3) The PIC18C452 MSSP module offers full hardware support for
39500 18C Reference Manual.book Page 6 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39540A-page 36-7
Source Code
Source Code
; master mode I2C.
;************************************************************
LIST P=18C452
#include
listn=0 ; suppress list file page breaks
listST=off; suppress list file symbol table
;************************************************************
; Register File Assignment
EEADDRequ0x000; Address register
EEDATAequ0x001; data to read/write
EESLAVE equ 0x002; Device address (1010xxxy)
DelayCtr1equ0x003; delay routine counter
DelayCtr2equ0x004; delay routine counter
SlaveAddrequ0xA0; slave address literal
;************************************************************
; Vector Assignment
ORG 0x00000
gotoStart; Reset Vector
;************************************************************
; Main Program
ORG 0x00020; Start of Program space
Start
; initialize PORTB
clrfLATB; Clear PORTB output latch
clrfTRISB; Set PORTB as all outputs
; configure SSP for hardware master mode I2C
bsf SSPSTAT,SMP; I2C slew rate control disabled
bsf SSPCON1,SSPM3; I2C master mode in hardware
bsf SSPCON1,SSPEN; enable SSP module
movlw0x09; set I2C clock rate to 100kHz
movwfSSPADD
bsf TRISC,3; I2C SCL pin is input
bsf PORTC,3; (will be controlled by SSP)
bsf TRISC,4; I2C SDA pin is input
bsf PORTC,4; (will be controlled by SSP)
movlwSlaveAddr; EEPROM I2C address
39500 18C Reference Manual.book Page 7 Monday, July 10, 2000 6:12 PM
DS39540A-page 36-8
PIC18C Reference Manual
2000 Microchip Technology Inc.
movwfEESLAVE
Main
clrfPORTB; initialize variables
clrfEEDATA
clrfEEADDR
WrEEPROM
bsf PORTB,7; indicate write, light TX LED
rcallDelay
bcf EESLAVE,0; write mode
rcallWakeSlave; gets slave attention
rcallWrADDR; sends EEPROM address
rcallWrDATA; sends data to slave
rcallStop; send stop bit
incfPORTB,F; increment count
incfEEDATA,F; increment data
incfEEADDR,F; Point to next address
btfssEEADDR,7; at end of EEPROM?
gotoWrEEPROM; no, write more data
RdLoop
clrfPORTB; initialize variables
clrfEEDATA
clrfEEADDR
RdEEPROM
rcallDelay
bcf EESLAVE,0; write mode
rcallWakeSlave; gets slave attention
rcallWrADDR; sends EEPROM address
rcallStop; send stop bit
bsf EESLAVE,0; read mode
rcallWakeSlave; gets slave attention
rcallRdDATA; receive one data byte, leaves idle
movfEEDATA,W; get data
movwfPORTB; move received data to PORTB
xorwfEEADDR,W; compare data with address
bz GoodData; branch if DATA = ADDR
rcallErrorloop; DATA is wrong, indicate error
39500 18C Reference Manual.book Page 8 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39540A-page 36-9
Source Code
Source Code
GoodDataincfEEADDR,F; Point to next address
btfssEEADDR,7; at end of EEPROM?
gotoRdEEPROM; no, read more data
gotoMain; do it all over again
;************************************************************
; TX LED flashes to indicate error while displaying received data.
Errorloop
rcallDelay
btg PORTB,7; Toggle TX LED
rcallDelay
btg PORTB,7; Toggle TX LED
rcallDelay
btg PORTB,7; Toggle TX LED
rcallDelay
btg PORTB,7; Toggle TX LED
rcallDelay
btg PORTB,7; Toggle TX LED
rcallDelay
btg PORTB,7; Toggle sTX LED
return
;************************************************************
; sends start bit, slave address
; if ACK not recieved, sends restart, tries again
; execution can get stuck in this loop if slave not present
; can be used to poll slave status (retries until slave responds)
WakeSlave
bsf SSPCON2,SEN; Send start bit
btfscSSPCON2,SEN; Has SEN cleared yet?
goto$-2 ; No, loop back to test.
rWakeSlave
bcf PIR1,SSPIF; clear interrupt flag
nop
movfEESLAVE,W
movwfSSPBUF; move slave address to SSPBUF
btfssPIR1,SSPIF; has SSP completed sending SLAVE Address?
goto$-2 ; no, loop back to test
btfssSSPCON2,ACKSTAT; was ACK received from slave?
return ; yes, return to calling routine
bsf SSPCON2,RSEN; send repeated start bit
39500 18C Reference Manual.book Page 9 Monday, July 10, 2000 6:12 PM
DS39540A-page 36-10
PIC18C Reference Manual
2000 Microchip Technology Inc.
btfscSSPCON2,RSEN; has repeated start been sent yet?
goto$-2 ; no, loop back to test
bra rWakeSlave; send slave address again
;************************************************************
; writes EEPROM memory address, hangs if no ACK
WrADDR
bcf PIR1,SSPIF; clear interrupt flag
movffEEADDR,SSPBUF; move EEPROM address to SSPBUF
btfssPIR1,SSPIF; has SSP completed sending EEPROM Address?
goto$-2 ; no, loop back to test
btfscSSPCON2,ACKSTAT; has slave sent ACK?
goto$-2 ; no, try again
return
;************************************************************
; Sends one byte of data to slave, hangs if no ACK
WrDATA
bcf PIR1,SSPIF; clear interrupt flag
movffEEDATA,SSPBUF; move data to SSPBUF
btfssPIR1,SSPIF; has SSP completed sending data to EEPROM?
goto$-2 ; no, loop back to test
btfscSSPCON2,ACKSTAT; has slave sent ACK?
goto$-2 ; no, try again
return
;************************************************************
; receive one byte from slave
; do not send ACK, send stop bit instead
RdDATA
bcf PIR1,SSPIF; clear interrupt flag
bsf SSPCON2,RCEN; enable receive mode
btfssPIR1,SSPIF; has SSP received a data byte?
goto$-2 ; no, loop back to test
bsf SSPCON2,ACKDT; no ACK
39500 18C Reference Manual.book Page 10 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39540A-page 36-11
Source Code
Source Code
bsf SSPCON2,ACKEN; send ACKDT bit
btfscSSPCON2,ACKEN; has ACKDT bit been sent yet?
goto$-2 ; no, loop back to test
bsf SSPCON2,PEN; send stop bit
btfscSSPCON2,PEN; has stop bit been sent?
goto$-2 ; no, loop back to test
movffSSPBUF,EEDATA; save data to RAM
bcf SSPCON2,RCEN; disable receive mode
return
;************************************************************
; Sends stop bit, waits until sent
Stop
bsf SSPCON2,PEN; send stop bit
btfscSSPCON2,PEN; has stop bit been sent?
goto$-2 ; no, loop back to test
return
;************************************************************
; a delay of 98.57mS
Delay
movlw0x80
movwfDelayCtr2; preset
clrfDelayCtr1; clear counter
Delay1
decfszDelayCtr1; decrement counter
bra Delay1; back to top of loop
decfszDelayCtr2; decrement counter
bra Delay1; back to top of loop
return
END
39500 18C Reference Manual.book Page 11 Monday, July 10, 2000 6:12 PM
DS39540A-page 36-12
PIC18C Reference Manual
2000 Microchip Technology Inc.
;
; Software License Agreement
;
; The software supplied herewith by Microchip Technology Incorporated
; (the “Company”) for its PICmicro® Microcontroller is intended and
; supplied to you, the Company’s customer, for use solely and
; exclusively on Microchip PICmicro Microcontroller products. The
; software is owned by the Company and/or its supplier, and is
; protected under applicable copyright laws. All rights are reserved.
; Any use in violation of the foregoing restrictions may subject the
; user to criminal sanctions under applicable laws, as well as to
; civil liability for the breach of the terms and conditions of this
; license.
;
; THIS SOFTWARE IS PROVIDED IN AN “AS IS” CONDITION. NO WARRANTIES,
; WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT NOT LIMITED
; TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
; PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. THE COMPANY SHALL NOT,
; IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL OR
; CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.
;
;************************************************************
; PIC18CXX2 EXAMPLE CODE FOR PICDEM-2
;
; TITLE: Interrupt Priority Demonstration
; FILENAME: intrp_ex .asm
; REVISION HISTORY: A 5/13/00 jb format change
; HARDWARE: PICDEM-2 board
; FREQUENCY: 4MHz
:
;************************************************************
; This program uses Timer1 and Timer3 to demonstrate the use of
; interrupt priority.
;
; Timer1 is configured for high-priority interrupts
; and Timer3 is configured for low-priority interrupts. By writing
; to the PORTB LEDS, it is shown that a high-priority interrupts
; override low-priority interrupts.
list p=18c452, n=48, t=ON, st=OFF
#include "p18c452.inc"
;------------------BIT DEFINITIONS------------------------------------
F EQU 0x0001
;------------------VECTORS--------------------------------------------
39500 18C Reference Manual.book Page 12 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39540A-page 36-13
Source Code
Source Code
org 0x000000; reset vector
bra START
org 0x000008; high priority interrupt vector
bra TMR1_ISR
org 0x000018; low priority interrupt vector
bra TMR3_ISR
;--------------------PROGRAM-----------------------------------
START
rcall INIT
;Set up priority interrupts.
bsf RCON,IPEN;enable priority interrupts.
bsf IPR1,TMR1IP;set Timer1 as a high priority interrupt source
bcf IPR2,TMR3IP;set Timer3 as a low priority interrupt source
bcf PIR1,TMR1IF;clear the Timer1 interrupt flag
bcf PIR2,TMR3IF;clear the Timer3 interrupt flag
bsf PIE1,TMR1IE;enable Timer1 interrupts
bsf PIE2,TMR3IE;enable Timer3 interrupts
bsf INTCON,GIEH;set the global interrupt enable bits
bsf INTCON,GIEL;"
;Timer1 setup
clrfT1CON
clrfTMR1H;clear Timer1 high
clrfTMR1L;clear Timer1 low
bsf T1CON,TMR1ON;turn on Timer1
;Timer3 setup
clrfT3CON
movlw0xF0
movwfTMR3H;write 0xf000 to Timer3
clrfTMR3L
bsf T3CON,TMR3ON;turn on Timer3
MLOOP
gotoMLOOP
;-------------------------------SUBROUTINES---------------------------------
TMR1_ISR ; high priority isr
bcf PIR1,TMR1IF;Clear the Timer1 interrupt flag.
bcf PORTB,0;Turn off PORTB<0> to indicate high priority
39500 18C Reference Manual.book Page 13 Monday, July 10, 2000 6:12 PM
DS39540A-page 36-14
PIC18C Reference Manual
2000 Microchip Technology Inc.
; interrupt has overridden low priority.
bsf PORTB,7;Turn on PORTB<7> to indicate high priority
; interrupt is occuring.
T1POLL
btfssPIR1,TMR1IF;Poll TMR11 interrupt flag to wait for another
; TMR1 overflow.
bra T1POLL
bcf PIR1,TMR1IF;Clear the Timer1 interrupt flag again.
bcf PORTB,7;Turn off PORTB<7> to indicate the
; high-priority ISR is over.
retfie
TMR3_ISR ;low priority isr
bcf PIR2,TMR3IF;Clear the TMR3 interrupt flag.
movlw0xF0;Load TMR3 with the value 0xF000
movwfTMR3H
clrfTMR3L
bsf PORTB,0;Turn on PORTB<0> to indicate low priority
; interrupt is occurring.
T3POLL
btfssPIR2,TMR3IF;Poll TMR3 interrupt flag to wait for another TMR3 overflow.
bra T3POLL
movlw0xF0;Load TMR3 with the value 0xF000 again.
movwfTMR3H
clrfTMR3L
bcf PIR2,TMR3IF;Clear the Timer3 interrupt flag again.
bcf PORTB,0;Turn off PORTB<0> to indicate the low-priority ISR is over.
retfie
INIT
clrfPORTB; setup portb for outputs
clrfDDRB
return
END
39500 18C Reference Manual.book Page 14 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39540A-page 36-15
Source Code
Source Code
;
; Software License Agreement
;
; The software supplied herewith by Microchip Technology Incorporated
; (the “Company”) for its PICmicro® Microcontroller is intended and
; supplied to you, the Company’s customer, for use solely and
; exclusively on Microchip PICmicro Microcontroller products. The
; software is owned by the Company and/or its supplier, and is
; protected under applicable copyright laws. All rights are reserved.
; Any use in violation of the foregoing restrictions may subject the
; user to criminal sanctions under applicable laws, as well as to
; civil liability for the breach of the terms and conditions of this
; license.
;
; THIS SOFTWARE IS PROVIDED IN AN “AS IS” CONDITION. NO WARRANTIES,
; WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT NOT LIMITED
; TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
; PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. THE COMPANY SHALL NOT,
; IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL OR
; CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.
;
;************************************************************
; PIC18CXX2 EXAMPLE CODE FOR PICDEM-2
;
; TITLE: Oscillator Switching Demonstration
; FILENAME: osc.asm
; REVISION HISTORY: A 5/13/00 jb format change
; HARDWARE: PICDEM-2 board
; FREQUENCY: 4MHz
:
;************************************************************
; This program demonstrates the use of oscillator switching.
;
; The data held in MYDAT is periodically flashed on the PORTB
; LEDs. Each time a keypress is detected on RA4, the data is
; incremented and the oscillator source is changed.
list p=18c452, n=48, t=ON, st=OFF
#include "p18c452.inc"
KEY EQU 4
;-------------------18C452 RAM LOCATIONS------------------------------
COUNT0EQU 0x0000 ; used for software timing loop
COUNT1EQU 0x0001 ; "
39500 18C Reference Manual.book Page 15 Monday, July 10, 2000 6:12 PM
DS39540A-page 36-16
PIC18C Reference Manual
2000 Microchip Technology Inc.
MYDAT EQU 0x0002 ; data storage register
;------------------BIT DEFINITIONS------------------------------------
F EQU 0x0001
;------------------VECTORS--------------------------------------------
ORG 0x000000; reset vector
BRA START
;--------------------PROGRAM-----------------------------------
START
rcall INIT; setup ports, etc.
bsf T1CON, T1OSCEN; setup the LP oscillator
MLOOP
btfss PORTA,KEY
rcall KEYPRESS; call keypress routine if
; button is pressed
movff MYDAT,PORTB; move data to portb
rcall WAIT; wait a while
clrf PORTB; clear the port
rcall WAIT; wait a while
bra MLOOP
;-------------------------------SUBROUTINES---------------------------------
KEYPRESS
btfss PORTA,KEY
bra KEYPRESS
incf MYDAT
; Oscillator source changes every time the subroutine is called.
btg OSCCON,SCS
return
INIT
clrf PORTA
clrf PORTB
39500 18C Reference Manual.book Page 16 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39540A-page 36-17
Source Code
Source Code
bsf DDRA,4
clrf DDRB
return
WAIT ; software time delay
clrf COUNT0
movlw 0x08
movwf COUNT1
WLOOP
decfsz COUNT0,F
bra WLOOP
decfsz COUNT1,F
bra WLOOP
return
end
39500 18C Reference Manual.book Page 17 Monday, July 10, 2000 6:12 PM
DS39540A-page 36-18
PIC18C Reference Manual
2000 Microchip Technology Inc.
;
; Software License Agreement
;
; The software supplied herewith by Microchip Technology Incorporated
; (the “Company”) for its PICmicro® Microcontroller is intended and
; supplied to you, the Company’s customer, for use solely and
; exclusively on Microchip PICmicro Microcontroller products. The
; software is owned by the Company and/or its supplier, and is
; protected under applicable copyright laws. All rights are reserved.
; Any use in violation of the foregoing restrictions may subject the
; user to criminal sanctions under applicable laws, as well as to
; civil liability for the breach of the terms and conditions of this
; license.
;
; THIS SOFTWARE IS PROVIDED IN AN “AS IS” CONDITION. NO WARRANTIES,
; WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT NOT LIMITED
; TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
; PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. THE COMPANY SHALL NOT,
; IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL OR
; CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.
;
;************************************************************
; PIC18CXX2 EXAMPLE CODE FOR PICDEM-2
;
; TITLE: Pulse Width Modulation Demonstration
; FILENAME: pwm_ex .asm
; REVISION HISTORY: A 5/13/00 jb format change
; HARDWARE: PICDEM-2 board
; FREQUENCY: 4MHz
:
;************************************************************
; This program demonstrates pulse width modulation using CCP2.
;
; The PWM period is fixed and then the duty cycle is varied by
; looking up a new value in a table. When the final value of
; the table is read, the table is read in reverse. The PWM output
; is set to RC1. Parts Y3, C6 & C7 are are not installed the
; on the PICDEM 2 board. PWM signal can be observed on RC1 pin.
;
list p=18c452, n=48, t=ON, st=OFF
#include "p18c452.inc"
;************************************************************
; bit definitions
F EQU 0x0001
39500 18C Reference Manual.book Page 18 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39540A-page 36-19
Source Code
Source Code
;************************************************************
; 18C452 RAM LOCATIONS
DIRFLAG EQU 0x0000
;************************************************************
; 18C452 ROM LOCATIONS
TABLADDR EQU 0x0003000
;************************************************************
; vectors
org 0x000000; reset vector
bra START
org 0x000008; high priority interrupt vector
bra TMR1_ISR
;************************************************************
; program
START
; Set up PWM module
; Set PWM period by writing to PR2
; Set PWM duty cycle by writing to the CCPR2L register
; and the CCP2CON<5:4>>bits
; Make the CCP2 pin an output by clearing the TRISC<2> bit.
clrfCCP2CON;CCP module is off
bsf CCP2CON, CCP2M3;select PWM mode
bsf CCP2CON, CCP2M2;select PWM mode
movlw0x3F;Set PWM frequency to 78.12kHz
movwfPR2;
bcf TRISC, 1;make channel 1 an output
movlw0x00
movwfCCPR2L
;Set the TMR2 prescale value and enable Timer2 by writing to T2CON
;Configure the CCP2 module for PWM operation
clrfT2CON;clear T2CON
clrfTMR2;clear Timer2
bsf T2CON,TMR2ON;turn on Timer2
;initialize direction flag for table
clrfDIRFLAG
; Initialize the table pointer registers
39500 18C Reference Manual.book Page 19 Monday, July 10, 2000 6:12 PM
DS39540A-page 36-20
PIC18C Reference Manual
2000 Microchip Technology Inc.
; to the first location of the data stored in program memory.
movlwUPPER(TABLADDR)
movwfTBLPTRU
movlwHIGH(TABLADDR)
movwfTBLPTRH
movlwLOW(TABLADDR)
movwfTBLPTRL
;setup interrupt
bsf RCON,IPEN;enable priority interrupts.
bsf IPR1,TMR1IP;set Timer1 as a high priority interrupt source
bcf PIR1,TMR1IF;clear the Timer1 interrupt flag
bsf PIE1,TMR1IE;enable Timer1 interrupts
bsf INTCON,GIEH;set the global interrupt enable bits
bsf INTCON,GIEL;"
;Timer1 setup
clrfT1CON
clrfTMR1H;clear Timer1 high
clrfTMR1L;clear Timer1 low
bsf T1CON,TMR1ON;turn on Timer1
MLOOP
gotoMLOOP
;************************************************************
; subroutines
TMR1_ISR ; high priority isr
bcf PIR1,TMR1IF;Clear the Timer1 interrupt flag.
rcall CHECK_ADDR
btfsc DIRFLAG,0
bra RD_DOWN
RD_UP
; Code here does a table read, post-increments, and writes the
; value to the CCPR2L PWM duty-cycle register.
tblrd*+
movffTABLAT,CCPR2L
39500 18C Reference Manual.book Page 20 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39540A-page 36-21
Source Code
Source Code
bra T1POLL
RD_DOWN
; Code here does a table read, post-decrements, and writes the
; value to the CCPR2L PWM duty-cycle register.
tblrd*-
movffTABLAT,CCPR2L
bra T1POLL
T1POLL
btfssPIR1,TMR1IF;Poll TMR11 interrupt flag to wait for another
; TMR1 overflow.
bra T1POLL
bcf PIR1,TMR1IF;Clear the Timer1 interrupt flag again.
retfie
CHECK_ADDR
movlw LOW(TABEND) - 1
subwf TBLPTRL,W
bnz CHECK_LOW
setf DIRFLAG
return
CHECK_LOW
movlw LOW(TABLADDR)
subwf TBLPTRL,W
bnz DONE_CHECK
clrf DIRFLAG
DONE_CHECK
return
;-------------------------------DATA---------------------------------------
org TABLADDR
DB 0x00,0x06,0x0C,0x12,0x18,0x1E,0x23,0x28
DB 0x2D,0x31,0x35,0x38,0x3A,0x3D,0x3E,0x3F
TABEND
END
39500 18C Reference Manual.book Page 21 Monday, July 10, 2000 6:12 PM
DS39540A-page 36-22
PIC18C Reference Manual
2000 Microchip Technology Inc.
;
; Software License Agreement
;
; The software supplied herewith by Microchip Technology Incorporated
; (the “Company”) for its PICmicro® Microcontroller is intended and
; supplied to you, the Company’s customer, for use solely and
; exclusively on Microchip PICmicro Microcontroller products. The
; software is owned by the Company and/or its supplier, and is
; protected under applicable copyright laws. All rights are reserved.
; Any use in violation of the foregoing restrictions may subject the
; user to criminal sanctions under applicable laws, as well as to
; civil liability for the breach of the terms and conditions of this
; license.
;
; THIS SOFTWARE IS PROVIDED IN AN “AS IS” CONDITION. NO WARRANTIES,
; WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT NOT LIMITED
; TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
; PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. THE COMPANY SHALL NOT,
; IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL OR
; CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.
;
;************************************************************
; PIC18CXX2 EXAMPLE CODE FOR PICDEM-2
;
; TITLE: Table Read Demonstration
; FILENAME: table.asm
; REVISION HISTORY: A 5/13/00 jb format change
; HARDWARE: PICDEM-2 board
; FREQUENCY: 4MHz
:
;************************************************************
; This program demonstrates the use of the TBLRD instruction
; to read program memory.
;
; A pre-defined sequence of data
; bytes is included in program memory. Each time the button
; on pin RA4 is pressed, the next byte of data is accessed
; and displayed on the PORTB LEDS. When the beginning or end of
; the data is reached, the direction of access is reversed.
list p=18c452, n=48, t=ON, st=OFF
#include "p18c452.inc"
;-------------------18C452 RAM LOCATIONS------------------------------
DIRFLAG EQU 0x0000
39500 18C Reference Manual.book Page 22 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39540A-page 36-23
Source Code
Source Code
;-------------------18C452 ROM LOCATIONS------------------------------
TABLADDR EQU 0x0003000
;------------------BIT DEFINITIONS------------------------------------
KEY EQU 4
;------------------VECTORS--------------------------------------------
ORG 0x000000; rest vector
GOTOSTART
ORG 0x000008; high priority interrupt vector
GOTOSTART
ORG 0x000018; low priority interrupt vector
GOTOSTART
;--------------------PROGRAM-----------------------------------
START
bsfDDRA,4; porta button input
clrf PORTB; setup portb for outputs
clrf DDRB
clrf DIRFLAG
; Code should be written here to intialize the table pointer registers
; to the first location of the data stored in program memory. Use
; the appropriate assembler directives to accomplish this.
; (Refer to the 'DATA' statements in this source code.)
movlwUPPER(TABLADDR)
movwfTBLPTRU
movlwHIGH(TABLADDR)
movwfTBLPTRH
movlwLOW(TABLADDR)
movwfTBLPTRL
MLOOP
btfsc PORTA,KEY; keypress routine
bra $ - 2; decrenment PC by 2 because
39500 18C Reference Manual.book Page 23 Monday, July 10, 2000 6:12 PM
DS39540A-page 36-24
PIC18C Reference Manual
2000 Microchip Technology Inc.
btfss PORTA,KEY; of byte addressing!
bra $ - 2
rcall CHECK_ADDR
btfsc DIRFLAG,0
bra RD_DOWN
RD_UP
; Code here does a table read, post-increments, and writes the
; value to the PORTB LEDS
tblrd*+
movff TABLAT,PORTB
bra MLOOP
RD_DOWN
; Code here does a table read, post-decrements, and writes the
; value to the PORTB LEDS
tblrd*-
movff TABLAT,PORTB
bra MLOOP
;-----------------------------SUBROUTINES--------------------------
CHECK_ADDR
movlw LOW(TABEND) - 1
subwf TBLPTRL,W
bnz CHECK_LOW
setf DIRFLAG
return
CHECK_LOW
movlw LOW(TABLADDR)
subwf TBLPTRL,W
bnz DONE_CHECK
clrf DIRFLAG
DONE_CHECK
return
;-------------------------------DATA---------------------------------------
39500 18C Reference Manual.book Page 24 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39540A-page 36-25
Source Code
Source Code
org TABLADDR
DATA 0x0201,0x0804,0x2010,0x8040 ; 0x003000 - 0x003007
DATA 0x4281,0x1824,0x2400,0x8142 ; 0x003008 - 0x00300F
DATA 0x1211,0x1814,0x2818,0x8848 ; 0x003010 - 0x003017
DATA 0xaa55,0xaa55,0x0100,0x0703 ; 0x003018 - 0x00301F
DATA 0x1F0F,0x7F3F,0xFFFF,0xFFFF ; 0x003020 - 0x003027
TABEND
END
39500 18C Reference Manual.book Page 25 Monday, July 10, 2000 6:12 PM
DS39540A-page 36-26
PIC18C Reference Manual
2000 Microchip Technology Inc.
;
; Software License Agreement
;
; The software supplied herewith by Microchip Technology Incorporated
; (the “Company”) for its PICmicro® Microcontroller is intended and
; supplied to you, the Company’s customer, for use solely and
; exclusively on Microchip PICmicro Microcontroller products. The
; software is owned by the Company and/or its supplier, and is
; protected under applicable copyright laws. All rights are reserved.
; Any use in violation of the foregoing restrictions may subject the
; user to criminal sanctions under applicable laws, as well as to
; civil liability for the breach of the terms and conditions of this
; license.
;
; THIS SOFTWARE IS PROVIDED IN AN “AS IS” CONDITION. NO WARRANTIES,
; WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT NOT LIMITED
; TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
; PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. THE COMPANY SHALL NOT,
; IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL OR
; CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.
;
;************************************************************
; PIC18CXX2 EXAMPLE CODE FOR PICDEM-2
;
; TITLE: Timer Read/Write Demonstration
; FILENAME: tmrrw.asm
; REVISION HISTORY: A 5/13/00 jb format change
; HARDWARE: PICDEM-2 board
; FREQUENCY: 4MHz
:
;************************************************************
; This program uses Timer1 and Timer3 to demonstrate the use of
; 8 and 16 bit write modes.
;
; The counters are used to maintain
; overflow count registers (similar to a RTCC). The 16 bit write to
; Timer3 will introduce an error between the overflow registers.
; This error is calculated in the main program loop and displayed on
; the PORTB LEDS.
list p=18c452, n=48, t=ON, st=OFF
#include "p18c452.inc"
;-------------------18C452 RAM LOCATIONS------------------------------
T1COUNT EQU 0x0000
T3COUNT EQU 0x0001
39500 18C Reference Manual.book Page 26 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39540A-page 36-27
Source Code
Source Code
;------------------BIT DEFINITIONS------------------------------------
F EQU 0x0001
;------------------VECTORS--------------------------------------------
org 0x000000; reset vector
bra START
org 0x000008; high priority interrupt vector
bra TMR_ISR
org 0x000018; low priority interrupt vector
bra START
;--------------------PROGRAM-----------------------------------
START
rcallINIT
; Setup Timer1
clrf T1CON
bsf T1CON,T1CKPS1; set prescaler 1:8
bsf T1CON,T1CKPS0; set prescaler 1:8
bsf T1CON,RD16; enable 16 bit read/write mode
movlw 0x80; initialize TMR1 with 8000
movwf TMR1H;
clrf TMR1L;
bsf T1CON,TMR1ON; turn on TMR1
; Setup Timer3
clrf T3CON
bsf T3CON,TMR3CS
bsf T3CON,RD16
bsf T3CON,T3CKPS1; set prescaler 1:8
bsf T3CON,T3CKPS0; set prescaler 1:8
bcf T3CON,RD16; enable 8 bit read/write mode
movlw 0x80; initialize TMR3 with 8000
movwf TMR3H
clrf TMR3L
bsf T3CON,TMR3ON
39500 18C Reference Manual.book Page 27 Monday, July 10, 2000 6:12 PM
DS39540A-page 36-28
PIC18C Reference Manual
2000 Microchip Technology Inc.
MLOOP
; Subtract T3COUNT from T1COUNT
; and write the result to PORTB LEDS.
movf T3COUNT,W
subwf T1COUNT,W
movwf PORTB
bra MLOOP
;-------------------------------SUBROUTINES---------------------------------
TMR_ISR
btfsc PIR1,TMR1IF; check which timer caused the interrupt
bra T1_HANDLER
btfsc PIR2,TMR3IF
bra T3_HANDLER
retfie
T1_HANDLER
; Load Timer1 with 0x8000 by writing to the high byte only.
; Increment the T1COUNT register.
; Clear the Timer1 interrupt flag.
movlw 0x80
movwf TMR1H
incf T1COUNT
bcf PIR1,TMR1IF
retfie
T3_HANDLER
; Load Timer3 with 0x8000 by performing a 16-bit timer write.
; Increment the T3COUNT register.
; Clear the Timer3 interrupt flag.
movlw 0x80
movwf TMR3H
clrf TMR3L
incf T3COUNT
39500 18C Reference Manual.book Page 28 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39540A-page 36-29
Source Code
Source Code
bcf PIR2,TMR3IF
retfie
;-----------------------------SUBROUTINES----------------------------------
INIT
clrf T1COUNT
clrf T3COUNT
bsf DDRA,4; porta
clrf PORTB; setup portb for outputs
clrf DDRB
bsf PIE1,TMR1IE; enable interrupts
bsf PIE2,TMR3IE
bsf INTCON,PEIE; enable peripheral interrupts
bsf INTCON,GIE; enable global interrupts
return
END
39500 18C Reference Manual.book Page 29 Monday, July 10, 2000 6:12 PM
DS39540A-page 36-30
PIC18C Reference Manual
2000 Microchip Technology Inc.
;
; Software License Agreement
;
; The software supplied herewith by Microchip Technology Incorporated
; (the “Company”) for its PICmicro® Microcontroller is intended and
; supplied to you, the Company’s customer, for use solely and
; exclusively on Microchip PICmicro Microcontroller products. The
; software is owned by the Company and/or its supplier, and is
; protected under applicable copyright laws. All rights are reserved.
; Any use in violation of the foregoing restrictions may subject the
; user to criminal sanctions under applicable laws, as well as to
; civil liability for the breach of the terms and conditions of this
; license.
;
; THIS SOFTWARE IS PROVIDED IN AN “AS IS” CONDITION. NO WARRANTIES,
; WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT NOT LIMITED
; TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
; PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. THE COMPANY SHALL NOT,
; IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL OR
; CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.
;
;************************************************************
; PIC18CXX2 EXAMPLE CODE FOR PICDEM-2
;
; TITLE: A/D Converter Demonstration
; FILENAME: a2d.asm
; REVISION HISTORY: A 5/13/00 jb format change
; HARDWARE: PICDEM-2 board
; FREQUENCY: 4MHz
:
;************************************************************
; This program is a simple implementation of the
; PIC18C452's A/D.
;
; One Channel is selected (AN0).
; The hardware for this program is the PICDEM-2 board. The program
; converts the potentiometer value on RA0 and displays it as
; an 8 bit binary value on Port B.
;
; The A/D is configured as follows:
; Vref = +5V internal
; A/D Osc. = internal RC
; A/D Channel = AN0 (RA0)
LIST P=18C452
#include ; File contains addresses for register and bit names
39500 18C Reference Manual.book Page 30 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39540A-page 36-31
Source Code
Source Code
;************************************************************
; reset and interrupt vectors
org 0x00000; Reset Vector Address
gotoStart
org 0x00008; Interrupt Vector Address
gotoISR ; goto Interrupt Service Routine
;************************************************************
; program code starts here
org 0x00020
Start
clrfPORTB; clear all bits of PORTB
clrfTRISB; Set PORTB as outputs
callInitializeAD ; configure A/D module
callSetupDelay; delay for 15 instruction cycles
bsf ADCON0,GO; Start first A/D conversion
MaingotoMain; do nothing loop
;************************************************************
; Service A/D interrupt
; Get value and display on LEDs
ISR
; Save context (WREG and STATUS) if required.
btfssPIR1,ADIF; Did A/D cause interrupt?
gotoOtherInt; No, check other sources
movfADRESH,W; Get A/D value
movwfLATB; Display on LEDs
bcf PIR1,ADIF; Reset A/D int flag
callSetupDelay; Delay for 15 cycles
bsf ADCON0,GO; Start A/D conversion
gotoEndISR; return from ISR
OtherInt
; This would be replaced by code to check and service other interrupt sources
39500 18C Reference Manual.book Page 31 Monday, July 10, 2000 6:12 PM
DS39540A-page 36-32
PIC18C Reference Manual
2000 Microchip Technology Inc.
goto$ ; trap here, loops to self
EndISR
; Restore context if saved.
retfie; Return, enables GIE
;************************************************************
; InitializeAD - initializes and sets up the A/D hardware.
; Select AN0 to AN3 as analog inputs, RC clock, and read AN0.
InitializeAD
movlwB'00000100'; Make RA0,RA1,RA4 analog inputs
movwfADCON1
movlwB'11000001'; Select RC osc, AN0 selected,
movwfADCON0; A/D enabled
bcf PIR1,ADIF; Clear A/D interrupt flag
bsf PIE1,ADIE; Enable A/D interrupt
bsf INTCON,PEIE; Enable peripheral interrupts
bsf INTCON,GIE; Enable Global interrupts
return
;************************************************************
; This is used to allow the A/D time to sample the input
; (acquisition time).
;
; This routine requires 11 cycles to complete.
; The call and return add another 4 cycles.
;
; 15 cycles with Fosc=4MHz means this delay consumes 15us.
SetupDelay
movlw.3 ; Load Temp with decimal 3
movwfTEMP
SD
decfszTEMP, F; Delay loop
gotoSD
return
END
39500 18C Reference Manual.book Page 32 Monday, July 10, 2000 6:12 PM
2000 Microchip Technology Inc. DS39539A-page 1
PIC18C Reference Manual
Index
Index
A
A/D
Accuracy/Error ............................................25-17, 26-17
ADCON0 Register...........................................25-2, 26-2
ADCON1 Register.................................................... 25-6
ADIF bit...........................................................25-7, 26-7
Analog Input Model Block Diagram.................25-9, 26-9
Configuring Analog Port Pins......................25-11, 26-11
Configuring the Interrupt .................................25-7, 26-7
Configuring the Module...................................25-7, 26-7
Connection Considerations.........................25-18, 26-18
Conversion Clock........................................25-10, 26-10
Conversions................................................25-12, 26-12
Converter Characteristics ......................................32-36
converter characteristics........................................32-14
Delays.............................................................25-9, 26-9
Effects of a Reset...............................25-16, 26-16, 27-6
Equations........................................................25-8, 26-8
Flowchart of A/D Operation.........................25-13, 26-13
GO/DONE bit ..................................................25-7, 26-7
Internal Sampling Switch (Rss) Impedence ....25-8, 26-8
Operation During Sleep .....................25-16, 26-16, 27-6
Sampling Requirements..................................25-8, 26-8
Sampling Time ................................................25-8, 26-8
Source Impedence..........................................25-8, 26-8
Time Delays....................................................25-9, 26-9
Transfer Function........................................25-18, 26-18
ACK................................................................................20-19
Acknowledge Pulse........................................................20-19
ADDLW Instruction ........................................................31-14
ADDWF Instruction .............................................31-16, 31-20
ADRES Register .....................................................25-2, 26-2
AKS ................................................................................20-37
ANDLW Instruction ........................................................31-22
ANDWF Instruction ..................... 31-24, 31-26, 31-30, 31-32,
...............................31-34, 31-36, 31-38, 31-40, 31-42, 31-48
Assembler ........................................................................34-6
B
Baud Rate Generator .....................................................20-30
BCF Instruction ..............................................................31-28
BF ................................................ 19-20, 20-19, 20-37, 20-40
Block Diagrams
Analog Input Model .........................................25-9, 26-9
Baud Rate Generator.............................................20-30
External Brown-out Protection Circuit (Case1) ........3-13
I
2C Master Mode....................................................20-27
I
2C Module .............................................................20-17
SSP (I2C Mode) .....................................................20-17
SSP (SPI Mode).......................................................20-9
SSP Module (I2C Master Mode) ..............................20-3
SSP Module (I2C Slave Mode) ................................ 20-3
SSP Module (SPI Mode).......................................... 20-2
Timer1......................................................................16-2
BODEN ............................................................................3-10
BRG ...............................................................................20-30
BRGH bit.......................................................................... 21-5
Brown-out Protection .......................................................3-13
BSF Instruction ...................................................31-44, 31-47
BTFSC Instruction..........................................................31-45
BTFSS Instruction ........................ 31-46, 31-56, 31-58, 31-60
Buffer Full bit, BF ...........................................................20-19
Bus Arbitration ...............................................................20-48
Bus Collision ..................................................................20-48
Bus Collision During a RESTART Condition..................20-51
Bus Collision During a Start Condition........................... 20-49
Bus Collision During a Stop Condition........................... 20-52
C
C ........................................................................................ 8-3
C Compiler (MP-C) .......................................................... 34-6
CALL Instruction ............................................................ 31-50
Clock/Instruction Cycle (Figure)......................................... 4-5
Clocking Scheme/Instruction Cycle ................................... 4-5
CLRF Instruction............................................... 31-52, 31-114
CLRWDT Instruction...................................................... 31-53
Code Examples
Loading the SSPBUF register ...................... 19-9, 20-10
Code Protection ............................................................. 29-10
COMF Instruction........................................................... 31-54
D
DC ..................................................................................... 8-3
DC Characteristics
PIC16C73 ................................................................ 32-6
PIC16C74 ................................................................ 32-6
DECF Instruction ................................................ 31-62, 31-64
DECFSZ Instruction............................................31-66, 31-68
Development Support...................................................... 34-2
F
Filter/Mask Truth Table.................................................. 22-54
Flowcharts
Acknowledge ......................................................... 20-44
Master Receiver .................................................... 20-41
Master Transmit..................................................... 20-38
Restart Condition................................................... 20-35
Start Condition....................................................... 20-32
Stop Condition ....................................................... 20-46
FS0 .................................................................................... 8-3
FS1 .................................................................................... 8-3
FS2 .................................................................................... 8-3
FS3 .................................................................................... 8-3
G
General Call Address Sequence ................................... 20-25
General Call Address Support....................................... 20-25
GOTO Instruction........................................................... 31-70
I
I
2C ................................................................................. 20-17
BF.......................................................................... 19-20
CKP ....................................................................... 19-24
I
2C Overview ........................................................... 36-1
Initiating and Terminating Data Transfer ................. 36-2
START..................................................................... 36-2
STOP....................................................................... 36-2
I
2C Master Mode Receiver Flowchart............................ 20-41
I
2C Master Mode Reception .......................................... 20-40
I
2C Master Mode Restart Condition............................... 20-33
I
2C Mode Selection........................................................ 20-18
I
2C Module
10-bit Address mode ............................................. 20-20
Acknowledge Flowchart......................................... 20-44
Acknowledge Sequence timing ............................. 20-43
Addressing............................................................. 20-20
Baud Rate Generator ............................................ 20-30
Block Diagram ....................................................... 20-27
BRG Block Diagram .............................................. 20-30
BRG Reset due to SDA Collision .......................... 20-50
BRG Timing........................................................... 20-30
Bus Arbitration ....................................................... 20-48
Bus Collision.......................................................... 20-48
Acknowledge ................................................. 20-48
Restart Condition........................................... 20-51
Restart Condition Timing (Case1) ................. 20-51
39500 18C Reference ManualIX.fm Page 1 Tuesday, July 11, 2000 8:33 AM
PIC18C Reference Manual
DS39539A-page 2 2000 Microchip Technology Inc.
Restart Condition Timing (Case2)..................20-51
Start Condition ...............................................20-49
Start Condition Timing ........................20-49, 20-50
Stop Condition ...............................................20-52
Stop Condition Timing (Case1)......................20-52
Stop Condition Timing (Case2)......................20-52
Transmit Timing .............................................20-48
Bus Collision timing................................................20-48
Clock Arbitration.....................................................20-47
Clock Arbitration Timing (Master Transmit)............20-47
Conditions to not give ACK Pulse ..........................20-19
General Call Address Support ...............................20-25
Master Mode ..........................................................20-27
Master Mode 7-bit Reception timing ......................20-42
Master Mode Operation .........................................20-29
Master Mode Start Condition .................................20-31
Master Mode Transmission....................................20-37
Master Mode Transmit Sequence ..........................20-29
Master Transmit Flowchart ....................................20-38
Multi-Master Communication .................................20-48
Multi-master Mode .................................................20-28
Operation ...............................................................20-17
Repeat Start Condition timing ................................20-34
Restart Condition Flowchart...................................20-35
Slave Mode ............................................................20-19
Slave Reception .....................................................20-21
Slave Transmission................................................20-22
SSPBUF.................................................................20-18
Start Condition Flowchart.......................................20-32
Stop Condition Flowchart.......................................20-46
Stop Condition Receive or Transmit timing............20-45
Stop Condition timing .............................................20-45
Waveforms for 7-bit Reception ..............................20-22
Waveforms for 7-bit Transmission .........................20-22
I
2C Module Address Register, SSPADD........................20-18
I
2C Slave Mode ..............................................................20-19
INCF Instruction .............................................................31-72
INCFSZ Instruction..............................................31-74, 31-76
Instruction Flow/Pipelining .................................................4-6
Instruction Set
ADDLW ..................................................................31-14
ADDWF.......................................................31-16, 31-20
ANDLW ..................................................................31-22
ANDWF....................31-24, 31-26, 31-30, 31-32, 31-34,
.................................. 31-36, 31-38, 31-40, 31-42, 31-48
BCF ........................................................................31-28
BSF .............................................................31-44, 31-47
BTFSC ...................................................................31-45
BTFSS ................................. 31-46, 31-56, 31-58, 31-60
CALL ......................................................................31-50
CLRF.........................................................31-52, 31-114
CLRWDT................................................................31-53
COMF ....................................................................31-54
DECF ..........................................................31-62, 31-64
DECFSZ......................................................31-66, 31-68
GOTO ....................................................................31-70
INCF.......................................................................31-72
INCFSZ .......................................................31-74, 31-76
IORLW ...................................................................31-78
IORWF ...................................................................31-80
MOVLW .................... 31-82, 31-84, 31-86, 31-87, 31-88
MOVWF ...................31-89, 31-90, 31-91, 31-92, 31-94,
....................................................................31-95, 31-96
NOP ............................................................31-93, 31-98
RETFIE ................................................................31-100
RETLW ................................................................31-102
RETURN ..............................................................31-104
RLF .........................................................31-106, 31-108
RRF ........................................................ 31-110, 31-112
SLEEP ................................................................. 31-115
SUBLW................................................... 31-116, 31-118
SUBWF................................................... 31-120, 31-122
SWAPF......................................31-124, 31-126, 31-128
XORLW ............................................................... 31-132
XORWF ..................................................31-130, 31-134
Summary Table ................................................5-3, 31-6
Inter-Integrated Circuit (I2C) ............................................ 20-2
Internal Sampling Switch (Rss) Impedence............ 25-8, 26-8
Interrupts
Flag bits
TMR1IE ........................................................... 10-4
TMR1IF............................................................ 10-4
TMR2IE ........................................................... 10-4
TMR2IF............................................................ 10-4
TMR3IE ........................................................... 10-4
TMR3IF............................................................ 10-4
Logic ........................................................................ 10-4
Introduction...................................................................... 31-2
IORLW Instruction ......................................................... 31-78
IORWF Instruction ......................................................... 31-80
L
Loading of PC .................................................................... 7-7
M
MOVLW Instruction........... 31-82, 31-84, 31-86, 31-87, 31-88
MOVWF Instruction .....................31-89, 31-90, 31-91, 31-92,
.................................................................31-94, 31-95, 31-96
MPASM Assembler................................................. 34-2, 34-6
MP-C C Compiler............................................................. 34-6
MPSIM Software Simulator.............................................. 34-3
Multi-Master Communication......................................... 20-48
Multi-Master Mode ......................................................... 20-28
Multiply Examples
16 x 16 Routine ......................................................... 6-4
16 x 16 Signed Routine ............................................. 6-5
8 x 8 Routine ............................................................. 6-3
8 x 8 Signed Routine ................................................. 6-3
N
NOP Instruction .................................................. 31-93, 31-98
O
OSCCON........................................................................... 2-3
OSCCON Register............................................................. 2-3
Oscillator Start-up Time (Figure) ....................................... 3-5
OV...................................................................................... 8-3
P
PICDEM-1 Low-Cost PIC16/17 Demo Board .......34-2, 34-12
PICDEM-2 Low-Cost PIC16CXX Demo Board..... 34-2, 34-12
PICDEM-3 Low-Cost PIC16C9XXX Demo Board ......... 34-13
PICSTART‰ Low-Cost Development System..... 34-2, 34-10
Pin Functions
MCLR/VPP ................................................................. 4-9
OSC1/CLKIN ......................................................4-8, 4-9
OSC2/CLKOUT ..................................................4-8, 4-9
RA0/AN0.................................................................... 4-9
RA1/AN1.................................................................... 4-9
RA2/AN2.................................................................... 4-9
RA3/AN3/VREF........................................................... 4-9
RA4/T0CKI ................................................................ 4-9
RA5/AN4/SS.............................................................. 4-9
RB0/INT..................................................................... 4-9
RB1............................................................................ 4-9
RB2............................................................................ 4-9
RB3............................................................................ 4-9
RB4............................................................................ 4-9
39500 18C Reference ManualIX.fm Page 2 Tuesday, July 11, 2000 8:33 AM
2000 Microchip Technology Inc. DS39539A-page 3
PIC18C Reference Manual
Index
RB5............................................................................ 4-9
RB6............................................................................ 4-9
RB7............................................................................ 4-9
RC0/T1OSO/T1CKI ................................................. 4-10
RC1/T1OSI/CCP2.................................................... 4-10
RC2/CCP1 ...............................................................4-10
RC3/SCK/SCL .........................................................4-10
RC4/SDI/SDA ..........................................................4-10
RC5/SDO .................................................................4-10
RC6/TX/CK ..............................................................4-10
RC7/RX/DT..............................................................4-10
RD0/PSP0................................................................ 4-10
RD1/PSP1................................................................ 4-10
RD2/PSP2................................................................ 4-10
RD3/PSP3................................................................ 4-10
RD4/PSP4................................................................ 4-10
RD5/PSP5................................................................ 4-10
RD6/PSP6................................................................ 4-10
RD7/PSP7................................................................ 4-10
RE0/RD/AN5..........................................4-10, 4-11, 4-12
RE1/WR/AN6.........................................4-10, 4-11, 4-12
RE2/CS/AN7 ..........................................4-10, 4-11, 4-12
VDD .......................................................................... 4-13
VSS...........................................................................4-13
PRO MATE‰ Universal Programmer...................34-2, 34-10
Program Verification ......................................................29-10
PSPMODE bit ..................................................................12-2
PWM (CCP Module)
Example Frequencies/Resolutions ........................17-13
R
R/W bit ..................................................................20-20, 36-4
R/W bit ...........................................................................20-21
Read-Modify-Write .........................................................11-37
Registers
SSPSTAT.................................................................20-4
T1CON
.........................................................................16-3
Diagram ........................................................... 16-3
Resets................................................................................3-4
RETFIE Instruction.......................................................31-100
RETLW Instruction.......................................................31-102
RETURN Instruction ....................................................31-104
RLF Instruction................................................31-106, 31-108
RRF Instruction ...............................................31-110, 31-112
S
SCK..................................................................................20-9
SCL ................................................................................20-19
SDA................................................................................20-19
SDI ...................................................................................20-9
SDO ................................................................................. 20-9
Serial Clock, SCK ............................................................20-9
Serial Clock, SCL ...........................................................20-19
Serial Data Address, SDA..............................................20-19
Serial Data In, SDI ........................................................... 20-9
Serial Data Out, SDO.......................................................20-9
SFR ................................................................................31-12
SFR As Source/Destination ...........................................31-12
Signed Math..................................................................... 5-10
Slave Select Synchronization ........................................20-13
Slave Select, SS ..............................................................20-9
SLEEP Instruction ........................................................31-115
Special Features of the CPU ..................................29-2, 30-2
Special Function Registers ............................................31-12
SPI
Master Mode ...............................................19-12, 20-12
Serial Clock.....................................................19-8, 20-9
Serial Data In.................................................. 19-8, 20-9
Serial Data Out............................................... 19-8, 20-9
Serial Peripheral Interface (SPI).............................. 20-2
Slave Select.................................................... 19-8, 20-9
SPI clock..................................................... 19-12, 20-12
SPI Mode................................................................. 20-9
SPI Master/Slave Connection........................................ 20-11
SPI Module
Master/Slave Connection ...................................... 20-11
Slave Mode............................................................ 20-13
Slave Select Synchronization................................ 20-13
Slave Synch Timnig............................................... 20-14
Slave Timing with CKE = 0.................................... 20-14
Slave Timing with CKE = 1.................................... 20-15
SS.................................................................................... 20-9
SSP ................................................................................. 20-2
Block Diagram (SPI Mode) ...................................... 20-9
SPI Mode................................................................. 20-9
SSPADD..........................................19-21, 20-18, 20-20
SSPBUF ...............................19-12, 19-24, 20-12, 20-18
SSPCON1 ............................................................... 20-6
SSPCON2 ............................................................... 20-8
SSPSR ............................................19-12, 20-12, 20-19
SSPSTAT ..................................................... 20-4, 20-18
SSP I2C
SSP I2C Operation ................................................ 20-17
SSP Module
SPI Master Mode................................................... 20-12
SPI Master./Slave Connection............................... 20-11
SPI Slave Mode..................................................... 20-13
SSPCON1 Register............................................... 20-18
SSP Overflow Detect bit, SSPOV.................................. 20-19
SSPBUF .............................................................20-18, 20-19
SSPCON1 ............................................................ 20-6, 20-18
SSPCON2 ....................................................................... 20-8
SSPIF ............................................................................ 20-21
SSPOV ............................................................... 20-19, 20-40
SSPSTAT ............................................................. 20-4, 20-18
SUBLW Instruction ......................................... 31-116, 31-118
SUBWF Instruction ......................................... 31-120, 31-122
SWAPF Instruction ............................31-124, 31-126, 31-128
Synchronous Serial Port.................................................. 20-2
T
TAD .....................................................................25-10, 26-10
Timer Modules
Timer1
Block Diagram ................................................. 16-2
Timers
Timer1
Capacitor Selection .............................. 14-10, 16-9
Timing Diagrams
A/D Conversion ..................................................... 32-37
Acknowledge Sequence Timing ............................ 20-43
Baud Rate Generator with Clock Arbitration.......... 20-30
BRG Reset Due to SDA Collision.......................... 20-50
Bus Collision
Start Condition Timing ................................... 20-49
Bus Collision During a Restart Condition (Case 1) 20-51
Bus Collision During a Restart Condition (Case2). 20-51
Bus Collision During a Start Condition (SCL = 0).. 20-50
Bus Collision During a Stop Condition................... 20-52
Bus Collision for Transmit and Acknowledge ........ 20-48
Capture/Compare/PWM ........................................ 32-24
External Clock Timing............................................ 32-19
I
2C Bus Data...............................................32-31, 32-33
I
2C Bus Start/Stop bits........................................... 32-30
I
2C Master Mode First Start bit timing ................... 20-31
39500 18C Reference ManualIX.fm Page 3 Tuesday, July 11, 2000 8:33 AM
PIC18C Reference Manual
DS39539A-page 4 2000 Microchip Technology Inc.
I
2C Master Mode Reception timing ........................20-42
I
2C Master Mode Transmission timing...................20-39
Master Mode Transmit Clock Arbitration................20-47
Oscillator Start-up Time .............................................3-5
Parallel Slave Port .................................................32-25
Power-up Timer .....................................................32-22
Repeat Start Condition...........................................20-34
Reset......................................................................32-22
Slave Synchronization ...........................................20-14
SPI Mode Timing (Master Mode)SPI Mode
Master Mode Timing Diagram........................20-12
SPI Mode Timing (Slave Mode with CKE = 0) .......20-14
SPI Mode Timing (Slave Mode with CKE = 1) .......20-15
Start-up Timer ........................................................32-22
Stop Condition Receive or Transmit ......................20-45
USART RX Pin Sampling.......................................21-17
USART Synchronous Receive ...............................32-34
USART Synchronous Transmission ......................32-34
USART, Asynchronous Reception .........................21-16
Watchdog Timer.....................................................32-22
TRISC ............................................................................19-26
TRISC Register ..............................................................19-17
TRISD Register ...................................................11-27, 11-29
U
Universal Synchronous Asynchronous Receiver Transmitter
(USART)
Asynchronous Receiver
Setting Up Reception.....................................21-15
Timing Diagram..............................................21-16
USART
Asynchronous Transmitter .......................................21-9
Baud Rate Generator (BRG)
Sampling..........................................................21-5
W
Watchdog Timer (WDT) .................................................29-10
Waveform for General Call Address Sequence .............20-25
WCOL ............................... 20-31, 20-37, 20-40, 20-43, 20-45
WCOL Status Flag .........................................................20-31
X
XORLW Instruction ......................................................31-132
XORWF Instruction .........................................31-130, 31-134
Z
Z.........................................................................................8-3
39500 18C Reference ManualIX.fm Page 4 Tuesday, July 11, 2000 8:33 AM
2000 Microchip Technology Inc. DS39539A-page 5
PIC18C Reference Manual
Index
NOTES:
39500 18C Reference ManualIX.fm Page 5 Tuesday, July 11, 2000 8:33 AM
PIC18C Reference Manual
DS39539A-page 6 2000 Microchip Technology Inc.
NOTES:
39500 18C Reference ManualIX.fm Page 6 Tuesday, July 11, 2000 8:33 AM
2000 Microchip Technology Inc. DS39539A-page 7
PIC18C Reference Manual
Index
NOTES:
39500 18C Reference ManualIX.fm Page 7 Tuesday, July 11, 2000 8:33 AM
PIC18C Reference Manual
DS39539A-page 8 2000 Microchip Technology Inc.
NOTES:
39500 18C Reference ManualIX.fm Page 8 Tuesday, July 11, 2000 8:33 AM
2000 Microchip Technology Inc. DS39539A-page 9
PIC18C Reference Manual
Index
NOTES:
39500 18C Reference ManualIX.fm Page 9 Tuesday, July 11, 2000 8:33 AM
PIC18C Reference Manual
DS39539A-page 10 2000 Microchip Technology Inc.
NOTES:
39500 18C Reference ManualIX.fm Page 10 Tuesday, July 11, 2000 8:33 AM
2000 Microchip Technology Inc. DS39539A-page 11
PIC18C Reference Manual
Index
NOTES:
39500 18C Reference ManualIX.fm Page 11 Tuesday, July 11, 2000 8:33 AM
PIC18C Reference Manual
DS39539A-page 12 2000 Microchip Technology Inc.
NOTES:
39500 18C Reference ManualIX.fm Page 12 Tuesday, July 11, 2000 8:33 AM
2000 Microchip Technology Inc. DS39539A-page 13
PIC18C Reference Manual
Index
NOTES:
39500 18C Reference ManualIX.fm Page 13 Tuesday, July 11, 2000 8:33 AM
PIC18C Reference Manual
DS39539A-page 14 2000 Microchip Technology Inc.
NOTES:
39500 18C Reference ManualIX.fm Page 14 Tuesday, July 11, 2000 8:33 AM
2000 Microchip Technology Inc. DS39539A-page 15
PIC18C Reference Manual
Index
NOTES:
39500 18C Reference ManualIX.fm Page 15 Tuesday, July 11, 2000 8:33 AM
Information contained in this publication regarding device applications and the like is intended through suggestion only and may be superseded by updates.
It is your responsibility to ensure that your application meets with your specifications. No representation or warranty is given and no liability is assumed by
Microchip Technology Incorporated with respect to the accuracy or use of such information, or infringement of patents or other intellectual property rights
arising from such use or otherwise. Use of Microchip’s products as critical components in life support systems is not authorized except with express written
approval by Microchip. No licenses are conveyed, implicitly or otherwise, except as maybe explicitly expressed herein, under any intellectual property
rights. The Microchip logo and name are registered trademarks of Microchip Technology Inc. in the U.S.A. and other countries. All rights reserved. All other
trademarks mentioned herein are the property of their respective companies.
DS39500A 2000 Microchip Technology Inc.
All rights reserved. © 2000 Microchip Technology Incorporated. Printed in the USA. 7/00 Printed on recycled paper.
AMERICAS
Corporate Office
Microchip Technology Inc.
2355 West Chandler Blvd.
Chandler, AZ 85224-6199
Tel: 480-786-7200 Fax: 480-786-7277
Technical Support: 480-786-7627
Web Address: http://www.microchip.com
Atlanta
Microchip Technology Inc.
500 Sugar Mill Road, Suite 200B
Atlanta, GA 30350
Tel: 770-640-0034 Fax: 770-640-0307
Boston
Microchip Technology Inc.
2 LAN Drive, Suite 120
Westford, MA 01886
Tel: 508-480-9990 Fax: 508-480-8575
Chicago
Microchip Technology Inc.
333 Pierce Road, Suite 180
Itasca, IL 60143
Tel: 630-285-0071 Fax: 630-285-0075
Dallas
Microchip Technology Inc.
4570 Westgrove Drive, Suite 160
Addison, TX 75001
Tel: 972-818-7423 Fax: 972-818-2924
Dayton
Microchip Technology Inc.
Two Prestige Place, Suite 150
Miamisburg, OH 45342
Tel: 937-291-1654 Fax: 937-291-9175
Detroit
Microchip Technology Inc.
Tri-Atria Office Building
32255 Northwestern Highway, Suite 190
Farmington Hills, MI 48334
Tel: 248-538-2250 Fax: 248-538-2260
Los Angeles
Microchip Technology Inc.
18201 Von Karman, Suite 1090
Irvine, CA 92612
Tel: 949-263-1888 Fax: 949-263-1338
New York
Microchip Technology Inc.
150 Motor Parkway, Suite 202
Hauppauge, NY 11788
Tel: 631-273-5305 Fax: 631-273-5335
San Jose
Microchip Technology Inc.
2107 North First Street, Suite 590
San Jose, CA 95131
Tel: 408-436-7950 Fax: 408-436-7955
AMERICAS (continued)
Toronto
Microchip Technology Inc.
5925 Airport Road, Suite 200
Mississauga, Ontario L4V 1W1, Canada
Tel: 905-405-6279 Fax: 905-405-6253
ASIA/PACIFIC
China - Beijing
Microchip Technology, Beijing
Unit 915, 6 Chaoyangmen Bei Dajie
Dong Erhuan Road, Dongcheng District
New China Hong Kong Manhattan Building
Beijing, 100027, P.R.C.
Tel: 86-10-85282100 Fax: 86-10-85282104
China - Shanghai
Microchip Technology
Unit B701, Far East International Plaza,
No. 317, Xianxia Road
Shanghai, 200051, P.R.C.
Tel: 86-21-6275-5700 Fax: 86-21-6275-5060
Hong Kong
Microchip Asia Pacific
Unit 2101, Tower 2
Metroplaza
223 Hing Fong Road
Kwai Fong, N.T., Hong Kong
Tel: 852-2-401-1200 Fax: 852-2-401-3431
India
Microchip Technology Inc.
India Liaison Office
No. 6, Legacy, Convent Road
Bangalore, 560 025, India
Tel: 91-80-229-0061 Fax: 91-80-229-0062
Japan
Microchip Technology Intl. Inc.
Benex S-1 6F
3-18-20, Shinyokohama
Kohoku-Ku, Yokohama-shi
Kanagawa, 222-0033, Japan
Tel: 81-45-471- 6166 Fax: 81-45-471-6122
Korea
Microchip Technology Korea
168-1, Youngbo Bldg. 3 Floor
Samsung-Dong, Kangnam-Ku
Seoul, Korea
Tel: 82-2-554-7200 Fax: 82-2-558-5934
ASIA/PACIFIC (continued)
Singapore
Microchip Technology Singapore Pte Ltd.
200 Middle Road
#07-02 Prime Centre
Singapore, 188980
Tel: 65-334-8870 Fax: 65-334-8850
Taiwan
Microchip Technology Taiwan
10F-1C 207
Tung Hua North Road
Taipei, Taiwan
Tel: 886-2-2717-7175 Fax: 886-2-2545-0139
EUROPE
Denmark
Microchip Technology Denmark ApS
Regus Business Centre
Lautrup hoj 1-3
Ballerup DK-2750 Denmark
Tel: 45 4420 9895 Fax: 45 4420 9910
France
Arizona Microchip Technology SARL
Parc d’Activite du Moulin de Massy
43 Rue du Saule Trapu
Batiment A - ler Etage
91300 Massy, France
Tel: 33-1-69-53-63-20 Fax: 33-1-69-30-90-79
Germany
Arizona Microchip Technology GmbH
Gustav-Heinemann-Ring 125
D-81739 München, Germany
Tel: 49-89-627-144 0 Fax: 49-89-627-144-44
Italy
Arizona Microchip Technology SRL
Centro Direzionale Colleoni
Palazzo Taurus 1 V. Le Colleoni 1
20041 Agrate Brianza
Milan, Italy
Tel: 39-039-65791-1 Fax: 39-039-6899883
United Kingdom
Arizona Microchip Technology Ltd.
505 Eskdale Road
Winnersh Triangle
Wokingham
Berkshire, England RG41 5TU
Tel: 44 118 921 5858 Fax: 44-118 921-5835
05/16/00
WORLDWIDE SALES AND SERVICE
Microchip received QS-9000 quality system
certification for its worldwide headquarters,
design and wafer fabrication facilities in
Chandler and Tempe, Arizona in July 1999. The
Company’s quality system processes and
procedures are QS-9000 compliant for its
PICmicro® 8-bit MCUs, KEELOQ® code hopping
devices, Serial EEPROMs and microperipheral
products. In addition, Microchip’s quality
system for the design and manufacture of
development systems is ISO 9001 certified.
39500 18C Reference Manual.book Page 33 Monday, July 10, 2000 6:12 PM
ATWINC15x0
ATWINC15x0 Wi-Fi® Network Controller Software Design
Guide
Introduction
Microchip’s SmartConnect ATWINC15x0 is an IEEE®
802.11 b/g/n network controller SoC for Internet of
Things (IoT) applications. It is an ideal add-on to the existing microcontroller (MCU) solutions bringing WiFi
and network capabilities through an SPI-to-Wi-Fi interface. The ATWINC15x0 connects to any
Microchip AVR®
or Microchip SMART™
MCU with minimal resource requirements.
Features
• Wi-Fi IEEE 802.11 b/g/n STA, and AP modes
• Wi-Fi Protected Setup (WPS)
• Support of WEP, WPA/WPA2 Personal, and WPA/WPA2 Enterprise Security
– EAP-TLS
– EAP-PEAPv0/1 with TLS
– EAP-TTLSv0 with MSCHAPv2
– EAP-PEAPv0/1 with MSCHAPv2
• Embedded network stack protocols to offload work from the MCU (minimize the host CPU
requirements). This allows the Wi-Fi Network Controller (WINC) to operate with a wide range of
MCUs including low-end MCUs.
• Embedded uIP TCP/IP stack with BSD-Style socket API
• Embedded network protocols
– DHCP client/server
– DNS resolver client
– SNTP client for UTC time synchronization
• Embedded TLS security abstracted behind BSD-style socket API
• HTTP server for provisioning over AP mode
• Ultra-low C IEEE 802.11 b/g/n RF/PH/MAC SoC
• Fast boot from On-Chip boot ROM
• 8 Mb (WINC1510) and 4 Mb (WINC1500) internal Flash memory with Over-the-Air (OTA) firmware
upgrade
• WINC1510 support Host File Download feature which can be used for host MCU over the air
firmware update
• Low-power consumption with different Power Save modes
• Low footprint host driver with the following capabilities:
– Can run on 8-, 16-, and 32-bit MCU using SPI interface
– Little- and big-endian support
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 1
Table of Contents
Introduction......................................................................................................................1
Features.......................................................................................................................... 1
1. Host Driver Architecture............................................................................................ 5
1.1. WLAN API.................................................................................................................................... 5
1.2. Socket API....................................................................................................................................5
1.3. Host Interface (HIF)......................................................................................................................6
1.4. Board Support Package (BSP).....................................................................................................6
1.5. Serial Bus Interface......................................................................................................................6
2. ATWINC15x0 System Architecture............................................................................7
2.1. Bus Interface................................................................................................................................ 7
2.2. Nonvolatile Storage......................................................................................................................8
2.3. CPU..............................................................................................................................................8
2.4. IEEE 802.11 MAC Hardware........................................................................................................8
2.5. Program Memory..........................................................................................................................8
2.6. Data Memory................................................................................................................................8
2.7. Shared Packet Memory................................................................................................................8
2.8. IEEE 802.11 MAC Firmware........................................................................................................ 8
2.9. Memory Manager......................................................................................................................... 8
2.10. Power Management..................................................................................................................... 9
2.11. WINC RTOS.................................................................................................................................9
2.12. WINC IoT Library..........................................................................................................................9
3. WINC Initialization and Simple Application..............................................................11
3.1. BSP Initialization.........................................................................................................................11
3.2. WINC Host Driver Initialization................................................................................................... 11
3.3. Socket Layer Initialization...........................................................................................................11
3.4. WINC Event Handling................................................................................................................ 12
3.5. Example Code............................................................................................................................13
4. ATWINC15x0 Configuration.....................................................................................14
4.1. Device Parameters.....................................................................................................................14
4.2. WINC Modes of Operation......................................................................................................... 14
4.3. Network Parameters...................................................................................................................16
4.4. Power Save Modes.................................................................................................................... 17
4.5. Configuring Listen Interval and DTIM Monitoring.......................................................................18
5. Wi-Fi Station Mode.................................................................................................. 20
5.1. Scan Configuration Parameters................................................................................................. 20
5.2. Wi-Fi Scan..................................................................................................................................20
5.3. Wi-Fi Security.............................................................................................................................21
5.4. On Demand Wi-Fi Connection................................................................................................... 22
ATWINC15x0
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 2
5.5. Default Connection.....................................................................................................................25
5.6. Encrypted Credential Storage.................................................................................................... 26
5.7. Simple Roaming.........................................................................................................................27
5.8. Multiple Gain Table.....................................................................................................................29
5.9. Host File Download.................................................................................................................... 30
6. Socket Programming............................................................................................... 39
6.1. Overview.................................................................................................................................... 39
6.2. Sockets API................................................................................................................................39
6.3. Socket Connection Flow.............................................................................................................47
6.4. Example Code............................................................................................................................51
7. Transport Layer Security (TLS)............................................................................... 56
7.1. TLS Overview.............................................................................................................................56
7.2. TLS Connection Establishment..................................................................................................56
7.3. Server Certificate Installation..................................................................................................... 58
7.4. WINC TLS Limitations................................................................................................................59
7.5. SSL Client Code Example..........................................................................................................60
8. Wi-Fi AP Mode........................................................................................................ 62
8.1. Overview.................................................................................................................................... 62
8.2. Setting the WINC AP Mode........................................................................................................62
8.3. Limitations.................................................................................................................................. 62
8.4. Sequence Diagram.....................................................................................................................62
8.5. AP Mode Code Example............................................................................................................63
9. Provisioning............................................................................................................. 65
9.1. HTTP Provisioning..................................................................................................................... 65
9.2. Limitations.................................................................................................................................. 68
9.3. Wi-Fi Protected Setup (WPS).....................................................................................................68
10. Over-The-Air Upgrade.............................................................................................71
10.1. Overview.................................................................................................................................... 71
10.2. OTA Image Architecture............................................................................................................. 71
10.3. OTA Download Sequence Diagram........................................................................................... 72
10.4. OTA Firmware Rollback............................................................................................................. 72
10.5. OTA Limitations..........................................................................................................................73
10.6. OTA Code Example....................................................................................................................73
11. Multicast Sockets.....................................................................................................74
11.1. Overview.................................................................................................................................... 74
11.2. How to Use Filters......................................................................................................................74
11.3. Multicast Socket Code Example.................................................................................................74
12. WINC Serial Flash Memory.....................................................................................78
12.1. Overview and Features.............................................................................................................. 78
12.2. Accessing to Serial Flash...........................................................................................................78
12.3. Read/Write/Erase Operations.................................................................................................... 78
ATWINC15x0
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 3
13. Host Interface (HIF) Protocol...................................................................................81
13.1. Transfer Sequence Between the HIF Layer and the WINC Firmware........................................82
13.2. HIF Message Header Structure..................................................................................................84
13.3. HIF Layer APIs...........................................................................................................................84
13.4. Scan Code Example...................................................................................................................85
14. WINC SPI Protocol..................................................................................................90
14.1. Introduction.................................................................................................................................90
14.2. Message Flow for Basic Transactions......................................................................................101
14.3. SPI Level Protocol Example.....................................................................................................105
15. Appendix A. How to Generate Certificates............................................................128
15.1. Introduction...............................................................................................................................128
15.2. Steps........................................................................................................................................ 128
15.3. Limitations................................................................................................................................ 128
16. Appendix B. X.509 Certificate Format and Conversion.........................................129
16.1. Introduction...............................................................................................................................129
16.2. Conversion Between Different Formats................................................................................... 129
17. References............................................................................................................ 131
18. Document Revision History................................................................................... 132
The Microchip Web Site.............................................................................................. 133
Customer Change Notification Service........................................................................133
Customer Support....................................................................................................... 133
Microchip Devices Code Protection Feature............................................................... 133
Legal Notice.................................................................................................................134
Trademarks................................................................................................................. 134
Quality Management System Certified by DNV...........................................................135
Worldwide Sales and Service......................................................................................136
ATWINC15x0
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 4
1. Host Driver Architecture
The following figure shows the architecture of the WINC host driver software, which runs on the host
MCU.
Figure 1-1. Host Driver Software Architecture
The ATWINC15x0 host driver software is a C library, which provides the host MCU application with
necessary APIs to perform necessary WLAN and socket operations. The components of the host driver
are described in the following sub-sections.
1.1 WLAN API
This module provides an interface to the application for all Wi-Fi operations and any non-IP related
operations.
This includes the following services:
• Wi-Fi STA management operations
– Wi-Fi scan
– Wi-Fi connection management (connect, disconnect, connection status, and so on)
– WPS activation/deactivation
• Wi-Fi AP enable/disable
• Wi-Fi power save control API
This interface is defined in the m2m_wifi.h file.
1.2 Socket API
This module provides the socket communication APIs that are mostly compliant with the well-known BSD
sockets to enable rapid application development. To comply with the nature of the MCU application
environment, there are differences in API prototypes and in usage of some APIs between the WINC
sockets and BSD sockets.
This interface is defined in the socket.h file.
ATWINC15x0
Host Driver Architecture
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 5
The detailed description of the socket operations is provided in Socket Programming.
1.3 Host Interface (HIF)
The HIF is responsible for handling the communication between the host driver and the WINC firmware.
This includes interrupt handling, DMA and HIF command/response management. The host driver
communicates with the firmware in the form of commands and responses formatted by the HIF layer.
The interface is defined in the m2m_hif.h file.
The detailed description of the HIF design is provided in Host Interface Protocol.
1.4 Board Support Package (BSP)
The Board Support Package abstracts the functionality of a specific host MCU platform. This allows the
driver to be portable to a wide range of hardware and hosts. Abstraction includes: pin assignment, power
on/off sequence, reset sequence and peripheral definitions (Push buttons, LEDs, and so on).
The minimum required BSP functionality is defined in the nm_bsp.h file.
1.5 Serial Bus Interface
The Serial Bus Interface module abstracts the hardware associated with implementing the bus between
the Host and the WINC. The serial bus interface abstracts I2C, SPI, or UART bus (Currently, host driver
supports only SPI bus interface). The basic bus access operations (Read and Write) are implemented in
this module as appropriate for the interface type and the specific hardware.
The bus interface APIs are defined in the nm_bus_wrapper.h file.
ATWINC15x0
Host Driver Architecture
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 6
2. ATWINC15x0 System Architecture
The following figure shows the ATWINC15x0 system architecture. In addition to its built-in Wi-Fi
IEEE-802.11 physical layer and RF front end, the WINC ASIC contains an embedded APS3S-Cortus 32-
bit CPU to run the WINC firmware. The firmware comprises the Wi-Fi IEEE-802.11 MAC layer and
embedded protocol stacks which offload the host MCU. The components of the system are described in
the following sub-sections.
Figure 2-1. ATWINC15x0 System Architecture
2.1 Bus Interface
Hardware logic for the supported bus types for the ATWINC15x0 communications.
Note: SPI is currently the bus interface supported by the Host Driver.
ATWINC15x0
ATWINC15x0 System Architecture
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 7
2.2 Nonvolatile Storage
The ATWINC1510 has an integrated 8 Mb and the ATWINC1500 has an integrated 4 Mb serial Flash
inside the WINC package (SIP). This stores the WINC firmware image and can store a second image to
support OTA. It also stores information used by the WINC firmware in the run-time.
The detailed description of the serial Flash is provided in WINC Serial Flash Memory.
2.3 CPU
The SoC contains an APS3S-Cortus 32-bit CPU running at 40 MHz clock speed which executes the
embedded WINC firmware.
2.4 IEEE 802.11 MAC Hardware
The SoC contains a hardware accelerator to ensure fast and compliant implementation of the IEEE
802.11 MAC layer and associated timing. It offloads IEEE 802.11 MAC functionality from firmware to
improve performance and boost the MAC throughput. The accelerator includes hardware encryption/
decryption of Wi-Fi traffic and traffic filtering mechanisms to avoid unnecessary processing in software.
2.5 Program Memory
128 KB Instruction RAM is provided for execution of the ATWINC15x0 firmware code.
2.6 Data Memory
64 KB RAM is provided for the ATWINC15x0 firmware data storage.
2.7 Shared Packet Memory
128 KB memory is provided for TX/RX packet management. It is shared between the MAC hardware and
the CPU. This memory is managed by the Memory Manager SW component.
2.8 IEEE 802.11 MAC Firmware
The system supports IEEE 802.11 b/g/n Wi-Fi MAC including WEP and WPA/WPA2 security supplicant.
Between the MAC hardware and the firmware, a full range of IEEE 802.11 features are implemented and
supported including beacon generation and reception, control packet generation and reception, and
packet aggregation and de-aggregation.
2.9 Memory Manager
The memory manager is responsible for the allocation and de-allocation of memory chunks in both
shared packet memory and data memory.
ATWINC15x0
ATWINC15x0 System Architecture
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 8
2.10 Power Management
The Power Management module is responsible for handling different Power Save modes supported by
the WINC and coordinating these modes with the Wi-Fi transceiver.
2.11 WINC RTOS
The firmware includes a low-footprint real-time scheduler which allows concurrent multi-tasking on the
ATWINC15x0 CPU. The ATWINC15x0 RTOS provides semaphores and timer functionality.
2.12 WINC IoT Library
The WINC IoT library provides a set of networking protocols in the WINC firmware. It offloads the host
MCU from networking and transport layer protocols. The following sections describe the components of
the WINC IoT library.
2.12.1 WINC TCP/IP STACK
The WINC TCP/IP is an IPv4.0 stack based on the uIP (pronounced micro IP) TCP/IP stack.
uIP is a low footprint TCP/IP stack which has the ability to run on a memory-constrained microcontroller
platform. It was originally developed by Adam Dunkels, licensed under a BSD style license, and further
developed by a wide group of developers. The WINC TCP/IP stack is a customized version of the original
uIP implementation which has several enhancements to boost TCP and UDP throughput.
2.12.2 DHCP CLIENT/SERVER
A DHCP client is embedded in the WINC firmware that can automatically obtain an IP configuration after
connecting to a Wi-Fi network.
The WINC firmware provides an instance of a DHCP server that automatically starts when the WINC AP
mode is enabled. When the host MCU application activates the AP mode, it is allowed to configure the
DHCP Server IP address pool range within the AP configuration parameters.
2.12.3 DNS RESOLVER
The WINC firmware contains an instance of an embedded DNS resolver. This module can return an IP
address by resolving the host domain names supplied with the socket API call gethostbyname.
2.12.4 SNTP
The SNTP (Simple Network Time Protocol) module implements an SNTP client used to synchronize the
WINC internal clock to the UTC clock.
2.12.5 Enterprise Security
The Enterprise Security module implements the following authentication protocols for establishing a Wi-Fi
connection with an AP by WPA/WPA2-Enterprise Security.
• EAP with TLS
• EAP-PEAPv0/v1 with MSCHAPV2
• EAP-TTLSv0 with MSCHAPv2
• EAP-PEAPv0/v1 with MSCHAPv2
2.12.6 TRANSPORT LAYER SECURITY
For TLS implementation, refer to Section 7 “Transport Layer Security (TLS)” for details.
ATWINC15x0
ATWINC15x0 System Architecture
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 9
2.12.7 WI-FI PROTECTED SETUP
For WPS protocol implementation, refer to Section 10.3 “Wi-Fi Protected Setup (WPS)” for details.
2.12.8 CRYPTO LIBRARY
The Crypto Library contains a set of cryptographic algorithms used by the common security protocols.
This library has an implementation of the following algorithms:
• MD4 Hash algorithm (used only for MsChapv2.0 digest calculation)
• MD5 Hash algorithm
• SHA-1 Hash algorithm
• SHA-256 Hash algorithm
• DES Encryption (used only for MsChapv2.0 digest calculation)
• MS-CHAPv2.0 (used as the EAP-TTLS inner authentication algorithm)
• MS-CHAPv2.0 (used as the EAP-PEAP and EAP-TTLS inner authentication algorithm)
• AES-128, AES-256 Encryption (used for securing WPS and TLS traffic)
• BigInt module for large integer arithmetic (for Public Key Cryptographic computations)
• RSA Public Key cryptography algorithms (includes RSA Signature and RSA Encryption algorithms)
ATWINC15x0
ATWINC15x0 System Architecture
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 10
3. WINC Initialization and Simple Application
After powering-up the WINC device, a set of synchronous initialization sequences must be executed, for
the correct operation of the Wi-Fi functions. This chapter aims to explain the different steps required
during the initialization phase of the system. After initialization, the host MCU application is required to
call the WINC driver entry point to handle events from the WINC firmware.
• BSP Initialization
• WINC Host Driver Initialization
• Socket Layer Initialization
• Call WINC Driver Entry Point
Note: The initialization sequence must be completed to successfully operate the WINC start-up
procedure.
3.1 BSP Initialization
The BSP is initialized by calling the nm_bsp_init API. The BSP initialization routine performs the
following steps:
• Resets the WINC1
using the corresponding host MCU control GPIOs.
• Initializes the host MCU GPIO which connects to the WINC interrupt line. It configures the GPIO as
an interrupt source to the host MCU. During runtime, the WINC interrupts the host to notify the
application of events and data pending inside the WINC firmware.
• Initializes the host MCU delay function used within nm_bsp_sleep implementation.
3.2 WINC Host Driver Initialization
The WINC host driver is initialized by calling the m2m_wifi_init API. The host driver initialization
routine performs the following steps:
• Initializes the bus wrapper and SPI peripheral. The compilation flag CONF_WINC_USE_SPI must be
enabled in conf_winc.h (bus interfaces CONF_WINC_USE_UART and CONF_WINC_USE_I2C are
currently not supported).
• Registers an application-defined Wi-Fi event handler.
• Initializes the driver and ensures compatibility between the WINC firmware version and the driver
version.
• Initializes the host interface and the Wi-Fi layer and registers the BSP Interrupt.
Note: A Wi-Fi event handler is required for the correct operation of any WINC application.
3.3 Socket Layer Initialization
Socket layer initialization is carried out by calling the socketInit API. It must be called prior to any
socket activity. For more information about socket initialization and programming, refer to WINC Sockets
API.
1 Refer to the ATWINC15x0-MR210xB Data Sheet (DS70005304) for more information about the
hardware power-up/down sequence.
ATWINC15x0
WINC Initialization and Simple Application
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 11
3.4 WINC Event Handling
The WINC host driver API allows the host MCU application to interact with the WINC firmware. To
facilitate interaction, the WINC driver implements the Host Interface (HIF) Protocol as described in
Section 15 “Host Interface (HIF) Protocol”. The HIF protocol defines how to serialize and de-serialize
API requests and response callbacks over the serial bus interface SPI (I2C and UART are currently not
supported).
Figure 3-1. WINC System Architecture
The WINC host driver API provides services to the host MCU applications that are mainly divided in two
major categories: Wi-Fi control services and Socket services. The Wi-Fi control services allow actions
such as channel scanning, network identification, connection and disconnection. The Socket control
services allow application data transfer once a Wi-Fi connection is established.
3.4.1 Asynchronous Events
Some APIs in the ATWINC15x0 host driver are synchronous function calls, where the result is ready by
the return of the function. However, most API functions in the ATWINC15x0 host driver are asynchronous.
This means that when the application calls an API to request a service, the call is non-blocking and
returns immediately, before the requested action is completed. When completed, a notification is provided
in the form of a HIF protocol message from the WINC firmware to the host which, in turn, is delivered to
the application via a callback2
function. Asynchronous operation is essential when the requested service
such as Wi-Fi connection may take significant time to complete. In general, the ATWINC15x0 firmware
uses asynchronous events to signal the host driver about status change or pending data.
The HIF uses push architecture where the data and events are pushed from the ATWINC15x0 firmware
to the host MCU in a First-Come First-Served (FCFS) manner. For instance, the host MCU application
has two open sockets: socket 1 and socket 2. If the ATWINC15x0 receives socket 1 data followed by
socket 2 data, then HIF delivers socket data in two HIF protocol messages in the order in which it is
received. HIF does not allow reading socket 2 data before socket 1 data.
3.4.2 Interrupt Handling
The HIF interrupts the host MCU when one or more events are pending in the ATWINC15x0 firmware.
The host MCU application is a big state machine which processes received data and events when the
2 The callback is C function which contains an application-defined logic. The callback is registered
using the ATWINC15x0 host driver registration API to handle the result of the requested service.
ATWINC15x0
WINC Initialization and Simple Application
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 12
ATWINC15x0 driver calls the event callback function(s). To receive event callbacks, the host MCU
application is required to call the m2m_wifi_handle_events API to let the host driver retrieve and
process the pending events from the ATWINC15x0 firmware. It is recommended to call this function if any
of the following events occur:
• The host MCU application polls the API in main loop or a dedicated task
• When the host MCU receives an interrupt from the ATWINC15x0 firmware
Note: All the application-defined event callback functions registered with the ATWINC15x0 driver run in
the context m2m_wifi_handle_events API.
The above HIF architecture allows the ATWINC15x0 host driver to be flexible to run in the following
configurations:
• Host MCU with no operating system configuration – the MCU main loop is responsible to handle
deferred work from the interrupt handler
• Host MCU with operating system configuration – a dedicated task or thread is required to call
m2m_wifi_handle_events to handle deferred work from the interrupt handler
Note:
1. Host driver entry point m2m_wifi_handle_events is non-reentrant. In the operating system
configuration, it is required to protect the host driver from reentrance by a synchronization object.
2. When the host MCU is polling m2m_wifi_handle_events, the API checks for pending
unhandled interrupt from the ATWINC15x0. If no interrupt is pending, it returns immediately. If an
interrupt is pending, m2m_wifi_handle_events sequentially reads all the pending HIF
messages and dispatches the HIF message content to the respective registered callback. If a
callback is not registered to handle the type of message, the HIF message content is discarded.
3.5 Example Code
The following example code shows the initialization flow, as described in the previous sections.
static void wifi_cb(uint8_t u8MsgType, void *pvMsg)
{
}
int main (void)
{
tstrWifiInitParam param;
nm_bsp_init();
m2m_memset((uint8*)¶m, 0, sizeof(param));
param.pfAppWifiCb = wifi_cb;
/*intilize the WINC Driver*/
ret = m2m_wifi_init(¶m);
if (M2M_SUCCESS != ret){
M2M_ERR("Driver Init Failed <%d>\n",ret);
while(1);
}
while(1){
/* Handle the app state machine plus the WINC event handler */
while(m2m_wifi_handle_events(NULL) != M2M_SUCCESS) {
}
}
}
ATWINC15x0
WINC Initialization and Simple Application
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 13
4. ATWINC15x0 Configuration
The ATWINC15x0 firmware offers a set of configurable parameters that control its behavior. There is a set
of APIs provided to the host MCU application to configure these parameters. The configuration APIs are
categorized according to their functionality, into device, network and power saving parameters.
Any parameters left unset by the host MCU application use their default values assigned during the
initialization of the ATWINC15x0 firmware. A host MCU application needs to configure its parameters
when coming out of cold boot or when a specific configuration change is required.
4.1 Device Parameters
4.1.1 System Time
It is important to set the WINC system to UTC time to ensure a proper validity check of the X509
certificate expiration date. Since the WINC does not contain a built-in Real-Time Clock (RTC), there are
two ways to obtain UTC time:
• Using the internal SNTP client – this is enabled by default in the WINC firmware at start-up. The
SNTP client synchronizes the WINC system clock to the UTC time from the time servers. The NTP
server that SNTP client uses can be configured using the API m2m_wifi_configure_sntp. The
default NTP server used by the WINC is time-c.nist.gov. The SNTP client uses a default
update cycle of one day.
• From the host MCU RTC – if the host MCU has a RTC, the application may disable the SNTP client
by calling m2m_wifi_enable_sntp(0) (by passing zero as the argument) after the WINC
initialization. The application provisions the WINC system time by calling
m2m_wifi_set_system_time API.
4.1.2 Firmware and Driver Version
During initialization (m2m_wifi_init), the host driver checks the compatibility between the driver and
the WINC firmware. The relevant parameters are:
• M2M_HIF_MAJOR_VALUE
• M2M_HIF_MINOR_VALUE
Note: These parameters are stated in release note version information as “Host Interface Level: X.Y”.
If the driver and the WINC firmware have the same values of M2M_HIF_MAJOR_VALUE, then they are
deemed compatible and m2m_wifi_init returns with M2M_SUCCESS.
If the driver and the WINC firmware have different values of M2M_HIF_MAJOR_VALUE, then they are
deemed incompatible and m2m_wifi_init returns with M2M_ERR_FW_VER_MISMATCH. In this case,
communication is limited; the only permitted communication is for the driver to request the WINC firmware
to switch to the WINC firmware image in the inactive partition of WINC flash, via
m2m_wifi_check_ota_rb and m2m_ota_switch_firmware.
Example code to handle this situation is available in the driver file m2m_ota.h.
4.2 WINC Modes of Operation
The WINC firmware supports the following modes of operation:
ATWINC15x0
ATWINC15x0 Configuration
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 14
• Idle mode
• Wi-Fi STA mode
• Wi-Fi Hotspot (AP)
Figure 4-1. WINC Modes of Operation
IDLE AP STA
m2_wifi_connect
m2m_wifi_default_connect
M2M_WIFI_RESP_CON_STATE_CHANGED
m2m_wifi_disconnect
m2m_wifi_disable_ap
m2m_wifi_enable_ap
4.2.1 Idle Mode
After the host MCU application calls the ATWINC15x0 driver initialization m2m_wifi_init API, the
ATWINC15x0 remains in Idle mode waiting for any command to change the mode or to update the
configuration parameters. In this mode, the ATWINC15x0 enters into Power Save mode which disables
the IEEE 802.11 radio and all unneeded peripherals and suspends the ATWINC15x0 CPU. If the
ATWINC15x0 receives any configuration commands from the host MCU, it updates the configuration,
sends back the response to the host MCU, and then returns to the Power Save mode.
4.2.2 Wi-Fi Station Mode
The ATWINC15x0 enters Station (STA) mode when the host MCU requests connection to an AP using
the m2m_wifi_connect or m2m_wifi_default_connect APIs.
Note: m2m_wifi_connect is deprecated from v19.6.1 and above. For more details, see 5.3 Wi-Fi
Security.
The ATWINC15x0 exits STA mode when it receives a disconnect request from the Wi-Fi AP conveyed to
the host MCU application via the event callback M2M_WIFI_RESP_CON_STATE_CHANGED or when the
host MCU application decides to terminate the connection via m2m_wifi_disconnect API.
Note: The supported API functions in this mode use the HIF command types: tenuM2mConfigCmd and
tenuM2mStaCmd. See the full list of commands in the m2m_types.h header file.
For more information about STA mode, refer to Wi-Fi Station Mode.
4.2.3 Wi-Fi Hotspot (AP) Mode
In AP mode, the WINC allows Wi-Fi stations to connect and obtain the IP address from the WINC DHCP
server. To enter AP mode, the host MCU application calls m2m_wifi_enable_ap API. To exit AP mode,
the application calls m2m_wifi_disable_ap API.
The supported API functions in this mode use the HIF command types: tenuM2mApCmd and
tenuM2mConfigCmd. See the full list of commands in the m2m_types.h header file.
For more information about this mode, refer to Wi-Fi AP Mode.
ATWINC15x0
ATWINC15x0 Configuration
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 15
4.3 Network Parameters
4.3.1 Wi-Fi MAC Address
The WINC firmware provides two methods to assign the WINC MAC address:
• Assignment from the host MCU – this method occurs when the host MCU application calls the
m2m_wifi_set_mac_address API after initialization using m2m_wifi_init API.
• Assignment from the WINC OTP (One-Time-Programmable) memory – the WINC supports an
internal MAC address assignment method through a built-in OTP memory. If MAC address is
programmed in the WINC OTP memory, the WINC working MAC address defaults to the OTP MAC
address unless the host MCU application programmatically sets a different MAC address after
initialization using the API m2m_wifi_set_mac_address.
Note:
• OTP MAC address is programmed in the WINC OTP memory at the time of manufacturing.
• Use m2m_wifi_get_otp_mac_address API to check if there is a valid programmed MAC
address in the WINC OTP memory. The host MCU application can also use the same API to read
the OTP MAC address octets. m2m_wifi_get_otp_mac_address API not to be confused with
the m2m_wifi_get_mac_address API which reads the working WINC MAC address in the WINC
firmware regardless from whether it is assigned from the host MCU or from the WINC OTP.
• For more details on API, refer to the Atmel Software Framework for ATWINC1500 (Wi-Fi).
4.3.2 IP Address
The ATWINC15x0 firmware uses the embedded DHCP client to automatically obtain an IP configuration
after a successful Wi-Fi connection. DHCP is the preferred method and therefore it is used as a default
method. After the IP configuration is obtained, the host MCU application is notified by the asynchronous
event M2M_WIFI_REQ_DHCP_CONF.
Alternatively, the host MCU application can set a static IP configuration by calling the
m2m_wifi_set_static_ip API. Before setting a static IP address, it is recommended to disable DHCP
using the API m2m_wifi_enable_dhcp(0) and then set the static IP as shown below.
In Main(), disable dhcp after m2m_wifi_init as shown below
/* Initialize Wi-Fi driver with data and status callbacks. */
param.pfAppWifiCb = wifi_cb;
ret = m2m_wifi_init(¶m);
if (M2M_SUCCESS != ret)
{
printf("main: m2m_wifi_init call error!(%d)\r\n", ret);
while (1)
{}
}
m2m_wifi_enable_dhcp(0);
Set Static IP when WINC is connected to AP as shown below.
static void wifi_cb(uint8_t u8MsgType, void *pvMsg)
{
switch (u8MsgType) {
case M2M_WIFI_RESP_CON_STATE_CHANGED:
{
tstrM2mWifiStateChanged *pstrWifiState = (tstrM2mWifiStateChanged *)pvMsg;
if (pstrWifiState->u8CurrState == M2M_WIFI_CONNECTED){
printf("Wi-Fi connected\r\n");
tstrM2MIPConfig ip_client;
ip_client.u32StaticIP = _htonl(0xc0a80167); // Provide the required Static
IP
ATWINC15x0
ATWINC15x0 Configuration
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 16
ip_client.u32DNS = _htonl(0xc0a80101); // Provide DNS server details
ip_client.u32SubnetMask = _htonl(0xFFFFFF00); // Provide the SubnetMask for
the currently connected AP
ip_client.u32Gateway = _htonl(0xc0a80101); // Provide the GAteway IP for
the AP
printf("Wi-Fi setting static ip\r\n");
m2m_wifi_set_static_ip(&ip_client);
}
}
}
4.4 Power Save Modes
The WINC firmware supports multiple Power Save modes which provide flexibility to the host MCU
application to tweak the system power consumption. The host MCU can configure the WINC Power
Saving policy using the m2m_wifi_set_sleep_mode and m2m_wifi_set_lsn_int APIs.
The WINC supports the following Power Save modes:
• M2M_PS_MANUAL
• M2M_PS_DEEP_AUTOMATIC
• M2M_PS_AUTOMATIC (deprecated, not be used in new implementations)
• M2M_PS_H_AUTOMATIC (deprecated, not be used in new implementations)
Note: M2M_PS_DEEP_AUTOMATIC mode recommended for most applications.
4.4.1 M2M_PS_MANUAL
This is a fully host-driven Power Save mode.
• The WINC sleeps when the host uses the m2m_wifi_request_sleep API. During this period,
the host MCU can also sleep for extended durations.
• The WINC wakes up when the host MCU application requests services from the WINC by calling
any host driver API function, for example, Wi-Fi or socket operation.
Note: In M2M_PS_MANUAL mode, when the WINC sleeps due to m2m_wifi_request_sleep API, the
WINC does not wake up to receive and monitor AP beacon. Beacon monitoring is resumed when the host
MCU application wakes up the WINC.
For an active Wi-Fi connection, the AP may exit the connection if the WINC is unavailable due to long
sleep time. If connection is dropped, the WINC detects the disconnection on the next wake-up cycle and
notifies the host to reconnect to the AP again. To maintain an active Wi-Fi connection for extended
durations, the host MCU application must periodically wake up the WINC in order to send a keep-alive
Wi-Fi frame to the AP. The host must carefully choose the sleep period to satisfy the tradeoff between
keeping the Wi-Fi connection uninterrupted and minimizing the system power consumption.
This mode is useful for applications which send notifications very rarely due to a certain trigger. It also fits
applications which periodically send notifications with a very long spacing between notifications. Careful
power planning is required when using this mode. If the host MCU decides to sleep for a longer period, it
may use M2M_PS_MANUAL or may power off the WINC3
. The advantage of this mode compared to
powering off the WINC is that M2M_PS_MANUAL saves the time required for the WINC firmware to boot
since the firmware is always loaded in the WINC memory. The real advantage and disadvantage depend
on the nature of the application. In some applications, the sleep duration can be long enough to be a
3 Refer to the ATWINC15x0-MR210xB Data Sheet (DS70005304) for more information about the
hardware power-up/down sequence.
ATWINC15x0
ATWINC15x0 Configuration
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 17
power-efficient decision to power off the WINC and then power it on again and reconnect to the AP when
the host MCU wakes up. In other situations, a latency-sensitive application may choose to use
M2M_PS_MANUAL to avoid the WINC firmware boot latency on the expense of slightly increased power
consumption.
During the WINC Sleep mode, the WINC in M2M_PS_MANUAL mode saves more power than
M2M_PS_DEEP_AUTOMATIC mode. In M2M_PS_MANUAL mode, the WINC skips beacon monitoring
whereas in M2M_PS_DEEP_AUTOMATIC mode, it wakes up to receive beacons. The comparison also
includes the effect of the host MCU sleep duration: if the host MCU sleeps for a longer period, the Wi-Fi
connection may frequently drop and the power advantage of the M2M_PS_MANUAL mode is lost due to the
power consumed in the Wi-Fi reconnection. In contrast, the M2M_PS_DEEP_AUTOMATIC mode can keep
the Wi-Fi connection for long durations at the expense of waking up the WINC to monitor the AP beacon.
4.4.2 M2M_PS_AUTOMATIC
This mode is deprecated and kept for backward compatibility and development reasons. It is not
recommended to use in new implementations.
4.4.3 M2M_PS_H_AUTOMATIC
This mode is deprecated and kept for backward compatibility and development reasons. It is not
recommended to use in new implementations.
4.4.4 M2M_PS_DEEP_AUTOMATIC
This mode implements the Wi-Fi standard power-saving method in the WINC module. The WINC sleeps
and periodically wakes up to monitor AP beacons. The AP is required to buffer data while stations are in
Power Save mode and transmit data when stations wake-up. The AP periodically transmits a beacon
frame to synchronize with a network for every beacon period. A station, which is in Power Save mode,
periodically wakes up to receive the beacon. The beacon conveys information to the station about
pending unicast data, which are buffered inside the AP while the station was in Sleep mode. The beacon
also provides information about the broadcast/multicast data.
In this mode, the WINC module enters into Sleep state by turning off the IEEE 802.11 radio, MAC, and
system clock. Prior to entering the Sleep mode, the ATWINC15x0 programs a hardware timer (running on
an internal low-power oscillator) with a sleep period determined by the WINC firmware power
management module.
Any of the following events can wake-up the WINC module from Sleep state:
• Expiry of the hardware sleep timer. The WINC wakes up to receive the upcoming beacon from AP.
• The WINC wakes up4
when the host MCU application requests services from the WINC by calling
any host driver API function, for example, Wi-Fi or socket operation.
4.5 Configuring Listen Interval and DTIM Monitoring
The WINC allows the host MCU application to tweak system power consumption by configuring beacon
monitoring parameters. The AP periodically send beacons for every DTIM period (for example, 100 ms).
The beacon contains a TIM element which informs the station about the unicast data for the station that
are buffered in the AP. The station negotiates with the AP for a listen interval. The listen interval tells the
AP for how many beacon periods the station will sleep before it wakes up to receive data buffered in the
4 The wake-up sequence is internally handled in the WINC host driver by the hif_chip_wake API.
Refer to Section 15 “Host Interface Protocol” for more information.
ATWINC15x0
ATWINC15x0 Configuration
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 18
AP. Some APs might drop buffered data after Listen Interval elapses if the data is not retrieved by the
station.
The WINC driver allows the host MCU application to configure beacon monitoring parameters as follows:
• Configure DTIM monitoring – that is to enable or disable reception of broadcast/multicast data
using the following API:
– m2m_wifi_set_sleep_mode(desired_mode, 1) to receive broadcast data
– m2m_wifi_set_sleep_mode(desired_mode, 0) to ignore broadcast data
• Configure the listen interval – using the m2m_wifi_set_lsn_int API
Note: Listen interval value provided to the m2m_wifi_set_lsn_int API is expressed in the unit of
beacon period.
ATWINC15x0
ATWINC15x0 Configuration
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 19
5. Wi-Fi Station Mode
This chapter provides information about the WINC Wi-Fi Station (STA) mode as described in Wi-Fi
Station Mode. The STA mode involves a scan operation; association to an AP using parameters (SSID
and credentials) provided by the host MCU or using AP parameters stored in the WINC nonvolatile
storage (default connection). The chapter also provides information about supported security modes
along with code examples.
5.1 Scan Configuration Parameters
5.1.1 Scan Region
The number of RF channels supported varies by geographical region. For example, 13 channels are
supported in Asia while 11 channels are supported in North America. By default, the WINC initial region
configuration is equal to 14 channels, but this can be changed by setting the scan region using the
m2m_wifi_set_scan_region API. The scan region can be selected from the enum
tenuM2mScanRegion.
5.1.2 Scan Options
During Wi-Fi scan operation, the WINC sends probe request Wi-Fi frames and waits for the scan wait
time to receive probe response frames in the current Wi-Fi channel. After the scan wait time, the WINC
switches to the next channel. Increasing the scan wait time increases the possibility to detect more
number of access points during scan operation but this leads to more power consumption and overall
scan duration. The WINC firmware default scan wait time is optimized to provide the tradeoff between the
power consumption and scan accuracy. The WINC firmware provides flexible configuration options to
allow the host MCU application to set the scan time. For more details, refer to the
m2m_wifi_set_scan_options API.
5.2 Wi-Fi Scan
A Wi-Fi scan operation can be initiated by calling the m2m_wifi_request_scan API. The scan can be
performed on all 2.4GHz Wi-Fi channels or on a specific requested channel.
The scan response time depends on the scan options which can be set by calling
m2m_wifi_set_scan_options(tstrM2MScanOption* ptstrM2MScanOption). For instance, if
the host MCU application requests to scan all channels, the scan time is equal to NoOfChannels (13) *
ptstrM2MScanOption->u8NumOfSlot * ptstrM2MScanOption->u8SlotTime.
The scan operation is illustrated in the following figure.
ATWINC15x0
Wi-Fi Station Mode
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 20
Figure 5-1. Wi-Fi Scan Operation
5.3 Wi-Fi Security
The following types of security are supported in the WINC Wi-Fi STA mode.
• OPEN
• WEP (Wired Equivalent Protocol)
• WPA/WPA2 (Wi-Fi Protected Access - Personal Security mode that is Passphrase)
• 802.1X (WPA/WPA2-Enterprise security)
For 802.1X Enterprise Security, the following authentication methods are supported from ATWINC1500
firmware version 19.6.1.
• EAP-TLS
• EAP-PEAPv0/TLS
• EAP-PEAPv1/TLS
• EAP-TTLSv0/MSCHAPv2
• EAP-PEAPv0/MSCHAPv2
ATWINC15x0
Wi-Fi Station Mode
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 21
• EAP-PEAPv1/MSCHAPv2
The m2m_wifi_connect is deprecated from v19.6.1 and above firmware. The legacy APIs
m2m_wifi_connect and m2m_wifi_connect_sc are available as wrappers for the new APIs.
Functionally its behavior is unchanged from previously released drivers.
The recommended API for various security type such as OPEN, WEP, WPA/WPA2, 802.1X are
summarized in the Table 5-1.
All new connect APIs, enable connection to a particular access point by specifying its BSSID and the
SSID. To restrict connection to a specific access point, the application can specify the BSSID (in addition
to SSID) in the argument tstrNetworkId -> pu8Bssid.
The application can instruct the WINC whether to store the credentials or not to store in Flash and also
whether the saved credentials must be encrypted or not. This is done by configuring the enum
tenuCredStoreOption.
For enterprise security, the application can configure WINC to send actual identity or use anonymous
identity during phase 1 authentication. This can be done by setting or clearing bUnencryptedUserName
in argument tstrAuth1xTls or tstrAuth1xMschap2.
For more details on usage of API m2m_wifi_connect_1x_tls, refer ASF (v3.42 or above) example
"WINC1500 Connecting a EAP-TLS / PEAPv0 with TLS / PEAPv1 with TLS Secured AP Example".
For more details on usage of API m2m_wifi_connect_1x_mschap2, refer ASF (v3.42 or above)
example "WINC1500 Connecting a EAP-TTLSv0 with MSCHAPv2 / EAP-PEAPv0 with MSCHAPv2 /
EAP-PEAPv1 with MSCHAPv2 Secured AP Example".
5.4 On Demand Wi-Fi Connection
The host MCU application may establish a Wi-Fi connection on demand when all the required connection
parameters (SSID, security credentials, and so on.) are known to the application. To start a Wi-Fi
connection on demand, the application calls the following APIs based on the security type.
Table 5-1. List of APIs based on Security Type
Security Type API
Open m2m_wifi_connect_open
WEP m2m_wifi_connect_wep
WPA/WPA2 m2m_wifi_connect_psk
802.1x with MSCHAPv2 m2m_wifi_connect_1x_mschap2
802.1x with TLS m2m_wifi_connect_1x_tls
Alternatively, the application can call the API m2m_wifi_connect to connect with an access point which
supports Open, WEP, WPA/WPA2 and 802.1x with MSCHAPv2. m2m_wifi_connect is deprecated in
v19.6.1 and is kept for legacy purpose.
Note: Using the API in the Table 5-1 implies that the host MCU application has prior knowledge of the
connection parameters. For instance, connection parameters can be stored on nonvolatile storage
attached to the host MCU.
The Wi-Fi on demand connection operation is described in the following figure.
ATWINC15x0
Wi-Fi Station Mode
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 22
Figure 5-2. On-demand Wi-Fi Connection
5.4.1 Example Code
5.4.1.1 Example Code for Connecting to Enterprise Network (PEAP and TTLSv0) with MSCHAPv2 as Phase2
Authentication
#define MAIN_WLAN_SSID "WINC1500_ENTERPRISE" /**< Destination SSID */
#define MAIN_WLAN_802_1X_USR_NAME "DEMO_USER" /**< RADIUS user account name */
#define MAIN_WLAN_802_1X_PWD "DemoPassword" /**< RADIUS user account password */
int main(void)
{
int8_t ret;
tstrWifiInitParam param;
tstrNetworkId networkId;
tstrAuth1xMschap2 mschapv2_credential;
/* Initialize the board. */
system_init();
/* Initialize the UART console. */
configure_console();
printf(STRING_HEADER);
/* Initialize the BSP. */
nm_bsp_init();
/* Initialize Wi-Fi parameters structure. */
memset((uint8_t *)¶m, 0, sizeof(tstrWifiInitParam));
/* Initialize Wi-Fi driver with data and status callbacks. */
param.pfAppWifiCb = wifi_cb;
ret = m2m_wifi_init(¶m);
if (M2M_SUCCESS != ret) {
printf("main: m2m_wifi_init call error!(%d)\r\n", ret);
while (1) {
}
}
ATWINC15x0
Wi-Fi Station Mode
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 23
networkId.pu8Bssid = NULL;
networkId.pu8Ssid = (uint8 *)MAIN_WLAN_SSID;
networkId.u8SsidLen = strlen(MAIN_WLAN_SSID);
networkId.enuChannel = M2M_WIFI_CH_ALL;
mschapv2_credential.pu8Domain = NULL;
//mschapv2_credential.u16DomainLen = strlen(mschapv2_credential.pu8Domain);
mschapv2_credential.pu8UserName = (uint8 *)MAIN_WLAN_802_1X_USR_NAME;
mschapv2_credential.pu8Password = (uint8 *)MAIN_WLAN_802_1X_PWD;
mschapv2_credential.u16UserNameLen = strlen(MAIN_WLAN_802_1X_USR_NAME);
mschapv2_credential.u16PasswordLen = strlen(MAIN_WLAN_802_1X_PWD);
mschapv2_credential.bUnencryptedUserName = false;
mschapv2_credential.bPrependDomain = true;
printf("Connecting to %s\r\n\tUsername:%s\r\n", MAIN_WLAN_SSID,
MAIN_WLAN_802_1X_USR_NAME);
m2m_wifi_connect_1x_mschap2( WIFI_CRED_SAVE_ENCRYPTED, &networkId, &mschapv2_credential);
/* Infinite loop to handle a event from the WINC1500. */
while (1) {
while (m2m_wifi_handle_events(NULL) != M2M_SUCCESS) {
}
}
return 0;
}
5.4.1.2 Example Code for Connecting to PEAP Enterprise Network with TLS as Phase2 Authentication and
EAP- TLS
/** security information for Wi-Fi connection */
#define MAIN_WLAN_SSID "WINC1500_ENTERPRISE" /**< Destination SSID */
#define MAIN_WLAN_802_1X_USR_NAME "DEMO_USER" /**< RADIUS user account name */
const uint8_t modulus[] = { /** private key modulus extracted from key file */ };
const uint8_t exponent[] = { /** private key exponent coefficient extracted from key file
*/ };
const uint8_t certificate[] = { /** certificate coefficient corresponding to Private Key
*/ };
int main(void)
{
int8_t ret;
tstrWifiInitParam param;
tstrNetworkId networkId;
tstrAuth1xTls tls_credential;
/* Initialize the board. */
system_init();
/* Initialize the UART console. */
configure_console();
printf(STRING_HEADER);
/* Initialize the BSP. */
nm_bsp_init();
/* Initialize Wi-Fi parameters structure. */
memset((uint8_t *)¶m, 0, sizeof(tstrWifiInitParam));
/* Initialize Wi-Fi driver with data and status callbacks. */
param.pfAppWifiCb = wifi_cb;
ret = m2m_wifi_init(¶m);
if (M2M_SUCCESS != ret) {
printf("main: m2m_wifi_init call error!(%d)\r\n", ret);
while (1) {
}
}
printf("Username:%s\r\n",MAIN_WLAN_802_1X_USR_NAME);
/* Connect to the enterprise network. */
networkId.pu8Bssid = NULL;
networkId.pu8Ssid = (uint8 *)MAIN_WLAN_SSID;
networkId.u8SsidLen = strlen(MAIN_WLAN_SSID);
networkId.enuChannel = M2M_WIFI_CH_ALL;
ATWINC15x0
Wi-Fi Station Mode
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 24
tls_credential.pu8Domain = NULL;
tls_credential.pu8UserName = (uint8 *)MAIN_WLAN_802_1X_USR_NAME;
tls_credential.pu8PrivateKey_Mod = (uint8 *)modulus;
tls_credential.pu8PrivateKey_Exp = (uint8 *)exponent;
tls_credential.pu8Certificate = (uint8 *)certificate;
tls_credential.u16UserNameLen = strlen(MAIN_WLAN_802_1X_USR_NAME);
tls_credential.u16PrivateKeyLen = sizeof(modulus);
tls_credential.u16CertificateLen = sizeof(certificate);
tls_credential.bUnencryptedUserName = true;
tls_credential.bPrependDomain = true;
printf("Connecting to %s...\r\n\t\tUsername:%s\r
\n",networkId.pu8Ssid,tls_credential.pu8UserName);
m2m_wifi_connect_1x_tls(WIFI_CRED_SAVE_ENCRYPTED, &networkId, &tls_credential);
/* Infinite loop to handle a event from the WINC1500. */
while (1) {
while (m2m_wifi_handle_events(NULL) != M2M_SUCCESS) {
}
}
return 0;
}
5.5 Default Connection
The host MCU application establishes the default connection based on the connection profile stored in
the WINC serial Flash using the m2m_wifi_default_connect API. This API does not require AP
information to establish the connection.
Note: The connection profile information is automatically stored in the WINC Flash when on-demand WiFi
connection API is called (see Table 5-1). Saving of this connection profile is dependent on the enum
tenuCredStoreOption.
The credentials such as passphrase of the AP or Enterprise certificate and other parameters like SSID, IP
address, BSSID are encrypted using AES128-CBC before they are written into the serial Flash. This
makes it difficult for an attacker to retrieve the sensitive information even if an attacker has physical
access to the device. If there is no cached profile or if a connection cannot be established with any of the
cached profile, an event of type M2M_WIFI_RESP_DEFAULT_CONNECT is delivered to the host driver
indicating failure.
Upon successful default connection, the host application can read the current Wi-Fi connection status by
calling m2m_wifi_get_connection_info API. The m2m_wifi_get_connection_info is an
asynchronous API. The actual connection information is provided in the asynchronous event
M2M_WIFI_RESP_CONN_INFO in Wi-Fi callback. The callback parameter of type tstrM2MConnInfo
provides information about AP SSID, RSSI (AP received power level), security type, IP address obtained
by DHCP.
Note: A connection profile is cached in the serial Flash if and only if the connection is successfully
established with the target AP.
The Wi-Fi default connection operation is shown in the following figure.
ATWINC15x0
Wi-Fi Station Mode
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 25
Figure 5-3. Wi-Fi Default Connection
5.6 Encrypted Credential Storage
In ATWINC15x0 firmware v19.6.1 and above, the credentials such as passphrase of the AP or Enterprise
certificate and other parameters like SSID, IP address, BSSID are encrypted using AES128-CBC before
they are written into the serial Flash. This makes it difficult for an attacker to retrieve the sensitive
information inspite of having physical access to the device. The encryption provided by this feature must
not be considered secure. The encryption is only intended to prevent credentials being revealed in plain
text by an opportunistic read of ATWINC15x0 Flash. Therefore, other security practices must be followed
where possible, such as changing passwords regularly and deleting credentials when they are no longer
required.
When requesting for a connection to a network, the application can specify how the connection
credentials must be stored in ATWINC15x0 Flash. The options are as follows:
• Do not store credentials
• Store credentials unencrypted
• Store credentials encrypted
The credentials consist of:
• SSID
• BSSID (if provided)
• WEP key (for WEP connection)
• Passphrase and PSK (for WPA/WPA2 PSK connection)
• Domain, User name and Password (for WPA/WPA2 1x MSCHAPv2 connection)
• Domain, User name, Certificate and Private Key (for WPA/WPA2 1x TLS connection)
ATWINC15x0
Wi-Fi Station Mode
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 26
The credentials are stored in ATWINC15x0 Flash when connection succeeds, and only one set of
credentials is stored at a time; if new credentials need to be stored then the old credentials are removed
(overwritten with 0’s).
If credentials are stored in ATWINC15x0 Flash, then the application can request subsequent connections
without providing the credentials again, using m2m_wifi_default_connect.
If roaming is enabled, roaming can take place regardless of whether the credentials are stored in
ATWINC15x0 Flash. (They are stored in data memory for the duration of a connection.) The application
can delete credentials from ATWINC15x0 Flash using m2m_wifi_delete_sc.
Note: Version 19.6.1 firmware implements a new format for the ATWINC15x0 Flash store for connection
parameters. The effects of this are:
• During a firmware upgrade to v19.6.1, previously stored credentials are reformatted. After the first
successful connection to an access point, these stored credentials are encrypted.
• During a firmware upgrade to v19.6.1, previously stored IP address and Wi-Fi channel are deleted.
• After a firmware downgrade from v19.6.1 to previous firmware, credentials stored by v19.6.1
firmware are not readable by the previous firmware. The operation of the previous firmware is
otherwise unaffected.
5.7 Simple Roaming
Simple Roaming is a custom feature which is supported by WINC firmware version 19.6.1 and above.
With Simple Roaming feature enabled, the ATWINC1500 configured as station can move around in an
ESS area with multiple access point. The WINC automatically switches to another AP which has the
same SSID, authentication procedure and credentials with better signal strength. Roaming enables a
station to change its AP while remaining connected to the network. The following figure explains the
simple roaming feature.
ATWINC15x0
Wi-Fi Station Mode
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 27
Figure 5-4. Simple Roaming
STA AP in Range
New AP
Old AP
(1) Probe Request (Ch 1)
(2) Probe Response (Ch 1)
(1) Probe Request (Ch n)
(2) Probe Response (Ch n)
(5) Authentication Request
(6) Authentication Reply
(7) Reassociation Request
(12) Reassociation Reply
(8) Send Security Block
(9) Ack Security Block
(10) Move Notify
(11) Move Response
In v19.6.1, the WINC roam occurs on link-loss detection with the existing AP, which is determined by
tracking beacons and sending NULL frame keep-alive packets. ISO/OSI Layer 2 roaming occurs when
the WINC roams from one AP to another AP, both of which are inside the same IP subnet. Layer 3
roaming occurs when the WINC roams from one AP to another AP which are in different subnets,
whereby the WINC attempts to obtain a new IP address within the new subnet via DHCP. As a result of
layer 3 roaming, any existing network connections is broken, and the upper layer protocols handle this IP
address change if a continuous connection is required in layers 4 and above.
Roaming algorithm is internal to WINC firmware. The Host MCU can enable or disable the roaming
functionality using the API's m2m_wifi_enable_roaming and m2m_wifi_disable_roaming. The
roaming must be called after the WINC initialization.
When roaming is enabled, if the WINC successfully roamed to a new AP, then the
M2M_WIFI_RESP_CON_STATE_CHANGED message with state as M2M_WIFI_ROAMED is sent to host
MCU. If the WINC is not able to find a new AP, then M2M_WIFI_RESP_CON_STATE_CHANGED message
with state as M2M_WIFI_DISCONNECTED is sent to the host MCU.
The API call m2m_wifi_enable_roaming() sets the ATWINC15x0 to detect link-loss, and when link
loss is detected with the existing access point, the following roaming steps are performed.
• A precautionary de-authentication frame is sent to the old AP.
• Scanning is performed to determine if there is an AP within the same ESS as the previous AP in
the vicinity.
• If an AP is found, authentication and re-association messages are exchanged with the new AP,
followed by a normal 4-way security handshake in the case of WPA/WPA2, or an EAPOL exchange
in the case of 802.1x Enterprise security.
ATWINC15x0
Wi-Fi Station Mode
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 28
• A DHCP request is sent to the new AP to attempt to retain the same IP address. A notification
event is sent to the host MCU of type M2M_WIFI_RESP_CON_STATE_CHANGE with the state of
M2M_WIFI_ROAMED. Additionally, an M2M_WIFI_REQ_DHCP_CONF event conveying either the
same or a new IP address is sent to the host MCU.
• If there is any problem with the connection, or DHCP fails, then a de-authentication message is
sent to the AP, and an M2M_WIFI_RESP_CON_STATE_CHANGED event is sent to the host MCU
with the state set as M2M_WIFI_DISCONNECTED.
The bEnableDhcp parameter enables control of whether or not a DHCP request is sent after roaming to
a new AP. The API call m2m_wifi_disable_roaming is used to disable roaming.
5.8 Multiple Gain Table
There are restrictions regarding the maximum transmit power of a wireless device according to the
regulatory agencies of the region. For Wi-Fi devices, the maximum transmit power is limited according the
regulation of the region in which the Wi-Fi device is used. The gain table can be used to configure the
transmission power in WINC. The digital gain (DG) that are used for different channels and different data
rates are stored in ATWINC15x0 Flash as a table called Gain table. In ATWINC15x0, the Power Amplifier
(PA) and Pre-power Amplifier (PPA) values are configured in the firmware directly.
The following figure shows the format of the gain table.
Figure 5-5. Gain Table
1 2 3 4 5 6 7 8 9 10 11 12 13 14
1 -10 -9 -9 -9 -9 -9 -9 -9 -9 -9 -10 -9 -9 -9
2 -10 -9 -9 -9 -9 -9 -9 -9 -9 -9 -10 -9 -9 -9
5.5 -10 -9 -9 -9 -9 -9 -9 -9 -9 -9 -10 -9 -9 -9
11 -10 -9 -9 -9 -9 -9 -9 -9 -9 -9 -10 -9 -9 -9
6 -11 -7 -7 -7 -7 -7 -7 -7 -7 -7 -9 -7 -7 -7
9 -11 -7 -7 -7 -7 -7 -7 -7 -7 -7 -9 -7 -7 -7
12 -11 -7 -7 -7 -7 -7 -7 -7 -7 -7 -9 -7 -7 -7
18 -11 -7 -7 -7 -7 -7 -7 -7 -7 -7 -9 -7 -7 -7
24 -11 -7 -7 -7 -7 -7 -7 -7 -7 -7 -9 -7 -7 -7
36 -11 -7 -7 -7 -7 -7 -7 -7 -7 -7 -9 -7 -7 -7
48 -11 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8
54 -11 -9 -9 -9 -8 -8 -8 -8 -8 -8 -9 -8 -8 -8 mcs0 -12 -7 -7 -7 -7 -7 -7 -7 -7 -7 -10 -7 -7 -7 mcs1 -12 -7 -7 -7 -7 -7 -7 -7 -7 -7 -10 -7 -7 -7 mcs2 -12 -7 -7 -7 -7 -7 -7 -7 -7 -7 -10 -7 -7 -7 mcs3 -12 -7 -7 -7 -7 -7 -7 -7 -7 -7 -10 -7 -7 -7 mcs4 -12 -7 -7 -7 -7 -7 -7 -7 -7 -7 -10 -7 -7 -7 mcs5 -12 -8 -8 -7 -7 -7 -7 -7 -7 -7 -10 -7 -7 -7 mcs6 -12 -9 -8 -8 -8 -8 -8 -8 -8 -8 -10 -8 -8 -8 mcs7 -12 -10 -9 -9 -9 -9 -9 -9 -9 -9 -10 -9 -9 -9
1e9c 0
1edc 0
Data Rates
Channels
Digital
Gain
Specific
Configuration
The Gain tables are provided as part of firmware update package in form of .csv file available at src/
firmware/Tools/gain_builder/gain_sheets folder. The gain values are downloaded as part of
complete download process. For more details, see "WINC Devices – Integrated Serial Flash Memory
Download Procedure" document.
Prior to v19.6.1 only one gain table was supported in ATWINC15x0, with which the WINC can only
operate in one regulatory region without requiring different Flash content.
The ATWINC15x0 firmware version 19.6.1 or above supports multiple gain table and the Flash can store
up to four gain tables. The table can be selected by the Host MCU using the API
m2m_wifi_set_gain_table_idx. If the ATWINC15x0 has to operate in multiple region with maximum
ATWINC15x0
Wi-Fi Station Mode
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 29
transmit power allowed in that region, multiple gain table feature can be used to select gain table (by Host
MCU) based on the region in which the ATWINC15x0 is operated.
5.8.1 Writing the Gain Table to ATWINC15x0
The gain builder application uses multiple .csv files (up to a maximum of 4) and perform the necessary
maths operations on the gain table to calculate the gain values and write them to the Flash:
gain_builder [-table
] [-index ][-no_wait] [-port]
Note: The img_path* parameters specify the separate tables, and the index parameter specifies the
default table to use on power up.
5.8.2 Selecting a Specific Gain Table
Setting the specific gain table index is achieved using API m2m_wifi_set_gain_table_idx. The
m2m_wifi_set_gain_table_idx must be called after the initialization and before any connection
request. The corresponding gain tables must be available in the Flash.
Note: The ATWINC15x0 firmware release v19.6.1 contains only one gain table that can be used in all
the region.
5.9 Host File Download
The Host File Download is a feature supported in the ATWINC15x0 firmware version 19.6.1 and above.
This feature is supported only in the ATWINC1510 device which has 8 Mb Flash. The ATWINC1500 only
has 4 Mbit of Flash memory and therefore this feature is not supported for the ATWINC1500. With Host
file download feature, the Host MCU can instruct the ATWINC1510 to download a file and save it in the
ATWINC1510 Flash. The ATWINC1510 can download the file from a HTTP or a HTTPS web server only.
The maximum size of file that can be stored in the ATWINC1510 is 508 KB. This feature is ideal for
updating the firmware of host MCU. However, the feature is not limited to MCU OTA only.
When performing MCU OTA updates, there is no enforced file format, so the Application Developer can
choose a strategy to perform integrity check validation on the received file. The WINC does not perform
any integrity check on the downloaded file and therefore, it is recommended that the Application do it
instead.
The feature is designed for single file support and allows for a maximum size of 508 KB. The driver
protects against invalid access to the file stored in the WINC’s Flash by using file handlers to identify each
file. If a new download starts or if the file is erased, access to the file partition is denied. Also, the
application can request an explicit erase to delete the file from the ATWINC’s Flash, destroying any
potentially confidential data.
The API m2m_ota_host_file_get is used to download file from remote location and store it in
ATWINC1500 Flash. The m2m_ota_host_file_get can be used to download only one file at a time.
When the get file API is called again, the previously stored file is erased and new file download is
initiated.
To retrieve the downloaded file from the ATWINC1510 Flash, m2m_ota_host_file_read_spi or
m2m_ota_host_file_read_hif API can be used by the host MCU. The completion of file download is
notified through the callback registered in m2m_ota_host_file_get API. The user can use the
m2m_ota_host_file_read_spi or m2m_ota_host_file_read_hif API by passing required
arguments to initiate the file read from the WINC Flash.
ATWINC15x0
Wi-Fi Station Mode
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 30
5.9.1 Overview
Whenever an application needs information which is stored in a file somewhere in a remote location, the
application can use the Host File Download feature to retrieve the file from the remote location and
temporarily store it in the WINC’s Flash. When a download is successfully completed, a file handler is
generated and stored in NVM in the WINC, therefore it is valid even after a WINC reset. After a handler is
generated, access to the file is possible via the provided APIs and reading of a file is possible via two
mechanisms, HIF and SPI. In either case, the read operation requires the file handler of the file which the
application is trying to access, if the handler being requested and the handler internally stored match,
then the access is granted. The same procedure is valid for erasing the file. The use of a file handler
avoids access to invalid data, for example when trying to concurrently access the file. The following figure
depicts the steps which the WINC follows when performing a Host File Download.
Figure 5-6. Host File Download Operation within the WINC
OTA File Get
Check Available Space
Start Download
OTA Get
Successful OTA Get Failed
Notify Host of the Result
OK
Failed
Completed Failed
The download starts only if the space available in Flash is enough to store the file which is requested to
be downloaded. If Host File Download is requested in the ATWINC1500 (4 Mb Flash), the download fails
since there is no Host File partition in Flash and therefore no space to store the file.
The “Start Download” step causes any previously available valid file handler to be invalidated. When
“OTA Get Successful” message is received, a new file handler is generated along with the status and the
total size of the downloaded file, they are included in the Download completion notification sent to the
host.
5.9.2 OTA Initialization
To use the Host File Download feature, the WINC and the OTA driver must be initialized. The following is
the procedure for OTA initialization:
1. m2m_wifi_init or m2m_wifi_reinit – this API is required to initialize the WINC and to set up
the callback for the HIF communication. After this step, the WINC can be configured to connect to a
network and download a file. For more details to understand when to use each of these two
options, see the API documentation.
ATWINC15x0
Wi-Fi Station Mode
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 31
2. m2m_ota_init – this API registers the OTA callback, which is required to execute any callbacks
configured through the Host File Download APIs and to notify the Application of file download
status.
5.9.3 Using Host File Download for MCU OTA
Host File Download allows an application to download a file from a remote location. The link to the file
can be through a secure connection and once the file is downloaded, it is stored in the WINC's Flash and
the Application is notified about it. The files to download can be of any kind and are not limited to MCU
binaries, making this feature both flexible and powerful. One example would be the download of text files,
which can hold, for instance, a file checksum, which can later be used by the Application to verify the
integrity of the downloaded binary. An Host MCU OTA requires the following steps:
• Provide an http/https link to the file to tell WINC to download the file from a specific remote location,
which can be done using API m2m_ota_host_file_get.
• Read the image from the WINC using spi_flash_read. Since there is a limitation currently in
which the bootloader would also need to perform m2m_wifi_init, m2m_ota_init and only then
it should do m2m_ota_host_file_read_spi to read the image from WINC.
m2m_ota_host_file_read_hif and m2m_ota_host_file_read_spi are not used in the
ASF Example for MCU OTA to keep the driver footprint small while working around the limitation
described above. However, this limitation is only present when the Application needs to be reset, or
in this case switch to a bootloader, the WINC driver will lose track of the file handler and will have to
load it again through the initialization process. If no reset or shutdown need to be performed and if
no different Application needs to be loaded after downloading the file, these two APIs can be used.
Figure 5-7. Example Host File Download for MCU OTA
File Get CB
Application WINC
Bootloader WINC
File Integrity Check
Switch to Bootloader
Switch to Application
File Handler inval
File Handler gen
MCU & WINC Reset
m2m_wifi_init()
m2m_ota_init()
**Connect to Wi-Fi network**
m2m_ota_host_file_get()
HIF Msg M2M_OTA_RESP_HOST_FILE_DOWNLOAD
m2m_wifi_download_mode()
spi_flash_read()
ATWINC15x0
Wi-Fi Station Mode
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 32
Other steps that must be considered by the Application Developer are:
• It is recommended to verify the integrity of the image using a checksum calculation and match it
against a previously known checksum. The user can design the validation mechanism since no
predefined file format is enforced for MCU OTA.
• There is an option to erase the file from Flash. Although this is not mandatory before requesting a
new download, it can be useful for security purposes, ensuring that sensitive data is unavailable
after its use.
Note: The WINC does not perform any integrity check of any of the downloaded files via Host File
Download and that must be checked by the application.
5.9.4 API Description
For a more detailed description of the APIs, refer to WINC1500_SW_API.chm.
5.9.4.1 OTA File Get
NMI_API sint8 m2m_ota_host_file_get
(
unsigned char *pcDownloadUrl,
tpfFileGetCb pfHFDGetCb
);
This API is used to get a file which links to the file stored remotely. The link is passed to the WINC to
establish a TCP connection to retrieve the file from that location. It is also possible to use a server
configured for TLS.
A callback must also be provided so that it is executed when the File Get operation completes. The status
of the File Get is passed onto this callback and if the status is successful, the file handler generated by
the WINC and the total size of the downloaded file is passed correctly to the callback.
5.9.4.2 File Get Callback
typedef void (*tpfFileGetCb)
(
uint8 u8Status,
uint8 u8Handler,
uint32 u32Size
);
The callback for the File Get receives three arguments; status of the File Get request, file handler ID and
the total size of the file. If the status is OTA_STATUS_SUCCESS, then the file handler and size can be
used, otherwise its values are not populated. From the Application’s point of view, they must not be
considered valid.
The file handler is auto-generated in the WINC and it identifies the file. Only when a download finishes
successfully, the corresponding file handler is generated. The handler is required to both read from the
file or erase the file. Similarly, if the download is aborted or interrupted, then the handler is not generated,
instead the handler will have the value of HFD_INVALID_HANDLER, which blocks any further operation
on the Flash through the APIs.
When the file download completes successfully, the total size of the download file is passed to the
callback to notify the application. Using which the application tracks the total size of the downloaded data
and the amount of data read.
5.9.4.3 OTA File Read HIF
NMI_API sint8 m2m_ota_host_file_read_hif
(
uint8 u8Handler,
uint32 u32Offset,
uint32 u32Size,
ATWINC15x0
Wi-Fi Station Mode
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 33
tpfFileReadCb pfHFDReadCb
);
When the download completes, the file is stored in the WINC’s Flash. This API can be used to read the
file from the WINC using HIF messages. It is mandatory to have a valid handler, not having one could
mean that the file has been invalidated and therefore it must be unavailable for any operation. This
protects read against invalid or corrupted data.
The offset marks the position in bytes of Flash to read from, counting from the beginning of the file.
Therefore, an offset of zero is translated as reading from the beginning of the file. Size specifies the
amount of bytes to read, starting at the offset defined. The last argument is the callback to be executed
when the read is complete.
Advantages (vs SPI read)
• While reading a file using HIF messages, the host can continue operation, being notified by an
interrupt from the WINC when data read is complete.
• Does not require the WINC to be reset after the read is complete.
Disadvantages (vs SPI read)
• File reads via HIF are slightly slower than reads via SPI.
5.9.4.4 File Read HIF Callback
typedef void (*tpfFileReadCb)
(
uint8 u8Status,
void *pBuff,
uint32 u32Size
);
The callback is only executed after a file read via HIF messages and it receives three arguments.
• The first argument is the status of the read, if the read is unsuccessful, then the other arguments
will have irrelevant values.
• The second argument is a pointer to the buffer of data read.
• The third argument is size, which indicates the amount of data read and therefore contained in the
buffer (maximum 128 bytes).
Specifying large amounts of data to be read via the HIF may exceed the buffer maximum size (128
bytes), therefore it is recommended to use u32Size to offset a second read from within this callback.
This requires the application to track the total size of the file and the amount of bytes read, requesting the
reading of each section at a time until the end of the file is reached.
5.9.4.5 OTA File Read SPI
NMI_API sint8 m2m_ota_host_file_read_spi
(
uint8 u8Handler,
uint8 *pu8Buff,
uint32 u32Offset,
uint32 u32Size
);
The file read via SPI is similar to the read via HIF. The use of a callback is not considered, because to
access the WINC’s Flash via SPI, the WINC must be set into a certain mode to allow for safe read/write
of its Flash. Therefore, it is typical to use a loop to read all the data necessary while the WINC is in that
state and then restart the WINC.
To use this API, the application must call m2m_wifi_download_mode to make the WINC safe for read/
write Flash access and once the read is completed, the WINC must be reinitialized (m2m_wifi_reinit,
ATWINC15x0
Wi-Fi Station Mode
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 34
m2m_ota_init) and to connect to the network again if the Application based on the request. pu8Buff is
a pointer to a buffer provided by the Application and to where the data will be read to.
Advantages (vs HIF read)
• SPI read is faster than HIF Read.
Disadvantages (vs HIF read)
• Requires the WINC to set into a special mode and restart later.
• Generally blocks as the read are done within a loop to minimize WINC reset.
5.9.4.6 OTA File Erase API
NMI_API sint8 m2m_ota_host_file_erase
(
uint8 u8Handler,
tpfFileEraseCb pfHFDEraseCb
);
The File Erase API requires the following two arguments:
• The first argument is a handler of the file to erase, to ensure that it is valid to perform a Flash erase.
• The second argument is a callback which executes when the erase is complete.
Having a callback to tell the Application when the erase has been completed is useful to act as a trigger
for a subsequent operation (example, download a second file).
Note: The file erase performs an erase of the entire host file partition and any file handler is destroyed
regardless of the end result of the erase operation in the WINC. Since the data in the Flash is partially or
completely destroyed, the handlers are invalidated when the process starts for safety.
5.9.4.7 File Erase Callback
typedef void (*tpfFileEraseCb)
(
uint8 u8Status
);
The callback for a File Erase receives the erase status of the operation. A status of
OTA_STATUS_SUCCESS ensures that the data has been completely erased, any other result does not
ensure that the data is still valid, but also do not ensure that the data has been completely erased.
5.9.4.8 OTA Abort API
NMI_API sint8 m2m_ota_abort
(
void
);
If a Host File Download has been started and the Application decides to cancel the download, it can issue
a call to this API to do so. This does not require any input parameter.
Note: This API is shared with the WINC OTA and if issued when a WINC OTA is in progress, the WINC
OTA is canceled.
5.9.5 Limitations
• Out of 512 KB of Flash in the ATWINC1510, the first sector (of size 4 KB) is used by the WINC for
storing the file information for host file download feature. Which means that a total of 508 KB size of
Flash can be used by application to store the host file.
• The feature is only supported in ATWINC1510 since the ATWINC1500 only has 4 Mbit of Flash
memory, which means there is no space to store a file.
ATWINC15x0
Wi-Fi Station Mode
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 35
• There is no file system and only one file is stored at a time. When the get file is called again, the
previously stored file is erased and a new file download is initiated.
• The WINC OTA firmware download and the Host OTA file download cannot run concurrently.
• The WINC interprets 404 Not Found error when application attempts to download a broken or
dead link and provides the OTA_STATUS_SERVER_ERROR error status. The WINC does not
interpret any other message for broken link. The WINC downloads the error message into SPI
Flash and indicates Host as file download. It is the application’s responsibility to check if the file is
valid.
5.9.6 Built in Automated Test Equipment (ATE) Mechanism
A factory flashed ATWINC15x0 module running the v19.6.1 firmware has a special ATE firmware in the
Flash space reserved for OTA transfers (which is overwritten by the first OTA update).
A host API can be called during WINC initialization that causes the device to boot into this special
firmware (m2m_ate_init). The API to control the ATE functions provided by this firmware is detailed in
\ASF\common\components\wifi\winc1500\driver\include\m2m_ate_mode.h.
The following is the sample code.
int main(void)
{
/* Initialize the board. */
system_init();
/* Initialize the UART console. */
configure_console();
printf(STRING_HEADER);
/* Initialize the BSP. */
nm_bsp_init();
/*Check if initialization of ATE firmware is succeeded or not*/
if(M2M_SUCCESS == m2m_ate_init())
{
/*Run TX test case if defined*/
#if (M2M_ATE_RUN_TX_TEST_CASE == ENABLE)
start_tx_test(M2M_ATE_TX_RATE_1_Mbps_INDEX);
#endif
/*Run RX test case if defined*/
#if (M2M_ATE_RUN_RX_TEST_CASE == ENABLE)
start_rx_test();
#endif
/*De-Initialization of ATE firmware test mode*/
m2m_ate_deinit();
}
else
{
M2M_ERR("Failed to initialize ATE firmware.\r\n");
while(1);
}
#if ((M2M_ATE_RUN_RX_TEST_CASE == ENABLE) && (M2M_ATE_RUN_TX_TEST_CASE == ENABLE))
M2M_INFO("Test cases have been finished.\r\n");
#else
M2M_INFO("Test case has been finished.\r\n");
#endif
while(1);
}
#if (M2M_ATE_RUN_TX_TEST_CASE == ENABLE)
static void start_tx_test(uint8_t tx_rate)
{
tstrM2mAteTx tx_struct;
ATWINC15x0
Wi-Fi Station Mode
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 36
/*Initialize parameter structure*/
m2m_memset((uint8 *)&tx_struct, 0 , sizeof(tx_struct));
/*Set TX Configuration parameters,
*refer to tstrM2mAteTx for more information about parameters*/
tx_struct.channel_num = M2M_ATE_CHANNEL_11;
tx_struct.data_rate = m2m_ate_get_tx_rate(tx_rate);
tx_struct.dpd_ctrl = M2M_ATE_TX_DPD_DYNAMIC;
tx_struct.duty_cycle = M2M_ATE_TX_DUTY_1;
tx_struct.frame_len = 1024;
tx_struct.num_frames = 0;
tx_struct.phy_burst_tx = M2M_ATE_TX_SRC_MAC;
tx_struct.tx_gain_sel = M2M_ATE_TX_GAIN_DYNAMIC;
tx_struct.use_pmu = M2M_ATE_PMU_DISBLE;
tx_struct.cw_tx = M2M_ATE_TX_MODE_CW;
tx_struct.xo_offset_x1000 = 0;
/*Start TX Case*/
if(M2M_ATE_SUCCESS == m2m_ate_start_tx(&tx_struct))
{
uint32 u32TxTimeout = M2M_ATE_TEST_DURATION_IN_SEC;
M2M_INFO(">>Running TX Test case on CH<%02u>.\r\n", tx_struct.channel_num);
do
{
nm_bsp_sleep(1000);
printf("%02u\r", (unsigned int)u32TxTimeout);
}while(--u32TxTimeout);
if(M2M_ATE_SUCCESS == m2m_ate_stop_tx())
{
M2M_INFO("Completed TX Test successfully.\r\n");
}
}
else
{
M2M_INFO("Failed to start TX Test case.\r\n");
}
}
#endif
#if (M2M_ATE_RUN_RX_TEST_CASE == ENABLE)
static void start_rx_test(void)
{
tstrM2mAteRx rx_struct;
/*Initialize parameter structure*/
m2m_memset((uint8 *)&rx_struct, 0, sizeof(rx_struct));
/*Set RX Configuration parameters*/
rx_struct.channel_num = M2M_ATE_CHANNEL_6;
rx_struct.use_pmu = M2M_ATE_PMU_DISBLE;
rx_struct.xo_offset_x1000 = 0;
/*Start RX Case*/
if(M2M_ATE_SUCCESS == m2m_ate_start_rx(&rx_struct))
{
tstrM2mAteRxStatus rx_data;
uint32 u32RxTimeout = M2M_ATE_TEST_DURATION_IN_SEC;
M2M_INFO(">>Running RX Test case on CH<%02u>.\r\n", rx_struct.channel_num);
do
{
m2m_ate_read_rx_status(&rx_data);
M2M_INFO("Num Rx PKTs: %d, Num ERR PKTs: %d, PER: %1.3f",
(int)rx_data.num_rx_pkts, (int)rx_data.num_err_pkts,
(rx_data.num_rx_pkts>0)?((double)rx_data.num_err_pkts/
(double)rx_data.num_rx_pkts):(0));
nm_bsp_sleep(1000);
}while(--u32RxTimeout);
printf("\r\n");
if(M2M_ATE_SUCCESS == m2m_ate_stop_rx())
{
M2M_INFO("Compeleted RX Test successfully.\r\n");
}
}
ATWINC15x0
Wi-Fi Station Mode
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 37
else
{
M2M_INFO("Failed to start RX Test case.\r\n");
}
}
#endif
ATWINC15x0
Wi-Fi Station Mode
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 38
6. Socket Programming
6.1 Overview
The ATWINC15x0 socket Application Programming Interface (API) allows the host MCU application to
interact with intranet and remote internet hosts. The ATWINC15x0 socket API is based on the BSD
(Berkeley) sockets. This chapter explains the ATWINC15x0 socket programming and how it differs from
regular BSD sockets.
Note: The reader must have a basic understanding of the following topics before reading this chapter:
• BSD sockets
• TCP
• UDP
• Internet protocols
6.1.1 Socket Types
The ATWINC15x0 socket API provides two types of sockets:
• Datagram sockets (connectionless sockets) – uses the UDP protocol
• Stream sockets (connection-oriented sockets) – uses the TCP protocol
6.1.2 Socket Properties
Each ATWINC15x0 socket is identified by a unique combination of the following:
• Socket ID – a unique identifier for each socket. This is the return value of the socket API.
• Local socket address – a combination of the ATWINC15x0 IP address and port number assigned
by the ATWINC15x0 firmware for the socket.
• Protocol – transport layer protocol, either TCP or UDP.
• Remote socket address – applicable only for TCP stream sockets. This is necessary since TCP is
connection oriented. Each connection made to a specific IP address and port number requires a
separate socket. The remote socket address can be obtained in the socket event callback which is
described in the succeeding section.
Note: TCP port 53 and UDP port 53 represent two different sockets.
6.1.3 Limitations
• The ATWINC15x0 sockets API support up to 7 TCP sockets and 4 UDP sockets.
• The ATWINC15x0 sockets API support only IPv4. It does not support IPv6.
6.2 Sockets API
6.2.1 API Prerequisites
• C header file socket.h – this includes all the necessary socket API function declarations. When
using any ATWINC15x0 socket API as described in the following sections, the host MCU
application must include the socket.h header file.
• Initialization – the ATWINC15x0 socket API initializes once before calling any socket API function.
This is done using the socketInit API described in Socket API Functions.
ATWINC15x0
Socket Programming
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 39
6.2.2 Non-blocking Asynchronous Socket APIs
Most ATWINC15x0 socket APIs are asynchronous function calls that do not block the host MCU
application. The behavior of the ATWINC15x0 asynchronous APIs are described in Asynchronous
Events.
For example, the host MCU application can register an application-defined socket event callback function
using the ATWINC15x0 socket API registerSocketCallback. When the host MCU application calls
the socket API connect, the API returns a zero value (SUCCESS) immediately indicating that the request
is accepted. The host MCU application must then wait for the ATWINC15x0 socket API to call the
registered socket callback when the connection is established or if a connection time-out occurred. The
socket callback function provides the necessary information to determine the connection status.
6.2.3 Socket API Functions
The ATWINC15x0 socket API provides the following functions.
6.2.3.1 socketInit
The host MCU application must call the API socketInit once during initialization. The API is a
synchronous API.
6.2.3.2 registerSocketCallback
The registerSocketCallback function allows the host MCU application to provide the ATWINC15x0
sockets with application-defined event callbacks for socket operations. The API is a synchronous API.
The API registers the following callbacks:
• The socket event callback
• The DNS resolve callback
The socket event callback is an application-defined function that is called by the ATWINC15x0 socket API
whenever a socket event occurs. Within this handler, the host MCU application must provide an
application-defined logic that handles the events of interest.
The DNS resolve event handler is the application-defined function that is called by the ATWINC15x0
socket API to return the results of gethostbyname. By implication, this only occurs after the host MCU
application has called the gethostbyname function. If successful, the callback provides the IP address
for the desired domain name.
6.2.3.3 socket
The socket function creates a new socket of a specified type and returns the corresponding socket ID.
The API is a synchronous API.
The socket ID is required by most other socket functions and is also passed as an argument to the socket
event callback function to identify which socket generated the event.
6.2.3.4 connect
The connect function is used with TCP sockets to establish a new connection to a TCP server.
The connect function results in a SOCKET_MSG_CONNECT sent to the socket event handler callback
upon completion. The connect event is sent when the TCP server accepts the connection or, if no remote
host response is received, after a time-out interval of approximately 30 seconds.
Note: The SOCKET_MSG_CONNECT event callback provides a tstrSocketConnectMsg containing an
error code. The error code value indicates:
• Zero value to indicate the successful connection or
ATWINC15x0
Socket Programming
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 40
• Negative value to indicate an error due to a time-out condition or if connect is used with UDP
socket.
The following figure shows the ATWINC15x0 socket API connect to remote server host.
Figure 6-1. TCP Client API Call Sequence
6.2.3.5 bind
The bind function can be used for server operation for both UDP and TCP sockets. It is used to
associate a socket with an address structure (port number and IP address).
The bind function call results to a SOCKET_MSG_BIND event sent to the socket callback handler with the
bind status. Calls to listen, send, sendto, recv, and recvfrom functions must not be issued until the
bind callback is received.
6.2.3.6 listen
The listen function is used for server operations with TCP stream sockets. After calling the listen
API, the socket accepts a connection request from a remote host. The listen function causes a
SOCKET_MSG_LISTEN event notification to be sent to the host after the socket port is ready to indicate
listen operation success or failure.
ATWINC15x0
Socket Programming
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 41
When a remote peer establishes a connection, a SOCKET_MSG_ACCEPT event notification is sent to the
application.
6.2.3.7 accept
The accept function is deprecated and calling this API has no effect. It is kept only for backward
compatibility.
Note: The listen API implicitly accepts the TCP remote peer connections request.
Figure 6-2. TCP Server API Call Sequence
Although the accept function is deprecated, the SOCKET_MSG_ACCEPT event occurs whenever a
remote host connects to the ATWINC15x0 TCP server. The event message contains the IP address and
port number of the connected remote host.
6.2.3.8 send
The send function is used by the application to send data to a remote host. The send function can be
used to send either UDP or TCP data depending on the type of socket.
• For a TCP socket a connection must be established first.
• For a UDP socket, the recommended way is to use sendto API, where the destination address is
defined. However, it is possible to use send API instead of sendto API. For this, at least one
successful call must be made to sendto API prior to the consecutive calls of send function. This
ensures that the destination address is saved in the ATWINC15x0 firmware.
The send function generates a SOCKET_MSG_SEND event callback after the data is transmitted to the
remote host. For TCP sockets, this event guarantees that the data is delivered to the remote host TCP/IP
stack (the remote application must use the recv function to read the data). For UDP sockets, it means
that the data is transmitted, but there is no guarantee that the data is delivered to the remote host as per
UDP protocol. The application is responsible to guarantee data delivery in the UDP sockets case.
The SOCKET_MSG_SEND event callback returns the size of the data transmitted of the transmission in the
success case and zero or negative value in case of an error.
ATWINC15x0
Socket Programming
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 42
6.2.3.9 sendto
The sendto function is used by the application to send UDP data to a remote host. It can only be used
with UDP sockets. The IP address and port of the destination remote host is included as a parameter to
the sendto function.
The SOCKET_MSG_SENDTO event callback returns the size of the data transmitted in the success case
and zero or negative value in case of an error.
6.2.3.10 recv/recvfrom
The recv and recvfrom functions are used to read data from TCP and UDP sockets, respectively, and
their operation is otherwise identical.
The host MCU application calls the recv or recvfrom function with a pre allocated buffer. When the
SOCKET_MSG_RECV or SOCKET_MSG_RECVFROM event callback arrives, this buffer must have the
received data.
The received data size indicates the status as follows:
• Positive – data is received
• Zero – socket connection is terminated
• Negative – indicates an error
In the case of TCP sockets, it is recommended to call the recv function after each successful socket
connection (client or server). Otherwise, the received data is buffered in the ATWINC15x0 firmware
wasting the system's resources until the socket is explicitly closed using a close function call.
6.2.3.11 close
The close function is used to release the resources allocated to the socket and, for a TCP stream
socket, also terminate an open connection.
Each call to the socket function must match with a call to the close function. In addition, sockets that
are accepted on a server socket port must be closed using this function.
6.2.3.12 setsockopt
The setsockopt function may be used to set socket options to control the socket behavior.
The options supported are as follows:
• SO_SET_UDP_SEND_CALLBACK – enables or disables the send /sendto event callbacks. The
user may want to disable the sendto event callback for UDP sockets to enhance the socket
connection throughput.
• IP_ADD_MEMBERSHIP – enables subscribe to an IP Multicast address.
• IP_DROP_MEMBERSHIP – enables unsubscribe to an IP Multicast address.
• SOL_SSL_SOCKET – sets SSL Socket. The following are the options supported for SSL socket:
– SO_SSL_BYPASS_X509_VERIF command allows opening of the SSL socket to bypass the
X509 certification verification process.
Example:
struct sockaddr_in addr_in;
int optVal =1;
addr_in.sin_family = AF_INET;
addr_in.sin_port = _htons(MAIN_HOST_PORT);
addr_in.sin_addr.s_addr = gu32HostIp;
/* Create secure socket */
if (tcp_client_socket < 0) {
tcp_client_socket = socket(AF_INET, SOCK_STREAM,
ATWINC15x0
Socket Programming
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 43
SOCKET_FLAGS_SSL);
}
/* Check if socket was created successfully */
if (tcp_client_socket == -1) {
printf("socket error.\r\n");
close(tcp_client_socket);
return -1;
}
/* Enable X509 bypass verification */
setsockopt(tcp_client_socket,
SOL_SSL_SOCKET,SO_SSL_BYPASS_X509_VERIF,&optVal,sizeof(optVal));
/* If success, connect to socket */
if (connect(tcp_client_socket, (struct sockaddr
*)&addr_in,
sizeof(struct sockaddr_in)) !=
SOCK_ERR_NO_ERROR) {
printf("connect error.\r\n");
return SOCK_ERR_INVALID;
}
– SO_SSL_SNI command sets the Server Name Indicator (SNI). During TLS handshake
process, client can indicate which hostname it is trying to connect by setting Server Name in
(extended) client hello. SNI allows a server to present multiple certificates on the same IP
address and TCP port number and hence allows multiple secure websites to be served by the
same IP address without requiring all of the websites to use the same certificate.
– SO_SSL_ENABLE_SNI_VALIDATION enables SNI validation functionality in case SNI is set.
The server name validation is disabled by default. To enable server name validation, both
SO_SSL_SNI and SO_SSL_ENABLE_SNI_VALIDATION must be set by the application
through setsockopt() as shown in the example code snippet. When the SNI validation is
enabled, the SNI is compared with the common name (CN) in the received server certificate.
If the supplied SNI does not match the CN, the SSL connection will be forcibly closed by the
ATWINC15x0 firmware.
Example:
#define MAIN_HOST_NAME "www.google.com"
struct sockaddr_in addr_in;
int optVal =1;
addr_in.sin_family = AF_INET;
addr_in.sin_port = _htons(MAIN_HOST_PORT);
addr_in.sin_addr.s_addr = gu32HostIp;
/* Create secure socket */
if (tcp_client_socket < 0) {
tcp_client_socket = socket(AF_INET, SOCK_STREAM,
SOCKET_FLAGS_SSL);
}
/* Check if socket was created successfully */
if (tcp_client_socket == -1) {
printf("socket error.\r\n");
close(tcp_client_socket);
return -1;
}
/* set SNI on SSL Socket */
setsockopt(tcp_client_socket,
SOL_SSL_SOCKET,SO_SSL_SNI,
MAIN_HOST_NAME,sizeof(MAIN_HOST_NAME));
/* Enable SSL SNI validation */
setsockopt(tcp_client_socket, SOL_SSL_SOCKET,
SO_SSL_ENABLE_SNI_VALIDATION,&optVal,sizeof(optVal));
/* If success, connect to socket */
if (connect(tcp_client_socket, (struct sockaddr
*)&addr_in, sizeof(
ATWINC15x0
Socket Programming
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 44
struct sockaddr_in)) != SOCK_ERR_NO_ERROR) {
printf("connect error.\r\n");
return SOCK_ERR_INVALID;
}
– SO_SSL_ENABLE_SESSION_CACHING command allows the TLS to cache the session
information to speed up the future TLS session establishment.
Example:
struct sockaddr_in addr_in;
int optVal =1;
addr_in.sin_family = AF_INET;
addr_in.sin_port = _htons(MAIN_HOST_PORT);
addr_in.sin_addr.s_addr = gu32HostIp;
/* Create secure socket */
if (tcp_client_socket < 0) {
tcp_client_socket = socket(AF_INET, SOCK_STREAM,
SOCKET_FLAGS_SSL);
}
/* Check if socket was created successfully */
if (tcp_client_socket == -1) {
printf("socket error.\r\n");
close(tcp_client_socket);
return -1;
}
/* Enable SSL Session cache */
setsockopt(tcp_client_socket,
SOL_SSL_SOCKET,SO_SSL_ENABLE_SESSION_CACHING,&optVal,sizeof(optVal));
/* If success, connect to socket */
if (connect(tcp_client_socket, (struct sockaddr
*)&addr_in, sizeof(struct
sockaddr_in)) != SOCK_ERR_NO_ERROR) {
printf("connect error.\r\n");
return SOCK_ERR_INVALID;
}
WARNING SO_SSL_BYPASS_X509_VERIF is only provided for debugging and testing purposes. It is NOT
recommended to use this socket option in production software applications.
6.2.3.13 gethostbyname
The gethostbyname function is used to resolve a host name (for example, URL) to a host IP address
via the Domain Name System (DNS). This is limited only to IPv4 addresses. The operation depends on
the configuration of a DNS server IP address and access to the DNS hierarchy through the internet.
After gethostbyname is called, a callback to the DNS resolver handler is made. If the IP address is
determined, a positive value is returned. If it cannot be determined or if the DNS server is not accessible
(30-second time-out), an IP address value of zero is indicated.
Note: An IP returns a zero value to indicate an error (for example, the internet connection is down or
DNS is unavailable) and the host MCU application may try the function call gethostbyname again later.
6.2.4 Summary
The following table summarizes the ATWINC15x0 socket API and shows its compatibility with BSD socket
APIs.
ATWINC15x0
Socket Programming
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 45
Table 6-1. ATWINC15x0 Socket API Summary
BSD API ATWINC15x0
API
ATWINC15x0
API Type
Server/
Client
TCP/UD
P
Brief
socket socket Synchronous Both Both Creates a new socket.
connect connect Asynchronous Client TCP Initializes a TCP
connection request to a
remote server.
bind bind Asynchronous Server Both Binds a socket to an
address (address/port).
listen listen Asynchronous Server TCP Allows a bound socket
to listen to remote
connections for its local
port.
accept accept Deprecated, Implicit accept in listen.
send send Asynchronous Both Both Sends packet.
sendto sendto Asynchronous Both UDP Sends packet over UDP
sockets.
write - Not supported
recv recv Asynchronous Both Both Receives packet.
recvfrom recvfrom Asynchronous Both Both Receives packet.
read - Not supported
close close Synchronous Both Both Terminates the TCP
connection and release
system resources.
gethostbyname gethostbyname Asynchronous Both Both Gets the IP address of a
certain host name
gethostbyaddr - Not supported
select - Not supported
poll - Not supported
setsockopt setsockopt Synchronous Both Both Sets socket option.
getsockopt Not supported
htons/ntohs _htons/_ntohs Synchronous Both Both Converts 2 byte integer
from the host
representation to the
Network byte order
representation (and vice
versa).
ATWINC15x0
Socket Programming
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 46
...........continued
BSD API ATWINC15x0
API
ATWINC15x0
API Type
Server/
Client
TCP/UD
P
Brief
htonl/ntohl21 _htonl/_ntohl Synchronous Both Both Converts 4 byte integer
from the host
representation to the
Network byte order
representation (and vice
versa).
6.3 Socket Connection Flow
In the following sub-sections, the TCP and UDP (client and server) operations are described in details.
Figure 6-3. Typical Socket Connection Flow
ATWINC15x0
Socket Programming
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 47
6.3.1 TCP Client Operation
The following figure shows the flow for transferring data with a TCP client.
Figure 6-4. TCP Client Sequence Diagram
Note:
1. The host application must register a socket notification callback function. The function must be of
tpfAppSocketCb type and must handle socket event notifications appropriately.
2. If the client knows the IP of the server, it may call connect directly as shown in the figure above. If
only the server URL is known, then the application must resolve the server URL first calling the
gethostbyname API.
ATWINC15x0
Socket Programming
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 48
6.3.2 TCP Server Operation
Figure 6-5. TCP Server Sequence Diagram
Note: The host application must register a socket notification callback function. The function must be of
type tpfAppSocketCb and must handle socket event notifications appropriately.
6.3.3 UDP Client Operation
The following figure shows the flow for transferring data with a UDP client.
Figure 6-6. UDP Client Sequence Diagram
ATWINC15x0
Socket Programming
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 49
Note:
1. The first send message must be performed with the sendto API with the destination address
specified.
2. If further messages are sent to the same address, the send API can also be used. For more
details, refer to send.
3. recv can be used instead of recvfrom.
6.3.4 UDP Server Operation
The following figure shows the flow for transferring data after establishing a UDP server.
Figure 6-7. UDP Server Sequence Diagram
6.3.5 DNS Host Name Resolution
The following figure shows the flow of DNS host name resolution.
Figure 6-8. DNS Resolution Sequence
ATWINC15x0
Socket Programming
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 50
Note:
1. The host application requests to resolve hostname (for example, http://www.foobar.com), by calling
the function gethostbyname.
2. Before calling the gethostbyname, the application must register a DNS response callback
function using the function registerSocketCallback.
3. After the ATWINC15x0 DNS_Resolver module obtains the IP Address (hostIP) corresponding to
the given HostName, the dnsResolveCB is called with the hostIP.
4. If an error occurs or if the DNS request encounters a time-out, the dnsResolveCB is called with IP
Address value zero indicating a failure to resolve the domain name.
6.4 Example Code
This section provides code examples for different socket applications. For additional socket code
examples, refer to the Wi-Fi Network Controller Software Programming Guide.
6.4.1 TCP Client Example Code
SOCKET clientSocketHdl;
uint8 rxBuffer[256];
/* Socket event handler. */
void tcpClientSocketEventHandler(SOCKET sock, uint8 u8Msg, void * pvMsg)
{
if(sock == clientSocketHdl)
{
if(u8Msg == SOCKET_MSG_CONNECT)
{
// Connect Event Handler.
tstrSocketConnectMsg *pstrConnect = (tstrSocketConnectMsg*)pvMsg;
if(pstrConnect->s8Error == 0)
{
// Perform data exchange.
uint8 acSendBuffer[256];
uint16 u16MsgSize;
// Fill in the acSendBuffer with some data here
// send data
send(clientSocketHdl, acSendBuffer, u16MsgSize, 0);
// Recv response from server.
recv(clientSocketHdl, rxBuffer, sizeof(rxBuffer), 0);
}
else
{
printf("TCP Connection Failed\n");
}
}
else if(u8Msg == SOCKET_MSG_RECV)
{
tstrSocketRecvMsg *pstrRecvMsg = (tstrSocketRecvMsg*)pvMsg;
if((pstrRecvMsg->pu8Buffer != NULL) && (pstrRecvMsg->s16BufferSize > 0))
{
// Process the received message.
// Close the socket.
close(clientSocketHdl);
}
}
}
}
// This is the DNS callback. The response of gethostbyname is here.
void dnsResolveCallback(uint8* pu8HostName, uint32 u32ServerIP)
{
struct sockaddr_in strAddr;
ATWINC15x0
Socket Programming
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 51
if(u32ServerIP != 0)
{
clientSocketHdl = socket(AF_INET,SOCK_STREAM,u8Flags);
if(clientSocketHdl >= 0)
{
strAddr.sin_family = AF_INET;
strAddr.sin_port = _htons(443);
strAddr.sin_addr.s_addr = u32ServerIP;
connect(clientSocketHdl, (struct sockaddr*)&strAddr, sizeof(struct sockaddr_in));
}
}
else
{
printf("DNS Resolution Failed\n");
}
}
/* This function needs to be called from main function. For the callbacks to be invoked
correctly, the API m2m_wifi_handle_events should be called continuously from main. */
void tcpConnect(char *pcServerURL)
{
// Initialize the socket layer.
socketInit();
// Register socket application callbacks.
registerSocketCallback(tcpClientSocketEventHandler, dnsResolveCallback);
// Resolve Server URL.
gethostbyname((uint8*)pcServerURL);
}
6.4.2 TCP Server Example Code
SOCKET listenSocketHdl, acceptedSocketHdl;
uint8 rxBuffer[256];
uint8 bIsfinished = 0;
/* Socket event handler. */
void tcpServerSocketEventHandler(SOCKET sock, uint8 u8Msg, void * pvMsg)
{
if(u8Msg == SOCKET_MSG_BIND)
{
tstrSocketBindMsg *pstrBind = (tstrSocketBindMsg*)pvMsg;
if(pstrBind->status == 0)
{
listen(listenSocketHdl, 0);
}
else
{
printf("Bind Failed\n");
}
}
else if(u8Msg == SOCKET_MSG_LISTEN)
{
tstrSocketListenMsg *pstrListen = (tstrSocketListenMsg*)pvMsg;
if(pstrListen->status != 0)
{
printf("listen Failed\n");
}
}
else if(u8Msg == SOCKET_MSG_ACCEPT)
{
// New Socket is accepted.
tstrSocketAcceptMsg *pstrAccept = (tstrSocketAcceptMsg *)pvMsg;
if(pstrAccept->sock >= 0)
{
// Get the accepted socket.
acceptedSocketHdl = pstrAccept->sock;
recv(acceptedSocketHdl, rxBuffer, sizeof(rxBuffer), 0);
}
else
ATWINC15x0
Socket Programming
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 52
{
printf("Accept Failed\n");
}
}
else if(u8Msg == SOCKET_MSG_RECV)
{
tstrSocketRecvMsg *pstrRecvMsg = (tstrSocketRecvMsg*)pvMsg;
if((pstrRecvMsg->pu8Buffer != NULL) && (pstrRecvMsg->s16BufferSize > 0))
{
// Process the received message
// Perform data exchange
uint8 acSendBuffer[256];
uint16 u16MsgSize;
// Fill in the acSendBuffer with some data here
// Send some data.
send(acceptedSocketHdl, acSendBuffer, u16MsgSize, 0);
// Recv response from client.
recv(acceptedSocketHdl, rxBuffer, sizeof(rxBuffer), 0);
// Close the socket when finished.
if(bIsfinished)
{
close(acceptedSocketHdl);
close(listenSocketHdl);
}
}
}
}
/* This function needs to be called from main function. For the callbacks to be invoked
correctly, the API m2m_wifi_handle_events should be called continuously from main. */
void tcpStartServer(uint16 u16ServerPort)
{
struct sockaddr_in strAddr;
// Initialize the socket layer.
socketInit();
// Register socket application callbacks.
registerSocketCallback(tcpServerSocketEventHandler, NULL);
// Create the server listen socket.
listenSocketHdl = socket(AF_INET, SOCK_STREAM, 0);
if(listenSocketHdl >= 0)
{
strAddr.sin_family = AF_INET;
strAddr.sin_port = _htons(u16ServerPort);
strAddr.sin_addr.s_addr = 0; //INADDR_ANY
bind(listenSocketHdl, (struct sockaddr*)&strAddr, sizeof(struct sockaddr_in));
}
}
6.4.3 UDP Client Example Code
SOCKET clientSocketHdl;
uint8 rxBuffer[256], acSendBuffer[256];
/* Socket event handler */
void udpClientSocketEventHandler(SOCKET sock, uint8 u8Msg, void * pvMsg)
{
if((u8Msg == SOCKET_MSG_RECV) || (u8Msg == SOCKET_MSG_RECVFROM))
{
tstrSocketRecvMsg *pstrRecvMsg = (tstrSocketRecvMsg*)pvMsg;
if((pstrRecvMsg->pu8Buffer != NULL) && (pstrRecvMsg->s16BufferSize > 0))
{
uint16 len;
// Format a message in the acSendBuffer and put its length in len
sendto(clientSocketHdl, acSendBuffer, len, 0,
(struct sockaddr*)&strAddr, sizeof(struct sockaddr_in));
recvfrom(clientSocketHdl, rxBuffer, sizeof(rxBuffer), 0);
ATWINC15x0
Socket Programming
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 53
// Close the socket after finished
close(clientSocketHdl);
}
}
}
/* This function needs to be called from main function. For the callbacks to be invoked
correctly, the API m2m_wifi_handle_events should be called continuously from main.*/
void udpClientStart(char *pcServerIP)
{
struct sockaddr_in strAddr;
// Initialize the socket layer.
socketInit();
// Register socket application callbacks.
registerSocketCallback(udpClientSocketEventHandler, NULL);
clientSocketHdl = socket(AF_INET,SOCK_STREAM,u8Flags);
if(clientSocketHdl >= 0)
{
uint16 len;
strAddr.sin_family = AF_INET;
strAddr.sin_port = _htons(1234);
strAddr.sin_addr.s_addr = nmi_inet_addr(pcServerIP);
// Format some message in the acSendBuffer and put its length in len
sendto(clientSocketHdl, acSendBuffer, len, 0, (struct sockaddr*)&strAddr,
sizeof(struct sockaddr_in));
recvfrom(clientSocketHdl, rxBuffer, sizeof(rxBuffer), 0);
}
}
6.4.4 UDP Server Example Code
SOCKET serverSocketHdl;
uint8 rxBuffer[256];
/* Socket event handler.*/
void udpServerSocketEventHandler(SOCKET sock, uint8 u8Msg, void * pvMsg)
{
if(u8Msg == SOCKET_MSG_BIND)
{
tstrSocketBindMsg *pstrBind = (tstrSocketBindMsg*)pvMsg;
if(pstrBind->status == 0)
{
// call Recv
recvfrom(serverSocketHdl, rxBuffer, sizeof(rxBuffer), 0);
}
else
{
printf("Bind Failed\n");
}
}
else if(u8Msg == SOCKET_MSG_RECV)
{
tstrSocketRecvMsg *pstrRecvMsg = (tstrSocketRecvMsg*)pvMsg;
if((pstrRecvMsg->pu8Buffer != NULL) && (pstrRecvMsg->s16BufferSize > 0))
{
// Perform data exchange.
uint8 acSendBuffer[256];
uint16 u16MsgSize;
// Fill in the acSendBuffer with some data
// Send some data to the same address.
sendto(acceptedSocketHdl, acSendBuffer, u16MsgSize, 0,
pstrRecvMsg-> strRemoteAddr, sizeof(pstrRecvMsg-> strRemoteAddr));
// call Recv
recvfrom(serverSocketHdl, rxBuffer, sizeof(rxBuffer), 0);
// Close the socket when finished.
close(serverSocketHdl);
}
ATWINC15x0
Socket Programming
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 54
}
}
/* This function needs to be called from main function. For the callbacks to be invoked
correctly, the API m2m_wifi_handle_events should be called continuously from main.
*/
void udpStartServer(uint16 u16ServerPort)
{
struct sockaddr_in strAddr;
// Initialize the socket layer.
socketInit();
// Register socket application callbacks.
registerSocketCallback(udpServerSocketEventHandler, NULL);
// Create the server listen socket.
listenSocketHdl = socket(AF_INET, SOCK_DGRAM, 0);
if(listenSocketHdl >= 0)
{
strAddr.sin_family = AF_INET;
strAddr.sin_port = _htons(u16ServerPort);
strAddr.sin_addr.s_addr = 0; //INADDR_ANY
bind(serverSocketHdl, (struct sockaddr*)&strAddr, sizeof(struct sockaddr_in));
}
}
ATWINC15x0
Socket Programming
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 55
7. Transport Layer Security (TLS)
Transport Layer Security (TLS) layer sits on top of TCP and provides security services including privacy,
authenticity, and message integrity. Various security methods are available with TLS in the WINC
firmware.
7.1 TLS Overview
The ATWINC15x0 features an embedded low-memory footprint TLS protocol stack bundled within the
WINC firmware.
It features the following functionality:
• Supports TLS versions TLS1.0, TLS1.1 and TLS1.2.
• Supports TLS client operation with TLS client authentication.
• Supports TLS Server mode.
• A simple application interface to the TLS stack. The TLS functionality is abstracted by the
ATWINC15x0 socket interface, hiding the implementation complexity from the application developer
and minimizing the effort to port existing plain TCP code to TLS.
7.2 TLS Connection Establishment
From the application’s point of view, the TLS functionality is wrapped behind the socket APIs. This hides
the complexity of TLS from the application which can use the TLS in the same way as the TCP (non-TLS)
client and server. The main difference between the TLS sockets and the regular TCP sockets is that the
application sets the SOCKET_FLAGS_SSL while creating the TLS client and server listening sockets. The
detailed sequence of TLS connection establishment is described in the following figure.
Note:
• For proper TLS Client operation, ensure that both SOCKET_FLAGS_SSL flag and the correct port
number is set in the TLS client application. For instance, an HTTP client application uses no flag
when calling socket API function and connect to port 80. The same application source code
becomes an HTTPS client application if you use the flag SOCKET_FLAGS_SSL and change the port
number in connect API to port 433.
• For proper TLS server operation, ensure that both SOCKET_FLAGS_SSL flag and the correct port
number is set in the TLS server application. For instance, an HTTP server application uses no flag
when calling socket API function and bind to port 80. The same application source code
becomes an HTTPS server application, if you use the flag SOCKET_FLAGS_SSL and change the
port number in bind API to port 443.
ATWINC15x0
Transport Layer Security (TLS)
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 56
Figure 7-1. TLS Client Application Connection Establishment
ATWINC15x0
Transport Layer Security (TLS)
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 57
Figure 7-2. TLS Server Application Connection Establishment
7.3 Server Certificate Installation
7.3.1 Technical Background
7.3.1.1 Public Key Infrastructure
The TLS security is based on the Public Key Infrastructure PKI, in which:
• A server has its public key stored in a digital certificate with X.509 standard format.
• The server must have its X.509 certificate issued by Certificate Authority (CA) which in turn may be
certified by another CA.
ATWINC15x0
Transport Layer Security (TLS)
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 58
• This structure forms a chain of X.509 certificates known as chain of trust.
• The top most CA of the Chain is known to be the Trusted Root Certificate Authority of the chain.
7.3.1.2 TLS Server Authentication
• When a TLS client initiates a connection with a server, the server sends its X.509 certificate chain
(may or may not include the root certificate) to the client.
• The client must authenticate the Server (verify the Server identity) before starting data exchange.
• The client must verify the entire certificate chain and also verify that the root certificate authority of
the chain is in the client’s trusted root certificate store.
7.3.2 Adding a Certificate to the WINC Trusted Root Certificate Store
• Before connecting to a TLS Server, the root certificate of the server must be installed on the
ATWINC15x0. If this is not done, the TLS connection to the server is locally aborted by the WINC.
• The root certificate must be in DER format. If it is not provided in DER format, it must be converted
before installation. Refer to Section 17 “How to Generate Certificates” for certificate formats and
conversion methods.
• To install the certificate, execute root_certificate_downloader.exe with the following syntax:
root_certificate_downloader.exe -n N File1.cer File2.cer .... FileN.cer
7.4 WINC TLS Limitations
7.4.1 Concurrent Connections
Only 2 TLS concurrent connections are allowed.
7.4.2 TLS Supported Ciphers
The ATWINC15x0 supports the following cipher suites (for both client and server modes).
• TLS_DHE_RSA_WITH_AES_128_CBC_SHA
• TLS_DHE_RSA_WITH_AES_128_CBC_SHA256
• TLS_RSA_WITH_AES_128_CBC_SHA
• TLS_RSA_WITH_AES_128_CBC_SHA256
The ATWINC15x0 also optionally support the following ECC cipher suites.
• TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
• TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
• TLS_ECDHE_ ECDSA _WITH_AES_128_CBC_SHA256
7.4.3 Supported Hash Algorithms
The current implementation (WINC firmware version 19.5.2 onwards) supports the following hash
algorithms:
• MD5
• SHA-1
• SHA256
• SHA384
• SHA512
• RSA 4096
ATWINC15x0
Transport Layer Security (TLS)
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 59
7.4.4 TLS Certificate Constraints
For TLS server and TLS client authentication, the ATWINC15x0 can accept the following certificate types:
• RSA certificates with key size no more than 2048 bits
• ECDSA certificates only for NIST P256 EC Curve (secp256r1); conditionally supported
7.4.5 ECC Cipher Suite
The ATWINC15x0 TLS library features support of ECC cipher suites. Although, the ATWINC15x0 device
does not contain a built-in hardware accelerator for ECC math, the WINC TLS library leverages the ECC
math from the host MCU. To perform the ECC computations needed by the ECC ciphers, an ECC
hardware accelerator (or software library) on the host MCU is mandatory.
The WINC TLS initializes with the ECC cipher suites disabled by default. The host MCU application can
enable the ciphers via the API sslSetActiveCipherSuites.
7.5 SSL Client Code Example
SOCKET sslSocketHdl;
uint8 rxBuffer[256];
/* Socket event handler. */
void SSL_SocketEventHandler(SOCKET sock, uint8 u8Msg, void * pvMsg)
{
if(sock == sslSocketHdl)
{
if(u8Msg == SOCKET_MSG_CONNECT)
{
// Connect event
tstrSocketConnectMsg *pstrConnect = (tstrSocketConnectMsg*)pvMsg;
if(pstrConnect->s8Error == 0)
{
// Perform data exchange.
uint8 acSendBuffer[256];
uint16 u16MsgSize;
// Fill in the acSendBuffer with some data here
// Send some data.
send(sock, acSendBuffer, u16MsgSize, 0);
// Recv response from server.
recv(sslSocketHdl, rxBuffer, sizeof(rxBuffer), 0);
}
else
{
printf("SSL Connection Failed\n");
}
}
else if(u8Msg == SOCKET_MSG_RECV)
{
tstrSocketRecvMsg *pstrRecvMsg = (tstrSocketRecvMsg*)pvMsg;
if((pstrRecvMsg->pu8Buffer != NULL) && (pstrRecvMsg->s16BufferSize > 0))
{
// Process the received message here
// Close the socket if finished.
close(sslSocketHdl);
}
}
}
}
/* This is the DNS callback. The response of gethostbyname is here. */
void dnsResolveCallback(uint8* pu8HostName, uint32 u32ServerIP)
{
struct sockaddr_in strAddr;
if(u32ServerIP != 0)
{
ATWINC15x0
Transport Layer Security (TLS)
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 60
sslSocketHdl = socket(AF_INET,SOCK_STREAM,u8Flags);
if(sslSocketHdl >= 0)
{
strAddr.sin_family = AF_INET;
strAddr.sin_port = _htons(443);
strAddr.sin_addr.s_addr = u32ServerIP;
connect(sslSocketHdl, (struct sockaddr*)&strAddr, sizeof(struct sockaddr_in));
}
}
else
{
printf("DNS Resolution Failed\n");
}
}
/* This function needs to be called from main function. For the callbacks to be invoked
correctly, the API m2m_wifi_handle_events should be called continuously from main.*/
void SSL_Connect(char *pcServerURL)
{
// Initialize the socket layer.
socketInit();
// Register socket application callbacks.
registerSocketCallback(SSL_SocketEventHandler, dnsResolveCallback);
// Resolve Server URL.
gethostbyname((uint8*)pcServerURL);
}
ATWINC15x0
Transport Layer Security (TLS)
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 61
8. Wi-Fi AP Mode
8.1 Overview
This chapter provides an overview of the WINC Access Point (AP) mode and describes how to setup this
mode and configure its parameters.
In ATWINC1500 v19.6.1 firmware and above, the DHCP default gateway, DNS server and subnet mask
can be customized when entering AP and provisioning modes. Earlier, the default gateway and DNS
server is the same as the host IP of the WINC and the subnet mask is 255.255.255.0. Configuring these
values allow the use of 0.0.0.0 for the default gateway and DNS server, allowing mobile devices to
connect to the WINC AP without disconnecting from the mobile network. Using IPs other than 0.0.0.0 is
possible but it is of no use since only one device can connect to the WINC AP at any time.
8.2 Setting the WINC AP Mode
Set the WINC AP mode configuration parameters using the tstrM2MAPConfig structure.
There are two functions to enable/disable the WINC AP mode:
• sint8 m2m_wifi_enable_ap (CONST tstrM2MAPConfig* pstrM2MAPConfig)
• sint8 m2m_wifi_disable_ap (void)
For more details on API, refer to the Atmel Software Framework for ATWINC1500 (Wi-Fi).
In ATWINC1500 v19.6.1 firmware and above, to maintain backwards compatibility with older drivers, new
structures and APIs were introduced.
To customize these fields when entering AP or provisioning mode the tstrM2MAPModeConfig structure
must be populated and passed to the new m2m_wifi_enable_ap_ext() or
m2m_wifi_start_provision_mode_ext() APIs. The tstrM2MAPModeConfig structure contains
the original tstrM2MAPConfig structure for storing the AP SSID, password, and so on. and another
tstrM2MAPConfigExt structure for configuring the default router, DNS server and subnet mask.
8.3 Limitations
• The AP can only support a single associated station. Further connection attempts are rejected.
• The ATWINC15x0 supports WPA2 security feature starting from the firmware version 19.5.x.
• Concurrency (simultaneous STA and AP mode) is not supported. Prior to activating the AP mode,
the host MCU application must disable the mode that is currently running.
8.4 Sequence Diagram
Once AP mode is established, data interface does not exist before a station associates to the AP;
therefore, the application needs to wait until it receives a notification via an event callback. This process
is shown in the following figure.
ATWINC15x0
Wi-Fi AP Mode
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 62
Figure 8-1. ATWINC15x0 AP Mode Establishment
8.5 AP Mode Code Example
The following example shows how to configure the ATWINC15x0 AP mode with WINC_SSID as
broadcasted SSID on channel one with open security and an IP address equals 192.168.1.1.
#include "m2m_wifi.h"
#include "m2m_types.h"
void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg)
{
switch(u8WiFiEvent)
{
case M2M_WIFI_REQ_DHCP_CONF:
{
uint8 *pu8IPAddress = (uint8*)pvMsg;
printf("Associated STA has IP Address \"%u.%u.%u.%u\"\n", pu8IPAddress[0],
pu8IPAddress[1], pu8IPAddress[2], pu8IPAddress[3]);
}
break;
default:
break;
}
}
int main()
{
tstrWifiInitParam param;
/* Platform specific initializations. */
ATWINC15x0
Wi-Fi AP Mode
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 63
param.pfAppWifiCb = wifi_event_cb;
if (!m2m_wifi_init(¶m))
{
tstrM2MAPConfig apConfig;
strcpy(apConfig.au8SSID, "WINC_SSID"); // Set SSID
apConfig.u8SsidHide = SSID_MODE_VISIBLE; // Set SSID to be broadcasted
apConfig.u8ListenChannel = 1; // Set Channel
apConfig.u8SecType = M2M_WIFI_SEC_WEP; // Set Security to WEP
apConfig.u8KeyIndx = 0; // Set WEP Key Index
apConfig.u8KeySz = WEP_40_KEY_STRING_SIZE; // Set WEP Key Size
strcpy(apConfig.au8WepKey, "1234567890"); // Set WEP Key
// IP Address
apConfig.au8DHCPServerIP[0] = 192;
apConfig.au8DHCPServerIP[1] = 168;
apConfig.au8DHCPServerIP[2] = 1;
apConfig.au8DHCPServerIP[3] = 1;
// Start AP mode
m2m_wifi_enable_ap(&apConfig);
while(1)
{
m2m_wifi_handle_events(NULL);
}
}
}
Note: Power Save mode is not supported in the ATWINC15x0 AP mode.
ATWINC15x0
Wi-Fi AP Mode
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 64
9. Provisioning
For normal operation the ATWINC15x0 device requires certain parameters to be loaded. In particular,
when operating in Station mode, it must know the identity (SSID) and credentials of the access point to
which it needs to connect. The entry of this information is facilitated through the following provisioning
steps.
The current ATWINC15x0 software supports the following methods of provisioning:
• HTTP-based (browser) provisioning, while the WINC is in AP mode
• Wi-Fi Protected Setup (WPS)
9.1 HTTP Provisioning
In this method, the ATWINC15x0 is placed in AP mode and another device with a browser capability
(mobile phone, tablet, PC, and so on) is instructed to connect to the ATWINC15x0 HTTP server. Once
connected, the desired configuration can be entered.
The HTTP Provisioning home page is as shown in the following figure.
Figure 9-1. ATWINC15x0 HTTP Provisioning Page
ATWINC15x0
Provisioning
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 65
9.1.1 Provisioning Control Flow
Figure 9-2. HTTP Provisioning Sequence Diagram
The preceding figure shows the provisioning operation for a WINC device. The detailed steps are
described as follows:
1. The WINC device starts the HTTP Provisioning mode.
2. A user with a smartphone finds the WINC AP SSID in the Wi-Fi search list.
3. The user connects to the WINC AP.
4. The user launches the web browser and writes the WINC home page in the address bar.
5. If the HTTP redirect bit (bEnableHttpRedirect) is set in m2m_wifi_start_provision_mode
API, then all http traffic (http://URL) from the associated device (Phone, PC, and so on) are
redirected to the WINC HTTP Provisioning home page. Some phones display a notification
message “sign in to Wi-Fi networks?” which, when accepted, automatically loads the WINC home
page. The WINC home page, as shown in Figure 10.1, appears on the browser.
6. To discover the list of Wi-Fi APs in the area, the user can press “Refresh”.
7. The desired AP is then selected from the search list (by one click or one touch) and its name
automatically appears in the “Network Name” text box.
ATWINC15x0
Provisioning
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 66
8. The user must then enter the correct AP passphrase (for WPA/WPA2 personal security) in the
“Pass Phrase” text box. If the desired AP uses open security, (M2M_WIFI_SEC_OPEN) then the
Pass Phrase field is left empty.
9. A WINC device name may be optionally configured, if desired, by the user in the “Device Name”
text box.
10. Then user should press Connect.
The WINC turns off AP mode and start connecting to the provisioned AP.
9.1.2 HTTP Redirect Feature
The ATWINC15x0 HTTP Provisioning server supports the HTTP redirect feature, which forces all HTTP
traffic originating from the associated user device to be redirected to the ATWINC15x0 Provisioning home
page.
This simplifies the mechanism of loading the provisioning page instead of typing the exact web address of
the HTTP Provisioning server.
To enable this feature, set the redirect flag when calling the API m2m_wifi_start_provision_mode.
For further details, refer to the following code example.
9.1.3 Provisioning Code Example
void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg)
{
if(u8WiFiEvent == M2M_WIFI_RESP_PROVISION_INFO)
{
tstrM2MProvisionInfo *provInfo = (tstrM2MProvisionInfo*)pvMsg;
if(provInfo->u8Status == M2M_SUCCESS)
{
// connect to the provisioned AP.
m2m_wifi_connect((char*)provInfo->au8SSID, strlen(provInfo ->au8SSID),
provInfo->u8SecType, provInfo->au8Password, M2M_WIFI_CH_ALL);
printf("PROV SSID : %s\n", provInfo->au8SSID);
printf("PROV PSK : %s\n", provInfo->au8Password);
}
else
{
printf("(ERR) Provisioning Failed\n");
}
}
}
int main()
{
tstrWifiInitParam param;
// Platform specific initializations.
// Driver initialization.
param.pfAppWifiCb = wifi_event_cb;
if(!m2m_wifi_init(¶m))
{
tstrM2MAPConfig apConfig;
uint8 bEnableRedirect = 1;
strcpy(apConfig.au8SSID, "WINC_AP");
apConfig.u8ListenChannel = 1;
apConfig.u8SecType = M2M_WIFI_SEC_OPEN;
apConfig.u8SsidHide = 0;
// IP Address
apConfig.au8DHCPServerIP[0] = 192;
apConfig.au8DHCPServerIP[1] = 168;
apConfig.au8DHCPServerIP[2] = 1;
apConfig.au8DHCPServerIP[0] = 1;
m2m_wifi_start_provision_mode(&apConfig, "atmelconfig.com", bEnableRedirect);
ATWINC15x0
Provisioning
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 67
while(1)
{
m2m_wifi_handle_events(NULL);
}
}
}
9.2 Limitations
The current implementation of the HTTP Provisioning has the following limitations:
• The ATWINC15x0 AP limitations are applicable to the Provisioning mode. For a list of AP mode
limitations, refer to Limitations.
• Provisioning uses AP mode with open security. No Wi-Fi security nor application level security (for
example, TLS) is used; therefore, the AP credentials entered by the user are sent on the clear and
can be seen by eavesdroppers.
• The WINC Provisioning home page is a static HTML page. No server-side scripting allowed in the
WINC HTTP server.
• Only APs with WPA-personal security (passphrase based) and no security (Open network) can be
provisioned. WEP and WPA-Enterprise APs cannot be provisioned.
• The Provisioning is responsible to deliver the connection parameters to the application, the
connection procedure and the connection parameters validity are the application's responsibility.
9.3 Wi-Fi Protected Setup (WPS)
Most modern Access Points support Wi-Fi Protected Setup method, typically using the push button
method. From the user’s perspective WPS is a simple mechanism to make a device connect securely to
an AP without remembering passwords or passphrases. WPS uses asymmetric cryptography to form a
temporary secure link which is then used to transfer a passphrase (and other information) from the AP to
the new station. After the transfer, secure connections are made as for normal static PSK configuration.
9.3.1 WPS Configuration Methods
There are two authentication methods that can be used with WPS:
1. PBC (push button) method – A physical button is pressed on the AP which puts the AP into WPS
mode for a limited period of time. WPS is initiated on the ATWINC15x0 by calling m2m_wifi_wps
with input parameter WPS_PBC_TRIGGER.
2. PIN method – The AP is always available for WPS initiation but requires proof that the user has
knowledge of an 8-digit PIN, usually printed on the body of the AP. Since the WINC is often used in
headless devices (no user interface), it is necessary to reverse this process and force the AP to use
a PIN number provided with the WINC device. Some APs allow the PIN to be changed through
configuration. WPS is initiated on the ATWINC15x0 by calling m2m_wifi_wps with input parameter
WPS_PIN_TRIGGER. Given the difficulty of this approach, it is not recommend for most
applications.
The flow of messages and actions for WPS operation is shown in the following figure.
ATWINC15x0
Provisioning
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 68
9.3.2 WPS Control Flow
Figure 9-3. WPS Operation for Push Button Trigger
9.3.3 WPS Limitations
• WPS is used to transfer the WPA/WPA2 key only; other security types are not supported.
• The WPS standard rejects the session (WPS response fail) if the WPS button is pressed on more
than one AP in the same proximity, and the application can try again after a couple of minutes.
• If no WPS button is pressed on the AP, the WPS scan will time-out after two minutes since the
initial WPS trigger.
• The WPS is responsible to deliver the connection parameters to the application, the connection
procedure and the connection parameters’ validity is the application's responsibility.
9.3.4 WPS Code Example
void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg)
{
if(u8WiFiEvent == M2M_WIFI_REQ_WPS)
{
tstrM2MWPSInfo *pstrWPS = (tstrM2MWPSInfo*)pvMsg;
if(pstrWPS->u8AuthType != 0)
{
printf("WPS SSID : %s\n",pstrWPS->au8SSID);
printf("WPS PSK : %s\n",pstrWPS->au8PSK);
printf("WPS SSID Auth Type : %s\n",
pstrWPS->u8AuthType == M2M_WIFI_SEC_OPEN ? "OPEN" : "WPA/WPA2");
printf("WPS Channel : %d\n",pstrWPS->u8Ch + 1);
// Establish Wi-Fi connection
m2m_wifi_connect((char*)pstrWPS->au8SSID, (uint8)m2m_strlen(pstrWPS->au8SSID),
pstrWPS->u8AuthType, pstrWPS->au8PSK, pstrWPS->u8Ch);
}
ATWINC15x0
Provisioning
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 69
else
{
printf("(ERR) WPS Is not enabled OR Timedout\n");
}
}
}
int main()
{
tstrWifiInitParam param;
// Platform specific initializations.
// Driver initialization.
param.pfAppWifiCb = wifi_event_cb;
if(!m2m_wifi_init(¶m))
{
// Trigger WPS in Push button mode.
m2m_wifi_wps(WPS_PBC_TRIGGER, NULL);
while(1)
{
m2m_wifi_handle_events(NULL);
}
}
}
ATWINC15x0
Provisioning
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 70
10. Over-The-Air Upgrade
10.1 Overview
The ATWINC15x0 supports OTA upgrade of firmware on internal serial Flash. No host Flash memory
resources are required to store the firmware. The ATWINC15x0 uses an internal HTTP client to retrieve
the firmware from a remote server.
10.2 OTA Image Architecture
The WINC serial Flash can store two copies of the firmware image: a working image and a rollback
image. Upon first-time boot, the working image is the factory image and the rollback image will not be
available in the WINC Flash. Instead ATE firmware will be available in rollback image firmware section.
On performing the OTA firmware upgrade, the ATE firmware will be erased and the newly received
firmware will be written into the Roll back image section. The WINC has insufficient internal memory to
save the whole image in RAM during an OTA upgrade; therefore, each block of downloaded data is
written to the Flash as it is received. In the event that the OTA fails, the existing (Working) image is
retained and the rollback image is invalidated. If the transfer succeeds, the Flash control structure is
updated to reflect a new working image and the existing image is marked as a valid rollback image.
Figure 10-1. OTA Image Organization
ATWINC15x0
Over-The-Air Upgrade
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 71
10.3 OTA Download Sequence Diagram
Figure 10-2. OTA Image Download and Install
10.4 OTA Firmware Rollback
Figure 10-3. OTA Image Rollback Sequence
ATWINC15x0
Over-The-Air Upgrade
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 72
10.5 OTA Limitations
• Rollback is allowed, only after at least one successful OTA download.
• Rollback image is overwritten by any new successful or failed OTA attempt.
10.6 OTA Code Example
/*! */
static void OtaUpdateCb(uint8 u8OtaUpdateStatusType ,uint8 u8OtaUpdateStatus)
{
if(u8OtaUpdateStatusType == DL_STATUS)
{
if(u8OtaUpdateStatus == OTA_STATUS_SUCSESS)
{
//switch to the upgraded firmware
m2m_ota_switch_firmware();
}
}
else if(u8OtaUpdateStatusType == SW_STATUS)
{
if(u8OtaUpdateStatus == OTA_STATUS_SUCSESS)
{
M2M_INFO("Now OTA suceesfully done");
//start the host SW upgrade then system reset is required (Reintilize the driver)
}
}
}
void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg)
{
case M2M_WIFI_REQ_DHCP_CONF:
{
//after suceesfull connection, start the over air upgrade
m2m_ota_start_update(OTA_URL);
}
break;
default:
break;
}
int main (void)
{
tstrWifiInitParam param;
tstr1xAuthCredentials gstrCred1x = AUTH_CREDENTIALS;
nm_bsp_init();
m2m_memset((uint8*)¶m, 0, sizeof(param));
param.pfAppWifiCb = wifi_event_cb;
//intilize the WINC Driver
ret = m2m_wifi_init(¶m);
if (M2M_SUCCESS != ret)
{
M2M_ERR("Driver Init Failed <%d>\n",ret);
while(1);
}
//intilize the ota module
m2m_ota_init(OtaUpdateCb,NULL);
//connect to AP that provide connection to the OTA server
m2m_wifi_default_connect();
while(1)
{
while(m2m_wifi_handle_events(NULL) != M2M_SUCCESS) {}
}
}
Note: For more details on example codes, refer to the Wi-Fi Network Controller Software Programming
Guide.
ATWINC15x0
Over-The-Air Upgrade
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 73
11. Multicast Sockets
11.1 Overview
The purpose of the multicast filters is to provide the ability to send/receive messages to/from multicast
addresses. This feature is useful for one-to-many communication over networks, whether it’s intended to
send Internet Protocol (IP) datagrams to a group of interested receivers in a single transmission,
participate in a zero-configuration networking or listening to a multicast stream or any other application.
11.2 How to Use Filters
Whenever the application wishes to use a multicast IP address, for either sending or receiving, a filter is
needed. The application can establish this through setting the IP_ADD_MEMBERSHIP option for the
required socket accompanied by the multicast address that the application wants to use. If subsequently
the host wants to stop receiving the multicast stream, set the IP_DROP_MEMBERSHIP option for the
required socket accompanied with the multicast address.
Adding or removing a multicast address filter causes the WINC chip firmware to add/remove both MAC
layer filter and IP layer filter in order to pass or prevent messages from reaching to the host.
11.3 Multicast Socket Code Example
To illustrate the functionality, a simple example is implemented where the host application responds to
mDNS (Multicast Domain Name System) queries sent from a computer/mobile application. The computer/
mobile is looking for devices which support the zero configuration service as indicated by an mDNS
response. The WINC responds, notifying its presence and its capability of sending and receiving multicast
messages.
The example consists of a UDP server that binds on port 5353 (mDNS port) and waits for messages,
parsing them and replying with a previously saved response message.
• Server Initialization:
void MDNS_ServerInit()
{
tstrSockAddr strAddr ;
unsigned int MULTICAST_IP = 0xE00000FB; //224.0.0.251
socketInit();
dns_server_sock = socket( AF_INET, SOCK_DGRAM,0);
MDNS_INFO("DNS_server_init \n");
setsockopt(dns_server_sock,1,IP_ADD_MEMBERSHIP,&MULTICAST_IP,sizeof(MULTICAST_IP));
strAddr.u16Port =HTONS(MDNS_SERVER_PORT);
bind(dns_server_sock,(struct sockaddr*)&strAddr,sizeof(strAddr));
registerSocketCallback(UDP_SocketEventHandler,AppServerCb);
}
• Sockets Events Handler:
void MDNS_RecvfromCB(signed char sock,unsigned char *pu8RxBuffer,signed short s16DataSize,
unsigned char *pu8IPAddr,unsigned short u16Port,void *pvArg)
{
MDNS_INFO("DnsServer_RecvfromCB \n");
if((pu8RxBuffer != 0) && (s16DataSize > 0))
{
tstrDnsHdr strDnsHdr;
strdnsquery;
MDNS_INFO("DNS Packet Recieved \n");
ATWINC15x0
Multicast Sockets
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 74
if(MDNS_ParseQuery(&pu8RxBuffer[0], &strDnsHdr,&strDnsQuery))
MDNS_SendResp (sock,pu8IPAddr, u16Port,&strDnsHdr,&strDnsQuery );
}
else
{
MDNS_INFO("DnsServer_RecvfromCB Error !\n");
}
}
• Server Socket Callback:
void MDNS_RecvfromCB(signed char sock,unsigned char *pu8RxBuffer,signed short
s16DataSize,unsigned char *pu8IPAddr,unsigned short u16Port,void *pvArg)
{
MDNS_INFO("DnsServer_RecvfromCB \n");
if((pu8RxBuffer != 0) && (s16DataSize > 0))
{
tstrDnsHdr strDnsHdr ;
strdnsquery ;
MDNS_INFO("DNS Packet Recieved \n");
if(MDNS_ParseQuery(&pu8RxBuffer[0], &strDnsHdr,&strDnsQuery))
MDNS_SendResp (sock,pu8IPAddr, u16Port,&strDnsHdr,&strDnsQuery );
}
else
{
MDNS_INFO("DnsServer_RecvfromCB Error !\n");
}
}
• Parse mDNS Query:
int MDNS_ParseQuery(unsigned char * pu8RxBuffer, tstrDnsHdr *pstrDnsHdr, strdnsquery
*pstrDnsQuery )
{
unsigned char dot_size,temp=0;
unsigned short n=0,i=0,u16index=0;
int bDNSmatch = 0;
/* ----Identification--------------------------|QR| Opcode |AA|TC|RD|RA|Z|AD|CD|
Rcode | */
/* ----Total Questions------------------------|-----------------Total Answer
RRs---------------*/
/* ----Total Authority RRs --------------------|----------------Total Additional
RRs------------*/
/* --------------------------------- Questions
--------------------------------- */
/* ------------------------------------ Answer RRs
------------------------------------------*/
/* ----------------------------------- Authority RRs
----------------------------------*/
/* -----------------------------------Additional RRs
----------------------------------*/
MDNS_INFO("Parsing DNS Packet\n");
pstrDnsHdr->id = (( pu8RxBuffer[u16index]<<8)| (pu8RxBuffer[u16index+1]));
MDNS_INFO ("id = %.4x \n",pstrDnsHdr->id);
u16index+=2;
pstrDnsHdr->flags1= pu8RxBuffer[u16index++];
pstrDnsHdr->flags2= pu8RxBuffer[u16index++];
MDNS_INFO ("flags = %.2x %.2x \n",pstrDnsHdr->flags1,pstrDnsHdr->flags2);
pstrDnsHdr->numquestions = ((pu8RxBuffer[u16index]<<8)| (pu8RxBuffer[u16index+1]));
MDNS_INFO ("numquestions = %.4x \n",pstrDnsHdr->numquestions);
u16index+=2;
pstrDnsHdr->numanswers = ((pu8RxBuffer[u16index]<<8)| (pu8RxBuffer[u16index+1]));
MDNS_INFO ("numanswers = %.4x \n",pstrDnsHdr->numanswers);
u16index+=2;
pstrDnsHdr->numauthrr = ((pu8RxBuffer[u16index]<<8)| (pu8RxBuffer[u16index+1]));
MDNS_INFO ("numauthrr = %.4x \n",pstrDnsHdr->numauthrr);
u16index+=2;
pstrDnsHdr->numextrarr = ((pu8RxBuffer[u16index]<<8)| (pu8RxBuffer[u16index+1]));
MDNS_INFO ("numextrarr = %.4x \n",pstrDnsHdr->numextrarr);
u16index+=2;
dot_size =pstrDnsQuery->query[n++]= pu8RxBuffer[u16index++];
pstrDnsQuery->u16size=1;
ATWINC15x0
Multicast Sockets
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 75
while (dot_size--!=0) //(pu8RxBuffer[++u16index] != 0)
{
pstrDnsQuery->query[n++]=pstrDnsQuery->queryForChecking[i++]=pu8RxBuffer[u16index++] ;
pstrDnsQuery->u16size++;
gu8pos=temp;
if (dot_size == 0 )
{
pstrDnsQuery->queryForChecking[i++]= '.' ;
temp=u16index;
dot_size =pstrDnsQuery->query[n++]= pu8RxBuffer[u16index++];
pstrDnsQuery->u16size++;
}
}
pstrDnsQuery->queryForChecking[--i] = 0;
MDNS_INFO("parsed query <%s>\n",pstrDnsQuery->queryForChecking);
// Search for any match in the local DNS table.
for(n = 0; n < DNS_SERVER_CACHE_SIZE; n++)
{
MDNS_INFO("Saved URL <%s>\n",gpacDnsServerCache[n]);
if(strcmp(gpacDnsServerCache[n], pstrDnsQuery->queryForChecking) ==0)
{
bDNSmatch= 1;
MDNS_INFO("MATCH \n");
}
else
{
MDNS_INFO("Mismatch\n");
}
}
pstrDnsQuery->u16class = ((pu8RxBuffer[u16index]<<8)| (pu8RxBuffer[u16index+1]));
u16index+=2;
pstrDnsQuery->u16type= ((pu8RxBuffer[u16index]<<8)| (pu8RxBuffer[u16index+1]));
return bDNSmatch;
}
• Send mDNS Response:
void MDNS_SendResp (signed char sock,unsigned char * pu8IPAddr,
unsigned short u16Port,tstrDnsHdr *pstrDnsHdr,strdnsquery *pstrDnsQuery)
{
unsigned short u16index=0;
tstrSockAddr strclientAddr ;
unsigned char * pu8sendBuf;
char * serviceName2 = (char*)malloc(sizeof(serviceName)+1);
unsigned int MULTICAST_IP = 0xFB0000E0;
pu8sendBuf= gPu8Buf;
memcpy(&strclientAddr.u32IPAddr,&MULTICAST_IP,IPV4_DATA_LENGTH);
strclientAddr.u16Port=u16Port;
MDNS_INFO("%s \n",pstrDnsQuery->query);
MDNS_INFO("Query Size = %d \n",pstrDnsQuery->u16size);
MDNS_INFO("class = %.4x \n",pstrDnsQuery->u16class);
MDNS_INFO("type = %.4x \n",pstrDnsQuery->u16type);
MDNS_INFO("PREPARING DNS ANSWER BEFORE SENDING\n");
/*----------------------------ID 2 Bytes -----------------------------*/
pu8sendBuf [u16index++] =0; //( pstrDnsHdr->id>>8);
pu8sendBuf [u16index++] = 0;//( pstrDnsHdr->id)&(0xFF);
MDNS_INFO ("(ResPonse) id = %.2x %.2x \n",
pu8sendBuf[u16index-2],pu8sendBuf[u16index-1]);
/*----------------------------Flags 2 Bytes----------------------------*/
pu8sendBuf [u16index++] = DNS_RSP_FLAG_1;
pu8sendBuf [u16index++] = DNS_RSP_FLAG_2;
MDNS_INFO ("(ResPonse) Flags = %.2x %.2x \n",
pu8sendBuf[u16index-2],pu8sendBuf[u16index-1]);
/*----------------------------No of Questions--------------------------*/
pu8sendBuf [u16index++] =0x00;
pu8sendBuf [u16index++] =0x01;
MDNS_INFO ("(ResPonse) Questions = %.2x %.2x \n",
pu8sendBuf[u16index-2],pu8sendBuf[u16index-1]);
/*---------------------------No of Answers----------------------------*/
pu8sendBuf [u16index++] =0x00;
pu8sendBuf [u16index++] =0x01;
MDNS_INFO ("(ResPonse) Answers = %.2x %.2x \n",
pu8sendBuf[u16index-2],pu8sendBuf[u16index-1]);
ATWINC15x0
Multicast Sockets
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 76
/*---------------------------No of Authority RRs------------------------*/
pu8sendBuf [u16index++] =0x00;
pu8sendBuf [u16index++] =0x00;
MDNS_INFO ("(ResPonse) Authority RRs = %.2x %.2x \n",
pu8sendBuf[u16index-2],pu8sendBuf[u16index-1]);
/*----------------------------No of Additional RRs----------------------*/
pu8sendBuf [u16index++] =0x00;
pu8sendBuf [u16index++] =0x00;
MDNS_INFO ("(ResPonse) Additional RRs = %.2x %.2x \n",
pu8sendBuf[u16index-2],pu8sendBuf[u16index-1]);
/*--------------------------------Query-----------------------------*/
memcpy(&pu8sendBuf[u16index],pstrDnsQuery->query,pstrDnsQuery->u16size);
MDNS_INFO("\nsize = %d \n",pstrDnsQuery->u16size);
u16index+=pstrDnsQuery->u16size;
/*-------------------------------Query Type----------------------------*/
pu8sendBuf [u16index++] = ( pstrDnsQuery->u16type>>8);//MDNS_TYPE>>8;
pu8sendBuf [u16index++] = ( pstrDnsQuery->u16type)&(0xFF);//(MDNS_TYPE&0xFF);
MDNS_INFO ("Query Type = %.2x %.2x \n", pu8sendBuf[u16index-2],pu8sendBuf[u16index-1]);
/*------------------------------Query Class-----------------------------------*/
pu8sendBuf [u16index++] =MDNS_CLASS>>8;//(( pstrDnsQuery->u16class>>8)|0x80);
pu8sendBuf [u16index++] = (MDNS_CLASS & 0xFF);//( pstrDnsQuery->u16class)&(0xFF);
MDNS_INFO ("Query Class = %.2x %.2x \n", pu8sendBuf[u16index-2],pu8sendBuf[u16index-1]);
/*########################Answers#########################*/
/*------------------------------Name---------------------------------*/
pu8sendBuf [u16index++]= 0xC0 ; //pointer to query name location
pu8sendBuf [u16index++]= 0x0C ; // instead of writing the whole query name again
/*-----------------------------Type----------------------------------*/
pu8sendBuf [u16index++] =MDNS_TYPE>>8; //Type 12 PTR (domain name Pointer).
pu8sendBuf [u16index++] =(MDNS_TYPE&0xFF);
/*------------------------------Class-----------------------------------*/
pu8sendBuf [u16index++] =0x00;//MDNS_CLASS; //Class IN, Internet.
pu8sendBuf [u16index++] =0x01;// (MDNS_CLASS & 0xFF);
/*-----------------------------TTL----------------------------------*/
pu8sendBuf [u16index++] =(TIME_TO_LIVE >>24);
pu8sendBuf [u16index++] =(TIME_TO_LIVE >>16);
pu8sendBuf [u16index++] =(TIME_TO_LIVE >>8);
pu8sendBuf [u16index++] =(TIME_TO_LIVE );
/*---------------------------Date Length----------------------------------*/
pu8sendBuf [u16index++] =(sizeof(serviceName)+2)>>8;//added 2 bytes for the pointer
pu8sendBuf [u16index++] =(sizeof(serviceName)+2);
/*-----------------------------DATA--------------------------------*/
convertServiceName(serviceName,sizeof(serviceName),serviceName2);
memcpy(&pu8sendBuf[u16index],serviceName2,sizeof(serviceName)+1);
u16index+=sizeof(serviceName);
pu8sendBuf [u16index++] =0xC0;//Pointer to .local (from name)
pu8sendBuf [u16index++] =gu8pos;//23
/*###########################################################*/
strclientAddr.u16Port=HTONS(MDNS_SERVER_PORT);
// MultiCast RESPONSE
sendto( sock, pu8sendBuf,(uint16)u16index,0,(struct
sockaddr*)&strclientAddr,sizeof(strclientAddr));
strclientAddr.u16Port=u16Port;
memcpy(&strclientAddr.u32IPAddr,pu8IPAddr,IPV4_DATA_LENGTH);
}
• Service Name:
static char gpacDnsServerCache[DNS_SERVER_CACHE_SIZE][MDNS_HOSTNAME_SIZE] =
{
"_services._dns-sd._udp.local","_workstation._tcp.local","_http._tcp.local"
};
unsigned char gPu8Buf [MDNS_BUF_SIZE];
unsigned char gu8pos ;
signed char dns_server_sock ;
#define serviceName "_ATMELWIFI._tcp"
ATWINC15x0
Multicast Sockets
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 77
12. WINC Serial Flash Memory
12.1 Overview and Features
The WINC has internal serial (SPI) Flash memory of 4 Mb capacity in the ATWINC1500 and 8 Mb
capacity in the ATWINC1510. The Flash memory is used to store:
• User configuration
• Firmware
• Connection Profiles
During start-up and mode changes, firmware is loaded from the serial Flash into program memory (IRAM)
in which the firmware is executed. The Flash is accessed at other points during run time to retrieve
configuration and profile data.
A minimum of 4 Mb Flash is required for OTA feature in order to store both working and rollback images.
The Flash memory can be read, written and erased directly from the host without co-operation with the
WINC firmware. However, if operational firmware is already loaded, it is necessary to halt any running
WINC firmware first before accessing the serial Flash to avoid access conflict between the host and the
WINC processor.
12.2 Accessing to Serial Flash
• The host has transparent access to the serial (SPI) Flash through the WINC SPI Master.
• The host can program the serial (SPI) Flash without the need for operational firmware in the WINC.
The function m2m_wifi_download_mode must be called first.
Figure 12-1. System Block Diagram showing SPI Flash Connection
12.3 Read/Write/Erase Operations
SPI Flash can be accessed to be read, written and erased.
It is required to change the WINC’s mode to Download mode first before attempting to access the SPI
Flash by calling:
sint32 m2m_wifi_download_mode();
ATWINC15x0
WINC Serial Flash Memory
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 78
All SPI Flash functions are blocking. A return of M2M_SUCCESS indicates that the requested operation is
successfully completed.
The following is a list of Flash functions that may be used:
• Query the size of the SPI Flash:
uint32 spi_flash_get_size();
This function returns with the size of the SPI Flash in Mb.
• Read data from the SPI Flash:
sint8 spi_flash_read(uint8 *pu8Buf, uint32 u32offset, uint32 u32Sz)
Where the size of data is limited by the SPI Flash size.
• Erase sectors in the SPI Flash:
sint8 spi_flash_erase(uint32 u32Offset, uint32 u32Sz)
Note: The size is limited by the SPI Flash size.
Prior to writing to any sector, erase this sector first. If some data needs to be changed within a sector, it is
advised to read the sector first, modify the data and then erase and write the whole sector again.
• Write data to the SPI Flash:
sint8 spi_flash_write(uint8* pu8Buf, uint32 u32Offset, uint32 u32Sz)
If the application wants to write any number of bytes within any sector, it has to erase the entire sector
first. It may be necessary to read the entire sector, erase the sector and then write back with
modifications. It is also recommended to verify that data is written after it returns success by reading data
again and compare it with the original.
12.3.1 Flash Read, Erase, and Write Code Examples
#include "spi_flash.h"
#define DATA_TO_REPLACE "THIS IS A NEW SECTOR IN FLASH"
int main()
{
uint8 au8FlashContent[FLASH_SECTOR_SZ] = {0};
uint32u32FlashTotalSize = 0, u32FlashOffset = 0;
// Platform specific initializations.
ret = m2m_wifi_download_mode();
if(M2M_SUCCESS != ret)
{
printf("Unable to enter download mode\r\n");
}
else
{
u32FlashTotalSize = spi_flash_get_size();
}
while((u32FlashTotalSize > u32FlashOffset) && (M2M_SUCCESS == ret))
{
ret = spi_flash_read(au8FlashContent, u32FlashOffset, FLASH_SECTOR_SZ);
if(M2M_SUCCESS != ret)
{
printf("Unable to read SPI sector\r\n");
break;
}
memcpy(au8FlashContent, DATA_TO_REPLACE, strlen(DATA_TO_REPLACE));
ATWINC15x0
WINC Serial Flash Memory
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 79
ret = spi_flash_erase(u32FlashOffset, FLASH_SECTOR_SZ);
if(M2M_SUCCESS != ret)
{
printf("Unable to erase SPI sector\r\n");
break;
}
ret = spi_flash_write(au8FlashContent, u32FlashOffset, FLASH_SECTOR_SZ);
if(M2M_SUCCESS != ret)
{
printf("Unable to write SPI sector\r\n");
break;
}
u32FlashOffset += FLASH_SECTOR_SZ;
}
if(M2M_SUCCESS == ret)
{
printf("Successful operations\r\n");
}
else
{
printf("Failed operations\r\n");
}
while(1);
return M2M_SUCCESS;
}
ATWINC15x0
WINC Serial Flash Memory
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 80
13. Host Interface (HIF) Protocol
Communication between the user application and the WINC device is facilitated by the driver software.
This driver implements the Host Interface (HIF) Protocol and exposes an API to the application with
various services. The services are broadly divided in two categories: Wi-Fi device control and IP Socket.
The Wi-Fi device control services allow actions such as channel scanning, network identification,
connection and disconnection. The Socket services allow data transfer once a connection is established
and similar to BSD socket definitions.
The host driver implements services asynchronously. This means that when the application calls an API
to request a service action, the call is non-blocking and returns immediately, often before the action is
completed. Where appropriate a notification that an action has completed is provided in a subsequent
message from the WINC device to the host which is delivered to the application via a callback function. In
general, the WINC firmware uses asynchronous events to signal the host driver of certain status
changes. Asynchronous operation is essential where functions (such as Wi-Fi connection) may take
significant time.
When an API is called, a sequence of layers is activated to format the request and arranging to transfer it
to the WINC device through the serial protocol.
Note: Dealing with HIF messages in the host MCU application is an advanced topic. For most
applications, it is recommended to use Wi-Fi and socket layers. Both layers hide the complexity of the HIF
APIs.
After the application sends request, the Host Driver (Wi-Fi/Socket layer) formats the request and sends it
to the HIF layer which then interrupts the WINC device to notify that a new request is posted. Upon
receipt, the WINC firmware parses the request and starts the required operation.
Figure 13-1. WINC Driver Layers
The Host Interface Layer is responsible for handling communication between the host MCU and the
WINC device. This includes interrupt handling, DMA control and management of the communication logic
between the firmware driver in the host and the WINC firmware.
The Request/Response sequence between the host and the WINC chip is shown in the following figure.
ATWINC15x0
Host Interface (HIF) Protocol
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 81
Figure 13-2. The Request/Response Sequence Diagram
13.1 Transfer Sequence Between the HIF Layer and the WINC Firmware
The following section shows the individual steps taken during a HIF frame transmit (HIF message to the
WINC) and a HIF frame receive (HIF message from the WINC).
13.1.1 Frame Transmit
The following figure shows the steps and states involved in sending a message from the host to the
WINC device.
Figure 13-3. HIF Frame Transmit to WINC
ATWINC15x0
Host Interface (HIF) Protocol
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 82
Table 13-1. Steps in HIF Frame Transmit to WINC
Step Description
Step (1) Wake up the
WINC device
Wake up the device to be able to receive the host requests.
Step (2) Interrupt the
WINC device
Prepare and set the HIF layer header to NMI_STATE_REG register (4 bytes
header describing the sent packet).
Set BIT [1] of WIFI_HOST_RCV_CTRL_2 register to raise an interrupt to the
WINC chip.
Step (3) Poll for DMA
address
Wait until the WINC chip clears BIT [1] of WIFI_HOST_RCV_CTRL_2
register.
Get the DMA address (for the allocated memory) from register 0x150400.
Step (4) Write data Write the data blocks in sequence, the HIF header then the Control buffer (if
any) then the Data buffer (if any).
Step (5) TX Done
Interrupt
Send a notification that writing the data is completed by setting BIT [1] of
WIFI_HOST_RCV_CTRL_3 register.
Step (6) Allow the WINC
device to Sleep
Allow the WINC device to enter Sleep mode again (if it wishes).
13.1.2 Frame Receive
The following figure shows the steps and states involved in sending a message from the WINC device to
the host.
Figure 13-4. HIF Frame Receive from WINC to Host
Table 13-2. Steps in HIF Frame Receive from WINC to Host
Step Description
Step (1) Wake up the
WINC device
Wake up the device to be able to receive host requests.
Step (2) Check for
Interrupt
Monitor BIT [0] of WIFI_HOST_RCV_CTRL_0 register.
Disable the host from receiving interrupts (until this interrupt is processed).
Step (3) Clear interrupt Write zero to BIT [0] of WIFI_HOST_RCV_CTRL_0 register.
ATWINC15x0
Host Interface (HIF) Protocol
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 83
...........continued
Step Description
Step (4) Read data Get the address of the data block from WIFI_HOST_RCV_CTRL_1 register.
Read data block with size obtained from WIFI_HOST_RCV_CTRL_0 register
BIT [13] <-> BIT [2].
Step (5) Process
Request
Parse the HIF header at the start of the data and forward the data to the
appropriate registered Callback function.
Step (6) HOST RX Done Raise an interrupt for the chip to free the memory holding the data by setting
BIT [1] of WIFI_HOST_RCV_CTRL_0 register.
Enable host interrupt reception again.
Step (7) Allow the WINC
device to Sleep
Allow the WINC device to enter Sleep mode again (if it wishes).
13.2 HIF Message Header Structure
The HIF message is the data structure exchanged back and forth between the Host Interface and the
WINC firmware. The HIF message header structure consists of three fields:
• The Group ID (8-bit) – a group ID is the category of the message. Valid categories are enumerated
in tenuM2mReqGroup.
• Op Code (8-bit) – is a command number. Valid command number is a value enumerated in:
tenuM2mConfigCmd and tenuM2mStaCmd, tenuM2mApCmd, and tenuM2mP2pCmd
corresponding to configuration, STA mode, AP mode, and P2P mode commands.
Note:
• Refer to the m2m_types.h for the full list of commands.
• The P2P mode is not supported after release v19.5.3.
• Payload Length (16-bit) – the payload length is shown in bytes (does not include header).
13.3 HIF Layer APIs
The interface between the application and the driver is done at the higher layer API interface (Wi-Fi /
Socket.) As explained previously, the driver upper layer uses a lower layer API to access the services of
the Host Interface Protocol. This section describes the Host Interface APIs that the upper layers use:
The following API functions are described:
ATWINC15x0
Host Interface (HIF) Protocol
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 84
• hif_chip_wake
• hif_chip_sleep
• hif_register_cb
• hif_isr
• hif_receive
• hif_send
• hif_set_sleep_mode
• hif_get_sleep_mode
For all functions, the return value is either M2M_SUCCESS (zero) in case of success or a negative value in
case of failure.
• sint8 hif_chip_wake (void) – this function wakes the WINC chip from Sleep mode using
clockless register access. It sets bit '1' of register 0x01 and sets the value of WAKE_REG register
to WAKE_VALUE.
• sint8 hif_chip_sleep (void) – this function enables Sleep mode for the WINC chip by setting
the WAKE_REG register to a value of SLEEP_VALUE and clearing bit '1' of register 0x01.
• sint8 hif_register_cb (uint8 u8Grp, tpfHifCallBack fn) – this function sets the callback
function for different components (for example, M2M_WIFI, M2M_HIF, M2M_OTA and so on.). A
callback is registered by upper layers to receive specific events of a specific message group.
• sint8 hif_isr (void) – this is the host interface interrupt service routine. It handles interrupts
generated by the WINC chip and parses the HIF header to call back the appropriate handler.
• sint8 hif_receive (uint32 u32Addr, uint8 *pu8Buf, uint16 u16Sz, uint8 is Done) – this function
causes the host driver to read data from the WINC chip. The location and length of the data must
be known in advance and specified. This is typically extracted from an earlier part of a transaction.
• sint8 hif_send (uint8 u8Gid, uint8 u8Opcode, uint8 *pu8CtrlBuf, uint16 u16CtrlBufSize, uint8
*pu8DataBuf, uint16 u16DataSize, uint16 16DataOffset) – this function causes the host driver to
send data to the WINC chip. The WINC chip must be prepared for reception according to the flow
described in the previous section.
• void hif_set_sleep_mode (uint8 u8Pstype) – this function is used to set the Sleep mode of the
HIF layer.
• uint8 hif_get_sleep_mode (void) – this function return the Sleep mode of the HIF layer.
13.4 Scan Code Example
The following code example illustrates the Request/Response flow on a Wi-Fi Scan request.
Note: For more details on example codes, refer to the Wi-Fi Network Controller Software Programming
Guide.
• The application requests a Wi-Fi scan.
{
m2m_wifi_request_scan(M2M_WIFI_CH_ALL);
}
• The host driver Wi-Fi layer formats the request and forward it to HIF (Host Interface) layer.
sint8 m2m_wifi_request_scan(uint8 ch)
{
tstrM2MScan strtmp;
sint8 s8Ret = M2M_ERR_SCAN_IN_PROGRESS;
ATWINC15x0
Host Interface (HIF) Protocol
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 85
strtmp.u8ChNum = ch;
s8Ret = hif_send(M2M_REQ_GRP_WIFI, M2M_WIFI_REQ_SCAN, (uint8*)&strtmp,
sizeof(tstrM2MScan),NULL, 0,0);
return s8Ret;
}
• The HIF layer sends the request to the WINC chip.
sint8 hif_send(uint8 u8Gid,uint8 u8Opcode,uint8 *pu8CtrlBuf,uint16 u16CtrlBufSize,
uint8 *pu8DataBuf,uint16 u16DataSize, uint16 u16DataOffset)
{
sint8 ret = M2M_ERR_SEND;
volatile tstrHifHdr strHif;
strHif.u8Opcode = u8Opcode&(~NBIT7);
strHif.u8Gid = u8Gid;
strHif.u16Length = M2M_HIF_HDR_OFFSET;
if(pu8DataBuf != NULL)
{
strHif.u16Length += u16DataOffset + u16DataSize;
}
else
{
strHif.u16Length += u16CtrlBufSize;
}
/* TX STEP (1) */
ret = hif_chip_wake();
if(ret == M2M_SUCCESS)
{
volatile uint32 reg, dma_addr = 0;
volatile uint16 cnt = 0;
reg = 0UL;
reg |= (uint32)u8Gid;
reg |= ((uint32)u8Opcode<<8);
reg |= ((uint32)strHif.u16Length<<16);
ret = nm_write_reg(NMI_STATE_REG,reg);
if(M2M_SUCCESS != ret) goto ERR1;
reg = 0;
/* TX STEP (2) */
reg |= (1<<1);
ret = nm_write_reg(WIFI_HOST_RCV_CTRL_2, reg);
if(M2M_SUCCESS != ret) goto ERR1;
dma_addr = 0;
for(cnt = 0; cnt < 1000; cnt ++)
{
ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_2,(uint32 *)®);
if(ret != M2M_SUCCESS) break;
if (!(reg & 0x2))
{
/* TX STEP (3) */
ret = nm_read_reg_with_ret(0x150400,(uint32 *)&dma_addr);
if(ret != M2M_SUCCESS) {
/*in case of read error clear the dma address and return error*/
dma_addr = 0;
}
/*in case of success break */
break;
}
}
if (dma_addr != 0)
{
volatile uint32 u32CurrAddr;
u32CurrAddr = dma_addr;
strHif.u16Length=NM_BSP_B_L_16(strHif.u16Length);
/* TX STEP (4) */
ret = nm_write_block(u32CurrAddr, (uint8*)&strHif, M2M_HIF_HDR_OFFSET);
if(M2M_SUCCESS != ret) goto ERR1;
u32CurrAddr += M2M_HIF_HDR_OFFSET;
if(pu8CtrlBuf != NULL)
{
ret = nm_write_block(u32CurrAddr, pu8CtrlBuf, u16CtrlBufSize);
if(M2M_SUCCESS != ret) goto ERR1;
u32CurrAddr += u16CtrlBufSize;
}
ATWINC15x0
Host Interface (HIF) Protocol
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 86
if(pu8DataBuf != NULL)
{
u32CurrAddr += (u16DataOffset - u16CtrlBufSize);
ret = nm_write_block(u32CurrAddr, pu8DataBuf, u16DataSize);
if(M2M_SUCCESS != ret) goto ERR1;
u32CurrAddr += u16DataSize;
}
reg = dma_addr << 2;
reg |= (1 << 1);
/* TX STEP (5) */
ret = nm_write_reg(WIFI_HOST_RCV_CTRL_3, reg);
if(M2M_SUCCESS != ret) goto ERR1;
}
else
{
/* ERROR STATE */
M2M_DBG("Failed to alloc rx size\r");
ret = M2M_ERR_MEM_ALLOC;
goto ERR1;
}
}
else
{
M2M_ERR("(HIF)Fail to wakup the chip\n");
goto ERR1;
}
/* TX STEP (6) */
ret = hif_chip_sleep();
ERR1:
return ret;
}
• The WINC chip processes the request and interrupts the host after finishing the operation.
• The HIF layer then receives the response.
static sint8 hif_isr(void)
{
sint8 ret = M2M_ERR_BUS_FAIL;
uint32 reg;
volatile tstrHifHdr strHif;
/* RX STEP (1) */
ret = hif_chip_wake();
if(ret == M2M_SUCCESS)
{
/* RX STEP (2) */
ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_0, ®);
if(M2M_SUCCESS == ret)
{
/* New interrupt has been received */
if(reg & 0x1)
{
uint16 size;
nm_bsp_interrupt_ctrl(0);
/*Clearing RX interrupt*/
ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_0,®);
if(ret != M2M_SUCCESS)goto ERR1;
reg &= ~(1<<0);
/* RX STEP (3) */
ret=nm_write_reg(WIFI_HOST_RCV_CTRL_0,reg);
if(ret != M2M_SUCCESS)goto ERR1;
/* read the rx size */
ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_0, ®);
if(M2M_SUCCESS != ret)
{
M2M_ERR("(hif) WIFI_HOST_RCV_CTRL_0 bus fail\n");
nm_bsp_interrupt_ctrl(1);
goto ERR1;
}
gu8HifSizeDone = 0;
size = (uint16)((reg >> 2) & 0xfff);
if (size > 0)
{
uint32 address = 0;
/** start bus transfer **/
ATWINC15x0
Host Interface (HIF) Protocol
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 87
/* RX STEP (4) */
ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_1, &address);
if(M2M_SUCCESS != ret)
{
M2M_ERR("(hif) WIFI_HOST_RCV_CTRL_1 bus fail\n");
nm_bsp_interrupt_ctrl(1);
goto ERR1;
}
ret = nm_read_block(address, (uint8*)&strHif, sizeof(tstrHifHdr));
strHif.u16Length = NM_BSP_B_L_16(strHif.u16Length);
if(M2M_SUCCESS != ret)
{
M2M_ERR("(hif) address bus fail\n");
nm_bsp_interrupt_ctrl(1);
goto ERR1;
}
if(strHif.u16Length != size)
{
if((size - strHif.u16Length) > 4)
{
M2M_ERR("(hif) Corrupted packet Size = %u \n",
size, strHif.u16Length, strHif.u8Gid, strHif.u8Opcode);
nm_bsp_interrupt_ctrl(1);
ret = M2M_ERR_BUS_FAIL;
goto ERR1;
}
}
/* RX STEP (5) */
if(M2M_REQ_GRP_WIFI == strHif.u8Gid)
{
if(pfWifiCb)
{
pfWifiCb(strHif.u8Opcode,strHif.u16Length - M2M_HIF_HDR_OFFSET,
address + M2M_HIF_HDR_OFFSET);
}
}
else if(M2M_REQ_GRP_IP == strHif.u8Gid)
{
if(pfIpCb)
{
pfIpCb(strHif.u8Opcode,strHif.u16Length - M2M_HIF_HDR_OFFSET,
address + M2M_HIF_HDR_OFFSET);
}
}
else if(M2M_REQ_GRP_OTA == strHif.u8Gid)
{
if(pfOtaCb)
{
pfOtaCb(strHif.u8Opcode,strHif.u16Length - M2M_HIF_HDR_OFFSET,
address + M2M_HIF_HDR_OFFSET);
}
}
else
{
M2M_ERR("(hif) invalid group ID\n");
ret = M2M_ERR_BUS_FAIL;
goto ERR1;
}
/* RX STEP (6) */
if(!gu8HifSizeDone)
{
M2M_ERR("(hif) host app didn't set RX Done\n");
ret = hif_set_rx_done();
}
}
else
{
ret = M2M_ERR_RCV;
M2M_ERR("(hif) Wrong Size\n");
goto ERR1;
}
}
else
ATWINC15x0
Host Interface (HIF) Protocol
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 88
{
#ifndef WIN32
M2M_ERR("(hif) False interrupt %lx",reg);
#endif
}
}
else
{
M2M_ERR("(hif) Fail to Read interrupt reg\n");
goto ERR1;
}
}
else
{
M2M_ERR("(hif) FAIL to wakeup the chip\n");
goto ERR1;
}
/* RX STEP (7) */
ret = hif_chip_sleep();
ERR1:
return ret;
}
• The appropriate handler in the Wi-Fi layer (called from the HIF layer).
static void m2m_wifi_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr)
{ // …code eliminated…
else if (u8OpCode == M2M_WIFI_RESP_SCAN_DONE)
{
tstrM2mScanDone strState;
gu8scanInProgress = 0;
if(hif_receive(u32Addr, (uint8*)&strState, sizeof(tstrM2mScanDone), 0) == M2M_SUCCESS)
{
gu8ChNum = strState.u8NumofCh;
if (gpfAppWifiCb)
gpfAppWifiCb(M2M_WIFI_RESP_SCAN_DONE, &strState);
}
}
// …code eliminated…
}
• The Wi-Fi layer sends the response to the application through its callback function.
if (u8MsgType == M2M_WIFI_RESP_SCAN_DONE)
{
tstrM2mScanDone *pstrInfo = (tstrM2mScanDone*) pvMsg;
if( (gu8IsWiFiConnected == M2M_WIFI_DISCONNECTED) &&
(gu8WPS == WPS_DISABLED) && (gu8Prov == PROV_DISABLED) )
{
gu8Index = 0;
gu8Sleep = PS_WAKE;
if (pstrInfo->u8NumofCh >= 1)
{
m2m_wifi_req_scan_result(gu8Index);
gu8Index++;
}
else
{
m2m_wifi_request_scan(M2M_WIFI_CH_ALL);
}
}
}
ATWINC15x0
Host Interface (HIF) Protocol
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 89
14. WINC SPI Protocol
The WINC main interface is SPI. The WINC device employs a protocol to allow exchange of formatted
binary messages between the WINC firmware and the host MCU application. The WINC protocol uses
raw bytes exchanged on the SPI bus to form high level structures like requests and callbacks.
The WINC SPI protocol consists of three layers:
• Layer 1 – the WINC SPI Slave protocol, which allows the host MCU application to perform register/
memory read and write operation in the ATWINC15x0 device using raw SPI data exchange.
• Layer 2 – the host MCU application uses the register and memory read and write capabilities to
exchange the host interface frames with the WINC firmware. It also provides asynchronous
callback from the WINC firmware to the host MCU through interrupts and the host interface RX
frames. For more information on this layer, refer to Section 15 “Host Interface (HIF) Protocol”.
• Layer 3 – allows the host MCU application to exchange high level messages (for example, Wi-Fi
scan, socket connection, or TCP data received) with the WINC firmware to employ in the host MCU
application logic.
Figure 14-1. WINC SPI Protocol Layers
14.1 Introduction
The WINC SPI Protocol is implemented as a command-response transaction and assumes one party is
the Master and the other is the Slave. The roles correspond to the Master and Slave devices on the SPI
bus. Each message has an identifier in the first byte indicating the type of message:
• Command
• Response
ATWINC15x0
WINC SPI Protocol
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 90
• Data
In the case of Command and Data messages, the last byte is used as data integrity check.
The format of Command and Response and Data frames are described in the following sections. The
following points apply:
• There is a response for each command.
• Transmitted/received data is divided into packets with fixed size.
• For a WR transaction (Slave is receiving data packets), the Slave sends a response for each data
packet.
• For a RD transaction (Master is receiving data packets), the Master does not send a response. If
there is an error, the Master requests a retransmission on the lost data packet.
• Protection of commands and data packets by CRC is optional.
14.1.1 Command Format
The following frame format is used for commands where the host supports a DMA address of three bytes.
The first byte contains two fields:
• The CMD/Data Start field indicates that this is a Command frame.
• The CMD type field specifies the command to be executed.
The CMD type may be one of 15 commands:
• DMA write
• DMA read
• Internal register write
• Internal register read
• Transaction termination
• Repeat data packet
• DMA extended write
• DMA extended read
• DMA single-word write
• DMA single-word read
• Soft Reset
The Payload field contains command specific data and its length depends on the CMD type.
The CRC field is optional and generally computed in software.
The Payload field can be one of four types each having a different length:
• A: Three bytes
• B: Five bytes
• C: Six bytes
• D: Seven bytes
ATWINC15x0
WINC SPI Protocol
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 91
Type A commands include:
• DMA single-word RD
• internal register RD
• Transaction termination command
• Repeat data PKT command
• Soft Reset command
Type B commands include:
• DMA RD Transaction
• DMA WR Transaction
Type C commands include:
• DMA Extended RD transaction
• DMA Extended WR transaction
• Internal register WR
Type D commands include:
• DMA single-word WR
Full details of the frame format fields are provided in the following table:
Table 14-1. Frame Format Fields
Field Size Description
CMD Start 4 bits Command Start: 4’b1100
CMD Type 4 bits Command type:
4’b0001: DMA write transaction
4’b0010: DMA read transaction
4’b0011: Internal register write
4’b0100: Internal register read
4’b0101: Transaction termination
4’b0110: Repeat data Packet
command
4’b0111: DMA extended write
transaction
4’b1000: DMA extended read
transaction
4’b1001: DMA single-word write
4’b1010: DMA single-word read
4’b1111: Soft Reset command
ATWINC15x0
WINC SPI Protocol
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 92
...........continued
Field Size Description
Payload A: 3 The Payload field may be of Type
A, B, C, or D
Type A (length 3)
1- DMA single-word RD
Param: Read Address:
Payload bytes:
B0: ADDRESS[23:16]
B1: ADDRESS[15:8]
B2: ADDRESS[7:0]
2- internal register RD
Param: Offset address (two
bytes):
Payload bytes:
B0: OFFSET-ADDR[15:8]
B1: OFFSET-ADDR[7:0]
B2: 0
3- Transaction termination
command
Param: none
Payload bytes:
B0: 0
B1: 0
B2: 0
4- Repeat Data PKT command
Param: none
Payload bytes:
B0: 0
B1: 0
B2: 0
5- Soft Reset command
Param: none
Payload bytes:
B0: 0xFF
B1: 0xFF
B2: 0xFF
ATWINC15x0
WINC SPI Protocol
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 93
...........continued
Field Size Description
Payload B: 5 Type B (length 5)
1- DMA RD Transaction
Params:
DMA Start Address: 3 bytes
DMA count: 2 bytes
Payload bytes:
B0: ADDRESS[23:16]
B1: ADDRESS[15:8]
B2: ADDRESS[7:0]
B3: COUNT[15:8]
B4: COUNT[7:0]
2- DMA WR Transaction
Params:
DMA Start Address: 3 bytes
DMA count: 2 bytes
Payload bytes:
B0: ADDRESS[23:16]
B1: ADDRESS[15:8]
B2: ADDRESS[7:0]
B3: COUNT[15:8]
B4: COUNT[7:0]
ATWINC15x0
WINC SPI Protocol
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 94
...........continued
Field Size Description
Payload C: 6 Type C (length 6)
1- DMA Extended RD
transaction
Params:
DMA Start Address: 3 bytes
DMA extended count: 3 bytes
Payload bytes:
B0: ADDRESS[23:16]
B1: ADDRESS[15:8]
B2: ADDRESS[7:0]
B3: COUNT[23:16]
B4: COUNT[15:8]
B5: COUNT[7:0]
2- DMA Extended WR
transaction
Params:
DMA Start Address: 3 bytes
DMA extended count: 3 bytes
Payload bytes:
B0: ADDRESS[23:16]
B1: ADDRESS[15:8]
B2: ADDRESS[7:0]
B3: COUNT[23:16]
B4: COUNT[15:8]
B5: COUNT[7:0]
ATWINC15x0
WINC SPI Protocol
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 95
...........continued
Field Size Description
Payload C: 6 3- Internal register WR*
Params:
Offset address: 3 bytes
Write data: 3 bytes
* “clocked or clockless registers”
Payload bytes:
B0: OFFSET-ADDR[15:8]
B1: OFFSET-ADDR [7:0]
B2: DATA[31:24]
B3: DATA [23:16]
B4: DATA [15:8]
B5: DATA [7:0]
Payload D: 7 Type D (length 7)
1- DMA single-word WR
Params:
Address: 3 bytes
DMA Data: 4 bytes
Payload bytes:
B0: ADDRESS[23:16]
B1: ADDRESS[15:8]
B2: ADDRESS[7:0]
B3: DATA[31:24]
B4: DATA [23:16]
B5: DATA [15:8]
B6: DATA [7:0]
CRC7 1 byte Optional data integrity field
comprising two subfields:
bit 0: fixed value ‘1’
bits 1-7: 7 bit CRC value
computed using polynomial G(x)
= X^7 + X^3 + 1 with seed value:
0x7F
ATWINC15x0
WINC SPI Protocol
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 96
The following table summarizes the different commands according to the payload type (DMA address = 3
bytes):
Table 14-2. Commands in Payload
Payload Type Payload Size Command Packet Size with CRC Commands
Type A 3 bytes 5 bytes 1- DMA Single-Word Read
2- Internal Register Read
3- Transaction Termination
4- Repeat Data Packet
5- Soft Reset
Type B 5 bytes 7 bytes 1- DMA Read
2- DMA Write
Type C 6 bytes 8 bytes 1- DMA Extended Read
2- DMA Extended Write
3- Internal Register Write
Type D 7 bytes 9 bytes 1- DMA Single-Word Write
14.1.2 Response Format
The following frame format is used for responses sent by the WINC device as the result of receiving a
Command or certain Data frames. The Response message has a fixed length of two bytes.
The first byte contains two fields of four bits each to identify the response message and the response
type.
The second byte indicates the status of the WINC after receiving and, where possible, executing the
command/data. This byte contains two sub fields:
• B0-B3: Error state
• B4-B7: DMA state
States that may be indicated are:
• DMA state:
– DMA ready for any transaction
– DMA engine is busy
• Error state:
– No error
– Unsupported command
– Receiving unexpected data packet
– Command CRC7 error
ATWINC15x0
WINC SPI Protocol
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 97
Table 14-3. Response Format
Field Size Description
Response Start 4 bits Response Start : 4’b1100
Response Type 4 bits If the response packet is for Command:
• Contains of copy of the Command Type field in the Command.
If the response packet is for received Data Packet:
• 4’b0001: first data packet is received
• 4’b0010: Receiving data packets
• 4’b0011: last data packet is received
• 4’b1111: Reserved value
State 1 byte This field is divided into two subfields:
DMA State :
• 4’b0000: DMA ready for any transaction
• 4’b0001: DMA engine is busy
Error State:
• 4’b0000: No error
• 4’b0001: Unsupported command
• 4’b0010: Receiving unexpected data packet
• 4’b0011: Command CRC7 error
• 4’b0100: Data CRC16 error
• 4’b0101: Internal general error
14.1.3 Data Packet Format
The Data Packet Format is used in either direction (Master to Slave or Slave to Master) to transfer
opaque data. A command frame is used either to inform the Slave that a data packet is about to be sent
or to request the Slave to send a data packet to the Master. In the case of Master to Slave, the Slave
sends a response after the command and each subsequent data frame. The format of a data packet is
shown below.
To support DMA hardware, a large data transfer may be fragmented into multiple smaller Data Packets.
This is controlled by the value of DATA_PACKET_SIZE which is agreed between the Master and the
Slave in software and is a fixed value such as 256B, 512B, 1KB (default), 2KB, 4KB, or 8KB. If a transfer
has a length of m, which exceeds DATA_PACKET_SIZE, the sender must split it into multiple
DATA_PACKET_SIZE as shown in Equation 1:
ATWINC15x0
WINC SPI Protocol
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 98
(m – (n-1)* DATA_PACKET_SIZE) -------------------------- Equation 1
Where,
1.. n-1 = length of the DATA_PACKET_SIZE
n = frame length
This is illustrated below.
• If DMA count <= DATA_PACKET_SIZE:
The data packet is “DATA_Header + DMA count +optional CRC16“, that is no padding.
• If DMA count > DATA_PACKET_SIZE:
• If remaining data < DATA_PACKET_SIZE, the last data packet is:
“DATA_Header + remaining data + optional CRC16 “, that is no padding.
The frame fields are described in detail in the following table:
Table 14-4. Frame Field
Field Size Description
Data Start 4 bits 4’b1111 (Default)
(Can be changed to any value by programming
DATA_START_CTRL register)
Packet
Order
4 bits 4’b0001: First packet in this transaction
4’b0010: Neither the first or the last packet in this transaction
4’b0011: Last packet in this transaction
4’b1111: Reserved
Data bytes DATA_PACKET_SIZE User data
CRC16 2 bytes Optional data integrity field comprising a 16-bit CRC value
encoded in two bytes. The most significant 8 bits are transmitted
first in the frame.
The CRC16 value is computed on data bytes only based on the
polynomial:
G(x) = X^16 + X^12 + X^5 + 1, seed value: 0xFFFF
ATWINC15x0
WINC SPI Protocol
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 99
14.1.4 Error Recovery Mechanism
Table 14-5. Error Recovery Mechanism
Error Type Recovery Mechanism
Master
CRC error in
command
1. Error response received from Slave.
2. Retransmit the command.
CRC error in received
data
1. Issue a repeat command for the data packet that has a CRC error.
2. Slave sends a response to the previous command.
3. Slave keeps the start DMA address of the previous data packet, so it can
retransmit it.
4. Receive the data packet again.
No response is
received from Slave
• Synchronization is lost between the Master and Slave.
• The worst case is when Slave is in receiving data state.
• Solution: The Master must wait for max DATA_PACKET_SIZE period
then generate a Soft Reset command.
Unexpected response Retransmit the command.
TX/RX Data count
error
Retransmit the command.
No response to Soft
Reset command
• Transmit all ones until Master receives a response of all ones from the
Slave.
• Then deactivate the output data line.
Slave
Unsupported
command
• Send response with error.
• Returns to command monitor state.
Receive command
CRC error
• Send response with error.
• Wait for command retransmission.
Received data CRC
error
• Send response with error.
• Wait for retransmission of the data packet.
Internal general error • The Master must do a Soft Reset on the Slave.
TX/RX Data count
error
• Only the Master can detect this error.
• Slave operates with the data count received until the count finishes or the
Master terminates the transaction.
• In both cases, the Master can retry the command from the start.
ATWINC15x0
WINC SPI Protocol
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 100
...........continued
Error Type Recovery Mechanism
No response to Soft
Reset command
1. First received 4’b1001, it decides data start.
2. Then received packet order 4’b1111 that is reserved value.
3. Then monitors for 7 bytes all ones to decide Soft Reset action.
4. The Slave must activate the output data line.
5. Waits for deactivation for the received line.
6. The Slave then deactivates the output data line and returns to the CMD/
DATA start monitor state.
General Notes • The Slave must monitor the received line for command reception at any
time.
• When a CMD start is detected, the Slave receives 8 bytes then return
again to the command reception state.
• When the Slave is transmitting data, it must also monitor for command
reception.
• When the Slave is receiving data, it monitors for command reception
between the data packets.
• Issuing a Soft Reset command is detected in all cases.
14.1.5 Clockless Registers Access
Clockless register access allows a host device to access registers on the WINC device while it is held in a
reset state. This type of access can only be done using the “internal register read” and “internal register
write” commands. For clockless access, bit 15 of the Offset_addr in the command must be ‘1’ to
differentiate between the Clockless and Clocked access mode.
For Clockless register write: - the protocol Master must wait for the response as shown here:
For Clockless register read: - according to the interface, the protocol Slave may not send CRC16. One or
two byte padding depends on three or four byte DMA addresses.
14.2 Message Flow for Basic Transactions
This section shows the essential message exchanges and timings associated with the following
commands:
• Read Single Word
• Read Internal Register (clockless)
ATWINC15x0
WINC SPI Protocol
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 101
• Read Block
• Write Single Word
• Write Internal Register (clockless)
• Write Bock
14.2.1 Read Single Word
14.2.2 Read Internal Register (for clockless registers)
14.2.3 Read Block
Normal transaction:
Master - issues a DMA read transaction and waits for a response.
Slave - sends a response after CMD_RES_PERIOD.
Master - waits for a data packet start.
Slave - sends the data packets, separated by DATA_DATA_PERIOD[1] where DATA_DATA_PERIOD is
controlled by software and has one of these values: NO_DELAY (default), 4_BYTE_PERIOD,
8_BYTE_PERIOD, and 16_BYTE_PERIOD.
Slave - continues sending until the count ends.
Master - receives data packets. No response is sent for data packets but a termination/retransmit
command may be sent if there is an error.
The message sequence for this case is shown below:
Termination command is issued:
Master - can issue a termination command at any time during the transaction.
ATWINC15x0
WINC SPI Protocol
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 102
Master - monitors for RES_START after CMD_RESP_PERIOD.
Slave - cuts off the current running data packet if there is any.
Slave - responds to the termination command after CMD_RESP_PERIOD from the end of the
termination command packet.
Repeat command is issued:
1. Master - can issue a repeat command at any time during the transaction.
2. Master - monitors for RES_START after CMD_RESP_PERIOD.
3. Slave - cuts off the current running data packet, if any.
4. Slave - responds to the repeat command after CMD_RESP_PERIOD from the end of the repeat
command packet.
5. Slave - sends the data packet again that has an error then continues the transaction as normal.
[1] The period between the data packets is “DATA_DATA_PERIOD + DMA access time.” The Master
monitors for DATA_START directly after DATA_DATA_PERIOD.
14.2.4 Write Single Word
1. Master - issues DMA single-word write command, including the data.
2. Slave - takes the data and sends a command response.
14.2.5 Write Internal Register (for clockless registers)
1. Master - issues an internal register write command, including the data.
ATWINC15x0
WINC SPI Protocol
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 103
2. Slave - takes the data and sends a command response.
14.2.6 Write Block
• Case 1: Master waits for a command response:
1.1. Master - issues a DMA write command and waits for a response.
1.2. Slave - sends response after CMD_RES_PERIOD.
1.3. Master - sends the data packets after receiving response.
1.4. Slave - sends a response packet for each data packet received after
DATA_RES_PERIOD.
1.5. Master - does not wait for the data response before sending the following data packet
notes:
CMD_RES_PERIOD is controlled by SW taking one of the values:
NO_DELAY (default), 1_BYTE_PERIOD, 2_BYTE_PERIOD and 3_BYTE_PERIOD
The Master must monitor for RES_START after CMD_RES_PERIOD
DATA_RES_PERIOD is controlled by SW taking one of the values:
NO_DELAY (default), 1_BYTE_PERIOD, 2_BYTE_PERIOD and 3_BYTE_PERIOD
• Case 2: Master does not wait for a command response:
2.1. Master - sends the data packets directly after the command but it still monitors for a
command response after CMD_RESP_PERIOD.
2.2. Master - retransmits the data packets if there is an error in the command.
ATWINC15x0
WINC SPI Protocol
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 104
14.3 SPI Level Protocol Example
To illustrate how the WINC SPI protocol works, the SPI bytes from the scan request example are dumped
and the sequence is described below.
14.3.1 TX (Send Request)
1. First step in hif_send() API is to wake up the chip.
sint8 nm_clkless_wake(void)
{
ret = nm_read_reg_with_ret(0x1, ®);
/* Set bit 1 */
ret = nm_write_reg(0x1, reg | (1 << 1));
// Check the clock status
ret = nm_read_reg_with_ret(clk_status_reg_adr, &clk_status_reg);
// Tell Firmware that Host waked up the chip
ret = nm_write_reg(WAKE_REG, WAKE_VALUE);
return ret;
}
Command CMD_INTERNAL_READ: 0xC4 /* internal register read */
BYTE [0] = CMD_INTERNAL_READ
BYTE [1] = address >> 8; /* address = 0x01 */
BYTE [1] |= (1 << 7); /* clockless register */
BYTE [2] = address;
BYTE [3] = 0x00;
2. The WINC acknowledges the command by sending three bytes [C4] [0] [F3].
3. The WINC chip sends the value of the register 0x01 which equals 0x01.
ATWINC15x0
WINC SPI Protocol
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 105
Command CMD_INTERNAL_WRITE: C3 /* internal register write */
BYTE [0] = CMD_INTERNAL_WRITE
BYTE [1] = address >> 8; /* address = 0x01 */
BYTE [1] |= (1 << 7); /* clockless register */
BYTE [2] = address;
BYTE [3] = u32data >> 24; /* Data = 0x03 */
BYTE [4] = u32data >> 16;
BYTE [5] = u32data >> 8;
BYTE [6] = u32data;
4. The WINC acknowledges the command by sending two bytes [C3] [0].
Command CMD_INTERNAL_READ: 0xC4 /* internal register read */
BYTE [0] = CMD_INTERNAL_READ
BYTE [1] = address >> 8; /* address = 0x0F */
BYTE [1] |= (1 << 7); /* clockless register */
BYTE [2] = address;
BYTE [3] = 0x00;
5. The WINC acknowledges the command by sending three bytes [C4] [0] [F3].
6. The WINC chip sends the value of the register 0x01 which equals 0x07.
ATWINC15x0
WINC SPI Protocol
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 106
Command CMD_SINGLE_WRITE:0XC9 /* single word write */
BYTE [0] = CMD_SINGLE_WRITE
BYTE [1] = address >> 16; /* WAKE_REG address = 0x1074 */
BYTE [2] = address >> 8;
BYTE [3] = address;
BYTE [4] = u32data >> 24; /* WAKE_VALUE Data = 0x5678 */
BYTE [5] = u32data >> 16;
BYTE [6] = u32data >> 8;
BYTE [7] = u32data;
7. The chip acknowledges the command by sending two bytes [C9] [0].
8. At this point, HIF finishes executing the clockless wake up of the WINC chip.
9. The HIF layer prepares and sets the HIF layer header to NMI_STATE_REG register (4 byte or 8
byte header describing the packet to be sent).
10. Set bit '1' of WIFI_HOST_RCV_CTRL_2 register to raise an interrupt to the chip.
sint8 hif_send(uint8 u8Gid,uint8 u8Opcode,uint8 *pu8CtrlBuf,uint16 u16CtrlBufSize,
uint8 *pu8DataBuf,uint16 u16DataSize, uint16 u16DataOffset)
{
volatile tstrHifHdr strHif;
volatile uint32 reg;
strHif.u8Opcode = u8Opcode&(~NBIT7);
strHif.u8Gid = u8Gid;
strHif.u16Length = M2M_HIF_HDR_OFFSET;
strHif.u16Length += u16CtrlBufSize;
ret = nm_clkless_wake();
reg = 0UL;
reg |= (uint32)u8Gid;
reg |= ((uint32)u8Opcode<<8);
reg |= ((uint32)strHif.u16Length<<16);
ret = nm_write_reg(NMI_STATE_REG,reg);
ATWINC15x0
WINC SPI Protocol
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 107
reg = 0;
reg |= (1<<1);
ret = nm_write_reg(WIFI_HOST_RCV_CTRL_2, reg);
Command CMD_SINGLE_WRITE:0XC9 /* single word write */
BYTE [0] = CMD_SINGLE_WRITE
BYTE [1] = address >> 16; /* NMI_STATE_REG address = 0x108c */
BYTE [2] = address >> 8;
BYTE [3] = address;
BYTE [4] = u32data >> 24; /* Data = 0x000C3001 */
BYTE [5] = u32data >> 16; /* 0x0C is the length and equals 12 */
BYTE [6] = u32data >> 8; /* 0x30 is the Opcode =
M2M_WIFI_REQ_SET_SCAN_REGION */
BYTE [7] = u32data; /* 0x01 is the Group ID = M2M_REQ_GRP_WIFI */
11. The WINC acknowledges the command by sending two bytes [C9] [0].
Command CMD_SINGLE_WRITE:0XC9 /* single word write */
BYTE [0] = CMD_SINGLE_WRITE
BYTE [1] = address >> 16; /* WIFI_HOST_RCV_CTRL_2address = 0x1078*/
BYTE [2] = address >> 8;
BYTE [3] = address;
BYTE [4] = u32data >> 24; /* Data = 0x02 */
BYTE [5] = u32data >> 16;
BYTE [6] = u32data >> 8;
BYTE [7] = u32data;
ATWINC15x0
WINC SPI Protocol
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 108
12. The WINC acknowledges the command by sending two bytes [C9] [0].
13. Then HIF polls for DMA address.
for (cnt = 0; cnt < 1000; cnt ++)
{
ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_2,(uint32 *)®);
if(ret != M2M_SUCCESS) break;
if (!(reg & 0x2))
{
ret = nm_read_reg_with_ret(0x150400,(uint32 *)&dma_addr);
/*in case of success break */
break;
}
}
Command CMD_SINGLE_READ: 0xCA /* single word (4 bytes) read */
BYTE [0] = CMD_SINGLE_READ
BYTE [1] = address >> 16; /* WIFI_HOST_RCV_CTRL_2 address = 0x1078 */
BYTE [2] = address >> 8;
BYTE [3] = address;
14. The WINC acknowledges the command by sending three bytes [CA] [0] [F3].
15. The WINC chip sends the value of the register 0x1078, which equals 0x00.
ATWINC15x0
WINC SPI Protocol
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 109
Command CMD_SINGLE_READ: 0xCA /* single word (4 bytes) read */
BYTE [0] = CMD_SINGLE_READ
BYTE [1] = address >> 16; /* address = 0x1504 */
BYTE [2] = address >> 8;
BYTE [3] = address;
16. The WINC acknowledges the command by sending three bytes [CA] [0] [F3].
17. The WINC chip sends the value of the register 0x1504, which equals 0x037AA0.
18. The WINC writes the HIF header to the DMA memory address.
u32CurrAddr = dma_addr;
strHif.u16Length=NM_BSP_B_L_16(strHif.u16Length);
ret = nm_write_block(u32CurrAddr, (uint8*)&strHif, M2M_HIF_HDR_OFFSET);
Command CMD_DMA_EXT_WRITE: 0xC7 /* DMA extended write */
BYTE [0] = CMD_DMA_EXT_WRITE
BYTE [1] = address >> 16; /* address = 0x037AA0 */
BYTE [2] = address >> 8;
BYTE [3] = address;
BYTE [4] = size >> 16; /* size = 0x08 */
BYTE [5] = size >> 8;
BYTE [6] = size;
ATWINC15x0
WINC SPI Protocol
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 110
19. The WINC acknowledges the command by sending three bytes [C7] [0] [F3].
20. The HIF layer writes the data.
21. The HIF writes the Control Buffer data (part of the framing of the request).
if (pu8CtrlBuf != NULL)
{
ret = nm_write_block(u32CurrAddr, pu8CtrlBuf, u16CtrlBufSize);
if(M2M_SUCCESS != ret) goto ERR1;
u32CurrAddr += u16CtrlBufSize;
}
Command CMD_DMA_EXT_WRITE: 0xC7 /* DMA extended write */
BYTE [0] = CMD_DMA_EXT_WRITE
BYTE [1] = address >> 16; /* address = 0x037AA8 */
BYTE [2] = address >> 8;
BYTE [3] = address;
BYTE [4] = size >> 16; /* size = 0x04 */
BYTE [5] = size >> 8;
BYTE [6] = size;
ATWINC15x0
WINC SPI Protocol
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 111
22. The WINC acknowledges the command by sending three bytes [C7] [0] [F3].
23. The HIF layer writes the data.
24. The HIF finished writing the request data to memory and is going to interrupt the chip notifying that
host TX is done.
reg = dma_addr << 2;
reg |= (1 << 1);
ret = nm_write_reg(WIFI_HOST_RCV_CTRL_3, reg);
Command CMD_SINGLE_WRITE:0XC9 /* single word write */
BYTE [0] = CMD_SINGLE_WRITE
BYTE [1] = address >> 16; /* WIFI_HOST_RCV_CTRL_3 address = 0x106C */
BYTE [2] = address >> 8;
BYTE [3] = address;
BYTE [4] = u32data >> 24; /* Data = 0x000DEA82 */
BYTE [5] = u32data >> 16;
BYTE [6] = u32data >> 8;
BYTE [7] = u32data;
ATWINC15x0
WINC SPI Protocol
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 112
25. The WINC acknowledges the command by sending two bytes [C9] [0].
26. The HIF layer allows the chip to enter Sleep mode again.
sint8 hif_chip_sleep(void)
{
sint8 ret = M2M_SUCCESS;
uint32 reg = 0;
ret = nm_write_reg(WAKE_REG, SLEEP_VALUE);
/* Clear bit 1 */
ret = nm_read_reg_with_ret(0x1, ®);
if(reg&0x2)
{
reg &=~(1 << 1);
ret = nm_write_reg(0x1, reg);
}
}
Command CMD_SINGLE_WRITE:0XC9 /* single word write */
BYTE [0] = CMD_SINGLE_WRITE
BYTE [1] = address >> 16; /* WAKE_REG address = 0x1074 */
BYTE [2] = address >> 8;
BYTE [3] = address;
BYTE [4] = u32data >> 24; /* SLEEP_VALUE Data = 0x4321 */
BYTE [5] = u32data >> 16;
BYTE [6] = u32data >> 8;
BYTE [7] = u32data;
27. The WINC acknowledges the command by sending two bytes [C9] [0].
ATWINC15x0
WINC SPI Protocol
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 113
Command CMD_INTERNAL_READ: 0xC4 /* internal register read */
BYTE [0] = CMD_INTERNAL_READ
BYTE [1] = address >> 8; /* address = 0x01 */
BYTE [1] |= (1 << 7); /* clockless register */
BYTE [2] = address;
BYTE [3] = 0x00;
28. The WINC acknowledges the command by sending three bytes [C4] [0] [F3].
29. The WINC chip sends the value of the register 0x01 which equals 0x03.
Command CMD_INTERNAL_WRITE: C3 /* internal register write */
BYTE [0] = CMD_INTERNAL_WRITE
BYTE [1] = address >> 8; /* address = 0x01 */
BYTE [1] |= (1 << 7); /* clockless register */
BYTE [2] = address;
BYTE [3] = u32data >> 24; /* Data = 0x01 */
BYTE [4] = u32data >> 16;
BYTE [5] = u32data >> 8;
BYTE [6] = u32data;
ATWINC15x0
WINC SPI Protocol
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 114
30. The WINC chip acknowledges the command by sending two bytes [C3] [0].
31. At this point, the HIF layer has completed posting the scan Wi-Fi request to the WINC chip for
processing.
14.3.2 RX (Receive Response)
After finishing the required operation (scan Wi-Fi), the WINC interrupts the host to notify of the processing
of the request. The host handles this interrupt to receive the response.
1. First step in hif_isr is to wake up the WINC chip.
sint8 nm_clkless_wake(void)
{
ret = nm_read_reg_with_ret(0x1, ®);
/* Set bit 1 */
ret = nm_write_reg(0x1, reg | (1 << 1));
// Check the clock status
ret = nm_read_reg_with_ret(clk_status_reg_adr, &clk_status_reg);
// Tell Firmware that Host waked up the chip
ret = nm_write_reg(WAKE_REG, WAKE_VALUE);
return ret;
}
Command CMD_INTERNAL_READ: 0xC4 /* internal register read */
BYTE [0] = CMD_INTERNAL_READ
BYTE [1] = address >> 8; /* address = 0x01 */
BYTE [1] |= (1 << 7); /* clockless register */
BYTE [2] = address;
BYTE [3] = 0x00;
2. The WINC acknowledges the command by sending three bytes [C4] [0] [F3].
ATWINC15x0
WINC SPI Protocol
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 115
3. The WINC chip sends the value of the register 0x01 which equals 0x01.
Command CMD_INTERNAL_WRITE: C3 /* internal register write */
BYTE [0] = CMD_INTERNAL_WRITE
BYTE [1] = address >> 8; /* address = 0x01 */
BYTE [1] |= (1 << 7); /* clockless register */
BYTE [2] = address;
BYTE [3] = u32data >> 24; /* Data = 0x03 */
BYTE [4] = u32data >> 16;
BYTE [5] = u32data >> 8;
BYTE [6] = u32data;
4. The WINC acknowledges the command by sending two bytes [C3] [0].
Command CMD_INTERNAL_READ: 0xC4 /* internal register read */
BYTE [0] = CMD_INTERNAL_READ
BYTE [1] = address >> 8; /* address = 0x0F */
BYTE [1] |= (1 << 7); /* clockless register */
BYTE [2] = address;
BYTE [3] = 0x00;
5. The WINC acknowledges the command by sending three bytes [C4] [0] [F3].
ATWINC15x0
WINC SPI Protocol
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 116
6. Then WINC chip sends the value of the register 0x01 which equals 0x07.
Command CMD_SINGLE_WRITE:0XC9 /* single word write */
BYTE [0] = CMD_SINGLE_WRITE
BYTE [1] = address >> 16; /* WAKE_REG address = 0x1074 */
BYTE [2] = address >> 8;
BYTE [3] = address;
BYTE [4] = u32data >> 24; /* WAKE_VALUE Data = 0x5678 */
BYTE [5] = u32data >> 16;
BYTE [6] = u32data >> 8;
BYTE [7] = u32data;
7. The chip acknowledges the command by sending two bytes [C9] [0].
8. Read register WIFI_HOST_RCV_CTRL_0 to check if there is a new interrupt, and clear it.
static sint8 hif_isr(void)
{
sint8 ret ;
uint32 reg;
volatile tstrHifHdr strHif;
ret = hif_chip_wake();
ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_0, ®);
if(reg & 0x1) /* New interrupt has been received */
ATWINC15x0
WINC SPI Protocol
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 117
{
uint16 size;
/*Clearing RX interrupt*/
ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_0,®);
reg &= ~(1<<0);
ret = nm_write_reg(WIFI_HOST_RCV_CTRL_0,reg);
Command CMD_SINGLE_READ: 0xCA /* single word (4 bytes) read */
BYTE [0] = CMD_SINGLE_READ
BYTE [1] = address >> 16; /* WIFI_HOST_RCV_CTRL_0 address = 0x1070 */
BYTE [2] = address >> 8;
BYTE [3] = address;
9. The WINC acknowledges the command by sending three bytes [CA] [0] [F3].
10. The WINC chip sends the value of the register 0x1070 which equals 0x31.
Command CMD_SINGLE_READ: 0xCA /* single word (4 bytes) read */
BYTE [0] = CMD_SINGLE_READ
BYTE [1] = address >> 16; /* WIFI_HOST_RCV_CTRL_0 address = 0x1070 */
BYTE [2] = address >> 8;
BYTE [3] = address;
11. The WINC acknowledges the command by sending three bytes [CA] [0] [F3].
ATWINC15x0
WINC SPI Protocol
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 118
12. The WINC chip sends the value of the register 0x1070 which equals 0x31.
13. Clear the WINC Interrupt.
Command CMD_SINGLE_WRITE:0XC9 /* single word write */
BYTE [0] = CMD_SINGLE_WRITE
BYTE [1] = address >> 16; /* WIFI_HOST_RCV_CTRL_0 address = 0x1070 */
BYTE [2] = address >> 8;
BYTE [3] = address;
BYTE [4] = u32data >> 24; /* Data = 0x30 */
BYTE [5] = u32data >> 16;
BYTE [6] = u32data >> 8;
BYTE [7] = u32data;
14. The chip acknowledges the command by sending two bytes [C9] [0].
15. The HIF reads the data size.
/* read the rx size */
ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_0, ®);
Command CMD_SINGLE_READ: 0xCA /* single word (4 bytes) read */
BYTE [0] = CMD_SINGLE_READ
BYTE [1] = address >> 16; /* WIFI_HOST_RCV_CTRL_0 address = 0x1070 */
BYTE [2] = address >> 8;
BYTE [3] = address;
ATWINC15x0
WINC SPI Protocol
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 119
16. The WINC acknowledges the command by sending three bytes [CA] [0] [F3].
17. The WINC chip sends the value of the register 0x1070 which equals 0x30.
18. The HIF reads hif header address.
/** start bus transfer**/
ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_1, &address);
Command CMD_SINGLE_READ: 0xCA /* single word (4 bytes) read */
BYTE [0] = CMD_SINGLE_READ
BYTE [1] = address >> 16; /* WIFI_HOST_RCV_CTRL_1 address = 0x1084 */
BYTE [2] = address >> 8;
BYTE [3] = address;
19. The WINC acknowledges the command by sending three bytes [CA] [0] [F3].
20. The WINC chip sends the value of the register 0x1078 which equals 0x037AB0.
ATWINC15x0
WINC SPI Protocol
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 120
21. The HIF reads the hif header data (as a block).
ret = nm_read_block(address, (uint8*)&strHif, sizeof(tstrHifHdr));
Command CMD_DMA_EXT_READ: C8 /* dma extended read */
BYTE [0] = CMD_DMA_EXT_READ
BYTE [1] = address >> 16; /* address = 0x037AB0*/
BYTE [2] = address >> 8;
BYTE [3] = address;
BYTE [4] = size >> 16;
BYTE [5] = size >>;
BYTE [6] = size;
22. The WINC acknowledges the command by sending three bytes [C8] [0] [F3].
23. The WINC sends the data block (four bytes).
24. The HIF calls the appropriate handler according to the hif header received which tries to receive the
Response data payload.
ATWINC15x0
WINC SPI Protocol
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 121
Note: hif_receive obtains additional data.
sint8 hif_receive(uint32 u32Addr, uint8 *pu8Buf, uint16 u16Sz, uint8 isDone)
{
uint32 address, reg;
uint16 size;
sint8 ret = M2M_SUCCESS;
ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_0,®);
size = (uint16)((reg >> 2) & 0xfff);
ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_1,&address);
/* Receive the payload */
ret = nm_read_block(u32Addr, pu8Buf, u16Sz);
}
Command CMD_SINGLE_READ: 0xCA /* single word (4 bytes) read */
BYTE [0] = CMD_SINGLE_READ
BYTE [1] = address >> 16; /* WIFI_HOST_RCV_CTRL_0 address = 0x1070 */
BYTE [2] = address >> 8;
BYTE [3] = address;
25. The WINC acknowledges the command by sending three bytes [CA] [0] [F3].
26. The WINC chip sends the value of the register 0x1070 which equals 0x30.
Command CMD_SINGLE_READ: 0xCA /* single word (4 bytes) read */
BYTE [0] = CMD_SINGLE_READ
BYTE [1] = address >> 16; /* WIFI_HOST_RCV_CTRL_1 address = 0x1084 */
BYTE [2] = address >> 8;
BYTE [3] = address;
27. The WINC acknowledges the command by sending three bytes [CA] [0] [F3].
ATWINC15x0
WINC SPI Protocol
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 122
28. The WINC chip sends the value of the register 0x1078 which equals 0x037AB0.
Command CMD_DMA_EXT_READ: C8 /* dma extended read */
BYTE [0] = CMD_DMA_EXT_READ
BYTE [1] = address >> 16; /* address = 0x037AB8*/
BYTE [2] = address >> 8;
BYTE [3] = address;
BYTE [4] = size >> 16;
BYTE [5] = size >>;
BYTE [6] = size;
29. The WINC acknowledges the command by sending three bytes [C8] [0] [F3].
30. The WINC sends the data block (four bytes).
ATWINC15x0
WINC SPI Protocol
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 123
31. After the HIF layer received the response, it interrupts the chip to send the notification that the host
RX is done.
static sint8 hif_set_rx_done(void)
{
uint32 reg;
sint8 ret = M2M_SUCCESS;
ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_0,®);
/* Set RX Done */
reg |= (1<<1);
ret = nm_write_reg(WIFI_HOST_RCV_CTRL_0,reg);
}
Command CMD_SINGLE_READ: 0xCA /* single word (4 bytes) read */
BYTE [0] = CMD_SINGLE_READ
BYTE [1] = address >> 16; /* WIFI_HOST_RCV_CTRL_0 address = 0x1070 */
BYTE [2] = address >> 8;
BYTE [3] = address;
32. The WINC acknowledges the command by sending three bytes [CA] [0] [F3].
33. The WINC chip sends the value of the register 0x1070 which equals 0x30.
Command CMD_SINGLE_WRITE:0XC9 /* single word write */
BYTE [0] = CMD_SINGLE_WRITE
BYTE [1] = address >> 16; /* WIFI_HOST_RCV_CTRL_0 address = 0x1070 */
BYTE [2] = address >> 8;
BYTE [3] = address;
BYTE [4] = u32data >> 24; /* Data = 0x32*/
BYTE [5] = u32data >> 16;
BYTE [6] = u32data >> 8;
BYTE [7] = u32data;
ATWINC15x0
WINC SPI Protocol
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 124
34. The chip acknowledges the command by sending two bytes [C9] [0].
35. The HIF layer allows the chip to enter Sleep mode again.
sint8 hif_chip_sleep(void)
{
sint8 ret = M2M_SUCCESS;
uint32 reg = 0;
ret = nm_write_reg(WAKE_REG, SLEEP_VALUE);
/* Clear bit 1 */
ret = nm_read_reg_with_ret(0x1, ®);
if(reg&0x2)
{
reg &=~(1 << 1);
ret = nm_write_reg(0x1, reg);
}
}
Command CMD_SINGLE_WRITE:0XC9 /* single word write */
BYTE [0] = CMD_SINGLE_WRITE
BYTE [1] = address >> 16; /* WAKE_REG address = 0x1074 */
BYTE [2] = address >> 8;
BYTE [3] = address;
BYTE [4] = u32data >> 24; /* SLEEP_VALUE Data = 0x4321 */
BYTE [5] = u32data >> 16;
BYTE [6] = u32data >> 8;
BYTE [7] = u32data;
36. The WINC acknowledges the command by sending two bytes [C9] [0].
ATWINC15x0
WINC SPI Protocol
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 125
Command CMD_INTERNAL_READ: 0xC4 /* internal register read */
BYTE [0] = CMD_INTERNAL_READ
BYTE [1] = address >> 8; /* address = 0x01 */
BYTE [1] |= (1 << 7); /* clockless register */
BYTE [2] = address;
BYTE [3] = 0x00;
37. The WINC acknowledges the command by sending three bytes [C4] [0] [F3].
38. Then WINC chip sends the value of the register 0x01 which equals 0x03.
Command CMD_INTERNAL_WRITE: C3 /* internal register write */
BYTE [0] = CMD_INTERNAL_WRITE
BYTE [1] = address >> 8; /* address = 0x01 */
BYTE [1] |= (1 << 7); /* clockless register */
BYTE [2] = address;
BYTE [3] = u32data >> 24; /* Data = 0x01 */
BYTE [4] = u32data >> 16;
BYTE [5] = u32data >> 8;
BYTE [6] = u32data;
39. The WINC chip acknowledges the command by sending two bytes [C3] [0].
ATWINC15x0
WINC SPI Protocol
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 126
40. Scan Wi-Fi request is sent to the WINC chip and the response is successfully sent to the host.
ATWINC15x0
WINC SPI Protocol
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 127
15. Appendix A. How to Generate Certificates
15.1 Introduction
This chapter explains the required procedures to create and sign custom certificates using OpenSSL. To
use this guide you must install OpenSSL on your machine.
OpenSSL is an open-source implementation of the SSL and TLS protocols. The core library, written in the
C programming language, implements basic cryptographic functions and provides various utility
functions.
OpenSSL can be downloaded from the following URL: https://www.openssl.org/related/binaries.html.
15.2 Steps
After installing OpenSSL, open a CMD prompt and navigate to the directory where OpenSSL was
installed (For example: C:\OpenSSL-Win64\bin).
1. Generate a key for the CA (certification authority). To generate a 4096-bit long RSA (creates a new
file CA_KEY.key to store the random key), using the following command (CMD):
openssl genrsa -out CA_KEY.key 4096
2. Create your self-signed root CA certificate CA_CERT.crt; you need to provide some data for your
Root certificate, using the following command (CMD):
openssl req -new -x509 -days 1826 -key CA_KEY.key -out CA_CERT.crt
3. Create the custom certificate, which is signed by the CA root certificate created earlier. First,
generate the Custom.key, using the following command (CMD):
openssl genrsa -out Custom.key 4096
4. To generate a certificate request file (CSR) using this generated key, use the following command
(CMD):
openssl req -new -key Custom.key -out CertReq.csr
5. Process the request for the certificate and get it signed by the root CA, using the following
command (CMD):
openssl x509 -req -days 730 -in CertReq.csr -CA CA_CERT.crt -CAkey CA_KEY.key -
set_serial 01 -out CustomCert.crt
15.3 Limitations
The following are the limitations of BigInt_ModExp() API.
1. DHE greater than 2048-bit is not supported.
2. RSA signature verification greater than 2048-bit is done in software; 4096-bit takes 4 seconds per
verification, assuming a typical public key of 2^16+1.
3. RSA signature generation greater than 2048-bit is not supported.
ATWINC15x0
Appendix A. How to Generate Certificates
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 128
16. Appendix B. X.509 Certificate Format and Conversion
16.1 Introduction
The most known encodings for the X.509 digital certificates are PEM and DER formats.
The PEM format is base64 encoding of the DER enclosed with messages "-----BEGIN CERTIFICATE-----"
and "-----END CERTIFICATE-----".
16.2 Conversion Between Different Formats
The current implementation of the WINC root_certificate_downloader supports only DER format. If the
certificate is not in DER format, it must be converted first. The conversion between different formats are
done in several methods:
16.2.1 Using Windows
From Windows®
7, double click on the .crt certificate file and then go to the Details Tab and press “Copy
to File”. Follow the Certificate Export Wizard until the Finish button.
16.2.2 Using OpenSSL
The OpenSSL is used for certificate conversion by the following command.
openssl x509 -outform der -in certificate.pem -out certificate.der
ATWINC15x0
Appendix B. X.509 Certificate Format and C...
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 129
16.2.3 Online Conversion
There are useful online tools which provide conversion between the certificate formats, which can be
found through searching online using keywords such as "OpenSSL".
ATWINC15x0
Appendix B. X.509 Certificate Format and C...
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 130
17. References
The following documents can be used for further study:
• ATWINC15x0 Wi-Fi Network Controller Software Programming Guide
• ATWINC15x0-MR210xB Data Sheet
The following web page can be referred for further study on API:
• Atmel Software Framework for ATWINC1500 (Wi-Fi)
ATWINC15x0
References
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 131
18. Document Revision History
Rev B - 10/2018
Section Changes
6.2.3.12 setsockopt Added SOL_SSL_SOCKET information with example.
10. Over-The-Air
Upgrade
Removed “no HTTPS supported” from the chapter.
8.5 AP Mode Code
Example
Added Power Save note.
Document Removed the content related to Wi-Fi Direct mode and Wi-Fi Sniffer mode.
4.2 WINC Modes of
Operation
Updated WINC modes of operation.
8.1 Overview and 8.2
Setting the WINC AP
Mode
Updated the Wi-Fi AP mode chapter corresponding to WINC1500 v19.6.1
firmware.
5. Wi-Fi Station Mode Added support for Encrypted Credential Storage, Simple Roaming, Multiple
Gain Table, and Host File Download for Wi-Fi Station mode.
Rev A - 05/2017
Section Changes
Document • Updated from Atmel to Microchip template.
• Assigned a new Microchip document number. Previous version is
Atmel 42420 revision B.
• ISBN number added.
ATWINC15x0
Document Revision History
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 132
The Microchip Web Site
Microchip provides online support via our web site at http://www.microchip.com/. This web site is used as
a means to make files and information easily available to customers. Accessible by using your favorite
Internet browser, the web site contains the following information:
• Product Support – Data sheets and errata, application notes and sample programs, design
resources, user’s guides and hardware support documents, latest software releases and archived
software
• General Technical Support – Frequently Asked Questions (FAQ), technical support requests,
online discussion groups, Microchip consultant program member listing
• Business of Microchip – Product selector and ordering guides, latest Microchip press releases,
listing of seminars and events, listings of Microchip sales offices, distributors and factory
representatives
Customer Change Notification Service
Microchip’s customer notification service helps keep customers current on Microchip products.
Subscribers will receive e-mail notification whenever there are changes, updates, revisions or errata
related to a specified product family or development tool of interest.
To register, access the Microchip web site at http://www.microchip.com/. Under “Support”, click on
“Customer Change Notification” and follow the registration instructions.
Customer Support
Users of Microchip products can receive assistance through several channels:
• Distributor or Representative
• Local Sales Office
• Field Application Engineer (FAE)
• Technical Support
Customers should contact their distributor, representative or Field Application Engineer (FAE) for support.
Local sales offices are also available to help customers. A listing of sales offices and locations is included
in the back of this document.
Technical support is available through the web site at: http://www.microchip.com/support
Microchip Devices Code Protection Feature
Note the following details of the code protection feature on Microchip devices:
• Microchip products meet the specification contained in their particular Microchip Data Sheet.
• 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.
ATWINC15x0
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 133
• 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.
Legal Notice
Information contained in this publication regarding device applications and the like is provided only for
your convenience and may be superseded by updates. It is your responsibility to ensure that your
application meets with your specifications. MICROCHIP MAKES NO REPRESENTATIONS OR
WARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED, WRITTEN OR ORAL, STATUTORY
OR OTHERWISE, RELATED TO THE INFORMATION, INCLUDING BUT NOT LIMITED TO ITS
CONDITION, QUALITY, PERFORMANCE, MERCHANTABILITY OR FITNESS FOR PURPOSE.
Microchip disclaims all liability arising from this information and its use. Use of Microchip devices in life
support and/or safety applications is entirely at the buyer’s risk, and the buyer agrees to defend,
indemnify and hold harmless Microchip from any and all damages, claims, suits, or expenses resulting
from such use. No licenses are conveyed, implicitly or otherwise, under any Microchip intellectual
property rights unless otherwise stated.
Trademarks
The Microchip name and logo, the Microchip logo, AnyRate, AVR, AVR logo, AVR Freaks, BitCloud,
chipKIT, chipKIT logo, CryptoMemory, CryptoRF, dsPIC, FlashFlex, flexPWR, Heldo, JukeBlox, KeeLoq,
Kleer, LANCheck, LINK MD, maXStylus, maXTouch, MediaLB, megaAVR, MOST, MOST logo, MPLAB,
OptoLyzer, PIC, picoPower, PICSTART, PIC32 logo, Prochip Designer, QTouch, SAM-BA, SpyNIC, SST,
SST Logo, SuperFlash, tinyAVR, UNI/O, and XMEGA are registered trademarks of Microchip Technology
Incorporated in the U.S.A. and other countries.
ClockWorks, The Embedded Control Solutions Company, EtherSynch, Hyper Speed Control, HyperLight
Load, IntelliMOS, mTouch, Precision Edge, and Quiet-Wire are registered trademarks of Microchip
Technology Incorporated in the U.S.A.
Adjacent Key Suppression, AKS, Analog-for-the-Digital Age, Any Capacitor, AnyIn, AnyOut, BodyCom,
CodeGuard, CryptoAuthentication, CryptoAutomotive, CryptoCompanion, CryptoController, dsPICDEM,
dsPICDEM.net, Dynamic Average Matching, DAM, ECAN, EtherGREEN, In-Circuit Serial Programming,
ICSP, INICnet, Inter-Chip Connectivity, JitterBlocker, KleerNet, KleerNet logo, memBrain, Mindi, MiWi,
motorBench, MPASM, MPF, MPLAB Certified logo, MPLIB, MPLINK, MultiTRAK, NetDetach, Omniscient
Code Generation, PICDEM, PICDEM.net, PICkit, PICtail, PowerSmart, PureSilicon, QMatrix, REAL ICE,
Ripple Blocker, SAM-ICE, Serial Quad I/O, SMART-I.S., SQI, SuperSwitcher, SuperSwitcher II, Total
Endurance, TSHARC, USBCheck, VariSense, ViewSpan, WiperLock, Wireless DNA, and ZENA are
trademarks of Microchip Technology Incorporated in the U.S.A. and other countries.
SQTP is a service mark of Microchip Technology Incorporated in the U.S.A.
Silicon Storage Technology is a registered trademark of Microchip Technology Inc. in other countries.
GestIC is a registered trademark of Microchip Technology Germany II GmbH & Co. KG, a subsidiary of
Microchip Technology Inc., in other countries.
All other trademarks mentioned herein are property of their respective companies.
ATWINC15x0
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 134
© 2018, Microchip Technology Incorporated, Printed in the U.S.A., All Rights Reserved.
ISBN: 978-1-5224-3632-4
Quality Management System Certified by DNV
ISO/TS 16949
Microchip received ISO/TS-16949:2009 certification for its worldwide headquarters, design and wafer
fabrication facilities in Chandler and Tempe, Arizona; Gresham, Oregon and design centers in California
and India. The Company’s quality system processes and procedures are for its PIC®
MCUs and dsPIC®
DSCs, KEELOQ®
code hopping devices, Serial EEPROMs, microperipherals, nonvolatile memory and
analog products. In addition, Microchip’s quality system for the design and manufacture of development
systems is ISO 9001:2000 certified.
ATWINC15x0
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 135
AMERICAS ASIA/PACIFIC ASIA/PACIFIC EUROPE
Corporate Office
2355 West Chandler Blvd.
Chandler, AZ 85224-6199
Tel: 480-792-7200
Fax: 480-792-7277
Technical Support:
http://www.microchip.com/
support
Web Address:
www.microchip.com
Atlanta
Duluth, GA
Tel: 678-957-9614
Fax: 678-957-1455
Austin, TX
Tel: 512-257-3370
Boston
Westborough, MA
Tel: 774-760-0087
Fax: 774-760-0088
Chicago
Itasca, IL
Tel: 630-285-0071
Fax: 630-285-0075
Dallas
Addison, TX
Tel: 972-818-7423
Fax: 972-818-2924
Detroit
Novi, MI
Tel: 248-848-4000
Houston, TX
Tel: 281-894-5983
Indianapolis
Noblesville, IN
Tel: 317-773-8323
Fax: 317-773-5453
Tel: 317-536-2380
Los Angeles
Mission Viejo, CA
Tel: 949-462-9523
Fax: 949-462-9608
Tel: 951-273-7800
Raleigh, NC
Tel: 919-844-7510
New York, NY
Tel: 631-435-6000
San Jose, CA
Tel: 408-735-9110
Tel: 408-436-4270
Canada - Toronto
Tel: 905-695-1980
Fax: 905-695-2078
Australia - Sydney
Tel: 61-2-9868-6733
China - Beijing
Tel: 86-10-8569-7000
China - Chengdu
Tel: 86-28-8665-5511
China - Chongqing
Tel: 86-23-8980-9588
China - Dongguan
Tel: 86-769-8702-9880
China - Guangzhou
Tel: 86-20-8755-8029
China - Hangzhou
Tel: 86-571-8792-8115
China - Hong Kong SAR
Tel: 852-2943-5100
China - Nanjing
Tel: 86-25-8473-2460
China - Qingdao
Tel: 86-532-8502-7355
China - Shanghai
Tel: 86-21-3326-8000
China - Shenyang
Tel: 86-24-2334-2829
China - Shenzhen
Tel: 86-755-8864-2200
China - Suzhou
Tel: 86-186-6233-1526
China - Wuhan
Tel: 86-27-5980-5300
China - Xian
Tel: 86-29-8833-7252
China - Xiamen
Tel: 86-592-2388138
China - Zhuhai
Tel: 86-756-3210040
India - Bangalore
Tel: 91-80-3090-4444
India - New Delhi
Tel: 91-11-4160-8631
India - Pune
Tel: 91-20-4121-0141
Japan - Osaka
Tel: 81-6-6152-7160
Japan - Tokyo
Tel: 81-3-6880- 3770
Korea - Daegu
Tel: 82-53-744-4301
Korea - Seoul
Tel: 82-2-554-7200
Malaysia - Kuala Lumpur
Tel: 60-3-7651-7906
Malaysia - Penang
Tel: 60-4-227-8870
Philippines - Manila
Tel: 63-2-634-9065
Singapore
Tel: 65-6334-8870
Taiwan - Hsin Chu
Tel: 886-3-577-8366
Taiwan - Kaohsiung
Tel: 886-7-213-7830
Taiwan - Taipei
Tel: 886-2-2508-8600
Thailand - Bangkok
Tel: 66-2-694-1351
Vietnam - Ho Chi Minh
Tel: 84-28-5448-2100
Austria - Wels
Tel: 43-7242-2244-39
Fax: 43-7242-2244-393
Denmark - Copenhagen
Tel: 45-4450-2828
Fax: 45-4485-2829
Finland - Espoo
Tel: 358-9-4520-820
France - Paris
Tel: 33-1-69-53-63-20
Fax: 33-1-69-30-90-79
Germany - Garching
Tel: 49-8931-9700
Germany - Haan
Tel: 49-2129-3766400
Germany - Heilbronn
Tel: 49-7131-67-3636
Germany - Karlsruhe
Tel: 49-721-625370
Germany - Munich
Tel: 49-89-627-144-0
Fax: 49-89-627-144-44
Germany - Rosenheim
Tel: 49-8031-354-560
Israel - Ra’anana
Tel: 972-9-744-7705
Italy - Milan
Tel: 39-0331-742611
Fax: 39-0331-466781
Italy - Padova
Tel: 39-049-7625286
Netherlands - Drunen
Tel: 31-416-690399
Fax: 31-416-690340
Norway - Trondheim
Tel: 47-72884388
Poland - Warsaw
Tel: 48-22-3325737
Romania - Bucharest
Tel: 40-21-407-87-50
Spain - Madrid
Tel: 34-91-708-08-90
Fax: 34-91-708-08-91
Sweden - Gothenberg
Tel: 46-31-704-60-40
Sweden - Stockholm
Tel: 46-8-5090-4654
UK - Wokingham
Tel: 44-118-921-5800
Fax: 44-118-921-5820
Worldwide Sales and Service
© 2018 Microchip Technology Inc. User Guide DS00002389B-page 136
MPLAB Harmony Help
MPLAB Harmony
Copyright (c) 2013 Microchip Technology Inc. All rights reserved.
Table of Contents
1 Start Here 1-1
MPLAB Harmony Help
1
1 Start Here
This topic describes how to get started using the MPLAB Harmony Integrated Software Framework.
1. First Time Users
Name Description
Before You Start Before you start using MPLAB Harmony, be sure to install the MPLAB X IDE
Plug-In modules.
What is MPLAB Harmony? This topic provides an overview of key concepts necessary to understand the
MPLAB Harmony architecture.
Project Layout This topic explains how an MPLAB Harmony project is organized.
The Main File This topic describes the logic of the "main.c" file and the C-language "main"
function in an MPLAB Harmony project.
The Application File(s) This topic describes the normal structure of MPLAB Harmony application files.
More Information Describes what is available from the MPLAB Harmony web page.
Description
Software Building Blocks
MPLAB Harmony is a framework of software modules that serve as building blocks for your application. If this is the first time
you've used MPLAB Harmony, the "First Time Users" section is the best place to start learning. If you're an experienced MPLAB
Harmony developer, be sure to look at the "Release Notes & Information" section to find out what is in this release and what is
new.
1 MPLAB Harmony Help
1-1
1.1 1. First Time Users
1.1.1 Before You Start
Before you start using MPLAB Harmony, be sure to install the MPLAB X IDE Plug-In modules.
Description
Before you start using MPLAB Harmony, you should install the following MPLAB X IDE plug in modules, included in the MPLAB
Harmony installation.
1. The MPLAB Harmony "Help" plug-in module. (Located at: /doc/org-microchip-harmony_help.nbm)
2. The MPLAB Harmony Configurator plug-in module. (Located at:
/utilities/configurator/com-microchip-harmonyconfigurator.nbm)
Installing the Plug In Modules
1. Start MPLAB X IDE and select "Plugins" from the "Tools" menu as shown below.
2. Click the "Add Plugins..." button, navigate to and open the "com-microchip-harmonyconfigurator.nbm" plug-in file, as shown
below.
1.1 1. First Time Users MPLAB Harmony Help Before You Start
1-2
3. Ensure that the box under "Install" for the "MPLAB Harmony Configurator" plug-in is selected and click "Install" as shown
below.
1.1 1. First Time Users MPLAB Harmony Help Before You Start
1-3
4. Follow the prompts from the installation and continue until the installation completes. (Do not worry if the version you're
installing is "signed" but not "trusted". Just click "continue"). Once the installation has finished you can close the "Plugins" dialog
box.
You should now see a "MPLAB Harmony Configurator" option under the "Tools" menu. This indicates that the project
Configurator has been successfully installed.
1.1.2 What is MPLAB Harmony?
This topic provides an overview of key concepts necessary to understand the MPLAB Harmony architecture.
Description
Introduction
Microchip MPLAB® Harmony is the result of a holistic, aggregate approach to creating firmware solutions for embedded systems
using Microchip microcontrollers.
MPLAB® Harmony Block Diagram
1.1 1. First Time Users MPLAB Harmony Help What is MPLAB Harmony?
1-4
MPLAB Harmony Overview
Designed almost completely in the C language (with support for C++), MPLAB Harmony takes key elements of modular and
object-oriented design, adds in the flexibility to use a Real-Time Operating System (RTOS) or work without one if you prefer, and
provides a framework of software modules that are easy to use, configurable for your specific needs, and that work together in
complete harmony.
Portability
Portability is a concern that is often overlooked when a silicon manufacturer provides software. However, breadth of solutions is
a hallmark strength of Microchip, and MPLAB Harmony provides simple libraries to abstract away part-specific details and make
Microchip microcontrollers easy to use, regardless of which part you choose. Any time you design a new product or update an
existing one you have to balance capabilities against cost, but cost is more than just the bill of materials. It’s also the
Non-Refundable Engineering (NRE) cost to design and develop your solution. MPLAB Harmony provides peripheral libraries,
device drivers, and other libraries that use clear and consistent interfaces, requiring little or no change in your application code
and minimizing the engineering time and effort for each new design.
Device Drivers
The primary purpose of an MPLAB Harmony device driver (or “driver”) is to provide a simple and highly abstracted interface to a
peripheral, allowing your application (or other module in the system) to interact with a peripheral through a consistent set of
functions. A device driver is responsible for managing access to a peripheral, so that requests from different modules do not
conflict with each other, and for managing the state of that peripheral so that it always operates correctly.
Peripheral Libraries
A Peripheral Library (PLIB) is a simple access library that provides a consistent (but very low level) interface to a peripheral that
is “on board” the microcontroller. PLIBs hide register details, making it easier to write drivers that support multiple microcontroller
families, but they are not normally used by applications directly to interact with peripherals, as they provide little abstraction, and
because they require the caller to manage the detailed operation of a peripheral (including preventing conflicting requests from
other modules). Because of the lack of conflict protection in a PLIB, only one module in a system should directly access the PLIB
for a peripheral. Therefore, PLIBs are primarily used to implement device drivers (and some system services) to make them
portable.
Modularity
MPLAB Harmony libraries are modular software “building blocks” that allow you to divide-and-conquer your firmware design. The
interface to each library consists of a highly cohesive set of functions (not globally accessible variables or shared registers), so
that each module can manage its own resources. If one module needs to use the resources of another module, it calls that
module’s interface functions to do so. Interfaces between modules are kept simple with minimal inter-dependencies so that
modules are loosely coupled to each other. This approach helps to eliminate conflicts between modules and allows them to be
more easily used together like building blocks to create the solutions you need.
1.1 1. First Time Users MPLAB Harmony Help What is MPLAB Harmony?
1-5
Middleware Libraries
The normal usage models of some of the more complex peripherals, (i.e., USB or network interfaces) requires interpreting
complex protocols or may require substantial additional processing to produce useable results, such as drawing graphical
images on an LCD screen with an LCD controller peripheral. Therefore, while a device driver may be completely sufficient for a
simple peripheral like a UART, some peripherals require what is frequently called “middleware” (aptly named because it sits
between your application and the hardware abstraction layer or “driver” layer). MPLAB Harmony provides several middleware
library “stacks” to manage these more complex peripherals and provide the functionality you need and expect.
MPLAB Harmony middleware “stacks” are usually built upon device drivers and system services (explained below) so that they
can be supported on any Microchip microcontroller for which the required driver or service is supported. However, special
purpose implementations may be available that integrate the driver, certain services, and various modules within the “stack” for
efficiency.
System Services
MPLAB Harmony system services are responsible for managing shared resources so that other modules (drivers, middleware,
and applications) do not conflict on shared resources. For example, if the TCP/IP, USB, and Graphics stacks attempted to
concurrently use the Timer2 peripheral to perform some periodic task, they would very likely interfere with each other. However,
if instead they used a timer system service (as the following image illustrates), it is the responsibility of the system service to
keep the separate requests from interfering with each other. The timer service can be configured as desired for a specific system
(for example, you might decide to use Timer3 instead of Timer2) isolating the necessary changes to the configuration of a single
module and preventing potential conflicts.
The use of a system service is very similar the use of a device driver, except that a driver normally requires the caller to “open” it
to create unique client-to-driver association. A system service does not normally require the caller to open the service before
using it because system services are frequently shared by many clients within the system.
Compatibility
MPLAB Harmony modules (drivers, system services, and middleware – excluding PLIBs) are “active”. This means when an
application calls a module’s interface function, the call will usually return immediately and the module will continue working on its
own to complete the operation. Most modules will then provide a notification mechanism so the caller (i.e., client) can determine
when the operation has finished.
Harmony modules are implemented as cooperative state machines. The following image shows the basic idea of how this works.
Each module has an “Initialize” function and each module has one (or more) “Tasks” function(s) to maintain its state machine(s).
The state machines of all modules are initialized, shortly after the system comes out of reset in “main”. After that (in a polled
1.1 1. First Time Users MPLAB Harmony Help What is MPLAB Harmony?
1-6
configuration, with no OS), the system drops into a “super loop” where each module’s state machine function is repeatedly
called, one after the other, to allow it to do the next “task” necessary to keep its state machine running. This allows the system to
keep all modules running using a cooperative or shared “multi-tasking” technique. Modules (under control of your application)
interact with each other by calling the interface functions of other modules (as illustrated below) and the system-wide “super
loop” keeps all modules in the system running so they stay “active” and do their jobs.
This method is not suitable for all needs; therefore, other configurations are possible. However, a polled configuration is the
simplest to understand and it best illustrates the basic concept of how MPLAB Harmony modules work together, as shown
below. It is also easy to implement, easy to understand, and easy to debug.
Flexibility
The basic MPLAB Harmony model of cooperating state-machine driven modules, when combined with a little configurability,
becomes flexible enough to meet the needs of almost any embedded system. For example, if you’re using multiple identical
peripherals, MPLAB Harmony has “dynamic” driver implementations that can manage all instances of a peripheral with a single
instance of the driver code. You might also have a need for multiple “client” modules to use the same instance of a peripheral at
the same time (like the timer example, described previously). To manage this need, MPLAB Harmony has driver
implementations that are intelligent enough to manage requests from multiple clients. On the other hand, your needs may be
simpler than that. So, static and single client drivers are also available to help reduce the amount of code and data storage
needed for your system.
Or, your system may need to combine several middleware stacks and multiple, potentially independent, applications. If that is the
1.1 1. First Time Users MPLAB Harmony Help What is MPLAB Harmony?
1-7
case, the simple polling operation, using the “super loop” method frequently seen in simple embedded systems may not be
sufficient. However, when you start adding more modules, it becomes more and more difficult to meet the timing requirements of
all peripherals using a simple polled super loop.
Fortunately, MPLAB Harmony modules are written so that (where appropriate) their state machines can be run directly from an
Interrupt Service Routine (ISR) or an RTOS thread. Using an ISR allows you to eliminate the latency of waiting for the execution
of other modules in the loop to finish before a time-critical event is serviced, and it allows you to use the interrupt prioritization
capabilities available on some Microchip devices to ensure that your system responds to events in the real world in real-time.
Additionally, the ability to schedule and prioritize different tasks for different modules can be obtained for modules that are not
associated with a specific processor interrupt (such as many middleware modules and your application) using a Real-Time
Operating System (RTOS). In fact, that is one of the main reasons to use an RTOS. When your system becomes complex
enough that you start struggling to meet your timing requirements using the super loop method, it’s time to use an RTOS.
Fortunately, the MPLAB Harmony module state machines functions can be called from a loop in an RTOS thread just as easily
as they can be called from a polled “super loop” in a system without an RTOS. To allow this, modules are designed to be “thread
safe” by calling semaphore and mutex operations (and a few others, as necessary) through an Operating System Abstraction
Layer (OSAL). The OSAL provides a consistent set of functions to call, regardless of which RTOS is being used (or even if no
RTOS is used). The choice of RTOS to use, if any, is a configuration option. MPLAB Harmony supports several OS and non-OS
configurations and support for more operating systems is possible. All that is required is to implement the OSAL functions
appropriately for the desired OS.
Configurability
Most MPLAB Harmony libraries support a variety of build-time configuration options.
• Selection of supported Microchip microcontroller
• Interrupt-driven or polled execution
• Static-or-dynamic peripheral instance selection (for drivers)
• Single-or-multi-client support (for drivers)
• Other library-specific options
The need for selection of the microcontroller and execution environment has been previously explained. In addition, most drivers
and other library modules are designed to allow you to select a variety of configuration options to tailor them to your specific
usage. For example, you may be able to select buffer sizes for data transfer modules or clock sources for timer modules. The set
of configuration options for each module is identified and explained in the help documentation (along with the interface and
usage information) and peripheral initializer (MPLAB Harmony “Pi”) and configuration tools are provided to help simplify the
process of configuring your system exactly the way you want and to get you started with a set of initial source files for your
project.
Project Structure
To facilitate configurability, MPLAB Harmony projects are normally structured in a way that isolates the code necessary to
1.1 1. First Time Users MPLAB Harmony Help What is MPLAB Harmony?
1-8
configure a “system” from the library modules themselves and from your application code. The following illustrates this concept,
while the second figure shows how the files might appear in an MPLAB X IDE project.
In an MPLAB Harmony project, the “main.c” file is kept very simple and consistent (containing primarily, just the super-loop
previously discussed). The application files (app.c and app.h in the example to the left) are separate from the configuration files
in the “system_config” folder, so it is possible for a single application to have more than one configuration. (Usage of this
capability can be seen in example and demonstration projects included with the installation of MPLAB Harmony.) The library
modules that make up the MPLAB Harmony framework (in the “framework” folder) use the definitions provided in the selected
configuration header (system_config.h, highlighted in the illustration) to specify the configuration options you selected when you
configured the project. Finally the processor-specific peripheral libraries (if used) are provided as both a prebuilt binary (“.a”
linker file) and as in-line source code to allow for maximum build efficiency for your firmware projects.
Conclusion
MPLAB Harmony provides a complete framework for developing your firmware solutions using Microchip microcontrollers and
development tools. The firmware libraries and tools that make up the MPLAB Harmony framework are modular and compatible,
making them simple to use. They’re flexible and configurable, making them easy to tailor to your specific needs. And, they’re
portable across a wide range of Microchip microcontrollers so you’re sure to find a supported part that meets your needs.
1.1 1. First Time Users MPLAB Harmony Help Project Layout
1-9
1.1.3 Project Layout
This topic explains how an MPLAB Harmony project is organized.
Description
A sample project has been created to show you the structure of an MPLAB Harmony project. The "sample" project is available in
the following folder, directly under your MPLAB Harmony installation root folder.
/apps/examples/sample/firmware/sample.X
You should open this project in MPLAB X IDE and follow along with this guide.
An MPLAB Harmony Project is organized as shown below within MPLAB X IDE.
This organization consists of a few key "logical" folders and C-language files, as described below.
The "app" folder, which contains:
• The "main.c" file
• The "app.c" file
The "app" (short for "application") folder holds all of the application's firmware source files for the project. In a simple project, the
"app" folder will directly contain the "main.c" file and the "app.c" file. More complex projects will very likely contain additional files,
as needed. In an MPLAB Harmony project, the "main.c" file normally contains the C-language "main" function and little or nothing
else. This "main" logic is usually consistent across all MPLAB Harmony projects and should not need to be changed. The "app.c"
file normally contains the logic of the application itself. This is where the desired over-all behavior of your system is usually
implemented (although complex applications may have additional files).
The "system_config" folder
1.1 1. First Time Users MPLAB Harmony Help Project Layout
1-10
The "system_config" folder contains one or more subdirectories, each of which corresponds to a configuration of your application
or, more accurately, "system". MPLAB Harmony projects may have multiple configuration. In each configuration, you can select a
different set of libraries or modules, different build parameters for each module and different source files for your application. A
configuration consists of a specific set of properties (tools settings) in MPLAB X IDE and a set of source files that define the build
parameters and source code that control which modules are initialized and maintained in your system.
In MPLAB X IDE, the tools configuration can be selected by using a "pull down" menu in the tool bar at the top of the window or
buy "Right-clicking' on the project name and selecting "Properties". In most example and demo projects distributed with MPLAB
Harmony, name of each MPLAB X IDE configuration will match the name of the associated folder under the "system_config"
folder in the project (the "pic32mx_default" folder in the sample project). When a specific MPLAB X IDE configuration is selected,
the configuration files for that configuration are included in the build and the configuration files in other configuration folders are
excluded from the build.
Note: This is project convention used by example and demo projects provided with MPLAB Harmony. You, of course, may
organize your own projects any way you wish. But, we recommend following this convention if you use multiple configurations in
your projects. We think you'll appreciate the power and flexibility of it.
Configuration Files
• The "system_config.h" file
• The "system_init.c" file
• The "system_tasks.c" file
• The "system_int.c" file (optionally)
A set of three or four files normally make up a complete configuration of the system. The purpose of each of these files is
described in more detail in the following sections. But, the basic idea is that you may want different configurations of your
application for different physical hardware boards, different Microchip microcontrollers, or different feature sets, depending on
your specific needs.
Allowing different configurations of the same application logic makes your application more flexible and provides a
well-organized way to deal with the sort of variation that usually occurs in any project of sufficient size and complexity. This
technique helps to eliminate the duplication of code (and labor) that would otherwise be necessary to manage multiple related
projects. Of course, if you don't need or want that flexibility, all of these files are specifically created for your project and you can
make any modifications to them that you like. The choice is always yours.
1.1 1. First Time Users MPLAB Harmony Help Project Layout
1-11
Important!
The relative path, from the MPLAB X IDE project folder to the configuration folder (containing the "system_config.h" file) for each
project configuration must be placed in the "Includes directories" list in the compiler properties for each configuration of the
MPLAB X IDE project.
The "framework" folder
The "framework" logical folder contains the source files for the MPLAB Harmony framework and libraries. Depending on your
project configuration, there can be many, many files and sub folders under this folder. These files are for MPLAB Harmony
libraries that you should not need to edit. In fact, the framework source files are not normally located in your project. Instead,
these files are included in your project directly from the MPLAB Harmony installation (using relative directory paths). All of the
actual files stay in the MPLAB Harmony installation folder, out of the way.
Notes
1. You always have the option of copying the framework files directly into your project's source folder, if desired. In fact, doing so
is a good idea if you plan to move or distribute your project separately from the MPLAB Harmony installation.
2. In most cases, the "logical folder" organization within the MPLAB X IDE project matches exactly with the physical directory
organization within the MPLAB Harmony installation (and within your project directory) on your disk drive. This is done to keep
things simple and consistent so you only need to learn a single layout. But, there are a couple of notable exceptions.
• MPLAB has a convention of splitting out "Header Files" (".h" files) and "Source Files" (".c" files), so the virtual folder
organization in the MPLAB X IDE project separates the files in to these two groups and the physical directories on disk do
not.
• In an MPLAB Harmony example or demo project, the "app" folder will correspond to the "src" directory on disk under the
application's main folder.
1.1.4 The Main File
This topic describes the logic of the "main.c" file and the C-language "main" function in an MPLAB Harmony project.
Description
The C-language entry point for an MPLAB Harmony embedded application is the "main" function. This function is defined in the
"main.c" file, contained in the project's "app" folder (or "src" directory on disk). The "main" function (see example, below)
implements a simple "super loop", commonly used in embedded applications that do not make use of an operating system.
Example "main" Function Logic
int main ( void )
{
/* Initialize the system. */
SYS_Initialize ( NULL );
while ( true )
{
/* Perform system tasks. */
SYS_Tasks ( );
}
/* Should not come here during normal operation. */
SYS_ASSERT ( false , "Error! Exiting main" );
return ( EXIT_FAILURE );
}
The "SYS_Initialize" Function
1.1 1. First Time Users MPLAB Harmony Help The Main File
1-12
The first thing the main function does is call a function called "SYS_Initialize". The purpose of the "SYS_Initialize" function is to
initialize every software module in the system. MPLAB Harmony is based upon a model of cooperating state machines. So, this
function must ensure that every module's state machine is placed in a valid initial state. The implementation of this function is
one of the things that must be done to configure an MPLAB Harmony system. This function's definition is normally located in the
"system_init.c" file and is normally implemented by you since you're the only one who knows which software modules you want
to include in your project. However, MPLAB Harmony provide a project Configurator to help you get started.
Note: The "SYS_Initialize" function signature has a "void *" input parameter. This is so that it may later be implemented in a
library and an arbitrary initialization data structure may be passed into it. However, for a statically implemented "SYS_Initialize"
function (which will normally be the case if you implement it yourself), this parameter is unnecessary and can be passed as
"NULL". (Note: You could eliminate the parameter, but that may lead to future incompatibilities and the compiler will remove it
automatically for you when optimizations are enabled.)
The "Super Loop"
After all of the modules in the system have been initialized, the "main" function executes an infinite loop to keep the system
running. This is commonly called a "super loop" as it is the outer-most loop, within which the entire system operates. This loop
never exits. So, the code that exists after the end of that loop should never be executed and is only included there for safety,
clarity, and syntactical completeness.
The "SYS_Tasks" Function
Inside of the "super loop", the "main" function calls the "SYS_Tasks" function. The purpose of the "SYS_Tasks" function is to poll
every module in the system to ensure that it continues to operate. This is how the system maintains the state machine of all
polled modules. (Note that some modules may be interrupt driven and thus, not called from the "SYS_Tasks" function.) The
implementation of the "SYS_Tasks" function is also one of the things that you must normally do as part of the system
configuration, again because you are the only one who knows which modules you want to include in your project. You might also
have guessed that this function's definition is normally located in the "system_tasks.c" file. Of course, the MPLAB Harmony
project Configurator can help with this also.
1.1.5 The Application File(s)
This topic describes the normal structure of MPLAB Harmony application files.
Description
From the point of view of an MPLAB Harmony system, an application consists of two basic functions.
• APP_Initialize()
• APP_Tasks()
The application's initialization function (APP_Initialize) is normally called from the "SYS_Initialize" function, called from "main"
before entering the top-level loop. The application's "tasks" function (APP_Tasks) is normally called from the "SYS_Tasks"
function, called from "main" from inside the top-level loop. This is how the application's state machine is initialized and "polled" so
that it can do it's job. The "SYS_Initialize" function is normally implemented in the "system_init.c" file and the "SYS_Tasks"
function is normally implemented in the "sys_tasks.c" file. That is the convention for example and demo projects distributed with
MPLAB Harmony and that is the case for the sample project. You may do as you choose in your own projects, but we
recommend following this convention as it will make it easier to manage multiple configurations if you need them and it will be
consistent with the MPLAB Harmony project Configurator and other tools.
Application Initialization
An application's initialization function places the application's state machine in its initial state and may perform additional
initialization if necessary. This function must not block and it should not call the routines of any other modules that may block. If
1.1 1. First Time Users MPLAB Harmony Help The Application File(s)
1-13
something needs to be initialized that may take time to complete, that initialization should be done in the application's state
machine (i.e. in it's "Tasks" function).
Sample Application Initialization Function:
void APP_Initialize( void )
{
/* Copy the message string to a buffer. */
strncpy(appData.buffer, APP_HELLO_STRING, APP_BUFFER_SIZE);
/* Prepare a buffer object for transfer using the USART driver. */
appData.bufferObject.buffer = appData.buffer;
appData.bufferObject.bufferSize = min(APP_BUFFER_SIZE, strlen(appData.buffer));
appData.bufferObject.flags = DRV_USART_BUFFER_FLAG_WRITE;
/* Place the App state machine in it's initial state. */
appData.state = APP_STATE_INIT;
}
The sample project's initialization function initializes an internal buffer to prepare a "Hello World" message for transmission on a
USART and places the application's state machine in its initial state by assigning the "APP_STATE_INIT" enumeration value into
the "state" member of the data structure that contains all of the data required by the application (appData). This structure is
defined globally, but is only ever accessed by the application itself. The application's initialization function is called from the
"SYS_Initialize" function (defined in "system_init.c") which is called from "main" after a system reset. Using this technique, the
application is initialized (along with the rest of the system) whenever the system comes out of reset.
Application Tasks
The application's state machine breaks up the job that the application must do into several short "tasks" that it can complete
quickly, but between which it must wait for some other module to complete some tasks of its own. (In this case the other module
is the USART driver.) Once each short task has completed successfully, the application transitions to another state to perform
the next short task.
Example Application Tasks Function:
void APP_Tasks( void )
{
/* Status of USART driver */
DRV_USART_CLIENT_STATUS usartStatus;
/* Status of buffer submitted to USART */
DRV_USART_BUFFER_STATUS bufferStatus;
/* Check the application state*/
switch ( appData.state )
{
/* Keep trying to open the driver until we succeed. */
case APP_STATE_INIT:
{
/* open an instance of USART driver */
appData.usartHandle = DRV_USART_Open(SYS_USART_DRIVER_INDEX,
DRV_IO_INTENT_READWRITE);
if (appData.usartHandle != DRV_HANDLE_INVALID )
{
/* Update the state */
appData.state = APP_STATE_WAIT_FOR_READY;
}
break;
}
/* Send the message when the driver is ready. */
case APP_STATE_WAIT_FOR_READY:
{
1.1 1. First Time Users MPLAB Harmony Help The Application File(s)
1-14
/* Get the USART driver status */
usartStatus = DRV_USART_ClientStatus( appData.usartHandle );
if ( usartStatus == DRV_USART_CLIENT_STATUS_READY )
{
/* Submit buffer to USART */
appData.usartBufferHandle = DRV_USART_BufferAdd(appData.usartHandle,
&appData.bufferObject);
if ( appData.usartBufferHandle != DRV_HANDLE_INVALID )
{
/* Buffer is accepted. Driver will transmit. */
appData.state = APP_STATE_WAIT_FOR_DONE;
}
}
break;
}
case APP_STATE_WAIT_FOR_DONE:
{
bufferStatus = DRV_USART_BufferStatus(appData.usartHandle,
appData.usartBufferHandle);
if ( DRV_USART_BUFFER_COMPLETED == bufferStatus )
{
/* Work is done, move to idle state. */
appData.state = APP_STATE_IDLE;
}
}
/* Idle state (do nothing) */
case APP_STATE_IDLE:
default:
break;
}
}
Sample Application States
The sample application's "tasks" function breaks the operation of the application down in to the following states using a "switch"
statement with the following "cases".
• APP_STATE_INIT
• APP_STATE_WAIT_FOR_READY
• APP_STATE_WAIT_FOR_DONE
• APP_STATE_IDLE
The sample application is placed into the "APP_STATE_INIT" state when by the application's initialization function before the
"tasks" function is ever called. So, the first time the "APP_Tasks" function is called, the switch statement executes the code
under this case and the first short "task" the sample application attempts to do is open the USART driver to obtain a handle so
that it can transfer data over the USART. Notice that the application checks the value of the handle returned from the
"DRV_USART_Open" function to ensure that it is valid before it transitions to the "APP_STATE_WAIT_FOR_READY" state. If
the value of the handle retuned be the driver's "open" function is invalid (equal to "DRV_HANDLE_INVALID"), then the
application stays in the "APP_STATE_INIT" state and keeps trying to open the USART driver every time it's "tasks" function is
called.
Once the application has a valid handle to the USART driver, it executes the code under the
"APP_STATE_WAIT_FOR_READY" case the next time its "APP_Tasks" function is called . In this state, the application calls a
USART driver status routine (DRV_USART_ClientStatus) to see if the driver is ready to transfer data . If the driver is ready, the
application calls a USART driver data transfer routine (DRV_USART_BufferAdd) to send the data buffer it prepared in the
"APP_Initiaize" function to the USART. Then, it checks the handle returned by the "DRV_USART_BufferAdd" routine to see if it
is valid. If the buffer handle is valid, it indicates that the USART driver has accepted the buffer and will take responsibility for the
1.1 1. First Time Users MPLAB Harmony Help The Application File(s)
1-15
data transfer from that point forward. The application does not have to do anything else to cause the data transfer to occur, but it
may want to know when the transfer has completed, so it transitions to the "APP_STATE_WAIT_FOR_DONE" state. However, if
the buffer is not accepted by the driver (in which case the handle returned by the "DRV_USART_BufferAdd" function would be
invalid), the application stays in the "APP_STATE_WAIT_FOR_READY" and tries again the next time the "APP_Tasks" function
is called by the system (i.e. the "SYS_Tasks" function).
Once the application is in the "APP_STATE_WAIT_FOR_DONE" state, it calls a buffer status routine
(DRV_USART_BufferStatus) to check and see if the buffer it sent has completed. Note that it passes the handle value returned
from the "DRV_USART_BufferAdd" function (stored in the "usartBufferHandle" member of the global "appData" structure) into
the buffer status function to identify the buffer on which it wishes to check status. If the buffer status routine returns
"DRV_USART_BUFFER_COMPLETED", then the transfer has completed and the application transitions to the
"APP_STATE_IDLE" state where it stays and does nothing any time its "tasks" function is called. It's job is done! A more
complex application would go on to some other task or potentially begin the process again. But, this is a simple "Hello World"
sample application.
Note:
The application is normally initialized last, after all other modules in the system have been initialized. But, it should never assume
that any other module that it must call has completed its initialization when the application is initialized or when it's "tasks"
function is first called. Instead, it should always check the return value or status from any other module it calls to ensure that the
call succeeded before moving on to the next state. Following this rule makes applications more robust and allows then to handle
errors more effectively.
1.1.6 System Configurations
1.1.6.1 system_config.h
This topic describes the purpose of system configuration header file.
Description
System Configuration
In MPLAB Harmony, most library modules have a set of build time configuration options that define a variety of parameters (such
as buffer sizes, maximum or minimum limits, and default behavior). These configuration options normally have acceptable
default values. However, if you want to configure a library for your specific needs, its configuration options can be defined using
C-language pre-processor "#define" statements. The set of configuration options supported is described for each library in the
"Configuring the Library" section of its help document and most libraries provide a template and example configuration header
files in a "config" sub-folder under their "src" folder.
To obtain its build configuration options, every library includes the same common top-level configuration file that must be called
"system_config.h" and that must be defined as part of your application or, more specifically, as part of your system configuration.
The relative directory path to configuration directory that contains this file must be defined in the build properties of your project
so that the compiler can find it in it's include file search path.
Example Configuration "system_config.h" Header
// *****************************************************************************
// *****************************************************************************
// Section: Application Configuration
// *****************************************************************************
// *****************************************************************************
1.1 1. First Time Users MPLAB Harmony Help System Configurations
1-16
/* Define the size of the application's message buffer. */
#define APP_BUFFER_SIZE 15
#define APP_UART_BAUDRATE 9600
/* Define the application's "hello world" message string. */
#define APP_HELLO_STRING "Hello World\r\n"
// *****************************************************************************
// *****************************************************************************
// Section: System Services Configuration
// *****************************************************************************
// *****************************************************************************
/* Define the index for the driver we'll use. */
#define SYS_USART_DRIVER_INDEX DRV_USART_INDEX_0
/* Define the hardware (PLIB) index associted with this instance of the driver. */
#define SYS_USART_ID USART_ID_2
// *****************************************************************************
// *****************************************************************************
// Section: UART Driver Configuration
// *****************************************************************************
// *****************************************************************************
#define DRV_USART_INSTANCES_NUMBER 1
#define DRV_USART_CLIENTS_NUMBER 1
#define DRV_USART_INTERRUPT_MODE false
#define DRV_USART_XFER_BUFFER_NUMBER 10
#define DRV_USART_INTERRUPT_SOURCE_TX INT_SOURCE_USART_2_TRANSMIT
#define DRV_USART_CONFIG_BYTE_Q_SIZE_TX 1
#define DRV_USART_CONFIG_BYTE_Q_SIZE_RX 1
#define DRV_USART_CONFIG_BLOCK_DEVICE_MODE
#define DRV_USART_INTERRUPT_MODE false
#define DRV_USART_INSTANCES_NUMBER 1
#define DRV_USART_CLIENTS_NUMBER 1
#define DRV_USART_INTERRUPT_SOURCE_TX INT_SOURCE_USART_2_TRANSMIT
#define DRV_USART_INTERRUPT_SOURCE_RX INT_SOURCE_USART_2_RECEIVE
The example above defines configuration options for the application, system services, and USART driver used in the
"pic32mx_default" configuration of the sample project..
1.1.6.2 system_init.c
This topic describes the purpose of the system initialization file.
Description
In an MPLAB Harmony project, the "SYS_Initialization" function is called from the "main" function in order to initialize all modules
in the system. This function is implemented as part of a system configuration, normally in a file called "system_init.c". This file
may also include other necessary global system items that must be implemented in order to initialize a system such as processor
configuration bits and system-wide global data structures.
Example "system_init.c" File
// ****************************************************************************
1.1 1. First Time Users MPLAB Harmony Help System Configurations
1-17
// ****************************************************************************
// Section: Configuration Bits
// ****************************************************************************
// ****************************************************************************
#pragma config FPLLODIV = DIV_1, FPLLMUL = MUL_20, FPLLIDIV = DIV_2
#pragma config FWDTEN = OFF, FCKSM = CSECME, FPBDIV = DIV_1
#pragma config OSCIOFNC = ON, POSCMOD = XT, FSOSCEN = ON, FNOSC = PRIPLL
#pragma config CP = OFF, BWP = OFF, PWP = OFF
#pragma config ICESEL = ICS_PGx2
// *****************************************************************************
// *****************************************************************************
// Section: Driver Initialization Data
// *****************************************************************************
// *****************************************************************************
static DRV_USART_INIT uartInit =
{
/* System module initialization */
.moduleInit = {0} ,
/* Identifies USART hardware module (PLIB-level) ID */
.usartID = SYS_USART_ID ,
/* Operation Modes of the driver */
.operationMode = DRV_USART_OPERATION_MODE_RS232 ,
/* Flags for the usart initialization */
.initFlags = 0 ,
/* Control the line control configuration */
.lineControlMode = DRV_USART_LINE_CONTROL_MODE_8NONE1 ,
/* Baud Rate value to be used, if not using auto baud */
.brgValue = APP_UART_BAUDRATE ,
/* Operation mode initialization data */
.operationModeInit = {{0}},
/* Handshake Mode */
.handShakeMode = DRV_USART_HANDSHAKE_MODE_NONE ,
/* Interrupt Source for TX Interrupt */
.txInterruptSource = INT_SOURCE_USART_2_TRANSMIT ,
/* Interrupt Source for RX Interrupt */
.rxInterruptSource = INT_SOURCE_USART_2_RECEIVE ,
/* Interrupt Source for Error Interrupt */
.errorInterruptSource = INT_SOURCE_USART_2_ERROR,
/* Receive Queue length */
.rxQueueSize = 3,
/* Transmit Queue length */
.txQueueSize = 3
};
// *****************************************************************************
// *****************************************************************************
// Section: System Data
// *****************************************************************************
// *****************************************************************************
1.1 1. First Time Users MPLAB Harmony Help System Configurations
1-18
/* Structure to hold the sample application's system data. */
SAMPLE_SYSTEM_OBJECTS sysSample;
// ****************************************************************************
// ****************************************************************************
// Section: System Initialization
// ****************************************************************************
// ****************************************************************************
void SYS_Initialize ( void* data )
{
/* Inialize the system */
sysSample.usart = DRV_USART_Initialize(SYS_USART_DRIVER_INDEX, (SYS_MODULE_INIT
*)&uartInit );
/* Initialize the Application */
APP_Initialize ( );
}
In addition to the "SYS_Initialize" function implementation, the above example "system_init.c" file from the "pic32mx_default"
configuration of the "sample" project defines the processor configuration bits, a data structure used to initialize the USART driver,
and a global "sysSample" data structure used to hold a global handle to the USART driver object returned by the driver's
initialization function.
Notice that the "SYS_Initialize" function initializes first the driver, then the application. These are the only two active modules in
this system.
1.1.6.3 system_tasks.c
This topic describes the purpose of the system tasks file.
Description
Since MPLAB Harmony modules are state machine driven, they each have a "Tasks" function that must be called repeatedly
(from the system-wide "super" loop in "main" or from an ISR or OS thread). The "Tasks" functions are all called from the top-level
"SYS_Initialize" function that is normally implemented in a file called "system_tasks.c" that is part of a system configuration.
Example "system_tasks.c" File
void SYS_Tasks ( void )
{
/* Call the "tasks" functions for any modules in the system. */
DRV_USART_TasksTX(sysSample.usart);
/* Call the application's tasks routine */
APP_Tasks ( );
}
The "system_tasks.c" file for the "pic32mx_default" configuration of the "sample" project, contains only the implementation of the
"SYS_Tasks" function for that configuration. This function calls the USART driver's transmitter tasks function
"DRV_USART_TasksTX", passing in the driver's object handle returned from the driver's initialization routine, and it calls the
application's tasks function "APP_Tasks" to keep both the driver and the application's state machines running.
1.1.6.4 system_int.c
This topic describes the purpose of the system interrupts file.
1.1 1. First Time Users MPLAB Harmony Help System Configurations
1-19
Description
In an interrupt-driven configuration, any modules (such as drivers or system services) that can be driven from an interrupt must
have their interrupt-capable tasks function(s) called from an Interrupt Service Routine (ISR) "vector" function instead of from the
"SYS_Tasks" function. The form of the definition of the ISR vector function is dependent on what type of PIC microcontroller on
which the system is running. So, any vector functions required are normally implemented as part of the a specific system
configuration in a file normally called "system_int.c"
Example "system_int.c" File
void __ISR ( _UART_2_VECTOR ) _InterruptHandler_USART_2_stub ( void )
{
if ( SYS_INT_SourceStatusGet ( APP_USART_INT_SOURCE_TX ) )
{
/* Call the USART driver's "Tasks" routine */
DRV_USART_TasksTX ( sysSample.usart );
}
}
Notice that, in this example, the ISR function must determine if the interrupt occurred because of a transmitter (TX) interrupt
because on the PIC32 part used by this configuration of the application, this interrupt vector is shared with other types of
interrupts for this USART. Once it has determined that the interrupt is indeed a transmitter interrupt, the ISR calls the USART
driver's TX tasks routine and passed in the USART object handle returned from the driver's initialization function.
Note: The USART driver's "DRV_USART_TasksTX" function is interrupt capable when the USART driver is built with the correct
configuration options.
1.1.7 More Information
Describes what is available from the MPLAB Harmony web page.
Description
Information on MPLAB Harmony is available from microchip.com/harmony.
From this landing page, information on additional downloads, links to a MPLAB Harmony discussion forum, among others is
available.
1.1 1. First Time Users MPLAB Harmony Help More Information
1-20
1.2 2. Creating Your Own Applications
This section describes the steps necessary to create your own MPLAB Harmony applications.
Description
To support the framework, the application (or MPLAB Harmony "system") is responsible for the following:
1. Create a New Project: This can be accomplished by either running the MPLAB X IDE new project wizard or copying and
using a basic template located in the /apps/examples/templates directory. If you copy the template to a new
location, you may be required you to modify your include paths. To use the project wizard, select Microchip Embedded >
Standalone Project. Next, choose the device. The device you choose will determine what peripheral libraries are included in
your MPLAB Harmony project. Continue in the new project Wizard, selecting your hardware and software tools. When you
name and locate your project, there are two choices: 1) You can locate it in the ‘apps’ folder of the MPLAB Harmony
installation or 2) You can locate it outside of the Harmony installation. Placing the project in the ‘apps’ folder of MPLAB
Harmony will require you to copy it if you install a new version of MPLAB Harmony. Installing your project outside of the
MPLAB Harmony installation will require you to modify your include paths when a new version of MPLAB Harmony is
installed. It is recommend to use relative paths when installing in the ‘apps’ folder in MPLAB Harmony. Make sure that your
new project is set to the main (active) project.
2. Determine which MPLAB Harmony Modules are needed for your Application: Modules are divided into four categories;
Peripheral Libraries, System Services, Device Drivers and other libraries (commonly called middleware). To determine your
needs, read the MPLAB Harmony Overview and the Introductory sections for the modules of interest. Some modules have
dependencies while others do not. Peripheral Libraries have no dependencies. Drivers depend on peripheral libraries. System
Services depend on Peripheral Libraries and or Drivers. Your application or its middleware will typically use drivers or system
services.
3. Add the required Module Source Files to your Project: This can be accomplished by reading the help for each module to
determine what source files you need and manually entering them into your project. Alternatively, the MPLAB Harmony
Configurator can be used to select the modules from a list or tree and it will automatically insert the source files into your
project and optionally generate a skeletal template for your project. Note that some modules have multiple implementations
each optimized for different purposes. Others may implement optional features in multiple files. Be sure to select the source
file right for your implementation and be sure to include the pre-built peripheral library binary “.a” file for the processor you
selected in your project.
4. Configure The Modules: With the exceptions of the Peripheral Libraries, every MPLAB Harmony module will require some
set of build time configuration options implemented using ‘c’ language macros ‘#define’. Descriptions of the supported options
are available in the "Configuring the Library" section in the help document for every MPLAB Harmony library. These options
must be defined in the system_config.h header that is part of your project template generated by the MPLAB Harmony
Configurator. Every MPLAB Harmony source file that supports build time configuration options will include this header. As
such, this file must be part of every MPLAB Harmony Project.
5. Initialize System: This task involves completing the system_init.c file. First add the necessary configuration bits for your
processor. These are defined in the Special Features section of your device's data sheet. The next step is to complete the
SYS_Initialize function. Finish any necessary processor initialization (wait states, cache control, etc.) MPLAB Harmony may
provide services to accomplish this in the System Services Module. Initialize any features specific to the board that are not
initialized by other modules such as drivers or system services. Next, initialize all library modules selected in step 2 above
used by your application. To do this you must first define the initialization data structure for each module. This can be done
statically in the system_init.c file and passed in by pointer to the appropriate initialization function for each library. Needed
initialization structures can be found in the help section for each module. Add a call to the initialization function for each library
module into the SYS_Initialize function. Each initialization function will return an object handle for the module instance. These
should be captured so that they can be passed to the module task routine. Finally, add the call to APP_Initialize function into
the SYS_Initialize function.
6. Call System State Machine Tasks: The system must call the various task state machine functions at appropriate times. This
is accomplished by either adding the call into the SYS_Tasks function for polled modules or adding the call to the interrupt
handler for interrupt driven modules. The object handle saved during the initialization process is used as an argument for the
various task state machine functions. The SYS_Tasks function is typically implemented in the system_tasks.c file while the
interrupt handlers are defined in the system_int.c file.
1.2 2. Creating Your Own Applications MPLAB Harmony Help
1-21
7. Develop Application State Machine: You are now ready to develop your application. Since Harmony is based on
cooperative state machines, your application should also be state machine driven. At minimum, the APP_Initialize function
must put your application in its initial state. It may perform other initialization as long as it does not have to wait for other
modules. Any initialization that depends on other modules should be implemented as part of the application state machine.
Finally, complete your application functionality by implementing the APP_Tasks state machine function.
1.2 2. Creating Your Own Applications MPLAB Harmony Help
1-22
1.3 3. Release Notes & Information
This section contains release notes for this release and information on version numbers and release types.
1.3.1 Release Notes
Release notes for MPLAB Harmony v0.70b. Target Release Date: November 18, 2013.
Description
Please refer to Release Contents for a complete list of modules that are provided in this release.
MPLAB Harmony is a framework of system services, device drivers, and other libraries that are built upon a base of portable
peripheral libraries to provide flexible, portable, and consistent software “building blocks” which you can use to develop your
embedded PIC32 applications.
This is the first fully public release of MPLAB Harmony. Previous releases were internal to Microchip and had very limited
external distribution.
A complete list of the contents of this release is provided in the Release Contents section. You can find these contents under the
installation folder you selected in the following sub-folders:
• “apps” – Contains all demo and example applications provide with this installation.
• “bin” – Contains pre-built binary libraries (“.a” files) for the MPLAB Harmony peripheral libraries for each supported processor
and for key libraries provided in binary form.
• “bsp” – Contains MPLAB Harmony board support packages provided for selected Microchip demo and development boards.
• “build” – Provides MPLAB X IDE projects that you can use to re-build the libraries provide under the “bin” folder (in case you
want to use different build settings).
• “doc” – Contains the MPLAB Harmony help documentation in PDF and MPLAB X IDE “.nbm” plug-in formats.
• “framework” – Contains source code and API headers for all MPLAB Harmony libraries that are provided in source form.
• “third_party” – Contains MPLAB Harmony compatible libraries and Real-Time Operating Systems (RTOS) provided with this
installation.
• “utilities” – Contains design and development utilities and MPLAB X IDE plug-in utilities provided with MPLAB Harmony.
Please review the following key help topics (and their subtopics) to gain an initial understanding of what MPLAB Harmony is and
how to use it.
• Start Here > First Time Users
• Start Here > Creating your Own Applications
• MPLAB Harmony Configurator Help
• The “Introduction” sections of the individual help topics for the system services, drivers, and libraries that are of interest to you
• Applications Help > Applications Overview
• The “Introduction” sections of the individual applications help topics
Once you have a basic understanding of MPLAB Harmony, you can begin using the provided demo and example applications to
explore it’s capabilities and begin developing your own applications.
1.3 3. Release Notes & Information MPLAB Harmony Help Release Notes
1-23
Before developing your own applications, be sure to look at the example “template” application provided in the
“/apps/examples/templates” folder.
The following sections provide a brief overview of items that are new in this release and known issues at the time of the release.
Refer to the “Release Notes” section under the help topic for each individual library, application, or utility for additional details.
Refer to the “Using the Library” section for each individual library for a description of how to use library functions to accomplish
the tasks that the library was intended to support.
Refer to the “Library Interface” section for each individual library for a programmer’s reference or dictionary of functions and data
types defined by that library’s interface.
New This Release:
• Significant SD Card Driver improvements.
• The SPI driver has had configuration and interoperability improvements.
• The NVM driver now handles sector erasing during writes.
• USB Driver demonstrations
• TCP/IP Stack updates (see the TCP/IP Stack Library Help)
• Graphics Library API has been updated
• File System Service Library has been updated
• The following System Services have been added: Clock and Device Control
• USART Driver has been updated
• USB Driver has been updated
• Peripheral Libraries now support PIC32MZ devices
• FreeRTOS now supports PIC32MZ devices
• CyaSSL Library has been added
Known Issues:
• The SD Card driver has had limited testing and is missing a few desired features
• The SPI driver does not support slave mode or DMA
• The NVM driver has only been tested in it’s current memory configuration
• NVM Driver demonstration has limited testing
• SPI Driver demonstration has limited testing and hardware support
• USART Driver demonstration does not support PIC32MZ devices
• USB demonstrations (see the related Release Notes)
• USB Host Stack has limited testing and functional limitations (see the related Release Notes)
• USB Device Stack has limited testing and functional limitations (see the related Release Notes)
• No multi-display support for the Graphics Primitive Library
• File System Service Library does not support MIP16 mode, has limited testing and functional limitations (see the related
Release Notes)
• USART Driver has flow control and parity mode limitations and no multi-client support
• MRF24W Wi-Fi Driver Library has limited demonstration support and testing (see the related Release Notes)
1.3 3. Release Notes & Information MPLAB Harmony Help Release Contents
1-24
1.3.2 Release Contents
This topic lists the contents of this release and identifies the individual version numbers of each module.
Description
This table lists the contents of this release, including a brief description of each module.
Cryptographic Applications:
/apps/crypto/
Crypto Demonstration Crypto Library Demonstration 1.00
Example Applications:
/apps/examples/
peripheral/blocking/pic32mz Simple blocking PLIB examples. 1.00
peripheral/blocking/pic32mx Simple blocking PLIB examples 1.00
state_driven Simple MPLAB Harmony compliant state-driven Peripheral Library
examples
1.00
sample Sample “Hello World” demonstration used in “Getting Started” guide in
Help system
N/A
DEMOS: Driver Application demos:
/apps/driver/
nvm demo NVM demonstration application 1.00
usart demo USART demonstration application 1.00
spi demo SPI demonstration application 1.00
DEMOS : RTOS Application demos:
/apps/rtos/
freertos FreeRTOS demonstration application 1.00
openrtos OpenRTOS demonstration application 1.00
File System Applications:
/apps/fs/
nvm_fat_single_disk Single-disk Non-Volatile Memory FAT FS Demonstration 1.00
nvm_sdcard_fat_multi_disk Multi-disk Non-Volatile Memory FAT FS Demonstration 1.00
sdcard_fat_single_disk SD Card FAT Disk demonstration 1.00
nvm_mpfs_single_disk Single-disk Non-Volatile Memory 1.00
nvm_sdcard_fat_mpfs_multi_disk Multi-disk Non-Volatile Memory FAT MPFS Demostration 1.00
DEMOS: Graphics Applications:
/apps/gfx/
lcc Low-Cost Controllerless Graphics Demonstration 4.00b
object Graphics Object Layer Demonstration 4.00b
primitive Graphics Primitives Layer Demonstration 4.00b
s1d13517 Epson S1D13517 LCD Controller Demonstration 4.00b
ssd1926 Solomon Systech SSD1926 Controller Demonstration 4.00b
1.3 3. Release Notes & Information MPLAB Harmony Help Release Contents
1-25
DEMOS: TCP/IP Applications &
Utilities: /apps/tcpip/
tcpip_web_server TCP/IP Web Server Demonstration 1.01
bsd_tcp_server TCP/IP BSD Server Demonstration 1.00
bsd_tcp_client TCP/IP BSD Client Demonstration 1.00
bsd_udp_server TCP/IP BSD Server Demonstration 1.00
bsd_udp_client TCP/IP BSD Client Demonstration 1.00
tcpip_tcp_server TCP/IP TCP Server Demonstration 1.00
tcpip_tcp_client TCP/IP TCP Client Demonstration 1.00
tcpip_udp_server TCP/IP UDP Server Demonstration 1.00
tcpip_udp_client TCP/IP UDP Client Demonstration 1.00
wolf_ssl wolf ssl Demonstration 1.00
wifi_console TCP/IP Wi-Fi Console Demonstration
wifi_easyconf TCP/IP Wi-Fi Easy Configuration Demonstration
DEMOS: USB Device (Function)
Applications:
/apps/usb/device/
audio_speaker USB Audio Device Speaker Demonstration 1.00
cdc_com_port_dual CDC Dual Serial COM Ports Emulation Demonstration 1.00
cdc_com_port_single CDC Single Serial COM Port Emulation Demonstration 1.00
generic_device Microchip Generic USB Device Demonstration 1.00
hid_basic Basic USB Human Interface Device (HID) Demonstration 1.00
hid_joystick USB HID-Class Joystick Device Demonstration 1.00
hid_keyboard USB HID-Class Keyboard Device Demonstration 1.00
hid_mouse USB HID-Class Mouse Device Demonstration 1.00
msd_basic USB Mass Storage Device Demonstration 1.00
cdc_serial_emulator CDC Serial Emulation Demonstration 1.00
DEMOS: USB Host Applications:
/apps/usb/host/
msd_simple_thumb_drive USB MSD Host Simple Thumb Drive Demonstration 1.00
cdc_basic USB CDC Basic Demonstration 1.00
cdc_serial USB CDC Serial Demonstration 1.00
hid_keyboard USB HID-Class Joystick Host Demonstration 1.00
hid_mouse USB HID-Class Mouse Host Demonstration 1.00
generic_device Microchip Generic USB Host Demonstration 1.00
Pre-built Binaries: /bin/
framework/peripheral Pre-built Peripheral Libraries 1.00
framework/math/dsp Pre-built DSP libraries for PIC32MZ devices 1.00
framework/math/libq Pre-built fixed-point math libraries for PIC32MZ devices 1.00
1.3 3. Release Notes & Information MPLAB Harmony Help Release Contents
1-26
Board Support Packages (BSPs):
/bsp/
explorer16/pic32mx795f512l Explorer 16 Development Board and PIC32MX795F512L PIM 1.00
sk_pic32_mx_usb PIC32 USB Starter Kit 1.00
sk_pic32_mz PIC32MZ Embedded Connectivity (EC) Starter Kit 1.00
usb_audio_pic32mx PIC32 USB Starter Kit II 1.00
gfx Graphics (GFX) boards 1.00
Documentation: /doc
doc/org-microchip-harmony_help.nbm MPLAB Harmony Help MPLAB X IDE Plug-In 0.70b
doc/harmony_help.pdf MPLAB Harmony Help 0.70b
Middleware & Libraries:
/framework/
Crypto (Software) Microchip Cryptographic Libraries 1.00
GFX Graphics Library 4.00b
MATH/DSP API header for PIC32MZ DSP Libraries 1.00
MATH/LIBQ API header for PIC32MX fixed-point libraries 1.00
AAC/MP3 Audio Decoder Libraries 1.00
TCP/IP TCP/IP Network Stack 7.10
USB Host USB Host Stack 0.02b
USB Device USB Device Stack 0.05b
Device Drivers:
/framework/driver/
adc Analog-to-Digital Converter Driver 0.01b
ethmac Ethernet Media Access Controller Driver 7.10
ethphy Ethernet Physical Interface Driver 7.10
gfx/gfx_lcc Low-Cost Controllerless Graphics Driver 4.00b
gfx/gfx_otm2201a OTM LCD Controller Driver 4.00b
gfx/gfx_s1d13517 Epson S1D13517 LCD Controller Driver 4.00b
gfx/gfx_ssd1926 Solomon Systech SSD1926 Controller Driver 4.00b
nvm Non-Volatile Memory Driver 0.50b
pmp Parallel Master Port Driver 0.50b
sdcard SD Card Driver (Client of SPI Driver) 0.50b
spi Serial Peripheral Interface (SPI) Driver 0.50b
tmr Timer Driver 0.50b
usart Universal Synchronous/Asynchronous Receiver/Transmitter (USART)
Driver
0.50b
usb/usbhs Universal Serial Bus (USB) Controller Driver 0.05b
wifi/mrf24w Wi-Fi MAC driver for the MRF24W controller 3.0.0
1.3 3. Release Notes & Information MPLAB Harmony Help Release Contents
1-27
Operating System Abstraction Layer
(OSAL): /framework/osal
osal.h OSAL Interface 0.52b
osal_freertos.h
osal_freertos.c
OSAL Implementation for FreeRTOS 0.52b
osal_openrtos.h
osal_openrtos.c OSAL Implementation for OpenRTOS
0.52b
osal_impl_basic.h OSAL “bare metal” (no OS) implementation 0.52b
osal_imple_none.h OSAL implementation that removes the OSAL when not used 0.52b
osal_ucos3.h
osal_ucos3.c
OSAL Implementation for Micrium µCOS-III 0.52b
osal_ucos2.h
osal_ucos2.c
OSAL Implementation for Micrium µCOS-II N/A
osal_threadx.h OSAL Implementation for Express Logic ThreadX N/A
osal_threadx.c N/A
Peripheral Libraries: /
framework/peripheral Peripheral Library Source Code for all Supported PIC32 Processors 0.70b
Build Framework:
/build/framework/
crypto/test Test Vector App for crypto/zlib 1.00
crypto/zlib zlib library 1.00
crypto/crypto crypto library 1.00
peripheral Peripheral Library build project 1.00
math/libq libq library build project 1.00
math/DSP DSP library build project 1.00
System Services:
/framework/system/
clk Clock Services Library 0.04a
common Common Services 0.02a
devcon Devcon Services Library 0.02b
fs File System Services Library 0.50b
int Interrupt Services Library 0.04a
msg Message Services Library 0.01a
ports Input/Output Ports Services Library 0.02b
tmr Software Timer Services Library 0.02a
wdt Watchdog Timer Services Library 0.02b
Third-Party Software:
/third_party/
1.3 3. Release Notes & Information MPLAB Harmony Help Release Contents
1-28
rtos/FreeRTOSV7.5.2 FreeRTOS Source Distribution v7.5 with support for PIC32MZ devices Yes
(Vendor
Version)
rtos/FreeRTOSVX.XX.XX FreeRTOS Source Distribution v7.5 with support for PIC32MX devices Yes
(Vendor
Version)
rtos/OpenRTOSVx.x.x OpenRTOS Source Distribution vx.x.x with support for PIC32MZ
devices
Yes
(Vendor
Version)
rtos/OpenRTOSVx.x.x OpenRTOS Source Distribution vx.x.x with support for PIC32MX
devices
Yes
(Vendor
Version)
uC/OS-III Micrium uC/OS-III Binary Demonstration with support for PIC32MZ
devices
Yes
(Vendor
Version)
uC/OS-III Micrium uC/OS-III Binary Demonstration with support for PIC32MX
devices
Maybe
(Vendor
Version)
uC/OS-II Micrium uC/OS-II Binary Demonstration (PIC32MZ)
uC/OS-II Micrium uC/OS-II Binary Demonstration (PIC32MX)
ThreadX Express Logic (ThreadX) Demonstration with Support for PIC32MZ
devices
CyaSSL Embedded SSL Library Open Source based demonstration 2.8.0
(Vendor
Version)
CyaSSL Embedded SSL Library Open Source based demonstration Yes
(Vendor
Version)
InterNiche Technologies, Inc. Suitable TCP/IP demonstrations Yes
(Vendor
Version)
Utilities: /utilities/
MPLAB Configurator MPLAB Harmony Project/Library Configurator MPLAB X IDE Plug-In 0.02a
gfx/gdd Graphics Display Designer 2.00b
gfx/grc Graphics Resource Compiler 4.00.39
mib2bib/mib2bib.jar Compiles Custom Microchip MIB script (snmp.mib) to generate
snmp.bib and mib.h
2.00
mpfs_generator/mpfs2.jar TCP/IP MPFS File Generator and Upload Utility 2.02.06
tcpip_discoverer/tcpip_discoverer.jar TCP/IP Microchip Node Discoverer Utility 2.00
1.3.3 Version Numbers
This section describes the version numbers and their meaning.
1.3 3. Release Notes & Information MPLAB Harmony Help Version Numbers
1-29
Description
MPLAB Harmony Version Numbering Scheme
Libraries released with MPLAB Harmony each have their own version number, using the following scheme.
.[.<“dot”>][]
• Major revision (architecture or paradigm shift)
• Minor revision (new features, regular releases)
• “Dot” release (bug fixes, unscheduled releases)
• Release Type (‘a’ = alpha, ‘b’ = beta, Full release versions 1.0 or above have no type letter)
Items in square brackets are only present when needed (see examples, below).
Examples:
• MPLAB Harmony USB Library v2.6 (“dot” of ‘0’ implied)
• MPLAB Harmony Graphics Library v1.12.02
Note: The version number of the over all MPLAB Harmony release is not related to the version numbers of each individual
library or module included in the release and has no bearing on the versions of any libraries it includes. It is merely a way to keep
track of what libraries (and what versions of what libraries) are included in each release. Refer to the current release notes to
identify what libraries are included and what their version numbers are.
1.3.4 Release Types
This section describes the release types and their meaning.
Description
MPLAB Harmony module releases can be of three different types, based on the version type.
Alpha Release
An alpha release version of a module is usually an initial release. Alpha releases will have complete implementations of their
basic feature set, they are unit tested (usually by the original developer) and will build correctly in their basic configuration. An
1.3 3. Release Notes & Information MPLAB Harmony Help Release Types
1-30
alpha release is a great "preview" of what a new development Microchip is working on and it can be very helpful for exploring
new features. However, it has not gone through a formal test process and it is almost certain that some of its interface will
change before the full version is released. It is not recommended for production use.
Beta Release
A beta release version of a module has gone through the internal interface review process and has had formal testing of its
functionality. Also, issues reported from the alpha release will have been fixed or documented. When a module is in a beta
version, you can expect it to function correctly in normal circumstances and you can expect that its interface is very close to the
final form (although changes can still be made if required). However, it has not had stress testing or been tested and it may not
fail gracefully if used incorrectly. A beta release is not recommended for production use, but it can be used for development.
1.0+ Release
By the time a module is released as a 1.0 version or above, it is feature complete, fully tested, and its interface is "frozen". All
known issues from previous releases will have been fixed or documented. The existing interface will not change in future
releases. It may be expanded with additional features and additional interface functions, but existing interface functions will not
change. This is stable code with a stable Application Program Interface (API) that you can rely on for production purposes.
1.3 3. Release Notes & Information MPLAB Harmony Help Release Types
1-31
1.4 4. Previous Releases
This topic contains information about past version(s) of MPLAB Harmony.
1.4.1 v0.51.03b
Release notes for MPLAB Harmony v0.51.03b.
Description
This topic contains the release notes for MPLAB Harmony v0.51.03b. Please refer to the Release Contents topic for a complete
list modules that are provided in this release.
This release will support MPLAB X IDE v1.95 and XC32 v1.30 tc9 and above.
New this Release
• Updated the Documentation
• Updated Peripheral Pre-Built Binary Libraries (".a" files)
• Added IPv6 API for generation of the Unique Local Address (ULA)
Known Issues
1. No documentation available for the Crypto libraries and peripheral libraries example applications.
2. For TCP/IP stack running on PIC32MZ platforms the write-back mode is not supported yet. Write-through has to be used for
now.
3. Early samples of the PIC32MZ silicon do not have a factory pre-programmed MAC address. This will cause the TCP/IP stack
and related applications to not properly run in most network configuration. Manual update of the related "network_config.h" file
with a valid MAC address is required.
4. The Wi-Fi driver for the TCP/IP stack and the supporting demos are not part of this release.
This table lists the contents of this release, gives a brief description
Module Description Version
File System Applications:
/apps/fs/
nvm_fat_single_disk Single-disk Non-Volatile Memory FAT FS Demonstration 0.02a
nvm_sdcard_fat_multi_disk Multi-disk Non-Volatile Memory FAT FS Demonstration 0.02a
sdcard_fat_single_disk SD-Card FAT Disk Demonstration 0.02a
nvm_mpfs_single_disk Single-disk Non-Volatile Memory MPFS Demonstration 0.02a
nvm_sdcard_fat_mpfs_multi_disk Multi-disk Non-Volatile Memory FAT MPFS Demonstration 0.02a
Graphics Applications:
/apps/gfx/
lcc Low-Cost Controllerless Graphics Demonstration 0.51b
object Graphics Object Layer Demonstration 0.51b
1.4 4. Previous Releases MPLAB Harmony Help v0.51.03b
1-32
primitive Graphics Primitives Layer Demonstration 0.51b
ssd1926 Solomon Systech SSD1926 Controller Demonstration 0.51b
TCP/IP Applications & Utilities:
/apps/tcpip/
tcpip_web_server TCPIP Web Server Demonstration 7.02a
utilities/mpfs_generator/mpfs2.jar TCP/IP MPFS File Generator and Upload Utility 2.2.5
utilities/tcpip_dicoverer/tcpip_discoverer.jar TCP/IP Microchip Node Discoverer Utility 2.0
utilities/mib2bib/mib2bib.jar Compiles Custom Microchip MIB script ( snmp.mib) to generate
snmp.bib and mib.h
2.0
USB Device (Function) Applications:
/apps/usb/device/
audio_speaker USB Audio Device - Speaker Demonstration 0.51b
cdc_com_port_dual CDC Dual Serial COM Ports Emulation Demonstration 0.51b
cdc_com_port_single CDC Single Serial COM Ports Emulation Demonstration 0.51b
generic_device Generic USB Device Demonstration 0.51b
hid_basic USB Human Interface Device (HID) Demonstration 0.51b
hid_joystick USB HID Joystick Device Demonstration 0.51b
hid_keyboard USB HID Keyboard Device Demonstration 0.51b
hid_mouse USB HID Mouse Device Demonstration 0.51b
msd_basic USB Mass Storage Device Demonstration 0.51b
USB Host Applications:
/apps/usb/host/
cdc_serial USB CDC Host Demonstration 0.51b
Crypto Applications: /apps/
crypto Wolf SSL Cryptographic Demonstration 0.01a
PIC32MZ Applications: /apps/
pic32mz PIC32MZ Device Demonstration 0.51.01b
Example Applications:
/apps/examples
peripheral Peripheral Demonstration 0.51b
sample Sample Demonstration 0.51b
Board Support Packages
(BSPs): /bsp/
explorer16/pic32mx795f512l Explorer 16 Development Board and PIC32MX795F512L PIM
pic32_sk/pic32_usb_sk PIC32 USB Starter Kit
pic32_sk\pic32mz_sk PIC32MZ Starter Kit
pic32mx_usb_audio PIC32 USB Digital Audio Accessory Board
Third Party
Software: /third_party/
rtos/FreeRTOSV7.5.0 FreeRTOS Source Distribution v7.5.0 7.5.0
Middleware: /framework/
1.4 4. Previous Releases MPLAB Harmony Help v0.51.03b
1-33
gfx Graphics Library 0.51b
tcpip TCP/IP Network Stack 7.02a
usb USB Host & Device Stack 0.51b
Crypto Library: /framework/
crypto Wolf SSL Cryptographic Libraries 0.01a
System Services:
/framework/system/
clk Clock Services Library 0.03a
debug Debug Services Library 0.01a
fs File System Services Library 0.02a
int Interrupt Services Library 0.03a
msg Message Services Library 0.01a
ports Input-Output Ports Services Library 0.01a
reset System Reset Services Library 0.01a
tmr Software Timer Services Library 0.01a
wdt Watchdog Timer Services Library 0.01a
Device Drivers:
/framework/driver/
adc Analog-to-Digital Converter Driver 0.01a
ethmac Ethernet Media Access Controller Driver 0.03a
ethphy Ethernet Physical Interface Driver 0.03a
gfx/gfx_lcc Low-Cost Controllerless Graphics Driver 0.51b
gfx/gfx_s1d13517 Epson S1D13517 LCD Controller Driver 0.51b
gfx/gfx_ssd1926 Solomon Systech SSD1926 Controller Driver 0.51b
nvm Non-Volatile Memory Driver 0.01a
pmp Parallel Master Port Driver 0.01a
sdcard SD Card Driver (Client of SPI Driver) 0.01a
spi Serial Peripheral Interface (SPI) Driver 0.01a
tmr Timer Driver 0.01a
usart Universal Synchronous/Asynchronous Receiver/Transmitter
(USART) Driver
0.01a
usb Universal Serial Bus (USB) Controller Driver 0.51b
usbhs Hi-Speed USB Controller Driver 0.51b
wifi Wi-Fi Driver 0.01a
Peripheral Libraries (PLIBs): /
framework/peripheral Peripheral Library Source Code 0.51b
bin/framework/peripheral Peripheral Pre-Built Binary Libraries for all PIC32 Processors 0.51b
build/framework/peripheral Project used for Peripheral Library Prebuilt Binary Libraries
Creation
0.51b
1.4 4. Previous Releases MPLAB Harmony Help v0.51.03b
1-34
Operating System Abstraction Layer
(OSAL): /framework/osal/
osal.h
osal.c
OSAL interface 0.51b
osal_impl_none.h OSAL implementation that removes the OSAL when not used 0.51b
osal_impl_basic.h OSAL "bare metal" (no OS) implemenrtation 0.51b
osal_freertos.h
osal_freertos.c
OSAL implementation for FreeRTOS 0.51b
osal_ucos.h
osal_ucos.c
OSAL implementation for Micrium uCOS-III 0.51b
1.4 4. Previous Releases MPLAB Harmony Help v0.51.03b
1-35
1.5 5. Tips and Tricks
This topic provides a few helpful tips and tricks to keep in mind while developing your MPLAB Harmony projects.
Description
You may find the following MPLAB Harmony "tips" and "tricks" helpful when developing your own MPLAB Harmony projects.
1. After creating a new MPLAB X IDE project, use the project wizard to add MPLAB Harmony libraries to your project and create
a set if initial files for your project. After that, your job is to ensure that the necessary initialization and configuration data and
definitions are in place and to write your own application.
2. You can use MPLAB Harmony example and demo projects to put together a "first approximation" of your application.
1. Copy the source files from the various example or demo apps to your project.
2. Rename the "APP_Initialize" and "APP_Tasks" functions so that they are all different and will build in your application by
simply appending a descriptive name to the end of the existing function names. (Note: you may also need to rename any
global data "objects" that conflict with each other from the examples).
3. Call the individual "APP_Initialize" and "APP_Tasks" functions from the "SYS_Initialize" and
"SYS_Tasks" functions in your application's configuration files.
4. Use the project wizard to add any required drivers, services, or middleware.
5. At this point, you now have your application made out of several independent state machines. Now, you can begin to
develop your own custom application code and modifying any of the code copied from the provided applications to behave
as you desire.
1.5 5. Tips and Tricks MPLAB Harmony Help
1-36
1.6 6. Glossary
This section contains a glossary of general MPLAB Harmony terms.
Description
Glossary of Harmony Terms
Term Definition
Application One or more application modules define the over all behavior of an MPLAB Harmony system. Applications are
either demonstrations or examples provided with the installation or are implemented by you, using MPLAB
Harmony libraries to accomplish a desired task.
Client A client module is any module that uses the services (calls the interface functions) of another module.
Configuration An MPLAB Harmony configuration consists of static definitions (C-language "#define" statements), executable
source code, and other definitions in a set of files that are necessary to create a working MPLAB Harmony
system. (See Start Here for additional information.)
Configuration
Options
Configuration options are the specific set of "#define" statements that are required by any specific MPLAB
Harmony library to specify certain parameters (such as buffer sizes, minimum and maximum values, etc.) build
that library. Configuration options are defined in the "system_config.h" system-wide configuration header.
Driver A "driver" (AKA device driver) is an MPLAB Harmony software module designed to control and provide access
to a specific peripheral, either built into the microcontroller or external to it.
Driver Index Dynamic MPLAB Harmony drivers (and other dynamic modules) can manage the more than one instance of the
peripheral (and other resources) that they control. The "driver index" is a static index number (0, 1, 2,...) that
identifies which instance of the driver is to be used.
Note: The driver index is not necessarily identical to the peripheral index. The association between these two is
made when the driver is initialized.
Driver
Instance
An instance of a driver (or other module) consists of a complete set of the memory (and other resources)
controlled by the driver's code. Selection of which set of resources to control is made using a driver index.
Note: Even though there may be multiple instances of the resources managed by a dynamic driver, there is only
ever one instance of the actual object code. However, static drivers always maintain a 1:1 relationship between
resource and code instances.
Framework The MPLAB Harmony framework consists of a set of libraries (and the rules and conventions used to create
those libraries) that can be used to create MPLAB Harmony systems.
Initialization
Overrides
Initialization overrides are configuration options that can be defined to statically override (at build time)
parameters that are normally passed into the "Initialize" function of a driver or other MPLAB Harmony module.
This mechanism allows you to statically initialize a module, instead of dynamically initializing the module.
Interface The interface to a module is the set of functions, data types, and other definitions that must be used to interact
with that module.
Middleware The term "middleware" is used to describe any software that fits between the application and the device drivers
within an MPLAB Harmony system. It is something of a catch all term that is loosely used to describe libraries
that use drivers to access peripheral and then implement communication protocols (such as TCP/IP, USB
protocols, and graphics image processing) and other more complex processing that is required to use certain
peripherals, but is not properly part of controlling the peripheral itself.
Module An MPLAB Harmony software module is a closely related group of functions controlling a related set of
resources (memory and registers) that can be initialized and maintained by the system. Most MPLAB Harmony
modules provide an interface for client interaction. However, "headless" modules with no interface are possible.
1.6 6. Glossary MPLAB Harmony Help
1-37
Peripheral
Index
A peripheral index is a static label (usually an C-language "enum" value) that is used to identify a specific
instance of a peripheral.
Note: Unlike a driver index, which always starts at '0', a peripheral index may be internally represented as any
number, letter, or even a base address and the user should not rely on the value itself - only the label.
Peripheral
Instance
An instance of a peripheral is a complete set of the registers (and internal physical resources) necessary to
provide the core functionality of a given type of peripheral (either built into the microcontroller or external to it).
Note: A specific peripheral instance is identified using a peripheral index.
System An MPLAB Harmony system is a complete set of libraries, applications, and configuration items loaded and
executing on a specific hardware platform (microcontroller, board, and external peripherals) or the source items
necessary to build such a system.
Note: Since a system can multiple configurations, one MPLAB Harmony project may support multiple systems
through multiple supported configurations. See the demo applications included in the installation for examples.
System
Service
A system service is an MPLAB Harmony module that provides access to and/or control of common system
resources (memory and registers) with which other modules (drivers, middleware, libraries and application) may
interact.
Note: System services, much like drivers, manage sharing of resources so as to avoid conflicts between
modules that would otherwise occur if each module attempted to manage the share resource itself. But, unlike
drivers, system services do not normally need to be "opened" in order to use them.
1.6 6. Glossary MPLAB Harmony Help
1-38
2 MPLAB Harmony Configurator Help
2 MPLAB Harmony Help
2-39
2.1 MPLAB Harmony Configurator
2.1.1 Introduction
This topic provides an overview of the MPLAB Harmony Configurator.
Description
The MPLAB Harmony Configurator is a MPLAB X IDE plug-in. It must be installed into your MPLAB X IDE installation to be used.
2.1.2 Release Notes
MPLAB Harmony Version: v0.70b Release Date: 18Nov2013
Description
====================================
Version 0.02a
MPLAB Harmony Configurator Plug-in
November 2013
====================================
Operating System Support
MPLAB Harmony Configurator Plug-in was tested on the following operating systems:.
• Windows XP SP3 and Windows 7
• Linux OS - Ubuntu
• Mac OS v8
Supported Features:
• Provides a simple hierarchical way for users to select the MPLAB Harmony modules to be used in the project and adds the
selected module source files with the necessary configuration and project settings (include path) into the created MPLAB X
IDE project.
• Supports importing project related files from relative path.
• Adds predefined source and header template files to the MPLAB X IDE project.
• Library Configuration is supported only for the TCP/IP and USB libraries.
Unsupported Features:
• System-related API calls are not added automatically to the system_init.c, main.c, and system_tasks.c files. Only the standard
C templates are added to the project. The application code must be added by the user in the application source and header
2.1 MPLAB Harmony Configurator MPLAB Harmony Help Release Notes
2-40
files for a successful compilation of the project.
• Library Configuration is not supported for the Graphics library, OSAL, Drivers and Third-Party libraries. However, the
corresponding source and header files of the selected modules could be added to the created MPLAB X IDE project using this
Configurator.
Notes for Users:
1. The terms "MPLAB Configurator" and "MPLAB Configuration Wizard" are used interchangeably throughout the MPLAB
Harmony Help.
2. Check for "TODO" tags that are placed in added template files for directions on what sections in the code should be modified
or code to be added by the user. Look for system_config.h, system_init.c, system_int.c, system_tasks.c, app.c, app.h, and
main.c files.
Known Issues:
• The Configurator Plug-in generated template files are stored in the MPLAB X IDE project folder (inside the
MPLABX_Project.X folder). Users need to add the current directory ‘.’ Path in the MPLAB X Project “properties” > gcc >”
include path settings” for removing “the template file not found error”.
• The created project may compile but not work, as application and system related API calls are not added automatically to the
system_init.c, main.c and system_tasks.c. Only the standard C templates are added to the project.
• The MPLAB Harmony Configurator version during installation or in the plug-in description is shown as 0.0.2 where as the
actual version of the tool is “0.02a”.
• Certain TCP/IP configuration files are getting modified from the default MPLAB Harmony installation directory if the TCP/IP
stack is configured using the Configurator. It is recommended to backup these default configuration files: tcpip_config.h,
http_config.h, snmp_config.h, ssl_config.h, and telnet_config.h, in case it is necessary to revert back to the default
configuration.
• TCPIP system_config.h file is not modified in this release of the Configurator to add the configurations from “ *
*_config.h”. As explained above, the specific module files get updated.
• The Configurator is not preserving the previous project configuration if the TCP/IP sub-modules are selected using the ‘Select
to add default modules’ checkbox in the “TCPIP Stack -> tcpip” module tree.
• Warning message about ‘template files getting overwritten (if already present)’ is not shown if the USB library configuration is
selected.
2.1.3 SW License Agreement
(c) 2013 Microchip Technology Inc.
Microchip licenses this software to you solely for use with Microchip products. The software is owned by Microchip and its
licensors, and is protected under applicable copyright laws. All rights reserved.
SOFTWARE IS PROVIDED "AS IS" MICROCHIP EXPRESSLY DISCLAIMS ANY WARRANTY OF ANY KIND, WHETHER
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL MICROCHIP BE LIABLE FOR
ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, HARM TO
YOUR EQUIPMENT, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS
BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR
CONTRIBUTION, OR OTHER SIMILAR COSTS.
To the fullest extent allowed by law, Microchip and its licensors liability shall not exceed the amount of fees, if any, that you have
paid directly to Microchip to use this software.
MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE TERMS.
2.1 MPLAB Harmony Configurator MPLAB Harmony Help SW License Agreement
2-41
2.2 Using the Configurator
2.2.1 Installing the Configurator Plug-in
The MPLAB Harmony Configurator is a MPLAB X IDE plug-in. It must be installed into your MPLAB X IDE installation to be used.
Description
Location
The MPLAB Harmony Configurator (MPLAB X IDE plug-in) is located in the following folder in the MPLAB Harmony installation.
\utilities\configurator\com-microchip-harmonyconfigurator.nbm
Installation
1. Start MPLAB X IDE and select "Plugins" from the "Tools" menu as shown below.
2. Select the “Downloaded” tab.
3. Click the "Add Plugins..." button, browse to \utilities\configurator\ and open the plug in file
"com-microchip-harmonyconfigurator.nbm" as shown below
2.2 Using the Configurator MPLAB Harmony Help Installing the Configurator Plug-in
2-42
4. Ensure that the Check box for the "MPLAB Harmony Configurator" plug-in is selected. Click "Install" as shown below.
2.2 Using the Configurator MPLAB Harmony Help Installing the Configurator Plug-in
2-43
5. Follow the prompts from the installation wizard and continue until the installation completes. Just click "continue”. Once the
installation wizard has finished you can close the "Plugins" dialog box.
You should now see a "MPLAB Harmony Configurator" option under the "Tools" menu. This indicates that the project wizard was
successfully installed.
2.2.2 Running the Configurator Plug-in
This session describes how to run the MPLAB Harmony Configurator to add required files from selected modules into MPLAB X
IDE project.
Note: This version of the Configurator provides Project Configuration (to add files into MPLAB X IDE project) and limited Library
Configuration (only for configuring a few sub-modules of the TCP/IP and USB middleware) capability.
Description
1. To run the Configurator, select "MPLAB Harmony Configurator" from the "Tools" menu.
2. Browse to the root installation folder of the version of MPLAB Harmony that you're using. This folder must contain
"manifest.xml". This file has the information and the path of various software modules available in the installed MPLAB Harmony
version. manifest.xml file should not be moved or deleted from Root directory. Click "Next" when the root path is set.
2.2 Using the Configurator MPLAB Harmony Help Running the Configurator Plug-in
2-44
Note: It is recommended that you create and maintain your MPLAB X IDE project under a subdirectory of the
"/apps" folder and use a relative path to this project.
3. In the Left-hand pane of the "Select Modules and Configurations" dialog, select the desired modules and respective
sub-modules. The right-hand pane shows a brief introduction of the selected module. Click "Next" when the required modules for
the project are selected.
2.2 Using the Configurator MPLAB Harmony Help Running the Configurator Plug-in
2-45
The tool has two configuration sections.
• Project Configuration: All the required modules and Sub modules could be selected here. The respective files would be
added into the MPLAB X IDE project. (example: Graphics, TCP/IP, USB CDC, USB HID selection)
• Library Configuration: The individual configuration of each module could be done here. (Configuration for selected module
from the selected section.)
If the user is required to add their custom module into the MPLAB Harmony directory structure and add the files into the project
through Configurator, the manifest.xml should be modified to accommodate the custom module files. This would allow the
Project Configurator to add the files to the MPLAB X IDE project from the manifest.xml for the custom module. This would not
provide custom configuration capability, however the files can be added to the MPLAB X IDE project.
4. If there are any XML modifications those can be reflected by reloading the tree. To reload the project tree structure, right-click
on “harmony” tree node and click "Reload Tree".
5. To get back to default project configuration of MPLAB Harmony, right-click on “harmony” tree node and click "Load default".
2.2 Using the Configurator MPLAB Harmony Help Running the Configurator Plug-in
2-46
Note: Next window pane is for individual library (Modules and Sub modules) configuration. Currently only TCP/IP and USB
library configuration is supported.
Though all the sub-modules of TCP/IP can be enabled or disabled through project configuration window pane, the individual sub
module configuration is supported only for HTTP, SSL, SNMP and Telnet server. For USB, only CDC and HID class
configuration basic support is provided.
Library Configuration
1. In the "Project configuration" pane, to configure USB CDC select the respective modules and click “Next”. Next window pane
is Library Configuration window as shown below. Configure USB CDC as required, click “Next”.
2.2 Using the Configurator MPLAB Harmony Help Running the Configurator Plug-in
2-47
2. In the "Application Template" pane, select the "Include application template" check box and select "Finish" to add the module
files and template files to the MPLAB X IDE project.
2.2 Using the Configurator MPLAB Harmony Help Running the Configurator Plug-in
2-48
Note: The generate project may compile for PIC32MZ devices, but not necessarily work on the hardware.
The set of template files added to the MPLAB X IDE project would require to be modified with additional configuration information
and the custom application code.
Later versions of the configuration tool may provide additional configuration options and sample application code for each library,
to create a executable project.
2.2.3 Tutorial
This tutorial explains about creating a new MPLAB X IDE project and configuring this project using the MPLAB Harmony
Configurator. The tutorial provides step by step instructions on how to create a MPLAB X IDE project for the TCP/IP Stack.
Description
This tutorial explains about creating a MPLAB X IDE project for TCP/IP library by adding required configurations and TCP/IP
library files, template files and Peripheral Library modules to the selected MPLAB X IDE project using the Configurator.
In this tutorial user would,
1. Create a new project in MPLAB X IDE.
2. Add required source and header files with required configurations for TCP/IP application using MPLAB Harmony Configurator
to the MPLAB X IDE project.
3. Add the required Peripheral header files and template files to the MPLAB X IDE project.
2.2 Using the Configurator MPLAB Harmony Help Tutorial
2-49
Creating an MPLAB X IDE Project
1. Open MPLAB X IDE, and select File > New Project to open a project explorer window.
2. In Categories, select “Microchip Embedded” and in Projects, select “Standalone Project”. Click Next.
3. Select the PIC device.
4. Select optional Debug Header. Click Next.
2.2 Using the Configurator MPLAB Harmony Help Tutorial
2-50
5. Select a hardware tool and Click Next.
6. Select the appropriate compiler. Click Next.
7. Name the MPLAB X IDE project and specify its path.
2.2 Using the Configurator MPLAB Harmony Help Tutorial
2-51
For this tutorial, create a project by name “MyHarmoyConfDemoProject”. Set the project as main project. Click Finish. Now the
project MyHarmonyConfDemoProject” is created.
Note: It is recommended that you maintain your project under a subdirectory of the "/apps" folder and use a relative
path to your project.
Once the MPLAB X IDE project is created, you should see a screen similar to the picture as shown below.
2.2 Using the Configurator MPLAB Harmony Help Tutorial
2-52
Using MPLAB Harmony Configurator
1. After creating the MPLAB X IDE project, select “Tools -> MPALB Harmony Configuration wizard” to open this plug-in with
MPLAB X IDE.
"MPLAB Harmony Configurator" will open in a new dialogue, as shown below.
2.2 Using the Configurator MPLAB Harmony Help Tutorial
2-53
2. Browse to the root directory path under "MPLAB Harmony Root Directory" option. This path is remembered by the
Configurator for subsequent usage.
Check or uncheck the "Relative Path" check box as required. Once the path is set, click "Next".
2.2 Using the Configurator MPLAB Harmony Help Tutorial
2-54
3. Now configure required middleware modules and Peripheral Library modules.
Peripheral Library headers are selected by default by the tool. For this tutorial user will configure TCP/IP Library. Select the
required configuration modules of TCP/IP modules and also other middleware modules in the Tree structure. Click "Next" once
the selection is complete.
2.2 Using the Configurator MPLAB Harmony Help Tutorial
2-55
For this release, both the TCP/IP and USB module Library Configuration Pane will appear. For this Tutorial, the TCP/IP module
is selected (default selection ”tcpip ”node) in tree, we get the Library Configuration as below.
2.2 Using the Configurator MPLAB Harmony Help Tutorial
2-56
4. Select the required configurable items of TCP/IP, and click next (Next button in “Library configuration navigation pane) which
takes to next TCP/IP configuration pane, and continue until the last configuration pane. Once TCP/IP configuration is done, click
Next(Next button at the bottom of TCP/IP Library configuration pane) which takes into the next window "Application Template" to
include template files.
5. Select to Include MPLAB Harmony Application template files. Tool would add template files (main.c, app.c, system_init.c,
system_tasks.c, system_int.c, system_config.h and app.h) to MPLAB X IDE project. Click "Finish".
2.2 Using the Configurator MPLAB Harmony Help Tutorial
2-57
6. Check for selected files being added in MPLAB X IDE project. The following figure shows the MPLAB X IDE project with the
added files.
2.2 Using the Configurator MPLAB Harmony Help Tutorial
2-58
The "MPLAB Harmony Assembly Generator" window in MPLAB X IDE shows the list of files added from "MPLAB Harmony
Configurator" to the MPLAB X IDE project.
2.2 Using the Configurator MPLAB Harmony Help Tutorial
2-59
2.2 Using the Configurator MPLAB Harmony Help Tutorial
2-60
3 Applications Help
3 MPLAB Harmony Help
3-61
3.1 Applications Overview
Applications use MPLAB Harmony libraries and define the behavior of a system.
Description
Applications determine how MPLAB Harmony libraries (device drivers, middleware, and system services) are used to do
something useful. In an MPLAB Harmony system, there may be one main application, there may be multiple independent
applications or there may be one or more Operating System (OS) specific applications. Applications interact with MPLAB
Harmony libraries through well defined interfaces. Applications may operate in a strictly polling environment, they may be
interrupt driven, they may be executed in OS-specific threads, or they may be written so as to be flexible and easily configured
for any of these environments.
Applications generally fit into one of the following categories:
Demo Applications:
Demos applications are provided (with MPLAB Harmony or in separate installations) to demonstrate typical or interesting usage
models of one or more MPLAB Harmony libraries. Demonstration applications can demonstrate realistic solutions to real-life
problems.
Sample Applications:
Sample applications are extremely simple applications provided with MPLAB Harmony as examples of how to use individual
features of a library. They will not normally accomplish anything useful on their own. They are provided primarily as
"documentation" to show how to use a library.
Skeletal Applications:
Skeletal applications are provided as bare-bones “skeletons” (potentially targeted to a specific usage or market) that MPLAB
Harmony developers can use as a starting point to for writing their own applications. Skeleton applications contain the necessary
calls, configuration definitions and subroutine stubs with “To Do” items clearly marked for MPLAB Harmony developers to fill in
as desired to create a working application.
Customer Applications:
Customer applications are (of course) not provide by Microchip. Rather, they are any applications developed by customers to
suit specific hardware and software needs. Refer to the Start Here help topic for information on the structure and to learn how to
develop your own MPLAB Harmony applications.
Application Directories
Applications are contained in the "/apps" folder. Under the "apps" folder, they are grouped by technology, board,
and/or market segment.
Examples:
Folder Type of Demos
/apps/examples/peripheral Contains simple peripheral library example applications
/apps/fs Contains graphics library demonstration applications
/apps/gfx Contains TCP/IP networking stack demonstration applications
/apps/tcpip Contains USB device demonstration applications
3.1 Applications Overview MPLAB Harmony Help
3-62
/apps/usb/device Contains USB host demonstration applications
Additional Information
Refer to Release Notes & Information for a complete listing of applications included with this release.
Refer to the help documentation for each individual application for build instructions and information on required hardware and
application usage.
3.1.1 System Overview
To support the framework, the application (or application developer) is responsible for the following:
• Configuring the Framework - Required, unless using a pre-built library. Each driver, middleware layer, and system service
require build-time configuration options that must be defined for the specific application, board, and processor that is used by
any particular demo or customer application. Please refer to the help file of that module on the list of configuration options,
and how they apply to the application.The application can use the board support package configuration file or define its own
configuration for the board.
• Building the Framework Library - Required, unless using a prebuilt library
• Implementing the System Initialization service. Please refer to the help file for the system initialization service for
information on implementing it statically or dynamically
• Implementing a Interrupt Service Routine (ISR) - Required, unless polled. Please refer to the help file for system tasks
service for examples on implementing ISRs.
• Implementing the System Tasks routine - Please refer to the help file for system tasks service for how to implement it
statically or dynamically
3.1 Applications Overview MPLAB Harmony Help System Overview
3-63
3.2 File System Demonstrations
3.2.1 Introduction
MPLAB Harmony File System Demonstration Help
Description
This help file contains instructions and associated information about MPLAB Harmony File System demonstration applications,
which are contained in the MPLAB Harmony Library distribution.
3.2.2 Release Notes
MPLAB Harmony Version: v0.70b File System Demonstrations Version : 0.01a Release Date: 18Nov2013
The interface can change in the beta and\or 1.0 release.
For the latest release information, please refer to the File System Service Library Release Notes section.
New This Release:
Nothing to report for this release.
Known Issues:
Nothing to report for this release.
3.2.3 SW License Agreement
(c) 2013 Microchip Technology Inc.
Microchip licenses this software to you solely for use with Microchip products. The software is owned by Microchip and its
licensors, and is protected under applicable copyright laws. All rights reserved.
SOFTWARE IS PROVIDED "AS IS" MICROCHIP EXPRESSLY DISCLAIMS ANY WARRANTY OF ANY KIND, WHETHER
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL MICROCHIP BE LIABLE FOR
ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, HARM TO
YOUR EQUIPMENT, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS
BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR
CONTRIBUTION, OR OTHER SIMILAR COSTS.
To the fullest extent allowed by law, Microchip and its licensors liability shall not exceed the amount of fees, if any, that you have
3.2 File System Demonstrations MPLAB Harmony Help SW License Agreement
3-64
paid directly to Microchip to use this software.
MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE TERMS.
3.2.4 Demonstrations
Provides instructions on how to run the demonstration applications.
Description
The following demonstration applications are available in this release of the MPLAB Harmony File System framework.
3.2.4.1 Overview
Provides an overview of how most of the File System Demonstration applications are structured.
Description
The MPLAB Harmony File System Demonstration Applications show example usage of the File System framework. These
demonstration applications also contain example configurations of media drivers such as Internal Flash and SD Card, that can
be used readily in the end application with the some changes to initialization parameters, if required. A demonstration application
may have multiple MPLAB X IDE project configurations (for different demonstration hardware and microcontrollers). The relevant
configuration should be selected in the MPLAB X IDE before compiling the demonstration. Figure 1 shows the dialog box in
MPLAB X IDE that allows selection of different configurations.
Figure 1: Demonstration MPLAB X IDE Configurations
The project will contain files which are configuration specific. Wherever applicable, these configuration files are placed in
separate MPLAB X IDE project logical folders. Figure 2 shows how the configuration dependant nvm_disk_images.c file is
included in the project. In this case two configurations (pic32mx_usb_sk_Int_dyn and pic32mz_sk_int_dyn) are supported in the
project.
Figure 2: Configuration specific file in File System Demonstration Projects.
Note that some demonstration projects may not support all configurations. In general, the following the demonstration project
contain the following MPLAB X IDE configurations:
• pic32mx_usb_sk_int_dyn: This configuration runs on the PIC32 USB Starter Kit. The media drivers are configured for
interrupt and dynamic operation
3.2 File System Demonstrations MPLAB Harmony Help Demonstrations
3-65
• pic32mz_sk_int_dyn: This configuration runs on the PIC33MZ Embedded Connectivity (EC) Starter Kit. Some demonstration
projects that support this configuration may need the Multimedia Expansion Board II (MEB II) to attached to the starter kit. The
media drivers in this configuration are configured for interrupt and dynamic operation.
Unless specified, the File System demonstration application are structured as indicated in Figure 3.
Figure 3: File System Demonstration Application General Architecture
Here are some general notes while working with the demonstration applications:
1. The system and application is initialized in SYS_Initialize() function, implemented in sys_init.c. The sys_init.c file is
configuration specific. The SYS_Initialize() function initializes the application (APP_Initialize() function) and the BSP
(BSP_Initialize() function).
2. The application then calls SYS_Tasks() function in an infinite loop. This function updates the state machines of all system
components in the demonstration application and also calls the APP_Tasks() function. The is implemented in file sys_tasks.c
which is configuration specific.
3. All Interrupt service routines are implemented in sys_interrupt.c. This file is configuration specific.
3.2.4.2 nvm_fat_single_disk
This demonstration uses a FAT12 image of file on NVM flash memory and demonstrates the working of all file system functions.
Description
This demonstration shows an example of implementing a FAT12 disk in device Flash memory. The demonstration contains a
FAT12 disk image consisting of a Master Boot Record (MBR) sector, Logical Boot Sector, File Allocation Table, Root Directory
Area. The demonstration opens an existing file named "FILE.TXT" and performs all file system related function calls on the file
viz. SYS_FS_FileStat, SYS_FS_FileSize, SYS_FS_FileSeek, SYS_FS_FileEOF. Finally, the string "Hello World" is written to this
file. The file is then closed and reopend for read. The read string is then compared with the string which was written to the file. If
the string compare is successful, LED indication is provided.
3.2 File System Demonstrations MPLAB Harmony Help Demonstrations
3-66
3.2.4.2.1 Supported Demonstration Boards
Lists supported demonstration and development hardware boards.
Description
Following board is supported for PIC32MX devices: -
Demonstration Board (click link for board information) Notes
PIC32 USB Starter Kit II -
Following board is supported for PIC32MZ devices: -
Demonstration Board (click link for board information) Notes
PIC32MZ Embedded Connectivity (EC) Starter Kit -
3.2.4.2.2 Configuring the Hardware
Describes how to configure the supported hardware.
Description
PIC32 USB Starter Kit II
No hardware related configuration or jumper setting changes are necessary.
PIC32MZ Embedded Connectivity (EC) Starter Kit
No hardware related configuration or jumper setting changes are necessary.
3.2.4.2.3 Running the Demonstration
Provides instructions on how to build and run the NVM FAT single disk demonstration.
Description
Select the MPLAB X IDE project configuration: -
• pic32mx_usb_sk_int_dyn -- For PIC32MX devices
• pic32mz_sk_int_dyn -- For PIC32MZ devices
Build the selected configuration in the MPLAB X IDE project and program the demonstration board. The execution status
(pass/fail) of the demonstration is indicated by LEDs on the demonstration board.
Demonstration Board Demonstration Successful Demonstration Failure
PIC32 USB Starter Kit II LED3 LED1
PIC32MZ Embedded Connectivity (EC) Starter Kit Green LED Red LED
About the demonstration:
This demonstration shows an example of
- implementing a FAT12 disk in device Flash memory.
- opening a file for read or write.
- implements all the file system functions.
3.2 File System Demonstrations MPLAB Harmony Help Demonstrations
3-67
- closing a file.
The demonstration contains a FAT12 disk image consisting of a Master Boot Record (MBR) sector, Logical Boot Sector, File
Allocation Table, Root Directory Area. This image is implemented in the file nvm_disk_images.c (this is project configuration
specific file and is contained in the nvm_disk_images logical folder in the MPLAB X IDE project). The image contains a single file
named "FILE.TXT" which contains the string "Data".
The demonstration opens an existing file named "FILE.TXT" and performs all file system related function calls on the file viz.
SYS_FS_FileStat, SYS_FS_FileSize, SYS_FS_FileSeek, SYS_FS_FileEOF. Finally, the string "Hello World" is written to this file.
The file is then closed and reopened for read. The read string is then compared with the string which was written to the file. If the
string compare is successful, LED indication is provided.
The demonstration application logic is implemented as a state machine in the APP_Tasks() function in the file main.c.
1. The disk is first mounted using the SYS_FS_Mount() function. The "/dev/nvma1" path instructs the mount command to mount
an internal flash volume. The volume is mounted against a FAT type file system and mounted at "/mnt/myDrive/".
2. If the mount is successful, the application opens a file "FILE.TXT" for reading and writing
(SYS_FS_FILE_OPEN_READ_PLUS) with a SYS_FS_FileOpen() function. The valid file handle is received once a successful
opening of file is performed.
3. If file open is successful, the status of file "FILE.TXT" is stored in the appData.fileStatus structure, using SYS_FS_FileStat()
function.
4. If the file status check is successful, the size of the "FILE.TXT" is checked by passing the file handle to the SYS_FS_FileSize()
function.
5. If the file size check is successful, the size of file is compared with the size element received earlier as a part of
appData.fileStatus structure. If both value matches, then the code moves to the next step of file seek.
6. The file pointer is then moved by 4 bytes from the start of the file by calling the function SYS_FS_FileSeek() and passing
parameter as SYS_FS_SEEK_SET (seek from the beginning of the file).
7. If the file seek operation is successful, the file pointer should have reached the end of the file. This is because, the content of
the FILE.TXT had only 4 byte string = "Data". The end of file is verified by calling the function SYS_FS_FileEOF(). If the function
returns "true" (end of file reached), the next step is performed.
8. In the next step, the file pointer is moved again by [(-1)*size of file], from the end of the file by calling the function
SYS_FS_FileSeek() and passing parameter SYS_FS_SEEK_END (seek from the end of the file).
9. If the file seek operation is successful, the file pointer should have reached the beginning of the file. 4 Bytes are read from the
file using SYS_FS_FileRead() function (into a buffer).
10. If the read is successful, the content of file (present in the buffer) is compared with the "Data" string. If the comparison
passed, the code moves to the next step.
11. In the next step, the file pointer is moved again by [(-1)*size of file], from the end of the file by calling the function
SYS_FS_FileSeek() and passing parameter SYS_FS_SEEK_END (seek from the end of the file).
12. If the file seek operation is successful, the string "Hello World" is written to the file using SYS_FS_FileWrite() function.
13. If the write operation is successful, the file is closed.
14. The file "FILE.TXT" is opened again in read mode (SYS_FS_FILE_OPEN_READ).
15. If the file open is successful, the content of the file is read using SYS_FS_FileRead() function (into a buffer).
16. If the read operation is successful, the content of the file (present in the buffer) is compared with the "Hello World" string
using the strcmp() function. A LED indicates the success of the demonstration.
3.2 File System Demonstrations MPLAB Harmony Help Demonstrations
3-68
3.2.4.3 sd_card_fat_single_disk
This demonstration uses the SDTM Card with FAT file system as media and performs a read/ write / verify operation on the files
using long file names (LFN).
Description
This demonstration shows an example of using the MPLAB Harmony File System to access and modify the contents of an SDTM
Card. The demonstration opens a file "FILE_TOO_LONG_NAME_EXAMPLE_123.JPG" on the SD Card, reads the content of
the file and writes the content into another file "FILE_TOO_LONG_NAME_EXAMPLE_123_1.JPG" (create a copy of one file into
another file).
The input file "FILE_TOO_LONG_NAME_EXAMPLE_123.JPG" is not provided along with the release package. It could be any
arbitrary JPG (picture) file chosen by user and then suitably renamed to "FILE_TOO_LONG_NAME_EXAMPLE_123.JPG". The
reason for choosing a JPG file for test purpose is that the duplicate file "FILE_TOO_LONG_NAME_EXAMPLE_123_1.JPG"
created by the FS demonstration could be easily verified for correctness by inserting the SD card in computer and opening the
"FILE_TOO_LONG_NAME_EXAMPLE_123_1.JPG" file. If the file "FILE_TOO_LONG_NAME_EXAMPLE_123_1.JPG" opens
for viewing on the computer, the test is deemed to have passed. Otherwise, if the
"FILE_TOO_LONG_NAME_EXAMPLE_123_1.JPG" does not open (is corrupted), the test will be considered as failed.
3.2.4.3.1 Supported Demonstration Boards
Lists supported demonstration and development hardware boards.
Description
Following board is supported for PIC32MX devices: -
Demonstration Board (click link for board information)
PIC32MX795F512L Plug-In-Module (PIM)
PICtail Daughter Board for SD and MMC
Note: This board can not be used by itself. An Explorer 16 Development Board is required.
Following board is supported for PIC32MZ devices: -
Demonstration Board (click link for board information) Notes
PIC32MZ Embedded Connectivity (EC) Starter Kit -
Note: This board can not be used by itself. An Multimedia Expansion Board II (MEB II) is required to run the demonstration.
3.2.4.3.2 Configuring the Hardware
Describes how to configure the supported hardware.
Description
Explorer 16 Development Board Based Demonstrations
Use the following instructions for all Explorer 16 Development Board-based demonstration boards:
PIC32MX795F512L PIM
1. Insert the PIM into the Explorer 16 Development Board PIM connector.
3.2 File System Demonstrations MPLAB Harmony Help Demonstrations
3-69
2. Jumpers JP1, JP2 and JP3 on the SD Card PICtail Daughter Board should connect to points 2 and 3 on their respective
connectors as shown here.
3. Insert the SD Card PICtail Daughter Board into the PICtail Plus connector on the Explorer 16 Development Board.
4. Insert a SD card into the SD card connector on the SD Card PICtail Daughter Board.
5. Power up the board.
Multimedia Expansion Board II (MEB II)
No hardware setting change is required. Insert the micro SD card into the connector and power up the board.
3.2.4.3.3 Running the Demonstration
Provides instructions on how to build and run the SD card FAT single disk demonstration.
Description
Select the MPLAB X IDE project configuration: -
• exp16_32mx_int_dyn -- For PIC32MX devices
• pic32mz_sk_int_dyn -- For PIC32MZ devices
Insert the SD card, which contains the file "FILE_TOO_LONG_NAME_EXAMPLE_123.JPG". The file can be of any size.
Compile the selected configuration in the MPLAB X IDE project and run the code. After a few seconds, once the LED glows,
remove the SD card from the SD Card PICtail Daughter Board (for PIC32MX) or MEB2 Board (for PIC32MZ) and insert it into the
SD card reader on a PC. Examine the contents of the SD card and another file named
"FILE_TOO_LONG_NAME_EXAMPLE_123_1.JPG" would have been created.
"FILE_TOO_LONG_NAME_EXAMPLE_123_1.JPG" will be a copy of "FILE_TOO_LONG_NAME_EXAMPLE_123.JPG". Verify
both the files opens for viewing on the PC.
Demonstration Board Demonstration Successful Demonstration Failure
Explorer 16 Development Board LED5 (D5) LED6 (D6)
PIC32MZ Embedded Connectivity (EC) Starter Kit Green LED Red LED
About the demonstration:
This demonstration shows an example of
- implementing a FAT File system (FAT16/ FAT32) on SD card.
- implementing long file name (LFN).
- opening a file for read or write.
- closing a file.
The demonstration opens a file "FILE_TOO_LONG_NAME_EXAMPLE_123.JPG" on the SD Card, reads the content of the file
and writes the content into another file "FILE_TOO_LONG_NAME_EXAMPLE_123_1.JPG" (create a copy of one file into
another file).
The demonstration application logic is implemented as a state machine in the APP_Tasks() function in the file main.c.
1. The disk is first mounted using the SYS_FS_Mount() function. The "/dev/mmcblka1" path instructs the mount command to
mount a SD card volume. The volume is mounted against a FAT type file system and mounted at "/mnt/myDrive/".
2. If mount is successful, the volume is unmouned by passing the mount name "/mnt/myDrive" to SYS_FS_Unmount() function.
This unmounting is done for demonstration purpose only. Real application do not need to unmount unless it is required for the
application.
3.2 File System Demonstrations MPLAB Harmony Help Demonstrations
3-70
3. If unmount is successful, the mounting process is repeated.
4. If the mount is successful, the application opens a file "FILE_TOO_LONG_NAME_EXAMPLE_123.JPG" for reading with a
SYS_FS_FileOpen() function.
3. If the file open is successful, the application opens a file "FILE_TOO_LONG_NAME_EXAMPLE_123_1.JPG" for writing with
SYS_FS_FileOpen() function. The attributes for file write is selected as "SYS_FS_FILE_OPEN_WRITE". Hence, if the file does
not exist on the drive, the file is created.
4. If the file open is successful, 512Bytes from the file "FILE_TOO_LONG_NAME_EXAMPLE_123.JPG" is read into application
buffer using SYS_FS_FileRead() function.
5. If the file read successful, the 512Bytes is written from the application buffer to the
FILE_TOO_LONG_NAME_EXAMPLE_123_1.JPG file using SYS_FS_FileWrite() function.
6. If the write operation is successful, the end of file for FILE_TOO_LONG_NAME_EXAMPLE_123.JPG is checked. If the end of
file is not reached, the process of reading and writing continues (step - 4 and step - 5).
7. Once end of file is reached, both the files are closed with SYS_FS_FileClose() function.
8. Finally, a LED indicates the success of the demonstration.
3.2.4.4 nvm_sdcard_fat_multi_disk
This demonstration uses NVM and SDTM Card as 2 media and reads files from one media and write onto another media.
Description
This demonstration shows an example of using the MPLAB Harmony File System to access files across multiple media. The
demonstration contains a FAT12 disk image consisting of a Master Boot Record (MBR) sector, Logical Boot Sector, File
Allocation Table, Root Directory Area, placed in the internal flash memory (NVM). Also, a SD card is used as another disk, which
might have FAT16 or FAT32 implemented on it (depends on the formatting of SD card).The demonstration reads the contents of
"FILE.TXT" in NVM and copies the contents to "FILE.TXT" in the SDTM Card. If the write operation is successful, LED indication
is provided.
3.2.4.4.1 Supported Demonstration Boards
Lists supported demonstration and development hardware boards.
Description
Following board is supported for PIC32MX devices: -
Demonstration Board (click link for board information)
PIC32MX795F512L Plug-In-Module (PIM)
PICtail Daughter Board for SD and MMC
Note: This board can not be used by itself. An Explorer 16 Development Board is required.
Following board is supported for PIC32MZ devices: -
Demonstration Board (click link for board information) Notes
PIC32MZ Embedded Connectivity (EC) Starter Kit -
Note: This board can not be used by itself. An Multimedia Expansion Board II (MEB II) is required to run the demonstration.
3.2 File System Demonstrations MPLAB Harmony Help Demonstrations
3-71
3.2.4.4.2 Configuring the Hardware
Describes how to configure the supported hardware.
Description
Explorer 16 Development Board Based Demonstrations
Use the following instructions for all Explorer 16 Development Board-based demonstration boards:
PIC32MX795F512L PIM
1. Insert the PIM into the Explorer 16 Development Board PIM connector.
2. Jumpers JP1, JP2 and JP3 on the SD Card PICtail Daughter Board should connect to points 2 and 3 on their respective
connectors as shown here.
3. Insert the SD Card PICtail Daughter Board into the PICtail Plus connector on the Explorer 16 Development Board.
4. Insert a SD card into the SD card connector on the SD Card PICtail Daughter Board.
5. Power up the board.
Multimedia Expansion Board II (MEB II)
No hardware setting change is required. Insert the micro SD card into the connector and power up the board.
3.2.4.4.3 Running the Demonstration
Provides instructions on how to build and run the NVM SD card FAT multi disk demonstration.
Description
Select the MPLAB X IDE project configuration: -
• exp16_32mx_int_dyn -- For PIC32MX devices
• pic32mz_sk_int_dyn -- For PIC32MZ devices
Insert the SD card, which contains the file "FILE.TXT" and the file contains "abc" (some arbitrary existing content).
Compile the selected configuration in the MPLAB X IDE project and run the code. After a few seconds, once the LED glows,
remove the SD card from the Board and insert it into the SD card reader on a PC. Examine the contents of the file named
"FILE.TXT". The file should contain the string "This data is from NVM Disk".
Demonstration Board Demonstration Successful Demonstration Failure
Explorer 16 Development Board LED5 (D5) LED6 (D6)
PIC32MZ Embedded Connectivity (EC) Starter Kit Green LED Red LED
About the demonstration:
This demonstration shows an example of:
- implementing a multi disk demonstration with FAT12 on internal flash memory (NVM) and FAT File system (FAT16/ FAT32) on
SD card.
- opening two files from two different disks, read content of file from first disk and write into the file of second disk.
- closing the files.
The demonstration contains a FAT12 disk image consisting of a Master Boot Record (MBR) sector, Logical Boot Sector, File
Allocation Table, Root Directory Area, placed in the internal flash memory (NVM). Also, a SD card is used as another disk, which
3.2 File System Demonstrations MPLAB Harmony Help Demonstrations
3-72
might have FAT16 or FAT32 implemented on it (depends on the formatting of SD card).The demonstration reads the contents of
"FILE.TXT" in NVM and copies the contents to "FILE.TXT" in the SDTM Card. If the write operation is successful, LED indication
is provided.
The demonstration application logic is implemented as a state machine in the APP_Tasks() function in the file main.c.
1. The first disks is mounted using the SYS_FS_Mount() function. The "/dev/nvma1" path instructs the mount command to mount
a internal flash volume. The volume is mounted against a FAT type file system and mounted at "/mnt/myDrive1/".
2. If the mount is successful, the second disks is mounted using the SYS_FS_Mount() function. The "/dev/mmcblka1" path
instructs the mount command to mount a SD card volume. The volume is mounted against a FAT type file system and mounted
at "/mnt/myDrive2/".
3. If the mount is successful, the application opens a file "FILE.TXT" from "/mnt/myDrive1/" for reading and "FILE.TXT" from
"/mnt/myDrive2/" for writing with a SYS_FS_FileOpen() function.
4. If the file open is successful, the application reads 27Bytes from "FILE.TXT" of internal flash volume using
SYS_FS_FileRead().
5. If the read is successful, the application closes the "FILE.TXT" from internal flash volume and then writes the 27Bytes into
"FILE.TXT" of SD card volume using SYS_FS_FileWrite().
6. If the write is successful, the application closes the "FILE.TXT" from SD card volume.
7. If file close is successful, LED indicates the success of the operation.
3.2.4.5 nmv_mpfs_single_disk
This demonstration uses a MPFS image of 3 files on NVM flash memory and demonstrates the working of all file system
functions.
Description
This demonstration shows an example of implementing a MPFS disk in device Flash memory. The demonstration contains a
MPFS disk image in the internal flash memory. The disk image contains 3 files named: -
"FILE.txt" , Size = 11Bytes. The content of the file is -- "Hello World".
"ABC.txt", Size = 31744Bytes. The content of the file is not important. Just a file of sufficiently big size.
"TEST.txt" , Size = 72Bytes. The content of the file is -- "This file contains a test string and it is meant for testing. 1234567890".
The demonstration performs all file system related function calls on the file viz. SYS_FS_FileRead, SYS_FS_FileStat,
SYS_FS_FileSize, SYS_FS_FileSeek, SYS_FS_FileEOF. If all the test succeeds, LED indication is provided.
3.2.4.5.1 Supported Demonstration Boards
Lists supported demonstration and development hardware boards.
Description
Following board is supported for PIC32MX devices: -
Demonstration Board (click link for board information) Notes
PIC32 USB Starter Kit II -
3.2 File System Demonstrations MPLAB Harmony Help Demonstrations
3-73
Following board is supported for PIC32MZ devices: -
Demonstration Board (click link for board information) Notes
PIC32MZ Embedded Connectivity (EC) Starter Kit -
3.2.4.5.2 Configuring the Hardware
Describes how to configure the supported hardware.
Description
PIC32 USB Starter Kit II
No hardware related configuration or jumper setting changes are necessary.
PIC32MZ Embedded Connectivity (EC) Starter Kit
No hardware related configuration or jumper setting changes are necessary.
3.2.4.5.3 Running the Demonstration
Provides instructions on how to build and run the NVM MPFS single disk demonstration.
Description
Select the MPLAB X IDE project configuration: -
• pic32mx_usb_sk_int_dyn -- For PIC32MX devices
• pic32mz_sk_int_dyn -- For PIC32MZ devices
Build the selected configuration in the MPLAB X IDE project and program the demonstration board. The execution status
(pass/fail) of the demonstration is indicated by LEDs on the demo board.
Demonstration Board Demonstration Successful Demonstration Failure
PIC32 USB Starter Kit II LED3 LED1
PIC32MZ Embedded Connectivity (EC) Starter Kit Green LED Red LED
About the demonstration:
This demonstration shows an example of
- implementing a MPFS disk in device Flash memory.
- opening a file for read.
- implements all the file system functions.
- closing a file.
This demonstration shows an example of implementing a MPFS disk in device Flash memory. The demonstration contains a
MPFS disk image in the internal flash memory. The disk image contains 3 files named: -
"FILE.txt" , Size = 11Bytes. The content of the file is -- "Hello World".
"ABC.txt", Size = 31744Bytes. The content of the file is not important. Just a file of sufficiently big size.
"TEST.txt" , Size = 72Bytes. The content of the file is -- "This file contains a test string and it is meant for testing. 1234567890".
The demonstration application logic is implemented as a state machine in the APP_Tasks() function in the file main.c.
3.2 File System Demonstrations MPLAB Harmony Help Demonstrations
3-74
1. The disk is first mounted using the SYS_FS_Mount() function. The "/dev/nvma1" path instructs the mount command to mount
an internal flash volume. The volume is mounted against a MPFS2 type file system and mounted at "/mnt/myDrive/".
2. If the mount is successful, the application opens a file "FILE.txt" for reading with a SYS_FS_FileOpen() function.
3. If the open is successful, the application opens another file "TEST.txt" for reading with SYS_FS_FileOpen() function.
4. If open is successful, the application checks the status of another file "ABC.txt" using SYS_FS_FileStat() function and stores
the status of the file into the structure "appData.fileStatus".
5. If file status check is successful, the application compares the size of file (from "appData.fileStatus" structure) with the known
value of 31744 (Bytes).
6. If the comparison is successful, the application checks for size of file "FILE.txt", by passing the handle obtained during file
open, to the function SYS_FS_FileSize().
7. If the file size matches the known value of 11 (Bytes), the application moves the file pointer for the file "TEST.txt" 10Bytes from
the end of file, using the function SYS_FS_FileSeek().
8. If file seek is successful, 10 Bytes of content of the file "TEST.txt" is read into the application buffer, using the function
SYS_FS_FileRead().
9. If read is successful, the application buffer content is compared with the known string of "1234567890" using the strncmp()
function.
10. If the comparison is successful, the application checks if the file pointer for file "TEST.txt" has reached the end of file using
the SYS_FS_FileEOF() function.
11. If end of file is reached, a LED indicates the success of the demonstration.
3.2.4.6 nvm_sdcard_fat_mpfs_multi_disk
This demonstration uses NVM and SDTM Card with MPFS and FAT image of file and performs a read/ write/ verify operation
from file of one media to another media.
Description
This demonstration shows an example of using the MPLAB Harmony File System to access files across multiple disks and
multiple file system. The demonstration contains a MPFS disk image in the internal flash memory. The disk image contains a file
named "abc.txt" with content "Hello World". Another disk is a SD card, which is formatted to FAT (FAT16 or FAT32). The
demonstration reads the contents of "abc.txt" from the disk implemented on internal flash memory and writes the contents to
"FILE.TXT" on the SDTM Card. A successful write is indicated by a LED glow.
3.2.4.6.1 Supported Demonstration Boards
Lists supported demonstration and development hardware boards.
Description
Following board is supported for PIC32MX devices: -
Demonstration Board (click link for board information)
PIC32MX795F512L Plug-In-Module (PIM)
PICtail Daughter Board for SD and MMC
Note: This board can not be used by itself. An Explorer 16 Development Board is required.
3.2 File System Demonstrations MPLAB Harmony Help Demonstrations
3-75
Following board is supported for PIC32MZ devices: -
Demonstration Board (click link for board information) Notes
PIC32MZ Embedded Connectivity (EC) Starter Kit -
Note: This board can not be used by itself. An Multimedia Expansion Board II (MEB II) is required to run the demonstration.
3.2.4.6.2 Configuring the Hardware
Describes how to configure the supported hardware.
Description
Explorer 16 Development Board Based Demonstrations
Use the following instructions for all Explorer 16 Development Board-based demonstration boards:
PIC32MX795F512L PIM
1. Insert the PIM into the Explorer 16 Development Board PIM connector.
2. Jumpers JP1, JP2 and JP3 on the SD Card PICtail Daughter Board should connect to points 2 and 3 on their respective
connectors as shown here.
3. Insert the SD Card PICtail Daughter Board into the PICtail Plus connector on the Explorer 16 Development Board.
4. Insert a SD card into the SD card connector on the SD Card PICtail Daughter Board.
5. Power up the board.
Multimedia Expansion Board II (MEB II)
No hardware setting change is required. Insert the micro SD card into the connector and power up the board.
3.2.4.6.3 Running the Demonstration
Provides instructions on how to build and run the NVM SD card FAT MPFS multi disk demonstration.
Description
Select the MPLAB X IDE project configuration: -
• exp16_32mx_int_dyn -- For PIC32MX devices
• pic32mz_sk_int_dyn -- For PIC32MZ devices
Insert the SD card, which contains the file "FILE.TXT" and the file contains "abc" (some arbitrary existing content).
Compile the selected configuration in the MPLAB X IDE project and run the code. After a few seconds, once the LED glows,
remove the SD card from the SD Card PICtail Daughter Board and insert it into the SD card reader on a PC. Examine the
contents of the file named "FILE.TXT". The file should contain the string "Hello World".
Demonstration Board Demonstration Successful Demonstration Failure
Explorer 16 Development Board LED5 (D5) LED6 (D6)
PIC32MZ Embedded Connectivity (EC) Starter Kit Green LED Red LED
About the demonstration:
This demonstration shows an example of
- implementing a multi disk demonstration with MPFS on internal flash memory (NVM) and FAT File system (FAT16/ FAT32) on
3.2 File System Demonstrations MPLAB Harmony Help Demonstrations
3-76
SD card.
- opening two files from two different disks, read content of file from first disk and write into the file of second disk.
- closing the files.
The demonstration contains a MPFS disk image in the internal flash memory. The disk image contains a file named "abc.txt" with
content "Hello World". Another disk is a SD card, which is formatted to FAT (FAT16 or FAT32). The demonstration reads the
contents of "abc.txt" from the disk implemented on internal flash memory and writes the contents to "FILE.TXT" on the SDTM
Card. A successful write is indicated by a LED glow.
The demonstration application logic is implemented as a state machine in the APP_Tasks() function in the file main.c.
1. The first disks is mounted using the SYS_FS_Mount() function. The "/dev/nvma1" path instructs the mount command to mount
a internal flash volume. The volume is mounted against a MPFS2 type file system and mounted at "/mnt/myDrive1/".
2. If the mount is successful, the second disks is mounted using the SYS_FS_Mount() function. The "/dev/mmcblka1" path
instructs the mount command to mount a SD card volume. The volume is mounted against a FAT type file system and mounted
at "/mnt/myDrive2/".
3. If the mount is successful, the application opens a file "abc.txt" from "/mnt/myDrive1/" for reading and "FILE.TXT" from
"/mnt/myDrive2/" for writing with a SYS_FS_FileOpen() function.
4. If the file open is successful, the application reads 13Bytes from "abc.txt" of internal flash volume using SYS_FS_FileRead().
5. If the read is successful, the application closes the "abc.txt" from internal flash volume and then writes the 13Bytes into
"FILE.TXT" of SD card volume using SYS_FS_FileWrite().
6. If the write is successful, the application closes the "FILE.TXT" from SD card volume.
7. If file close is successful, LED indicates the success of the operation.
3.2.5 Demonstration Board Information
Information on Hardware used by the File System Demonstration Applications.
Description
The File System Library Demonstration Applications can be tried across different hardware boards. This section provide details
on these hardware boards.
3.2.5.1 PIC32 USB Starter Kit II
Hardware Information:
3.2 File System Demonstrations MPLAB Harmony Help Demonstration Board Information
3-77
SW1 - Application switch. Tied to RD6.
SW2 - Application switch. Tied to RD7.
SW3 - Application switch. Tied to RD13.
LED1 - Application LED. Tied to RD0.
LED2 - Application LED. Tied to RD1.
LED3 - Application LED. Tied to RD2.
More Information
Product webpage
3.2.5.2 Explorer 16 Development Board
Hardware Information:
3.2 File System Demonstrations MPLAB Harmony Help Demonstration Board Information
3-78
S1 - Reset button (MCLR)
S2 - Processor switch. This switch determines which processor is running, the processor on the board or the processor on the
Plug-In-Module (PIM).
S3, S4, S5, S6 - Application switches. For information about what pin is connected to this switch, please refer to the information
for the PIM in use.
D3 through D10 - Application LEDs. For information about what pin is connected to this LED, please refer to the information for
the PIM in use.
More Information:
Product webpage
3.2.5.3 PIC32MX795F512 Plug-In-Module (PIM)
More Information
Product webpage
3.2 File System Demonstrations MPLAB Harmony Help Demonstration Board Information
3-79
3.2.5.4 PICtail Daughter Board for SD and MMC
More Information:
Product webpage.
3.2.5.5 PIC32MZ Embedded Connectivity (EC) Starter Kit
Provides details information on the PIC32MZ Embedded Connectivity (EC) Starter Kit.
Description
Microchip Part Number: DM320006 (without Crypto) or DM320006-C (with Crypto)
The top assembly of the board includes these key features, as indicated in Figure 1:
1. PIC32MZ2048ECH144 32-bit microcontroller.
2. Green power indicator LED.
3. On-board crystal or oscillator for precision microcontroller clocking (12 MHz).
4. USB connectivity for on-board debugger communications.
5. Green debug indicator LED.
6. Three push button switches for user-defined inputs.
7. Three user-defined indicator LEDs.
8. USB Type A receptacle connectivity for PIC32 host-based applications.
9. HOST mode power jumper.
10. Daughter board connectors for flexible Ethernet PHY options.
11. 32 kHz oscillator for RTCC and Timer1 (optional).
12. External 2 GB SQI memory for expanded memory application.
13. Jumper for using or disconnecting the on-board debugger.
NOTE: When running self-powered USB device applications, open the jumper JP1 to prevent possibly back-feeding voltage onto
the Vbus from one port on the host to another (or from one host to another).
3.2 File System Demonstrations MPLAB Harmony Help Demonstration Board Information
3-80
Figure 1: PIC32MZ Embedded Connectivity (EC) Starter Kit Layout (Front)
The bottom assembly of the board includes these key features, as indicated in Figure 2:
1. PIC24FJ256GB106 USB microcontroller for on-board debugging.
2. Regulated +3.3V power supply for powering the starter kit via USB or expansion board.
3. Connector for various expansion boards.
4. USB Type micro-AB receptacle for OTG and USB device connectivity for PIC32 OTG/device-based applications.
5. 50 MHz Ethernet PHY oscillator.
6. USB Host and OTG power supply for powering PIC32 USB applications.
Figure 2: PIC32MZ Embedded Connectivity (EC) Starter Kit Layout (Back)
3.2 File System Demonstrations MPLAB Harmony Help Demonstration Board Information
3-81
3.2.5.6 Multimedia Expansion Board II (MEB II)
Provides details information on the Multimedia Expansion Board II (MEB) II.
Description
Microchip Part Number: DM320005-2
Product Page
The front side of the MEB II includes these key features, as shown in Figure 1:
1. Display daughter board connector (60-pin Hirose board-to-board connector).
2. mTouch™ buttons.
3. Push Button.
4. Power LED.
5. User LEDs.
6. VGA Camera (OVM7690).
7. PICtail™ Connector.
8. Analog temperature sensor.
Figure 1: Multimedia Expansion Board II Layout (Front)
The underside of the MEB II includes these key features, as shown in Figure 2:
1. Regulated 5V and 3.3V power supply for powering the board via a 9-15V DC Adapter.
2. PIC32 Starter Kit connector (168-pin Hirose board-to-board connector).
3. 24-bit stereo audio codec (AK4953A).
4. Integrated 802.11bg wireless module (MRF24WG0MA).
5. Low-cost Bluetooth® HCI transceiver (BTM805).
6. EBI SRAM memory (IS61WV102416BLL).
7. microSD slot.
3.2 File System Demonstrations MPLAB Harmony Help Demonstration Board Information
3-82
8. Analog accelerometer (ADXL325).
Figure 2: Multimedia Expansion Board II Layout (Back)
3.2 File System Demonstrations MPLAB Harmony Help Demonstration Board Information
3-83
3.3 Graphics Demonstrations
3.3.1 Introduction
Graphics Library Demonstrations Applications Help
Description
This distribution package contains a variety of Graphics-related firmware projects that demonstrate the capabilities of the MPLAB
Harmony Graphics library. This help file describes the hardware requirement and procedures to run these firmware projects on
Microchip graphics boards.
To know more about MPLAB Harmony Graphics, configuring the library and the APIs provided; refer to the Graphics Library
documentation.
Graphic Demonstration Description
Primitive Cyclically demonstrates various types of shapes and images, which include circles, lines, and
rectangles that can be created from the Graphics Library.
Object Touch interactive demonstration of various pages of objects that can be created from the
Graphics Library.
ssd1926 Touch interactive demonstration of JPEG decoded images from an SD card utilizing the JPEG
decoder of the Solomon Systech SSD1926 graphics controller.
lcc Demonstrates the advanced capabilities of the Graphics Library utilizing the software graphics
controller.
3.3.2 Release Notes
MPLAB Harmony Version: v0.70b Graphics Demonstrations Version : 4.00b Release Date: 18Nov2013
New This Release:
Nothing to report for this release.
Known Issues:
LCC Demonstration: For the PIC32MZ Embedded Connectivity (EC) Starter Kit, after programming, the application may not
display the UI folders as expected. If this occurs, to activate the UI display, touch the screen in the folder icons area. This issue
will be addressed in the next release of MPLAB Harmony.
3.3 Graphics Demonstrations MPLAB Harmony Help SW License Agreement
3-84
3.3.3 SW License Agreement
(c) 2013 Microchip Technology Inc.
Microchip licenses this software to you solely for use with Microchip products. The software is owned by Microchip and its
licensors, and is protected under applicable copyright laws. All rights reserved.
SOFTWARE IS PROVIDED "AS IS" MICROCHIP EXPRESSLY DISCLAIMS ANY WARRANTY OF ANY KIND, WHETHER
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL MICROCHIP BE LIABLE FOR
ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, HARM TO
YOUR EQUIPMENT, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS
BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR
CONTRIBUTION, OR OTHER SIMILAR COSTS.
To the fullest extent allowed by law, Microchip and its licensors liability shall not exceed the amount of fees, if any, that you have
paid directly to Microchip to use this software.
MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE TERMS.
3.3.4 Demonstrations
This topic provides information on how to run the Graphics Library demonstration applications included in this release.
Description
All demonstrations provided should be built using the MPLAB X IDE development environment tool supplied by Microchip.
The information that follows, communicate the general steps to building the graphics demos.
• Using MPLAB X IDE, click the File drop-down, select "Open Project...". Navigate to your Harmony installation folder. The
default location on Windows will be: C:\Microchip\Harmony\\apps\gfx.
• In the \app\gfx folder there will be the object, primitive, lcc, and ssd1926 demonstration applications.
• Within each demonstration folder, there will be a firmware folder. In the firmware folder will exist the MPLAB X IDE project
specific to each demonstration.
• Select the project and click "Open Project"
• To configure the project specific to a preset board configuration, right click on the project and select "Set Configuration". This
will set the build configuration to match the supported board configuration.
3.3.4.1 lcc_demo
Demonstrates the advanced capabilities of the Graphics Library utilizing the software graphics controller.
Description
This demonstration provides the ability to display alpha blend and gradient colors through the software graphics controller. The
demonstration renders four folders for alpha blend, gradient, picture-in-picture (PIP), and performance for all PIC32 devices.
For PIC32MX devices, the demonstration runs on the PICtail Plus LCC Daughter Board, and on PIC32MZ devices, it runs on the
Multimedia Expansion Board II (MEB II).
3.3 Graphics Demonstrations MPLAB Harmony Help Demonstrations
3-85
3.3.4.1.1 Supported Demonstration Boards
Lists supported demo and development hardware boards.
Description
Demo Board (click link for board information) Notes
PIC32 USB Starter Kit II -
Graphics PICtail LCC Board AC164144 -
WQVGA 480x272 Board AC164127-6 -
Multimedia Expansion Board II (MEB II) -
PIC32MZ Embedded Connectivity (EC) Starter Kit -
3.3.4.1.2 Configuring the Hardware
Describes how to configure the supported hardware.
Description
PIC32MZ Embedded Connectivity (EC) Starter Kit
No hardware related configuration or jumper setting changes are necessary.
PIC32 USB Starter Kit II
No hardware related configuration or jumper setting changes are necessary.
Multimedia Expansion Board II (MEB II)
The MEB II has two memory options: External or Internal. This demonstration requires External EBI memory, which is configured
using the following J9 jumper settings:
• EBIOE and LCD_PCLK (jumper is closed)
• EBIWE (jumper is open)
3.3.4.1.3 Running the Demonstration
Provides instructions on how to build and run the LCC demo.
Description
Select one of the following build configurations to build the LCC demo:
• pic32mxusbsk_pictaillcc_wqvga -- For PIC32MX devices
• pic32mzsk_meb2_wqvga -- For PIC32MZ devices
Build the selected configuration in the MPLAB X IDE project and program the demonstration board. The demonstration renders
four folders for alpha blend, gradient, picture-in-picture (PIP), and performance. Touch one of the folders to activate the
demonstration.
Short Name Long Name
pic32mxusbsk PIC32 USB Starter Kit II
pic32mzsk PIC32MZ Embedded Connectivity (EC) Starter Kit
meb2 Multimedia Expansion Board II (MEB II)
3.3 Graphics Demonstrations MPLAB Harmony Help Demonstrations
3-86
wqvga Graphics Display Powertip 4.3" 480 × 272 Board (AC164127-6)
3.3.4.2 primitive_demo
An example of primitive drawing capabilities of the Graphics Library.
Description
The Primitive example demonstrates the various types of shapes and images which include: circles, lines, rectangles that exist in
the Graphics Library.
This example shows the following primitives:
• GFX_LineDraw
• GFX_CircleDraw
• GFX_CircleFillDraw
• GFX_RectangleRoundDraw
• GFX_RectangleRoundFillDraw
• GFX_RectangleFillDraw
• GFX_ArcDraw
• GFX_PolygonDraw
• GFX_FontSet
• GFX_TextStringXYPut
• GFX_ImageDraw
• GFX_ScreenClear
3.3.4.2.1 Supported Demonstration Boards
Lists supported demo and development hardware boards.
Description
Following boards are supported for PIC32MX devices:
Demo Board (click link for board information) Notes
PIC32 USB Starter Kit II -
Graphics LCD Controller PICtail Plus SSD1926 Board AC164127-5 -
QVGA 320x240 Board AC164127-4 -
Following board is supported for PIC32MZ devices:
Demo Board (click link for board information) Notes
PIC32MZ Embedded Connectivity (EC) Starter Kit -
Multimedia Expansion Board II (MEB II) -
3.3 Graphics Demonstrations MPLAB Harmony Help Demonstrations
3-87
3.3.4.2.2 Configuring the Hardware
Describes how to configure the supported hardware.
Description
PIC32 USB Starter Kit II
No hardware related configuration or jumper setting changes are necessary.
PIC32MZ Embedded Connectivity (EC) Starter Kit
No hardware related configuration or jumper setting changes are necessary.
3.3.4.2.3 Running the Demonstration
Provides instructions on how to build and run the primitive demo.
Description
Navigate to the apps/gfx/primitive/firmware folder and open the primitive project, and then select one of the following build
configurations to build the Primitive demo:
• pic32mxusbsk_pictails1d_wqvga -- For PIC32MX devices
• pic32mxusbsk_pictailssd_qvga -- For PIC32MX devices
• pic32mzsk_meb2_wqvga -- For PIC32MZ devices
Once the project is loaded and executed on the target board, a continuous display of primitive graphics will appear on the LCD.
Short Name Long Name
pic32mxusbsk PIC32 USB Starter Kit II
pic32mzsk PIC32MZ Embedded Connectivity (EC) Starter Kit
pictails1d Graphics LCD Controller PICtail Plus S1D1357 Board
pictailssd Graphics LCD Controller PICtail Plus SSD1926 Board
meb2 Multimedia Expansion Board II (MEB II)
qvga Graphics Display Truly 3.2" 240 × 320 Board (AC164127-4)
wqvga Graphics Display Powertip 4.3" 480 × 272 Board (AC164127-6)
3.3.4.3 object_demo
An example of standard user-interface widgets of the Graphics Library.
Description
The Object example demonstrates the standard types of objects/widgets that exist in the Graphics Library Graphics Object Layer
(GOL). The demonstration is composed of several pages of examples.
The demonstration requires that the user touch the screen to begin the demo. The user is expected to navigate to the next or
previous page by selecting the buttons on the far right and left locations of the screen.
This example shows the following widgets:
• GFX_GOL_ButtonCreate
3.3 Graphics Demonstrations MPLAB Harmony Help Demonstrations
3-88
• GFX_GOL_ButtonTextSet
• GFX_GOL_CheckboxCreate
• GFX_GOL_GroupboxCreate
• GFX_GOL_RadioButtonCreate
• GFX_GOL_GroupboxCreate
• GFX_GOL_StaticTextCreate
• GFX_GOL_ScrollBarCreate
• GFX_GOL_ProgressBarCreate
• GFX_GOL_ListboxCreate
• GFX_GOL_ScrollBarCreate
• GFX_GOL_Editbox_Create
• GFX_GOL_MeterCreate
• GFX_GOL_DigitalMeterCreate
• GFX_GOL_RoundDialCreate
• GFX_GOL_PictureCreate
• GFX_GOL_CustomControlCreate
3.3.4.3.1 Supported Demonstration Boards
Lists supported demo and development hardware boards.
Description
Following boards are supported for PIC32MX devices:
Demo Board (click link for board information) Notes
PIC32 USB Starter Kit II -
Graphics LCD Controller PICtail Plus SSD1926 Board AC164127-5 -
QVGA 320x240 Board AC164127-4 -
Following board is supported for PIC32MZ devices:
Demo Board (click link for board information) Notes
PIC32MZ Embedded Connectivity (EC) Starter Kit -
Multimedia Expansion Board II (MEB II) -
3.3.4.3.2 Configuring the Hardware
Describes how to configure the supported hardware.
Description
PIC32 USB Starter Kit II
No hardware related configuration or jumper setting changes are necessary.
PIC32MZ Embedded Connectivity (EC) Starter Kit
3.3 Graphics Demonstrations MPLAB Harmony Help Demonstrations
3-89
No hardware related configuration or jumper setting changes are necessary.
3.3.4.3.3 Running the Demonstration
Provides instructions on how to build and run the object demo.
Description
Navigate to the apps/gfx/object/firmware and open the object project, and then select one of the following build configurations to
build the Object demo:
• pic32mxusbsk_pictailssd_qvga -- For PIC32MX devices
• pic32mzsk_meb2_wqvga -- For PIC32MZ devices
Once the project is loaded and executed on the target board, various objects are displayed. Touch the forward or back arrow to
view additional objects.
Short Name Long Name
pic32mxusbsk PIC32 USB Starter Kit II
pic32mzsk PIC32MZ Embedded Connectivity (EC) Starter Kit
pictailssd Graphics LCD Controller PICtail Plus SSD1926 Board
meb2 Multimedia Expansion Board II (MEB II)
qvga Graphics Display Truly 3.2" 240 × 320 Board (AC164127-4)
3.3.4.4 ssd_demo
Shows how to display JPEG images using the Solomon Systech (SSD1926) graphics controller that resides on the PICtail™
Plus SSD1926 Board.
Description
The SSD1926 demo shows how to decode of JPEG images from an SD card utilizing the JPEG decoder capabilities of the
Solmon Systech SSD1926 graphics controller.
3.3.4.4.1 Supported Demonstration Boards
Lists supported demo and development hardware boards.
Description
Following board is supported for PIC32MX devices:
Demo Board (click link for board information) Notes
PIC32 USB Starter Kit II -
Graphics LCD Controller PICtail Plus SSD1926 Board AC164127-5 -
QVGA 320x240 Board AC164127-4 -
3.3.4.4.2 Configuring the Hardware
Describes how to configure the supported hardware.
3.3 Graphics Demonstrations MPLAB Harmony Help Demonstrations
3-90
Description
PIC32 USB Starter Kit II
No hardware related configuration or jumper setting changes are necessary.
3.3.4.4.3 Running the Demonstration
Provides instructions on how to build and run the SSD1926 demo.
Description
Navigate to the apps/gfx/ssd1926/firmware and open the ssd1926 project, and then select one of the following build
configurations to build the SSD1926 demo:
• pic32mxusbsk_pictailssd_qvga -- For PIC32MX devices
Once the project is loaded and executed on the target board, various JPEG images, which are stored on a SD card are
displayed.
Short Name Long Name
pic32mxusbsk PIC32 USB Starter Kit II
pictalssd Graphics LCD Controller PICtail Plus SSD13517 Board
qvga Graphics Display Truly 3.2" 240 × 320 Board (AC164127-4)
3.3.5 Demonstration Board Information
This topic provides specific information about the development boards available for the demonstration applications.
3.3.5.1 PIC32 USB Starter Kit II
Provides information on the PIC32 USB Starter II.
Description
SW1 - Application switch. Tied to RD6.
SW2 - Application switch. Tied to RD7.
3.3 Graphics Demonstrations MPLAB Harmony Help Demonstration Board Information
3-91
SW3 - Application switch. Tied to RD13.
LED1 - Application LED. Tied to RD0.
LED2 - Application LED. Tied to RD1.
LED3 - Application LED. Tied to RD2.
This board supports the following USB Device demonstrations:
• CDC Single COM port (cdc_com_port_single).
• CDC Dual COM port (cdc_com_port_dual)
• HID Basic (hid_basic)
• HID Mouse (hid_mouse)
• HID Keyboard (hid_keyboard)
• HID Joystick (hid_joystick)
• MSD Flash Drive (msd_basic)
• Generic USB Device (generic_device)
More Information
Microchip Part Number : DM320003-2
3.3.5.2 PIC32MZ Embedded Connectivity (EC) Starter Kit
Provides details information on the PIC32MZ Embedded Connectivity (EC) Starter Kit.
Description
Microchip Part Number: DM320006 (without Crypto) or DM320006-C (with Crypto)
The top assembly of the board includes these key features, as indicated in Figure 1:
1. PIC32MZ2048ECH144 32-bit microcontroller.
2. Green power indicator LED.
3. On-board crystal or oscillator for precision microcontroller clocking (12 MHz).
4. USB connectivity for on-board debugger communications.
5. Green debug indicator LED.
6. Three push button switches for user-defined inputs.
7. Three user-defined indicator LEDs.
8. USB Type A receptacle connectivity for PIC32 host-based applications.
9. HOST mode power jumper.
10. Daughter board connectors for flexible Ethernet PHY options.
11. 32 kHz oscillator for RTCC and Timer1 (optional).
12. External 2 GB SQI memory for expanded memory application.
13. Jumper for using or disconnecting the on-board debugger.
NOTE: When running self-powered USB device applications, open the jumper JP1 to prevent possibly back-feeding voltage onto
the Vbus from one port on the host to another (or from one host to another).
3.3 Graphics Demonstrations MPLAB Harmony Help Demonstration Board Information
3-92
Figure 1: PIC32MZ Embedded Connectivity (EC) Starter Kit Layout (Front)
The bottom assembly of the board includes these key features, as indicated in Figure 2:
1. PIC24FJ256GB106 USB microcontroller for on-board debugging.
2. Regulated +3.3V power supply for powering the starter kit via USB or expansion board.
3. Connector for various expansion boards.
4. USB Type micro-AB receptacle for OTG and USB device connectivity for PIC32 OTG/device-based applications.
5. 50 MHz Ethernet PHY oscillator.
6. USB Host and OTG power supply for powering PIC32 USB applications.
Figure 2: PIC32MZ Embedded Connectivity (EC) Starter Kit Layout (Back)
3.3 Graphics Demonstrations MPLAB Harmony Help Demonstration Board Information
3-93
Microchip Part Number: DM320006 (without Crypto) or DM320006-C (with Crypto)
The top assembly of the board includes these key features, as indicated in Figure 1:
1. PIC32MZ2048ECH144 32-bit microcontroller.
2. Green power indicator LED.
3. On-board crystal or oscillator for precision microcontroller clocking (12 MHz).
4. USB connectivity for on-board debugger communications.
5. Green debug indicator LED.
6. Three push button switches for user-defined inputs.
7. Three user-defined indicator LEDs.
8. USB Type A receptacle connectivity for PIC32 host-based applications.
9. HOST mode power jumper.
10. Daughter board connectors for flexible Ethernet PHY options.
11. 32 kHz oscillator for RTCC and Timer1 (optional).
12. External 2 GB SQI memory for expanded memory application.
13. Jumper for using or disconnecting the on-board debugger.
NOTE: When running self-powered USB device applications, open the jumper JP1 to prevent possibly back-feeding voltage onto
the Vbus from one port on the host to another (or from one host to another).
Figure 1: PIC32MZ Embedded Connectivity (EC) Starter Kit Layout (Front)
The bottom assembly of the board includes these key features, as indicated in Figure 2:
1. PIC24FJ256GB106 USB microcontroller for on-board debugging.
2. Regulated +3.3V power supply for powering the starter kit via USB or expansion board.
3. Connector for various expansion boards.
4. USB Type micro-AB receptacle for OTG and USB device connectivity for PIC32 OTG/device-based applications.
5. 50 MHz Ethernet PHY oscillator.
3.3 Graphics Demonstrations MPLAB Harmony Help Demonstration Board Information
3-94
6. USB Host and OTG power supply for powering PIC32 USB applications.
Figure 2: PIC32MZ Embedded Connectivity (EC) Starter Kit Layout (Back)
3.3.5.3 PICtail Plus SSD1926 Daughter Board
This topic provides information about the Graphics LCD Controller PICtail™ Plus SSD1926 Board.
Description
More Information
Microchip Part Number: AC164127-5
Microchip Product Page
3.3.5.4 PICtail Plus S1D13517 Daughter Board
This topic provides information about the Graphics LCD Controller PICtail™ Plus SSD1926 Daughter Board.
Description
More Information
Microchip Part Number: AC164127-7
Microchip Product Page
3.3.5.5 PICtail Plus LCC Daughter Board
This topic provides information about the Graphics LCD Controller PICtail™ Plus LCC Daughter Board.
Description
More Information
3.3 Graphics Demonstrations MPLAB Harmony Help Demonstration Board Information
3-95
Microchip Part Number: AC164144
Microchip Product Page
3.3.5.6 PIC32MX795F512L Plug-In-Module (PIM)
Provides information on the PIC32MX795F512L Plug-In-Module (PIM).
Description
This PIM is required while using the Explorer 16 Development Board.
More Information
Microchip Part Number: MA320003
microchipDIRECT Product Page
3.3.5.7 Multimedia Expansion Board (MEB)
This topic provides information about the Multimedia Expansion Board (MEB).
3.3.5.8 Multimedia Expansion Board II (MEB II)
Provides details information on the Multimedia Expansion Board II (MEB) II.
Description
Description
Microchip Part Number: DM320005-2
Product Page
The front side of the MEB II includes these key features, as shown in Figure 1:
1. Display daughter board connector (60-pin Hirose board-to-board connector).
2. mTouch™ buttons.
3. Push Button.
4. Power LED.
5. User LEDs.
6. VGA Camera (OVM7690).
7. PICtail™ Connector.
8. Analog temperature sensor.
3.3 Graphics Demonstrations MPLAB Harmony Help Demonstration Board Information
3-96
Figure 1: Multimedia Expansion Board II Layout (Front)
The underside of the MEB II includes these key features, as shown in Figure 2:
1. Regulated 5V and 3.3V power supply for powering the board via a 9-15V DC Adapter.
2. PIC32 Starter Kit connector (168-pin Hirose board-to-board connector).
3. 24-bit stereo audio codec (AK4953A).
4. Integrated 802.11bg wireless module (MRF24WG0MA).
5. Low-cost Bluetooth® HCI transceiver (BTM805).
6. EBI SRAM memory (IS61WV102416BLL).
7. microSD slot.
8. Analog accelerometer (ADXL325).
Figure 2: Multimedia Expansion Board II Layout (Back)
3.3 Graphics Demonstrations MPLAB Harmony Help Demonstration Board Information
3-97
3.4 Peripheral Library Example Applications
This topic describes the peripheral library example applications.
3.4.1 Introduction
Peripheral Library Example Applications
for
MPLAB Harmony
The example applications for MPLAB peripheral libraries (PLIBs) provide very simple single-purpose examples of how to use
MPLAB Harmony peripheral libraries.
Description
Peripheral libraries (PLIBs) are the lowest level libraries provided with MPLAB Harmony. They provide a functional abstraction of
the peripherals available on Microchip microcontrollers to hide differences in register details that can exist from part to part.
However, they do not maintain any state data (at least not any that isn't stored in the hardware registers) from call to call and
they do not provide any protection of the peripheral's resources. As such, any code that calls the PLIB for a peripheral must take
responsibility for ownership of that peripheral and is responsible for managing the behavior of that peripheral.
As such, PLIBs are normally only used by MPLAB Harmony device drivers or system services. However, there are some times
when it is necessary and appropriate to interact with a PLIB directly from an application. So, simple examples are provided to
show how to use the interfaces the peripheral libraries. These examples are available in the MPLAB Harmony installation in the
following location.
Location of Example Applications
/apps/examples/peripheral
Examples are divided into two different groups:
• Blocking Examples
• State-Driven Examples
Most MPLAB Harmony applications use a state-machine driven structure. So, examples are provided that follow this structure in
the "state_driven" subdirectory. However, it is sometimes easier to understand a simple blocking example (one that sits in a loop
for ever or until its task is done). So, simple blocking examples are also provided in the "blocking" subdirectory.
Blocking examples are divided into PIC32MX and PIC32MZ variants. PIC32MX examples are written for the Explorer16
Development Board with a PIC32MX795F512L PIM. PIC32MZ examples are written for the PIC32MZ Embedded Connectivity
(EC) Starter Kit. The state-driven examples are tested and working on the Explorer 16 Development Board, the PIC32 USB
Starter Kit II, and the PIC32MZ Embedded Connectivity (EC) Starter Kit, and the appropriate board configuration for each project
can be selected in MPLAB X IDE.
3.4 Peripheral Library Example Applications MPLAB Harmony Help Release Notes
3-98
3.4.2 Release Notes
MPLAB Harmony Version: v0.70b Peripheral Library Example Applications Version: 0.01a Release Date: 18Nov2013
The interface can change in the beta and\or 1.0 release.
New This Release:
Nothing to report for this release.
Known Issues:
Nothing to report for this release.
3.4.3 SW License Agreement
(c) 2013 Microchip Technology Inc.
Microchip licenses this software to you solely for use with Microchip products. The software is owned by Microchip and its
licensors, and is protected under applicable copyright laws. All rights reserved.
SOFTWARE IS PROVIDED "AS IS" MICROCHIP EXPRESSLY DISCLAIMS ANY WARRANTY OF ANY KIND, WHETHER
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL MICROCHIP BE LIABLE FOR
ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, HARM TO
YOUR EQUIPMENT, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS
BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR
CONTRIBUTION, OR OTHER SIMILAR COSTS.
To the fullest extent allowed by law, Microchip and its licensors liability shall not exceed the amount of fees, if any, that you have
paid directly to Microchip to use this software.
MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE TERMS.
3.4.4 Blocking Applications
This topic contains a list of the MPLAB Harmony blocking peripheral library (PLIB) example applications.
Description
The tables below list and summarizes the simple blocking peripheral library example applications.
Location
/apps/examples/peripheral/blocking/pic32mx
PIC32MX PLIB-based Applications
3.4 Peripheral Library Example Applications MPLAB Harmony Help Blocking Applications
3-99
Name Subdirectory Description
ADC
Potentiometer
adc/adc_pot Repeatedly reads the Explorer 16 Development Board potentiometer and outputs a
pattern on the LEDs corresponding to the potentiometer's position.
Memory
Partition
bmx/mem_partition Partitions flash memory and ram. Explorer 16 Development Board LEDs are turned
on if the RAM partition sizes are correct and the partitioning completed successfully.
Simple
Comparator
cmp/simple_comparator Toggles the LEDs on the Explorer 16 Development Board, depending on which input
of the comparator is at a higher voltage.
Triangle
Wave
cvref/triangle_wave This example will generate a triangular wave on the CVREF output pin.
LED Pattern dma/led_pattern Blinks LEDs on the Explorer 16 Development Board using a pattern stored in Flash
memory. It uses the DMA controller to transfer data from flash to the I/O port
controlling the LEDs.
Master-Slave i2c/master_slave The I2C1 module is setup to operate as the master, while the I2C2 module operates
as the slave. The master sends a string to the slave, which stores the data into an
array.
Simple
Input-Capture
ic/simple_input_capture When a rising edge is output to the Input Capture 1 pin (RD8), it triggers an interrupt,
which then stores the captured timer value into the 'CaptureTime' variable.
Flash Modify nvm/flash_modify Reads, writes and erases data in the program Flash memory.
PWM
Example
oc/oc_pwm Generates a 40 kHz PWM with a 25% duty cycle on the OC1 output pin.
Oscillator
Configuration
osc/osc_config Demonstrates how to change the system clock source and PLL values during
run-time.
LCD Example pmp/pmp_lcd Writes two lines of text to the LCD screen on the Explorer 16 Development Board.
Blinky Leds ports/blinky_leds Toggles the Explorer 16 Development Board LEDs in an infinite loop.
Change
Notice
ports/cn_interrupt When SW4 (the right most button on Explorer 16 Development Board) is pressed, it
triggers a change notice interrupt, which then toggles the Explorer 16 Development
Board LEDs.
Sleep Mode power/sleep_mode This example demonstrates how to put the device into Sleep mode and then awake
the device using the Watchdog Timer.
Reset
Handler
reset/reset_handler This example does checks on various reset flags, assigning each one to an Explorer
16 Development Board LED. If the flag is set, the LED is turned on and the reset flag
is cleared.
RTCC Alarm rtcc/rtcc_alarm Sets up the RTCC module to function as an alarm, which goes off at 6:00am every
morning.
SPI
Loopback
spi/spi_loopback This example assumes that the SPI SDO (output) is connected to the SDI (input).
Data is then transferred directly from the output to the input and the Explorer 16
Development Board LEDs are turned on if the data transfer is successful.
Timer
Example
tmr/timer2_interrupt Uses Timer2 in 32-bit mode to generate an interrupt every one second, blinking the
LEDs on the Explorer 16 Development Board.
Simple UART uart/simple_uart When the Explorer 16 Development Board is connected to a PC with an RS-232
cable, the device will echo what characters the user types into a terminal program
(e.g., Putty) and write the corresponding 8-bit character pattern to the Explorer 16
Development Board LEDs.
Simple WDT wdt/simple_wdt Demonstrates how to setup the Watchdog Timer and detect whether or not a
time-out reset has occurred.
Location
/apps/examples/peripheral/blocking/pic32mz
3.4 Peripheral Library Example Applications MPLAB Harmony Help Blocking Applications
3-100
PIC32MZ PLIB-based Applications
Name Subdirectory Description
Triangle
Wave
cvref/triangle_wave This example will generate a triangular wave on the CVref output pin.
LED Pattern dma/led_pattern Blinks LEDs on the PIC32MZ Starter-Kit using a pattern stored in flash memory. It
uses the DMA controller to transfer data from flash to the I/O port controlling the
LEDs.
Master-Slave i2c/master_slave The I2C1 module is setup to operate as the master, while the I2C2 module operates
as the slave. The master sends a string to the slave, which stores the data into an
array.
Flash Modify nvm/flash_modify Reads, writes and erases data in the program flash memory.
PWM
Example
oc/oc_pwm Generates a 40KHz PWM with a 25% duty cycle on the OC1 output pin.
Oscillator
Configuration
osc/osc_config Demonstrates how to change the system clock source and PLL values during
run-time.
Blinky Leds ports/blinky_leds Toggles the PIC32MZ Starter-Kit LEDs in an infinite loop.
Change
Notice
ports/cn_interrupt When SW1 is pressed, it triggers a change notice interrupt, which then toggles the
PIC32MZ Starter-Kit LEDs.
Sleep Mode power/sleep_mode This example demonstrates how to put the device into sleep mode and then awake
the device using the watchdog timer.
Reset
Handler
reset/reset_handler This example does checks on various reset flags, assigning each one to an LED. If
the flag is set, the LED is turned on and the reset flag is cleared.
RTCC Alarm rtcc/rtcc_alarm Sets up the RTCC module to function as an alarm, which goes off at 6:00am every
morning.
SPI
Loopback
spi/spi_loopback This example assumes that the SPI SDO (output) is connected to the SDI (input).
Data is then transferred directly from the output to the input and the LEDs are turned
on if the data transfer is successful.
Timer
Example
tmr/timer2_interrupt Uses Timer 2 in 32-bit mode to generate an interrupt every one second, blinking the
LEDs on the PIC32MZ Starter-Kit.
Simple
UART
uart/simple_uart When the PIC32MZ Starter-Kit is connected to a PC with an RS-232 cable, the
device will echo what characters the user types into a terminal program (e.g. Putty).
Simple WDT wdt/simple_wdt Demonstrates how to setup the watchdog timer and detect whether or not a timeout
reset has occurred.
3.4.5 State-Driven Applications
Note: This information was not available at time of release and will be added in a future release of MPLAB Harmony.
3.4 Peripheral Library Example Applications MPLAB Harmony Help State-Driven Applications
3-101
3.5 NVM Driver Demonstration
3.5.1 Introduction
This help file contains instructions and associated information about MPLAB Harmony NVM driver application demonstrations,
which are contained in the MPLAB Harmony Library distribution.
Description
This application demonstrates the capabilities of the MPLAB Harmony NVM driver. This help file describes the hardware
requirement and procedures to build, run the demo project on Microchip development tools. In this demo application, NVM driver
is used to access the internal flash memory of PIC32 MX and PIC32 MZ Devices to perform Write and Read operations and
indicates the result by LED display.
To know more about MPLAB Harmony NVM driver, configuring the NVM driver and API's provided by the NVM driver, refer to
MPLAB Harmony NVM Driver Library documentation.
3.5.2 Release Notes
MPLAB Harmony Version: v0.70b NVM Driver Demonstration Version: 0.01a Release Date: 18Nov2013
New This release:
This is the first release of this NVM Driver demonstration application. This demonstration has been developed to support
PIC32MX and PIC32MZ devices.
Known Issues:
• This Demo application is tested only up to 150 bytes in interrupt mode in PIC32MZ devices
• Changes in NVM driver interfaces will have impact on this demo application as well in subsequent releases
3.5.3 SW License Agreement
(c) 2013 Microchip Technology Inc.
Microchip licenses this software to you solely for use with Microchip products. The software is owned by Microchip and its
licensors, and is protected under applicable copyright laws. All rights reserved.
SOFTWARE IS PROVIDED "AS IS" MICROCHIP EXPRESSLY DISCLAIMS ANY WARRANTY OF ANY KIND, WHETHER
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL MICROCHIP BE LIABLE FOR
ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, HARM TO
3.5 NVM Driver Demonstration MPLAB Harmony Help SW License Agreement
3-102
YOUR EQUIPMENT, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS
BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR
CONTRIBUTION, OR OTHER SIMILAR COSTS.
To the fullest extent allowed by law, Microchip and its licensors liability shall not exceed the amount of fees, if any, that you have
paid directly to Microchip to use this software.
MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE TERMS.
3.5.4 Hardware
This section describes how to select and use an appropriate development board and steps to configure the hardware to run this
NVM driver demo.
3.5.4.1 Required Hardware
This section describes the overview of required hardware family and supported demonstration boards for running this NVM driver
demo application.
Description
To run this demonstration project. you will require one of the following sets of hardware.
3.5.4.1.1 Supported Demonstration Boards
Lists supported demonstration and development hardware boards.
Description
Following board is supported for PIC32MX devices: -
Demo Board (click link for board information) Notes
PIC32 USB Starter Kit II -
Explorer 16 Development Board -
PIC32MX795F512L Plug-in Module (PIM) -
Following board is supported for PIC32MZ devices: -
Demo Board (click link for board information) Notes
PIC32MZ Embedded Connectivity (EC) Starter Kit -
3.5.4.1.2 Hardware Information
Information on hardware used by the NVM driver demo application.
Description
The NVM driver demo application can be tried on different hardware boards. This section provide details on the different
hardware boards that this demo application supports.
3.5 NVM Driver Demonstration MPLAB Harmony Help Hardware
3-103
3.5.4.1.2.1 PIC32 USB Starter Kit II
Provides information on the PIC32 USB Starter Kit II.
Description
SW1 - Application switch. Tied to RD6.
SW2 - Application switch. Tied to RD7.
SW3 - Application switch. Tied to RD13.
LED1 - Application LED. Tied to RD0.
LED2 - Application LED. Tied to RD1.
LED3 - Application LED. Tied to RD2.
More Information
Microchip Part Number : DM320003-2
3.5.4.1.2.2 Explorer 16 Development Board
Provides information on the Explorer 16 Development Board.
3.5 NVM Driver Demonstration MPLAB Harmony Help Hardware
3-104
Description
S1 - Reset button (MCLR)
S2 - Processor switch. This switch determines which processor is running, the processor on the board or the processor on the
Plug-In-Module (PIM).
S3, S4, S5, S6 - Application switches. For information about what pin is connected to this switch, please refer to the information
for the PIM in use.
D3 through D10 - Application LEDs. For information about what pin is connected to this LED, please refer to the information for
the PIM in use.
More Information:
Microchip Part Number: DM240001
3.5.4.1.2.3 PIC32MX795F512L Plug-in Module (PIM)
Provides information on the PIC32MX795F512L Plug-In-Module (PIM).
Description
This PIM is required while using the Explorer 16 Development Board.
3.5 NVM Driver Demonstration MPLAB Harmony Help Hardware
3-105
More Information
Microchip Part Number: MA320003
microchipDIRECT Product Page
3.5.4.1.2.4 PIC32MZ Embedded Connectivity (EC) Starter Kit
Provides information on the PIC32MZ Embedded Connectivity (EC) Starter Kit.
Description
Microchip Part Number: DM320006 (without Crypto) or DM320006-C (with Crypto)
The top assembly of the board includes these key features, as indicated in Figure 1:
1. PIC32MZ2048ECH144 32-bit microcontroller.
2. Green power indicator LED.
3. On-board crystal or oscillator for precision microcontroller clocking (12 MHz).
4. USB connectivity for on-board debugger communications.
5. Green debug indicator LED.
6. Three push button switches for user-defined inputs.
7. Three user-defined indicator LEDs.
8. USB Type A receptacle connectivity for PIC32 host-based applications.
9. HOST mode power jumper.
10. Daughter board connectors for flexible Ethernet PHY options.
11. 32 kHz oscillator for RTCC and Timer1 (optional).
12. External 2 GB SQI memory for expanded memory application.
13. Jumper for using or disconnecting the on-board debugger.
NOTE: When running self-powered USB device applications, open the jumper JP1 to prevent possibly back-feeding voltage onto
the Vbus from one port on the host to another (or from one host to another).
3.5 NVM Driver Demonstration MPLAB Harmony Help Hardware
3-106
Figure 1: PIC32MZ Embedded Connectivity (EC) Starter Kit Layout (Front)
The bottom assembly of the board includes these key features, as indicated in Figure 2:
1. PIC24FJ256GB106 USB microcontroller for on-board debugging.
2. Regulated +3.3V power supply for powering the starter kit via USB or expansion board.
3. Connector for various expansion boards.
4. USB Type micro-AB receptacle for OTG and USB device connectivity for PIC32 OTG/device-based applications.
5. 50 MHz Ethernet PHY oscillator.
6. USB Host and OTG power supply for powering PIC32 USB applications.
Figure 2: PIC32MZ Embedded Connectivity (EC) Starter Kit Layout (Back)
3.5.4.1.2.5 Multimedia Expansion Board II (MEB II)
Provides information on the Multimedia Expansion Board II (MEB II).
Description
Microchip Part Number: DM320005-2
Product Page
The front side of the MEB II includes these key features, as shown in Figure 1:
1. Display daughter board connector (60-pin Hirose board-to-board connector).
2. mTouch™ buttons.
3. Push Button.
4. Power LED.
5. User LEDs.
6. VGA Camera (OVM7690).
7. PICtail™ Connector.
8. Analog temperature sensor.
3.5 NVM Driver Demonstration MPLAB Harmony Help Hardware
3-107
Figure 1: Multimedia Expansion Board II Layout (Front)
The underside of the MEB II includes these key features, as shown in Figure 2:
1. Regulated 5V and 3.3V power supply for powering the board via a 9-15V DC Adapter.
2. PIC32 Starter Kit connector (168-pin Hirose board-to-board connector).
3. 24-bit stereo audio codec (AK4953A).
4. Integrated 802.11bg wireless module (MRF24WG0MA).
5. Low-cost Bluetooth® HCI transceiver (BTM805).
6. EBI SRAM memory (IS61WV102416BLL).
7. microSD slot.
8. Analog accelerometer (ADXL325).
Figure 2: Multimedia Expansion Board II Layout (Back)
3.5 NVM Driver Demonstration MPLAB Harmony Help Hardware
3-108
3.5.4.2 Configuring the Hardware
Describes how to configure the supported hardware.
Description
Explorer 16 Development Board
This demonstration application is demonstrated using Explorer 16 Development Board, PIC32 USB Starter Kit II and PIC32MZ
Embedded Connectivity (EC) Starter Kit. The following hardware configuration should be set up before running this application.
1. Before attaching the PIC32MX795F512L PIM to the Explorer 16 Development Board, ensure that the processor select switch
(S2) is in the PIM Position.
2. Short JP2 on the Explorer 16 Development Board to enable the LEDs.
PIC32 USB Starter Kit II
No hardware related configuration or jumper setting changes are necessary.
PIC32MZ Embedded Connectivity (EC) Starter Kit
No hardware related configuration or jumper setting changes are necessary.
3.5.5 Building the Application
This section describes how to build this demonstration project.
Description
Once the hardware is configured, you are ready to build this application.
Project Setup :
From the MPLAB X IDE, Select "open project" and browse to this demo location. This demo application is available in "/apps/driver/nvm/nvm_read_write/firmware/nvm_read_write.X". This directory contains all the application related source
files, header files as well as MPLAB X IDE project related workspace files.
How to build this demonstration application:
To build this demo in debug mode, Go to "Run" menu in MPLAB X IDE and select "Build Main Project" or select "Build Main
Project" in toolbar. Once the project gets compiled successfully, you can run this demonstration application.
For more information on how to compile and program projects, refer to the MPLAB X IDE help available through the help menu
in MPLAB X IDE.
Note:The appropriate project configurations should be selected before building the project for the configured hardware.
3.5.5.1 Configuring the Application
This section describes the list of configuration options, build options, and how they are configured for this demonstration
application.
Build options:
This application supports both PIC32MX and PIC32MZ devices. From project properties of MPLAB X IDE, select
"pic32mx_usb_starterkit_II" configuration if the target hardware is a PIC32MX device, or select "pic32mz_sk" configuration if the
3.5 NVM Driver Demonstration MPLAB Harmony Help Building the Application
3-109
target hardware is a PIC32MZ device.
The default target device is "PIC32MX795F512L" for "pic32mx_usb_starterkit_II" configuration and "PIC32MZ2048ECH144" for
"pic32mz_sk" configuration with optimization level as "0". The various optimization levels can be selected from the list to run this
demonstration.
Note: If the target device is changed, the appropriate PIM needs to be used to run this demonstration application.
Configuration options:
All of the demonstration application related configuration options are available in "system_config.h" file. This file is available in
the "apps/driver/nvm/nvm_read_write/firmware/src/system_config/pic32mx_usb_starterkit_II" or "apps/driver/nvm/nvm_read_write/firmware/src/system_config/pic32mz_sk"directory based on the configuration selected.
This file has the following list of configurations:
• General System Clock Services
• NVM Driver
• Interrupt services
Note: Based on the configurations, the demo application behavior will be changed.
3.5.5.2 Configuring the Libraries
This section describes the configuration options provided by MPLAB Harmony Libraries used by the application.
Macro Name Description
#define
DRV_NVM_INSTANCES_NUMBER
This definition selects the maximum number of hardware instances that can be supported
by the dynamic NVM driver
#define
DRV_NVM_CLIENTS_NUMBER
This definition selects the maximum number of clients that the NVM driver can support at
run time
#define
DRV_NVM_INTERRUPT_MODE
This macro controls the operation of the driver in the interrupt mode of operation
#define DRV_NVM_ROW_SIZE This macro defines the row size of target Flash
#define DRV_NVM_PAGE_SIZE This macro selects the NVM page size size
#define NVM_BASE_ADDRESS This macro defines the address to which the data is written and read
3.5.5.3 Customizing the Application
This section explains the steps involved in customizing the existing demonstration application.
Customizing Existing Demonstration Application:
In this demo application, the NVM driver operates in interrupt mode. Following are the steps to be used to customize this
application in olling mode.
1. Change #define DRV_NVM_INTERRUPT_MODE as false in "system_config.h" file
2. Remove the NVM ISR routine from "system_int.c" file
3. Call the DRV_NVM_Tasks function in "system_task.c" file
After changing the above configurations, compile the customized application and program the target device.
3.5 NVM Driver Demonstration MPLAB Harmony Help Running the Application
3-110
3.5.6 Running the Application
This section demonstrates how to run the NVM Driver demonstration.
Description
This is a simple demonstration to show how to configure and make use of NVM driver API's to implement and access on-board
Flash memory of PIC32MX and PIC32MZ devices.
How to run this demonstration application:
Once the demonstration application is compiled successfully, you are ready to program the firmware in the target device.
To run the demonstration in debug mode, below are the steps to be followed.
1. Select appropriate configuration from project properties based on the target hardware.
2. Select your device programmer from the "hardware tool" in MPLAB X IDE.
3. Select the "Debug Main Project" in "Debug" menu or select the "Debug Main Project" in toolbar.
Build the selected configuration in the MPLAB X IDE project and program the demonstration board. The execution status
(pass/fail) of the demonstration is indicated by LEDs on the demonstration board.
Demonstration Board Successful Indication Failure Indication
PIC32 USB Starter Kit II LED2 LED1
PIC32MZ Embedded Connectivity (EC) Starter Kit Green LED Red LED
This demonstration first reads the data from specific NVM address define in system_config.h header file and erases the entire
sector, write 150 bytes of data and reads back. The Pass/Fail criteria is indicated using LEDs as defined above.
3.5.7 Files
This section provides a complete list of source files required by the application and describes the purpose of adding each files.
MPLAB Harmony installation follows a standard directory structure for all application solutions. In this directory structure, the
driver, plib, system services related source files, header files for this demonstration application are available in "/framework/". Below are the list of files added in this demonstration application.
Files Description
driver.h Driver Library Interface Header
drv_common.h This file defines all common macros and definitions used by the driver
drv_nvm.h NVM device driver interface file.
system.h System Service Interface Headers
sys_common.h This file contains system Common definitions and declarations
sys_module.h This file contains system module definitions
system_config.h This is file contains all the system configurations
system_definitions.h This contains system prototypes and definitions
3.5 NVM Driver Demonstration MPLAB Harmony Help Files
3-111
app.h This file contains application related definitions and prototypes
config_performance.c BSP file for Explorer 16 Development Board
drv_nvm_dynamic.c This file contains NVM device driver dynamic implementation
plib_int_pic32.c Interrupt Source implementation for PIC32 devices
sys_int_pic32.c This file contains functions related to the Interrupt System Service for PIC32 devices
app.c This file contains application related implementations
main.c This file contains application's main entry point
system_init.c This file contains source code necessary to initialize the system
system_int.c This file contains a definitions of the raw ISRs required to support the interrupt sub-system
system_tasks.c This file will contain any source code necessary to maintain various tasks in the system
3.5 NVM Driver Demonstration MPLAB Harmony Help Files
3-112
3.6 RTOS Demonstrations
3.6.1 Introduction
RTOS Demonstration Applications Help
Description
This distribution package contains a variety of RTOS based firmware projects that demonstrate the capabilities of the MPLAB
Harmony services and stacks integrated with RTOS running on PIC32 devices. This help file describes the hardware
requirement and procedures to run these firmware projects on Microchip demonstration and development boards.
To learn more about MPLAB Harmony stacks and libraries refer to the related Framework help documentation.
3.6.2 Release Notes
MPLAB Harmony Version: v0.70b RTOS Demonstrations Version: 0.01a Release Date: 18Nov2013
New This Release:
This release contains the FreeRTOS basic project.
Known Issues:
Nothing to report for this release.
3.6.3 SW License Agreement
(c) 2013 Microchip Technology Inc.
Microchip licenses this software to you solely for use with Microchip products. The software is owned by Microchip and its
licensors, and is protected under applicable copyright laws. All rights reserved.
SOFTWARE IS PROVIDED "AS IS" MICROCHIP EXPRESSLY DISCLAIMS ANY WARRANTY OF ANY KIND, WHETHER
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL MICROCHIP BE LIABLE FOR
ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, HARM TO
YOUR EQUIPMENT, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS
BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR
CONTRIBUTION, OR OTHER SIMILAR COSTS.
To the fullest extent allowed by law, Microchip and its licensors liability shall not exceed the amount of fees, if any, that you have
paid directly to Microchip to use this software.
3.6 RTOS Demonstrations MPLAB Harmony Help SW License Agreement
3-113
MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE TERMS.
3.6.4 Demonstrations
This topic provides information on how to run the RTOS demonstration applications included in this release.
Description
All demonstrations provided should be built using the MPLAB X IDE development environment tool supplied by Microchip.
The following information communicates the general steps to building the demonstrations.
• Using MPLAB X IDE, click the File drop-down, select "Open Project...". Navigate to your Harmony installation folder. The
default location on Windows will be: C:\Microchip\Harmony\\apps\rtos
• In the \app\rtos folder there will be the demonstration applications.
• Within each demonstration folder, there will be a MPLAB X IDE project specific to each demonstration
• Select the project and click "Open Project"
• To configure the project specific to a preset board configuration, right click on the project and select "Set Configuration"
This will set the build configuration to match the supported board configuration.
3.6.4.1 FreeRTOS_basic_demo
3.6.4.1.1 Supported Demonstration Boards
Lists supported demonstration and development hardware boards.
Description
Demonstration Board (click link for board information) Notes
PIC32 USB Starter Kit II -
PIC32MZ Embedded Connectivity (EC) Starter Kit -
3.6.4.1.2 Configuring the Hardware
Describes how to configure the supported hardware.
Description
PIC32 USB Starter Kit II
No hardware related configuration or jumper setting changes are necessary.
PIC32MZ Embedded Connectivity (EC) Starter Kit
No hardware related configuration or jumper setting changes are necessary.
3.6 RTOS Demonstrations MPLAB Harmony Help Demonstrations
3-114
3.6.4.1.3 Running the Demonstration
Provides instructions on how to build and run the FreeRTOS basic demonstration.
Description
Please use the following procedure to run the demonstration:
1. Load demonstration project into MPLAB X IDE.
2. Connect the mini-B debugger port on-board the PIC32MX or PIC32MZ Starter board to an USB port on the development
computer using the USB cable provided in the kit.
3. Build, Download, and Run demonstration project on the target board.
The demonstration application features the following:
• Application creates one queue and four tasks. One task that sends the data using FreeRTOS queue to the two tasks that
waits for the data in the queue. (QueueReceiveTask2 priority is higher than the QueueReceiveTask1 priority.)
• QueueReceiveTask2 receives the data first, toggles the LED, and then sleeps for the specified time
• QueueReceiveTask1 receives the next data since QueueReceiveTask2 is not in running state
• QueueReceiveTask1 receives the data, toggles the LED and waits for the data arrival
3.6.4.2 uC_OS_III_basic_demo
3.6.4.2.1 Supported Demonstration Boards
Lists supported demonstration and development hardware boards.
Description
Demonstration Board (click link for board information) Notes
PIC32 USB Starter Kit II -
PIC32MZ Embedded Connectivity (EC) Starter Kit -
3.6.4.2.2 Configuring the Hardware
Describes how to configure the supported hardware.
Description
PIC32 USB Starter Kit II
No hardware related configuration or jumper setting changes are necessary.
PIC32MZ Embedded Connectivity (EC) Starter Kit
No hardware related configuration or jumper setting changes are necessary.
3.6.4.2.3 Running the Demonstration
Provides instructions on how to build and run the uC_OS_III basic demonstration.
3.6 RTOS Demonstrations MPLAB Harmony Help Demonstrations
3-115
Description
Demonstration applications are available in the following folders:
• \app\rtos\freeRTOS\gfx
• \app\rtos\uC_OS_III\gfx
• \app\rtos\freeRTOS\basic
• \app\rtos\uC_OS_III\basic
Within each demonstration folder, there will be a MPLAB X IDE project specific to each demonstration
Select the project and click "Open Project"
These demos will show the following:
• <\gfx> The selected RTOS integrated in with the Harmony compliant Graphics stack.
• <\basic> The basic blink LED demo showing the selected RTOS running with the hardware.
Once the demo is up running an LED will toggle every 500ms. This demo will show the RTOS running with the selected
hardware.
3.6.4.3 FreeRTOS RTOS with Graphics
3.6.4.3.1 Supported Demonstration Boards
Lists supported demonstration and development hardware boards.
Description
Demonstration Board (click link for board information) Notes
PIC32 USB Starter Kit II -
PIC32MZ Embedded Connectivity (EC) Starter Kit -
3.6.4.3.2 Configuring the Hardware
Describes how to configure the supported hardware.
Description
PIC32 USB Starter Kit II
No hardware related configuration or jumper setting changes are necessary.
PIC32MZ Embedded Connectivity (EC) Starter Kit
No hardware related configuration or jumper setting changes are necessary.
3.6.4.3.3 Running the Demonstration
Provides instructions on how to build and run the FreeRTOS RTOS with Graphics demonstration.
3.6 RTOS Demonstrations MPLAB Harmony Help Demonstrations
3-116
Description
Demonstration applications are available in the following folders:
• \app\rtos\freeRTOS\gfx
• \app\rtos\uC_OS_III\gfx
• \app\rtos\freeRTOS\basic
• \app\rtos\uC_OS_III\basic
Within each demonstration folder, there will be a MPLAB X IDE project specific to each demonstration
Select the project and click "Open Project"
These demos will show the following:
• <\gfx> The selected RTOS integrated in with the Harmony compliant Graphics stack.
• <\basic> The basic blink LED demo showing the selected RTOS running with the hardware.
Once the demo is up running the screen color on the graphics display will change once every 500ms. A LED will toggle every
500ms.
The projects have been setup to use relative paths from the project folder and must remain under the apps\rtos\ root folders in
order to build correctly.
3.6.4.4 Micrium uC_OS_III with Graphics
3.6.4.4.1 Supported Demonstration Boards
Lists supported demonstration and development hardware boards.
Description
Demonstration Board (click link for board information) Notes
PIC32 USB Starter Kit II -
PIC32MZ Embedded Connectivity (EC) Starter Kit -
3.6.4.4.2 Configuring the Hardware
Describes how to configure the supported hardware.
Description
PIC32 USB Starter Kit II
No hardware related configuration or jumper setting changes are necessary.
PIC32MZ Embedded Connectivity (EC) Starter Kit
No hardware related configuration or jumper setting changes are necessary.
3.6 RTOS Demonstrations MPLAB Harmony Help Demonstrations
3-117
3.6.4.4.3 Running the Demonstration
Provides instructions on how to build and run the Micrium uC_OS_III with Graphics demonstration.
Description
Demonstration applications are available in the following folders:
• \app\rtos\freeRTOS\gfx
• \app\rtos\uC_OS_III\gfx
• \app\rtos\freeRTOS\basic
• \app\rtos\uC_OS_III\basic
Within each demonstration folder, there will be a MPLAB X IDE project specific to each demonstration
Select the project and click "Open Project"
These demos will show the following:
• <\gfx> The selected RTOS integrated in with the Harmony compliant Graphics stack.
• <\basic> The basic blink LED demo showing the selected RTOS running with the hardware.
Once the demo is up running the screen color on the graphics display will change once every 500ms. A LED will toggle every
500ms.
The projects have been setup to use relative paths from the project folder and must remain under the apps\rtos\ root folders in
order to build correctly.
Under the uC_OS_III\ folder, an extra step must be taken to build the project successfully. The RTOS source code and
appropriate port for the selected hardware must be download from Micrium and installed into the follow folder,
\third_party\rtos\.
3.6.5 Demonstration Board Information
3.6.5.1 PIC32 USB Starter Kit II
Provides information on the PIC32 USB Starter II.
3.6 RTOS Demonstrations MPLAB Harmony Help Demonstration Board Information
3-118
Description
SW1 - Application switch. Tied to RD6.
SW2 - Application switch. Tied to RD7.
SW3 - Application switch. Tied to RD13.
LED1 - Application LED. Tied to RD0.
LED2 - Application LED. Tied to RD1.
LED3 - Application LED. Tied to RD2.
More Information
Microchip Part Number : DM320003-2
3.6.5.2 PIC32MZ Embedded Connectivity (EC) Starter Kit
Provides details information on the PIC32MZ Embedded Connectivity (EC) Starter Kit.
Description
Microchip Part Number: DM320006 (without Crypto) or DM320006-C (with Crypto)
The top assembly of the board includes these key features, as indicated in Figure 1:
1. PIC32MZ2048ECH144 32-bit microcontroller.
2. Green power indicator LED.
3. On-board crystal or oscillator for precision microcontroller clocking (12 MHz).
4. USB connectivity for on-board debugger communications.
5. Green debug indicator LED.
6. Three push button switches for user-defined inputs.
7. Three user-defined indicator LEDs.
8. USB Type A receptacle connectivity for PIC32 host-based applications.
9. HOST mode power jumper.
10. Daughter board connectors for flexible Ethernet PHY options.
11. 32 kHz oscillator for RTCC and Timer1 (optional).
12. External 2 GB SQI memory for expanded memory application.
3.6 RTOS Demonstrations MPLAB Harmony Help Demonstration Board Information
3-119
13. Jumper for using or disconnecting the on-board debugger.
NOTE: When running self-powered USB device applications, open the jumper JP1 to prevent possibly back-feeding voltage onto
the Vbus from one port on the host to another (or from one host to another).
Figure 1: PIC32MZ Embedded Connectivity (EC) Starter Kit Layout (Front)
The bottom assembly of the board includes these key features, as indicated in Figure 2:
1. PIC24FJ256GB106 USB microcontroller for on-board debugging.
2. Regulated +3.3V power supply for powering the starter kit via USB or expansion board.
3. Connector for various expansion boards.
4. USB Type micro-AB receptacle for OTG and USB device connectivity for PIC32 OTG/device-based applications.
5. 50 MHz Ethernet PHY oscillator.
6. USB Host and OTG power supply for powering PIC32 USB applications.
3.6 RTOS Demonstrations MPLAB Harmony Help Demonstration Board Information
3-120
Figure 2: PIC32MZ Embedded Connectivity (EC) Starter Kit Layout (Back)
Microchip Part Number: DM320006 (without Crypto) or DM320006-C (with Crypto)
The top assembly of the board includes these key features, as indicated in Figure 1:
1. PIC32MZ2048ECH144 32-bit microcontroller.
2. Green power indicator LED.
3. On-board crystal or oscillator for precision microcontroller clocking (12 MHz).
4. USB connectivity for on-board debugger communications.
5. Green debug indicator LED.
6. Three push button switches for user-defined inputs.
7. Three user-defined indicator LEDs.
8. USB Type A receptacle connectivity for PIC32 host-based applications.
9. HOST mode power jumper.
10. Daughter board connectors for flexible Ethernet PHY options.
11. 32 kHz oscillator for RTCC and Timer1 (optional).
12. External 2 GB SQI memory for expanded memory application.
13. Jumper for using or disconnecting the on-board debugger.
NOTE: When running self-powered USB device applications, open the jumper JP1 to prevent possibly back-feeding voltage onto
the Vbus from one port on the host to another (or from one host to another).
3.6 RTOS Demonstrations MPLAB Harmony Help Demonstration Board Information
3-121
Figure 1: PIC32MZ Embedded Connectivity (EC) Starter Kit Layout (Front)
The bottom assembly of the board includes these key features, as indicated in Figure 2:
1. PIC24FJ256GB106 USB microcontroller for on-board debugging.
2. Regulated +3.3V power supply for powering the starter kit via USB or expansion board.
3. Connector for various expansion boards.
4. USB Type micro-AB receptacle for OTG and USB device connectivity for PIC32 OTG/device-based applications.
5. 50 MHz Ethernet PHY oscillator.
6. USB Host and OTG power supply for powering PIC32 USB applications.
Figure 2: PIC32MZ Embedded Connectivity (EC) Starter Kit Layout (Back)
3.6 RTOS Demonstrations MPLAB Harmony Help Demonstration Board Information
3-122
3.7 SPI Driver Demonstrations
3.7.1 Introduction
This help file contains instructions and associated information about MPLAB Harmony SPI driver application demonstrations,
which are contained in the MPLAB Harmony Library distribution.
Description
This application demonstrates the capabilities of the MPLAB Harmony SPI driver. This help file describes the hardware
requirement and procedures to build, run the demo project on Microchip development tools. In this demo application, SPI driver
is used to access the external EEPROM in the Explorer 16 Development Board to perform Write and Read operations and
indicates the result by LED display.
To know more about MPLAB Harmony SPI driver, configuring the SPI driver and API's provided by the SPI driver, refer to the
SPI Driver Library documentation.
3.7.2 Release Notes
MPLAB Harmony Version: v0.70b SPI Driver Demonstrations Version: 0.01a Release Date: 18Nov2013
New This release:
This is the first release of this SPI driver demonstration application. This demo has been developed to support PIC32MX devices
only. The following demonstration shows the usage of the SPI driver:
• serial_eeprom
Limitations and Known Issues:
• Demo application is only developed and tested in Interrupt mode
• Changes in SPI driver interfaces will have impact on this demo application as well in subsequent releases
• This demo will support to run only on Explorer 16 Development Board
3.7.3 SW License Agreement
(c) 2013 Microchip Technology Inc.
Microchip licenses this software to you solely for use with Microchip products. The software is owned by Microchip and its
licensors, and is protected under applicable copyright laws. All rights reserved.
SOFTWARE IS PROVIDED "AS IS" MICROCHIP EXPRESSLY DISCLAIMS ANY WARRANTY OF ANY KIND, WHETHER
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
3.7 SPI Driver Demonstrations MPLAB Harmony Help SW License Agreement
3-123
FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL MICROCHIP BE LIABLE FOR
ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, HARM TO
YOUR EQUIPMENT, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS
BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR
CONTRIBUTION, OR OTHER SIMILAR COSTS.
To the fullest extent allowed by law, Microchip and its licensors liability shall not exceed the amount of fees, if any, that you have
paid directly to Microchip to use this software.
MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE TERMS.
3.7.4 Hardware
This section describes how to select and use an appropriate development board and steps to configure the hardware to run this
SPI driver demo.
3.7.4.1 Required Hardware
This section describes the overview of required hardware family and supported demonstration boards for running this SPI driver
demo application.
Description
To run this demonstration project. you will require one of the following sets of hardware.
3.7.4.1.1 Supported Demonstration Boards
The following demo boards are supported in this release.
Description
Demonstration Board Notes
Explorer 16 Development board -
3.7.4.1.2 Hardware Information
Information on hardware used by the SPI driver demo application.
Description
The SPI driver demo application can be tried across on hardware boards. This section provide details on the different hardware
boards that are used by the demo application.
3.7.4.1.2.1 Explorer 16 Development Board
Provides information on the Explorer 16 Development Board .
3.7 SPI Driver Demonstrations MPLAB Harmony Help Hardware
3-124
Description
S1 - Reset button (MCLR)
S2 - Processor switch. This switch determines which processor is running, the processor on the board or the processor on the
Plug-In-Module (PIM).
S3, S4, S5, S6 - Application switches. For information about what pin is connected to this switch, please refer to the information
for the PIM in use.
D3 through D10 - Application LEDs. For information about what pin is connected to this LED, please refer to the information for
the PIM in use.
More Information:
Microchip Part Number: DM240001
3.7.4.1.2.2 PIC32MX795F512L Plug-in Module (PIM)
Provides information on the PIC32MX795F512L Plug-In-Module (PIM).
Description
This PIM is required while using the Explorer 16 Development Board.
3.7 SPI Driver Demonstrations MPLAB Harmony Help Hardware
3-125
More Information
Microchip Part Number: MA320003
Information Sheet
3.7.4.2 Configuring the Hardware
Describes how to configure the supported hardware.
Description
serial_eeprom demo
This application is demonstrated using Explorer 16 Development Board. the following hardware configuration should be done
before running this application.
1. Before attaching the PIC32MX795F512L PIM to the Explorer 16 Development Board, ensure that the processor select switch
(S2) is in the PIM Position.
2. Short JP2 on the Explorer 16 Development Board to enable the LEDs.
Complete the previously described hardware configuration setup to to run this demo.
3.7.5 Building the Application
This section describes how to build this demo project.
Description
Once the hardware is configured, you are ready to build this application.
Project Setup :
From MPLAB X IDE, Select "open project" and browse to this demo location. This demo application is available in "/apps/driver/spi/serial_eeprom.X". This directory contains all the application related source files, header files as well as
MPLAB X IDE project related workspace files.
How to build this demo application:
To build this demo in debug mode, Go to "Run" menu in MPLAB X IDE and select "Build Main Project" or select "Build Main
Project" in toolbar. Once the project gets compiled successfully, you can run this demo application.
For more information on how to compile and program projects, refer to the MPLAB X IDE help available through the help menu
in MPLAB X IDE.
Note: The appropriate project configurations should be selected before building the project for the configured hardware.
3.7.5.1 Customizing the Application
This section explains the steps involved in customizing the existing demo application.
Customizing Existing Demo Application:
In this demo application, the SPI driver is operates in interrupt mode. Below are the steps to be followed to customize this
application in polling mode.
3.7 SPI Driver Demonstrations MPLAB Harmony Help Building the Application
3-126
1. Change #define DRV_SPI_INTERRUPT_MODE as false in "system_config.h" file
2. Remove the SPI interrupt source Priority and sub priority set functions calls from "system_init.c" file
3. Remove the SPI ISR routine from "system_int.c" file
4. Call the DRV_SPI_Tasks function in "system_task.c" file
After changing the above configurations, compile the customized application and program the target device.
3.7.5.2 Configuring the Libraries
This section describes the configuration options provided by MPLAB Harmony Libraries used by the application.
#define DRV_SPI_INSTANCES_NUMBER This definition selects the maximum number of hardware instances that can
be supported by the dynamic SPI driver
#define DRV_SPI_CLIENTS_NUMBER This definition selects the maximum number of clients that the SPI driver can
support at run time
#define DRV_SPI_INTERRUPT_MODE This macro controls the operation of the driver in the interrupt mode of
operation
#define DRV_SPI_PORTS_REMAP_USAGE This macro selects the SPI pins remap
#define DRV_SPI_BUFFER_SIZE This macro selects the SPI buffer size
#define
DRV_SPI_FRAME_SYNC_PULSE_DIRECTION
This macro selects the SPI frame sync pulse direction
#define
DRV_SPI_FRAME_SYNC_PULSE_POLARITY
This macro selects the SPI frame sync pulse polarity
#define
DRV_SPI_FRAME_SYNC_PULSE_EDGE
This macro selects the SPI frame sync pulse edge
3.7.5.3 Configuring the Application
This section describes the list of configuration options , build options and how they are configured for this demo application.
Build options:
This application supports only to demonstrate the SPI driver in master mode. This option "spi_master_explorer16" can be
selected from the project properties in MPLAB X IDE or from the configuration drop down in toolbar.
The default target device is selected as "PIC32MX795F512L" with optimization level as "0". The various optimization levels can
be selected from the list to run this demo.
Note: If the target device is changed, then appropriate PIM needs to be used to run this demo application
Configuration options:
All the demo application related configuration options are available in "system_config.h" file. This file is available in the "/apps/driver/spi/src/system_config/" directory based on the configured hardware. This file has the followingconfigurations,
• General System Clock Services
• SPI Driver
Note: Based on the configurations, the demo application behavior will be changed.
3.7 SPI Driver Demonstrations MPLAB Harmony Help Running the Application
3-127
3.7.6 Running the Application
This section demonstrates how to run the SPI driver demo.
Description
This is a simple demo to show how to configure and make use of SPI driver API's to implement and access on board EEPROM
chip in the Explorer 16 Development Board.
How to run this demo application
Once the demo application is compiled successfully, you are ready to program the firmware in the target device.
To run the demo in debug mode, below are the steps to be followed.
1. Select your device programmer from the "hardware tool" in MPLAB X IDE.
2. Select the "Debug Main Project" in "Debug" menu or select the "Debug Main Project" in toolbar.
Once the device is successfully programmed, you can observe LED in the Explorer 16 Development Board will be turned ON.
This shows the demo project has ran successfully and based on the LED "D4" or "D3" the demo application indicates the
PASS/FAIL.
Notes:
If LED "D3" is turned ON, it indicates the EEPROM W/R functionality has failed.
If LED "D4" is turned ON, it indicates the EEPROM W/R functionality has passed.
3.7.7 Files
This section provides a complete list of source files required by the application and describes the purpose of adding each files.
MPLAB Harmony installation follows a standard directory structure for all application solutions. In this directory structure, the
driver, plib, system services related source files, header files for this demo application are available in "/framework/". Below are the list of files added in this demo application.
Files Description
driver.h Driver Library Interface Header
drv_common.h This file defines all common macros and definitions used by the driver
drv_spi.h SPI device driver interface file.
system.h System Service Interface Headers
sys_common.h This file contains system Common definitions and declarations
sys_module.h This file contains system module definitions
system_config.h This is file contains all the system configurations
system_definitions.h This contains system prototypes and definitions
app.h This file contains application related definitions and prototypes
config_performance.c BSP file for Explorer 16 Development Board
drv_spi_dynamic.c This file contains SPI device driver dynamic implementation
3.7 SPI Driver Demonstrations MPLAB Harmony Help Files
3-128
plib_int_pic32.c Interrupt Source implementation for PIC32 devices
sys_clk.c This file contains clock system service implementation
sys_clk_pic32.c This file contains clock system service implementation specific to PIC32 devices
sys_queue.c This file contains system queue services
sys_int_pic32.c This file contains functions related to the Interrupt System Service for PIC32 devices
sys_ports.c This file contains Ports System Service interface implementation.
app.c This file contains application related implementations
main.c This file contains application's main entry point
system_init.c This file contains source code necessary to initialize the system
system_int.c This file contains a definitions of the raw ISRs required to support the interrupt sub-system
system_tasks.c This file will contain any source code necessary to maintain various tasks in the system
3.7 SPI Driver Demonstrations MPLAB Harmony Help Files
3-129
3.8 TCP/IP Demonstrations
3.8.1 Introduction
TCP/IP Web Server Demonstration Applications Help
Description
Note: This information was not available at time of release and will be added in a future release of MPLAB Harmony.
3.8.2 Release Notes
MPLAB Harmony Version: v0.70b TCP/IP Demonstrations Version: 0.01a Release Date: 18Nov2013
The interface can change in the beta and\or 1.0 release.
New This Release:
Nothing to report for this release.
Known Issues:
Nothing to report for this release.
3.8.3 SW License Agreement
(c) 2013 Microchip Technology Inc.
Microchip licenses this software to you solely for use with Microchip products. The software is owned by Microchip and its
licensors, and is protected under applicable copyright laws. All rights reserved.
SOFTWARE IS PROVIDED "AS IS" MICROCHIP EXPRESSLY DISCLAIMS ANY WARRANTY OF ANY KIND, WHETHER
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL MICROCHIP BE LIABLE FOR
ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, HARM TO
YOUR EQUIPMENT, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS
BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR
CONTRIBUTION, OR OTHER SIMILAR COSTS.
To the fullest extent allowed by law, Microchip and its licensors liability shall not exceed the amount of fees, if any, that you have
paid directly to Microchip to use this software.
MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE TERMS.
3.8 TCP/IP Demonstrations MPLAB Harmony Help Demonstrations
3-130
3.8.4 Demonstrations
Description of TCP/IP Stack Library Demonstration Application
Description
This section describes Microchip's TCP/IP Demonstration projects, including information about demonstration-hardware
compatibility and also provides the information about how to configure and run the demonstration.
3.8.4.1 web_server
3.8.4.1.1 pic32_ethernet_starter_kit
This section describes the steps necessary to begin using Microchip's TCP/IP Web server Demonstration Application.
Description
This section describes Microchip's TCP/IP Web Server Demonstration project, including information about
demonstration-hardware compatibility and also provides the information about how to configure and run the demonstration.
3.8.4.1.1.1 Supported Hardware
Lists supported demonstration and development hardware boards.
Description
Demo Board (click link for board information) Notes
PIC32 Ethernet Starter Kit --
PIC32MZ Embedded Connectivity (EC) Starter Kit --
3.8.4.1.1.2 Configuring the Hardware
Describes how to configure the supported hardware.
Description
No hardware related configuration or jumper setting changes are necessary.
3.8.4.1.1.3 Running the Demonstration
Provides instructions on how to build and run the TCP/IP Web Server demonstration.
Description
This demonstration hosts a HTTP server when connected to a network. To view the web page hosted by the demonstration
application open a web browser, type http://mchpboard in the address bar and press the enter key.
Please use the following procedure to run the demonstration:
1. Load demonstration project into MPLAB X IDE.
3.8 TCP/IP Demonstrations MPLAB Harmony Help Demonstrations
3-131
2. Connect the mini-B debugger port on-board the PIC32MZ Embedded Connectivity (EC) Starter Kit or PIC32MZ Ethernet
Starter Kit board to an USB port on the development computer using the USB cable provided in the kit.
3. Connect the RJ-45 Ethernet port on the PIC32MZ Embedded Connectivity (EC) Starter Kit or PIC32MZ Ethernet Starter Kit
board to a network hub or an Ethernet port on the development computer using the Ethernet patch cord provided in the kit.
4. Build, Download, and Run demonstration project on the target board.
5. A HTTP server is hosted by the demonstration application. Open a web browser, type http://mchpboard in the address bar and
press the enter key.
The demonstration application features following:
a) Real-time hardware control and Dynamic Variables - On the Overview page the the LEDs can be clicked to toggle LEDs on
the Ethernet Starter Board. The buttons on Ethernet Starter Board can be pressed to see the Buttons on the webpage toggle.
The dynamic variables can be updated in real time on the HTTP server.
b) Form Processing - Input can be handled from the client by using GET and POST methods.
c) Authentication - Shows an example to restricted access feature commonly used.
d) File Uploads - Shows an example of file upload using POST method. The HTTP server can accept a user defined
MPFS/MPFS2 image file for webpages.
e) Board Configuration - MAC address, host name and IP address of the PIC32 Ethernet starter board can be viewed in the
Network Configuration page and some configuration can be updated.
Note: LED functionality part of the demonstration is not implemented for PIC32MZ devices.
3.8 TCP/IP Demonstrations MPLAB Harmony Help Demonstrations
3-132
3.8.4.1.2 web_server_sdcard_fatfs
This section describes the steps necessary to begin using Microchip's TCP/IP Web server Demonstration Application.
Description
The TCP/IP SDCARD FATFS web server demo (‘apps/tcpip/web_server_sdcard_fatfs/firmware/pic32_ethernet_starter_kit.X’)
exercises the HTTP web server running on PIC32 devices. SDCARD (Secure Digital Card) FATFS (File Allocation Table File
System) web server demo has the web pages stored in external SD CARD and accessed through FATFS API. This demo
currently only works with PIC32MZ using the Multimedia Expansion Board II (MEB II) Setup. PIC32MZ Testing and Fixes in
progress.
3.8.4.1.2.1 Supported Hardware
Lists supported demonstration and development hardware boards.
Description
Demo Board (click link for board information) Notes
PIC32MZ Embedded Connectivity (EC) Starter Kit --
Multimedia Expansion Board II (MEB II) --
3.8.4.1.2.2 Configuring the Hardware
Describes how to configure the supported hardware.
Description
• Plug the PIC32MZ Embedded Connectivity (EC) Starter Kit into application board connector on the MEB II
• Make sure a microSD card is formatted and loaded with the web pages provided under
‘apps/tcpip/web_server_sdcard_fatfs/firmware/src/web_pages2_sdcard’ directory
• Insert the microSD card with the web pages into the microSD card slot (J8) on the MEB II
3.8.4.1.2.3 Running the Demonstration
This section provides instructions on how to build and run the TCP/IP SD CARD FS Web Server demonstration.
Description
To view the web page hosted by the demonstration application open a web browser, type http://mchpboard_e in the address bar
and press the Enter key.
Please use the following procedure to run the demonstration:
1. Load demonstration project into MPLAB X IDE.
2. Connect the mini-B debugger port on-board the PIC32MZ Embedded Connectivity (EC) Starter Kit or PIC32MZ Ethernet
Starter Kit to a USB port on the Development computer using the USB cable provided in the kit.
3. Connect the RJ-45 Ethernet port on the PIC32MZ Embedded Connectivity (EC) Starter Kit or PIC32MZ Ethernet Starter Kit
board to a network hub or an Ethernet port on the development computer using the Ethernet patch cord provided in the kit.
4. Make sure the microSD card with the web pages is inserted into the microSD card slot on the MEB II.
5. Build, Download, and Run demonstration project on the target board.
6. A HTTP server is hosted by the demonstration application. Open a web browser, type http://mchpboard_e in the address bar
and press the Enter key. The demonstration application features following:
3.8 TCP/IP Demonstrations MPLAB Harmony Help Demonstrations
3-133
a. Real-time hardware control and Dynamic Variables - On the Overview page the LEDs can be clicked to toggle LEDs on the
Ethernet Starter Board. The buttons on Ethernet Starter Board can be pressed to see the Buttons on the web page toggle. The
dynamic variables can be updated in real time on the HTTP server.
Note: LED functionality part of the demonstration is somewhat limited due to errata items related to the functional multiplexing on
GPIO and Ethernet pins.
b. Form Processing - Input can be handled from the client by using GET and POST methods.
c. Authentication - Shows an example to restricted access feature commonly used.
d. Cookies – Shows the example of storing small text stings on the client side.
e. File Uploads - Shows an example of file upload using POST method. The HTTP server can accept a user defined
MPFS/MPFS2 image file for web pages.
f. Send E-mail – Shows a simple SMTP POST methods.
g. Dynamic DNS – Exercise Dynamic DNS capabilities.
h. Network Configuration - MAC address, host name and IP address of the PIC32 Ethernet starter board can be viewed in the
Network Configuration page and some configuration can be updated.
3.8.4.1.3 web_server_nvm_mpfs
This section describes the steps necessary to begin using Microchip's TCP/IP Web server Demonstration Application.
3.8 TCP/IP Demonstrations MPLAB Harmony Help Demonstrations
3-134
Description
The TCP/IP NVM MPFS web server demo (‘apps/tcpip/web_server_nvm_mpfs/firmware/pic32_ethernet_starter_kit.X’) exercises
the HTTP web server running on PIC32 devices. The Non-Volatile Memory (NVM) MPFS (Microchip Proprietary File System)
web server demonstration has the web pages stored in internal Flash and accessed through the MPFS API.
3.8.4.1.3.1 Supported Hardware
Lists supported demonstration and development hardware boards.
Description
Demo Board (click link for board information) Notes
PIC32 Ethernet Starter Kit --
PIC32MZ Embedded Connectivity (EC) Starter Kit --
3.8.4.1.3.2 Configuring the Hardware
Describes how to configure the supported hardware.
Description
No hardware related configuration or jumper setting changes are necessary.
3.8.4.1.3.3 Running the Demonstration
This section provides instructions on how to build and run the TCP/IP Web Server demonstration.
Description
To view the web page hosted by the demonstration application open a web browser, type http://mchpboard_e in the address bar
and press the enter key.
Please use the following procedure to run the demonstration:
1. Load demonstration project into MPLAB X IDE.
2. Connect the mini-B debugger port on-board the PIC32MZ Embedded Connectivity (EC) Starter Kit or PIC32MZ Ethernet
Starter KitStarter board to a USB port on the Development computer using the USB cable provided in the kit.
3. Connect the RJ-45 Ethernet port on the PIC32MZ Embedded Connectivity (EC) Starter Kit or PIC32MZ Ethernet Starter Kit
board to a network hub or an Ethernet port on the development computer using the Ethernet patch cord provided in the kit.
4. Build, Download, and Run demonstration project on the target board.
5. A HTTP server is hosted by the demonstration application. Open a web browser, type http://mchpboard_e in the address bar
and press the enter key. The demonstration application features following:
a. Real-time hardware control and Dynamic Variables - On the Overview page the LEDs can be clicked to toggle LEDs on the
Ethernet Starter Board. The buttons on Ethernet Starter Board can be pressed to see the Buttons on the web page toggle. The
dynamic variables can be updated in real time on the HTTP server.
Note: LED functionality part of the demonstration is somewhat limited due to errata items related to the functional multiplexing on
GPIO and Ethernet pins.
b. Form Processing - Input can be handled from the client by using GET and POST methods.
c. Authentication - Shows an example to restricted access feature commonly used.
d. Cookies – Shows the example of storing small text stings on the client side.
3.8 TCP/IP Demonstrations MPLAB Harmony Help Demonstrations
3-135
e. File Uploads - Shows an example of file upload using POST method. The HTTP server can accept a user defined
MPFS/MPFS2 image file for web pages.
f. Send E-mail – Shows a simple SMTP POST methods.
g. Dynamic DNS – Exercise Dynamic DNS capabilities.
h. Network Configuration - MAC address, host name and IP address of the PIC32 Ethernet starter board can be viewed in the
Network Configuration page and some configuration can be updated.
3.8.5 Demonstration Board Information
Information on Hardware used by the TCP/IP Demonstration Applications.
Description
This section provide details on the different hardware boards that are used by the demonstration applications.
3.8.5.1 PIC32 Ethernet Starter Kit
Information on PIC32 Ethernet Starter Kit Hardware.
Description
This board provides a low-cost, modular development system for Microchip’s line of 32-bit Microcontrollers (MCUs)
3.8 TCP/IP Demonstrations MPLAB Harmony Help Demonstration Board Information
3-136
PIC32 Ethernet Starter Kit
More Information
Microchip Part Number: DM320004
Microchip Product Page
3.8.5.2 PIC32MZ Embedded Connectivity (EC) Starter Kit
Information on the PIC32MZ Embedded Connectivity (EC) Starter Kit.
Description
Microchip Part Number: DM320006 (without Crypto) or DM320006-C (with Crypto)
The top assembly of the board includes these key features, as indicated in Figure 1:
1. PIC32MZ2048ECH144 32-bit microcontroller.
2. Green power indicator LED.
3. On-board crystal or oscillator for precision microcontroller clocking (12 MHz).
4. USB connectivity for on-board debugger communications.
5. Green debug indicator LED.
6. Three push button switches for user-defined inputs.
7. Three user-defined indicator LEDs.
8. USB Type A receptacle connectivity for PIC32 host-based applications.
9. HOST mode power jumper.
10. Daughter board connectors for flexible Ethernet PHY options.
11. 32 kHz oscillator for RTCC and Timer1 (optional).
12. External 2 GB SQI memory for expanded memory application.
13. Jumper for using or disconnecting the on-board debugger.
NOTE: When running self-powered USB device applications, open the jumper JP1 to prevent possibly back-feeding voltage onto
the Vbus from one port on the host to another (or from one host to another).
3.8 TCP/IP Demonstrations MPLAB Harmony Help Demonstration Board Information
3-137
Figure 1: PIC32MZ Embedded Connectivity (EC) Starter Kit Layout (Front)
The bottom assembly of the board includes these key features, as indicated in Figure 2:
1. PIC24FJ256GB106 USB microcontroller for on-board debugging.
2. Regulated +3.3V power supply for powering the starter kit via USB or expansion board.
3. Connector for various expansion boards.
4. USB Type micro-AB receptacle for OTG and USB device connectivity for PIC32 OTG/device-based applications.
5. 50 MHz Ethernet PHY oscillator.
6. USB Host and OTG power supply for powering PIC32 USB applications.
Figure 2: PIC32MZ Embedded Connectivity (EC) Starter Kit Layout (Back)
3.8 TCP/IP Demonstrations MPLAB Harmony Help Demonstration Board Information
3-138
Microchip Part Number: DM320006 (without Crypto) or DM320006-C (with Crypto)
The top assembly of the board includes these key features, as indicated in Figure 1:
1. PIC32MZ2048ECH144 32-bit microcontroller.
2. Green power indicator LED.
3. On-board crystal or oscillator for precision microcontroller clocking (12 MHz).
4. USB connectivity for on-board debugger communications.
5. Green debug indicator LED.
6. Three push button switches for user-defined inputs.
7. Three user-defined indicator LEDs.
8. USB Type A receptacle connectivity for PIC32 host-based applications.
9. HOST mode power jumper.
10. Daughter board connectors for flexible Ethernet PHY options.
11. 32 kHz oscillator for RTCC and Timer1 (optional).
12. External 2 GB SQI memory for expanded memory application.
13. Jumper for using or disconnecting the on-board debugger.
NOTE: When running self-powered USB device applications, open the jumper JP1 to prevent possibly back-feeding voltage onto
the Vbus from one port on the host to another (or from one host to another).
Figure 1: PIC32MZ Embedded Connectivity (EC) Starter Kit Layout (Front)
The bottom assembly of the board includes these key features, as indicated in Figure 2:
1. PIC24FJ256GB106 USB microcontroller for on-board debugging.
2. Regulated +3.3V power supply for powering the starter kit via USB or expansion board.
3. Connector for various expansion boards.
4. USB Type micro-AB receptacle for OTG and USB device connectivity for PIC32 OTG/device-based applications.
5. 50 MHz Ethernet PHY oscillator.
3.8 TCP/IP Demonstrations MPLAB Harmony Help Demonstration Board Information
3-139
6. USB Host and OTG power supply for powering PIC32 USB applications.
Figure 2: PIC32MZ Embedded Connectivity (EC) Starter Kit Layout (Back)
3.8.5.3 Multimedia Expansion Board II (MEB II)
Provides details information on the Multimedia Expansion Board II (MEB) II.
Description
Microchip Part Number: DM320005-2
Product Page
The front side of the MEB II includes these key features, as shown in Figure 1:
1. Display daughter board connector (60-pin Hirose board-to-board connector).
2. mTouch™ buttons.
3. Push Button.
4. Power LED.
5. User LEDs.
6. VGA Camera (OVM7690).
7. PICtail™ Connector.
8. Analog temperature sensor.
3.8 TCP/IP Demonstrations MPLAB Harmony Help Demonstration Board Information
3-140
Figure 1: Multimedia Expansion Board II Layout (Front)
The underside of the MEB II includes these key features, as shown in Figure 2:
1. Regulated 5V and 3.3V power supply for powering the board via a 9-15V DC Adapter.
2. PIC32 Starter Kit connector (168-pin Hirose board-to-board connector).
3. 24-bit stereo audio codec (AK4953A).
4. Integrated 802.11bg wireless module (MRF24WG0MA).
5. Low-cost Bluetooth® HCI transceiver (BTM805).
6. EBI SRAM memory (IS61WV102416BLL).
7. microSD slot.
8. Analog accelerometer (ADXL325).
Figure 2: Multimedia Expansion Board II Layout (Back)
3.8 TCP/IP Demonstrations MPLAB Harmony Help Demonstration Board Information
3-141
3.9 USART Driver Demonstration
3.9.1 Introduction
This help manual contains instructions and information about MPLAB Harmony USART driver demo application, which are
contained in the MPLAB Harmony Library distribution.
Description
This application demonstrates how to use the MPLAB Harmony USART driver. This help manual describes the hardware
requirement and procedures to build and execute the demo project on Microchip development tools. In this demo application,
USART driver will initially transmit strings of data and then accept and characters received and transmit the data back. Error or
success status is indicated by LED display.
To know more about MPLAB Harmony USART driver, configuring the USART driver and API's provided by the USART driver,
refer to USART Driver Library documentation.
3.9.2 Release Notes
MPLAB Harmony Version: v0.70b USART Driver Demonstration: 0.01a Release Date: 18Nov2013
New This Release:
This is the first release of this USART driver demo application. This demo has been developed to support PIC32MX devices only.
Known Issues:
• Changes in USART driver interfaces will have impact on this demo application as well in subsequent releases
• This demo is has not been developed to run on PIC32MZ devices. Users must add a new configuration if intended to run on
PIC32MZ devices.
3.9.3 SW License Agreement
(c) 2013 Microchip Technology Inc.
Microchip licenses this software to you solely for use with Microchip products. The software is owned by Microchip and its
licensors, and is protected under applicable copyright laws. All rights reserved.
SOFTWARE IS PROVIDED "AS IS" MICROCHIP EXPRESSLY DISCLAIMS ANY WARRANTY OF ANY KIND, WHETHER
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL MICROCHIP BE LIABLE FOR
ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, HARM TO
YOUR EQUIPMENT, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS
3.9 USART Driver Demonstration MPLAB Harmony Help SW License Agreement
3-142
BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR
CONTRIBUTION, OR OTHER SIMILAR COSTS.
To the fullest extent allowed by law, Microchip and its licensors liability shall not exceed the amount of fees, if any, that you have
paid directly to Microchip to use this software.
MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE TERMS.
3.9.4 Hardware
This section describes how to select and use an appropriate development board and steps to configure the hardware to run this
USART driver demo.
3.9.4.1 Required Hardware
This section describes the overview of required device family and supported demonstration boards to run this USART driver
demo application.
Description
This section describes the hardware required to execute the Harmony USART driver demo application.
3.9.4.1.1 Supported Demonstration Boards
Lists supported demonstration and hardware development boards.
Description
Demonstration Board Notes
Explorer 16 Development Board -
3.9.4.1.2 Hardware Information
Information on hardware used by the USART driver demo application.
Description
The USART driver demo application can be tried across on hardware boards. This section provide details on the different
hardware boards that are used by the demo application.
3.9.4.1.2.1 Explorer 16 Development Board
Provides information on the Explorer 16 Development Board .
3.9 USART Driver Demonstration MPLAB Harmony Help Hardware
3-143
Description
S1 - Reset button (MCLR)
S2 - Processor switch. This switch determines which processor is running, the processor on the board or the processor on the
Plug-In-Module (PIM).
S3, S4, S5, S6 - Application switches. For information about what pin is connected to this switch, please refer to the information
for the PIM in use.
D3 through D10 - Application LEDs. For information about what pin is connected to this LED, please refer to the information for
the PIM in use.
More Information:
Microchip Part Number: DM240001
3.9.4.1.2.2 PIC32MX795F512L Plug-in Module (PIM)
Provides information on the PIC32MX795F512L Plug-In-Module (PIM).
Description
This PIM is required while using the Explorer 16 Development Board.
3.9 USART Driver Demonstration MPLAB Harmony Help Hardware
3-144
More Information
Microchip Part Number: MA320003
Information Sheet
3.9.4.2 Configuring the Hardware
This section describes how to configure the supported hardware.
Description
Explorer 16 Development Board
Below are the hardware hardware configuration settings required to execute this demo
1. Before attaching the PIC32MX795F512L PIM to the Explorer 16 Deveolpment Board, ensure that the processor select switch
(S2) is in the PIM Position.
2. Short JP2 on the Explorer 16 Development Board to enable the LEDs.
3.9.5 Building the Application
This section describes how to build this demo project.
3.9 USART Driver Demonstration MPLAB Harmony Help Building the Application
3-145
Description
Once the hardware is configured, you are ready to build this application.
Project Setup:
From MPLAB X IDE, Select "open project" and browse to this demo project location. This demo application is available in
"/apps/driver/usart/usart_echo/firmware/usart_echo.X". This directory contains all the application related source
files, header files as well as MPLAB X IDE project related workspace files.
How to build this demo application:
To build this demo in debug mode, Go to "Run" menu in MPLAB X IDE and select "Build Main Project" or select "Build Main
Project" in toolbar. Once the project gets compiled successfully, you can run this demo application.
For more information on how to compile and program projects, refer to the MPLAB X IDE help available through the help menu
in MPLAB X IDE.
Note: The appropriate project configurations should be selected before building the project for the configured hardware.
3.9.5.1 Configuring the Application
This section describes the list of configuration options , build options and how they are configured for this demo application.
Build options:
The default target device is selected as "PIC32MX795F512L" with optimization level as "0". The various optimization levels can
be selected from the list to run this demo.
Note: If the target device is changed, then appropriate PIM needs to be used to run this demo application
Configuration options:
All the demo application related configuration options are available in "system_config.h" file. This file is available in the "apps/driver/usart/usart_echo/firmware/src/system_config/pic32mx_default" directory based on the configured hardware.
Note: Based on the configurations, the demo application behavior will be changed.
3.9.5.2 Configuring the Libraries
This section describes the configuration options provided by MPLAB Harmony Libraries used by the application. The below
parameters are defined in "system_config.h" header file.
Parameter Name Description
#define
DRV_USART_INSTANCES_NUMBER
This macro defines the maximum number of hardware instances that will be used
by the application. The USART driver will support a maximum of that many
hardware instances.
#define
DRV_USART_CLIENTS_NUMBER
This macro defines the maximum number of clients that will be used by the
application. The USART driver will support a maximum of that many clients.
#define
DRV_USART_INTERRUPT_MODE
If this macro is set to "true", the application will run in interrupt mode. If this macro
is set to "false", the application will run in polling mode
#define
DRV_USART_INTERRUPT_SOURCE_TX
This macro defines the transmit interrupt source
#define
DRV_USART_INTERRUPT_SOURCE_RX
This macro defines the receive interrupt source
3.9 USART Driver Demonstration MPLAB Harmony Help Building the Application
3-146
#define SYS_USART_ID This macro defines the USART module number used in the appilcation
#define
DRV_USART_XFER_BUFFER_NUMBER
This macro defines the number of transfer buffers used in the application
#define APP_UART_BAUDRATE This macro defines the baud rate to be used
3.9.5.3 Customizing the Application
This section explains the steps involved in customizing the existing demo application.
Customizing Existing Demo Application:
Changing the USART module
In system_config.h header file, modify the SYS_USART_ID macro to change the USART module number.
Changing the demo to interrupt mode
By default, the USART demo application will run in polling mode. Below are the steps to be followed to run the demo in interrupt
mode.
1. Change #define DRV_USART_INTERRUPT_MODE to true in "system_config.h" file
2. Remove the DRV_USART_Tasks function call in sys_tasks in "system_task.c" file
3. Call the DRV_USART_Tasks function in ISR in "system_int.c" file
Changing USART settings
To change the USART related parameters such as baud rate, parity settings, number of stop bits, etc., select appropriate values
in drvUSARTInit structure in system_init.c file
After changing the above configurations, compile the customized application and program the target device.
3.9.6 Running the Application
This section demonstrates how to run the USART driver demo.
Description
Once the demo application has been compiled successfully for the intended configuration, program the firmware into the target
device.
Upon execution, the application will transmit the following strings through USART with settings as defined in the application.
/****************************************************
Welcome to Microchip USART Echo Demo App.
Press any character. Data will be echoed back.
Press 'ESC' key to exit the application
/****************************************************
After transmitting the above text, the firmware will read any characters received through USART and it will transmit back the
same data. If the received character is "ESC" (0x1B), the program will enetr into idle mode. Once in Idle mode, the firmware will
neither transmit nor receive any data. If the application enters Idle mode, LED 5 of the Explorer 16 Development Board will
3.9 USART Driver Demonstration MPLAB Harmony Help Running the Application
3-147
illuminate. If any error occurs, LED 9 of the Explorer 16 Development Board will illuminate.
3.9.7 Files
This section provides a complete list of source and header files used by the application and describes the purpose of adding
each files.
MPLAB Harmony installation follows a standard directory structure for all application solutions. In this directory structure, the
driver, plib, system services related source files, header files for this demo application are available in "/framework/". Below are the list of files added in this demo application.
Files Description
driver.h Driver Library Interface Header
drv_common.h This file defines all common macros and definitions used by the driver
drv_usart.h USART device driver interface file.
system.h System Service Interface Headers
sys_common.h This file contains system Common definitions and declarations
sys_module.h This file contains system module definitions
system_config.h This is file contains all the system configurations
system_definitions.h This contains system prototypes and definitions
app.h This file contains application related definitions and prototypes
config_performance.c BSP file for the Explorer 16 Development Board
drv_usart_dynamic.c This file contains USART device driver dynamic implementation
plib_int_pic32.c Interrupt Source implementation for PIC32 devices
sys_clk.c This file contains clock system service implementation
sys_clk_pic32.c This file contains clock system service implementation specific to PIC32 devices
sys_queue.c This file contains system queue services
sys_int_pic32.c This file contains functions related to the Interrupt System Service for PIC32 devices
sys_ports.c This file contains Ports System Service interface implementation.
app.c This file contains application related implementations
main.c This file contains application's main entry point
system_init.c This file contains source code necessary to initialize the system
system_int.c This file contains a definitions of the raw ISRs required to support the interrupt sub-system
system_tasks.c This file will contain any source code necessary to maintain various tasks in the system
3.9 USART Driver Demonstration MPLAB Harmony Help Files
3-148
3.10 USB Demonstrations
3.10.1 USB Demonstrations
3.10.1.1 Introduction
USB Library Demonstration Applications Help
Description
This distribution package contains a variety of USB-related firmware projects that demonstrate the capabilities of the MPLAB
Harmony USB stack. This help file describes the hardware requirement and procedures to run these firmware projects on
Microchip demonstration and development boards.
To know more about MPLAB Harmony USB stack and configuring the USB stack and the APIs provided by the USB stack, refer
to the USB Library documentation.
3.10.1.2 Release Notes
MPLAB Harmony Version: v0.70b USB Demonstration: 0.01a Release Date: 18Nov2013
New This Release:
Nothing to report in this release.
Known Issues:
Device Stack Demonstration Applications:
All Device Stack Demonstration applications uses a custom Board Support Package (BSP) to access demonstration board
switches and LEDs. The board support package does not use PORTS Peripheral Library. In the next release, all Device Stack
Demonstration Applications will be updated to use the standard Harmony BSP. The demonstration application specific issues are
listed here:
cdc_com_port_single:
Nothing to report in this release.
cdc_com_port_dual:
Nothing to report in this release.
cdc_serial emulator:
• This version of the demo does not support baud rate change. The supported baud rate is 9600bps, 1 stop bit and no parity.
3.10 USB Demonstrations MPLAB Harmony Help USB Demonstrations
3-149
• The application code accesses the UART2 peripheral SFR directly. This will be updated in the next release to use the USART
driver and the System Clock Service.
hid_basic:
Nothing to report in this release.
hid_keyboard:
Nothing to report in this release.
hid_joystick:
Nothing to report in this release.
hid_mouse:
Nothing to report in this release.
audio_speaker:
While running the pic32mz_sk_meb2_int_dyn configuration, a periodic glitch is heard in the output audio. This is a known issue
and will be fixed in the next release of the stack.
Host Stack Demonstration Applications:
All Host Stack Demonstration applications uses a custom Board Support Package (BSP) to access demonstration board
switches and LEDs. The board support package does not use PORTS Peripheral Library. In the next release, all Host Stack
Demonstration Applications will be updated to use the standard Harmony BSP.
cdc_basic:
This demo is not tested for the pic32mx_usb_sk_int_dyn configuration and may not function when built for this configuration.
msd_basic:
While running this demo, if the USB Flash drive already contains a file named “File.txt”, the file contents may become corrupted.
3.10.1.3 SW License Agreement
(c) 2013 Microchip Technology Inc.
Microchip licenses this software to you solely for use with Microchip products. The software is owned by Microchip and its
licensors, and is protected under applicable copyright laws. All rights reserved.
SOFTWARE IS PROVIDED "AS IS" MICROCHIP EXPRESSLY DISCLAIMS ANY WARRANTY OF ANY KIND, WHETHER
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL MICROCHIP BE LIABLE FOR
ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, HARM TO
YOUR EQUIPMENT, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS
BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR
CONTRIBUTION, OR OTHER SIMILAR COSTS.
To the fullest extent allowed by law, Microchip and its licensors liability shall not exceed the amount of fees, if any, that you have
paid directly to Microchip to use this software.
MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE TERMS.
3.10 USB Demonstrations MPLAB Harmony Help USB Demonstrations
3-150
3.10.1.4 Demonstration Application Configurations
This topic provides information on the USB demonstration project configuration that are available in MPLAB Harmony.
Description
The available USB Demonstration application MPLAB X IDE projects feature support for multiple configurations. Selecting these
configurations allow for the demonstration projects to run across different PIC32 microcontrollers and development boards. The
following project configurations are available:
• pic32mx_usb_sk_int_dyn – Selecting this configuration will set up the demonstration application to run on the PIC32 USB
Starter Kit II development board, with the PIC32MX795F512L microcontroller. The system will be configured for interrupt
mode operation and drivers will be configured for dynamic operation mode.
• pic32mz_sk_int_dyn – Selecting this configuration will set up the demonstration application to run on the PIC32MZ
Embedded Connectivity (EC) Starter Kit development board, with the PIC32MZ2048ECH144 microcontroller. The system will
be configured for interrupt mode operation and drivers will be configured for dynamic operation mode.
• explorer16_pic32mx795f512l_int_dyn – Selecting this configuration will set up the demonstration application to run on the
Explorer 16 Development Board along with the PIC32MX795F512L microcontroller Plug In Module . The system will be
configured for interrupt mode operation and drivers will be configured for dynamic operation mode.
• pic32mx_usb_audio_int_dyn - Selecting this configuration will set up the demonstration application to run on PIC32 USB
Digital Audio Accessory Board along with the PIC32MX250F128B microcontroller. The system will be configured for interrupt
mode operation and drivers will be configured for dynamic operation mode.
• pic32mz_sk_meb2_int_dyn – Selecting this configuration will set up the demonstration application to run on the PIC32MZ
EC Starter Kit development board, with the PIC32MZ2048ECH144 microcontroller board attached to the Multimedia
Expansion Board II (MEB II). The system will be configured for interrupt mode operation and drivers will be configured for
dynamic operation mode.
The following figure shows how a configuration can be selected in MPLAB X IDE.
Alternatively, the active configuration can be selected in the Project Properties dialog box. The following table shows the
availability of a configuration across available USB device demonstration applications. Green indicates support. Red indicates no
support.
3.10 USB Demonstrations MPLAB Harmony Help USB Demonstrations
3-151
The following table shows the availability of a configuration across available USB device demonstration applications. Green
indicates support. Red indicates no support.
3.10.1.5 Demonstrations
Description of USB Demonstrations
Description
The USB Demonstrations are grouped into USB Device Stack and USB Host Stack Demonstrations.
3.10.1.5.1 Device
3.10.1.5.1.1 cdc_com_port_single
Demonstrates a USB CDC device, emulating a serial COM port.
3.10 USB Demonstrations MPLAB Harmony Help USB Demonstrations
3-152
Description
This demonstration application creates a USB CDC Device that enumerates as a single COM port on the host PC. The
application demonstrates two-way communication between the USB device and the PC host.
3.10.1.5.1.1.1 Supported Demonstration Boards
Lists supported demonstration and development hardware boards.
Description
Demonstration Board (click link for board information) Notes
PIC32 USB Starter Kit II -
PIC32MZ Embedded Connectivity (EC) Starter Kit -
3.10.1.5.1.1.2 Configuring the Hardware
Describes how to configure the supported hardware.
Description
PIC32 USB Starter Kit II
No hardware related configuration or jumper setting changes are necessary.
PIC32MZ Embedded Connectivity (EC) Starter Kit
No hardware related configuration or jumper setting changes are necessary.
3.10.1.5.1.1.3 Running the Demonstration
Provides instructions on how to build and run the CDC single COM port demonstration.
Description
This demonstration allows the device to appear like a serial (COM) port to the host. In order to run this demonstration first
compile and program the target device. While compiling, select the pic32mx_usb_sk_xxx_xxx configurations for the PIC32M
USB Starter Kit II or select the pic32mz_sk_xxx_xxx configurations for PIC32MZ Embedded Connectivity (EC) Starter Kit. Attach
the device to the host. If the host is a PC and this is the first time you have plugged this device into the computer then you may
be asked for a .inf file.
3.10 USB Demonstrations MPLAB Harmony Help USB Demonstrations
3-153
Select the “Install from a list or specific location (Advanced)” option. Point to the “/apps/usb/device/cdc_com_port_single/inf” directory.
Once the device is successfully installed, open up a terminal program, such as HyperTerminal. Select the appropriate COM port.
On most machines this will be COM5 or higher.
Once connected to the device, there are two ways to run this example project. Typing a key in the terminal window will result in
the device echoing the key pressed. So if the user presses “b”, the device will echo “c”. If the pushbutton SW1 is pressed the
device will echo "PUSH BUTTON PRESSED" to the terminal window.
Note: Some terminal programs, like HyperTerminal, require users to click the disconnect button before removing the device from
the computer. Failing to do so may result in having to close and open the program again in order to reconnect to the device.
3.10.1.5.1.2 cdc_com_port_dual
Demonstrates a USB CDC device, emulating dual serial COM ports - one looping back into the other.
Description
This demonstration application creates a USB CDC Device that enumerates as 2 serial ports on USB Host PC. This application
demonstrates the ability of the MPLAB Harmony USB stack to support multiple instances of the same device class.
3.10.1.5.1.2.1 Supported Demonstration Boards
Lists supported demonstration and development hardware boards.
Description
Demonstration Board (click link for board information) Notes
PIC32 USB Starter Kit II -
PIC32MZ Embedded Connectivity (EC) Starter Kit -
3.10.1.5.1.2.2 Configuring the Hardware
Describes how to configure the supported hardware.
Description
PIC32 USB Starter Kit II
3.10 USB Demonstrations MPLAB Harmony Help USB Demonstrations
3-154
No hardware related configuration or jumper setting changes are necessary.
PIC32MZ Embedded Connectivity (EC) Starter Kit
No hardware related configuration or jumper setting changes are necessary.
3.10.1.5.1.2.3 Running the Demonstration
Provides instructions on how to build and run the CDC dual COM port demonstration.
Description
This demonstration allows the device to appear like dual serial (COM) ports to the host. In order to run this demonstration first
compile and program the target device. While compiling, select the pic32mx_usb_sk_xxx_xxx configurations for the PIC32 USB
Starter Kit II or select the pic32mz_sk_xxx_xxx configurations for PIC32MZ Embedded Connectivity (EC) Starter Kit. Attach the
device to the host. If the host is a PC and this is the first time you have plugged this device into the computer then you may be
asked for a .inf file.
Select the “Install from a list or specific location (Advanced)” option. Point to the “/apps/usb/device/cdc_com_port_dual/inf” directory.
Once the device is successfully installed, open up two instances of a terminal program, such as HyperTerminal. Select the
appropriate COM port for each of these terminal instance.
3.10 USB Demonstrations MPLAB Harmony Help USB Demonstrations
3-155
To run the demonstration, type a character or string in one terminal window. The same character or string appears on the
second terminal window. Similarly, any character typed on second window appears on the first window.
Note: Some terminal programs, like HyperTerminal, require users to click the disconnect button before removing the device from
the computer. Failing to do so may result in having to close and open the program again in order to reconnect to the device.
3.10.1.5.1.3 cdc_serial_emulator
This application demonstrates the use of the CDC device class in implementing a USB-to-Serial Dongle.
Description
This application demonstrates the use of the CDC device class in implementing a USB-to-Serial Dongle. The application
enumerates a COM port on the PC. Data received through the CDC USB interface is forwarded to a UART. Data received on the
UART is forwarded to the CDC USB interface. This emulates a USB-to-Serial Dongle.
3.10.1.5.1.3.1 Supported Demonstration Boards
Lists supported demonstration and development hardware boards.
Description
Demonstration Board (click link for board information) Notes
PIC32 USB PIC32MX795F512L Plug-In Module (PIM) 1
Any commercially available USB-to-Serial dongle -
Note 1: This board cannot be used by itself. It requires an Explorer 16 Development Board (DM240001) and a USB PICtail Plus
Daughter Board (AC164131) in order to operate.
3.10.1.5.1.3.2 Configuring the Hardware
Describes how to configure the supported hardware.
Description
Explorer 16 Development Board Based Demonstrations
For all of the Explorer 16-based demonstration boards, please follow the following instructions:
1. Connect the USB PICtail Plus Daughter Board to the Explorer 16 Development Board.
2. Short JP2 and JP3 on the USB PICtail Plus Daughter Board
3. Open JP1 and JP4 on the USB PICtail Plus Daughter Board
4. Make sure that S2 on the Explorer 16 Development Board is switched to the "PIM" setting.
5. Short JP2 on the Explorer 16 Development Board to enable the LEDs.
6. Follow any processor specific instructions below. All instructions apply to the PIM unless otherwise stated:
PIC32MX795F512L PIM
7. Open J10.
8. Short pins 1 (marked "USB") and pin 2 (center) of jumpers J1 and J2.
3.10.1.5.1.3.3 Running the Demonstration
Provides instructions on how to build and run the CDC Serial Emulator Demonstration. Please refer to Release Notes for
demonstration limitations, if any.
3.10 USB Demonstrations MPLAB Harmony Help USB Demonstrations
3-156
Description
This application demonstrates the use of the CDC device class in implementing a USB to Serial Dongle. The application
enumerates a COM port on the PC. Data received through the CDC USB interface is forwarded to a UART. Data received on the
UART is forwarded to the CDC USB interface. This emulates a USB-to-Serial Dongle.
1. Open the project in MPLAB X IDE. Make sure that exp16_pic32mx795f512l_int_dyn configuration is selected.
2. Build the code and program the device.
3. Connect the USB PICtail Plus Daughter Board to the Explorer 16 Development Board.
4. Power up the Explorer 16 Development Board and connect a debugger/programmer of your choice to the Explorer 16
Development Board.
5. Build the code and program the device.
6. Connect the mini-B device connector on the USB PICtail Plus Daughter Board to the PC. If the host is a PC and this is the first
time you have plugged this device into the computer, you may be asked for a .inf file.
7. Select the “Install from a list or specific location (Advanced)” option. Point to the “/apps/usb/device/cdc_serial_emulator/inf” directory.
3.10 USB Demonstrations MPLAB Harmony Help USB Demonstrations
3-157
When enumerated successfully, LED D5 will be the only LED illuminated on the Explorer 16 Development board.
8. Open a terminal emulation program of your choice and select the enumerated USB COM port.
9. Connect the USB-to-Serial Dongle to the same PC.
10. Open another instance of the terminal emulation program and select the USB-to-Serial Dongle.
11. Connect the serial connector of the USB-to-Serial Dongle to the UART connector (P1) on the Explorer 16 Development
Board.
12. Choose a baud rate of 9600, 1 stop bit and no parity while opening both of the terminal emulation programs.
The setup should be similar to the following diagram.
Any text entered into the terminal 1 program will be echoed on terminal 2 and vice versa.
3.10.1.5.1.4 hid_basic
This demonstration application creates a custom HID device that can be controlled by a PC based utility.
Description
This application creates a custom HID device that can be controlled by a PC based utility. The device allows the USB Host utility
to control the LEDs on the board and query the status of a switch.
3.10.1.5.1.4.1 Supported Demonstration Boards
Lists supported demonstration and development hardware boards.
Description
Demonstration Board (click link for board information) Notes
PIC32 USB Starter Kit II -
PIC32MZ Embedded Connectivity (EC) Starter Kit -
3.10.1.5.1.4.2 Configuring the Hardware
Describes how to configure the supported hardware.
Description
PIC32 USB Starter Kit II
No hardware related configuration or jumper setting changes are necessary.
3.10 USB Demonstrations MPLAB Harmony Help USB Demonstrations
3-158
PIC32MZ Embedded Connectivity (EC) Starter Kit
No hardware related configuration or jumper setting changes are necessary.
3.10.1.5.1.4.3 Running the Demonstration
Provides instructions on how to build and run the HID Basic demonstration.
Description
This demonstration uses the selected hardware platform as a HID class USB device, but uses the HID class for general purpose
I/O operations. While compiling, select the pic32mx_usb_sk_xxx_xxx configurations for the PIC32 USB Starter Kit II or select the
pic32mz_sk_xxx_xxx configurations for PIC32MZ Embedded Connectivity (EC) Starter Kit. Typically, the HID class is used to
implement human interface products, such as mice and keyboards. The HID protocol is however quite flexible, and can be
adapted and used to send/receive general purpose data to/from a USB device. Using the HID class for general purpose I/O
operations is quite advantageous, in that it does not require any kind of custom driver installation process. HID class drivers are
already provided by and are distributed with common operating systems. Therefore, upon plugging in a HID class device into a
typical computer system, no user installation of drivers is required, the installation is fully automatic.
HID devices primarily communicate through one interrupt IN endpoint and one interrupt OUT endpoint. In most applications, this
effectively limits the maximum achievable bandwidth for full speed HID devices to 64 kBytes/s of IN traffic, and 64 kBytes/s of
OUT traffic (64 kB/s, but effectively “full duplex”).
The GenericHIDSimpleDemo.exe program, and the associated firmware demonstrate how to use the HID protocol for basic
general purpose USB data transfer.
Before you can run the GenericHIDSimpleDemo.exe executable, you will need to have the Microsoft® .NET Framework Version
2.0 Redistributable Package (later versions probably okay, but not tested) installed on your computer. Programs which were built
in the Visual Studio® .NET languages require the .NET redistributable package in order to run. The redistributable package can
be freely downloaded from Microsoft’s website. Users of Windows Vista® operating systems will not need to install the .NET
framework, as it comes pre-installed as part of the operating system.
To launch the application, simply double click on the executable “GenericHIDSimpleDemo.exe” in the “\apps\usb\device\hid_basic\bin” directory. A window like that shown below should appear:
If instead of this window, an error message pops up while trying to launch the application, it is likely the Microsoft .NET
Framework Version 2.0 Redistributable Package has not yet been installed. Please install it and try again.
In order to begin sending/receiving packets to the device, you must first find and “connect” to the device. As configured by
default, the application is looking for HID class USB devices with VID = 0x04D8 and PID = 0x003F. The device descriptor in the
firmware project meant to be used with this demonstration uses the same VID/PID. If you plug in a USB device programmed with
the correct pre-compiled .hex file, and hit the “Connect” button, the other push buttons should become enabled. If hitting the
connect button has no effect, it is likely the USB device is either not connected, or has not been programmed with the correct
firmware.
Hitting the Toggle LED(s) should send a single packet of general purpose generic data to the HID class USB peripheral device.
The data will arrive on the interrupt OUT endpoint. The firmware has been configured to receive this generic data packet, parse
the packet looking for the “Toggle LED(s)” command, and should respond appropriately by controlling the LED(s) on the
demonstration board.
3.10 USB Demonstrations MPLAB Harmony Help USB Demonstrations
3-159
The “Get Pushbutton State” button will send one packet of data over the USB to the peripheral device (to the interrupt OUT
endpoint) requesting the current pushbutton state. The firmware will process the received Get Pushbutton State command, and
will prepare an appropriate response packet depending upon the pushbutton state.
Following table shows the button that has to be pressed on the demonstration board to see the push button state changing.
Demonstration Board Button
PIC32 USB Starter Kit II SW1
3.10.1.5.1.5 hid_mouse
Demonstrates a USB HID device, emulating a mouse pointing device.
Description
This demonstration application creates a USB HID based 2 button mouse device. When connected, the device emulates mouse
operation by moving the cursor in a circular pattern.
3.10.1.5.1.5.1 Supported Demonstration Boards
Lists supported demonstration and development hardware boards.
Description
Demonstration Board (click link for board information) Notes
PIC32 USB Starter Kit II -
PIC32MZ Embedded Connectivity (EC) Starter Kit -
3.10.1.5.1.5.2 Configuring the Hardware
Describes how to configure the supported hardware.
Description
PIC32 USB Starter Kit II
No hardware related configuration or jumper setting changes are necessary.
PIC32MZ Embedded Connectivity (EC) Starter Kit
No hardware related configuration or jumper setting changes are necessary.
3.10.1.5.1.5.3 Running the Demonstration
Provides instructions on how to build and run the HID Mouse Demonstration.
Description
This demonstration uses the selected hardware platform as a USB mouse. While compiling, select the pic32mx_usb_sk_xxx_xxx
configurations for the PIC32 USB Starter Kit II or select the pic32mz_sk_xxx_xxx configurations for PIC32MZ Embedded
Connectivity (EC) Starter Kit. Before connecting the board to the computer through the USB cable please be aware that the
device will start moving the mouse cursor around on the computer. There are two ways to stop the device from making the
cursor to continue to move. The first way is to disconnect the device from the computer. The second is to press the correct
button on the hardware platform. Pressing the button again will cause the mouse cursor to start moving in a circle again.
Following table shows the button that has to be pressed on the demonstration board to stop the circular motion:
3.10 USB Demonstrations MPLAB Harmony Help USB Demonstrations
3-160
Demonstration Board Button
PIC32 USB Starter Kit II SW1
3.10.1.5.1.6 hid_keyboard
Demonstrates a USB HID device, emulating a keyboard.
Description
This demonstration application creates a Generic HID keyboard. Pressing a key on the board emulates a keyboard key press.
3.10.1.5.1.6.1 Supported Demonstration Boards
Lists supported demonstration and development hardware boards.
Description
Demonstration Board (click link for board information) Notes
PIC32 USB Starter Kit II -
PIC32MZ Embedded Connectivity (EC) Starter Kit -
3.10.1.5.1.6.2 Configuring the Hardware
Describes how to configure the supported hardware.
Description
PIC32 USB Starter Kit II
No hardware related configuration or jumper setting changes are necessary.
PIC32MZ Embedded Connectivity (EC) Starter Kit
No hardware related configuration or jumper setting changes are necessary.
3.10.1.5.1.6.3 Running the Demonstration
Provides instructions on how to build and run the USB HID Keyboard demonstration.
Description
This demonstration uses the selected hardware platform as a USB keyboard. While compiling, select the
pic32mx_usb_sk_xxx_xxx configurations for the PIC32 USB Starter Kit II or select the pic32mz_sk_xxx_xxx configurations for
PIC32MZ Embedded Connectivity (EC) Starter Kit. Before pressing the button, select a window in which it is safe to type text
freely. Pressing the button on the demonstration board will cause the device to print a character on the screen.
Following table shows the button that has to be pressed on the demonstration board to print a character.
Demonstration Board Button
PIC32 USB Starter Kit II SW1
3.10.1.5.1.7 hid_joystick
Demonstrates a USB HID device emulating a joystick.
3.10 USB Demonstrations MPLAB Harmony Help USB Demonstrations
3-161
Description
This demonstration application creates a custom HID joystick. This application is only intended to demonstrate creation of
Joystick HID Report descriptors and may not be a definite end solution. The end application requirements may need the report
descriptor to be modified.
3.10.1.5.1.7.1 Supported Demonstration Boards
Lists supported demonstration and development hardware boards.
Description
Demonstration Board (click link for board information) Notes
PIC32 USB Starter Kit II -
PIC32MZ Embedded Connectivity (EC) Starter Kit -
3.10.1.5.1.7.2 Configuring the Hardware
Describes how to configure the supported hardware.
Description
PIC32 USB Starter Kit II
No hardware related configuration or jumper setting changes are necessary.
PIC32MZ Embedded Connectivity (EC) Starter Kit
No hardware related configuration or jumper setting changes are necessary.
3.10.1.5.1.7.3 Running the Demonstration
Provides instructions on how to build and run the USB HID Josytick demonstration.
Description
This demonstration uses the selected hardware platform as a USB Joystick. While compiling, select the
pic32mx_usb_sk_xxx_xxx configurations for the PIC32 USB Starter Kit II or select the pic32mz_sk_xxx_xxx configurations for
PIC32MZ Embedded Connectivity (EC) Starter Kit. To test the joystick feature, go to the “\apps\usb\device\generic_device\bin” directory. A window like that shown below should appear:
If instead of this window, an error message pops up while trying to launch the application, it is likely the Microsoft .NET
Framework Version 3.5 Redistributable Package has not yet been installed. Please install it and try again.
In order to begin sending/receiving packets to the device, you must first find and “connect” to the device. As configured by
default, the application is looking for USB devices with VID = 0x04D8 and PID = 0x0204. The device descriptor in the firmware
project meant to be used with this demonstration uses the same VID/PID. To run the demonstration program the USB device
with the correct precompiled .hex file. If you are connecting the device for the first time, Windows pops up a window asking you
3.10 USB Demonstrations MPLAB Harmony Help USB Demonstrations
3-165
to install the driver for the device. When asked for the driver point it to the inf file provided along with the demonstration.
Windows takes while to install the driver for the USB device that is just plugged in. Open the Device manager and ensure that
the USB device is listed under the ‘Libusb Demo Devices’. Once the driver is installed hit the “Connect” button, the other
pushbuttons should become enabled. If hitting the connect button has no effect, it is likely the USB device is either not
connected, or has not been programmed with the correct firmware.
If a different VID/PID combination from the default is desired, then the descriptors in the firmware must be changed as well as
the inf file. The easiest way to change the inf file is to use the utility provided with the LibUSB download for windows on the
LibUSB website. This utility can create a new inf file based on a connected device. So make sure to change the VID/PID
combination first in the firmware, connect the device, and then run the inf file creator utility. After completing the utility, a new
signed driver with inf file is created.
Once the driver is installed hit the “Connect” button, the other pushbuttons should become enabled. If hitting the connect button
has no effect, it is likely the USB device is either not connected, or has not been programmed with the correct firmware.
Hitting the Toggle LED(s) should send a single packet of general purpose generic data to the Custom class USB peripheral
device. The data will arrive on the Bulk OUT endpoint. The firmware has been configured to receive this generic data packet,
parse the packet looking for the “Toggle LED(s)” command, and should respond appropriately by controlling the LED(s) on the
demonstration board.
The “Get Pushbutton State” button will send one packet of data over the USB to the peripheral device (to the Bulk OUT endpoint)
requesting the current pushbutton state. The firmware will process the received Get Pushbutton State command, and will
prepare an appropriate response packet depending upon the pushbutton state.
The PC then requests a packet of data from the device (which will be taken from the Bulk IN endpoint). Once the PC application
receives the response packet, it will update the pushbutton state label.
Try experimenting with the application by holding down the appropriate pushbutton on the demonstration board, and then
simultaneously clicking on the “Get Pushbutton State” button. Then try to repeat the process, but this time without holding down
the pushbutton on the demonstration board.
Following table shows the button that has to be pressed on the demonstration board to see the push button state changing.
Demonstration Board Button
PIC32 USB Starter Kit II SW1
3.10.1.5.1.10 audio_speaker
Demonstrates a USB Audio Device that emulates a USB speaker.
Description
This demonstration application creates uses the USB Audio Device class to implement a speaker.
3.10.1.5.1.10.1 Supported Demonstration Boards
Lists supported demonstration and development hardware boards.
Description
Demonstration Board (click link for board information) Notes
PIC32 USB Digital Audio Accessory Board -
PIC32MZ Embedded Connectivity (EC) Starter Kit -
Multimedia Expansion Board II (MEB II) -
3.10 USB Demonstrations MPLAB Harmony Help USB Demonstrations
3-166
3.10.1.5.1.10.2 Configuring the Hardware
Describes how to configure the supported hardware.
Description
PIC32 USB Digital Audio Accessory Board
No hardware related configuration or jumper setting changes are necessary.
PIC32MZ Embedded Connectivity (EC) Starter Kit and Multimedia Expansion Board II (MEB II)
1) Fix the PIC32MZ Embedded Connectivity (EC) Starter Kit on the MEB II board.
2) Connect a Headphone to the HP OUT jack on the MEB II board.
3.10.1.5.1.10.3 Running the Demonstration
Provides instructions on how to build and run the Audio Speaker Demonstration.
Description
This demonstration functions as a speaker when plugged into a computer. Using any feature on the computer that normal
produces sound on the speaker will work with this demonstration. The feature unit only supports the Mute control.
Please note that some applications lock into a sound source when they open or close (such as some web browsers or plug-ins),
so that if you plug in the speaker with the web page or video already playing, the sound might not get redirected to the USB
based speakers until you close and reopen the browser.
The audio device created in this demonstration has the following characteristics:
• Sampling rate of 48 kHz
• 2 Channel (Stereo)
• PCM Format - 16 bits per Sample
• Asynchronous Audio Endpoint
3.10.1.5.2 Host
3.10.1.5.2.1 cdc_basic
This application demonstrates the use of the CDC Host Class Driver to enumerate and operate a CDC Device.
Description
This application demonstrates the use of the CDC Host Class Driver to enumerate and operate a CDC Device. The application
uses the USB Host layer and CDC class driver to enumerate a CDC USB device. The demonstration host application then
operates and uses the functionality of the attached CDC Device.
3.10.1.5.2.1.1 Supported Demonstration Boards
Lists supported demonstration and development hardware boards.
3.10 USB Demonstrations MPLAB Harmony Help USB Demonstrations
3-167
Description
Demonstration Board (click link for board information) Notes
PIC32MZ Embedded Connectivity (EC) Starter Kit -
PIC32 USB Starter Kit II -
Hardware required for USB Device CDC Serial Emulator Demonstration Application -
3.10.1.5.2.1.2 Configuring the Hardware
Describes how to configure the supported hardware.
Description
PIC32MZ Embedded Connectivity (EC) Starter Kit
This hardware does not require any configuration.
PIC32 Starter Kit USB II
This hardware does not require any configuration.
3.10.1.5.2.1.3 Running the Demonstration
Provides instructions on how to build and run the USB Host CDC Basic Demo. Please refer to the Release Notes for
demonstration limitations, if any.
Description
This application demonstrates the use of the CDC Host Class Driver to enumerate and operate a CDC Device. The application
uses the USB Host layer and CDC class driver to enumerate a CDC USB device. The demonstration host application then
operates and uses the functionality of the attached CDC Device.
1. Open the project in MPLAB X IDE and select the desired project configuration.
2. Build the code and program the device.
3. Follow the directions for setting up and running the cdc_serial_emulator USB device demonstration.
4. Connect the UART (P1) port on the Explorer 16 Development Board (running the cdc_serial_emulator demonstration) to a
USB Host PC via a commercially available Serial-to-USB Dongle.
5. Start a terminal program on the USB Host PC and select the Serial-to-USB Dongle as the communication port. Select the
baud rate as 9600, no parity, 1 stop bit and no flow control.
6. Connect the mini – B connector on the USB PICtail Plus Daughter Board , of the cdc_serial_emulator demonstration setup, to
the Type – A USB host connector on the starter kit.
7. A prompt (“LED : “) will be displayed immediately on the terminal emulation program.
8. Pressing either the 1, 2, or 3 key on the USB Host keyboard will cause LED 1, 2, or 3 on the PIC32 Starter kit (running the
USB CDC Host application) to switch on, respectively.
9. The prompt will again be displayed on terminal emulation program, and step 8 can be repeated.
The setup should be similar to the following diagram.
3.10 USB Demonstrations MPLAB Harmony Help USB Demonstrations
3-168
The cdc_serial_emulator demonstration emulates a USB-to-Serial Dongle. The CDC Host (running the cdc_basic demonstration
application) sends the prompt message to the CDC device. The CDC device forwards the prompt to the UART port from where it
is transmitted to the PC USB Host through the USB-to-Serial Dongle. A key press on the PC USB Host is transmitted to the CDC
device, which in turn presents the key press data to the CDC host. The cdc_basic demonstration then analyzes the key press
data and switches on the respective LED.
3.10.1.5.2.2 msd_basic
This application demonstrates the use of the MSD Host Class Driver to write a file to USB Flash Drive.
Description
This application demonstrates the use of the MSD Host Class Driver to write a file to a USB Flash drive. The application uses the
USB Host layer , MSD class driver and the MPLAB Harmony File System Framework to enumerate a USB Flash drive and to
write a file to it.
3.10.1.5.2.2.1 Supported Demonstration Boards
Lists supported demonstration and development hardware boards.
Description
Demonstration Board (click link for board information) Notes
PIC32MZ Embedded Connectivity (EC) Starter Kit -
PIC32 USB Starter Kit II -
3.10.1.5.2.2.2 Configuring the Hardware
Describes how to configure the supported hardware.
Description
PIC32MZ Embedded Connectivity (EC) Starter Kit
This hardware does not require any configuration.
3.10 USB Demonstrations MPLAB Harmony Help USB Demonstrations
3-169
PIC32 Starter Kit USB II
This hardware does not require any configuration.
3.10.1.5.2.2.3 Running the Demonstration
Provides instructions on how to build and run the USB Host MSD Basic demonstration. Please refer to theRelease Notes for
demonstration limitations, if any.
Description
This application demonstrates the use of the MSD Host Class Driver to write a file to USB Flash drive. The application uses the
USB Host layer, MSD class driver and the MPLAB Harmony File System Framework to enumerate a USB Flash drive and to
write a file to it.
1. Open the project in MPLAB X IDE and select the desired project configuration.
2. Build the code and program the device.
3. With the code running, attach a USB Flash drive to the Host connector on the starter kit.
4. The demonstration application will then create a file named “File.txt”. It will then write the text “Hello World” to this file, and
then close the file.
5. The demonstration will then move to Idle mode, which is indicated when LED 2 on the starter kit lights up.
6. The USB Flash drive can then be attached to a USB Host PC to verify the demonstration application operation.
7. Steps 3 through 6 can be repeated.
8. If the USB Flash drive already contains a file with the name “File.txt”, the demonstration application will append the text “Hello
World” to the end of the file name.
3.10.1.6 Demonstration Board Information
Information on Hardware used by the USB Library Demo Applications.
Description
The USB Library Demo Applications can be tried across on hardware boards. This section provide details on the different
hardware boards that are used by the demo applications.
3.10.1.6.1 PIC32 USB Starter Kit II
Provides details information on the PIC32 USB Starter II.
3.10 USB Demonstrations MPLAB Harmony Help USB Demonstrations
3-170
Description
SW1 - Application switch. Tied to RD6.
SW2 - Application switch. Tied to RD7.
SW3 - Application switch. Tied to RD13.
LED1 - Application LED. Tied to RD0.
LED2 - Application LED. Tied to RD1.
LED3 - Application LED. Tied to RD2.
This board supports the following USB Device demonstrations:
• CDC Single COM port (cdc_com_port_single).
• CDC Dual COM port (cdc_com_port_dual)
• HID Basic (hid_basic)
• HID Mouse (hid_mouse)
• HID Keyboard (hid_keyboard)
• HID Joystick (hid_joystick)
• MSD Flash Drive (msd_basic)
• Generic USB Device (generic_device)
More Information
Microchip Part Number : DM320003-2
3.10.1.6.2 Explorer 16 Development Board
Provides information on the Explorer 16 Development Board
3.10 USB Demonstrations MPLAB Harmony Help USB Demonstrations
3-171
Description
S1 - Reset button (MCLR)
S2 - Processor switch. This switch determines which processor is running, the processor on the board or the processor on the
Plug-In-Module (PIM).
S3, S4, S5, S6 - Application switches. For information about what pin is connected to this switch, please refer to the information
for the PIM in use.
D3 through D10 - Application LEDs. For information about what pin is connected to this LED, please refer to the information for
the PIM in use.
This board support the following USB Host demos:
1. CDC Host (cdc_serial)
More Information:
Microchip Part Number: DM240001
3.10 USB Demonstrations MPLAB Harmony Help USB Demonstrations
3-172
3.10.1.6.3 PIC32MX795F512L Plug-In-Module (PIM)
Provides information on the PIC32MX795F512L Plug-In-Module (PIM).
Description
This PIM is required while using the Explorer 16 Development Board.
More Information
Microchip Part Number: MA320003
Information Sheet
3.10.1.6.4 PIC32 USB Digital Audio Accessory Board
Provides information on the PIC32 USB Digital Audio Accessory Board
Description
This board support the following USB Device demonstration:
Audio Speaker (audio_speaker)
More Information:
Microchip Part Number: DM320014
3.10.1.6.5 PIC32MZ Embedded Connectivity (EC) Starter Kit
Provides details information on the PIC32MZ Embedded Connectivity (EC) Starter Kit.
Description
Microchip Part Number: DM320006 (without Crypto) or DM320006-C (with Crypto)
The top assembly of the board includes these key features, as indicated in Figure 1:
1. PIC32MZ2048ECH144 32-bit microcontroller.
2. Green power indicator LED.
3. On-board crystal or oscillator for precision microcontroller clocking (12 MHz).
4. USB connectivity for on-board debugger communications.
5. Green debug indicator LED.
6. Three push button switches for user-defined inputs.
7. Three user-defined indicator LEDs.
8. USB Type A receptacle connectivity for PIC32 host-based applications.
9. HOST mode power jumper.
10. Daughter board connectors for flexible Ethernet PHY options.
11. 32 kHz oscillator for RTCC and Timer1 (optional).
12. External 2 GB SQI memory for expanded memory application.
13. Jumper for using or disconnecting the on-board debugger.
NOTE: When running self-powered USB device applications, open the jumper JP1 to prevent possibly back-feeding voltage onto
the Vbus from one port on the host to another (or from one host to another).
3.10 USB Demonstrations MPLAB Harmony Help USB Demonstrations
3-173
Figure 1: PIC32MZ Embedded Connectivity (EC) Starter Kit Layout (Front)
The bottom assembly of the board includes these key features, as indicated in Figure 2:
1. PIC24FJ256GB106 USB microcontroller for on-board debugging.
2. Regulated +3.3V power supply for powering the starter kit via USB or expansion board.
3. Connector for various expansion boards.
4. USB Type micro-AB receptacle for OTG and USB device connectivity for PIC32 OTG/device-based applications.
5. 50 MHz Ethernet PHY oscillator.
6. USB Host and OTG power supply for powering PIC32 USB applications.
Figure 2: PIC32MZ Embedded Connectivity (EC) Starter Kit Layout (Back)
3.10 USB Demonstrations MPLAB Harmony Help USB Demonstrations
3-174
3.10.1.6.6 Multimedia Expansion Board II (MEB II)
Provides details information on the Multimedia Expansion Board II (MEB) II.
Description
Microchip Part Number: DM320005-2
Product Page
The front side of the MEB II includes these key features, as shown in Figure 1:
1. Display daughter board connector (60-pin Hirose board-to-board connector).
2. mTouch™ buttons.
3. Push Button.
4. Power LED.
5. User LEDs.
6. VGA Camera (OVM7690).
7. PICtail™ Connector.
8. Analog temperature sensor.
Figure 1: Multimedia Expansion Board II Layout (Front)
The underside of the MEB II includes these key features, as shown in Figure 2:
1. Regulated 5V and 3.3V power supply for powering the board via a 9-15V DC Adapter.
2. PIC32 Starter Kit connector (168-pin Hirose board-to-board connector).
3. 24-bit stereo audio codec (AK4953A).
4. Integrated 802.11bg wireless module (MRF24WG0MA).
5. Low-cost Bluetooth® HCI transceiver (BTM805).
6. EBI SRAM memory (IS61WV102416BLL).
7. microSD slot.
3.10 USB Demonstrations MPLAB Harmony Help USB Demonstrations
3-175
8. Analog accelerometer (ADXL325).
Figure 2: Multimedia Expansion Board II Layout (Back)
3.10 USB Demonstrations MPLAB Harmony Help USB Demonstrations
3-176
4 Building Projects Help
4 MPLAB Harmony Help
4-177
4.1 Building Projects
4.1.1 Introduction
This section describes the MPLAB X IDE projects that are provided to build binary (.a file) versions of key MPLAB Harmony
libraries.
Description
The following MPLAB Harmony libraries are provided in prebuilt binary (“.a” file) format because source code is not released or
to provide optimal performance for users of the free version of the compiler. The MPLAB X IDE projects used to build these
libraries are provided so that you can rebuild these libraries with different build parameters, optimization settings, and/or debug
symbols if desired.
Note: Building these libraries with high optimization settings will require a fully licensed version of the necessary Microchip XC
compiler.
Build Projects Folder: “/build”
Library Description
framework/crypto MPLAB Harmony Encryption/Decryption Library
framework/zlib MPLAB Harmony Compress/Decompression Library
framework/math/dsp MPLAB Harmony Digital Signal Processing Library
framework/math/libq MPLAB Harmony Fixed-point Math Library
framework/peripheral MPLAB Harmony Peripheral Library Build Project
4.1.2 Release Notes
MPLAB Harmony Version: v0.70b Building Projects: 0.70b Release Date: 18Nov2013
New This Release:
Peripheral Libraries
• Nothing to report in this release
Known Issues:
Peripheral Libraries
• Build configurations were not created for all PIC32 devices. As a workaround, select any configuration and choose a different
processor from the Project Properties dialog. This will require you to change the name of the output file to match the name of
the selected processor.
4.1 Building Projects MPLAB Harmony Help Using the Build Projects
4-178
4.1.3 Using the Build Projects
This section describes how to use the MPLAB Harmony build projects to generate binary (“.a” file) libraries that can be linked into
your project.
Description
The following information describes how to use the MPLAB Harmony build projects to generate binary (“.a” file) libraries that can
be linked into your project.
Prerequisites
To build MPLAB Harmony libraries, you must have the following installed on your development workstation:
• MPLAB X IDE (v1.95 or higher)
• MPLAB XC32 Compiler (v1.30 or higher)
• Appropriate compiler license for your desired optimization settings
Build Instructions
The following general instructions apply to all MPLAB Harmony library build projects. Refer to the related “Libraries” section for
additional information about building specific libraries.
1. Start MPLAB X IDE.
2. Open the desired build project.
3. Set it as the “main” project.
4.1 Building Projects MPLAB Harmony Help Using the Build Projects
4-179
4. Select the desired build configuration.
Note: Different libraries provide different build configurations, depending on the set of possible choices that are relevant to that
library. For example, the build project for the PIC32MX peripheral libraries (shown above) allows you to select the desired
PIC32MX processor. Other libraries may allow you to choose the desired optimization level or feature set. Refer to the related
“Libraries” section for information on the configurations provided by the build project for the library you want to build.
5. If required, select the desired processor (or other project settings, if desired).
Note: Projects that provide processor-specific configurations will not require this step.
a. Open the “Project Properties” dialog box.
b. Select the desired processor.
4.1 Building Projects MPLAB Harmony Help Using the Build Projects
4-180
6. Build the library.
7. Copy the binary “.a” library file to your project folder.
8. Add the binary “.a” library file to your project.
4.1.4 Supported Libraries
4.1.4.1 Crypto Library
This section describes MPLAB X IDE projects used to build the MPLAB Harmony Crypto libraries.
Description
The Crypto Library project is contained in the build/framework/crypto folder in the crypto.X project. The library contains functions
for operations on blocks of data.
Encryption/decryption operations can be done using AES, RSA, DES, Triple DES, and ECC.
Authentication/hashing can be done using MD5, SHA-1, SHA-256, SHA-384, and SHA-512.
Password-based key derivation can be done with HMAC.
Compression and decompression can be done using Huffman Encoding.
Random numbers can be created either one at a time or in a block.
4.1.4.2 Compression Library
This section describes MPLAB X IDE projects used to build the MPLAB Harmony compression/decompression “zlib” libraries.
Description
The “zlib” libraries consists of routines for handling gzip (.gz) files, include compression and decompression.
The library also contains functions that provide the Huffman compression available in the Crypto library.
4.1.4.3 DSP Math Library
This section describes MPLAB X IDE projects used to build the MPLAB Harmony DSP math libraries.
Description
The DSP Math Library consists of routines that are optimized in assembly to take advantage of the microAptivTM core of the
PIC32MZ devices. The library operates on fixed point integers, which are scaled to represent floating point numbers. Many
functions are available in both 16-bit and 32-bit numerical formats.
The library contains functions for mathematical operations on a vector (or array) of values, complex scalar values and matrixes.
4.1 Building Projects MPLAB Harmony Help Supported Libraries
4-181
Operations include add, subtract, multiply, power, data generation, and in the cases of vectors more complex functions including
statistics.
The DSP Math Library also contains a full set of digital filtering functions which include FIR and IIR primitives, as well as more
complex architectures (e.g., cascade and parallel bi-quad structures).
Finally the library contains a number of transform functions include FFT and inverse FFT, as well as a number of windowing
functions.
Some functions in the DSP Math Library require the use of the LIBQ Fixed Point Math library as well. In those cases the LIBQ
library must also be installed with your project. Details on dependent functions are found in the DSP Math Library help file under
the remarks section for that specific function.
4.1.4.4 Fixed-Point Math Library
This section describes MPLAB X IDE projects used to build the MPLAB Harmony fixed-point math “libq” libraries.
Description
The Fixed-Point Math Library consists of routines in optimized assembly for performing advanced mathematical operations on a
scalar. This is similar in construction to the floating point equivalent math.h file that is included with the compiler. All functions are
performed using fixed-point integer operations and generally available in both high precision and low precision variants. Lower
precision functions generally perform faster and may be suited for time critical operations.
4.1.4.5 Peripheral Libraries
This section describes MPLAB X IDE projects used to build the MPLAB Harmony peripheral libraries.
Description
The MPLAB Harmony peripheral libraries are implemented almost entirely using C-language inline functions. This is done for
efficiency so that the compiler can generate a few simple instructions in place of multiple layers of function calls when function
parameters are passed as constants. However, if the project that uses the peripheral library is built with low optimization settings,
the compiler may generate a function call instead of “inlining” the function implementation. Unfortunately, this will cause an
“undefined symbol” error at link time if the linker cannot find an actual implementation of the function to which it can link the “call”.
To satisfy the liker (and to provide optimized PLIB operation, even when low compiler optimization settings are used in your
project), the MPLAB Harmony peripheral libraries must be prebuilt as ‘.a’ file, linkable libraries. The appropriate MPLAB X IDE
peripheral library “.a” file for the processor in use must be added to the MPLAB X IDE project so that the linker can use them.
Note: Prebuilt binary “.a” files are provided for all supported processors in the MPLAB Harmony installation in the following
folder: /bin/framework/peripheral.
The MPLAB Harmony peripheral library “.a” file build projects are provided so that you may rebuild the binary peripheral library
“.a” files using any desired optimization settings. However, if you do this, you must have the appropriate xC compiler and you
must copy the resultant “.a” file to your project folder and add it to your MPLAB X IDE project. (See the “Build Instructions”
section for details of how to build the library.).
Build Configurations
Different MPLAB X IDE projects are provided for different processor families to build the peripheral libraries for MPLAB
Harmony. Each project provides a set of MPLAB X IDE configurations, one for each supported processor. For example, the
“mplab_pic32mx_plib.X” project provides configurations for each device in the PIC32MX family. To identify which devices are
supported, open the MPLAB X IDE project that is named after the device family in which you are interested, select the MPLAB X
IDE configuration named after the device you want to use, and look at the project properties to verify the device that is selected.
4.1 Building Projects MPLAB Harmony Help Supported Libraries
4-182
Key Configuration Options
To build the peripheral library binary “.a” files, there are two key configuration options that must be defined, as follows:
#define INLINE_API extern
#define INLINE static inline
These two configuration items are defined in the source file (“peripehral.c”), which then directly includes the peripheral library
implementation headers.
Note: This has already been done for you. This information is provided strictly for reference.
During normal peripheral library use, both of these options are defined as “extern inline” so that the compiler can choose
between generating a function call or generating inline code, directly in the calling function (as described above). However, to
build the binary library “.a” files the peripheral library Application Program Interface (API) functions must be exposed as global
“external” symbols. The “INLINE_API” attribute is placed as an attribute on all PLIB API function implementations. So, defining it
as “extern” allows the compiler to expose these functions within the library “.a” file so that the linker can find them. The VREG
and other “internal” functions prefixed by the “INLINE” attribute are then defined as “static inline” functions for efficiency.
4.1 Building Projects MPLAB Harmony Help Supported Libraries
4-183
5 Framework Help
5 MPLAB Harmony Help
5-184
5.1 Driver Library Help
5.1.1 Driver Library Overview
A device driver provides a simple well-defined interface to a hardware peripheral that can be used without operating system
support or that can be easily ported to a variety of operating systems. The basic driver operations allow an application to interact
with a device, reading and writing data, as if it was a simple file. More specific operations are present on most drivers and the
kind of specific operations available depends on the peripheral whose functionality is being exposed by the driver. A driver has
the following fundamental responsibilities:
1. Providing a highly-abstracted interface to a peripheral
2. Controlling access to a peripheral
3. Managing the state of a peripheral
The diagram below illustrates how a driver interacts with the other pieces of the system.
• The application calls the well defined driver interface to use the services provided by the driver.
• The driver calls various system services to perform the tasks that are possibly shared across other drivers.
• The driver also calls the peripheral library of the peripheral that its abstracting the interface to.
• Driver State machine can be invoked by the system task service (polling system) or the driver state machine can be invoked
from an ISR.
The driver provided the interfaces which can be broken down into the following two categories : ( is the abbreviation
identifying the module)
• System Operation - The interfaces for the system operation should be called by the system. Each driver can support all of
the system interfaces, or it can choose to not support the optional system interfaces. The system interfaces are
• DRV__Initialize - This routine initializes hardware for the index instance of the module, using the
hardware initialization given data. It also initializes any internal data structures. The DRV__Status operation will
return SYS_STATUS_READY when this operation has completed. Every driver module should define its own initialization
5.1 Driver Library Help MPLAB Harmony Help Driver Library Overview
5-185
data structure type named “DRV__INIT”. This structure must be an extension of the SYS_MODULE_INIT structure
(i.e. its first member must be the SYS_MODULE_INIT structure or equivalent). Any parameter that can change the power
state of the module must be included in the data structure. Once the Initialize operation has been called, the Deinitialize
operation must be called before the Initialize operation can be called again.
• DRV__Reinitialize - This routine reinitializes and refreshes the hardware using the hardware initialization given
data. The DRV__Status operation will return SYS_STATUS_READY when this operation has completed. It does not
clear or reinitialize internal data structures (although it may change the value of a few appropriate data items necessary to
manage the new hardware state) and it does not disconnect or interrupt any ongoing client operations.This operation can
be used to change the power state of the peripheral the module manages.
• DRV__Deinitialize - This routine de-initializes the index instance of the module, disabling its operation
(and any hardware for driver modules).The DRV__Status operation will return SYS_STATUS_READY when this
operation has completed.
• DRV__Status - The Status operation can be used to determine when any of the other three module operations has
completed. If the Status operation returns SYS_STATUS_BUSY, the previous operation has not yet completed. Once the
Status operation returns “SYS_STATUS_READY”, any previous operations have completed.
• The value of SYS_STATUS_READY is 1. Values between 1 and 10 are reserved for system defined “ready” states. A
module may define module-specific “ready” or “run” states greater than or equal to 10
(SYS_STATUS_READY_EXTENDED).
• The value of SYS_STATUS_ERROR is -1. Values between -1 and -10 are reserved for system-defined errors. A module
may define module-specific error values of less than or equal to -10 (SYS_STATUS_ERROR_EXTENDED).
• If the Status operation returns an error value, the error may be cleared by calling the reinitialize operation. If that fails,
the deinitialize operation will need to be called, followed by the initialize operation to return to normal operations.
(Remember to check the value returned by the Status routine after calling any of the module operations to find out when
they have completed.)
• DRV__Tasks - Used to maintain the driver’s state machine and implement its ISR. It is normally only called by the
system’s tasks routine or by an Interrupt Service Routine (ISR).
The usage model of the system interfaces is demonstrated in the diagram below:
The system is also responsible for either calling the Tasks routine through an ISR or poll the Tasks routine in a polling
environment.
• Client Operation - The interfaces provided by the driver for client operation, can be called by the application. Each driver can
provide a set of client interfaces, which supports the operation model of the peripheral that the driver is supporting. The client
interfaces can include
5.1 Driver Library Help MPLAB Harmony Help Driver Library Overview
5-186
• DRV__Open - This routine opens a driver for use by any client module and provides an “open-instance” handle that
must be provided to any of the other driver operations to identify the caller and the instance of the driver/hardware module.
• DRV__Close - This routine closes an opened-instance of a driver, invalidating the given handle. This routine is
optional, if the driver is designed to never be closed.
• DRV__ClientStatus - This routine provides the client, the status of the driver.
• DRV__ - This is the basic format of a driver interface routine. Driver interface routines (other than the
system module routines and the basic device driver routines) should follow this format.
The general usage model of the client interfaces is demonstrated in the diagram below, each driver will document usage model
specific to the driver in the driver help file.
Driver Configuration
A driver provides a set of configurations which can be divided into following categories:
1. Build Configuration Selection Configurations - The driver supports selecting the driver instance at build time (static
configuration) or at run time (dynamic configuration). A driver also supports selecting the number of clients that can possibly
connect to an hardware instance. All drivers will provide DRV__DRIVER_OBJECTS_NUMBER, when this
configuration macro is defined driver is built in dynamic driver configuration, else it is built in static driver configuration. The
number assigned to DRV__DRIVER_OBJECTS_NUMBER controls the maximum number of driver objects that can be
used. If a driver supports multiple clients it will provide DRV__CLIENT_OBJECTS_NUMBER, when this configuration
macro is defined driver is built to support multiple clients, else the driver is built to support single client. The number assigned
to DRV__DRIVER_OBJECTS_NUMBER controls the maximum number of client objects that can be used.
2. Initialization Overrides - Initialization overrides are provided to enable configuration of the hardware statically and with low
run time overhead. These override the parameters if also passed dynamically to Initialize or Reinitialize routine.
3. Other operational configurations - These can control the functionality of the driver or other setting of the driver that are
required for support core or optional functionality.
A driver allows the application to use the dynamic interface for all the above configuration when the application chooses the
appropriate configurations at build time. This is the preferred method of usage for the drivers.
As an exception, if the application wants to use multiple configurations in the same build for a driver type, or it needs to use
multiple instances of the same driver type, it needs to directly use the static single - client configuration interfaces, or it needs to
use the static multiple - client configuration interfaces.
While using the driver the static single client driver configuration, the application and system can choose to ignore the
SYS_MODULE_INDEX, SYS_MODULE_OBJ and DRV_HANDLE passed and returned to the driver and system interfaces.
While using the driver the static multiple client driver configuration, the application and system can choose to ignore the
5.1 Driver Library Help MPLAB Harmony Help Driver Library Overview
5-187
SYS_MODULE_INDEX and SYS_MODULE_OBJ passed and returned to the driver and system interfaces.
5.1.1.1 Data Types
Enumerations
Name Description
DRV_CLIENT_STATUS Identifies the current status/state of a client's connection to a driver.
DRV_IO_BUFFER_TYPES Identifies to which buffer a device operation will apply.
DRV_IO_INTENT Identifies the intended usage of the device when it is opened.
Types
Name Description
DRV_HANDLE Handle to an opened device driver.
Description
5.1.1.1.1 DRV_CLIENT_STATUS Enumeration
C
typedef enum {
DRV_CLIENT_STATUS_ERROR_EXTENDED = -10,
DRV_CLIENT_STATUS_ERROR = -1,
DRV_CLIENT_STATUS_CLOSED = 0,
DRV_CLIENT_STATUS_BUSY = 1,
DRV_CLIENT_STATUS_READY = 2,
DRV_CLIENT_STATUS_READY_EXTENDED = 10
} DRV_CLIENT_STATUS;
Description
Driver Client Status
This enumeration identifies the current status/state of a client's link to a driver.
Members
Members Description
DRV_CLIENT_STATUS_ERROR_EXTENDED
= -10
Indicates that a non-system defined error has occurred.
DRV_CLIENT_STATUS_ERROR = -1 An un-specified error has occurred.
DRV_CLIENT_STATUS_CLOSED = 0 An operation is currently in progress
DRV_CLIENT_STATUS_BUSY = 1 An operation is currently in progress
DRV_CLIENT_STATUS_READY = 2 Any previous operations have succeeded and the module is ready for
additional operations
DRV_CLIENT_STATUS_READY_EXTENDED
= 10
Indicates that the module is in a non-system defined ready/run state.
Remarks
The enumeration used as the return type for the client-level status routines defined by each device driver or system module (for
example, DRV_USART_ClientStatus) must be based on the values in this enumeration.
5.1 Driver Library Help MPLAB Harmony Help Driver Library Overview
5-188
5.1.1.1.2 DRV_HANDLE Type
C
typedef uintptr_t DRV_HANDLE;
Description
Device Handle
This handle identifies the open instance of a device driver. It must be passed to all other driver routines (except the initialization,
deinitialization, or power routines) to identify the caller.
Remarks
Every application or module that wants to use a driver must first call the driver's open routine. This is the only routine that is
absolutely required for every driver.
If a driver is unable to allow an additional module to use it, it must then return the special value DRV_HANDLE_INVALID. Callers
should check the handle returned for this value to ensure this value was not returned before attempting to call any other driver
routines using the handle.
5.1.1.1.3 DRV_IO_BUFFER_TYPES Enumeration
C
typedef enum {
DRV_IO_BUFFER_TYPE_NONE = 0x00,
DRV_IO_BUFFER_TYPE_READ = 0x01,
DRV_IO_BUFFER_TYPE_WRITE = 0x02,
DRV_IO_BUFFER_TYPE_RW = DRV_IO_BUFFER_TYPE_READ|DRV_IO_BUFFER_TYPE_WRITE
} DRV_IO_BUFFER_TYPES;
Description
Device Driver IO Buffer Identifier
This enumeration identifies to which buffer (read, write, both, or neither) a device operation will apply. This is used for "flush" (or
similar) operations.
Members
Members Description
DRV_IO_BUFFER_TYPE_NONE = 0x00 Operation does not apply to any buffer
DRV_IO_BUFFER_TYPE_READ = 0x01 Operation applies to read buffer
DRV_IO_BUFFER_TYPE_WRITE = 0x02 Operation applies to write buffer
DRV_IO_BUFFER_TYPE_RW =
DRV_IO_BUFFER_TYPE_READ|DRV_IO_BUFFER_TYPE_WRITE
Operation applies to both read and write buffers
5.1.1.1.4 DRV_IO_INTENT Enumeration
C
typedef enum {
DRV_IO_INTENT_READ,
DRV_IO_INTENT_WRITE,
DRV_IO_INTENT_READWRITE,
DRV_IO_INTENT_BLOCKING,
DRV_IO_INTENT_NONBLOCKING,
DRV_IO_INTENT_EXCLUSIVE,
DRV_IO_INTENT_SHARED
5.1 Driver Library Help MPLAB Harmony Help Driver Library Overview
5-189
} DRV_IO_INTENT;
Description
Device Driver I/O Intent
This enumeration identifies the intended usage of the device when the caller opens the device. It identifies the desired behavior
of the device driver for the following:
• Blocking or non-blocking I/O behavior (do I/O calls such as read and write block until the operation is finished or do they return
immediately and require the caller to call another routine to check the status of the operation)
• Support reading and/or writing of data from/to the device
• Identify the buffering behavior (sometimes called "double buffering" of the driver. Indicates if the driver should maintain its own
read/write buffers and copy data to/from these buffers to/from the caller's buffers.
• Identify the DMA behavior of the peripheral
Members
Members Description
DRV_IO_INTENT_READ Read
DRV_IO_INTENT_WRITE Write
DRV_IO_INTENT_READWRITE Read and Write
DRV_IO_INTENT_BLOCKING The driver will block and will return when the operation is complete
DRV_IO_INTENT_NONBLOCKING The driver will return immediately
DRV_IO_INTENT_EXCLUSIVE The driver will support only one client at a time
DRV_IO_INTENT_SHARED The driver will support multiple clients at a time
Remarks
The buffer allocation method is not identified by this enumeration. Buffers can be allocated statically at build time, dynamically at
run-time, or even allocated by the caller and passed to the driver for its own usage if a driver-specific routine is provided for such.
This choice is left to the design of the individual driver and is considered part of its interface.
These values can be considered "flags". One selection from each of the groups below can be ORed together to create the
complete value passed to the driver's open routine.
5.1.1.2 Constants
Macros
Name Description
DRV_CONFIG_NOT_SUPPORTED Not supported configuration.
DRV_HANDLE_INVALID Invalid device handle.
DRV_IO_ISBLOCKING Returns if the I/O intent provided is blocking
DRV_IO_ISEXCLUSIVE Returns if the I/O intent provided is non-blocking.
DRV_IO_ISNONBLOCKING Returns if the I/O intent provided is non-blocking.
5.1 Driver Library Help MPLAB Harmony Help Driver Library Overview
5-190
Description
5.1.1.2.1 DRV_CONFIG_NOT_SUPPORTED Macro
C
#define DRV_CONFIG_NOT_SUPPORTED (((unsigned short) -1))
Description
Not supported configuration
If the configuration option is not supported on an instance of the peripheral, use this macro to equate to that configuration. This
option should be listed as a possible value in the description of that configuration option.
5.1.1.2.2 DRV_HANDLE_INVALID Macro
C
#define DRV_HANDLE_INVALID (((DRV_HANDLE) -1))
Description
Invalid Device Handle
If a driver is unable to allow an additional module to use it, it must then return the special value DRV_HANDLE_INVALID. Callers
should check the handle returned for this value to ensure this value was not returned before attempting to call any other driver
routines using the handle.
Remarks
None.
5.1.1.2.3 DRV_IO_ISBLOCKING Macro
C
#define DRV_IO_ISBLOCKING(intent) (intent & DRV_IO_INTENT_BLOCKING)
Description
Device Driver Blocking Status Macro
This macro returns if the I/O intent provided is blocking.
Remarks
None.
5.1.1.2.4 DRV_IO_ISEXCLUSIVE Macro
C
#define DRV_IO_ISEXCLUSIVE(intent) (intent & DRV_IO_INTENT_EXCLUSIVE)
Description
Device Driver Exclusive Status Macro
This macro returns if the I/O intent provided is non-blocking.
5.1 Driver Library Help MPLAB Harmony Help Driver Library Overview
5-191
Remarks
None.
5.1.1.2.5 DRV_IO_ISNONBLOCKING Macro
C
#define DRV_IO_ISNONBLOCKING(intent) (intent & DRV_IO_INTENT_NONBLOCKING )
Description
Device Driver Non Blocking Status Macro
This macro returns if the I/ intent provided is non-blocking.
Remarks
None.
5.1.1.3 Files
Files
Name Description
driver.h This file aggregates all of the driver library interface headers.
driver_common.h This file defines the common macros and definitions used by the driver definition
and implementation headers.
Description
5.1.1.3.1 driver.h
Driver Library Interface Header
This file aggregates all of the driver library interface headers so client code only needs to include this one single header to obtain
prototypes and definitions for the interfaces to all driver libraries.
A device driver provides a simple well-defined interface to a hardware peripheral that can be used without operating system
support or that can be easily ported to a variety of operating systems.
A driver has the fundamental responsibilities:
• Providing a highly-abstraced interface to a peripheral
• Controlling access to a peripheral
• Managing the state of a peripheral
Remarks
The directory in which this file resides should be added to the compiler's search path for header files.
File Name
drv.h
Company
Microchip Technology Inc.
5.1 Driver Library Help MPLAB Harmony Help Driver Library Overview
5-192
5.1.1.3.2 driver_common.h
Driver Common Header
This file defines the common macros and definitions used by the driver definition and the implementation header.
Remarks
The directory in which this file resides should be added to the compiler's search path for header files.
Enumerations
Name Description
DRV_CLIENT_STATUS Identifies the current status/state of a client's connection to a driver.
DRV_IO_BUFFER_TYPES Identifies to which buffer a device operation will apply.
DRV_IO_INTENT Identifies the intended usage of the device when it is opened.
Macros
Name Description
DRV_CONFIG_NOT_SUPPORTED Not supported configuration.
DRV_HANDLE_INVALID Invalid device handle.
DRV_IO_ISBLOCKING Returns if the I/O intent provided is blocking
DRV_IO_ISEXCLUSIVE Returns if the I/O intent provided is non-blocking.
DRV_IO_ISNONBLOCKING Returns if the I/O intent provided is non-blocking.
Types
Name Description
DRV_HANDLE Handle to an opened device driver.
File Name
drv_common.h
Company
Microchip Technology Inc.
5.1.2 ADC Driver Library
5.1.2.1 Introduction
ADC Driver for Microchip Microcontrollers
This Analog-to-Digital Converter (ADC) driver provides an interface to manage the ADC module on the Microchip family of
microcontrollers.
Description
Overview
An ADC is a vital part of any system that interfaces to real-world signals. While there are many techniques for analog-to-digital
5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library
5-193
conversion, the Microchip family of microcontrollers uses Successive Approximation as one of its primary techniques.
5.1.2.2 Release Notes
MPLAB Harmony Version: v0.70b ADC Driver Library Version : 0.02a Release Date: 18Nov2013
New This Release:
This is the first release of the library. The interface can change in the beta and\or 1.0 release.
Known Issues:
Nothing to report in this release.
5.1.2.3 SW License Agreement
© 2013 Microchip Technology Inc.
Microchip licenses this software to you solely for use with Microchip products. The software is owned by Microchip and its
licensors, and is protected under applicable copyright laws. All rights reserved.
SOFTWARE IS PROVIDED “AS IS.” MICROCHIP EXPRESSLY DISCLAIMS ANY WARRANTY OF ANY KIND, WHETHER
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL MICROCHIP BE LIABLE FOR
ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, HARM TO
YOUR EQUIPMENT, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS
BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR
CONTRIBUTION, OR OTHER SIMILAR COSTS.
To the fullest extent allowed by law, Microchip and its licensors liability shall not exceed the amount of fees, if any, that you have
paid directly to Microchip to use this software.
MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE TERMS.
5.1.2.4 Using the Library
This topic describes the basic architecture of the ADC Driver Library and provides information and examples on how to use it.
Interface Header File: drv_adc.h
The interface to the ADC Driver Library is defined in the "drv_adc.h" header file.
Please refer to the MPLAB Harmony Overview for how the driver interacts with the framework.
5.1.2.4.1 Library Overview
Refer to the section Driver Overview for how the driver operates in a system.
The following table lists the interface section and its brief description.
Section Description
Configuring the Library Provides macros for configuring the system. It is required that the system
configures the driver to build correctly by choosing appropriate configuration
options as listed in this section.
5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library
5-194
System Interaction Functions Provides system module interfaces, Device initialization, deinitialization,
reinitialization and status functions.
Client Core Configuration Functions Provides interfaces for core functionality of the driver.
5.1.2.4.2 Abstraction Model
The ADC driver is modeled using the abstraction model, as shown in the following diagram.
• DRV_ADC_InputsRegister allows selection of inputs
• DRV_ADC_SamplesRead and DRV_ADC_SamplesReadLatest allow reading of the sample from the result buffer
• DRV_ADC_Start and DRV_ADC_Stop will control the operation of the ADC
5.1.2.4.3 How the Library Works
The library provides interfaces to support:
• System Interaction
• Client Core Functionality
5.1.2.4.3.1 System Initialization
This section describes the system initialization and reinitialization settings for the ADC Peripheral Library.
Description
System Initialization and Reinitialization
The system initialization and the reinitialization settings, effect only the instance of the peripheral that is being initialized or
re-initialized. During system initialization configure each instance of the module with the following configuration settings that are
supported by the specific ADC device hardware (refer to DRV_ADC_INIT)
1. Device requested power state: One of the system module power states.
2. Acquisition time: If the hardware supports this feature, configure this variable from DRV_ADC_ACQUISITION_TIME.
3. Voltage reference: If the hardware supports this feature, select the one from the available options(from
DRV_ADC_VOLTAGE_REFERENCE).
4. Conversion clock: If the hardware supports this feature, select the conversion clock prescaler value (from
DRV_ADC_CONVERSION_CLOCK_PRESCALER).
5. Conversion clock source: If the hardware supports this feature, select the conversion clock prescaler value (from
DRV_ADC_CONVERSION_CLOCK_SOURCE).
6. Clock frequency: Peripheral clock frequency configured for the device.
7. Conversion trigger source: If the hardware supports this feature, select the conversion trigger source(from
DRV_ADC_CONVERSION_TRIGGER_SOURCE).
8. Samples per interrupt: Configure the number of samples before to be generating interrupt(from
5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library
5-195
DRV_ADC_SAMPLES_PER_INTERRUPT).
9. Output data format: Select the output data format.
10. Interrupt source: Select the interrupt source.
Example: Auto Sampling Mode
#define MY_ADC_INSTANCE DRV_ADC_INDEX_0
SYS_MODULE_OBJ myAdcObj;
DRV_ADC_INIT adcInitData;
SYS_STATUS adcStatus;
// Populate the adcInitData structure
adcInitData.plibModuleId = ADC_ID_1;
adcInitData.acquisitionTime = PLIB_ADC_ACQUISITION_TIME_20_TAD;
adcInitData.voltageReference = PLIB_ADC_VREF_POS_TO_VDD_VREF_NEG_TO_VSS;
adcInitData.clockFrequency = 4000000; //4MHz
adcInitData.conversionClock = PLIB_ADC_CONV_CLOCK_20_TCY;
adcInitData.conversionClockSource = PLIB_ADC_CLOCK_SRC_SYSTEM_CLOCK;
adcInitData.conversionTriggerSource = PLIB_ADC_CONVERSION_TRIGGER_INTERNAL_COUNT;
adcInitData.dataOutputFormat = PLIB_ADC_OUTPUT_FORMAT_INTEGER_16BIT;
adcInitData.initFlags = DRV_ADC_AUTO_SAMPLING;
adcInitData.interruptSource= PLIB_INT_SOURCE_ADC_1;
adcInitData.samplesPerInterrupt = PLIB_ADC_SAMPLE_PER_INTERRUPT_AT_EACH_SAMPLE;
myAdcObj = DRV_ADC_Initialize(MY_ADC_INSTANCE, (SYS_MODULE_INIT*)&adcInitData);
adcStatus = DRV_ADC_Status(myAdcObj);
if (SYS_STATUS_BUSY == adcStatus)
{
// do something else and check back later
}
else if (SYS_STATUS_ERROR >= adcStatus)
{
// Handle error
}
5.1.2.4.3.2 Client Core Functionality
Core functionality provides a basic interface for the driver operation.
Description
General Client Operation
Core functionality provides a basic interface for the driver operation.
Applications using the timer core functionality, need to perform the following:
1. The system should have completed necessary initialization and DRV_ADC_Tasks should either be running in a polled
environment, or in an interrupt environment.
2. Open the driver using DRV_ADC_Open (the timer driver supports exclusive access only).
3. Registers the inputs to be used by the clients using DRV_ADC_InputsRegister.
5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library
5-196
4. Start the driver using DRV_ADC_Start.
5. Poll for the elapse status using DRV_ADC_SamplesAvailable, and then read the samples using either
DRV_ADC_SamplesReadLatest or DRV_ADC_SamplesRead.
6. The client will be able to stop the started ADC instance using DRV_ADC_Stop at any point and will be able to close it using
DRV_ADC_Close when it is no longer required.
Example:
DRV_HANDLE adcHandle; //Handle returned by DRV_ADC_Open function.
uint16_t dataBuffer; //Buffer to which the data will be written.
/*
Open a new client. The handle returned by the this function should be used
a passing parameter for all the specific client related operations.
*/
adcHandle = DRV_ADC_Open(MY_ADC_INSTANCE, DRV_IO_INTENT_NONBLOCKING);
DRV_ADC_InputsRegister ( adcHandle ,PLIB_ADC_INPUT_AN1|PLIB_ADC_INPUT_AN2 );
/*
ADC is not yet enabled. Enable it once the inputset is registered. Starts automatically
since auto sample mode is enabled.
*/
DRV_ADC_Start(adcHandle);
if ( DRV_ADC_SamplesAvailable(adcHandle) )
{
DRV_ADC_SamplesReadLatest ( adcHandle, &dataBuffer, 1);
/*
Once the above function returns success, the data is
in 'dataBuffer'. Application can use this data.
*/
}
5.1.2.4.3.3 Code Examples
Example1
//PIC32/PIC24 in auto sampling , Polling mode
#define MY_ADC_INSTANCE DRV_ADC_INDEX_0
DRV_HANDLE adcHandle; //Handle returned by DRV_ADC_Open function.
uint16_t dataBuffer; //Buffer to which the data will be written.
/*
Open a new client. The handle returned by the this function should be used
a passing parameter for all the specific client related operations.
*/
adcHandle = DRV_ADC_Open(MY_ADC_INSTANCE, DRV_IO_INTENT_NONBLOCKING);
ipHandle = DRV_ADC_InputsRegister ( adcHandle ,inputSetConfig );
/*
ADC is not yet enabled. Enable it once the inputset is registered. Starts automatically
since auto sample mode is enabled.
*/
DRV_ADC_Start(adcHandle);
while (DRV_ADC_SampleAvailable(adcHandle))
{
DRV_ADC_InputSetRead ( adcHandle, &dataBuffer, 1);
5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library
5-197
/*
Once the above function returns success, the data is
in 'dataBuffer'. Application can use this data.
*/
}
Example 2:
//PIC32/PIC24 in Manual triggering , Polling mode
#define MY_ADC_INSTANCE DRV_ADC_INDEX_0
int main()
{
SYS_MODULE_OBJ myAdcObj; //Object returned by DRV_ADC_Initialize function.
DRV_ADC_INIT adcInitData; //Contains all the initialization values.
DRV_HANDLE adcHandle; //Handle returned by DRV_ADC_Open function.
DRV_ADC_INPUTSET_HANDLE ipHandle; //Handle returned by DRV_ADC_InputSetRegister
function.
DRV_ADC_INPUTSET_CONFIG inputSetConfig;//Contains all values to configure the inputset.
uint16_t dataBuffer; //Buffer to which the data will be written.
/*
These initialization values should be based on the requirement of the
application and the way it wants the hardware to be operating. Most of
these values will be written directly to the hardware registers.
*/
adcInitData.plibModuleId = ADC_ID_1;
adcInitData.acquisitionTime = PLIB_ADC_ACQUISITION_TIME_15_TAD;
adcInitData.voltageReference = PLIB_ADC_VREF_POS_TO_VDD_VREF_NEG_TO_VSS;
adcInitData.clockFrequency = 4000000; //4MHz
adcInitData.conversionClock = PLIB_ADC_CONV_CLOCK_5_TCY;
adcInitData.conversionClockSource = PLIB_ADC_CLOCK_SRC_INTERNAL_RC;
adcInitData.conversionTriggerSource = PLIB_ADC_CONVERSION_TRIGGER_INTERNAL_COUNT;
adcInitData.dataOutputFormat = PLIB_ADC_OUTPUT_FORMAT_INTEGER_16BIT;
adcInitData.interruptSource= PLIB_INT_SOURCE_ADC_1;
adcInitData.samplesPerInterrupt = PLIB_ADC_SAMPLE_PER_INTERRUPT_AT_EACH_SAMPLE;
myAdcObj = DRV_ADC_Initialize(MY_ADC_INSTANCE, (SYS_MODULE_INIT*)&adcInitData);
/*
Open a new client. The handle returned by the this function should be used
a passing parameter for all the specific client related operations.
*/
adcHandle = DRV_ADC_Open(MY_ADC_INSTANCE, DRV_IO_INTENT_NONBLOCKING);
/*
Driver invokes the registered callback function every successful data read.
Application can perform an action or do a state change in the callback
*/
inputSetConfig.callback = adcCallback;
inputSetConfig.input = POTENTIOMETER_ANALOG_INPUT;
inputSetConfig.errorTolerance = 10;
inputSetConfig.samplingFrequency = 40000;
ipHandle = DRV_ADC_InputSetRegister ( adcHandle ,inputSetConfig );
/*
ADC is not yet enabled. Enable it once the inputset is registered. Starts automatically
since auto sample mode is enabled.
*/
DRV_ADC_Start(adcHandle);
while (1)
{
/*
5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library
5-198
This function can be either called in a sequential way or it could
be called from a timer periodically
*/
triggerAdc();
DRV_HANDLE handle;
DRV_ADC_Tasks (myAdcObj);
DRV_ADC_InputSetRead ( adcHandle, &dataBuffer, 1);
/*
Once the above function returns success, the data is
in 'dataBuffer'. Application can use this data.
*/
}
}
void adcCallback (void)
{
// Application can do something here
}
void triggerAdc(void)
{
DRV_ADC_OperationSetup(handle, DRV_ADC_START_SAMPLING);
/* Give some delay between the two operations. */
for (i=0; i<100; i++);
DRV_ADC_OperationSetup(handle, DRV_ADC_START_CONVERSION);
}
Example 3:
//PIC32/PIC24 in auto sampling , Interrupt mode
#define MY_ADC_INSTANCE DRV_ADC_INDEX_0
int main()
{
SYS_MODULE_OBJ myAdcObj; //Object returned by DRV_ADC_Initialize function.
DRV_ADC_INIT adcInitData; //Contains all the initialization values.
DRV_HANDLE adcHandle; //Handle returned by DRV_ADC_Open function.
DRV_ADC_INPUTSET_HANDLE ipHandle; //Handle returned by DRV_ADC_InputSetRegister
function.
DRV_ADC_INPUTSET_CONFIG inputSetConfig;//Contains all values to configure the inputset.
uint16_t dataBuffer; //Buffer to which the data will be written.
/*
These initialization values should be based on the requirement of the
application and the way it wants the hardware to be operating. Most of
these values will be written directly to the hardware registers.
*/
adcInitData.plibModuleId = ADC_ID_1;
adcInitData.acquisitionTime = PLIB_ADC_ACQUISITION_TIME_15_TAD;
adcInitData.voltageReference = PLIB_ADC_VREF_POS_TO_VDD_VREF_NEG_TO_VSS;
adcInitData.clockFrequency = 4000000; //4MHz
adcInitData.conversionClock = PLIB_ADC_CONV_CLOCK_5_TCY;
adcInitData.conversionClockSource = PLIB_ADC_CLOCK_SRC_INTERNAL_RC;
adcInitData.conversionTriggerSource = PLIB_ADC_CONVERSION_TRIGGER_INTERNAL_COUNT;
adcInitData.dataOutputFormat = PLIB_ADC_OUTPUT_FORMAT_INTEGER_16BIT;
adcInitData.initFlags = DRV_ADC_AUTO_SAMPLING;
adcInitData.interruptSource= PLIB_INT_SOURCE_ADC_1;
adcInitData.samplesPerInterrupt = PLIB_ADC_SAMPLE_PER_INTERRUPT_AT_EACH_SAMPLE;
5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library
5-199
myAdcObj = DRV_ADC_Initialize(MY_ADC_INSTANCE, (SYS_MODULE_INIT*)&adcInitData);
/*
Open a new client. The handle returned by the this function should be used
a passing parameter for all the specific client related operations.
*/
adcHandle = DRV_ADC_Open(MY_ADC_INSTANCE, DRV_IO_INTENT_NONBLOCKING);
/*
Driver invokes the registered callback function every successful data read.
Application can perform an action or do a state change in the callback
*/
inputSetConfig.callback = adcCallback;
inputSetConfig.input = POTENTIOMETER_ANALOG_INPUT;
inputSetConfig.errorTolerance = 10;
inputSetConfig.samplingFrequency = 40000;
ipHandle = DRV_ADC_InputSetRegister ( adcHandle ,inputSetConfig );
/*
ADC is not yet enabled. Enable it once the inputset is registered. Starts automatically
since auto sample mode is enabled.
*/
DRV_ADC_Start(adcHandle);
while (1)
{
/*
Task function need not be called. Task function
is registered as ISR in case of interrpt mode
*/
DRV_ADC_InputSetRead ( adcHandle, &dataBuffer, 1);
/*
Once the above function returns success, the data is
in 'dataBuffer'. Application can use this data.
*/
}
}
void adcCallback (void)
{
// Application can do something here
}
// Do something else...
} while(total < MY_BUFFER_SIZE);
Example 4:
//PIC32/PIC24 in Manual triggering , Interrupt mode
#define MY_ADC_INSTANCE DRV_ADC_INDEX_0
int main()
{
SYS_MODULE_OBJ myAdcObj; //Object returned by DRV_ADC_Initialize function.
DRV_ADC_INIT adcInitData; //Contains all the initialization values.
DRV_HANDLE adcHandle; //Handle returned by DRV_ADC_Open function.
DRV_ADC_INPUTSET_HANDLE ipHandle; //Handle returned by DRV_ADC_InputSetRegister
function.
5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library
5-200
DRV_ADC_INPUTSET_CONFIG inputSetConfig;//Contains all values to configure the inputset.
uint16_t dataBuffer; //Buffer to which the data will be written.
/*
These initialization values should be based on the requirement of the
application and the way it wants the hardware to be operating. Most of
these values will be written directly to the hardware registers.
*/
adcInitData.plibModuleId = ADC_ID_1;
adcInitData.acquisitionTime = PLIB_ADC_ACQUISITION_TIME_15_TAD;
adcInitData.voltageReference = PLIB_ADC_VREF_POS_TO_VDD_VREF_NEG_TO_VSS;
adcInitData.clockFrequency = 4000000; //4MHz
adcInitData.conversionClock = PLIB_ADC_CONV_CLOCK_5_TCY;
adcInitData.conversionClockSource = PLIB_ADC_CLOCK_SRC_INTERNAL_RC;
adcInitData.conversionTriggerSource = PLIB_ADC_CONVERSION_TRIGGER_INTERNAL_COUNT;
adcInitData.dataOutputFormat = PLIB_ADC_OUTPUT_FORMAT_INTEGER_16BIT;
adcInitData.interruptSource= PLIB_INT_SOURCE_ADC_1;
adcInitData.samplesPerInterrupt = PLIB_ADC_SAMPLE_PER_INTERRUPT_AT_EACH_SAMPLE;
myAdcObj = DRV_ADC_Initialize(MY_ADC_INSTANCE, (SYS_MODULE_INIT*)&adcInitData);
/*
Open a new client. The handle returned by the this function should be used
a passing parameter for all the specific client related operations.
*/
adcHandle = DRV_ADC_Open(MY_ADC_INSTANCE, DRV_IO_INTENT_NONBLOCKING);
/*
Driver invokes the registered callback function every successful data read.
Application can perform an action or do a state change in the callback
*/
inputSetConfig.callback = adcCallback;
inputSetConfig.input = POTENTIOMETER_ANALOG_INPUT;
inputSetConfig.errorTolerance = 10;
inputSetConfig.samplingFrequency = 40000;
ipHandle = DRV_ADC_InputSetRegister ( adcHandle ,inputSetConfig );
/*
ADC is not yet enabled. Enable it once the inputset is registered. Starts automatically
since auto sample mode is enabled.
*/
DRV_ADC_Start(adcHandle);
while (1)
{
/*
This function can be either called in a sequential way or it could
be called from a timer periodically
*/
triggerAdc();
/*
Task function need not be called. Task function
is registered as ISR in case of interrpt mode
*/
DRV_ADC_InputSetRead ( adcHandle, &dataBuffer, 1);
/*
Once the above function returns success, the data is
in 'dataBuffer'. Application can use this data.
*/
}
5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library
5-201
}
void adcCallback (void)
{
// Application can do something here
}
void triggerAdc(void)
{
DRV_ADC_OperationSetup(handle, DRV_ADC_START_SAMPLING);
/* Give some delay between the two operations. */
for (i=0; i<100; i++);
DRV_ADC_OperationSetup(handle, DRV_ADC_START_CONVERSION);
}
5.1.2.5 Configuring the Library
The configuration of the ADC device driver is based on the file sys_config.h
This header file contains the configuration selection for the ADC device driver build. Based on the selections made here and the
system setup the ADC device driver will support or not selected features. These configuration settings will apply to all instances
of the device driver.
This header can be placed anywhere in the application specific folders and the path of this header needs to be presented to the
include search for a successful build. Refer to the Applications Overview section for more details.
5.1.2.6 Building the Library
Files
Name Description
drv_adc.c ADC Driver source file.
drv_adc_client_multi.c ADC Driver multiple client implementations.
drv_adc_client_single.c ADC Driver single client implementations.
drv_adc_hw_dynamic.c ADC Driver build variant implementation for the dynamic driver.
drv_adc_hw_static.c ADC Driver build variant implementation for the static driver.
Description
5.1.2.6.1 drv_adc.c
ADC Driver Source File
This file implements the ADC Driver Interface routines. While building the driver from source, ALWAYS use this file in the build.
File Name
drv_adc.c
Company
Microchip Technology Inc.
5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library
5-202
5.1.2.6.2 drv_adc_client_multi.c
ADC Driver Multiple Client
This file implements the functions for the multiple client support. While building the driver from source, use this file in the build
when DRV_ADC_CLIENTS_NUMBER is defined in the system configuration or when DRV_ADC_INSTANCES_NUMBER is
defined in the system configuration.
File Name
drv_adc_client_multi.c
Company
Microchip Technology Inc.
5.1.2.6.3 drv_adc_client_single.c
ADC Driver Single Client
This file implements the functions for the single client support While building the driver from source, use this file in the build when
DRV_ADC_CLIENTS_NUMBER is not defined in system configuration.
File Name
drv_adc_client_single.c
Company
Microchip Technology Inc.
5.1.2.6.4 drv_adc_hw_dynamic.c
ADC Driver Build Variant implementation for dynamic driver
This file defines the build variant implementations for the dynamic driver. While building the driver from source, use this file in the
build when DRV_ADC_INSTANCES_NUMBER is defined in the system configuration.
File Name
drv_adc_hw_dynamic.c
Company
Microchip Technology Inc.
5.1.2.6.5 drv_adc_hw_static.c
ADC Driver build variant implementation for static driver
This file defines the build variant implementations for the static driver. While building the driver from source, use this file in the
build when DRV_ADC_INSTANCES_NUMBER is not defined in the system configuration.
File Name
drv_adc_hw_static.c
Company
Microchip Technology Inc.
5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library
5-203
5.1.2.7 Library Interface
Data Types and Constants
Name Description
DRV_ADC_CLIENT_STATUS Defines the client-specific status of the ADC driver.
DRV_ADC_INIT Defines the data required to initialize or reinitialize the
ADC driver.
DRV_ADC_INIT_FLAGS Identifies the initialization flags of the ADC module.
DRV_ADC_ACQUISITION_TIME Defines the acquisition time.
DRV_ADC_ALTERNATE_INPUT_SAMPLING_ENABLE Enable the alternate input sampling feature of the ADC.
DRV_ADC_ANALOG_INPUT Defines the analog input channel.
DRV_ADC_AUTO_SAMPLING_ENABLE Rnable the suto-sampling feature of the ADC.
DRV_ADC_CLIENTS_NUMBER Selects the miximum number of clients.
DRV_ADC_CONVERSION_CLOCK_PRESCALER Defines the conversion clock.
DRV_ADC_CONVERSION_CLOCK_SOURCE Defines the conversion clock source.
DRV_ADC_CONVERSION_TRIGGER_SOURCE Defines the conversion trigger source.
DRV_ADC_INDEX ADC static index selection.
DRV_ADC_INDEX_0 ADC driver index definitions.
DRV_ADC_INDEX_1 This is macro DRV_ADC_INDEX_1.
DRV_ADC_INDEX_2 This is macro DRV_ADC_INDEX_2.
DRV_ADC_INDEX_COUNT Number of valid ADC driver indices.
DRV_ADC_INSTANCES_NUMBER Sets up the maximum number of hardware instances that
can be supported.
DRV_ADC_INTERNAL_BUFFER_SIZE Define the internal buffer size.
DRV_ADC_INTERRUPT_MODE Controls operation of the driver in the interrupt or polled
mode.
DRV_ADC_INTERRUPT_SOURCE Defines the interrupt source of the static driver.
DRV_ADC_PERIPHERAL_ID ADC PLIB ID Selection
DRV_ADC_POWER_STATE Controls the power state of the ADC.
DRV_ADC_RESULT_FORMAT Defines the data output format.
DRV_ADC_SAMPLES_PER_INTERRUPT Define the sample per interrupt.
DRV_ADC_STOP_ON_CONVERSION_ENABLE Enable the stop on conversion feature of the ADC.
DRV_ADC_VOLTAGE_REFERENCE Defines the voltage reference.
Client Core Configuration Functions
Name Description
DRV_ADC_ClientStatus Gets the current client-specific status the ADC driver.
DRV_ADC_Close Closes an opened-instance of the ADC driver.
DRV_ADC_InputsRegister Registers an input set with the driver for sampling.
DRV_ADC_Open Opens the specified ADC driver instance and returns a handle to it.
DRV_ADC_SamplesAvailable Identifies if any the ADC driver has any samples available to read.
DRV_ADC_Start Starts the ADC driver sampling and converting analog to digital values.
DRV_ADC_Stop Stops the ADC driver from sampling and converting analog to digital values.
5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library
5-204
Other Functions
Name Description
DRV_ADC_SampleMaxGet Gets the max sample value.
DRV_ADC_SampleMinGet Gets the min sample value.
DRV_ADC_SamplesRead Reads the converted sample data from the ADC driver.
DRV_ADC_SamplesReadLatest Reads the most recently converted sample data from the ADC driver.
System Interaction Functions
Name Description
DRV_ADC_Deinitialize Deinitializes the specified instance of the ADC driver module.
DRV_ADC_Initialize Initializes the ADC driver.
DRV_ADC_Reinitialize Reinitializes the ADC instance for the specified module ID.
DRV_ADC_Status Provides the current status of the ADC driver module.
DRV_ADC_Tasks Maintains the driver's state machine and implements its ISR.
Description
5.1.2.7.1 System Interaction Functions
5.1.2.7.1.1 DRV_ADC_Deinitialize Function
C
void DRV_ADC_Deinitialize(
SYS_MODULE_OBJ object
);
Description
This function deinitializes the specified instance of the ADC driver module, disabling its operation (and any hardware).
Invalidates all the internal data.
Preconditions
The DRV_ADC_Initialize function should have been called before calling this function.
Parameters
Parameters Description
object Driver object handle, returned from DRV_ADC_Initialize
Returns
None.
Remarks
Once the Initialize operation has been called, the Deinitialize operation must be called before the Initialize operation can be
called again.
This function will NEVER block waiting for hardware. If the operation requires time to allow the hardware to complete, this will be
reported by the DRV_ADC_Status operation. The system has to use DRV_ADC_Status to find out when the module is in the
ready state.
5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library
5-205
Example
SYS_MODULE_OBJ object; // Returned from DRV_ADC_Initialize
SYS_STATUS status;
DRV_ADC_Deinitialize(object);
status = DRV_ADC_Status(object);
if (SYS_MODULE_DEINITIALIZED == status)
{
// Check again later if you need to know
// when the driver is deinitialized.
}
5.1.2.7.1.2 DRV_ADC_Initialize Function
C
SYS_MODULE_OBJ DRV_ADC_Initialize(
const SYS_MODULE_INDEX drvIndex,
const SYS_MODULE_INIT * const init
);
Description
This function initializes the ADC driver, making it ready for clients to open and use it.
Preconditions
None.
Parameters
Parameters Description
drvIndex Index for the driver instance to be initialized
init Pointer to a data structure containing any data necessary to initialize the driver.
This pointer may be null if no data is required because static overrides have been
provided.
Returns
If successful, returns a valid handle to a driver instance object. Otherwise, it returns SYS_MODULE_OBJ_INVALID.
Remarks
This function must be called before any other ADC function is called.
This function should only be called once during system initialization unless DRV_ADC_Deinitialize is called to deinitialize the
driver instance.
This function will NEVER block for hardware access. If the operation requires time to allow the hardware to re-initialize, it will be
reported by the DRV_ADC_Status operation. The system must use DRV_ADC_Status to find out when the driver is in the ready
state.
Build configuration options may be used to staticaly override options in the "init" sructure and will take precedance over
initialization data passed using this function.
Example
DRV_ADC_INIT init;
SYS_MODULE_OBJ objectHandle;
// Populate the init structure
init.moduleInit.value = SYS_MODULE_POWER_RUN_FULL;
init.adcID = ADC_ID_1;
5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library
5-206
init.initFlags = DRV_ADC_AUTO_SAMPLING;
init.clockFrequency = 4000000; // 4MHz
init.acquisitionTime = ADC_ACQUISITION_TIME_15_TAD;
init.voltageReference = ADC_VREF_POS_TO_VDD_VREF_NEG_TO_VSS;
init.conversionClockPrescaler = ADC_CONV_CLOCK_5_TCY;
init.conversionClockSource = ADC_CLOCK_SRC_INTERNAL_RC;
init.conversionTriggerSource = ADC_CONVERSION_TRIGGER_INTERNAL_COUNT;
init.samplesPerInterrupt = ADC_SAMPLE_PER_INTERRUPT_AT_EACH_SAMPLE;
init.resultFormat = ADC_RESULT_FORMAT_INTEGER_16BIT;
init.analogInput = ADC_INPUT_AN2
init.interruptSource = INT_SOURCE_ADC_1;
// Initialize the ADC driver
objectHandle = DRV_ADC_Initialize(DRV_ADC_INDEX_0, (SYS_MODULE_INIT*)&init);
if (SYS_MODULE_OBJ_INVALID == objectHandle)
{
// Handle error
}
5.1.2.7.1.3 DRV_ADC_Reinitialize Function
C
void DRV_ADC_Reinitialize(
SYS_MODULE_OBJ object,
const SYS_MODULE_INIT * const init
);
Description
This function reinitializes and refreshes the hardware for the index instance of the ADC module using the hardware initialization
given data. It does not clear or reinitialize internal data structures (although it may change the value of a few appropriate data
items necessary to manage the new hardware state).
Preconditions
The DRV_ADC_Initialize function should have been called before calling this function.
Parameters
Parameters Description
object Driver object handle, returned from the DRV_ADC_Initialize
Returns
None.
Example
DRV_ADC_INIT init;
SYS_MODULE_OBJ objectHandle; // Returned from DRV_ADC_Initialize
SYS_STATUS adcStatus;
// Populate the init structure
init.moduleInit.value = SYS_MODULE_POWER_RUN_FULL;
init.adcID = ADC_ID_1;
init.initFlags = DRV_ADC_AUTO_SAMPLING;
init.clockFrequency = 4000000; // 4MHz
init.acquisitionTime = ADC_ACQUISITION_TIME_15_TAD;
init.voltageReference = ADC_VREF_POS_TO_VDD_VREF_NEG_TO_VSS;
init.conversionClockPrescaler = ADC_CONV_CLOCK_5_TCY;
init.conversionClockSource = ADC_CLOCK_SRC_INTERNAL_RC;
init.conversionTriggerSource = ADC_CONVERSION_TRIGGER_INTERNAL_COUNT;
init.samplesPerInterrupt = ADC_SAMPLE_PER_INTERRUPT_AT_EACH_SAMPLE;
init.resultFormat = ADC_RESULT_FORMAT_INTEGER_16BIT;
init.analogInput = ADC_INPUT_AN2
init.interruptSource = INT_SOURCE_ADC_1;
5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library
5-207
// Reinitialize the ADC driver
DRV_ADC_Reinitialize(objectHandle, (SYS_MODULE_INIT*)&init);
// Check the status of the driver
adcStatus = DRV_ADC_Status(myAdcObj);
if (SYS_STATUS_BUSY == adcStatus)
{
// do something else and check back later
}
else if (SYS_STATUS_ERROR >= adcStatus)
{
// Handle error
}
Remarks: This function can be called multiple times to reinitialize the module.
This operation can be used to refresh any supported hardware registers as
specified by the initialization data or to change the power state of the
module.
This function will NEVER block for hardware access. If the operation requires
time to allow the hardware to reinitialize, it will be reported by the
DRV_ADC_Status operation. The system must use DRV_ADC_Status to find out
when the driver is in the ready state.
Build configuration options may be used to staticaly override options in the
"init" sructure and will take precedance over initialization data passed
using this function.
5.1.2.7.1.4 DRV_ADC_Status Function
C
SYS_STATUS DRV_ADC_Status(
SYS_MODULE_OBJ object
);
Description
This function provides the current status of the ADC driver module.
Preconditions
The DRV_ADC_Initialize function must have been called before calling this function.
Parameters
Parameters Description
object Driver object handle, returned from the DRV_ADC_Initialize
Returns
SYS_STATUS_READY - Indicates that the driver is busy with a previous system level operation and cannot start another
Remarks
Any value greater than SYS_STATUS_READY is also a normal running state in which the driver is ready to accept new
operations.
SYS_STATUS_BUSY - Indicates that the driver is busy with a previous system level operation and cannot start another
SYS_STATUS_ERROR - Indicates that the driver is in an error state
Any value less than SYS_STATUS_ERROR is also an error state.
SYS_MODULE_DEINITIALIZED - Indicates that the driver has been deinitialized
This value is less than SYS_STATUS_ERROR
5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library
5-208
The this operation can be used to determine when any of the driver's module level operations has completed.
If the status operation returns SYS_STATUS_BUSY, the a previous operation has not yet completed. Once the status operation
returns SYS_STATUS_READY, any previous operations have completed.
The value of SYS_STATUS_ERROR is negative (-1). Any value less than that is also an error state.
This function will NEVER block waiting for hardware.
If the Status operation returns an error value, the error may be cleared by calling the reinitialize operation. If that fails, the
deinitialize operation will need to be called, followed by the initialize operation to return to normal operations.
Example
SYS_MODULE_OBJ object; // Returned from DRV_TMR_Initialize
SYS_STATUS status;
status = DRV_ADC_Status(object);
else if (SYS_STATUS_ERROR >= status)
{
// Handle error
}
5.1.2.7.1.5 DRV_ADC_Tasks Function
C
void DRV_ADC_Tasks(
SYS_MODULE_OBJ object
);
Description
This function is used to maintain the driver's internal state machine and implement its ISR for interrupt-driven implementations.
Preconditions
The DRV_ADC_Initialize function must have been called for the specified ADC driver instance.
Parameters
Parameters Description
object Object handle for the specified driver instance (returned from DRV_ADC_Initialize)
Returns
None
Remarks
This function is normally not called directly by an application. It is called by the system's Tasks function (SYS_Tasks) or by the
apropriate raw ISR.
This function may excute in an ISR context and will never block or access any resources that may cause it to block.
Example
SYS_MODULE_OBJ object; // Returned from DRV_ADC_Initialize
while (true)
{
DRV_ADC_Tasks (object);
// Do other tasks
}
5.1.2.7.2 Client Core Configuration Functions
5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library
5-209
5.1.2.7.2.1 DRV_ADC_ClientStatus Function
C
DRV_ADC_CLIENT_STATUS DRV_ADC_ClientStatus(
DRV_HANDLE handle
);
Description
This function gets the client-specfic status of the ADC driver associated with the given handle.
Preconditions
The DRV_ADC_Initialize function must have been called.
DRV_ADC_Open must have been called to obtain a valid opened device handle.
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open function
Returns
A DRV_ADC_CLIENT_STATUS value describing the current status of the driver.
Remarks
This function will not block for hardware access and will immediately return the current status.
Example
DRV_HANDLE handle; // Returned from DRV_ADC_Open
DRV_ADC_CLIENT_STATUS status;
status = DRV_ADC_ClientStatus(handle);
if(DRV_ADC_CLIENT_STATUS_ERROR >= status)
{
// Handle the error
}
5.1.2.7.2.2 DRV_ADC_Close Function
C
void DRV_ADC_Close(
DRV_HANDLE handle
);
Description
This function closes an opened-instance of the ADC driver, invalidating the handle.
Preconditions
The DRV_ADC_Initialize function must have been called for the specified ADC driver instance.
DRV_ADC_Open must have been called to obtain a valid opened device handle.
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open function
Returns
None
5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library
5-210
Remarks
After calling this function, the handle passed in "handle" must not be used with any of the remaining driver functions. A new
handle must be obtained by calling DRV_ADC_Open before the caller may use the driver again.
If DRV_IO_INTENT_BLOCKING was requested and the driver was built appropriately to support blocking behavior call may
block until the operation is complete.
If DRV_IO_INTENT_NON_BLOCKING request the driver client can call the DRV_ADC_Status operation to find out when the
module is in the ready state (the handle is no longer valid).
Usually there is no need for the driver client to verify that the Close operation has completed.
Example
DRV_HANDLE handle; // Returned from DRV_ADC_Open
DRV_ADC_Close(handle);
5.1.2.7.2.3 DRV_ADC_InputsRegister Function
C
void DRV_ADC_InputsRegister(
DRV_HANDLE handle,
uint32_t inputsMask
);
Description
This function registers an input set with the driver for sampling.
Preconditions
The DRV_ADC_Initialize function must have been called for the specified ADC device instance and the DRV_ADC_Status must
have returned SYS_STATUS_READY.
DRV_ADC_Open must have been called to obtain a valid opened device handle.
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open function
inputsMask Mask bits recognising the various Analog Channels
Returns
None.
Remarks
None.
Example
DRV_HANDLE handle; // Returned from DRV_ADC_Open
DRV_ADC_InputsRegister (handle, ADC_INPUT_AN2|ADC_INPUT_AN3);
5.1.2.7.2.4 DRV_ADC_Open Function
C
DRV_HANDLE DRV_ADC_Open(
const SYS_MODULE_INDEX drvIndex,
const DRV_IO_INTENT intent
);
5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library
5-211
Description
This function opens the specified ADC driver instance and provides a handle that must be provided to all other client-level
operations to identify the caller and the instance of the driver.
Preconditions
The DRV_ADC_Initialize function must have been called before calling this function.
Parameters
Parameters Description
drvIndex Identifier for the object instance to be opened
intent Zero or more of the values from the enumeration DRV_IO_INTENT "ORed"
together to indicate the intended use of the driver
Returns
If successful, the function returns a valid open-instance handle (a number identifying both the caller and the module instance).
If an error occurs, the return value is DRV_HANDLE_INVALID.
Remarks
The handle returned is valid until the DRV_ADC_Close function is called.
This function will NEVER block waiting for hardware.
If the DRV_IO_INTENT_BLOCKING is requested and the driver was built appropriately to support blocking behavior, other
client-level operations may block waiting on hardware until they are complete.
If DRV_IO_INTENT_NON_BLOCKING is requested the driver client can call the DRV_ADC_ClientStatus operation to find out
when the module is in the ready state.
If the requested intent flags are not supported, the function will return DRV_HANDLE_INVALID.
Example
DRV_HANDLE handle;
handle = DRV_ADC_Open(DRV_ADC_INDEX_0, DRV_IO_INTENT_EXCLUSIVE);
if (DRV_HANDLE_INVALID == handle)
{
// Unable to open the driver
}
5.1.2.7.2.5 DRV_ADC_SamplesAvailable Function
C
bool DRV_ADC_SamplesAvailable(
DRV_HANDLE handle
);
Description
This function identifies if any the ADC driver has any samples available to read.
Preconditions
The DRV_ADC_Initialize function must have been called.
DRV_ADC_Open must have been called to obtain a valid opened device handle.
The desired analog input set must have been selected by calling DRV_ADC_InputsRegister.
DRV_ADC_Start must have been called to start the driver sampling and converting analog input samples to digital values.
5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library
5-212
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open function
Returns
• true - If one or more samples are available for the registered input set
• false - If no samples are available
Remarks
None.
Example
DRV_HANDLE handle; // Returned from DRV_ADC_Open
DRV_ADC_SAMPLE buffer;
// An input set must have been registered and the ADC started.
if (DRV_ADC_SamplesAvailable(handle))
{
DRV_ADC_SamplesRead(handle, &buffer, sizeof(buffer));
}
5.1.2.7.2.6 DRV_ADC_Start Function
C
void DRV_ADC_Start(
DRV_HANDLE handle
);
Description
This function starts the ADC driver sampling the selected analog inputs and converting the samples to digital values.
Preconditions
The DRV_ADC_Initialize function must have been called.
DRV_ADC_Open must have been called to obtain a valid opened device handle.
The desired analog input set must have been selected by calling DRV_ADC_InputsRegister.
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open function
Returns
None.
Remarks
Call DRV_ADC_SamplesAvailable to find out when one or more samples is available.
Example
DRV_HANDLE handle; // Returned from DRV_ADC_Open
// Use DRV_ADC_InputsRegister to register the desired inputs.
DRV_ADC_Start(handle);
5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library
5-213
5.1.2.7.2.7 DRV_ADC_Stop Function
C
void DRV_ADC_Stop(
DRV_HANDLE handle
);
Description
This function stops the ADC driver from sampling analog inputs and converting the samples to digital values.
Preconditions
The DRV_ADC_Initialize function must have been called.
DRV_ADC_Open must have been called to obtain a valid opened device handle.
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open function
Returns
None.
Remarks
Call DRV_ADC_Start to restart sampling and conversion of analog inputs to digital values.
Example
DRV_HANDLE handle; // Returned from DRV_ADC_Open
DRV_ADC_Stop(handle);
5.1.2.7.3 Other Functions
5.1.2.7.3.1 DRV_ADC_SampleMaxGet Function
C
ADC_SAMPLE DRV_ADC_SampleMaxGet(
DRV_HANDLE handle
);
Description
This function returns the max sample value.
Preconditions
The DRV_ADC_Initialize function must have been called.
DRV_ADC_Open must have been called to obtain a valid opened device handle.
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open function
Returns
Max sample value.
5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library
5-214
Remarks
None
Example
DRV_HANDLE handle; // Returned from DRV_ADC_Open
ADC_SAMPLE maxValue, minValue;
maxValue = DRV_ADC_SampleMaxGet(handle);
minValue = DRV_ADC_SampleMinGet(handle);
adcRange = maxValue - minValue;
5.1.2.7.3.2 DRV_ADC_SampleMinGet Function
C
ADC_SAMPLE DRV_ADC_SampleMinGet(
DRV_HANDLE handle
);
Description
This function returns the min sample value.
Preconditions
The DRV_ADC_Initialize function must have been called.
DRV_ADC_Open must have been called to obtain a valid opened device handle.
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open function
Returns
Min sample value.
Remarks
None
Example
DRV_HANDLE handle; // Returned from DRV_ADC_Open
ADC_SAMPLE maxValue, minValue;
maxValue = DRV_ADC_SampleMaxGet(handle);
minValue = DRV_ADC_SampleMinGet(handle);
adcRange = maxValue - minValue;
5.1.2.7.3.3 DRV_ADC_SamplesRead Function
C
unsigned short DRV_ADC_SamplesRead(
DRV_HANDLE handle,
ADC_SAMPLE * buffer,
unsigned short bufferSize
);
Description
This function reads converted sample data from the ADC driver into the given buffer. How many samples depends on how many
samples are available and on the relative sizes of the samples and the buffer passed in.
Zero (0) samples are copied if the bufferSize is less than the size of a complete set of samples for the registered inputs.
5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library
5-215
N sets of samples where the bufferSize / size of a complete set of samples = N, unless less than N samples are currently
available. Then, the number of samples currently available are copied.
Preconditions
The DRV_ADC_Initialize function must have been called.
DRV_ADC_Open must have been called to obtain a valid opened device handle.
The desired analog input set must have been selected by calling DRV_ADC_InputsRegister.
DRV_ADC_Start must have been called to start the driver sampling and converting analog input samples to digital values.
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open function
buffer A pointer to the buffer to where the sample data will be copied
bufferSize Size of the buffer (in bytes)
Returns
Number of bytes of sample data copied to the specified buffer.
Remarks
The DRV_ADC_SamplesAvailable function can be used to determine if any sample data is available.
Calling this function removes the samples from the driver's internal buffer queue of samples.
Example
DRV_HANDLE handle; // Returned from DRV_ADC_Open
ADC_SAMPLE buffer;
// An input set must have been registered and the ADC started.
if (DRV_ADC_SamplesAvailable(handle))
{
DRV_ADC_SamplesRead(handle, &buffer, sizeof(buffer));
}
5.1.2.7.3.4 DRV_ADC_SamplesReadLatest Function
C
unsigned short DRV_ADC_SamplesReadLatest(
DRV_HANDLE handle,
ADC_SAMPLE * buffer,
unsigned short bufferSize
);
Description
This function reads only the most recenly converted sample data from the ADC driver into the given buffer. Only the data for a
single set of samples for the registerd inputs is copied to the caller's buffer. If the buffer size is less than the size of a complete
set of samples for the registerd inputs, no data is copied to the caller's buffer. Also, no sample data is copied to the caller's buffer
if no sample data is currently available.
Preconditions
The DRV_ADC_Initialize function must have been called.
DRV_ADC_Open must have been called to obtain a valid opened device handle.
The desired analog input set must have been selected by calling DRV_ADC_InputsRegister.
5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library
5-216
DRV_ADC_Start must have been called to start the driver sampling and converting analog input samples to digital values.
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open function
buffer A pointer to the buffer to where the sample data will be copied
bufferSize Size of the buffer (in bytes)
Returns
Number of bytes of sample data copied to the specified buffer.
Remarks
The DRV_ADC_SamplesAvailable function can be used to determine if any sample data is available.
This function does not remove any data from the driver's internal buffer queue of sample data.
Example
DRV_HANDLE handle; // Returned from DRV_ADC_Open
ADC_SAMPLE buffer;
// An input set must have been registered and the ADC started.
if (DRV_ADC_SamplesAvailable(handle))
{
DRV_ADC_SamplesReadLatest(handle, &buffer, sizeof(buffer));
}
5.1.2.7.4 Data Types and Constants
5.1.2.7.4.1 DRV_ADC_CLIENT_STATUS Enumeration
C
typedef enum {
DRV_ADC_CLIENT_STATUS_STARTED,
DRV_ADC_CLIENT_STATUS_STOPPED,
DRV_ADC_CLIENT_STATUS_READY,
DRV_ADC_CLIENT_STATUS_BUSY,
DRV_ADC_CLIENT_STATUS_INVALID,
DRV_ADC_CLIENT_STATUS_OVERFLOW,
DRV_ADC_CLIENT_STATUS_BUFFER_TOO_SMALL
} DRV_ADC_CLIENT_STATUS;
Description
ADC Client Status
This enumeration defines the client-specific status codes of the ADC driver.
Members
Members Description
DRV_ADC_CLIENT_STATUS_STARTED ADC Started
DRV_ADC_CLIENT_STATUS_STOPPED stopped on error
DRV_ADC_CLIENT_STATUS_READY Driver OK, ready for client operations
DRV_ADC_CLIENT_STATUS_BUSY An operation is currently in progress
DRV_ADC_CLIENT_STATUS_INVALID Client in an invalid (or un-opened) state
DRV_ADC_CLIENT_STATUS_OVERFLOW Driver Overflowed
5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library
5-217
DRV_ADC_CLIENT_STATUS_BUFFER_TOO_SMALL Input Set Read Buffer Too Small
Remarks
Returned by the DRV_ADC_ClientStatus function.
5.1.2.7.4.2 DRV_ADC_INIT Structure
C
typedef struct {
SYS_MODULE_INIT moduleInit;
ADC_MODULE_ID adcId;
DRV_ADC_INIT_FLAGS initFlags;
uint32_t clockFrequency;
ADC_ACQUISITION_TIME acquisitionTime;
ADC_VOLTAGE_REFERENCE voltageReference;
ADC_CONVERSION_CLOCK conversionClockPrescaler;
ADC_CLOCK_SOURCE conversionClockSource;
ADC_CONVERSION_TRIGGER_SOURCE conversionTriggerSource;
ADC_SAMPLES_PER_INTERRUPT samplesPerInterrupt;
ADC_RESULT_FORMAT resultFormat;
ADC_INPUTS_POSITIVE analogInput;
INT_SOURCE interruptSource;
} DRV_ADC_INIT;
Description
ADC Driver Initialization Data
This structure defines the data required to initialize or reinitialize the ADC driver.
Members
Members Description
SYS_MODULE_INIT moduleInit; System module initialization
ADC_MODULE_ID adcId; Identifies timer hardware module (PLIB-level) ID
DRV_ADC_INIT_FLAGS initFlags; Initialization Flags
uint32_t clockFrequency; Clock Frequency
ADC_ACQUISITION_TIME acquisitionTime; Acquisition Time
ADC_VOLTAGE_REFERENCE
voltageReference;
Voltage Reference Selection
ADC_CONVERSION_CLOCK
conversionClockPrescaler;
Clock Setup for the Conversion
ADC_CLOCK_SOURCE
conversionClockSource;
Clock Source for Conversion
ADC_CONVERSION_TRIGGER_SOURCE
conversionTriggerSource;
Conversion Trigger Source
ADC_SAMPLES_PER_INTERRUPT
samplesPerInterrupt;
Samples Per Interrupt valid values = 0- 15
ADC_RESULT_FORMAT resultFormat; Result Format
ADC_INPUTS_POSITIVE analogInput; Input Channel to convert
INT_SOURCE interruptSource; Interrupt Source for the module
Remarks
Not all init features are available for all devices. Refer to the specific data sheet to determine availability.
5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library
5-218
5.1.2.7.4.3 DRV_ADC_INIT_FLAGS Enumeration
C
typedef enum {
DRV_ADC_STOP_CONVERSION_ON_INTERRUPT,
DRV_ADC_ALTERNATE_INPUT_SAMPLING,
DRV_ADC_AUTO_SAMPLING,
DRV_ADC_MANUAL_SAMPLING
} DRV_ADC_INIT_FLAGS;
Description
ADC Initialization Flags
This data type identifies the initialization flags of the ADC module.
Members
Members Description
DRV_ADC_STOP_CONVERSION_ON_INTERRUPT Stops the conversion on the interrupt
DRV_ADC_ALTERNATE_INPUT_SAMPLING Alternate Input Sampling
DRV_ADC_AUTO_SAMPLING Begin sampling automaticaly after previous conversion
DRV_ADC_MANUAL_SAMPLING Manual Sampling
Remarks
Not all modes are available on all devices. Refer to the specific data sheet to determine availability.
5.1.2.7.4.4 DRV_ADC_ACQUISITION_TIME Macro
C
#define DRV_ADC_ACQUISITION_TIME ADC_ACQUISITION_TIME_4_TAD
Description
ADC Acquisition Time
This macro defines the acquistition time of the ADC driver. This provides static override of the dynamic selection of the
acquisition time. If this macro is defined, this will be used for setting up the acquisition time and not the acquisition time value
provided by DRV_ADC_INIT.
Remarks
None.
5.1.2.7.4.5 DRV_ADC_ALTERNATE_INPUT_SAMPLING_ENABLE Macro
C
#define DRV_ADC_ALTERNATE_INPUT_SAMPLING_ENABLE false
Description
ADC Alternate Input Sampling Enable
This macro enables the alternate input sampling feature of the ADC. This macro can take the following values:
• true - Enables the alternate Input sampling feature of the ADC
• false - Disables the alternate Input sampling feature of the ADC
• DRV_CONFIG_NOT_SUPPORTED - When the feature is not supported on the instance
5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library
5-219
Remarks
None.
5.1.2.7.4.6 DRV_ADC_ANALOG_INPUT Macro
C
#define DRV_ADC_ANALOG_INPUT ADC_INPUT_AN2
Description
ADC Analog input channel
This macro defines the analog input channel for the ADC driver. This provides static override of the dynamic selection of the
analog input. If this macro is defined, this will be used for setting up the analog input and not the analog input value provided by
DRV_ADC_INIT.
Remarks
None.
5.1.2.7.4.7 DRV_ADC_AUTO_SAMPLING_ENABLE Macro
C
#define DRV_ADC_AUTO_SAMPLING_ENABLE true
Description
ADC Auto Sampling Enable
This macro enables the auto-sampling feature of the ADC. This macro can take the following values:
• true - Enables the auto-sampling feature of the ADC
• false - Disables the auto-sampling feature of the ADC
• DRV_CONFIG_NOT_SUPPORTED - When the feature is not supported on the instance
Remarks
None.
5.1.2.7.4.8 DRV_ADC_CLIENTS_NUMBER Macro
C
#define DRV_ADC_CLIENTS_NUMBER 1
Description
ADC Maximum Number of Clients
This definition selectd the maximum number of clients that the ADC driver can support at run time.
Remarks
None.
5.1.2.7.4.9 DRV_ADC_CONVERSION_CLOCK_PRESCALER Macro
C
#define DRV_ADC_CONVERSION_CLOCK_PRESCALER ADC_CONV_CLOCK_4_TCY
5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library
5-220
Description
ADC Conversion Clock
This macro defines the conversion clock for the ADC driver. This provides static override of the dynamic selection of the
conversion clock. If this macro is defined, this will be used for setting up the conversion clock and not the conversion clock value
provided by DRV_ADC_INIT.
Remarks
None.
5.1.2.7.4.10 DRV_ADC_CONVERSION_CLOCK_SOURCE Macro
C
#define DRV_ADC_CONVERSION_CLOCK_SOURCE ADC_CLOCK_SRC_SYSTEM_CLOCK
Description
ADC Conversion Clock Source
This macro defines the conversion clock source for the ADC driver. This provides static override of the dynamic selection of the
conversion clock source. If this macro is defined, this will be used for setting up the conversion clock source and not the
conversion clock source value provided by DRV_ADC_INIT.
Remarks
None.
5.1.2.7.4.11 DRV_ADC_CONVERSION_TRIGGER_SOURCE Macro
C
#define DRV_ADC_CONVERSION_TRIGGER_SOURCE ADC_CONVERSION_TRIGGER_INTERNAL_COUNT
Description
Conversion Trigger Source
This macro defines the conversion trigger source for the ADC driver. This provides static override of the dynamic selection of the
conversion trigger source. If this macro is defined, this will be used for setting up the conversion trigger source and not the
conversion trigger source value provided by DRV_ADC_INIT.
Remarks
None.
5.1.2.7.4.12 DRV_ADC_INDEX Macro
C
#define DRV_ADC_INDEX DRV_ADC_INDEX_0
Description
ADC Static Index Selection
ADC static index selection for the driver object reference.
Remarks
This index is required to make a reference to the driver object.
5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library
5-221
5.1.2.7.4.13 DRV_ADC_INDEX_0 Macro
C
#define DRV_ADC_INDEX_0 0
Description
Driver ADC Module Index Numbers
These constants provide ADC driver index definitions.
Remarks
These constants should be used in place of hard-coded numeric literals.
These values should be passed into the DRV_ADC_Initialize function to identify the driver instance in use.
5.1.2.7.4.14 DRV_ADC_INDEX_1 Macro
C
#define DRV_ADC_INDEX_1 1
Description
This is macro DRV_ADC_INDEX_1.
5.1.2.7.4.15 DRV_ADC_INDEX_2 Macro
C
#define DRV_ADC_INDEX_2 2
Description
This is macro DRV_ADC_INDEX_2.
5.1.2.7.4.16 DRV_ADC_INDEX_COUNT Macro
C
#define DRV_ADC_INDEX_COUNT _ADC_EXISTS
Description
Driver ADC Driver Module Index Count
This constant identifies ADC driver index definitions.
Remarks
This constant should be used in place of hard-coded numeric literals.
This value is device-specific.
5.1.2.7.4.17 DRV_ADC_INSTANCES_NUMBER Macro
C
#define DRV_ADC_INSTANCES_NUMBER 1
Description
ADC hardware instance configuration
This macro sets up the maximum number of hardware instances that can be supported.
5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library
5-222
Remarks
None.
5.1.2.7.4.18 DRV_ADC_INTERNAL_BUFFER_SIZE Macro
C
#define DRV_ADC_INTERNAL_BUFFER_SIZE 2
Description
ADC Internal buffer size
This macro defines the internal buffer size.
Remarks
None.
5.1.2.7.4.19 DRV_ADC_INTERRUPT_MODE Macro
C
#define DRV_ADC_INTERRUPT_MODE true
Description
ADC Interrupt And Polled Mode Operation Control
This macro controls the operation of the driver in the interrupt mode of operation. The possible values of this macro are:
• true - Select if interrupt mode of adc operation is desired
• false - Select if polling mode of adc operation is desired
Not defining this option to true or false will result in a build error.
Remarks
None.
5.1.2.7.4.20 DRV_ADC_INTERRUPT_SOURCE Macro
C
#define DRV_ADC_INTERRUPT_SOURCE PLIB_INT_SOURCE_ADC_1
Description
ADC Interrupt Source
Macro to define the interrupt source of the static driver.
Remarks
Refer to the Interrupt Peripheral Library document for more information on the PLIB_INT_SOURCE enumeration.
5.1.2.7.4.21 DRV_ADC_PERIPHERAL_ID Macro
C
#define DRV_ADC_PERIPHERAL_ID ADC_ID_1
Description
ADC PLIB ID Selection
5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library
5-223
This macro selects the ADC PLIB ID Selection. This is an intialization override of the adcID member of the intialization
configuration.
Remarks
None.
5.1.2.7.4.22 DRV_ADC_POWER_STATE Macro
C
#define DRV_ADC_POWER_STATE SYS_MODULE_POWER_IDLE_STOP
Description
ADC power state configuration
This macro controls the power state of the ADC.
Remarks
This feature may not be available in the device or the ADC module selected.
5.1.2.7.4.23 DRV_ADC_RESULT_FORMAT Macro
C
#define DRV_ADC_RESULT_FORMAT ADC_RESULT_FORMAT_INTEGER_16BIT
Description
ADC Data Output Format
This macro defines the data output format for the ADC driver. This provides static override of the dynamic selection of the data
output format. If this macro is defined, this will be used for setting up the data output format and not the data output format value
provided by DRV_ADC_INIT.
Remarks
None.
5.1.2.7.4.24 DRV_ADC_SAMPLES_PER_INTERRUPT Macro
C
#define DRV_ADC_SAMPLES_PER_INTERRUPT 2
Description
Samples per Interrupt
This macro defines the samples per interrupt of the ADC driver. This provides static override of the dynamic selection of the
sample per interrupt. If this macro is defined, this will be used for setting up the samples per interrupt and not the samples per
interrupt value provided by DRV_ADC_INIT.
Remarks
Select this size based on the device available and the number of samples that are required to form a set.
5.1.2.7.4.25 DRV_ADC_STOP_ON_CONVERSION_ENABLE Macro
C
#define DRV_ADC_STOP_ON_CONVERSION_ENABLE false
5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library
5-224
Description
ADC Stop on conversion Enable
This macro enables the stop on conversion feature of the ADC. This macro can take the following values:
• true - Enables the ADC to stop on conversion
• false - Disables the ADC to stop on conversion
• DRV_CONFIG_NOT_SUPPORTED - When the feature is not supported on the instance
Remarks
None.
5.1.2.7.4.26 DRV_ADC_VOLTAGE_REFERENCE Macro
C
#define DRV_ADC_VOLTAGE_REFERENCE ADC_VREF_POS_TO_VDD_VREF_NEG_TO_VSS
Description
ADC Voltage Reference
This macro defines the voltage reference of the ADC driver. This provides static override of the dynamic selection of the voltage
reference. If this macro is defined, this will be used for setting up the voltage reference and not the voltage reference value
provided by DRV_ADC_INIT.
Remarks
None.
5.1.2.8 Files
Files
Name Description
drv_adc.h ADC Driver interface definition.
Description
5.1.2.8.1 drv_adc.h
ADC Driver Interface Definition
The ADC device driver provides a simple interface to manage the ADC modules on Microchip microcontrollers. This file defines
the interface definition for the ADC driver.
Enumerations
Name Description
DRV_ADC_CLIENT_STATUS Defines the client-specific status of the ADC driver.
DRV_ADC_INIT_FLAGS Identifies the initialization flags of the ADC module.
5.1 Driver Library Help MPLAB Harmony Help ADC Driver Library
5-225
Functions
Name Description
DRV_ADC_ClientStatus Gets the current client-specific status the ADC driver.
DRV_ADC_Close Closes an opened-instance of the ADC driver.
DRV_ADC_Deinitialize Deinitializes the specified instance of the ADC driver module.
DRV_ADC_Initialize Initializes the ADC driver.
DRV_ADC_InputsRegister Registers an input set with the driver for sampling.
DRV_ADC_Open Opens the specified ADC driver instance and returns a handle to it.
DRV_ADC_Reinitialize Reinitializes the ADC instance for the specified module ID.
DRV_ADC_SampleMaxGet Gets the max sample value.
DRV_ADC_SampleMinGet Gets the min sample value.
DRV_ADC_SamplesAvailable Identifies if any the ADC driver has any samples available to read.
DRV_ADC_SamplesRead Reads the converted sample data from the ADC driver.
DRV_ADC_SamplesReadLatest Reads the most recently converted sample data from the ADC driver.
DRV_ADC_Start Starts the ADC driver sampling and converting analog to digital values.
DRV_ADC_Status Provides the current status of the ADC driver module.
DRV_ADC_Stop Stops the ADC driver from sampling and converting analog to digital values.
DRV_ADC_Tasks Maintains the driver's state machine and implements its ISR.
Macros
Name Description
DRV_ADC_INDEX_0 ADC driver index definitions.
DRV_ADC_INDEX_1 This is macro DRV_ADC_INDEX_1.
DRV_ADC_INDEX_2 This is macro DRV_ADC_INDEX_2.
DRV_ADC_INDEX_COUNT Number of valid ADC driver indices.
Structures
Name Description
DRV_ADC_INIT Defines the data required to initialize or reinitialize the ADC driver.
File Name
drv_adc.h
Company
Microchip Technology Inc.
5.1.3 Ethernet MAC Driver Library
5.1.3.1 Introduction
Ethernet (Media Access) Controller Driver Library
for
5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library
5-226
Microchip Microcontrollers
This library provides a driver-level abstraction of the on-chip Ethernet Controller found on many PIC32 devices.
The "Host-To-Network" layer of a TCP/IP stack organization covers the Data Link and Physical Layers of the standard OSI stack.
The Ethernet Controller provides the Data Link or Media Access Control Layer, in addition to other functions discussed below.
An external Ethernet "PHY" provides the Physical layer, providing conversion between the digital and analog.
Description
The PIC32 Ethernet Controller is a bus master module that interfaces with an off-chip PHY in order to implement a complete
Ethernet node in a system. The following are some of the key features of this module:
• Supports 10/100 Ethernet
• Full-Duplex and Half-Duplex operation
• Broadcast, Multicast and Unicast packets
• Manual and automatic flow control
• Supports Auto-MDIX enabled PHYs
• Reduced Media Independent Interface (RMII) and Media Independent Interface (MII) PHY data interfaces
• Performance statistics metrics in hardware.
• RAM descriptor based DMA operation for both receive and transmit path
• Fully configurable interrupts
• Configurable receive packet filtering using:
• 64-bit Hash Table
• 64-byte Pattern Match
• Magic Packet™Filtering
• Runt Packet Detection and Filtering
• Supports Packet Payload Checksum calculation
• CRC Check
Support for the Serial Management Interface (SMI) (also known as the MIIM interface) is provided by the Ethernet PHY Driver
Library.
5.1.3.2 Release Notes
MPLAB Harmony Version: v0.70b Ethernet MAC Library Version : 7.10 Release Date: 18Nov2013
New This Release:
This is the first release of the library. The interface can change in the beta and\or 1.0 release.
Known Issues:
Nothing to report in this release.
5.1.3.3 SW License Agreement
(c) 2013 Microchip Technology Inc.
Microchip licenses this software to you solely for use with Microchip products. The software is owned by Microchip and its
5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library
5-227
licensors, and is protected under applicable copyright laws. All rights reserved.
SOFTWARE IS PROVIDED "AS IS" MICROCHIP EXPRESSLY DISCLAIMS ANY WARRANTY OF ANY KIND, WHETHER
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL MICROCHIP BE LIABLE FOR
ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, HARM TO
YOUR EQUIPMENT, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS
BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR
CONTRIBUTION, OR OTHER SIMILAR COSTS.
To the fullest extent allowed by law, Microchip and its licensors liability shall not exceed the amount of fees, if any, that you have
paid directly to Microchip to use this software.
MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE TERMS.
5.1.3.4 Using the Library
This topic describes the basic architecture of the Ethernet MAC Driver Library and provides information and examples on how to
use it.
Interface Header File: drv_ethmac.h
The interface to the Ethernet MAC library is defined in the "drv_ethmac.h" header file. This file is included by the "drv_ethmac.h"
file. Any C language source (.c) file that uses the Ethernet MAC Driver Library should include "drv.h".
Library File:
The Ethernet MAC Driver Library archive (.a) file is installed with MPLAB Harmony.
Please refer to the MPLAB Harmony Overview for how the library interacts with the framework.
5.1.3.4.1 Abstraction Model
The Ethernet Controller provides the modules needed to implement a 10/100 Mbps Ethernet node using an external Ethernet
PHY chip. The PHY chip provides a digital-analog interface as part of the Physical Layer and the controller provides the Media
Access Controller (MAC) layer above the PHY.
As shown in Figure 1, the Ethernet Controller consists of the following modules:
• Media Access Control (MAC) block: Responsible for implementing the MAC functions of the Ethernet IEEE 802.3 Specification
• Flow Control (FC) block: Responsible for control of the transmission of PAUSE frames. (Reception of PAUSE frames is
handled within the MAC.)
• RX Filter (RXF) block: This module performs filtering on every receive packet to determine whether each packet should be
accepted or rejected
• TX DMA/TX Buffer Management Engine: The TX DMA and TX Buffer Management engines perform data transfers from the
memory (using descriptor tables) to the MAC Transmit Interface
• RX DMA/RX Buffer Management Engine: The RX DMA and RX Buffer Management engines transfer receive packets from the
MAC to the memory (using descriptor tables)
5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library
5-228
Figure 1: Ethernet Controller Block Diagram
For completeness, we also need to look at the interface diagram of a representative Ethernet PHY. As shown in Figure 2, the
PHY has two interfaces, one for configuring and managing the PHY (SMI/MIIM) and another for transmit and receive data (RMII
or MII). The SMI/MIIM interface is the responsibility of the Ethernet PHY Driver Library. When setting up the Ethernet PHY this
library calls primitives from the Ethernet PHY Driver library. The RMII/MII interface is the responsibility of the Ethernet MAC
Driver Library (this library).
5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library
5-229
Figure 2: Ethernet PHY Interfaces
5.1.3.4.2 Library Overview
Refer to the section Driver Overview for how the driver operates in a system.
The library interface routines are divided into various sub-sections, each of sub-section addresses one of the blocks or the
overall operation of the Ethernet MAC Driver Library.
Library Interface Section Description
Client Level Functions PIC32MACOpen, PIC32MACClose, and PIC32MACSetup to support the
TCP/IP Stack. Plus link status and power options.
Get and Put Functions Get/Put functions for bytes, byte arrays, and Ethernet headers.
Base Address and Buffer Size Functions Base address and sizes for buffers.
Receive Functions Receive routines.
Transmit Functions Transmit routines.
Events Ethernet event support routines.
Other Functions Checksum support, memory copying, version support.
Data Types and Constants Typedefs and #defines.
5.1.3.4.3 MPLAB Harmony vs. Unified Stack Functions
The following is a cross-reference linking MPLAB Harmony functions with functions from the legacy TCP/IP Stack:
5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library
5-230
MPLAB Harmony Function: MCHP_tcpip_unified Function:
DRV_ETHMAC_BaseAddrTxGet
DRV_ETHMAC_RxPacketDiscard
DRV_ETHMAC_EventAck
DRV_ETHMAC_EventDeInit
DRV_ETHMAC_EventInit
DRV_ETHMAC_EventNotifyClear
DRV_ETHMAC_EventNotifyHandlerSet
DRV_ETHMAC_EventNotifySet
DRV_ETHMAC_EventPendingGet
DRV_ETHMAC_ByteArrayGet
DRV_ETHMAC_HeaderGet
DRV_ETHMAC_IPBufferChecksumCalc
DRV_ETHMAC_LinkCheck
DRV_ETHMAC_MemoryCopyIsDone
DRV_ETHMAC_PIC32MACClose
DRV_ETHMAC_PIC32MACOpen
DRV_ETHMAC_PIC32MACSetup
DRV_ETHMAC_PIC32MACTeardown
DRV_ETHMAC_PowerMode
DRV_ETHMAC_ByteArrayPut
DRV_ETHMAC_HeaderPut
DRV_ETHMAC_ReadPointerBaseSet
DRV_ETHMAC_ReadPointerSet
DRV_ETHMAC_RxChecksumCalc
DRV_ETHMAC_RxHashTableEntrySet
DRV_ETHMAC_RxReadPointerGet
DRV_ETHMAC_RxReadPointerSet
DRV_ETHMAC_TxBufferFlush
DRV_ETHMAC_TxIsReady
DRV_ETHMAC_VersionGet
DRV_ETHMAC_VersionStrGet
DRV_ETHMAC_WritePointerSet
PIC32MACGetTxBaseAddr
PIC32MACDiscardRx
PIC32MACEventAck
PIC32MACEventDeInit
PIC32MACEventInit
PIC32TCPIP_MAC_EventNotifyClear
PIC32MACEventSetNotifyHandler
PIC32MACEventSetNotifyEvents
PIC32MACEventGetPending
PIC32MACGetArray
PIC32MACGetHeader
PIC32MACCalcIPBufferChecksum
PIC32MACCheckLink
PIC32MACIsMemCopyDone
PIC32MACClose
PIC32MACOpen
PIC32MACInitialize
PIC32MACDeinitialize
PIC32MACPowerMode
PIC32MACPutArray
PIC32MACPutHeader
PIC32MACSetBaseReadPtr
PIC32MACSetReadPtr
PIC32MACCalcRxChecksum
PIC32MACSetRXHashTableEntry
PIC32MACGetReadPtrInRx
PIC32MACSetReadPtrInRx
PIC32MACFlush
PIC32MACIsTxReady
-none-
-nonePIC32MACSetWritePtr
5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library
5-231
MCHP_tcpip_unified Function MPLAB Harmony Function:
PIC32MACCalcIPBufferChecksum
PIC32MACCalcRxChecksum
PIC32MACCheckLink
PIC32MACDeinitialize
PIC32MACDiscardRx
PIC32MACEventAck
PIC32MAC_EventNotifyClear
PIC32MACEventDeInit
PIC32MACEventGetPending
PIC32MACEventInit
PIC32MACEventSetNotifyEvents
PIC32MACEventSetNotifyHandler
PIC32MACFlush
PIC32MACGetArray
PIC32MACGetHeader
PIC32MACGetReadPtrInRx
PIC32MACGetTxBaseAddr
PIC32MACIsMemCopyDone
PIC32MACIsTxReady
PIC32MACDeinitialize
PIC32MACInitialize
PIC32MACOpen
PIC32MACClose
PIC32MACPowerMode
PIC32MACPutArray
PIC32MACPutHeader
PIC32MACSetBaseReadPtr
PIC32MACSetRXHashTableEntry
PIC32MACSetReadPtr
PIC32MACSetReadPtrInRx
PIC32MACSetWritePtr
DRV_ETHMAC_IPBufferChecksumCalc
DRV_ETHMAC_RxChecksumCalc
DRV_ETHMAC_LinkCheck
DRV_ETHMAC_PIC32MACTeardown
DRV_ETHMAC_RxPacketDiscard
DRV_ETHMAC_EventAck
DRV_ETHMAC_EventNotifyClear
DRV_ETHMAC_EventDeInit
DRV_ETHMAC_EventPendingGet
DRV_ETHMAC_EventInit
DRV_ETHMAC_EventNotifySet
DRV_ETHMAC_EventNotifyHandlerSet
DRV_ETHMAC_TxBufferFlush
DRV_ETHMAC_ByteArrayGet
DRV_ETHMAC_HeaderGet
DRV_ETHMAC_RxReadPointerGet
DRV_ETHMAC_BaseAddrTxGet
DRV_ETHMAC_MemoryCopyIsDone
DRV_ETHMAC_TxIsReady
DRV_ETHMAC_PIC32MACTeardown
DRV_ETHMAC_PIC32MACSetup
DRV_ETHMAC_PIC32MACOpen
DRV_ETHMAC_PIC32MACClose
DRV_ETHMAC_PowerMode
DRV_ETHMAC_ByteArrayPut
DRV_ETHMAC_HeaderPut
DRV_ETHMAC_ReadPointerBaseSet
DRV_ETHMAC_RxHashTableEntrySet
DRV_ETHMAC_ReadPointerSet
DRV_ETHMAC_RxReadPointerSet
DRV_ETHMAC_WritePointerSet
DRV_ETHMAC_VersionGet
DRV_ETHMAC_VersionStrGet
5.1.3.4.4 Support for Legacy "Ethernet Controller Library"
These routines (DRV_ETHMAC_Legacy*) provide MPLAB Harmony support for applications that use the "Ethernet Controller
Library for Microchip PIC32MX Microcontrollers" that is installed with XC32 compilers. (See
Microchip\xc32\v1.20\docs\pic32-lib-help\hlpETH.chm for information on this legacy support.)
For some functions the argument list is the same, but for others the addition of an index value from the ETH_MODULE_ID
enumeration has been added to make the function work from within the context of this MPLAB Harmony driver.
5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library
5-232
Legacy Controller Library MPLAB Harmony
EthClose
EthDescriptorGetBuffer
EthDescriptorsPoolAdd
EthDescriptorsPoolCleanUp
EthDescriptorsPoolRemove
EthEventsClr
EthEventsEnableClr
EthEventsEnableGet
EthEventsEnableSet
EthEventsEnableWrite
EthEventsGet
EthInit
EthMACGetAddress
EthMACOpen
EthMACSetAddress
EthMACSetMaxFrame
EthRxAcknowledgeBuffer
EthRxAcknowledgePacket
EthRxBuffersAppend
EthRxFiltersClr
EthRxFiltersHTSet
EthRxFiltersPMClr
EthRxFiltersPMSet
EthRxFiltersSet
EthRxFiltersWrite
EthRxGetBuffer
EthRxGetPacket
EthRxSetBufferSize
EthStatRxAlgnErrCnt
EthStatRxFcsErrCnt
EthStatRxOkCnt
EthStatRxOvflCnt
EthStatTxMColCnt
EthStatTxOkCnt
EthStatTxSColCnt
EthTxAcknowledgeBuffer
EthTxAcknowledgePacket
EthTxGetBufferStatus
EthTxGetPacketStatus
EthTxSendBuffer
EthTxSendPacket
DRV_ETHMAC_LegacyClose
DRV_ETHMAC_LegacyDescriptorGetBuffer
DRV_ETHMAC_LegacyDescriptorsPoolAdd
DRV_ETHMAC_LegacyDescriptorsPoolCleanUp
DRV_ETHMAC_LegacyDescriptorsPoolRemove
PLIB_ETH_LegacyEventsClr
PLIB_ETH_LegacyEventsEnableClr
PLIB_ETH_LegacyEventsEnableGet
PLIB_ETH_LegacyEventsEnableSet
PLIB_ETH_LegacyEventsEnableWrite
PLIB_ETH_LegacyEventsGet
DRV_ETHMAC_LegacyInit
PLIB_ETH_LegacyMACGetAddress
DRV_ETHMAC_LegacyMACOpen
PLIB_ETH_LegacyMACSetAddress
PLIB_ETH_LegacyMACSetMaxFrame
DRV_ETHMAC_LegacyRxAcknowledgeBuffer
DRV_ETHMAC_LegacyRxAcknowledgePacket
DRV_ETHMAC_LegacyRxBuffersAppend
PLIB_ETH_LegacyRxFiltersClr
PLIB_ETH_LegacyRxFiltersHTSet
PLIB_ETH_LegacyRxFiltersPMClr
PLIB_ETH_LegacyRxFiltersPMSet
PLIB_ETH_LegacyRxFiltersSet
PLIB_ETH_LegacyRxFiltersWrite
DRV_ETHMAC_LegacyRxGetBuffer
DRV_ETHMAC_LegacyRxGetPacket
PLIB_ETH_LegacyRxSetBufferSize
PLIB_ETH_LegacyStatRxAlgnErrCnt
PLIB_ETH_LegacyStatRxFcsErrCnt
PLIB_ETH_LegacyStatRxOkCnt
PLIB_ETH_LegacyStatRxOvflCnt
PLIB_ETH_LegacyStatTxMColCnt
PLIB_ETH_LegacyStatTxOkCnt
PLIB_ETH_LegacyStatTxSColCnt
DRV_ETHMAC_LegacyTxAcknowledgeBuffer
DRV_ETHMAC_LegacyTxAcknowledgePacket
DRV_ETHMAC_LegacyTxGetBufferStatus
DRV_ETHMAC_LegacyTxGetPacketStatus
DRV_ETHMAC_LegacyTxSendBuffer
DRV_ETHMAC_LegacyTxSendPacket
5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library
5-233
MAC Driver Function Legacy Controller Library
DRV_ETHMAC_LegacyClose
DRV_ETHMAC_LegacyDescriptorGetBuffer
DRV_ETHMAC_LegacyDescriptorsPoolAdd
DRV_ETHMAC_LegacyDescriptorsPoolCleanUp
DRV_ETHMAC_LegacyDescriptorsPoolRemove
DRV_ETHMAC_LegacyInit
DRV_ETHMAC_LegacyMACOpen
DRV_ETHMAC_LegacyRxAcknowledgeBuffer
DRV_ETHMAC_LegacyRxAcknowledgePacket
DRV_ETHMAC_LegacyRxBuffersAppend
DRV_ETHMAC_LegacyRxGetBuffer
DRV_ETHMAC_LegacyRxGetPacket
DRV_ETHMAC_LegacyTxAcknowledgeBuffer
DRV_ETHMAC_LegacyTxAcknowledgePacket
DRV_ETHMAC_LegacyTxGetBufferStatus
DRV_ETHMAC_LegacyTxGetPacketStatus
DRV_ETHMAC_LegacyTxSendBuffer
DRV_ETHMAC_LegacyTxSendPacket
EthClose
EthDescriptorGetBuffer
EthDescriptorsPoolAdd
EthDescriptorsPoolCleanUp
EthDescriptorsPoolRemove
EthInit
EthMACOpen
EthRxAcknowledgeBuffer
EthRxAcknowledgePacket
EthRxBuffersAppend
EthRxGetBuffer
EthRxGetPacket
EthTxAcknowledgeBuffer
EthTxAcknowledgePacket
EthTxGetBufferStatus
EthTxGetPacketStatus
EthTxSendBuffer
EthTxSendPacket
5.1.3.5 Configuring the Library
Macros
Name Description
DRV_ETHMAC_CLIENTS_NUMBER Selects the maximum number of clients.
DRV_ETHMAC_INDEX Ethernet MAC static index selection.
DRV_ETHMAC_INSTANCES_NUMBER Selects the maximum number of hardware instances that can be
supported by the dynamic driver.
DRV_ETHMAC_INTERRUPT_MODE Controls operation of the driver in the interrupt or polled mode.
DRV_ETHMAC_INTERRUPT_SOURCE Defines an override of the interrupt source in case of static driver.
DRV_ETHMAC_PERIPHERAL_ID Defines an override of the peripheral ID.
DRV_ETHMAC_POWER_STATE Defines an override of the power state of the Ethernet MAC driver.
Description
The configuration of the Ethernet MAC Driver is based on the file sys_config.h
This header file contains the configuration selection for the Ethernet MAC Driver. Based on the selections made, the Ethernet
MAC Driver will support or not support selected features. These configuration settings will apply to all instances of the Ethernet
MAC DRiver.
This header can be placed anywhere; however, the path of this header needs to be present in the include search path for a
successful build. Refer to the Applications Overview section for more details.
5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library
5-234
5.1.3.5.1 DRV_ETHMAC_CLIENTS_NUMBER Macro
C
#define DRV_ETHMAC_CLIENTS_NUMBER 1
Description
Ethernet MAC Maximum Number of Clients
This definition select the maximum number of clients that the Ethernet MAC driver can support at run time. Not defining it means
using a single client.
Remarks
None.
5.1.3.5.2 DRV_ETHMAC_INDEX Macro
C
#define DRV_ETHMAC_INDEX DRV_ETHMAC_INDEX_1
Description
Ethernet MAC Static Index Selection
This definition selects the Ethernet MAC static index for the driver object reference
Remarks
This index is required to make a reference to the driver object.
5.1.3.5.3 DRV_ETHMAC_INSTANCES_NUMBER Macro
C
#define DRV_ETHMAC_INSTANCES_NUMBER 1
Description
Ethernet MAC hardware instance configuration
This definition selects the maximum number of hardware instances that can be supported by the dynamic driver. Not defining it
means using a static driver.
Remarks
None.
5.1.3.5.4 DRV_ETHMAC_INTERRUPT_MODE Macro
C
#define DRV_ETHMAC_INTERRUPT_MODE true
Description
Ethernet MAC Interrupt And Polled Mode Operation Control
This macro controls the operation of the driver in the interrupt mode of operation. The possible values of this macro are:
5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library
5-235
• true - Select if interrupt mode of timer operation is desired
• false - Select if polling mode of timer operation is desired
Not defining this option to true or false will result in a build error.
Remarks
None.
5.1.3.5.5 DRV_ETHMAC_INTERRUPT_SOURCE Macro
C
#define DRV_ETHMAC_INTERRUPT_SOURCE INT_SOURCE_ETH_1
Description
Ethernet MAC Interrupt Source
Defines an override of the interrupt source in case of static driver.
Remarks
Refer to the INT PLIB document for more information on INT_SOURCE enumeration.
5.1.3.5.6 DRV_ETHMAC_PERIPHERAL_ID Macro
C
#define DRV_ETHMAC_PERIPHERAL_ID ETHMAC_ID_1
Description
Ethernet MAC Peripheral ID Selection
Defines an override of the peripheral ID, using macros.
Remarks
Some devices also support ETHMAC_ID_0
5.1.3.5.7 DRV_ETHMAC_POWER_STATE Macro
C
#define DRV_ETHMAC_POWER_STATE SYS_MODULE_POWER_IDLE_STOP
Description
Ethernet MAC power state configuration
Defines an override of the power state of the Ethernet MAC driver.
Remarks
This feature may not be available in the device or the Ethernet MAC module selected.
5.1.3.6 Building the Library
This section list the files that are available in the \src of the Ethernet MAC Driver. It lists which files need to be included in the
5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library
5-236
build based on either a hardware feature present on the board or configuration option selected by the system.
5.1.3.7 Library Interface
Data Types and Constants
Name Description
ETH_CLOSE_FLAGS Defines the possible disable codes of Ethernet controller
"DRV_ETHMAC_LegacyClose" call.
ETH_LINK_STATUS Defines the possible status flags of Ethernet link.
ETH_MODULE_STATUS Defines the possible status codes of the Ethernet controller.
ETH_OPEN_FLAGS Supported open configuration flags for the Ethernet module (EthMACOpen).
ETH_PAUSE_TYPE Defines the possible Ethernet MAC pause types.
ETH_RESULT_CODE Defines the possible results of Ethernet operations that can succeed or fail
ETHPHY_CONFIG_FLAGS flags for DRV_ETHPHY_Setup() call
DRV_ETHMAC_INDEX_1 This is macro DRV_ETHMAC_INDEX_1.
DRV_ETHPHY_INDEX_1 This is macro DRV_ETHPHY_INDEX_1.
Client Level Functions
Name Description
DRV_ETHMAC_PIC32MACClose Closes a client instance of the PIC32 MAC Driver.
DRV_ETHMAC_PIC32MACGetConfig Supports PIC32 Ethernet MAC by copying its configuration..
DRV_ETHMAC_PIC32MACLinkCheck Checks current link status.
DRV_ETHMAC_PIC32MACOpen Opens a client instance of the PIC32 MAC Driver.
DRV_ETHMAC_PIC32MACSetup Supports PIC32 Ethernet MAC setup.
DRV_ETHMAC_PIC32MACTeardown Supports PIC32 Ethernet MAC Teardown (opposite of setup).
Event Functions
Name Description
DRV_ETHMAC_PIC32MACEventAcknowledge This function acknowledges and re-enables processed events.
Multiple events can be orr-ed together as they are processed
together. The events acknowledged by this function should be the
events that have been retrieved from the stack by calling
DRV_ETHMAC_PIC32MACEventPendingGet() or have been
passed to the user by the stack using the notification handler
(PIC32MACEventSetNotifyHandler()) and have been processed
and have to be re-enabled.
DRV_ETHMAC_PIC32MACEventMaskSet Enables the MAC events.
DRV_ETHMAC_PIC32MACEventPendingGet Returns the currently pending events.
Other Functions
Name Description
DRV_ETHMAC_PIC32MACPowerMode Powers down the Ethernet MAC.
DRV_ETHMAC_PIC32MACProcess MAC periodic processing function.
Receive Functions
Name Description
DRV_ETHMAC_PIC32MACPacketRx A packet is returned if such a pending packet exists.
DRV_ETHMAC_PIC32MACPacketTx A packet is submitted to the MAC driver for transmission.
5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library
5-237
Transmit Functions
Name Description
DRV_ETHMAC_PIC32MACRxFilterHashTableEntrySet Calculates a CRC-32 and sets the approriate bit in the
ETHHTx registers
Description
5.1.3.7.1 Client Level Functions
5.1.3.7.1.1 DRV_ETHMAC_PIC32MACClose Function
C
TCPIP_MAC_RES DRV_ETHMAC_PIC32MACClose(
TCPIP_MAC_HANDLE hMac
);
Description
This function closes a client instance of the PIC32 MAC Driver.
Preconditions
DRV_ETHMAC_PIC32MACOpen should have been called.
Parameters
Parameters Description
macId MAC idenfification, from the TCPIP_STACK_MODULE enumeration
Returns
TCPIP_MAC_RES_OK if initialization completed; otherwise, the error enumeration value.
Example
5.1.3.7.1.2 DRV_ETHMAC_PIC32MACGetConfig Function
C
size_t DRV_ETHMAC_PIC32MACGetConfig(
TCPIP_STACK_MODULE modId,
void* configBuff,
size_t buffSize,
size_t* pConfigSize
);
Description
Supports PIC32 Ethernet MAC Teardown (opposite of Setup). Used by tcpip_module_manager.
Preconditions
Supports PIC32 Ethernet MAC by copying its configuration..
Parameters
Parameters Description
modId Module ID from TCPIP_STACK_MODULE enumeration, identifying MAC.
configBuff Pointer to configuration buffer to be copied
5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library
5-238
buffSize Size of configuration buffer provided by configBuff
pConfigSize Pointer to size of configuration buffer copied.
Returns
Size of configuration buffer copied.
Remarks
This function deinitializes the Eth controller, the MAC and the associated PHY. It should be called to be able to schedule any Eth
transmit or receive operation.
Example
5.1.3.7.1.3 DRV_ETHMAC_PIC32MACLinkCheck Function
C
bool DRV_ETHMAC_PIC32MACLinkCheck(
TCPIP_MAC_HANDLE hMac
);
Description
This function checks the link status, performing a MAC reconfiguration if the link went up after being down.
Preconditions
None.
Parameters
Parameters Description
hMac Ethernet MAC client handle
Returns
• true - If the link is up
• false - If the link is not up
Remarks
If auto negotiation is enabled the MAC we may have to be reconfigured.
Example
5.1.3.7.1.4 DRV_ETHMAC_PIC32MACOpen Function
C
TCPIP_MAC_HANDLE DRV_ETHMAC_PIC32MACOpen(
TCPIP_STACK_MODULE macId
);
Description
This function opens a client instance of the PIC32 MAC Driver. Used by tcpip_module_manager.
Preconditions
DRV_ETHMAC_PIC32MACSetup should have been called.
Parameters
Parameters Description
macId MAC idenfification, from the TCPIP_STACK_MODULE enumeration
5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library
5-239
Returns
TCPIP_MAC_HANDLE - handle (pointer) to MAC client
Example
5.1.3.7.1.5 DRV_ETHMAC_PIC32MACSetup Function
C
TCPIP_MAC_RES DRV_ETHMAC_PIC32MACSetup(
TCPIP_MAC_MODULE_CTRL* const stackData,
const TCPIP_MODULE_MAC_PIC32INT_CONFIG* initData
);
Description
This function supports setup of the PIC32 Ethernet MAC. Used by tcpip_module_manager.
Preconditions
DRV_ETHMAC_Open must have been called to obtain a valid opened device handle.
Parameters
Parameters Description
pStackData Pointer to stack data
initData Pointer to initialization data
Returns
TCPIP_MAC_RES_OK if initialization completed; otherwise, error enumeration value.
Remarks
This function initializes the Ethernet controller, the MAC and the associated PHY. It should be called to be able to schedule any
Ethernet transmit or receive operation.
Example
5.1.3.7.1.6 DRV_ETHMAC_PIC32MACTeardown Function
C
TCPIP_MAC_RES DRV_ETHMAC_PIC32MACTeardown(
const TCPIP_MAC_MODULE_CTRL* const stackData
);
Description
This function supports teardown of the PIC32 Ethernet MAC (opposite of setup). Used by tcpip_module_manager.
Preconditions
DRV_ETHMAC_PIC32MACSetup must have been called to setup the driver.
Parameters
Parameters Description
pStackData Pointer to Stack Data
Returns
TCPIP_MAC_RES_OK if initialization completed, error enumeration value otherwise.
5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library
5-240
Remarks
This function deinitializes the Ethernet controller, the MAC and the associated PHY. It should be called to be able to schedule
any Ethernet transmit or receive operation.
Example
5.1.3.7.2 Get and Put Functions
5.1.3.7.3 Base Address and Buffer Size Functions
5.1.3.7.4 Receive Functions
5.1.3.7.4.1 DRV_ETHMAC_PIC32MACPacketRx Function
C
TCPIP_MAC_PACKET* DRV_ETHMAC_PIC32MACPacketRx(
TCPIP_MAC_HANDLE hMac,
TCPIP_MAC_RES* pRes,
const TCPIP_MAC_PACKET_RX_STAT** ppPktStat
);
Description
This is the MAC receive function.
Once a pending packet is available in the MAC driver internal RX queues this function will dequeue the packet and hand it over
to the MAC driver's client - i.e. the stack - for further processing.
The flags for a RX packet have to be updated by the MAC driver:
• TCPIP_MAC_PKT_FLAG_RX has to be set If the MAC supports it, it should set:
• TCPIP_MAC_PKT_FLAG_UNICAST has to be set if that packet is a unicast packet
• TCPIP_MAC_PKT_FLAG_BCAST has to be set if that packet is a broadcast packet
• TCPIP_MAC_PKT_FLAG_MCAST has to be set if that packet is a multicast packet
• TCPIP_MAC_PKT_FLAG_QUEUED has to be set
• TCPIP_MAC_PKT_FLAG_SPLIT has to be set if the packet has multiple data segments
Additional information about the packet is available by providing the pRes and ppPktStat fields.
Preconditions
DRV_ETHMAC_PIC32MACSetup() should have been called.
Parameters
Parameters Description
hMac Ethernet MAC client handle
pRes optional pointer to an address that will receive an additional result associated with
the operation. Can be 0 if not needed.
ppPktStat optional pointer to an address that will receive the received packet status. Note
that this pointer cannot be used once the packet acknowledgement function was
called. Can be 0 if not needed.
5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library
5-241
Returns
a valid pointer to an available RX packet 0 if no packet pending/available
Remarks
The MAC driver dequeues and return to the caller just one single packet.
Once the higher level layers in the stack are done with processing the RX packet, they have to call the corresponding packet
acknowledgement function that tells the MAC driver that it can resume control of that packet.
Once the stack modules are done processing the RX packets and the acknowledge function is called the MAC driver will reuse
the RX packets.
The MAC driver may use the DRV_ETHMAC_PIC32MACProcess() for obtaining new RX packets if needed.
Example
5.1.3.7.4.2 DRV_ETHMAC_PIC32MACPacketTx Function
C
TCPIP_MAC_RES DRV_ETHMAC_PIC32MACPacketTx(
TCPIP_MAC_HANDLE hMac,
TCPIP_MAC_PACKET * ptrPacket
);
Description
This is the MAC transmit function. The MAC driver has to suport internal queueing! A packet is to be rejected only if it's not
properly formatted. Otherwise it has to be scheduled for transmission in an internal queue!
Once the packet is scheduled for transmission the MAC driver has to set the TCPIP_MAC_PKT_FLAG_QUEUED flag so that
the stack is aware that this packet is under processing cnd cannot be modified!
Once the packet is transmitted, the TCPIP_MAC_PKT_FLAG_QUEUED has to be cleared, the proper packet acknowledgement
result (ackRes) has to be set and the packet acknowledgement function (ackFunc) has to be called. It is implementation
dependant if all these steps are implemented as part of the ackFunc itself or as discrete steps.
Preconditions
DRV_ETHMAC_PIC32MACSetup() should have been called.
Parameters
Parameters Description
hMac Ethernet MAC client handle
ptrPacket pointer to a TCPIP_MAC_PACKET that's completely formatted and ready to be
transmitted over the network
Returns
TCPIP_MAC_RES_OK if the packet transmitted, TCPIP_MAC_RES errocode for not properly formatted packets, etc.
Example
5.1.3.7.5 Transmit Functions
5.1.3.7.5.1 DRV_ETHMAC_PIC32MACRxFilterHashTableEntrySet Function
C
TCPIP_MAC_RES DRV_ETHMAC_PIC32MACRxFilterHashTableEntrySet(
5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library
5-242
TCPIP_MAC_HANDLE hMac,
TCPIP_MAC_ADDR* DestMACAddr
);
Description
This function salculates a CRC-32 using polynomial 0x4C11DB7 and then, using bits 28 through 23 of the CRC, sets the
appropriate bit in the ETHHT0-ETHHT1 registers.
Preconditions
DRV_ETHMAC_PIC32MACSetup() should have been called.
Parameters
Parameters Description
hMac Ethernet MAC client handle
DestMACAddr 6-byte group destination MAC address to allow through the Hash Table Filter. If
DestMACAddr is set to '0000 0000 0000', the hash table will be cleared of all
entries and the filter will be disabled.
Returns
TCPIP_MAC_RES_OK if success, an eror code otherwise.
Remarks
Sets the appropriate bit in the ETHHT0/1 registers to allow packets sent to DestMACAddr to be received and enabled the Hash
Table receive filter
There is no way to individually unset destination MAC addresses from the hash table since it is possible to have a hash collision
and therefore multiple MAC addresses relying on the same hash table bit. The stack would have to individually store each 6 byte
MAC address to support this feature, which would waste a lot of RAM and be unnecessary in most applications. As a simple
compromise, you can call DRV_ETHMAC_PIC32MACRxFilterHashTableEntrySet() using a 00-00-00-00-00-00 destination MAC
address, which will clear the entire hash table and disable the hash table filter. This will allow you to then readd the necessary
destination addresses.
Example
5.1.3.7.6 Event Functions
5.1.3.7.6.1 DRV_ETHMAC_PIC32MACEventAcknowledge Function
C
bool DRV_ETHMAC_PIC32MACEventAcknowledge(
TCPIP_MAC_HANDLE hMac,
TCPIP_MAC_EVENT tcpAckEv
);
Description
This function acknowledges and re-enables processed events. Multiple events can be orr-ed together as they are processed
together. The events acknowledged by this function should be the events that have been retrieved from the stack by calling
DRV_ETHMAC_PIC32MACEventPendingGet() or have been passed to the user by the stack using the notification handler
(PIC32MACEventSetNotifyHandler()) and have been processed and have to be re-enabled.
Preconditions
DRV_ETHMAC_PIC32MACSetup() should have been called.
5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library
5-243
Parameters
Parameters Description
hMac Ethernet MAC client handle
tcpAckEv the events that the user processed and need to be re-enabled
Returns
true if events acknowledged false if no events to be acknowledged
Remarks
All events should be acknowledged, in order to be re-enabled.
Some events are fatal errors and should not be acknowledged (TCPIP_MAC_EV_RX_BUSERR,
TCPIP_MAC_EV_TX_BUSERR). Stack re-initialization is needed under such circumstances.
Some events are just system/application behavior and they are intended only as simple info (TCPIP_MAC_EV_RX_OVFLOW,
TCPIP_MAC_EV_RX_BUFNA, TCPIP_MAC_EV_TX_ABORT, TCPIP_MAC_EV_RX_ACT).
The TCPIP_MAC_EV_RX_FWMARK and TCPIP_MAC_EV_RX_EWMARK events are part of the normal flow control operation
(if auto flow control was enabled). They should be enabled alternatively, if needed.
The events are persistent. They shouldn't be re-enabled unless they have been processed and the condition that generated
them was removed. Re-enabling them immediately without proper processing will have dramatic effects on system performance.
Example
DRV_ETHMAC_PIC32MACEventAcknowledge( hMac, stackNewEvents );
5.1.3.7.6.2 DRV_ETHMAC_PIC32MACEventMaskSet Function
C
bool DRV_ETHMAC_PIC32MACEventMaskSet(
TCPIP_MAC_HANDLE hMac,
TCPIP_MAC_EVENT macEvents,
bool enable
);
Description
This function sets the enabled events. Multiple events can be orr-ed together. All events that are set will be added to the
notification process. The old events will be disabled. The stack (or stack user) has to catch the events that are notified and
process them:
• The stack should process the TCPIP_MAC_EV_RX_PKTPEND/TCPIP_MAC_EV_RX_DONE, TCPIP_MAC_EV_TX_DONE
transfer events
• Process the specific condition and acknowledge them calling DRV_ETHMAC_PIC32MACEventAcknowledge() so that they
can be re-enabled.
Preconditions
DRV_ETHMAC_PIC32MACSetup() should have been called.
Parameters
Parameters Description
hMac Ethernet MAC client handle
macEvMask events the user of the stack wants to add/delete for notification
enable if true, the events will be enabled, else disabled
5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library
5-244
Returns
always true, operation succeeded.
Remarks
The event notification system enables the user of the TCPIP stack to call into the stack for processing only when there are
relevant events rather than being forced to periodically call from within a loop.
If the notification events are nill the interrupt processing will be disabled. Otherwise the event notification will be enabled and the
interrupts relating to the requested events will be enabled.
Note that once an event has been caught by the stack ISR (and reported if a notification handler is in place) it will be disabled
until the DRV_ETHMAC_PIC32MACEventAcknowledge() is called.
Example
DRV_ETHMAC_PIC32MACEventMaskSet( hMac, TCPIP_MAC_EV_RX_OVFLOW | TCPIP_MAC_EV_RX_BUFNA,
true );
5.1.3.7.6.3 DRV_ETHMAC_PIC32MACEventPendingGet Function
C
TCPIP_MAC_EVENT DRV_ETHMAC_PIC32MACEventPendingGet(
TCPIP_MAC_HANDLE hMac
);
Description
This function returns the currently pending events belonging to a group. Multiple events can be orr-ed together as they
accumulate. The stack should be called for processing whenever a stack managed event (TCPIP_MAC_EV_RX_PKTPEND,
TCPIP_MAC_EV_TX_DONE) is present. The other, non critical events, may not be managed by the stack and passed to an
user. They will have to be eventually acknowledged if re-enabling is needed.
Preconditions
DRV_ETHMAC_PIC32MACSetup should have been called.
Parameters
Parameters Description
hMac parameter identifying the intended MAC client
Returns
The currently stack pending events.
Remarks
This is the preferred method to get the current pending MAC events. The stack maintains a proper image of the events from their
occurrence to their acknowledgement.
Even with a notification handler in place it's better to use this function to get the current pending events rather than using the
events passed by the notification handler which could be stale.
The events are persistent. They shouldn't be re-enabled unless they have been processed and the condition that generated
them was removed. Re-enabling them immediately without proper processing will have dramatic effects on system performance.
The returned value is just a momentary value. The pending events can change any time.
Example
TCPIP_MAC_EVENT currEvents = DRV_ETHMAC_PIC32MACEventPendingGet( hMac);
5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library
5-245
5.1.3.7.7 Library Functions
5.1.3.7.8 Other Functions
5.1.3.7.8.1 DRV_ETHMAC_PIC32MACPowerMode Function
C
bool DRV_ETHMAC_PIC32MACPowerMode(
TCPIP_MAC_HANDLE hMac,
TCPIP_MAC_POWER_MODE pwrMode
);
Description
This function powers down the Ethernet MAC.
Preconditions
None.
Parameters
Parameters Description
hMac Ethernet MAC client handle
pwrMode Power Mode (?)
Returns
None.
Example
5.1.3.7.8.2 DRV_ETHMAC_PIC32MACProcess Function
C
TCPIP_MAC_RES DRV_ETHMAC_PIC32MACProcess(
TCPIP_MAC_HANDLE hMac
);
Description
This is a function that allows for internal processing by the MAC driver. It is meant for processing that cannot be done from within
ISR.
Some of the processing that this is intended for:
• the MAC driver can process its pending TX queues (although it should do that preferrably from within the TX ISR)
• RX buffers replenishing. If the number of packets in the RX queue falls below a specified limit, the MAC driver can use this
function to allocate some extra RX packets. Similarly, if there are too many allocated RX packets, the MAC driver can free
some of them.
Normally this function will be called in response to an TX and/or RX event signalled by the driver. This is specified by the MAC
driver at initialization time using TCPIP_MAC_MODULE_CTRL.
An alternative approach is that the MAC driver uses a system service to create a timer signal that will call the
TCPIP_MAC_Process on a periodic basis.
Preconditions
DRV_ETHMAC_PIC32MACSetup() should have been called.
5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library
5-246
Parameters
Parameters Description
hMac Ethernet MAC client handle
Returns
TCPIP_MAC_RES_OK if all processing went on OK a TCPIP_MAC_RES error code if processing failed for some reason
Remarks
The MAC driver may use the DRV_ETHMAC_PIC32MACProcess() for obtaining new RX packets if needed.
Example
5.1.3.7.9 Data Types and Constants
5.1.3.7.9.1 ETH_CLOSE_FLAGS Enumeration
C
typedef enum {
ETH_CLOSE_GRACEFUL,
ETH_CLOSE_DEFAULT = (0)
} ETH_CLOSE_FLAGS;
Description
Ethernet Close Flags
This enumeration defines the close capabilities of the Ethernet module.
Members
Members Description
ETH_CLOSE_GRACEFUL Wait for the current TX/RX op to finish
ETH_CLOSE_DEFAULT = (0) Default close options
5.1.3.7.9.2 ETH_LINK_STATUS Enumeration
C
typedef enum {
ETH_LINK_ST_DOWN,
ETH_LINK_ST_UP,
ETH_LINK_ST_LP_NEG_UNABLE,
ETH_LINK_ST_REMOTE_FAULT,
ETH_LINK_ST_PDF,
ETH_LINK_ST_LP_PAUSE,
ETH_LINK_ST_LP_ASM_DIR,
ETH_LINK_ST_NEG_TMO,
ETH_LINK_ST_NEG_FATAL_ERR
} ETH_LINK_STATUS;
Description
Ethernet Link Status Codes
This enumeration defines the flags describing the status of the Ethernet link.
5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library
5-247
Members
Members Description
ETH_LINK_ST_DOWN No connection to the LinkPartner
ETH_LINK_ST_UP Link is up
ETH_LINK_ST_LP_NEG_UNABLE LP non negotiation able
ETH_LINK_ST_REMOTE_FAULT LP fault during negotiation
ETH_LINK_ST_PDF Parallel Detection Fault encountered (when ETH_LINK_ST_LP_NEG_UNABLE)
ETH_LINK_ST_LP_PAUSE LP supports symmetric pause
ETH_LINK_ST_LP_ASM_DIR LP supports asymmetric TX/RX pause operation
ETH_LINK_ST_NEG_TMO LP not there
ETH_LINK_ST_NEG_FATAL_ERR An unexpected fatal error occurred during the negotiation
Remarks
Multiple flags can be set.
5.1.3.7.9.3 ETH_MODULE_STATUS Enumeration
C
typedef enum {
ETH_ST_RXBUSY,
ETH_ST_TXBUSY,
ETH_ST_BUSY
} ETH_MODULE_STATUS;
Description
Ethernet Controller Status Codes
This enumeration defines the flags describing the status of the Ethernet controller.
Members
Members Description
ETH_ST_RXBUSY A packet is currently received
ETH_ST_TXBUSY A packet is currently transmitted
ETH_ST_BUSY Module is on or completing a transaction
5.1.3.7.9.4 ETH_OPEN_FLAGS Enumeration
C
typedef enum {
ETH_OPEN_AUTO,
ETH_OPEN_FDUPLEX,
ETH_OPEN_HDUPLEX,
ETH_OPEN_100,
ETH_OPEN_10,
ETH_OPEN_HUGE_PKTS,
ETH_OPEN_MAC_LOOPBACK,
ETH_OPEN_PHY_LOOPBACK,
ETH_OPEN_MDIX_AUTO,
ETH_OPEN_MDIX_NORM,
ETH_OPEN_MDIX_SWAP,
ETH_OPEN_RMII,
ETH_OPEN_MII,
ETH_OPEN_DEFAULT = (ETH_OPEN_AUTO|ETH_OPEN_FDUPLEX|ETH_OPEN_HDUPLEX|
ETH_OPEN_100|ETH_OPEN_10|ETH_OPEN_MDIX_AUTO)
5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library
5-248
} ETH_OPEN_FLAGS;
Description
Ethernet Open Configuration Settings
This enumeration defines the various configuration options for the Ethernet module. These values can be ORed together to
create a configuration mask passed to the EthMACOpen routine.
Members
Members Description
ETH_OPEN_AUTO Use auto negotiation. set the following flags to specify
your choices
ETH_OPEN_FDUPLEX Use full duplex or full duplex negotiation capability
needed
ETH_OPEN_HDUPLEX Use half duplex or half duplex negotiation capability
needed
ETH_OPEN_100 Use 100MBps or 100MBps negotiation capability
needed
ETH_OPEN_10 Use 10MBps or 10MBps negotiation capability needed
ETH_OPEN_HUGE_PKTS Allow huge packets RX/TX
ETH_OPEN_MAC_LOOPBACK Loopbacked at the MAC level
ETH_OPEN_PHY_LOOPBACK When PHY is loopback-ed, negotiation will be disabled!
ETH_OPEN_MDIX_AUTO Use Auto MDIX
ETH_OPEN_MDIX_NORM Use normal MDIX when Auto MDIX disabled
ETH_OPEN_MDIX_SWAP Use swapped MDIX when Auto MDIX disabled
ETH_OPEN_RMII RMII connection
ETH_OPEN_MII MII connection
ETH_OPEN_DEFAULT =
(ETH_OPEN_AUTO|ETH_OPEN_FDUPLEX|ETH_OPEN_HDUPLEX|
ETH_OPEN_100|ETH_OPEN_10|ETH_OPEN_MDIX_AUTO)
All capabilities default
Remarks
When Auto-negotiation is specified:
• If multiple capability flags are set (ETH_OPEN_FDUPLEX, ETH_OPEN_HDUPLEX, ETH_OPEN_100, ETH_OPEN_10 ) they
are all advertised as this link side capabilities.
• If no setting is passed, the lowest one is taken, i.e., ETH_OPEN_HDUPLEX and ETH_OPEN_10.
• Auto-MDIX requires Auto-Negotiation; ETH_OPEN_MDIX_NORM or ETH_OPEN_MDIX_SWAP setting irrelevant.
When No Auto-negotiation is specified:
• If multiple settings, the highest priority setting is taken, i.e. ETH_OPEN_FDUPLEX over ETH_OPEN_HDUPLEX and
ETH_OPEN_100 over ETH_OPEN_10.
• If no setting, the lowest setting is taken, i.e., ETH_OPEN_HDUPLEX and ETH_OPEN_10.
• The MDIX is set based on the ETH_OPEN_MDIX_NORM/ETH_OPEN_MDIX_SWAP setting.
5.1.3.7.9.5 ETH_PAUSE_TYPE Enumeration
C
typedef enum {
ETH_MAC_PAUSE_TYPE_NONE,
ETH_MAC_PAUSE_TYPE_PAUSE,
ETH_MAC_PAUSE_TYPE_ASM_DIR,
5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library
5-249
ETH_MAC_PAUSE_TYPE_EN_TX,
ETH_MAC_PAUSE_TYPE_EN_RX,
ETH_MAC_PAUSE_ALL = (ETH_MAC_PAUSE_TYPE_PAUSE|ETH_MAC_PAUSE_TYPE_ASM_DIR|
ETH_MAC_PAUSE_TYPE_EN_TX|ETH_MAC_PAUSE_TYPE_EN_RX),
ETH_MAC_PAUSE_CPBL_MASK = ETH_MAC_PAUSE_ALL
} ETH_PAUSE_TYPE;
Description
Ethernet MAC Pause Types
This enumeration defines the pause capabilities of the Ethernet MAC.
Members
Members Description
ETH_MAC_PAUSE_TYPE_NONE No PAUSE capabilities
ETH_MAC_PAUSE_TYPE_PAUSE Supports symmetric PAUSE
ETH_MAC_PAUSE_TYPE_ASM_DIR Supports ASM_DIR
ETH_MAC_PAUSE_TYPE_EN_TX Enable MAC TX pause support
ETH_MAC_PAUSE_TYPE_EN_RX Enable MAC RX pause support
ETH_MAC_PAUSE_ALL =
(ETH_MAC_PAUSE_TYPE_PAUSE|ETH_MAC_PAUSE_TYPE_ASM_DIR|
ETH_MAC_PAUSE_TYPE_EN_TX|ETH_MAC_PAUSE_TYPE_EN_RX)
All types of pause
ETH_MAC_PAUSE_CPBL_MASK = ETH_MAC_PAUSE_ALL All pause capabilities our MAC supports
5.1.3.7.9.6 ETH_RESULT_CODE Enumeration
C
typedef enum {
ETH_RES_OK,
ETH_RES_NO_PACKET,
ETH_RES_PACKET_QUEUED,
ETH_RES_OUT_OF_MEMORY,
ETH_RES_NO_DESCRIPTORS,
ETH_RES_USPACE_ERR,
ETH_RES_RX_SIZE_ERR,
ETH_RES_RX_PKT_SPLIT_ERR,
ETH_RES_NEGOTIATION_UNABLE,
ETH_RES_NEGOTIATION_INACTIVE,
ETH_RES_NEGOTIATION_NOT_STARTED,
ETH_RES_NEGOTIATION_ACTIVE,
ETH_RES_NEGOTIATION_LINKDOWN,
ETH_RES_DTCT_ERR,
ETH_RES_CPBL_ERR,
ETH_RES_CFG_ERR
} ETH_RESULT_CODE;
Description
Ethernet Operation Result Codes
This enumeration defines the possible results of any of the Ethernet library operations that have the possibilty of failing. This
result should be checked to ensure that the operation achieved the desired result.
Members
Members Description
ETH_RES_OK Everything ok
ETH_RES_NO_PACKET No such packet exist
ETH_RES_PACKET_QUEUED Packet is queued (not transmitted or received and not processed)
5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library
5-250
ETH_RES_OUT_OF_MEMORY Some memory allocation failed
ETH_RES_NO_DESCRIPTORS Not enough descriptors available
ETH_RES_USPACE_ERR We don't support user space buffers.
ETH_RES_RX_SIZE_ERR The size of the receive buffers too small
ETH_RES_RX_PKT_SPLIT_ERR A received packet spans more buffers/descriptors than supplied
ETH_RES_NEGOTIATION_UNABLE No negotiation support
ETH_RES_NEGOTIATION_INACTIVE No negotiation active
ETH_RES_NEGOTIATION_NOT_STARTED Negotiation not started yet
ETH_RES_NEGOTIATION_ACTIVE Negotiation active
ETH_RES_NEGOTIATION_LINKDOWN Link down after negotiation, negotiation failed
ETH_RES_DTCT_ERR No Phy was detected or it failed to respond to reset command
ETH_RES_CPBL_ERR No match between the capabilities: the Phy supported and the open requested
ones
ETH_RES_CFG_ERR Hardware configuration doesn't match the requested open mode
5.1.3.7.9.7 ETHPHY_CONFIG_FLAGS Enumeration
C
typedef enum {
ETH_PHY_CFG_RMII,
ETH_PHY_CFG_MII,
ETH_PHY_CFG_ALTERNATE,
ETH_PHY_CFG_DEFAULT,
ETH_PHY_CFG_AUTO
} ETHPHY_CONFIG_FLAGS;
Description
flags for DRV_ETHPHY_Setup() call
Members
Members Description
ETH_PHY_CFG_RMII RMII data interface in configuration fuses.
ETH_PHY_CFG_MII MII data interface in configuration fuses.
ETH_PHY_CFG_ALTERNATE Configuration fuses is ALT
ETH_PHY_CFG_DEFAULT Configuration fuses is DEFAULT
ETH_PHY_CFG_AUTO Use the fuses configuration to detect if you are RMII/MII and ALT/DEFAULT
configuration
5.1.3.7.9.8 DRV_ETHMAC_INDEX_1 Macro
C
#define DRV_ETHMAC_INDEX_1 1
Description
This is macro DRV_ETHMAC_INDEX_1.
5.1.3.7.9.9 DRV_ETHPHY_INDEX_1 Macro
C
#define DRV_ETHPHY_INDEX_1 1
5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library
5-251
Description
This is macro DRV_ETHPHY_INDEX_1.
5.1.3.8 Files
Files
Name Description
drv_ethernet_flags.h Ethernet driver configuration flags file.
drv_ethmac.h Ethernet MAC device driver interface file.
drv_ethmac_config.h Ethernet MAC driver configuration definitions template.
Description
5.1.3.8.1 drv_ethernet_flags.h
Ethernet Drivers Configuration Flags
This file provides the definition of commonly-used configuration enumerations for use with the Ethernet PHY and Ethernet MAC
Drivers.
Enumerations
Name Description
ETH_CLOSE_FLAGS Defines the possible disable codes of Ethernet controller
"DRV_ETHMAC_LegacyClose" call.
ETH_LINK_STATUS Defines the possible status flags of Ethernet link.
ETH_OPEN_FLAGS Supported open configuration flags for the Ethernet module (EthMACOpen).
ETH_PAUSE_TYPE Defines the possible Ethernet MAC pause types.
ETH_RESULT_CODE Defines the possible results of Ethernet operations that can succeed or fail
ETHPHY_CONFIG_FLAGS flags for DRV_ETHPHY_Setup() call
Company
Microchip Technology Inc.
FileName: drv_ethernet_flags.h
5.1.3.8.2 drv_ethmac.h
Ethernet MAC Device Driver Interface
The Ethernet MAC device driver provides a simple interface to manage the Ethernet peripheral. This file defines the interface
definitions and prototypes for the Ethernet MAC driver.
Enumerations
Name Description
ETH_MODULE_STATUS Defines the possible status codes of the Ethernet controller.
5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library
5-252
Functions
Name Description
DRV_ETHMAC_PIC32MACClose Closes a client instance of the PIC32 MAC Driver.
DRV_ETHMAC_PIC32MACEventAcknowledge This function acknowledges and re-enables processed
events. Multiple events can be orr-ed together as they are
processed together. The events acknowledged by this
function should be the events that have been retrieved
from the stack by calling
DRV_ETHMAC_PIC32MACEventPendingGet() or have
been passed to the user by the stack using the notification
handler (PIC32MACEventSetNotifyHandler()) and have
been processed and have to be re-enabled.
DRV_ETHMAC_PIC32MACEventMaskSet Enables the MAC events.
DRV_ETHMAC_PIC32MACEventPendingGet Returns the currently pending events.
DRV_ETHMAC_PIC32MACGetConfig Supports PIC32 Ethernet MAC by copying its
configuration..
DRV_ETHMAC_PIC32MACLinkCheck Checks current link status.
DRV_ETHMAC_PIC32MACOpen Opens a client instance of the PIC32 MAC Driver.
DRV_ETHMAC_PIC32MACPacketRx A packet is returned if such a pending packet exists.
DRV_ETHMAC_PIC32MACPacketTx A packet is submitted to the MAC driver for transmission.
DRV_ETHMAC_PIC32MACPowerMode Powers down the Ethernet MAC.
DRV_ETHMAC_PIC32MACProcess MAC periodic processing function.
DRV_ETHMAC_PIC32MACRxFilterHashTableEntrySet Calculates a CRC-32 and sets the approriate bit in the
ETHHTx registers
DRV_ETHMAC_PIC32MACSetup Supports PIC32 Ethernet MAC setup.
DRV_ETHMAC_PIC32MACTeardown Supports PIC32 Ethernet MAC Teardown (opposite of
setup).
Macros
Name Description
DRV_ETHMAC_INDEX_0 Ethernet driver index definitions.
DRV_ETHMAC_INDEX_1 This is macro DRV_ETHMAC_INDEX_1.
DRV_ETHMAC_INDEX_COUNT Number of valid Ethernet driver indices.
Company
Microchip Technology Inc.
FileName: drv_ethmac.h
5.1.3.8.3 drv_ethmac_config.h
ETHMAC Driver Configuration Definitions for the template version
These definitions statically define the driver's mode of operation.
Macros
Name Description
DRV_ETHMAC_CLIENTS_NUMBER Selects the maximum number of clients.
DRV_ETHMAC_INDEX Ethernet MAC static index selection.
5.1 Driver Library Help MPLAB Harmony Help Ethernet MAC Driver Library
5-253
DRV_ETHMAC_INSTANCES_NUMBER Selects the maximum number of hardware instances that can be
supported by the dynamic driver.
DRV_ETHMAC_INTERRUPT_MODE Controls operation of the driver in the interrupt or polled mode.
DRV_ETHMAC_INTERRUPT_SOURCE Defines an override of the interrupt source in case of static driver.
DRV_ETHMAC_PERIPHERAL_ID Defines an override of the peripheral ID.
DRV_ETHMAC_POWER_STATE Defines an override of the power state of the Ethernet MAC driver.
File Name
drv_ethmac_config.h
Company
Microchip Technology Inc.
5.1.4 Ethernet PHY Driver Library
5.1.4.1 Introduction
Ethernet PHY Driver Library
for
Microchip Microcontrollers
This library provides a low-level abstraction of the Ethernet PHY Driver Library that is available on the Microchip family of
microcontrollers with a convenient C language interface. It can be used to simplify low-level access to the module without the
necessity of interacting directly with the module's registers, there by hiding differences from one microcontroller variant to
another.
Description
This library provides a software abstraction for configuring external Ethernet PHY devices for use with the on-chip Ethernet
Controller.
5.1.4.2 Release Notes
MPLAB Harmony Version: v0.70b Ethernet PHY Driver Library Version : 7.10 Release Date: 18Nov2013
New This Release:
This is the first release of the library. The interface can change in the beta and\or 1.0 release.
Known Issues:
Nothing to report in this release.
5.1.4.3 SW License Agreement
(c) 2013 Microchip Technology Inc.
5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library
5-254
Microchip licenses this software to you solely for use with Microchip products. The software is owned by Microchip and its
licensors, and is protected under applicable copyright laws. All rights reserved.
SOFTWARE IS PROVIDED "AS IS" MICROCHIP EXPRESSLY DISCLAIMS ANY WARRANTY OF ANY KIND, WHETHER
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL MICROCHIP BE LIABLE FOR
ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, HARM TO
YOUR EQUIPMENT, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS
BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR
CONTRIBUTION, OR OTHER SIMILAR COSTS.
To the fullest extent allowed by law, Microchip and its licensors liability shall not exceed the amount of fees, if any, that you have
paid directly to Microchip to use this software.
MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE TERMS.
5.1.4.4 Using the Library
This topic describes the basic architecture of the Ethernet PHY Driver Library and provides information and examples on how to
use it.
Interface Header File: drv_ethphy.h
The interface to the Ethernet PHY Driver Library is defined in the "drv_ethphy.h" header file. This file is included by the
"drv_ethphy.h" file. Any C language source (.c) file that uses the Ethernet PHY Driver Library should include "drv.h".
Library File:
The Ethernet PHY Driver Library archive (.a) file is installed with MPLAB Harmony.
Please refer to the MPLAB Harmony Overview for how the library interacts with the framework.
5.1.4.4.1 Abstraction Model
Overview
To understand how this library works you must first understand how an external Ethernet PHY interfaces with the Ethernet
Controller. As shown in Figure 1, the PHY has two interfaces, one for managing the PHY, known as the Serial Management
Interface (SMI), for configuring the device and a second, known as the Reduced Media Independent Interface (RMII), for transmit
and receive data.
5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library
5-255
Figure 1: Typical External PHY Interface
The block diagram also shows an interrupt signal (nINT) going to a external interrupt pin on the host device and signals going to
on-board LEDs to show link state and link activity.
The SMI interface is also known as the MII Management (MIIM) interface. This control interface is standardized for all PHY's by
Clause 22 of the 802.3 standard. It provides up to 32 16-bit registers on the PHY. The table below provides a summary of all 32
registers. Consult the data sheet for the PHY device for the specific bit fields in each register.
Register
Address
Register Name Register Type
0 Control Basic
1 Status Basic
2,3 PHY Identifier Extended
4 Auto-Negotiation
Advertisement
Extended
5 Auto-Negotiation
Link Partner Base
Page Ability
Extended
6 Auto-Negotiation
Expansion
Extended
7 Auto-Negotiation
Next Page Transmit
Extended
8 Auto-Negotiation
Link Partner
Received Next
Page
Extended
5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library
5-256
9 MASTER-SLAVE
Control Register
Extended
10 MASTER-SLAVE
Status Register
Extended
11-14 Reserved Extended
15 Extended Status Reserved
16-31 Vendor Specific Extended
5.1.4.4.2 Library Overview
The Ethernet PHY Driver Library is divided into the following sections:
Library Interface Section Description
System Level Functions Routines that integrate the driver into the MPLAB Harmony system
Client Level Functions Open, Close, Link Status, Auto Negotiation
SMI/MIIM Functions SMI/MIIM Management Interface
External PHY Support Functions Provides the API for PHY support routines that the driver will call when
setting up the PHY.
The driver library provides support for 4 PHYs.
Other Functions Functions that provide software version information.
Data Types and Constants C language typedefs and enums used by this library.
5.1.4.4.3 MPLAB Harmony vs. the Unified TCP/IP Stack
The following is a cross-reference of MPLAB Harmony functions and the equivalent Unified TCP/IP Stack function:
5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library
5-257
MPLAB Harmony Function: Unified Stack Function:
DRV_ETHPHY_ClientStatus
DRV_ETHPHY_Close
DRV_ETHPHY_Deinitialize
DRV_ETHPHY_HWConfigFlagsGet
DRV_ETHPHY_Setup
DRV_ETHPHY_Initialize
DRV_ETHPHY_LinkScanRead
DRV_ETHPHY_LinkScanStart
DRV_ETHPHY_LinkScanStop
DRV_ETHPHY_LinkStatusGet
DRV_ETHPHY_NegotiationIsComplete
DRV_ETHPHY_NegotiationResultGet
DRV_ETHPHY_Open
DRV_ETHPHY_Reinitialize
DRV_ETHPHY_Reset
DRV_ETHPHY_RestartNegotiation
DRV_ETHPHY_SMIReadResultGet
DRV_ETHPHY_SMIReadStart
DRV_ETHPHY_SMIScanDataGet
DRV_ETHPHY_SMIScanStart
DRV_ETHPHY_SMIScanStatusGet
DRV_ETHPHY_SMIScanStop
DRV_ETHPHY_SMIWriteStart
DRV_ETHPHY_SMIisBusy
DRV_ETHPHY_Status
DRV_ETHPHY_Tasks
DRV_ETHPHY_VersionGet
DRV_ETHPHY_VersionStrGet
DRV_ETHPHY_SMIClockSet
-none-
-none-
-noneEthPhyGetHwConfigFlags
EthPhyInit
-noneEthPhyScanLinkRead
EthPhyScanLinkStart
EthPhyScanLinkStop
EthPhyGetLinkStatus
EthPhyNegotiationComplete
EthPhyGetNegotiationResult
-none-
-noneEthPhyReset
EthPhyRestartNegotiation
EthMIIMReadResult
EthMIIMReadStart
EthMIIMScanResult
EthMIIMScanStart
-none-
-noneEthMIIMWriteStart
-none-
-none-
-none-
-none-
-noneEthMIIMConfig
5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library
5-258
Unified Stack Function: MPLAB Harmony Function:
EthMIIMConfig
EthMIIMReadResult
EthMIIMReadStart
EthMIIMScanResult
EthMIIMScanStart
EthMIIMWriteStart
EthPhyGetHwConfigFlags
EthPhyGetLinkStatus
EthPhyGetNegotiationResult
EthPhyInit
EthPhyNegotiationComplete
EthPhyReset
EthPhyRestartNegotiation
EthPhyScanLinkRead
EthPhyScanLinkStart
EthPhyScanLinkStop
-none-
-none-
-none-
-none-
-none-
-none-
-none-
-none-
-none-
-none-
-none-
-none-
-noneDRV_ETHPHY_SMIClockSet
DRV_ETHPHY_SMIReadResultGet
DRV_ETHPHY_SMIReadStart
DRV_ETHPHY_SMIScanDataGet
DRV_ETHPHY_SMIScanStart
DRV_ETHPHY_SMIWriteStart
DRV_ETHPHY_HWConfigFlagsGet
DRV_ETHPHY_LinkStatusGet
DRV_ETHPHY_NegotiationResultGet
DRV_ETHPHY_Setup
DRV_ETHPHY_NegotiationIsComplete
DRV_ETHPHY_Reset
DRV_ETHPHY_RestartNegotiation
DRV_ETHPHY_LinkScanRead
DRV_ETHPHY_LinkScanStart
DRV_ETHPHY_LinkScanStop
DRV_ETHPHY_ClientStatus
DRV_ETHPHY_Close
DRV_ETHPHY_Deinitialize
DRV_ETHPHY_Initialize
DRV_ETHPHY_Open
DRV_ETHPHY_Reinitialize
DRV_ETHPHY_SMIScanStatusGet
DRV_ETHPHY_SMIScanStop
DRV_ETHPHY_SMIisBusy
DRV_ETHPHY_Status
DRV_ETHPHY_Tasks
DRV_ETHPHY_VersionGet
DRV_ETHPHY_VersionStrGet
5.1.4.5 Configuring the Library
Macros
Name Description
DRV_ETHPHY_CLIENTS_NUMBER Selects the miximum number of clients.
DRV_ETHPHY_INDEX Ethernet PHY static index selection.
DRV_ETHPHY_INDEX_0 Ethernet PHY driver index definitions.
DRV_ETHPHY_INDEX_COUNT Number of valid Ethernet PHY driver indices.
DRV_ETHPHY_INSTANCES_NUMBER Selects the maximum number of hardware instances that can be
supported by the dynamic driver.
DRV_ETHPHY_PERIPHERAL_ID Defines an override of the peripheral ID.
PHY_NEG_DONE_TMO negotiation complete timeout, ms. based on IEEE 802.3 Clause 28 Table
28-9 autoneg_wait_timer value (max 1s)
PHY_NEG_INIT_TMO negotiation initiation timeout, ms.
5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library
5-259
PHY_RESET_CLR_TMO reset self clear timeout, ms. IEEE 802.3 Clause 22 Table 22-7 and
paragraph "22.2.4.1.1 Reset" (max 0.5s)
TCPIP_IF_PIC32INT We have an internal PIC32 MAC
Description
The configuration of the Ethernet MAC Driver Library is based on the file sys_config.h
This header file contains the configuration selection for the Ethernet MAC Driver Library. Based on the selections made, the
Ethernet MAC Driver Library will support or not support selected features. These configuration settings will apply to all instances
of the Ethernet MAC Driver Library.
This header can be placed anywhere; however, the path of this header needs to be present in the include search path for a
successful build. Refer to the Applications Overview section for more details.
5.1.4.5.1 DRV_ETHPHY_CLIENTS_NUMBER Macro
C
#define DRV_ETHPHY_CLIENTS_NUMBER 1
Description
Ethernet PHY Maximum Number of Clients
This definition select the maximum number of clients that the Ethernet PHY driver can support at run time. Not defining it means
using a single client.
Remarks
None.
5.1.4.5.2 DRV_ETHPHY_INDEX Macro
C
#define DRV_ETHPHY_INDEX DRV_ETHPHY_INDEX_1
Description
Ethernet PHY Static Index Selection
This definition selects the Ethernet PHY static index for the driver object reference.
Remarks
This index is required to make a reference to the driver object.
5.1.4.5.3 DRV_ETHPHY_INDEX_0 Macro
C
#define DRV_ETHPHY_INDEX_0 0
Description
Ethernet PHY Driver Module Index Numbers
These constants provide the Ethernet PHY driver index definitions.
Remarks
These constants should be used in place of hard-coded numeric literals.
5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library
5-260
These values should be passed into the DRV_ETHPHY_Initialize and DRV_ETHPHY_Open routines to identify the driver
instance in use.
5.1.4.5.4 DRV_ETHPHY_INDEX_COUNT Macro
C
#define DRV_ETHPHY_INDEX_COUNT 1
Description
Ethernet PHY Driver Module Index Count
This constant identifies the number of valid Ethernet PHY driver indices.
Remarks
This constant should be used in place of hard-coded numeric literals.
This value is derived from part-specific header files defined as part of the peripheral libraries.
5.1.4.5.5 DRV_ETHPHY_INSTANCES_NUMBER Macro
C
#define DRV_ETHPHY_INSTANCES_NUMBER 1
Description
Ethernet PHY hardware instance configuration
This definition selects the maximum number of hardware instances that can be supported by the dynamic driver. Not defining it
means using a static driver.
Remarks
None.
5.1.4.5.6 DRV_ETHPHY_PERIPHERAL_ID Macro
C
#define DRV_ETHPHY_PERIPHERAL_ID ETHPHY_ID_1
Description
Ethernet PHY Peripheral ID Selection
Defines an override of the peripheral ID, using macros.
Remarks
Some devices also support ETHPHY_ID_0
5.1.4.5.7 PHY_NEG_DONE_TMO Macro
C
#define PHY_NEG_DONE_TMO 2000 // negotiation complete timeout, ms.
Description
negotiation complete timeout, ms. based on IEEE 802.3 Clause 28 Table 28-9 autoneg_wait_timer value (max 1s)
5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library
5-261
5.1.4.5.8 PHY_NEG_INIT_TMO Macro
C
#define PHY_NEG_INIT_TMO 1 // negotiation initiation timeout, ms.
Description
negotiation initiation timeout, ms.
5.1.4.5.9 PHY_RESET_CLR_TMO Macro
C
#define PHY_RESET_CLR_TMO 500 // reset self clear timeout, ms.
Description
reset self clear timeout, ms. IEEE 802.3 Clause 22 Table 22-7 and paragraph "22.2.4.1.1 Reset" (max 0.5s)
5.1.4.5.10 TCPIP_IF_PIC32INT Macro
C
#define TCPIP_IF_PIC32INT
Description
We have an internal PIC32 MAC
5.1.4.6 Building the Library
This section list the files that are available in the \src of the Ethernet PHY Driver. It lists which files need to be included in the
build based on either a hardware feature present on the board or configuration option selected by the system.
5.1.4.7 Library Interface
Data Types and Constants
Name Description
DRV_ETHPHY_CLIENT_STATUS Identifies the client-specific status of the Ethernet PHY driver.
DRV_ETHPHY_INIT Contains all the data necessary to initialize the Ethernet PHY device.
SMI_SCAN_DATA_STATUS Returns the status of the SMI of the Ethernet PHY.
SYS_OBJ_HANDLE_INVALID This is macro SYS_OBJ_HANDLE_INVALID.
SYS_OBJ_HANDLE_STATIC This is macro SYS_OBJ_HANDLE_STATIC.
SYS_OBJ_HANDLE SYS_MODULE_OBJ is badly named. It should be
SYS_MODULE_OBJ_HANDLE or something shorter. For brevity, it is renamed
to SYS_OBJ_HANDLE.
Client Level Functions
Name Description
DRV_ETHPHY_ClientStatus Gets the current client-specific status the Ethernet PHY driver.
DRV_ETHPHY_Close Closes an opened instance of the Ethernet PHY driver.
5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library
5-262
DRV_ETHPHY_HWConfigFlagsGet Returns the current Ethernet PHY hardware MII/RMII and
ALTERNATE/DEFAULT configuration flags.
DRV_ETHPHY_LinkScanRead Returns current link status.
DRV_ETHPHY_LinkScanStart Starts an SMI scan of the link status.
DRV_ETHPHY_LinkScanStop Stops the SMI scan of the link status.
DRV_ETHPHY_LinkStatusGet Returns the current link status.
DRV_ETHPHY_NegotiationIsComplete Returns the results of a previously initiated Ethernet PHY negotiation.
DRV_ETHPHY_NegotiationResultGet Returns the link status after a completed negotiation.
DRV_ETHPHY_Open Opens the specified Ethernet PHY driver instance and returns a handle to
it.
DRV_ETHPHY_Reset Immediately resets the Ethernet PHY.
DRV_ETHPHY_RestartNegotiation Restarts auto-negotiation of the Ethernet PHY link.
DRV_ETHPHY_Setup Initializes Ethernet PHY communication.
External PHY Support Functions
Name Description
EXTPHY_MDIXCONFIGURE Configures the MDIX mode for the Ethernet PHY.
EXTPHY_MIICONFIGURE Configures the Ethernet PHY in one of the MII/RMII operation modes.
EXTPHY_SMIADDRESSGET Returns the SMI/MIIM address of the Ethernet PHY.
EXTPHY_SMICLOCKGET Returns the SMI/MIIM maximum clock speed in Hz of the Ethernet PHY.
Other Functions
Name Description
DRV_ETHPHY_VersionGet Gets the Ethernet PHY driver version in numerical format.
DRV_ETHPHY_VersionStrGet Gets the Ethernet PHY driver version in string format.
SMI/MIIM Functions
Name Description
DRV_ETHPHY_SMIClockSet Sets the SMI/MIIM interface clock.
DRV_ETHPHY_SMIisBusy Returns a boolean 'true' if the SMI/MIIM interface is busy with a transaction.
DRV_ETHPHY_SMIReadResultGet Gets the result of the SMI/MIIM register read.
DRV_ETHPHY_SMIReadStart Initiates SMI/MIIM read transaction.
DRV_ETHPHY_SMIScanDataGet Gets the latest SMI/MIIM scan data result.
DRV_ETHPHY_SMIScanStart Starts the scan of the SMI/MIIM register.
DRV_ETHPHY_SMIScanStatusGet Gets the status of the SMI/MIIM scan data.
DRV_ETHPHY_SMIScanStop Stops the scan of the SMI/MIIM register.
DRV_ETHPHY_SMIWriteStart Initiates a SMI/MIIM write transaction.
System Level Functions
Name Description
DRV_ETHPHY_Deinitialize Deinitializes the specified instance of the Ethernet PHY driver module.
DRV_ETHPHY_Initialize Initializes the Ethernet PHY driver.
DRV_ETHPHY_Reinitialize Reinitializes the driver and refreshes any associated hardware settings.
DRV_ETHPHY_Status Provides the current status of the Ethernet PHY driver module.
DRV_ETHPHY_Tasks Maintains the driver's state machine and implements its ISR.
Description
This section describes the Application Programming Interface (API) functions of the Ethernet PHY Driver Library.
5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library
5-263
Refer to each section for a detailed description.
5.1.4.7.1 System Level Functions
5.1.4.7.1.1 DRV_ETHPHY_Deinitialize Function
C
void DRV_ETHPHY_Deinitialize(
SYS_OBJ_HANDLE object
);
Description
This function deinitializes the specified instance of the Ethernet PHY driver module, disabling its operation (and any hardware)
and invalidates all of the internal data.
Preconditions
The DRV_ETHPHY_Initialize function must have been called before calling this routine and a valid SYS_OBJ_HANDLE must
have been returned.
Parameters
Parameters Description
object Driver object handle, returned from DRV_ETHPHY_Initialize
Returns
None.
Remarks
Once the Initialize operation has been called, the Deinitialize operation must be called before the Initialize operation can be
called again.
Example
SYS_OBJ_HANDLE object; // Returned from DRV_ETHPHY_Initialize
SYS_STATUS status;
DRV_ETHPHY_Deinitialize(object);
status = DRV_ETHPHY_Status(object);
if (SYS_MODULE_DEINITIALIZED == status)
{
// Check again later if you need to know
// when the driver is deinitialized.
}
5.1.4.7.1.2 DRV_ETHPHY_Initialize Function
C
SYS_OBJ_HANDLE DRV_ETHPHY_Initialize(
const SYS_MODULE_INDEX index,
const SYS_MODULE_INIT * const init
);
Description
This function initializes the Ethernet PHY driver, making it ready for clients to open and use it.
Preconditions
None.
5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library
5-264
Parameters
Parameters Description
drvIndex Index for the driver instance to be initialized
init Pointer to a data structure containing any data necessary to initialize the driver.
This pointer may be null if no data is required because static overrides have been
provided.
Returns
If successful, returns a valid handle to a driver object. Otherwise, it returns SYS_OBJ_HANDLE_INVALID. The returned object
must be passed as argument to DRV_ETHPHY_Reinitialize, DRV_ETHPHY_Deinitialize, DRV_ETHPHY_Tasks and
DRV_ETHPHY_Status routines.
Remarks
This function must be called before any other Ethernet PHY routine is called.
This function should only be called once during system initialization unless DRV_ETHPHY_Deinitialize is called to de-initialize
the driver instance.
Example
DRV_ETHPHY_INIT init;
SYS_OBJ_HANDLE objectHandle;
// Populate the Ethernet PHY initialization structure
init.phyId = ETHPHY_ID_0;
// Populate the Ethernet PHY initialization structure
init.phyId = ETHPHY_ID_2;
init.sExtPHYFunctions.MyPHYMIIConfigure = &SMSC8720_MIIConfigure;
init.sExtPHYFunctions.MyPHYMDIXConfigure = &SMSC8720_MDIXConfiguret;
init.sExtPHYFunctions.MyPHYSMIAddressGet = &SMSC8720_SMIAddressGet;
init.sExtPHYFunctions.MyPHYSMIClockGet = &SMSC8720_SMIClockGet;
// Do something
objectHandle = DRV_ETHPHY_Initialize(DRV_ETHPHY_INDEX_0, (SYS_MODULE_INIT*)&init);
if (SYS_OBJ_HANDLE_INVALID == objectHandle)
{
// Handle error
}
5.1.4.7.1.3 DRV_ETHPHY_Reinitialize Function
C
void DRV_ETHPHY_Reinitialize(
SYS_OBJ_HANDLE object,
const SYS_MODULE_INIT * const init
);
Description
This function reinitializes the driver and refreshes any associated hardware settings using the initialization data given, but it will
not interrupt any ongoing operations.
Preconditions
The DRV_ETHPHY_Initialize function must have been called before calling this routine and a valid SYS_OBJ_HANDLE must
have been returned.
5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library
5-265
Parameters
Parameters Description
object Driver object handle, returned from the DRV_ETHPHY_Initialize routine
init Pointer to the initialization data structure
Returns
None.
Remarks
This function can be called multiple times to reinitialize the module.
This operation can be used to refresh any supported hardware registers as specified by the initialization data or to change the
power state of the module.
Example
DRV_ETHPHY_INIT init;
SYS_OBJ_HANDLE objectHandle;
// Populate the Ethernet PHY initialization structure
init.phyId = ETHPHY_ID_2;
init.sExtPHYFunctions.MyPHYMIIConfigure = &SMSC8720_MIIConfigure;
init.sExtPHYFunctions.MyPHYMDIXConfigure = &SMSC8720_MDIXConfiguret;
init.sExtPHYFunctions.MyPHYSMIAddressGet = &SMSC8720_SMIAddressGet;
init.sExtPHYFunctions.MyPHYSMIClockGet = &SMSC8720_SMIClockGet;
DRV_ETHPHY_Reinitialize(objectHandle, (SYS_MODULE_INIT*)&init);
phyStatus = DRV_ETHPHY_Status(objectHandle);
if (SYS_STATUS_BUSY == phyStatus)
{
// Check again later to ensure the driver is ready
}
else if (SYS_STATUS_ERROR >= phyStatus)
{
// Handle error
}
5.1.4.7.1.4 DRV_ETHPHY_Status Function
C
SYS_STATUS DRV_ETHPHY_Status(
SYS_OBJ_HANDLE object
);
Description
This function provides the current status of the Ethernet PHY driver module.
Preconditions
The DRV_ETHPHY_Initialize function must have been called before calling this function.
Parameters
Parameters Description
object Driver object handle, returned from DRV_ETHPHY_Initialize
Returns
SYS_STATUS_READY - Indicates that the driver is busy with a previous system level operation and cannot start another
5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library
5-266
Remarks
Any value greater than SYS_STATUS_READY is also a normal running state in which the driver is ready to accept new
operations.
SYS_STATUS_BUSY - Indicates that the driver is busy with a previous system level operation and cannot start another
SYS_STATUS_ERROR - Indicates that the driver is in an error state
Any value less than SYS_STATUS_ERROR is also an error state.
SYS_MODULE_DEINITIALIZED - Indicates that the driver has been de-initialized
This value is less than SYS_STATUS_ERROR.
The this operation can be used to determine when any of the driver's module level operations has completed.
If the status operation returns SYS_STATUS_BUSY, the a previous operation has not yet completed. Once the status operation
returns SYS_STATUS_READY, any previous operations have completed.
The value of SYS_STATUS_ERROR is negative (-1). Any value less than that is also an error state.
This function will NEVER block waiting for hardware.
If the Status operation returns an error value, the error may be cleared by calling the reinitialize operation. If that fails, the
deinitialize operation will need to be called, followed by the initialize operation to return to normal operations.
Example
SYS_OBJ_HANDLE object; // Returned from DRV_ETHPHY_Initialize
SYS_STATUS status;
status = DRV_ETHPHY_Status(object);
else if (SYS_STATUS_ERROR >= status)
{
// Handle error
}
5.1.4.7.1.5 DRV_ETHPHY_Tasks Function
C
void DRV_ETHPHY_Tasks(
SYS_OBJ_HANDLE object
);
Description
This function is used to maintain the driver's internal state machine and implement its ISR for interrupt-driven implementations.
Preconditions
The DRV_ETHPHY_Initialize routine must have been called for the specified Ethernet PHY driver instance.
Parameters
Parameters Description
object Object handle for the specified driver instance (returned from
DRV_ETHPHY_Initialize)
Returns
None
Remarks
This function is normally not called directly by an application. It is called by the system's Tasks routine (SYS_Tasks) or by the
5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library
5-267
apropriate raw ISR.
This function may excute in an ISR context and will never block or access any resources that may cause it to block.
Example
SYS_OBJ_HANDLE object; // Returned from DRV_ETHPHY_Initialize
while (true)
{
DRV_ETHPHY_Tasks (object);
// Do other tasks
}
5.1.4.7.2 Client Level Functions
5.1.4.7.2.1 DRV_ETHPHY_ClientStatus Function
C
DRV_ETHPHY_CLIENT_STATUS DRV_ETHPHY_ClientStatus(
DRV_HANDLE handle
);
Description
This function gets the client-specfic status of the Ethernet PHY driver associated with the given handle.
Preconditions
The DRV_ETHPHY_Initialize routine must have been called.
DRV_ETHPHY_Open must have been called to obtain a valid opened device handle.
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open routine
Returns
A DRV_ETHPHY_CLIENT_STATUS value describing the current status of the driver.
Remarks
This function will not block for hardware access and will immediately return the current status.
Example
DRV_HANDLE phyHandle; // Returned from DRV_ETHPHY_Open
DRV_ETHPHY_CLIENT_STATUS phyClientStatus;
phyClientStatus = DRV_ETHPHY_ClientStatus(phyHandle);
if(DRV_ETHPHY_CLIENT_STATUS_ERROR >= phyClientStatus)
{
// Handle the error
}
5.1.4.7.2.2 DRV_ETHPHY_Close Function
C
void DRV_ETHPHY_Close(
DRV_HANDLE handle
);
5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library
5-268
Description
This function closes an opened instance of the Ethernet PHY driver, invalidating the handle.
Preconditions
The DRV_ETHPHY_Initialize routine must have been called for the specified Ethernet PHY driver instance.
DRV_ETHPHY_Open must have been called to obtain a valid opened device handle.
Parameters
Parameters Description
handle A valid open instance handle, returned from the driver's open routine
Returns
None
Remarks
After calling this routine, the handle passed in "handle" must not be used with any of the remaining driver routines. A new handle
must be obtained by calling DRV_ETHPHY_Open before the caller may use the driver again.
If DRV_IO_INTENT_BLOCKING was requested and the driver was built appropriately to support blocking behavior call may
block until the operation is complete.
If DRV_IO_INTENT_NON_BLOCKING request the driver client can call the DRV_ETHPHY_Status operation to find out when
the module is in the ready state (the handle is no longer valid).
Usually there is no need for the driver client to verify that the Close operation has completed.
Example
DRV_HANDLE handle; // Returned from DRV_ETHPHY_Open
DRV_ETHPHY_Close(handle);
5.1.4.7.2.3 DRV_ETHPHY_HWConfigFlagsGet Function
C
ETHPHY_CONFIG_FLAGS DRV_ETHPHY_HWConfigFlagsGet(
DRV_HANDLE handle
);
Description
This function returns the current Ethernet PHY hardware MII/RMII and ALTERNATE/DEFAULT configuration flags from the
Device Configuration Fuse bits.
Preconditions
None.
Parameters
Parameters Description
handle Client's driver handle (returned from DRV_ETHPHY_Open)
Returns
Ethernet PHY configuration flag, see ETHPHY_CONFIG_FLAGS enumeration for bit values.
Remarks
Please note,
5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library
5-269
• ETHPHY_CONFIG_FLAGS DRV_ETHPHY_HWConfigFlagsGet( DRV_HANDLE handle )
replaces the legacy "Ethernet Controller Library" function:
• eEthPhyCfgFlags EthPhyGetHwConfigFlags(void)
Example
5.1.4.7.2.4 DRV_ETHPHY_LinkScanRead Function
C
ETH_LINK_STATUS DRV_ETHPHY_LinkScanRead(
DRV_HANDLE handle
);
Description
This function returns the current link status.
Preconditions
DRV_ETHPHY_LinkScanStart must be called first.
Parameters
Parameters Description
handle Client's driver handle (returned from DRV_ETHPHY_Open)
Returns
Current link status, see ETH_LINK_STATUS enumeration.
Remarks
See also DRV_ETHPHY_LinkStatusGet.
Please note,
• ETH_LINK_STATUS DRV_ETHPHY_LinkScanRead( DRV_HANDLE handle )
replaces the legacy "Ethernet Controller Library" function:
• eEthLinkStat EthPhyScanLinkRead(void)
Example
5.1.4.7.2.5 DRV_ETHPHY_LinkScanStart Function
C
void DRV_ETHPHY_LinkScanStart(
DRV_HANDLE handle
);
Description
This function starts an SMI scan of the link status.
Preconditions
Communication with the Ethernet PHY was already established.
Parameters
Parameters Description
handle Client's driver handle (returned from DRV_ETHPHY_Open)
5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library
5-270
Returns
None.
Remarks
This function starts an SMII scan of the Ethernet PHY link status register. It is a more efficient way of having access to the
current link status, since the normal SMI frame read operation is slow.
Please note,
• void DRV_ETHPHY_LinkScanStart( DRV_HANDLE handle )
replaces the legacy "Ethernet Controller Library" function:
• void EthPhyScanLinkStart(void)
Example
5.1.4.7.2.6 DRV_ETHPHY_LinkScanStop Function
C
void DRV_ETHPHY_LinkScanStop(
DRV_HANDLE handle
);
Description
This function stops the SMI scan of the ink status.
Preconditions
Communication with the Ethernet PHY was already established.
Parameters
Parameters Description
handle Client's driver handle (returned from DRV_ETHPHY_Open)
Returns
None.
Remarks
Please note,
• void DRV_ETHPHY_LinkScanStop( DRV_HANDLE handle )
replaces the legacy "Ethernet Controller Library" function:
• void EthPhyScanLinkStop(void)
Example
5.1.4.7.2.7 DRV_ETHPHY_LinkStatusGet Function
C
ETH_LINK_STATUS DRV_ETHPHY_LinkStatusGet(
DRV_HANDLE handle,
bool refresh
);
Description
This function returns the urrent link status.
5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library
5-271
Preconditions
DRV_ETHPHY_Setup should have been called.
Parameters
Parameters Description
handle Client's driver handle (returned from DRV_ETHPHY_Open)
refresh Boolean flag, true to specify that a double read is needed
Returns
Current link status, see ETH_LINK_STATUS enumeration.
Remarks
This function reads the Ethernet PHY to get current link status If refresh is specified then, if the link is down a second read will be
performed to return the current link status.
Please note,
• ETH_LINK_STATUS DRV_ETHPHY_LinkStatusGet( DRV_HANDLE handle, bool refresh )
replaces the legacy "Ethernet Controller Library" function:
• eEthLinkStat EthPhyGetLinkStatus(int refresh)
Example
5.1.4.7.2.8 DRV_ETHPHY_NegotiationIsComplete Function
C
ETH_RESULT_CODE DRV_ETHPHY_NegotiationIsComplete(
DRV_HANDLE handle,
bool waitComplete
);
Description
This function returns the results of a previously initiated Ethernet PHY negotiation.
Preconditions
DRV_ETHPHY_Setup (and DRV_ETHPHY_RestartNegotiation) should have been called.
Parameters
Parameters Description
handle Client's driver handle (returned from DRV_ETHPHY_Open)
waitComplete Boolean flag, true if wait for completion is required
Returns
ETH_RES_OK if negotiation is done, ETH_RES_NEGOTIATION_INACTIVE if no negotiation in progress,
ETH_RES_NEGOTIATION_NOT_STARTED if negotiation not yet started yet (means tmo if waitComplete was requested), or
ETH_RES_NEGOTIATION_ACTIVE if negotiation ongoing (means tmo if waitComplete was requested).
Remarks
See also DRV_ETHPHY_NegotiationResultGet.
Please note,
• ETH_RESULT_CODE DRV_ETHPHY_NegotiationIsComplete( DRV_HANDLE handle, bool waitComplete )
replaces the legacy "Ethernet Controller Library" function:
5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library
5-272
• eEthRes EthPhyNegotiationComplete(int waitComplete)
Example
5.1.4.7.2.9 DRV_ETHPHY_NegotiationResultGet Function
C
ETH_LINK_STATUS DRV_ETHPHY_NegotiationResultGet(
DRV_HANDLE handle,
ETH_OPEN_FLAGS* pFlags,
ETH_PAUSE_TYPE* pPauseType
);
Description
This function returns the link status after a completed negotiation.
Preconditions
DRV_ETHPHY_Setup, DRV_ETHPHY_RestartNegotiation, and DRV_ETHPHY_NegotiationIsComplete should have been called.
Parameters
Parameters Description
handle Client's driver handle (returned from DRV_ETHPHY_Open)
pFlags Address to store the negotiation result
pPauseType Address to store the pause type supported by the link partner
Returns
Link status after the (completed) negotiation, see ETH_LINK_STATUS enumeration.
Remarks
If no negotiation possible/active/failed, most likely the flags are invalid!
Please note,
• ETH_LINK_STATUS DRV_ETHPHY_NegotiationResultGet( DRV_HANDLE handle, ETH_OPEN_FLAGS* pFlags,
ETH_PAUSE_TYPE* pPauseType )
replaces the legacy "Ethernet Controller Library" function:
• eEthLinkStat EthPhyGetNegotiationResult(eEthOpenFlags* pFlags, eEthMacPauseType* pPauseType)
Example
5.1.4.7.2.10 DRV_ETHPHY_Open Function
C
DRV_HANDLE DRV_ETHPHY_Open(
const SYS_MODULE_INDEX drvIndex,
const DRV_IO_INTENT intent
);
Description
This function opens the specified Ethernet PHY driver instance and provides a handle that must be provided to all other
client-level operations to identify the caller and the instance of the driver.
Preconditions
The DRV_ETHPHY_Initialize function must have been called before calling this function.
5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library
5-273
Parameters
Parameters Description
drvIndex Identifier for the object instance to be opened
intent Zero or more of the values from the enumeration DRV_IO_INTENT ORed together
to indicate the intended use of the driver
Returns
If successful, the routine returns a valid open-instance handle (a number identifying both the caller and the module instance).
If an error occurs, the return value is DRV_HANDLE_INVALID.
Remarks
The handle returned is valid until the DRV_ETHPHY_Close routine is called.
This function will NEVER block waiting for hardware.
If the DRV_IO_INTENT_BLOCKING is requested and the driver was built appropriately to support blocking behavior, other
client-level operations may block waiting on hardware until they are complete.
If DRV_IO_INTENT_NON_BLOCKING is requested the driver client can call the DRV_ETHPHY_ClientStatus operation to find
out when the module is in the ready state.
If the requested intent flags are not supported, the function will return DRV_HANDLE_INVALID.
Example
DRV_HANDLE handle;
handle = DRV_ETHPHY_Open(DRV_ETHPHY_INDEX_0, DRV_IO_INTENT_EXCLUSIVE);
if (DRV_HANDLE_INVALID == handle)
{
// Unable to open the driver
}
5.1.4.7.2.11 DRV_ETHPHY_Reset Function
C
bool DRV_ETHPHY_Reset(
DRV_HANDLE handle,
bool waitComplete
);
Description
This function immediately resets the Ethernet PHY, optionally waiting for a reset to complete.
Preconditions
Communication with the Ethernet PHY was already established.
Parameters
Parameters Description
handle Client's driver handle (returned from DRV_ETHPHY_Open)
waitComplete boolean flag, if true the procedure will wait for reset to complete
Returns
True - If PHY reset procedure completed (or completion not required) False - Otherwise
Remarks
Please note,
5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library
5-274
• bool DRV_ETHPHY_Reset( DRV_HANDLE handle, bool waitComplete )
replaces the legacy "Ethernet Controller Library" function:
• int EthPhyReset(int waitComplete)
Example
5.1.4.7.2.12 DRV_ETHPHY_RestartNegotiation Function
C
void DRV_ETHPHY_RestartNegotiation(
DRV_HANDLE handle
);
Description
This function restarts auto-negotiation of the Ethernet PHY link.
Preconditions
The Ethernet PHY should have been initialized with the proper duplex/speed mode.
Parameters
Parameters Description
handle Client's driver handle (returned from DRV_ETHPHY_Open)
Returns
None.
Remarks
Please note,
• void DRV_ETHPHY_RestartNegotiation( DRV_HANDLE handle )
replaces the legacy "Ethernet Controller Library" function:
• eEthRes EthPhyRestartNegotiation(void)
Example
5.1.4.7.2.13 DRV_ETHPHY_Setup Function
C
ETH_RESULT_CODE DRV_ETHPHY_Setup(
DRV_HANDLE handle,
ETH_OPEN_FLAGS oFlags,
ETHPHY_CONFIG_FLAGS cFlags,
ETH_OPEN_FLAGS * pResFlags
);
Description
This function initializes the Ethernet PHY communication. It tries to detect the external Ethernet PHY, to read the capabilties and
find a match with the requested features.Then it programs the Ethernet PHY accordingly.
Preconditions
DRV_ETHMAC_LegacyInit should have been called to initialize the Ethernet MAC.
5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library
5-275
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open routine
oFlags The requested open flags
cFlags Ethernet PHY MII/RMII configuration flags
pResFlags Address to store the initialization results
Returns
ETH_RES_OK for success; otherwise, an error code.
Remarks
Please note,
• ETH_RESULT_CODE DRV_ETHPHY_Setup( DRV_HANDLE handle, ETH_OPEN_FLAGS oFlags,
ETHPHY_CONFIG_FLAGS cFlags, ETH_OPEN_FLAGS* pResFlags )
replaces the legacy "Ethernet Controller Library" function:
• eEthRes EthPhyInit(eEthOpenFlags oFlags, eEthPhyCfgFlags cFlags, eEthOpenFlags* pResFlags)
Example
5.1.4.7.3 SMI/MIIM Functions
5.1.4.7.3.1 DRV_ETHPHY_SMIClockSet Function
C
void DRV_ETHPHY_SMIClockSet(
DRV_HANDLE handle,
uint32_t hostClock,
uint32_t maxSMIClock
);
Description
This function sets SMI/MIIM interface clock base on host clock and maximum supported SMI/MIIM interface clock speed.
Parameters
Parameters Description
handle Client's driver handle (returned from DRV_ETHPHY_Open)
hostClock Host clock speed in Hz
maxSMIClock Maximum supported SMI/MIIM clock speed in Hz
Returns
None.
Remarks
Please note,
• void DRV_ETHPHY_SMIClockSet( DRV_HANDLE handle, uint16_t hostClock, uint16_t maxSMIClock )
replaces the legacy "Ethernet Controller Library" function:
• void EthMIIMConfig(unsigned int hostClock, unsigned int miimClock)
Example
5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library
5-276
5.1.4.7.3.2 DRV_ETHPHY_SMIisBusy Function
C
bool DRV_ETHPHY_SMIisBusy(
DRV_HANDLE handle
);
Description
This function returns a boolean 'true' if the SMI/MIIM interface is busy with a transaction.
Preconditions
MyPHYSMIClockSet() called to setup SMI/MIIM clock.
Parameters
Parameters Description
handle Client's driver handle (returned from DRV_ETHPHY_Open)
Returns
• true - If the SMI/MIIM is busy
• false - If the SMI/MIIM is not busy
Example
5.1.4.7.3.3 DRV_ETHPHY_SMIReadResultGet Function
C
uint16_t DRV_ETHPHY_SMIReadResultGet(
DRV_HANDLE handle
);
Description
This function gets the result of the SMI/MIIM register read.
Preconditions
MyPHYSMIClockSet was called to set up the SMI/MIIM clock and DRV_ETHPHY_SMIReadStart was called to initiate a
SMI/MIIM register read. DRV_ETHPHY_SMIisBusy should return false.
Parameters
Parameters Description
handle Client's driver handle (returned from DRV_ETHPHY_Open)
Returns
Result of the SMI/MIIM register read previously scheduled.
Remarks
Please note,
• uint16_t DRV_ETHPHY_SMIReadResultGet( DRV_HANDLE handle )
replaces the legacy "Ethernet Controller Library" function:
• unsigned short EthMIIMReadResult ( void )
Example
5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library
5-277
5.1.4.7.3.4 DRV_ETHPHY_SMIReadStart Function
C
void DRV_ETHPHY_SMIReadStart(
DRV_HANDLE handle,
unsigned int rIx,
unsigned int phyAdd
);
Description
This function initiates SMI/MIIM read transaction for a given PHY address and register.
Preconditions
MyPHYSMIClockSet was called to set up the SMI/MIIM clock.
Parameters
Parameters Description
handle Client's driver handle (returned from DRV_ETHPHY_Open)
rIx PHY register to be accessed
phyAdd Address of PHY to be accessed
Returns
None.
Remarks
Please note,
• void DRV_ETHPHY_SMIReadStart( DRV_HANDLE handle, unsigned int rIx, unsigned int phyAdd )
replaces the legacy "Ethernet Controller Library" function:
• void EthMIIMReadStart(unsigned int rIx, unsigned int phyAdd)
Example
5.1.4.7.3.5 DRV_ETHPHY_SMIScanDataGet Function
C
uint16_t DRV_ETHPHY_SMIScanDataGet(
DRV_HANDLE handle
);
Description
This functino gets the latest SMI/MIIM scan data result.
Preconditions
DRV_ETHPHY_SMIScanStart() has been called. DRV_ETHPHY_SMIScanStatusGet() should return SMI_SCAN_DATA_VALID.
Parameters
Parameters Description
handle Client's driver handle (returned from DRV_ETHPHY_Open)
Returns
Current scan result.
5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library
5-278
Remarks
Scan data status must be SMI_SCAN_DATA_VALID.
Please note,
• uint16_t DRV_ETHPHY_SMIScanDataGet( DRV_HANDLE handle )
replaces the legacy "Ethernet Controller Library" function:
• unsigned short EthMIIMScanResult(void)
Example
5.1.4.7.3.6 DRV_ETHPHY_SMIScanStart Function
C
void DRV_ETHPHY_SMIScanStart(
DRV_HANDLE handle,
unsigned int rIx,
unsigned int phyAdd
);
Description
This function starts the scan of the SMI/MIIM register.
Parameters
Parameters Description
handle Client's driver handle (returned from DRV_ETHPHY_Open)
rIx PHY register to be accessed, 0-31
phyAdd PHY address, 0-31
Returns
None.
Remarks
Please note,
• void DRV_ETHPHY_SMIScanStart( DRV_HANDLE handle, unsigned int rIx, unsigned int phyAdd )
replaces the legacy "Ethernet Controller Library" function:
• void EthMIIMScanStart(unsigned int rIx, unsigned int phyAdd)
Example
5.1.4.7.3.7 DRV_ETHPHY_SMIScanStatusGet Function
C
SMI_SCAN_DATA_STATUS DRV_ETHPHY_SMIScanStatusGet(
DRV_HANDLE handle
);
Description
This function gets the status of the SMI/MIIM scan data.
Preconditions
DRV_ETHPHY_SMIScanStart() has been called.
5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library
5-279
Parameters
Parameters Description
handle Client's driver handle (returned from DRV_ETHPHY_Open)
Returns
SMI_SCAN_DATA_NOTVALID or SMI_SCAN_DATA_VALID
Remarks
None.
Example
5.1.4.7.3.8 DRV_ETHPHY_SMIScanStop Function
C
void DRV_ETHPHY_SMIScanStop(
DRV_HANDLE handle
);
Description
This function stops the scan of the SMI/MIIM register.
Parameters
Parameters Description
handle Client's driver handle (returned from DRV_ETHPHY_Open)
Returns
None.
Remarks
Stops a scan transaction on the SMI interface.
Please note,
• void DRV_ETHPHY_SMIScanStop( DRV_HANDLE handle )
replaces the legacy "Ethernet Controller Library" function:
• void EthMIIMScanStop ( void )
Example
5.1.4.7.3.9 DRV_ETHPHY_SMIWriteStart Function
C
void DRV_ETHPHY_SMIWriteStart(
DRV_HANDLE handle,
unsigned int rIx,
unsigned int phyAdd,
uint16_t wData
);
Description
This function initiates SMI/MIIM write transaction for a given PHY address and register.
Preconditions
MyPHYSMIClockSet was called to set up the SMI/MIIM clock.
5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library
5-280
Parameters
Parameters Description
handle Client's driver handle (returned from DRV_ETHPHY_Open)
rIx PHY register to be accessed
phyAdd Address of PHY to be accessed
wData Data to be written
Returns
None.
Remarks
Please note,
• void DRV_ETHPHY_SMIWriteStart( DRV_HANDLE handle, unsigned int rIx, unsigned int phyAdd, uint16_t wData )
replaces the legacy "Ethernet Controller Library" function:
• void EthMIIMWriteStart(unsigned int rIx, unsigned int phyAdd, unsigned short wData)
Example
5.1.4.7.4 External PHY Support Functions
5.1.4.7.4.1 EXTPHY_MDIXCONFIGURE Type
C
typedef ETH_RESULT_CODE (* EXTPHY_MDIXCONFIGURE)(DRV_HANDLE handle, ETH_OPEN_FLAGS oFlags);
Description
Pointer To Function: ETH_RESULT_CODE EXTPHY_MDIXConfigure( DRV_HANDLE handle, ETH_OPEN_FLAGS oFlags )
Configures the MDIX mode for the Ethernet PHY.
Preconditions
Communication to the PHY should have been established.
Parameters
Parameters Description
handle Client's driver handle (returned from DRV_PHY_Open)
oFlags Requested open flags: ETH_OPEN_MDIX_AUTO, ETH_OPEN_MDIX_NORM, or
ETH_OPEN_MDIX_NORM | ETH_OPEN_MDIX_SWAP
Returns
ETH_RES_OK - if success; otherwise, ETH_RES_CFG_ERR.
Remarks
For some external PHYs, the MDIX configuration is set by pins on the device. In this case, the function will return ETH_RES_OK
if the cFlags requests the already configured interface; otherwise, ETH_RES_CFG_ERR.
5.1.4.7.4.2 EXTPHY_MIICONFIGURE Type
C
typedef ETH_RESULT_CODE (* EXTPHY_MIICONFIGURE)(DRV_HANDLE handle, ETHPHY_CONFIG_FLAGS cFlags);
5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library
5-281
Description
Pointer To Function: ETH_RESULT_CODE EXTPHY_MIIConfigure( DRV_HANDLE handle, ETHPHY_CONFIG_FLAGS cFlags )
Configures the Ethernet PHY in one of the MII/RMII operation modes.
Preconditions
Communication to the PHY should have been established.
Parameters
Parameters Description
handle Client's driver handle (returned from DRV_PHY_Open)
cFlags Requested configuration flags: ETH_PHY_CFG_RMII or ETH_PHY_CFG_MII
Returns
ETH_RES_OK - if success; otherwise, ETH_RES_CFG_ERR.
Remarks
For some external PHYs, the data interface is set by pins on the device or fuses in the host. In this case, the function will return
ETH_RES_OK if the cFlags requests the already configured interface; otherwise, ETH_RES_CFG_ERR.
5.1.4.7.4.3 EXTPHY_SMIADDRESSGET Type
C
typedef unsigned int (* EXTPHY_SMIADDRESSGET)(DRV_HANDLE handle);
Description
Pointer To Function: uint16_t EXTPHY_SMIAddressGet( DRV_HANDLE handle );
Returns the SMI/MIIM address of the Ethernet PHY.
Preconditions
Communication to the PHY should have been established.
Parameters
Parameters Description
handle Client's driver handle (returned from DRV_PHY_Open)
Returns
The SMI/MIIM Ethernet PHY address as an unsigned 16-bit integer.
Remarks
For some external PHYs, the MDIX configuration is set by pins on the device. In this case, the function will return ETH_RES_OK
if the cFlags requests the already configured interface; otherwise, ETH_RES_CFG_ERR.
5.1.4.7.4.4 EXTPHY_SMICLOCKGET Type
C
typedef unsigned int (* EXTPHY_SMICLOCKGET)(DRV_HANDLE handle);
Description
Pointer to Function: uint16_t EXTPHY_SMIClockGet( DRV_HANDLE handle );
Returns the SMI/MIIM maximum clock speed in Hz of the Ethernet PHY.
5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library
5-282
Preconditions
Communication to the PHY should have been established.
Parameters
Parameters Description
handle Client's driver handle (returned from DRV_PHY_Open)
Returns
The maximum SMI/MIIM clock speed as an unsigned 16-bit integer.
Remarks
For some external PHYs, the MDIX configuration is set by pins on the device. In this case, the function will return ETH_RES_OK
if the cFlags requests the already configured interface; otherwise, ETH_RES_CFG_ERR.
5.1.4.7.5 Other Functions
5.1.4.7.5.1 DRV_ETHPHY_VersionGet Function
C
unsigned int DRV_ETHPHY_VersionGet(
const SYS_MODULE_INDEX drvIndex
);
Description
This function gets the Ethernet PHY driver version. The version is encoded as major * 10000 + minor * 100 + patch. The stringed
version can be obtained using DRV_ETHPHY_VersionStrGet()
Preconditions
None.
Parameters
Parameters Description
drvIndex Identifier for the object instance to get the version for
Returns
Current driver version in numerical format.
Remarks
None.
Example
unsigned int version;
version = DRV_ETHPHY_VersionGet( DRV_ETHPHY_INDEX_1 );
if(version < 110200)
{
// Do Something
}
5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library
5-283
5.1.4.7.5.2 DRV_ETHPHY_VersionStrGet Function
C
char * DRV_ETHPHY_VersionStrGet(
const SYS_MODULE_INDEX drvIndex
);
Description
This function gets the Ethernet PHY driver version. The version is returned as major.minor.path[type], where type is optional.
The numerical version can be obtained using DRV_ETHPHY_VersionGet()
Preconditions
None.
Parameters
Parameters Description
drvIndex Identifier for the object instance to get the version for.
Returns
Current Ethernet PHY driver version in the string format.
Remarks
None.
Example
char *version;
version = DRV_ETHPHY_VersionStrGet( DRV_ETHPHY_INDEX_1 );
printf("%s", version);
5.1.4.7.6 Data Types and Constants
5.1.4.7.6.1 DRV_ETHPHY_CLIENT_STATUS Enumeration
C
typedef enum {
DRV_ETHPHY_CLIENT_STATUS_ERROR,
DRV_ETHPHY_CLIENT_STATUS_CLOSED,
DRV_ETHPHY_CLIENT_STATUS_BUSY,
DRV_ETHPHY_CLIENT_STATUS_READY
} DRV_ETHPHY_CLIENT_STATUS;
Description
Ethernet PHY Driver Client Status
This enumeration identifies the client-specific status of the Ethernet PHY driver.
Members
Members Description
DRV_ETHPHY_CLIENT_STATUS_ERROR Unspecified error condition
DRV_ETHPHY_CLIENT_STATUS_CLOSED Client is not open
DRV_ETHPHY_CLIENT_STATUS_BUSY An operation is currently in progress
DRV_ETHPHY_CLIENT_STATUS_READY Up and running, no operations running
5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library
5-284
Remarks
None.
5.1.4.7.6.2 DRV_ETHPHY_INIT Structure
C
typedef struct {
SYS_MODULE_INIT moduleInit;
ETH_MODULE_ID ethphyId;
EXTPHY_MIICONFIGURE MyPHYMIIConfigure;
EXTPHY_MDIXCONFIGURE MyPHYMDIXConfigure;
EXTPHY_SMIADDRESSGET MyPHYSMIAddressGet;
EXTPHY_SMICLOCKGET MyPHYSMIClockGet;
} DRV_ETHPHY_INIT;
Description
Ethernet PHY Device Driver Initialization Data
This structure contains all the data necessary to initialize the Ethernet PHY device.
Members
Members Description
SYS_MODULE_INIT moduleInit; System module initialization
ETH_MODULE_ID ethphyId; Identifies peripheral (PLIB-level) ID
EXTPHY_MIICONFIGURE
MyPHYMIIConfigure;
Select MII or RMII data interface
EXTPHY_MDIXCONFIGURE
MyPHYMDIXConfigure;
AutoMDIX or Manual MDIX
EXTPHY_SMIADDRESSGET
MyPHYSMIAddressGet;
Returns PHY's SMI Address
EXTPHY_SMICLOCKGET
MyPHYSMIClockGet;
Returns PHY's clock speed
Remarks
A pointer to a structure of this format containing the desired initialization data must be passed into the DRV_ETHPHY_Initialize
routine.
5.1.4.7.6.3 SMI_SCAN_DATA_STATUS Enumeration
C
typedef enum {
SMI_SCAN_DATA_NOTVALID,
SMI_SCAN_DATA_VALID
} SMI_SCAN_DATA_STATUS;
Description
SMI Interface Scan Data Status Enumeration
This enumeration returns the status of the SMI of the Ethernet PHY.
Members
Members Description
SMI_SCAN_DATA_NOTVALID SMI interface ready for new scan/read/write
SMI_SCAN_DATA_VALID SMI interface ready for new scan/read/write
5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library
5-285
Remarks
None.
5.1.4.7.6.4 SYS_OBJ_HANDLE_INVALID Macro
C
#define SYS_OBJ_HANDLE_INVALID ( (SYS_OBJ_HANDLE) -1 )
Description
This is macro SYS_OBJ_HANDLE_INVALID.
5.1.4.7.6.5 SYS_OBJ_HANDLE_STATIC Macro
C
#define SYS_OBJ_HANDLE_STATIC ( (SYS_OBJ_HANDLE) 0 )
Description
This is macro SYS_OBJ_HANDLE_STATIC.
5.1.4.7.6.6 SYS_OBJ_HANDLE Type
C
typedef uintptr_t SYS_OBJ_HANDLE;
Description
SYS_MODULE_OBJ Rename
SYS_MODULE_OBJ is badly named. It should be SYS_MODULE_OBJ_HANDLE or something shorter. For brevity, it is
renamed to SYS_OBJ_HANDLE.
Remarks
None.
5.1.4.8 Files
Files
Name Description
drv_ethphy.h Ethernet ETHPHY Device Driver Interface File
drv_ethphy_config.h Ethernet PHY driver configuration definitions template.
Description
5.1.4.8.1 drv_ethphy.h
Ethernet ETHPHY Device Driver Interface
The Ethernet ETHPHY device driver provides a simple interface to manage an Ethernet ETHPHY peripheral using MIIM (or SMI)
interface. This file defines the interface definitions and prototypes for the Etherent ETHPHY driver.
5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library
5-286
Enumerations
Name Description
DRV_ETHPHY_CLIENT_STATUS Identifies the client-specific status of the Ethernet PHY driver.
SMI_SCAN_DATA_STATUS Returns the status of the SMI of the Ethernet PHY.
Functions
Name Description
DRV_ETHPHY_ClientStatus Gets the current client-specific status the Ethernet PHY driver.
DRV_ETHPHY_Close Closes an opened instance of the Ethernet PHY driver.
DRV_ETHPHY_Deinitialize Deinitializes the specified instance of the Ethernet PHY driver module.
DRV_ETHPHY_HWConfigFlagsGet Returns the current Ethernet PHY hardware MII/RMII and
ALTERNATE/DEFAULT configuration flags.
DRV_ETHPHY_Initialize Initializes the Ethernet PHY driver.
DRV_ETHPHY_LinkScanRead Returns current link status.
DRV_ETHPHY_LinkScanStart Starts an SMI scan of the link status.
DRV_ETHPHY_LinkScanStop Stops the SMI scan of the link status.
DRV_ETHPHY_LinkStatusGet Returns the current link status.
DRV_ETHPHY_NegotiationIsComplete Returns the results of a previously initiated Ethernet PHY negotiation.
DRV_ETHPHY_NegotiationResultGet Returns the link status after a completed negotiation.
DRV_ETHPHY_Open Opens the specified Ethernet PHY driver instance and returns a handle to
it.
DRV_ETHPHY_Reinitialize Reinitializes the driver and refreshes any associated hardware settings.
DRV_ETHPHY_Reset Immediately resets the Ethernet PHY.
DRV_ETHPHY_RestartNegotiation Restarts auto-negotiation of the Ethernet PHY link.
DRV_ETHPHY_Setup Initializes Ethernet PHY communication.
DRV_ETHPHY_SMIClockSet Sets the SMI/MIIM interface clock.
DRV_ETHPHY_SMIisBusy Returns a boolean 'true' if the SMI/MIIM interface is busy with a
transaction.
DRV_ETHPHY_SMIReadResultGet Gets the result of the SMI/MIIM register read.
DRV_ETHPHY_SMIReadStart Initiates SMI/MIIM read transaction.
DRV_ETHPHY_SMIScanDataGet Gets the latest SMI/MIIM scan data result.
DRV_ETHPHY_SMIScanStart Starts the scan of the SMI/MIIM register.
DRV_ETHPHY_SMIScanStatusGet Gets the status of the SMI/MIIM scan data.
DRV_ETHPHY_SMIScanStop Stops the scan of the SMI/MIIM register.
DRV_ETHPHY_SMIWriteStart Initiates a SMI/MIIM write transaction.
DRV_ETHPHY_Status Provides the current status of the Ethernet PHY driver module.
DRV_ETHPHY_Tasks Maintains the driver's state machine and implements its ISR.
DRV_ETHPHY_VersionGet Gets the Ethernet PHY driver version in numerical format.
DRV_ETHPHY_VersionStrGet Gets the Ethernet PHY driver version in string format.
Macros
Name Description
DRV_ETHPHY_INDEX_0 Ethernet PHY driver index definitions.
DRV_ETHPHY_INDEX_1 This is macro DRV_ETHPHY_INDEX_1.
DRV_ETHPHY_INDEX_COUNT Number of valid Ethernet PHY driver indices.
5.1 Driver Library Help MPLAB Harmony Help Ethernet PHY Driver Library
5-287
Structures
Name Description
DRV_ETHPHY_INIT Contains all the data necessary to initialize the Ethernet PHY device.
Types
Name Description
EXTPHY_MDIXCONFIGURE Configures the MDIX mode for the Ethernet PHY.
EXTPHY_MIICONFIGURE Configures the Ethernet PHY in one of the MII/RMII operation modes.
EXTPHY_SMIADDRESSGET Returns the SMI/MIIM address of the Ethernet PHY.
EXTPHY_SMICLOCKGET Returns the SMI/MIIM maximum clock speed in Hz of the Ethernet PHY.
Company
Microchip Technology Incorported
FileName: drv_ethphy.h
5.1.4.8.2 drv_ethphy_config.h
Ethernet PHY Driver Configuration Definitions for the Template Version
These definitions statically define the driver's mode of operation.
Macros
Name Description
DRV_ETHPHY_CLIENTS_NUMBER Selects the miximum number of clients.
DRV_ETHPHY_INDEX Ethernet PHY static index selection.
DRV_ETHPHY_INSTANCES_NUMBER Selects the maximum number of hardware instances that can be
supported by the dynamic driver.
DRV_ETHPHY_PERIPHERAL_ID Defines an override of the peripheral ID.
PHY_NEG_DONE_TMO negotiation complete timeout, ms. based on IEEE 802.3 Clause 28 Table
28-9 autoneg_wait_timer value (max 1s)
PHY_NEG_INIT_TMO negotiation initiation timeout, ms.
PHY_RESET_CLR_TMO reset self clear timeout, ms. IEEE 802.3 Clause 22 Table 22-7 and
paragraph "22.2.4.1.1 Reset" (max 0.5s)
TCPIP_IF_PIC32INT We have an internal PIC32 MAC
File Name
drv_ethphy_config.h
Company
Microchip Technology Inc.
5.1.4.8.3 drv_ethernet_flags.h
This file can be accessed through the following link: drv_ethernet_flags.h
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-288
5.1.5 Graphics (GFX) Driver Library
5.1.5.1 Introduction
Graphics (GFX) Driver Library
for
Microchip Microcontrollers
The Graphics (GFX) Driver Layer Library is the GFX library stack available for the Microchip family of microcontrollers.
Description
The MPLAB Harmony Graphics (GFX) Library is highly modular and is optimized for Microchip’s 32-bit microcontrollers.
Additionally, the library is free for Microchip customers, easy to use, and has an open documented interface for new driver
support, which requires creation of only one C file.
5.1.5.2 Release Notes
MPLAB Harmony Version: v0.70b Graphics (GFX) Driver Layer Library Version : 4.00b Release Date: 18Nov2013
New This Release:
This is the first release of the library. The interface can change in the beta and\or 1.0 release.
Known Issues:
Nothing to report in this release.
5.1.5.3 SW License Agreement
(c) 2013 Microchip Technology Inc.
Microchip licenses this software to you solely for use with Microchip products. The software is owned by Microchip and its
licensors, and is protected under applicable copyright laws. All rights reserved.
SOFTWARE IS PROVIDED "AS IS" MICROCHIP EXPRESSLY DISCLAIMS ANY WARRANTY OF ANY KIND, WHETHER
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL MICROCHIP BE LIABLE FOR
ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, HARM TO
YOUR EQUIPMENT, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS
BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR
CONTRIBUTION, OR OTHER SIMILAR COSTS.
To the fullest extent allowed by law, Microchip and its licensors liability shall not exceed the amount of fees, if any, that you have
paid directly to Microchip to use this software.
MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE TERMS.
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-289
5.1.5.4 Using the Library
5.1.5.4.1 Abstraction Model
The Graphics Driver Library structure consists of the following:
• Application Layer – This is the program that utilizes the Graphics Driver Library
• User Message Interface- This layer should be implemented by user to provide messages for the library
• Graphics Object Layer – This layer renders the widgets controls such as button, slider, window, and so on
• Graphics Primitives Layer – This layer implements the primitive drawing functions
• Device Display Driver – This layer is dependent on the display device being used
• Graphics Display Module – This is the display device being used
The library provides two configurations (Blocking and Non-Blocking).
For a Blocking configuration, all draw functions are blocking calls that delay the execution of program until rendering is done.
For a Non-Blocking configuration, draw functions do not wait for the drawing completion and release control to the program.
In this configuration, a draw function should be called repeatedly until the rendering of that particular draw function is complete.
This allows efficient use of microcontroller CPU time since it can perform other tasks if the rendering is not yet done.
5.1.5.4.2 Library Overview
This layer informs the GFX library on which graphics controller is being used along with the LCD. It takes input only from the
primitive layer. This layer contains all the hardware specific functions the primitive layer needs to render primitives onto the LCD.
Each driver contained in the GFX library has a build time structure associated with it that informs the primitive layer which
hardware specific functions are available. Thus when the primitive layer calls a specific rendering task it gets passed a pointer
from the driver of that task. If the task does not exist the driver passes back a NULL and the primitive layer and either render the
primitive without hardware support or let the application know that this feature is not available.
5.1.5.5 Configuring the Library
The configuration of the GFX driver is based on the file drv_gfx_config.h
This header file contains the configuration selection for the GFX Driver. Based on the selections made, the GFX Driver will
support or not support selected features. These configuration settings will apply to all instances of the GFX Driver.
This header can be placed anywhere; however, the path of this header needs to be present in the include search path for a
successful build. Refer to the Applications Overview section for more details.
The configuration of the GFX driver layer is mainly dependent on making sure the needed driver has the core driver functions
inside of it. The main rendering one being a PixelPut type function for the GFX primitive layer.
Once the GFX driver structure (GFX_DRV_DATA) is defined along with its primitive function rendering structure
(GFX_DRV_FUNCTIONS) it can be used by the GFX primitive layer.
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-290
5.1.5.6 Building the Library
This section lists the files that are available in the /src folder of the GFX driver. It lists which files need to be included in the build
based on either a hardware feature present on the board or a configuration option selected by the system.
5.1.5.7 Library Interface
Data Types and Constants
Name Description
GFX_DRV_DATA Structure containing the driver graphics controller data.
GFX_DRV_FUNCTIONS Structure containing the driver functions used by the primitive layer.
LAYER_TYPE types of Layers supported by the GFX Library
PAGE_TYPE types of pages supported by the GFX Library
NUM_ALPHA_LEVELS Specific to device
ALPHA_DELTA This is macro ALPHA_DELTA.
GFX_CONFIG_DRIVER_COUNT This is macro GFX_CONFIG_DRIVER_COUNT.
GFX_ALPHA_PARAMS This is type GFX_ALPHA_PARAMS.
GFX_LAYER_PARAMS This is type GFX_LAYER_PARAMS.
System Functions
Name Description
Percentage2Alpha
DriverInterfaceInit This is function DriverInterfaceInit.
Description
All of the drivers in the GFX library must follow certain guidelines to be used by the GFX Primitve. These guidelines are defined
in gfx_gol_display_driver.h
The GFX primitve calls function pointers to reference a particular GFX driver function. If the function does not exist for a
particular driver (ie Alpha Blending) then the driver defines the function as NULL at buildtime. The function structure for a driver
file can be seen in "Basic Renderring Routines".
5.1.5.7.1 System Functions
5.1.5.7.1.1 Percentage2Alpha Function
C
inline uint8_t Percentage2Alpha(
uint8_t alphaPercentage
);
5.1.5.7.1.2 DriverInterfaceInit Function
C
inline void DriverInterfaceInit(
DRV_HANDLE * pmphandle,
DRV_PMP_MODE_CONFIG * config
);
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-291
Description
This is function DriverInterfaceInit.
5.1.5.7.2 Data Types and Constants
5.1.5.7.2.1 GFX_DRV_DATA Structure
C
typedef struct {
uint16_t orientation;
uint16_t horizontalResolution;
uint16_t verticalResolution;
uint16_t dataWidth;
uint16_t horizontalPulseWidth;
uint16_t horizontalBackPorch;
uint16_t horizontalFrontPorch;
uint16_t verticalPulseWidth;
uint16_t verticalBackPorch;
uint16_t verticalFrontPorch;
uint8_t logicShift;
enum {
LCD_TFT = 1,
LCD_MSTN,
LCD_CSTN
} LCDType;
uint8_t colorType;
uint8_t timingControl;
GFX_DRV_FUNCTIONS PrimitiveFunction;
uint8_t driverBusy;
uint8_t ready;
GFX_COLOR color;
volatile uint8_t activePage;
volatile uint8_t visualPage;
} GFX_DRV_DATA;
Description
Structure: GFX_DRV_DATA
Each driver in order to be registered with the primitive layer needs these values. they are mainly dependent on the chosen LCD.
Members
Members Description
uint16_t orientation; Orientation of the display (given in degrees of 0,90,180,270)
uint16_t horizontalResolution; Horizontal Resolution of the displayed orientation in Pixels
uint16_t verticalResolution; Vertical resolution of the displayed orientation in pixels
uint16_t horizontalPulseWidth; Horizontal Pulse Width of the LCD
uint16_t horizontalBackPorch; Horizontal BackPorch of the LCD
uint16_t horizontalFrontPorch; Horizontal FrontPorch of the LCD
uint16_t verticalPulseWidth; Vertical Pulse width of the LCD
uint16_t verticalBackPorch; Vertical BackPorch of the LCD
uint16_t verticalFrontPorch; Vertical FrontPorch of the LCD
uint8_t logicShift; Rising/Falling edge indicator of the LCD pixel clock
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-292
enum {
LCD_TFT = 1,
LCD_MSTN,
LCD_CSTN
} LCDType;
LCD type
uint8_t colorType; color depth (18BPP, 24BPP, 8BPP, palette)
uint8_t timingControl; flag to
GFX_DRV_FUNCTIONS PrimitiveFunction; List of Primitive Renderring functions available by the driver
uint8_t driverBusy; Flag to indicate driver is currently busy
uint8_t ready; Flag to indicate driver has been initialized and recognized by the primitive layer
GFX_COLOR color; current Color set for the display driver
volatile uint8_t activePage; current activepage set for the display driver
volatile uint8_t visualPage; current visualPage set for the display driver
5.1.5.7.2.2 GFX_DRV_FUNCTIONS Structure
C
typedef struct {
uint16_t (* PixelsPut)(short,short,uint16_t, uint16_t);
uint16_t (* BarFill)(short,short,short,short);
uint16_t* (* PixelArrayPut)(uint16_t*,short,short,uint16_t, uint16_t);
uint16_t* (* PixelArrayGet)(uint16_t*,short,short,uint16_t);
uint16_t (* PixelPut)(short,short);
void (* ColorSet)(GFX_COLOR);
void (* InstanceSet)(uint8_t);
uint16_t (* PageSet)(uint8_t, uint8_t);
uint16_t* (* Layer)(uint8_t, GFX_LAYER_PARAMS*);
uint16_t (* PixelGet)(short,short);
uint16_t* (* AlphaBlendWindow)(GFX_ALPHA_PARAMS*, uint16_t, uint16_t, uint8_t);
} GFX_DRV_FUNCTIONS;
Description
Structure: GFX_DRV_FUNCTIONS
This structure needs to be defined in the driver file to inform the primitive layer as to what functions are available.
Members
Members Description
uint16_t (* PixelsPut)(short,short,uint16_t,
uint16_t);
This function sends pixels of an X,Y location to the LCD controller of a given
count and linecount.
uint16_t (* BarFill)(short,short,short,short); This function sends a 2D accelerated Bar command to the LCD controller
uint16_t* (*
PixelArrayPut)(uint16_t*,short,short,uint16_t,
uint16_t);
This function sends an array of pixels at an X,Y location to the LCD controller of
a given count and linecount from a memory location.
uint16_t* (*
PixelArrayGet)(uint16_t*,short,short,uint16_t);
This function gets an array of pixels at an X,Y location to the LCD controller of
a given count and linecount from a memory location.
uint16_t (* PixelPut)(short,short); This function sends a pixel of an X,Y location to the LCD controller.
void (* ColorSet)(GFX_COLOR); This function sets the global color for the display driver
void (* InstanceSet)(uint8_t); This function sets the global color for the display driver
uint16_t (* PageSet)(uint8_t, uint8_t); See Primitive PageSet Defition
uint16_t* (* Layer)(uint8_t,
GFX_LAYER_PARAMS*);
See Primitive Layer Definition
uint16_t (* PixelGet)(short,short); This function gets a pixel of an X,Y location to the LCD controller.
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-293
uint16_t* (*
AlphaBlendWindow)(GFX_ALPHA_PARAMS*,
uint16_t, uint16_t, uint8_t);
See Primitive AlphaBlendWindow Definition
5.1.5.7.2.3 LAYER_TYPE Enumeration
C
typedef enum {
PIP1 = 0,
PIP2
} LAYER_TYPE;
Description
Enumeration: LAYER_TYPE
5.1.5.7.2.4 PAGE_TYPE Enumeration
C
typedef enum {
ACTIVE_PAGE = 0,
VISUAL_PAGE,
BACKGROUND_PAGE,
FOREGROUND_PAGE,
DESTINATION_PAGE,
TRANSITION_PAGE
} PAGE_TYPE;
Description
Enumeration: PAGE_TYPE
Members
Members Description
TRANSITION_PAGE Page that displays the transition
5.1.5.7.2.5 NUM_ALPHA_LEVELS Macro
C
#define NUM_ALPHA_LEVELS 0x20 // Specific to device
Description
Specific to device
5.1.5.7.2.6 ALPHA_DELTA Macro
C
#define ALPHA_DELTA ((NUM_ALPHA_LEVELS) << 5)
Description
This is macro ALPHA_DELTA.
5.1.5.7.2.7 GFX_CONFIG_DRIVER_COUNT Macro
C
#define GFX_CONFIG_DRIVER_COUNT 1
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-294
Description
This is macro GFX_CONFIG_DRIVER_COUNT.
5.1.5.7.2.8 GFX_ALPHA_PARAMS Structure
C
typedef struct {
uint8_t foregroundPage;
short foregroundLeft;
short foregroundTop;
uint8_t backgroundPage;
short backgroundLeft;
short backgroundTop;
uint8_t destinationPage;
short destinationLeft;
short destinationTop;
uint8_t alpha;
GFX_COLOR prevAlphaColor;
} GFX_ALPHA_PARAMS;
Description
This is type GFX_ALPHA_PARAMS.
5.1.5.7.2.9 GFX_LAYER_PARAMS Structure
C
typedef struct {
uint8_t type;
uint8_t on;
uint8_t page;
short left;
short top;
uint16_t width;
uint16_t height;
short layerLeft;
short layerTop;
} GFX_LAYER_PARAMS;
Description
This is type GFX_LAYER_PARAMS.
5.1.5.8 Files
Files
Name Description
drv_gfx_display.h GFX Display Driver definitions
drv_gfx_config_template.h This is file drv_gfx_config_template.h.
Description
5.1.5.8.1 drv_gfx_display.h
GFX Display Driver definitions
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-295
This file describes the GFX Display Driver specific definitions.
Enumerations
Name Description
LAYER_TYPE types of Layers supported by the GFX Library
PAGE_TYPE types of pages supported by the GFX Library
Files
Name Description
drv_gfx_lcc.h Interface for the graphics library where the primitives are renderred and sent to the
graphics controller either external or internal
drv_gfx_s1d13517.h Interface for the graphics library where the primitives are renderred and sent to the
graphics controller either external or internal
drv_gfx_ssd1926.h Interface for the graphics library where the primitives are renderred and sent to the
graphics controller either external or internal
Functions
Name Description
DriverInterfaceInit This is function DriverInterfaceInit.
Percentage2Alpha
Macros
Name Description
ALPHA_DELTA This is macro ALPHA_DELTA.
GFX_CONFIG_DRIVER_COUNT This is macro GFX_CONFIG_DRIVER_COUNT.
NUM_ALPHA_LEVELS Specific to device
Structures
Name Description
GFX_ALPHA_PARAMS This is type GFX_ALPHA_PARAMS.
GFX_DRV_DATA Structure containing the driver graphics controller data.
GFX_DRV_FUNCTIONS Structure containing the driver functions used by the primitive layer.
GFX_LAYER_PARAMS This is type GFX_LAYER_PARAMS.
Company
Microchip Technology Incorporated
FileName: gfx_display_driver.h
5.1.5.8.1.1 drv_gfx_lcc.h
None
Enumerations
Name Description
DMA_ISR_TASK This is type DMA_ISR_TASK.
LCC_TASK This is type LCC_TASK.
Functions
Name Description
GFX_DRV_lcc_BrightnessSet Sets the brightness of the display backlight.
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-296
GFX_DRV_lcc_Close closes an instance of the graphics controller
GFX_DRV_lcc_Initialize resets LCD, initializes PMP
GFX_DRV_lcc_Layer This is function GFX_DRV_lcc_Layer.
GFX_DRV_lcc_Open opens an instance of the graphics controller
GFX_DRV_lcc_PixelArrayGet gets an array of pixels of length count starting at *color
GFX_DRV_lcc_PixelArrayPut outputs an array of pixels of length count starting at *color
GFX_DRV_lcc_PixelPut outputs one pixel into the frame buffer at the x,y coordinate given
GFX_DRV_lcc_PixelsPut outputs one pixel into the frame buffer at the x,y coordinate given
GFX_DRV_lcc_SetColor Sets the color for the driver instance
GFX_DRV_lcc_SetInstance Sets the instance for the driver
GFX_DRV_lcc_SetPage This is function GFX_DRV_lcc_SetPage.
GFX_DRV_lcc_Tasks Task machine that renders the driver calls for the graphics library it must be called
peridically to output the contents of its circular buffer
GFX_PRIM_SetPIPWindow This is function GFX_PRIM_SetPIPWindow.
Macros
Name Description
GFX_DRV_lcc_COMMANDQUEUESIZE This is macro GFX_DRV_lcc_COMMANDQUEUESIZE.
PIP_BUFFER This is macro PIP_BUFFER.
USE_LCC_SCROLLING This is macro USE_LCC_SCROLLING.
USE_PIP This is macro USE_PIP.
Structures
Name Description
GFX_DRV_lcc_COMMAND Structure for the commands in the driver queue.
File Name
drv_gfx_lcc.h
Company
Microchip Technology Incorporated
5.1.5.8.1.2 drv_gfx_s1d13517.h
None
Functions
Name Description
GFX_DRV_S1D13517_AlphaBlendWindow SEE primitive layer alphablendWindow definition
GFX_DRV_S1D13517_BrightnessSet Sets the brightness of the display backlight.
GFX_DRV_S1D13517_Close closes an instance of the graphics controller
GFX_DRV_S1D13517_GetReg returns graphics controller register value (byte access)
GFX_DRV_S1D13517_Initialize resets LCD, initializes PMP
GFX_DRV_S1D13517_Layer Updates a Layer depending on the layer parameters.
GFX_DRV_S1D13517_Open opens an instance of the graphics controller
GFX_DRV_S1D13517_PixelArrayPut outputs an array of pixels of length count starting at *color
GFX_DRV_S1D13517_PixelPut outputs one pixel into the frame buffer at the x,y coordinate given
GFX_DRV_S1D13517_PixelsPut outputs one pixel into the frame buffer at the x,y coordinate given
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-297
GFX_DRV_S1D13517_SetColor Sets the color for the driver instance
GFX_DRV_S1D13517_SetInstance Sets the instance for the driver
GFX_DRV_S1D13517_SetPage Sets the page of a certain page type
GFX_DRV_S1D13517_SetReg updates graphics controller register value (byte access)
GFX_DRV_S1D13517_Tasks Task machine that renders the driver calls for the graphics library it
must be called peridically to output the contents of its circular buffer
Structures
Name Description
GFX_DRV_S1D13517_COMMAND Structure for the commands in the driver queue.
LAYER_REGISTERS This structure is used to describe layer registers.
File Name
S1D13517.h
Company
Microchip Technology Incorporated
5.1.5.8.1.3 drv_gfx_ssd1926.h
None
Functions
Name Description
GFX_DRV_SSD1926_BarFill Hardware accelerated barfill function
GFX_DRV_SSD1926_BrightnessSet Sets the brightness of the display backlight.
GFX_DRV_SSD1926_Busy Returns non-zero if LCD controller is busy (previous drawing operation is not
completed).
GFX_DRV_SSD1926_Close closes an instance of the graphics controller
GFX_DRV_SSD1926_GetReg returns graphics controller register value (byte access)
GFX_DRV_SSD1926_Initialize resets LCD, initializes PMP
GFX_DRV_SSD1926_Open opens an instance of the graphics controller
GFX_DRV_SSD1926_PixelArrayGet gets an array of pixels of length count starting at *color
GFX_DRV_SSD1926_PixelArrayPut outputs an array of pixels of length count starting at *color
GFX_DRV_SSD1926_PixelPut outputs one pixel into the frame buffer at the x,y coordinate given
GFX_DRV_SSD1926_PixelsPut outputs one pixel into the frame buffer at the x,y coordinate given
GFX_DRV_SSD1926_SetColor Sets the color for the driver instance
GFX_DRV_SSD1926_SetInstance Sets the instance for the driver
GFX_DRV_SSD1926_SetReg updates graphics controller register value (byte access)
GFX_DRV_SSD1926_Tasks Task machine that renders the driver calls for the graphics library it must be
called peridically to output the contents of its circular buffer
Structures
Name Description
GFX_DRV_SSD1926_COMMAND Structure for the commands in the driver queue.
GFX_DRV_SSD1926_TASK Structure for the task machine
File Name
SSD1926.h
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-298
Company
Microchip Technology Incorporated
5.1.5.8.2 drv_gfx_config_template.h
This is file drv_gfx_config_template.h.
5.1.5.9 Software Drivers
5.1.5.9.1 Low-Cost Controllerless (LCC) Graphics Driver Library
5.1.5.9.1.1 Introduction
Low-Cost Controllerless Graphics Driver Library
for
Microchip Microcontrollers
This library provides a low-level abstraction of the Low-Cost Controllerless Graphics Controller Driver Library that is available on
the Microchip family of microcontrollers with a convenient C language interface. It can be used to simplify low-level access to the
module without the necessity of interacting directly with the module's registers, there by hiding differences from one
microcontroller variant to another.
Description
Note: This information was not available at time of release and will be added in a future release of MPLAB Harmony.
5.1.5.9.1.2 Release Notes
MPLAB Harmony Version: v0.70b Low-Cost Controllerless Graphics Driver Library Version : 4.00b Release Date:
18Nov2013
New This Release:
This is the first release of the library. The interface can change in the beta and\or 1.0 release.
Known Issues:
DMA Channel 1 is non-configurable. The LCC driver will require DMA Channel 1 and not allow configuration via Harmony
system services.
5.1.5.9.1.3 SW License Agreement
(c) 2013 Microchip Technology Inc.
Microchip licenses this software to you solely for use with Microchip products. The software is owned by Microchip and its
licensors, and is protected under applicable copyright laws. All rights reserved.
SOFTWARE IS PROVIDED "AS IS" MICROCHIP EXPRESSLY DISCLAIMS ANY WARRANTY OF ANY KIND, WHETHER
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-299
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL MICROCHIP BE LIABLE FOR
ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, HARM TO
YOUR EQUIPMENT, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS
BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR
CONTRIBUTION, OR OTHER SIMILAR COSTS.
To the fullest extent allowed by law, Microchip and its licensors liability shall not exceed the amount of fees, if any, that you have
paid directly to Microchip to use this software.
MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE TERMS.
5.1.5.9.1.4 Using the Library
This topic describes the basic architecture of the Low-Cost Controllerless (LCC) Graphics Driver Library and provides
information and examples on how to use it.
Interface Header File: gfx_drv_lcc.h
The interface to the Low-Cost Controllerless (LCC) Graphics Driver library is defined in the "gfx_drv_lcc.h" header file. This file is
included by the "gfx_drv_lcc.h" file. Any C language source (.c) file that uses the Low-Cost Controllerless (LCC) Graphics Driver
Library should include "gfx_drv_lcc.h".
Library File:
The GFX Low-Cost Controller library archive (.a) file installed with MPLAB Harmony.
Please refer to the MPLAB Harmony Overview for how the Low-Cost Controllerless (LCC) Graphics Driver Library interacts with
the framework.
5.1.5.9.1.4.1 Library Overview
Refer to the section Driver Overview for how the driver operates in a system.
The library interface routines are divided into various sub-sections, each of sub-section addresses one of the blocks or the
overall operation of the Low-Cost Controllerless (LCC) Graphics Controller Driver module.
Library Interface Section Description
Functions This section lists the API functions available in the library.
5.1.5.9.1.4.2 Abstraction Model
This library provides the low-level abstraction of the Low-Cost Controllerless (LCC) Graphics Controller Driver module on the
Microchip family of graphic display controllers with a convenient C language interface. This topic describes how that abstraction
is modeled in the software and introduces the library interface.
Description
Low-Cost Controllerless (LCC) Graphics Controller Driver Abstraction Block Diagram
Note: This information was not available at time of release and will be added in a future release of MPLAB Harmony.
5.1.5.9.1.5 Configuring the Library
The configuration of the Low-Cost Controllerless (LCC) Graphics Driver Library is based on the file system_config.h.
This header file contains the configuration selection for the GFX Low-Cost Controller. Based on the selections made, the
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-300
Low-Cost Controllerless (LCC) Graphics Driver Library will support or not support selected features. These configuration settings
will apply to all instances of the Low-Cost Controllerless (LCC) Graphics Driver Library.
This header can be placed anywhere; however, the path of this header needs to be present in the include search path for a
successful build. Refer to the Applications Overview section for more details.
5.1.5.9.1.6 Building the Library
This section list the files that are available in the \src of theLow-Cost Controllerless (LCC) Graphics Driver Library. It lists which
files need to be included in the build based on either a hardware feature present on the board or configuration option selected by
the system.
• gfx_drv_lcc.c
5.1.5.9.1.7 Library Interface
This section describes the Application Programming Interface (API) functions of the Low-Cost Controllerless (LCC) Graphics
Driver Library.
Refer to each section for a detailed description.
5.1.5.9.1.7.1 Functions
Functions
Name Description
GFX_DRV_lcc_Close closes an instance of the graphics controller
GFX_DRV_lcc_Initialize resets LCD, initializes PMP
GFX_DRV_lcc_Open opens an instance of the graphics controller
GFX_DRV_lcc_Tasks Task machine that renders the driver calls for the graphics library it must be called
peridically to output the contents of its circular buffer
GFX_DRV_lcc_BrightnessSet Sets the brightness of the display backlight.
GFX_DRV_lcc_PixelArrayGet gets an array of pixels of length count starting at *color
GFX_DRV_lcc_PixelArrayPut outputs an array of pixels of length count starting at *color
GFX_DRV_lcc_PixelPut outputs one pixel into the frame buffer at the x,y coordinate given
GFX_DRV_lcc_PixelsPut outputs one pixel into the frame buffer at the x,y coordinate given
GFX_DRV_lcc_SetColor Sets the color for the driver instance
GFX_DRV_lcc_SetInstance Sets the instance for the driver
GFX_DRV_lcc_Layer This is function GFX_DRV_lcc_Layer.
GFX_DRV_lcc_SetPage This is function GFX_DRV_lcc_SetPage.
GFX_PRIM_SetPIPWindow This is function GFX_PRIM_SetPIPWindow.
Description
5.1.5.9.1.7.1.1 GFX_DRV_lcc_Close Function
C
uint16_t GFX_DRV_lcc_Close(
uint8_t instance
);
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-301
Description
none
Returns
0 - instance closed 2 - instance doesn't exist 3 - instance already closed
5.1.5.9.1.7.1.2 GFX_DRV_lcc_Initialize Function
C
uint16_t GFX_DRV_lcc_Initialize(
uint8_t instance
);
Description
none
Parameters
Parameters Description
instance driver instance
Returns
NULL - call not successful (PMP driver busy) !NULL - address of the display driver queue command
5.1.5.9.1.7.1.3 GFX_DRV_lcc_Open Function
C
uint16_t GFX_DRV_lcc_Open(
uint8_t instance
);
Description
none
Returns
1 - driver not initialied 2 - instance doesn't exist 3 - instance already open instance to driver when successful
5.1.5.9.1.7.1.4 GFX_DRV_lcc_Tasks Function
C
void GFX_DRV_lcc_Tasks();
5.1.5.9.1.7.1.5 GFX_DRV_lcc_BrightnessSet Function
C
void GFX_DRV_lcc_BrightnessSet(
uint8_t instance,
uint16_t level
);
Description
none
Parameters
Parameters Description
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-302
5.1.5.9.1.7.1.6 GFX_DRV_lcc_PixelArrayGet Function
C
uint16_t* GFX_DRV_lcc_PixelArrayGet(
uint16_t * color,
short x,
short y,
uint16_t count
);
Description
none
Parameters
Parameters Description
instance driver instance
*color start of the array
x x coordinate of the start point.
y y coordinate of the end point.
count number of pixels
Returns
NULL - call not successful (lcc driver busy) !NULL - address of the display driver queue command
5.1.5.9.1.7.1.7 GFX_DRV_lcc_PixelArrayPut Function
C
uint16_t* GFX_DRV_lcc_PixelArrayPut(
uint16_t * color,
short x,
short y,
uint16_t count,
uint16_t lineCount
);
Description
none
Parameters
Parameters Description
instance driver instance
*color start of the array
x x coordinate of the start point.
y y coordinate of the end point.
count number of pixels
Returns
NULL - call not successful !NULL - handle to the number of pixels remaining
5.1.5.9.1.7.1.8 GFX_DRV_lcc_PixelPut Function
C
uint16_t GFX_DRV_lcc_PixelPut(
short x,
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-303
short y
);
Description
none
Parameters
Parameters Description
x,y pixel coordinates
Returns
NULL - call not successful (lcc driver busy) !NULL - address of the display driver queue command
5.1.5.9.1.7.1.9 GFX_DRV_lcc_PixelsPut Function
C
uint16_t GFX_DRV_lcc_PixelsPut(
short x,
short y,
uint16_t count,
uint16_t lineCount
);
Description
none
Parameters
Parameters Description
x,y pixel coordinates
Returns
NULL - call not successful (lcc driver busy) !NULL - address of the display driver queue command
5.1.5.9.1.7.1.10 GFX_DRV_lcc_SetColor Function
C
void GFX_DRV_lcc_SetColor(
GFX_COLOR color
);
Returns
none
5.1.5.9.1.7.1.11 GFX_DRV_lcc_SetInstance Function
C
void GFX_DRV_lcc_SetInstance(
uint8_t instance
);
Returns
none
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-304
5.1.5.9.1.7.1.12 GFX_DRV_lcc_Layer Function
C
uint16_t* GFX_DRV_lcc_Layer(
uint8_t instance,
GFX_LAYER_PARAMS* layer
);
Description
This is function GFX_DRV_lcc_Layer.
5.1.5.9.1.7.1.13 GFX_DRV_lcc_SetPage Function
C
uint16_t GFX_DRV_lcc_SetPage(
uint8_t pageType,
uint8_t page
);
Description
This is function GFX_DRV_lcc_SetPage.
5.1.5.9.1.7.1.14 GFX_PRIM_SetPIPWindow Function
C
void GFX_PRIM_SetPIPWindow(
uint16_t left,
uint16_t top,
uint16_t hlength,
uint16_t vlength,
uint16_t pipx,
uint16_t pipy
);
Description
This is function GFX_PRIM_SetPIPWindow.
5.1.5.9.1.7.2 Data Types and Constants
Enumerations
Name Description
LCC_TASK This is type LCC_TASK.
DMA_ISR_TASK This is type DMA_ISR_TASK.
Macros
Name Description
USE_LCC_SCROLLING This is macro USE_LCC_SCROLLING.
USE_PIP This is macro USE_PIP.
PIP_BUFFER This is macro PIP_BUFFER.
GFX_DRV_lcc_COMMANDQUEUESIZE This is macro GFX_DRV_lcc_COMMANDQUEUESIZE.
Structures
Name Description
GFX_DRV_lcc_COMMAND Structure for the commands in the driver queue.
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-305
Description
5.1.5.9.1.7.2.1 USE_LCC_SCROLLING Macro
C
#define USE_LCC_SCROLLING
Description
This is macro USE_LCC_SCROLLING.
5.1.5.9.1.7.2.2 USE_PIP Macro
C
#define USE_PIP
Description
This is macro USE_PIP.
5.1.5.9.1.7.2.3 GFX_DRV_lcc_COMMAND Structure
C
typedef struct {
uint8_t instance;
union {
uint32_t Val;
struct {
uint8_t b0 : 1;
uint8_t b1 : 1;
uint8_t b2 : 1;
uint8_t b3 : 1;
uint8_t b4 : 1;
uint8_t b5 : 1;
uint8_t b6 : 1;
uint8_t b7 : 1;
uint8_t b8 : 1;
uint8_t b9 : 1;
uint8_t b10 : 1;
uint8_t b11 : 1;
uint8_t b12 : 1;
uint8_t b13 : 1;
uint8_t b14 : 1;
uint8_t b15 : 1;
uint8_t b16 : 1;
uint8_t b17 : 1;
uint8_t b18 : 1;
uint8_t b19 : 1;
uint8_t b20 : 1;
uint8_t b21 : 1;
uint8_t b22 : 1;
uint8_t b23 : 1;
uint8_t b24 : 1;
uint8_t b25 : 1;
uint8_t b26 : 1;
uint8_t b27 : 1;
uint8_t b28 : 1;
uint8_t b29 : 1;
uint8_t b30 : 1;
uint8_t b31 : 1;
} bits;
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-306
} address;
uint16_t * array;
uint16_t data;
uint16_t count;
uint16_t lineCount;
uint8_t task;
} GFX_DRV_lcc_COMMAND;
Description
Structure: GFX_DRV_lcc_COMMAND
None
5.1.5.9.1.7.2.4 PIP_BUFFER Macro
C
#define PIP_BUFFER (3)
Description
This is macro PIP_BUFFER.
5.1.5.9.1.7.2.5 LCC_TASK Enumeration
C
typedef enum {
UPDATE_CLOCK = 0,
INITIALIZE,
WAIT_TRANSMIT_PIXELS,
FINISH_TRANSMIT_PIXELS,
WAIT_TRANSMIT_ARRAY,
FINISH_TRANSMIT_ARRAY,
WAIT_RECEIVE,
READ_RECEIVE,
PUT_ARRAY,
PUT_PIXELS,
GET_PIXELS,
COPY_PIXELS,
PAGE,
LAYERS
} LCC_TASK;
Description
This is type LCC_TASK.
5.1.5.9.1.7.2.6 GFX_DRV_lcc_COMMANDQUEUESIZE Macro
C
#define GFX_DRV_lcc_COMMANDQUEUESIZE 480
Description
This is macro GFX_DRV_lcc_COMMANDQUEUESIZE.
5.1.5.9.1.7.2.7 DMA_ISR_TASK Enumeration
C
typedef enum {
ACTIVE_PERIOD = 0,
BLANKING_PERIOD,
FINISH_LINE,
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-307
OVERFLOW,
PIP,
SCROLL
} DMA_ISR_TASK;
Description
This is type DMA_ISR_TASK.
5.1.5.9.1.8 Files
Files
Name Description
5.1.5.9.1.8.1 drv_gfx_lcc_config_template.h
• Module for Microchip Graphics Library
• This file contains compile time options for the Graphics Library.
*******************************************************************
• FileName: GraphicsConfig.h
• Dependencies: none
• Processor: PIC24F, PIC24H, dsPIC, PIC32
• Compiler: C30 V3.00/C32
• Company: Microchip Technology, Inc.
*
• Software License Agreement
*
• Copyright © 2008 Microchip Technology Inc. All rights reserved.
• Microchip licenses to you the right to use, modify, copy and distribute
• Software only when embedded on a Microchip microcontroller or digital
• signal controller, which is integrated into your product or third party
• product (pursuant to the sublicense terms in the accompanying license
• agreement).
*
• You should refer to the license agreement accompanying this Software
• for additional information regarding your rights and obligations.
*
• SOFTWARE AND DOCUMENTATION ARE PROVIDED ?AS IS? WITHOUT WARRANTY OF ANY
• KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION, ANY WARRANTY
• OF MERCHANTABILITY, TITLE, NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR
• PURPOSE. IN NO EVENT SHALL MICROCHIP OR ITS LICENSORS BE LIABLE OR
• OBLIGATED UNDER CONTRACT, NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION,
• BREACH OF WARRANTY, OR OTHER LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT
• DAMAGES OR EXPENSES INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL,
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-308
• INDIRECT, PUNITIVE OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA,
• COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY
• CLAIMS BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF),
• OR OTHER SIMILAR COSTS.
*
• Author Date Comment
*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
• Anton Alkhimenok 10/28/2007 Initial Version
• Pradeep Budagutta 10/28/2007 Display related defines
• moved to DisplayConfig.h
5.1.5.10 Hardware Drivers
5.1.5.10.1 OTM2201A Graphics Controller Driver Library
5.1.5.10.1.1 Introduction
OTM2201A Graphics Controller Driver Library
for
Microchip Microcontrollers
This library provides a low-level abstraction of the OTM2201A Graphics Controller Driver Library that is available on the
Microchip family of microcontrollers with a convenient C language interface. It can be used to simplify low-level access to the
module without the necessity of interacting directly with the module's registers, there by hiding differences from one
microcontroller variant to another.
Description
Note: This information was not available at time of release and will be added in a future release of MPLAB Harmony.
5.1.5.10.1.2 Release Notes
MPLAB Harmony Version: v0.70b OTM2201A Graphics Controller Driver Library Version : 4.00b Release Date: 18Nov2013
New This Release:
This is the first release of the library. The interface can change in the beta and\or 1.0 release.
Known Issues:
Nothing to report in this release.
5.1.5.10.1.3 SW License Agreement
(c) 2013 Microchip Technology Inc.
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-309
Microchip licenses this software to you solely for use with Microchip products. The software is owned by Microchip and its
licensors, and is protected under applicable copyright laws. All rights reserved.
SOFTWARE IS PROVIDED "AS IS" MICROCHIP EXPRESSLY DISCLAIMS ANY WARRANTY OF ANY KIND, WHETHER
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL MICROCHIP BE LIABLE FOR
ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, HARM TO
YOUR EQUIPMENT, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS
BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR
CONTRIBUTION, OR OTHER SIMILAR COSTS.
To the fullest extent allowed by law, Microchip and its licensors liability shall not exceed the amount of fees, if any, that you have
paid directly to Microchip to use this software.
MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE TERMS.
5.1.5.10.1.4 Using the Library
This topic describes the basic architecture of the OTM2201A Graphics Controller Driver Library and provides information and
examples on how to use it.
Interface Header File: drv_gfx_otm2201a.h
The interface to the OTM2201A Graphics Controller Driver library is defined in the "drv_gfx_otm2201a.h" header file. This file is
included by the "gfx_primitive.h" file. Any C language source (.c) file that uses the OTM2201A Graphics Controller Driver library
should include "gfx_primitive.h".
Library File:
The OTM2201A Graphics Controller Driver library archive (.a) file installed with MPLAB Harmony.
Please refer to the MPLAB Harmony Overview for how the OTM2201A Graphics Controller Driver interacts with the framework.
5.1.5.10.1.4.1 Abstraction Model
This library provides the low-level abstraction of the OTM2201A Graphics Controller Driver module on the Microchip family of
microcontrollers with a convenient C language interface. This topic describes how that abstraction is modeled in the software
and introduces the library interface.
Description
OTM2201A Graphics Controller Driver Abstraction Block Diagram
Note: This information was not available at time of release and will be added in a future release of MPLAB Harmony.
5.1.5.10.1.4.2 Library Overview
Refer to the section Driver Overview for how the driver operates in a system.
The library interface routines are divided into various sub-sections, each of sub-section addresses one of the blocks or the
overall operation of the OTM2201 Graphics Controller Driver module.
Library Interface Section Description
Functions This section lists the API functions available in the library.
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-310
5.1.5.10.1.5 Configuring the Driver Library
The configuration of the OTM2201 Graphics Controller Driver is based on the file sys_config.h
This header file contains the configuration selection for the OTM2201 Graphics Controller Driver. Based on the selections made,
the OTM2201 Graphics Controller Driver will support or not support selected features. These configuration settings will apply to
all instances of the OTM2201 Graphics Controller Driver.
This header can be placed anywhere; however, the path of this header needs to be present in the include search path for a
successful build. Refer to the Applications Overview section for more details.
5.1.5.10.1.6 Building the Library
This section list the files that are available in the \src of the OTM2201A Graphics Controller Driver. It lists which files need to be
included in the build based on either a hardware feature present on the board or configuration option selected by the system.
• drv_gfx_otm2201a.c
5.1.5.10.1.7 Library Interface
This section describes the Application Programming Interface (API) functions of the OTM2201A Graphics Controller Driver
Library.
Refer to each section for a detailed description.
5.1.5.10.1.7.1 Functions
Functions
Name Description
GFX_DRV_OTM2201A_AddressSet Sets the start GRAM address where pixel data to be written
GFX_DRV_OTM2201A_BrightnessSet Sets the brightness of the display backlight.
GFX_DRV_OTM2201A_Busy Returns non-zero value if LCD controller is busy (previous drawing
operation is not completed).
GFX_DRV_OTM2201A_Close Closes an instance of the graphics controller
GFX_DRV_OTM2201A_ColorSet Sets the color for the driver instance
GFX_DRV_OTM2201A_Initialize Intialize OTM2201A device
GFX_DRV_OTM2201A_InstanceSet Sets the instance for the driver
GFX_DRV_OTM2201A_Open Opens an instance of the graphics controller
GFX_DRV_OTM2201A_PixelArrayGet Gets an array of pixels of length count into an array starting at *color
GFX_DRV_OTM2201A_PixelArrayPut Outputs an array of pixels of length count starting at *color
GFX_DRV_OTM2201A_PixelPut Outputs one pixel into the frame buffer at the x,y coordinate given
GFX_DRV_OTM2201A_PixelsPut Outputs count number of pixels into the frame buffer from the given x,y
coordinate.
GFX_DRV_OTM2201A_RegGet Returns graphics controller register value (byte access)
GFX_DRV_OTM2201A_RegSet Updates graphics controller register value (byte access)
GFX_DRV_OTM2201A_Tasks Task machine that renders the driver calls for the graphics library it must
be called peridically to output the contents of its circular buffer
Description
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-311
5.1.5.10.1.7.1.1 GFX_DRV_OTM2201A_AddressSet Function
C
uint16_t GFX_DRV_OTM2201A_AddressSet(
uint32_t address
);
Description
Address consists of Lower 8 bit at Register REG_RAM_ADDR_LOW and Higher 8 bit at Register REG_RAM_ADDR_HIGH
Parameters
Parameters Description
address pixel address
Returns
DRV_OTM2201A_ERROR_PMP_WRITE - returns error during PMP Write, DRV_OTM2201A_ERROR_NO_ERROR - returns
success without any error.
5.1.5.10.1.7.1.2 GFX_DRV_OTM2201A_BrightnessSet Function
C
void GFX_DRV_OTM2201A_BrightnessSet(
uint8_t instance,
uint16_t level
);
Description
Sets the brightness of the display backlight.
Parameters
Parameters Description
instance instance of the driver
level Brightness level. Valid values are 0 to 100. 0 = brightness level is zero or display
is turned off. 100 = brightness level is maximum.
Returns
none
5.1.5.10.1.7.1.3 GFX_DRV_OTM2201A_Busy Function
C
uint16_t GFX_DRV_OTM2201A_Busy(
uint8_t instance
);
Description
Returns non-zero value if LCD controller is busy (previous drawing operation is not completed).
Parameters
Parameters Description
instance driver instance
Returns
DRV_OTM2201A_ERROR_DEVICE_BUSY - Device is busy, DRV_OTM2201A_ERROR_NO_ERROR - Success, driver is not
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-312
busy.
5.1.5.10.1.7.1.4 GFX_DRV_OTM2201A_Close Function
C
uint16_t GFX_DRV_OTM2201A_Close(
uint8_t instance
);
Description
Closes an instance if instance exists and not already closed
Parameters
Parameters Description
instance instance of the driver
Returns
DRV_OTM2201A_INSTANCE_CLOSED - instance closed, DRV_OTM2201A_INSTANCE_DOESNT_EXIST - instance doesn't
exist, DRV_OTM2201A_INSTANCE_ALREADY_CLOSED - instance already closed.
5.1.5.10.1.7.1.5 GFX_DRV_OTM2201A_ColorSet Function
C
void GFX_DRV_OTM2201A_ColorSet(
GFX_COLOR color
);
Description
Sets the color for the driver instance
Parameters
Parameters Description
color 16 bit 565 format color value
Returns
none
5.1.5.10.1.7.1.6 GFX_DRV_OTM2201A_Initialize Function
C
uint16_t GFX_DRV_OTM2201A_Initialize(
uint8_t instance
);
Description
Initialize OTM2201A device by initializing PMP interface, initializing command buffer for current instance initialize device registers
Parameters
Parameters Description
instance driver instance
Returns
DRV_OTM2201A_ERROR_QUEUE_FULL - OTM2201A command queue is full, DRV_OTM2201A_ERROR_REG_GET -
OTM2201A Error while reading register, DRV_OTM2201A_ERROR_REG_SET - OTM2201A Error while writing register,
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-313
DRV_OTM2201A_ERROR_DEVICE_BUSY - OTM2201A device is busy, DRV_OTM2201A_ERROR_NO_ERROR - Success
without any error.
5.1.5.10.1.7.1.7 GFX_DRV_OTM2201A_InstanceSet Function
C
void GFX_DRV_OTM2201A_InstanceSet(
uint8_t instance
);
Description
Sets the instance for the driver
Parameters
Parameters Description
instance driver instance
Returns
none
5.1.5.10.1.7.1.8 GFX_DRV_OTM2201A_Open Function
C
uint16_t GFX_DRV_OTM2201A_Open(
uint8_t instance
);
Description
Opens the instance of driver if instance is valid and not already opened
Parameters
Parameters Description
instance instance of the driver
Returns
DRV_OTM2201A_NEW_INSTANCE_OPEN - driver not initialied, DRV_OTM2201A_INSTANCE_DOESNT_EXIST - instance
doesn't exist, DRV_OTM2201A_INSTANCE_ALREADY_OPEN - instance already open.
5.1.5.10.1.7.1.9 GFX_DRV_OTM2201A_PixelArrayGet Function
C
uint16_t* GFX_DRV_OTM2201A_PixelArrayGet(
uint16_t * color,
short x,
short y,
uint16_t count
);
Description
Gets an array of pixels of length count into an array starting at *color
Parameters
Parameters Description
color Pointer to array where color data is to be loaded
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-314
x pixel coordinate on x axis
y pixel coordinate on y axis
count count number of pixels
Returns
DRV_OTM2201A_ERROR_QUEUE_FULL - OTM2201A command queue is full, DRV_OTM2201A_ERROR_NO_ERROR -
Success without any error.
5.1.5.10.1.7.1.10 GFX_DRV_OTM2201A_PixelArrayPut Function
C
uint16_t* GFX_DRV_OTM2201A_PixelArrayPut(
uint16_t * color,
short x,
short y,
uint16_t count,
uint16_t lineCount
);
Description
Outputs an array of pixels of length count starting at *color
Parameters
Parameters Description
color pointer to array of color of pixels
x pixel coordinate on x axis.
y pixel coordinate on y axis.
count count number of pixels
lineCount lineCount number of display lines
Returns
handle - handle to the number of pixels remaining, DRV_OTM2201A_ERROR_QUEUE_FULL - OTM2201A command queue is
full.
5.1.5.10.1.7.1.11 GFX_DRV_OTM2201A_PixelPut Function
C
uint16_t GFX_DRV_OTM2201A_PixelPut(
short x,
short y
);
Description
Outputs one pixel into the frame buffer at the x,y coordinate given
Parameters
Parameters Description
x pixel coordinate on x axis
y pixel coordinate on y axis
Returns
DRV_OTM2201A_ERROR_QUEUE_FULL - OTM2201A command queue is full, DRV_OTM2201A_ERROR_NO_ERROR -
Success without any error.
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-315
5.1.5.10.1.7.1.12 GFX_DRV_OTM2201A_PixelsPut Function
C
uint16_t GFX_DRV_OTM2201A_PixelsPut(
short x,
short y,
uint16_t count,
uint16_t lineCount
);
Description
Outputs count number of pixels into the frame buffer from the given x,y coordinate.
Parameters
Parameters Description
x pixel coordinate on x axis
y pixel coordinate on y axis
count count number of pixels
lineCount lineCount number of display lines
Returns
DRV_OTM2201A_ERROR_QUEUE_FULL - OTM2201A command queue is full, DRV_OTM2201A_ERROR_NO_ERROR -
Success without any error.
5.1.5.10.1.7.1.13 GFX_DRV_OTM2201A_RegGet Function
C
uint8_t GFX_DRV_OTM2201A_RegGet(
uint16_t index,
uint16_t * data
);
Description
Returns graphics controller register value (byte access)
Parameters
Parameters Description
index register number
*data array to store register data
Returns
DRV_OTM2201A_ERROR_PMP_WRITE - returns error during PMP Write, DRV_OTM2201A_ERROR_PMP_READ - returns
error during PMP Read, DRV_OTM2201A_ERROR_NO_ERROR - returns success without any error.
5.1.5.10.1.7.1.14 GFX_DRV_OTM2201A_RegSet Function
C
uint16_t GFX_DRV_OTM2201A_RegSet(
uint16_t index,
uint16_t value,
uint32_t repeatCount
);
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-316
Description
This call can set "value" of the register accessed by its "index" and can repeat the same by number of times mentioned in
"repeatCount"
Parameters
Parameters Description
index register number
value value to write to register
repeatCount repeatCount number of times value is to be written to the register.
Returns
DRV_OTM2201A_ERROR_PMP_WRITE - returns error during PMP Write, DRV_OTM2201A_ERROR_NO_ERROR - returns
success without any error.
5.1.5.10.1.7.1.15 GFX_DRV_OTM2201A_Tasks Function
C
void GFX_DRV_OTM2201A_Tasks();
Description
Task machine that renders the driver calls for the graphics library it must be called peridically to output the contents of its circular
buffer.
5.1.5.10.1.7.2 Data Types and Constants
Enumerations
Name Description
OTM2201A_TASK Enumeration for command type.
Structures
Name Description
GFX_DRV_OTM2201A_COMMAND Structure for the commands in the driver queue.
Description
5.1.5.10.1.7.2.1 GFX_DRV_OTM2201A_COMMAND Structure
C
typedef struct {
uint8_t instance;
uint32_t address;
uint16_t * array;
uint16_t data;
uint16_t count;
uint16_t lineCount;
OTM2201A_TASK task;
} GFX_DRV_OTM2201A_COMMAND;
Description
Structure: GFX_DRV_OTM2201A_COMMAND
Structure for the commands in the driver queue.
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-317
Parameters
Parameters Description
instance instance of the driver
address pixel address
array pointer to array of pixel data
data pixel color
count count number of pixels in one line
lineCount lineCount number of lines of display
task Type of task (OTM2201A_TASK enum)
5.1.5.10.1.7.2.2 OTM2201A_TASK Enumeration
C
typedef enum {
INITIALIZE = 0,
BUSY,
PUT_ARRAY,
PUT_PIXELS
} OTM2201A_TASK;
Description
Enum: OTM2201A_TASK
Enumeration for command type.
Parameters
Parameters Description
INITIALIZE driver initialization task
BUSY driver busy task
PUT_ARRAY driver put array task
PUT_PIXELS driver put pixels task
5.1.5.10.1.7.3 Files
Files
Name Description
drv_gfx_otm2201a.h Interface for the graphics library where the primitives are renderred and sent to the
graphics controller either external or internal
Description
5.1.5.10.1.7.3.1 drv_gfx_otm2201a.h
None
Enumerations
Name Description
OTM2201A_TASK Enumeration for command type.
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-318
Functions
Name Description
GFX_DRV_OTM2201A_AddressSet Sets the start GRAM address where pixel data to be written
GFX_DRV_OTM2201A_BrightnessSet Sets the brightness of the display backlight.
GFX_DRV_OTM2201A_Busy Returns non-zero value if LCD controller is busy (previous drawing
operation is not completed).
GFX_DRV_OTM2201A_Close Closes an instance of the graphics controller
GFX_DRV_OTM2201A_ColorSet Sets the color for the driver instance
GFX_DRV_OTM2201A_Initialize Intialize OTM2201A device
GFX_DRV_OTM2201A_InstanceSet Sets the instance for the driver
GFX_DRV_OTM2201A_Open Opens an instance of the graphics controller
GFX_DRV_OTM2201A_PixelArrayGet Gets an array of pixels of length count into an array starting at *color
GFX_DRV_OTM2201A_PixelArrayPut Outputs an array of pixels of length count starting at *color
GFX_DRV_OTM2201A_PixelPut Outputs one pixel into the frame buffer at the x,y coordinate given
GFX_DRV_OTM2201A_PixelsPut Outputs count number of pixels into the frame buffer from the given x,y
coordinate.
GFX_DRV_OTM2201A_RegGet Returns graphics controller register value (byte access)
GFX_DRV_OTM2201A_RegSet Updates graphics controller register value (byte access)
GFX_DRV_OTM2201A_Tasks Task machine that renders the driver calls for the graphics library it must
be called peridically to output the contents of its circular buffer
Structures
Name Description
GFX_DRV_OTM2201A_COMMAND Structure for the commands in the driver queue.
File Name
drv_gfx_otm2201a.h
Company
Microchip Technology Incorporated
5.1.5.10.2 S1D13517 Graphics Controller Driver Library
5.1.5.10.2.1 Introduction
S1D13517 Graphics Controller Driver Library
for
Microchip Microcontrollers
This library provides a low-level abstraction of the S1D13517 Graphics Controller Driver Library that is available on the Microchip
family of microcontrollers with a convenient C language interface. It can be used to simplify low-level access to the module
without the necessity of interacting directly with the module's registers, there by hiding differences from one microcontroller
variant to another.
Description
Note: This information was not available at time of release and will be added in a future release of MPLAB Harmony.
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-319
5.1.5.10.2.2 Release Notes
MPLAB Harmony Version: v0.70b S1D13517 Graphics Driver Library Version : 4.00b Release Date: 18Nov2013
New This Release:
This is the first release of the library. The interface can change in the beta and\or 1.0 release.
Known Issues:
Nothing to report in this release.
5.1.5.10.2.3 SW License Agreement
(c) 2013 Microchip Technology Inc.
Microchip licenses this software to you solely for use with Microchip products. The software is owned by Microchip and its
licensors, and is protected under applicable copyright laws. All rights reserved.
SOFTWARE IS PROVIDED "AS IS" MICROCHIP EXPRESSLY DISCLAIMS ANY WARRANTY OF ANY KIND, WHETHER
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL MICROCHIP BE LIABLE FOR
ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, HARM TO
YOUR EQUIPMENT, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS
BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR
CONTRIBUTION, OR OTHER SIMILAR COSTS.
To the fullest extent allowed by law, Microchip and its licensors liability shall not exceed the amount of fees, if any, that you have
paid directly to Microchip to use this software.
MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE TERMS.
5.1.5.10.2.4 Using the Library
This topic describes the basic architecture of the S1D13517 Graphics Controller Driver Library and provides information and
examples on how to use it.
Interface Header File: gfx_drv_s1d13517.h
The interface to the S1D13517 Graphics Controller Driver Library is defined in the "gfx_drv_s1d13517.h" header file. This file is
included by the "gfx_drv_s1d13517.h" file. Any C language source (.c) file that uses the S1D13517 Graphics Controller Driver
Library should include "gfx_drv_s1d13517.h".
Library File:
The S1D13517 Graphics Controller Driver Library archive (.a) file installed with MPLAB Harmony.
Please refer to the MPLAB Harmony Overview for how the GFX S1D13517 Controller Driver interacts with the framework.
5.1.5.10.2.4.1 Abstraction Model
This library provides the low-level abstraction of the S1D13517 Graphics Controller Driver module of the Microchip family of
graphic display controllers with a convenient C language interface. This topic describes how that abstraction is modeled in the
software and introduces the library interface.
Description
S1D13517 Graphics Controller Driver Abstraction Block Diagram
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-320
Note: This information was not available at time of release and will be added in a future release of MPLAB Harmony.
5.1.5.10.2.4.2 Library Overview
Refer to the section Driver Overview for how the driver operates in a system.
The library interface routines are divided into various sub-sections, each of sub-section addresses one of the blocks or the
overall operation of the S1D13517 Graphics Controller Driver module.
Library Interface Section Description
Functions This section lists the API functions available in the library.
5.1.5.10.2.5 Configuring the Library
Macros
Name Description
USE_ANALOGCLOCK Enable Analog Clock Object.
5.1.5.10.2.5.1 USE_ANALOGCLOCK Macro
C
#define USE_ANALOGCLOCK
Description
Enable Analog Clock Object.
5.1.5.10.2.5.2 USE_BITMAP_FLASH Macro
C
#define USE_BITMAP_FLASH
Description
Similar to Font data bitmaps can also be placed in two locations. One is in FLASH memory and the other is from external
memory. Definining one or both enables the support for bitmaps located in internal flash and external memory. Define this in
GraphicsConfig.h
• USE_BITMAP_FLASH - Images located in internal flash memory.
• USE_BITMAP_EXTERNAL - Images located in external memory (including external memory mapped to EDS)..
5.1.5.10.2.5.3 USE_BUTTON Macro
C
#define USE_BUTTON
Description
Enable Button Object.
5.1.5.10.2.5.4 USE_CHART Macro
C
#define USE_CHART
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-321
Description
This is macro USE_CHART.
5.1.5.10.2.5.5 USE_CHECKBOX Macro
C
#define USE_CHECKBOX
Description
Enable Checkbox Object.
5.1.5.10.2.5.6 USE_COMP_RLE Macro
C
#define USE_COMP_RLE
Description
• Overview: To enable support for DEFLATE compressed images for PutImage().
• When this macro is enabled, the PutImage() function will
• be able to process images generated by the Graphics Resource
• Converter (GRC) that are compressed using the DEFLATE algorithm.
• PutImage() will need the IPU module of the Microchip Graphics
• Module to decompress. Enable this feature only when the driver
• features the IPU module (example: PIC24FJ2456DA210).
• Define this in GraphicsConfig.h
*
******************************************************************
#define USE_COMP_IPU
5.1.5.10.2.5.7 USE_CUSTOM Macro
C
#define USE_CUSTOM
Description
Enable Custom Control Object (an example to create customized Object).
5.1.5.10.2.5.8 USE_DIGITALMETER Macro
C
#define USE_DIGITALMETER
Description
Enable DigitalMeter Object.
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-322
5.1.5.10.2.5.9 USE_EDITBOX Macro
C
#define USE_EDITBOX
Description
Enable Edit Box Object.
5.1.5.10.2.5.10 USE_FONT_FLASH Macro
C
#define USE_FONT_FLASH
5.1.5.10.2.5.11 USE_GOL Macro
C
#define USE_GOL
Description
Enable Graphics Object Layer.
5.1.5.10.2.5.12 USE_GRADIENT Macro
C
#define USE_GRADIENT
Description
To enable support for Gradient bars and bevel primitives. Define this in GraphicsConfig.h.
5.1.5.10.2.5.13 USE_GROUPBOX Macro
C
#define USE_GROUPBOX
Description
Enable Group Box Object.
5.1.5.10.2.5.14 USE_LISTBOX Macro
C
#define USE_LISTBOX
Description
Enable List Box Object.
5.1.5.10.2.5.15 USE_METER Macro
C
#define USE_METER
Description
Enable Meter Object.
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-323
5.1.5.10.2.5.16 USE_MULTIBYTECHAR Macro
C
#define USE_MULTIBYTECHAR
Description
To enable support for unicode fonts, USE_MULTIBYTECHAR must be defined. This sets the XCHAR definition (0-2^16 range).
See XCHAR for details. Define this in GraphicsConfig.h
5.1.5.10.2.5.17 USE_PICTURE Macro
C
#define USE_PICTURE
Description
Enable Picture Object.
5.1.5.10.2.5.18 USE_PROGRESSBAR Macro
C
#define USE_PROGRESSBAR
Description
Enable Progress Bar Object.
5.1.5.10.2.5.19 USE_RADIOBUTTON Macro
C
#define USE_RADIOBUTTON
Description
Enable Radio Button Object.
5.1.5.10.2.5.20 USE_ROUNDDIAL Macro
C
#define USE_ROUNDDIAL
Description
Enable Dial Object.
5.1.5.10.2.5.21 USE_SLIDER Macro
C
#define USE_SLIDER
Description
Enable Slider or Scroll Bar Object.
5.1.5.10.2.5.22 USE_STATICTEXT Macro
C
#define USE_STATICTEXT
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-324
Description
Enable Static Text Object.
5.1.5.10.2.5.23 USE_TEXTENTRY Macro
C
#define USE_TEXTENTRY
Description
Enable TextEntry Object.
5.1.5.10.2.5.24 USE_TOUCHSCREEN Macro
C
#define USE_TOUCHSCREEN
5.1.5.10.2.5.25 USE_WINDOW Macro
C
#define USE_WINDOW
Description
Enable Window Object.
5.1.5.10.2.5.26 COLOR_DEPTH Macro
C
#define COLOR_DEPTH 16
Description
Specifies the color depth used in the application defined in GraphicsConfig.h.
5.1.5.10.2.5.27 DRIVER_COUNT Macro
C
#define DRIVER_COUNT 1
Description
• Overview: For XC16 or C30 builds only: When placing fonts in internal
• data memory, there is a 32K limit for data space. The total
• data should not exceed 32K. When this is unavoidable, the macro
• USE_GFX_FONT_IN_PROGRAM_SECTION will relocate the font in
• program space. This will remove the 32K restriction but at
• the expense of slower access.
• Define this in GraphicsConfig.h to enable the font to be
• placed in program space.
*
******************************************************************
#define USE_GFX_FONT_IN_PROGRAM_SECTION
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-325
5.1.5.10.2.5.28 GFX_free Macro
C
#define GFX_free(pObj) free(pObj) //
Description
When using Operating Systems (OS), define the OS specific malloc() and free() functions for compatibility with the OS based
systems. Define these in GraphicsConfig.h
5.1.5.10.2.5.29 GFX_malloc Macro
C
#define GFX_malloc(size) malloc(size)
Description
When using Operating Systems (OS), define the OS specific malloc() and free() functions for compatibility with the OS based
systems. Define these in GraphicsConfig.h
5.1.5.10.2.6 Building the Library
This section list the files that are available in the \src of the S1D13517 Graphics Controller Driver Library. It lists which files need
to be included in the build based on either a hardware feature present on the board or configuration option selected by the
system.
• drv_gfx_s1d13517.c
5.1.5.10.2.7 Library Interface
This section describes the Application Programming Interface (API) functions of the S1D13517 Graphics Controller Driver Library.
Refer to each section for a detailed description.
5.1.5.10.2.7.1 Functions
Functions
Name Description
GFX_DRV_S1D13517_AlphaBlendWindow SEE primitive layer alphablendWindow definition
GFX_DRV_S1D13517_BrightnessSet Sets the brightness of the display backlight.
GFX_DRV_S1D13517_Close closes an instance of the graphics controller
GFX_DRV_S1D13517_GetReg returns graphics controller register value (byte access)
GFX_DRV_S1D13517_Initialize resets LCD, initializes PMP
GFX_DRV_S1D13517_Layer Updates a Layer depending on the layer parameters.
GFX_DRV_S1D13517_Open opens an instance of the graphics controller
GFX_DRV_S1D13517_PixelArrayPut outputs an array of pixels of length count starting at *color
GFX_DRV_S1D13517_PixelPut outputs one pixel into the frame buffer at the x,y coordinate given
GFX_DRV_S1D13517_PixelsPut outputs one pixel into the frame buffer at the x,y coordinate given
GFX_DRV_S1D13517_SetColor Sets the color for the driver instance
GFX_DRV_S1D13517_SetInstance Sets the instance for the driver
GFX_DRV_S1D13517_SetPage Sets the page of a certain page type
GFX_DRV_S1D13517_SetReg updates graphics controller register value (byte access)
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-326
GFX_DRV_S1D13517_Tasks Task machine that renders the driver calls for the graphics library it
must be called peridically to output the contents of its circular buffer
Description
5.1.5.10.2.7.1.1 GFX_DRV_S1D13517_AlphaBlendWindow Function
C
uint16_t* GFX_DRV_S1D13517_AlphaBlendWindow(
GFX_ALPHA_PARAMS* alphaParams,
uint16_t width,
uint16_t height,
uint8_t alpha
);
5.1.5.10.2.7.1.2 GFX_DRV_S1D13517_BrightnessSet Function
C
void GFX_DRV_S1D13517_BrightnessSet(
uint8_t instance,
uint16_t level
);
Description
none
Parameters
Parameters Description
5.1.5.10.2.7.1.3 GFX_DRV_S1D13517_Close Function
C
uint16_t GFX_DRV_S1D13517_Close(
uint8_t instance
);
Description
none
Returns
0 - instance closed 2 - instance doesn't exist 3 - instance already closed
5.1.5.10.2.7.1.4 GFX_DRV_S1D13517_GetReg Function
C
uint8_t GFX_DRV_S1D13517_GetReg(
uint8_t index
);
Description
none
Parameters
Parameters Description
index register number
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-327
*data array to store data
Returns
0 - when call was passed
5.1.5.10.2.7.1.5 GFX_DRV_S1D13517_Initialize Function
C
uint16_t GFX_DRV_S1D13517_Initialize(
uint8_t instance
);
Description
none
Parameters
Parameters Description
instance driver instance
Returns
NULL - call not successful (PMP driver busy) !NULL - address of the display driver queue command
5.1.5.10.2.7.1.6 GFX_DRV_S1D13517_Layer Function
C
uint16_t* GFX_DRV_S1D13517_Layer(
uint8_t type,
GFX_LAYER_PARAMS* layer
);
Description
none
Parameters
Parameters Description
type layer type
layer parameters for Layer function call
Returns
NULL - call not successful (PMP driver busy) !NULL - address of the display driver queue command
5.1.5.10.2.7.1.7 GFX_DRV_S1D13517_Open Function
C
uint16_t GFX_DRV_S1D13517_Open(
uint8_t instance
);
Description
none
Returns
1 - driver not initialied 2 - instance doesn't exist 3 - instance already open instance to driver when successful
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-328
5.1.5.10.2.7.1.8 GFX_DRV_S1D13517_PixelArrayPut Function
C
uint16_t* GFX_DRV_S1D13517_PixelArrayPut(
uint16_t * color,
short x,
short y,
uint16_t count,
uint16_t lineCount
);
Description
none
Parameters
Parameters Description
*color start of the array
x x coordinate of the start point.
y y coordinate of the end point.
count number of pixels
Returns
NULL - call not successful (PMP driver busy) !NULL - address to the number of pixels yet to be serviced
5.1.5.10.2.7.1.9 GFX_DRV_S1D13517_PixelPut Function
C
uint16_t GFX_DRV_S1D13517_PixelPut(
short x,
short y
);
Description
none
Parameters
Parameters Description
instance driver instance
color color to output
x,y pixel coordinates
Returns
NULL - call not successful (PMP driver busy) !NULL - address of the display driver queue command
5.1.5.10.2.7.1.10 GFX_DRV_S1D13517_PixelsPut Function
C
uint16_t GFX_DRV_S1D13517_PixelsPut(
short x,
short y,
uint16_t count,
uint16_t lineCount
);
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-329
Description
none
Parameters
Parameters Description
instance driver instance
color color to output
x,y pixel coordinates
Returns
NULL - call not successful (PMP driver busy) !NULL - address of the display driver queue command
5.1.5.10.2.7.1.11 GFX_DRV_S1D13517_SetColor Function
C
void GFX_DRV_S1D13517_SetColor(
GFX_COLOR color
);
Returns
none
5.1.5.10.2.7.1.12 GFX_DRV_S1D13517_SetInstance Function
C
void GFX_DRV_S1D13517_SetInstance(
uint8_t instance
);
Returns
none
5.1.5.10.2.7.1.13 GFX_DRV_S1D13517_SetPage Function
C
uint16_t GFX_DRV_S1D13517_SetPage(
uint8_t pageType,
uint8_t page
);
Description
none
Parameters
Parameters Description
instance driver instance
Returns
NULL - call not successful (PMP driver busy) !NULL - address of the display driver queue command
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-330
5.1.5.10.2.7.1.14 GFX_DRV_S1D13517_SetReg Function
C
uint16_t GFX_DRV_S1D13517_SetReg(
uint8_t index,
uint8_t value
);
Description
none
Parameters
Parameters Description
index register number
value value to write to register
Returns
1 - call was not passed 0 - call was passed
5.1.5.10.2.7.1.15 GFX_DRV_S1D13517_Tasks Function
C
void GFX_DRV_S1D13517_Tasks();
5.1.5.10.2.7.2 S1D13517 Data Types and Constants
Structures
Name Description
GFX_DRV_S1D13517_COMMAND Structure for the commands in the driver queue.
LAYER_REGISTERS This structure is used to describe layer registers.
Description
5.1.5.10.2.7.2.1 GFX_DRV_S1D13517_COMMAND Structure
C
typedef struct {
uint8_t instance;
short x;
short y;
uint16_t * array;
uint16_t data;
uint16_t count;
uint16_t lineCount;
uint8_t task;
} GFX_DRV_S1D13517_COMMAND;
Description
Structure: GFX_DRV_S1D13517_COMMAND
None
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-331
5.1.5.10.2.7.2.2 LAYER_REGISTERS Structure
C
typedef struct {
uint8_t XStart;
uint8_t XEnd;
uint8_t YStart0;
uint8_t YStart1;
uint8_t YEnd0;
uint8_t YEnd1;
uint8_t StartAddress0;
uint8_t StartAddress1;
uint8_t StartAddress2;
} LAYER_REGISTERS;
Description
This structure is used to describe layer registers.
5.1.5.10.2.8 Files
Files
Name Description
5.1.5.10.2.8.1 drv_gfx_s1d13517_config_template.h
• Module for Microchip Graphics Library
• This file contains compile time options for the Graphics Library.
*******************************************************************
• FileName: GraphicsConfig.h
• Dependencies: none
• Processor: PIC24F, PIC24H, dsPIC, PIC32
• Compiler: C30 V3.00/C32
• Company: Microchip Technology, Inc.
*
• Software License Agreement
*
• Copyright © 2008 Microchip Technology Inc. All rights reserved.
• Microchip licenses to you the right to use, modify, copy and distribute
• Software only when embedded on a Microchip microcontroller or digital
• signal controller, which is integrated into your product or third party
• product (pursuant to the sublicense terms in the accompanying license
• agreement).
*
• You should refer to the license agreement accompanying this Software
• for additional information regarding your rights and obligations.
*
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-332
• SOFTWARE AND DOCUMENTATION ARE PROVIDED ?AS IS? WITHOUT WARRANTY OF ANY
• KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION, ANY WARRANTY
• OF MERCHANTABILITY, TITLE, NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR
• PURPOSE. IN NO EVENT SHALL MICROCHIP OR ITS LICENSORS BE LIABLE OR
• OBLIGATED UNDER CONTRACT, NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION,
• BREACH OF WARRANTY, OR OTHER LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT
• DAMAGES OR EXPENSES INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL,
• INDIRECT, PUNITIVE OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA,
• COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY
• CLAIMS BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF),
• OR OTHER SIMILAR COSTS.
*
• Author Date Comment
*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
• Anton Alkhimenok 10/28/2007 Initial Version
• Pradeep Budagutta 10/28/2007 Display related defines
• moved to DisplayConfig.h
5.1.5.10.3 SSD1926 Graphics Controller Driver Library
5.1.5.10.3.1 Introduction
SSD1926 Graphics Controller Driver Library
for
Microchip Microcontrollers
This library provides a low-level abstraction of the SSD1926 Graphics Controller Driver Library that is available on the Microchip
family of microcontrollers with a convenient C language interface. It can be used to simplify low-level access to the module
without the necessity of interacting directly with the module's registers, there by hiding differences from one microcontroller
variant to another.
Description
Note: This information was not available at time of release and will be added in a future release of MPLAB Harmony.
5.1.5.10.3.2 Release Notes
MPLAB Harmony Version: v0.70b SSD1926 Graphics Controller Driver Library Version : 4.00b Release Date: 18Nov2013
New This Release:
This is the first release of the library. The interface can change in the beta and\or 1.0 release.
Known Issues:
Nothing to report in this release.
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-333
5.1.5.10.3.3 SW License Agreement
(c) 2013 Microchip Technology Inc.
Microchip licenses this software to you solely for use with Microchip products. The software is owned by Microchip and its
licensors, and is protected under applicable copyright laws. All rights reserved.
SOFTWARE IS PROVIDED "AS IS" MICROCHIP EXPRESSLY DISCLAIMS ANY WARRANTY OF ANY KIND, WHETHER
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL MICROCHIP BE LIABLE FOR
ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, HARM TO
YOUR EQUIPMENT, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS
BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR
CONTRIBUTION, OR OTHER SIMILAR COSTS.
To the fullest extent allowed by law, Microchip and its licensors liability shall not exceed the amount of fees, if any, that you have
paid directly to Microchip to use this software.
MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE TERMS.
5.1.5.10.3.4 Using the Library
This topic describes the basic architecture of the SSD1926 Graphics Controller Driver Library and provides information and
examples on how to use it.
Interface Header File: drv_gfx_ssd1926.h
The interface to the SSD1926 Graphics Controller Driver Library is defined in the "drv_gfx_ssd1926.h" header file. This file is
included by the "gfx_primitive.h" file. Any C language source (.c) file that uses the SSD1926 Graphics Controller Driver Library
should include "gfx_primitive.h".
Library File:
The SSD1926 Graphics Controller Driver Library archive (.a) file installed with MPLAB Harmony.
Please refer to the MPLAB Harmony Overview for how the SSD1926 Graphics Controller Driver Library interacts with the
framework.
5.1.5.10.3.4.1 Abstraction Model
This library provides the low-level abstraction of the SSD1926 Graphics Controller Driver module of the Microchip family of
graphic display controllers with a convenient C language interface. This topic describes how that abstraction is modeled in the
software and introduces the library interface.
Description
SSD1926 Graphics Controller Driver Abstraction Block Diagram
Note: This information was not available at time of release and will be added in a future release of MPLAB Harmony.
5.1.5.10.3.4.2 Library Overview
Refer to the section Driver Overview for how the driver operates in a system.
The library interface routines are divided into various sub-sections, each of sub-section addresses one of the blocks or the
overall operation of the SSD1926 Graphics Controller Driver module.
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-334
Library Interface Section Description
Functions This section lists the API functions available in the library.
5.1.5.10.3.5 Configuring the Library
The configuration of the SSD1926 Graphics Controller Driver is based on the file system_config.h.
This header file contains the configuration selection for the SSD1926 Graphics Controller Driver. Based on the selections made,
the SSD1926 Graphics Controller Driver will support or not support selected features. These configuration settings will apply to
all instances of the SSD1926 Graphics Controller Driver.
This header can be placed anywhere; however, the path of this header needs to be present in the include search path for a
successful build. Refer to the Applications Overview section for more details.
5.1.5.10.3.6 Building the Library
This section list the files that are available in the \src of the SSD1926 Graphics Controller Driver Library. It lists which files need
to be included in the build based on either a hardware feature present on the board or configuration option selected by the
system.
• drv_gfx_ssd1926.c
5.1.5.10.3.7 Library Interface
This section describes the Application Programming Interface (API) functions of the SSD1926 Graphics Controller Driver Library.
Refer to each section for a detailed description.
5.1.5.10.3.7.1 Functions
Functions
Name Description
GFX_DRV_SSD1926_BarFill Hardware accelerated barfill function
GFX_DRV_SSD1926_BrightnessSet Sets the brightness of the display backlight.
GFX_DRV_SSD1926_Busy Returns non-zero if LCD controller is busy (previous drawing operation is not
completed).
GFX_DRV_SSD1926_Close closes an instance of the graphics controller
GFX_DRV_SSD1926_GetReg returns graphics controller register value (byte access)
GFX_DRV_SSD1926_Initialize resets LCD, initializes PMP
GFX_DRV_SSD1926_Open opens an instance of the graphics controller
GFX_DRV_SSD1926_PixelArrayGet gets an array of pixels of length count starting at *color
GFX_DRV_SSD1926_PixelArrayPut outputs an array of pixels of length count starting at *color
GFX_DRV_SSD1926_PixelPut outputs one pixel into the frame buffer at the x,y coordinate given
GFX_DRV_SSD1926_PixelsPut outputs one pixel into the frame buffer at the x,y coordinate given
GFX_DRV_SSD1926_SetColor Sets the color for the driver instance
GFX_DRV_SSD1926_SetInstance Sets the instance for the driver
GFX_DRV_SSD1926_SetReg updates graphics controller register value (byte access)
GFX_DRV_SSD1926_Tasks Task machine that renders the driver calls for the graphics library it must be
called peridically to output the contents of its circular buffer
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-335
Description
5.1.5.10.3.7.1.1 GFX_DRV_SSD1926_BarFill Function
C
uint16_t GFX_DRV_SSD1926_BarFill(
short left,
short top,
short right,
short bottom
);
Description
see primitive BarFill
Returns
1 - call not successful (PMP driver busy) 0 - call successful
5.1.5.10.3.7.1.2 GFX_DRV_SSD1926_BrightnessSet Function
C
void GFX_DRV_SSD1926_BrightnessSet(
uint8_t instance,
uint16_t level
);
Description
none
Parameters
Parameters Description
5.1.5.10.3.7.1.3 GFX_DRV_SSD1926_Busy Function
C
uint16_t GFX_DRV_SSD1926_Busy(
uint8_t instance
);
Description
none
Parameters
Parameters Description
instance driver instance
Returns
1 - busy 0 - not busy
5.1.5.10.3.7.1.4 GFX_DRV_SSD1926_Close Function
C
uint16_t GFX_DRV_SSD1926_Close(
uint8_t instance
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-336
);
Description
none
Returns
0 - instance closed 2 - instance doesn't exist 3 - instance already closed
5.1.5.10.3.7.1.5 GFX_DRV_SSD1926_GetReg Function
C
uint8_t GFX_DRV_SSD1926_GetReg(
uint16_t index,
uint8_t * data
);
Description
none
Parameters
Parameters Description
index register number
*data array to store data
Returns
0 - when call was passed
5.1.5.10.3.7.1.6 GFX_DRV_SSD1926_Initialize Function
C
uint16_t GFX_DRV_SSD1926_Initialize(
uint8_t instance
);
Description
none
Parameters
Parameters Description
instance driver instance
Returns
1 - call not successful (PMP driver busy) 0 - call successful
5.1.5.10.3.7.1.7 GFX_DRV_SSD1926_Open Function
C
uint16_t GFX_DRV_SSD1926_Open(
uint8_t instance
);
Description
none
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-337
Returns
1 - driver not initialied 2 - instance doesn't exist 3 - instance already open instance to driver when successful
5.1.5.10.3.7.1.8 GFX_DRV_SSD1926_PixelArrayGet Function
C
uint16_t* GFX_DRV_SSD1926_PixelArrayGet(
uint16_t * color,
short x,
short y,
uint16_t count
);
Description
none
Parameters
Parameters Description
instance driver instance
*color start of the array
x x coordinate of the start point.
y y coordinate of the end point.
count number of pixels
Returns
NULL - call not successful !NULL - address of the display driver queue command
5.1.5.10.3.7.1.9 GFX_DRV_SSD1926_PixelArrayPut Function
C
uint16_t* GFX_DRV_SSD1926_PixelArrayPut(
uint16_t * color,
short x,
short y,
uint16_t count,
uint16_t lineCount
);
Description
none
Parameters
Parameters Description
instance driver instance
*color start of the array
x x coordinate of the start point.
y y coordinate of the end point.
count number of pixels
Returns
NULL - call not successful !NULL - handle to the number of pixels remaining
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-338
5.1.5.10.3.7.1.10 GFX_DRV_SSD1926_PixelPut Function
C
uint16_t GFX_DRV_SSD1926_PixelPut(
short x,
short y
);
Description
none
Parameters
Parameters Description
instance driver instance
color color to output
x,y pixel coordinates
Returns
NULL - call not successful !NULL - address of the display driver queue command
5.1.5.10.3.7.1.11 GFX_DRV_SSD1926_PixelsPut Function
C
uint16_t GFX_DRV_SSD1926_PixelsPut(
short x,
short y,
uint16_t count,
uint16_t lineCount
);
Description
none
Parameters
Parameters Description
x,y pixel coordinates
5.1.5.10.3.7.1.12 GFX_DRV_SSD1926_SetColor Function
C
void GFX_DRV_SSD1926_SetColor(
GFX_COLOR color
);
Returns
none
5.1.5.10.3.7.1.13 GFX_DRV_SSD1926_SetInstance Function
C
void GFX_DRV_SSD1926_SetInstance(
uint8_t instance
);
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-339
Returns
none
5.1.5.10.3.7.1.14 GFX_DRV_SSD1926_SetReg Function
C
uint16_t GFX_DRV_SSD1926_SetReg(
uint16_t index,
uint8_t value
);
Description
none
Parameters
Parameters Description
index register number
value value to write to register
Returns
1 - call was not passed 0 - call was passed
5.1.5.10.3.7.1.15 GFX_DRV_SSD1926_Tasks Function
C
void GFX_DRV_SSD1926_Tasks();
5.1.5.10.3.7.2 Data Types and Constants
Structures
Name Description
GFX_DRV_SSD1926_COMMAND Structure for the commands in the driver queue.
GFX_DRV_SSD1926_TASK Structure for the task machine
Description
5.1.5.10.3.7.2.1 GFX_DRV_SSD1926_COMMAND Structure
C
typedef struct {
uint8_t instance;
uint32_t address;
uint16_t * array;
uint16_t data;
uint16_t count;
uint16_t lineCount;
SSD1926_TASK task;
} GFX_DRV_SSD1926_COMMAND;
Description
Structure: GFX_DRV_SSD1926_COMMAND
None
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-340
Members
Members Description
uint32_t address; wether the task is complete or not
5.1.5.10.3.7.2.2 GFX_DRV_SSD1926_TASK Structure
C
typedef struct {
uint8_t instance;
uint32_t address;
uint16_t color;
uint8_t state;
} GFX_DRV_SSD1926_TASK;
Description
Structure: GFX_DRV_SSD1926_TASK
None
5.1.5.10.3.8 Files
Files
Name Description
5.1.5.10.3.8.1 drv_gfx_ssd1926_config_template.h
• Module for Microchip Graphics Library
• This file contains compile time options for the Graphics Library.
*******************************************************************
• FileName: GraphicsConfig.h
• Dependencies: none
• Processor: PIC24F, PIC24H, dsPIC, PIC32
• Compiler: C30 V3.00/C32
• Company: Microchip Technology, Inc.
*
• Software License Agreement
*
• Copyright © 2008 Microchip Technology Inc. All rights reserved.
• Microchip licenses to you the right to use, modify, copy and distribute
• Software only when embedded on a Microchip microcontroller or digital
• signal controller, which is integrated into your product or third party
• product (pursuant to the sublicense terms in the accompanying license
• agreement).
*
• You should refer to the license agreement accompanying this Software
• for additional information regarding your rights and obligations.
5.1 Driver Library Help MPLAB Harmony Help Graphics (GFX) Driver Library
5-341
*
• SOFTWARE AND DOCUMENTATION ARE PROVIDED ?AS IS? WITHOUT WARRANTY OF ANY
• KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION, ANY WARRANTY
• OF MERCHANTABILITY, TITLE, NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR
• PURPOSE. IN NO EVENT SHALL MICROCHIP OR ITS LICENSORS BE LIABLE OR
• OBLIGATED UNDER CONTRACT, NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION,
• BREACH OF WARRANTY, OR OTHER LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT
• DAMAGES OR EXPENSES INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL,
• INDIRECT, PUNITIVE OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA,
• COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY
• CLAIMS BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF),
• OR OTHER SIMILAR COSTS.
*
• Author Date Comment
*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
• Anton Alkhimenok 10/28/2007 Initial Version
• Pradeep Budagutta 10/28/2007 Display related defines
• moved to DisplayConfig.h
5.1.6 Non-Volatile Memory (NVM) Driver Library
5.1.6.1 Introduction
Non-Volatile Memory (NVM) Driver Library
for
Microchip Microcontrollers
This library provides a low-level abstraction of the NVM Driver Library that is available on the Microchip family of microcontrollers
with a convenient C language interface. It can be used to simplify low-level access to the module without the necessity of
interacting directly with the module's registers, thereby hiding differences from one microcontroller variant to another.
Description
The functions provides in the NVM Driver Library also perform certain mandatory assembly language instructions specific for
access and modification of memory, which are thus abstracted.
Memory Devices for PIC Microcontrollers
There are two primary forms of on-chip memory available for PIC microcontrollers: programmable Flash memory and data
EEPROM memory. The access mechanism for both of these types are varied and different techniques are specified for the
same.:
5.1 Driver Library Help MPLAB Harmony Help Non-Volatile Memory (NVM) Driver Library
5-342
Flash Program Memory
The Flash program memory is readable, writeable, and erasable during normal operation over the entire operating voltage range.
A read from program memory is executed at one byte/word at a time depending on the width of the data bus.
A write to the program memory is executed in either blocks of specific sizes or a single word depending on the type of processor
used.
An erase is performed in blocks. A bulk erase may be performed from user code depending on the type of processor supporting
the operation.
Writing or erasing program memory will cease instruction fetches until the operation is complete, restricting memory access, and
therefore preventing code execution. This is controlled by an internal programming timer.
There are three processor dependant methods for program memory modification.
• Run-Time Self Programming (RTSP)
• In-Circuit Serial Programming (ICSP)
• EJTAG programming
This section describes the RTSP techniques.
5.1.6.2 Release Notes
MPLAB Harmony Version: v0.70b NVM Driver Library Version : 0.01 Release Date: 18Nov2013
New This Release:
• Internal handling of erase feature for sector write function
Known Issues:
• Not tested by mapping the image to different parts of the memory
5.1.6.3 SW License Agreement
(c) 2013 Microchip Technology Inc.
Microchip licenses this software to you solely for use with Microchip products. The software is owned by Microchip and its
licensors, and is protected under applicable copyright laws. All rights reserved.
SOFTWARE IS PROVIDED AS IS MICROCHIP EXPRESSLY DISCLAIMS ANY WARRANTY OF ANY KIND, WHETHER
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL MICROCHIP BE LIABLE FOR
ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, HARM TO
YOUR EQUIPMENT, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS
BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR
CONTRIBUTION, OR OTHER SIMILAR COSTS.
To the fullest extent allowed by law, Microchip and its licensors liability shall not exceed the amount of fees, if any, that you have
paid directly to Microchip to use this software.
MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE TERMS.
5.1 Driver Library Help MPLAB Harmony Help Non-Volatile Memory (NVM) Driver Library
5-343
5.1.6.4 Using the Library
This topic describes the basic architecture of the NVM Driver Library and provides information and examples on how to use it.
Interface Header File: drv_nvm.h
The interface to the NVM Driver Library is defined in the "drv_nvm.h" header file. Any C language source (.c) file that uses the
NVM Driver library should include "drv.h".
Library File: The NVM Driver Library archive (.a) file installed with MPLAB Harmony.
Please refer to the MPLAB Harmony Overview for how the driver interacts with the framework.
5.1.6.4.1 Abstraction Model
This library provides a low-level abstraction of the NVM module on the Microchip family of microcontrollers with a convenient C
language interface. This topic describes how that abstraction is modeled in software and introduces the library's interface.
Description
NVM Software Abstraction Block Diagram
Note 1: This feature is not available on all devices. Refer to the specific device data sheet to determine availability.
Abstraction Model
The NVM peripheral library provides interface routines to interact with the blocks shown in the diagram.
The Flash Status and Control Logic ensures that the Flash memory is configured appropriately for modification. It also
provides the status of the different operations in progress as well as errors, if any. It also decides if the operation is for Flash
program memory or the special device configuration registers.
The Flash Read/Write block ensures that the user data is written to/read from the program memory holding latches. It provides
a layer of abstraction over the sequence of processor-specific instructions that are required to access this data. Depending on
the processor type either block or Word programming options area available.
5.1.6.4.2 Library Overview
Refer to the section Driver Overview for how the driver operates in a system.
The library interface routines are divided into various subsections, each of the sub-sections addresses one of the blocks or the
5.1 Driver Library Help MPLAB Harmony Help Non-Volatile Memory (NVM) Driver Library
5-344
overall operation of the NVM module.
Library Interface Section Description
System Functions Provides system module interfaces, device initialization, deinitialization,
reinitialization, tasks and status functions.
Client Core Functions Provides open, close, status and other setup functions.
Client Block Transfer Functions Provides buffered data operation functions available in the core
configuration.
Miscellaneous Functions Provides driver miscellaneous functions related to versions and others.
5.1.6.4.3 How the Library Works
The library provides interfaces to support:
• System Functionality
• Client Functionality
Note: Not all modes are available on all devices. Please refer to the specific device data sheet to determine the modes
supported for your device.
5.1.6.4.3.1 System Initialization
This section provides information for system initialization and reinitialization.
Description
System Initialization and Reinitialization
The system performs the initialization and the reinitialization of the device driver with settings that affect only the instance of the
device that is being initialized or reinitialized. During system initialization each instance of the NVM module would be initialized
with the following configuration settings (either passed dynamically at run time using DRV_NVM_INIT or by using initialization
overrides) that are supported by the specific NVM device hardware:
• Device requested power state: One of the system module power states. For specific details please refer to the Data Types
and Constants section.
• The actual peripheral ID enumerated as the PLIB level module ID (e.g., NVM_ID_0)
• Defining the respective interrupt sources for transmit (TX), receive (RX), and error interrupts
The DRV_NVM_Initialize function returns an object handle of the type SYS_MODULE_OBJ. After this, the object handle
returned by the initialize interface would be used by the other system interfaces, such as DRV_NVM_Reinitialize,
DRV_NVM_Deinitialize, DRV_NVM_Status, and DRV_NVM_Tasks.
Note: The system initialization and the reinitialization settings, only effect the instance of the peripheral that is being initialized or
reinitialized.
The SYS_MODULE_INDEX is passed to the DRV_NVM_Initialize function tol determine which type of memory is selected using:
• DRV_NVM_INDEX_0 - FLASH
Example:
// This code snippet shows an example
// of initializing the NVM Driver.
DRV_NVM_INIT NVMInitData;
SYS_MODULE_OBJ objectHandle;
5.1 Driver Library Help MPLAB Harmony Help Non-Volatile Memory (NVM) Driver Library
5-345
NVMInitData.moduleInit.value = SYS_MODULE_POWER_RUN_FULL;
NVMInitData.moduleId = NVM_ID_0;
NVMInitData.flashInterruptSource = INT_SOURCE_FLASH_CONTROL;
//usage of DRV_NVM_INDEX_0 indicates usage of flash realted APIs
objectHandle = DRV_NVM_Initialize(DRV_NVM_INDEX_0, (SYS_MODULE_INIT*)NVMInitData);
if (SYS_MODULE_OBJ_INVALID == objectHandle)
{
// Handle error
}
Tasks Routine
The system will call DRV_NVM_Tasks, from system task service (in a polled environment) or DRV_NVM_Taskswill be called
from the Interrupt Service Routine (ISR) of the NVM.
5.1.6.4.3.2 Client Access Operation
This section provides information for general client operation.
Description
General Client Operation
For the application to start using an instance of the module, it must call the DRV_NVM_Open function. This provides the
configuration required to open the NVM instance for operation. If the driver is deinitialized using the function
DRV_NVM_Deinitialize, the application must call the DRV_NVM_Open function again to set up the instance of the NVM. The
function DRV_NVM_Open need not be called again if the system is reinitialized using the DRV_NVM_Reinitialize function.
For the various options available for I/O INTENT please refer to the Data Types and Constants section.
Example:
DRV_HANDLE handle;
handle = DRV_NVM_Open(DRV_NVM_INDEX_0, DRV_IO_INTENT_EXCLUSIVE);
if (DRV_HANDLE_INVALID == handle)
{
// Unable to open the driver
}
5.1.6.4.3.3 Client Basic Operation
This section provides information for client basic functionality.
Description
An extremely basic interface for the driver operation is provided through client basic functionality.
The NVM driver provides the word and row programming operations in the basic mode of operation. The type of memory on
which these operations will be performed is provided as an index while initialization.
The SYS_MODULE_INDEX is passed to the DRV_NVM_Initialize function to determine which type of memory is selected using:
• DRV_NVM_INDEX_0 - FLASH
Note: Not all devices support the word/row programming operations. It is the responsibility of the user to determine which
devices support which mode of operation. The memory access method described in this document only refers to Real-Time
Self-Programming (RTSP).
Word Programming Operations
Applications using the NVM word write functionality need to perform the following:
5.1 Driver Library Help MPLAB Harmony Help Non-Volatile Memory (NVM) Driver Library
5-346
1. The system should have completed necessary initialization and DRV_NVM_Tasks should either be running in a polled
environment, or in an interrupt environment.
2. Open the driver using DRV_NVM_Open with the necessary intent.
3. Provide the desired mode of operation using the operation mode.
4. Write a word using DRV_NVM_WriteWord.
5. The client will be able to close itself using the DRV_NVM_Close when required.
DRV_HANDLE handle; // Returned from DRV_NVM_Open
char myBuffer[MY_BUFFER_SIZE];
char* nvmAddr = BASE_ADDRESS_OF_NVM_TO_WRITE_TO
DRV_NVM_OPERATION_STATUS myStatus = 0;
myStatus = DRV_NVM_WriteWord( handle, myBuffer, nvmAddr);
if(myStatus == DRV_NVM_STATUS_OPERATION_COMPLETE)
{
//Write successful
}
Applications using the NVM word erase functionality need to perform the following:
1. The system should have completed necessary initialization and DRV_NVM_Tasks should either be running in a polled
environment, or in an interrupt environment.
2. Open the driver using DRV_NVM_Open with the necessary intent.
3. Provide the desired mode of operation using the operation mode.
4. Erase a word using DRV_NVM_EraseWord.
5. The client will be able to close itself using the DRV_NVM_Close when required.
DRV_HANDLE handle; // Returned from DRV_NVM_Open
char* nvmAddr = BASE_ADDRESS_OF_NVM_TO_ERASE_FROM
DRV_NVM_OPERATION_STATUS myStatus = 0;
myStatus = DRV_NVM_EraseWord( handle, myBuffer, nvmAddr);
if(myStatus == DRV_NVM_STATUS_OPERATION_COMPLETE)
{
//Erase successful
}
Row Programming Operations
Applications using the NVM row erase functionality needs to perform the following:
1. The system should have completed necessary initialization and DRV_NVM_Tasks should either be running in a polled
environment, or in an interrupt environment.
2. Open the driver using DRV_NVM_Open with the necessary intent.
3. Provide the desired mode of operation using the operation mode.
4. Erase a word using DRV_NVM_EraseROW.
5. The client will be able to close itself using the DRV_NVM_Close when required.
DRV_HANDLE handle; // Returned from DRV_NVM_Open
char* nvmAddr = BASE_ADDRESS_OF_NVM_TO_ERASE_FROM
DRV_NVM_OPERATION_STATUS myStatus = 0;
myStatus = DRV_NVM_EraseROW( handle, nvmAddr);
if(myStatus == DRV_NVM_STATUS_OPERATION_COMPLETE)
{
//Erase successful
5.1 Driver Library Help MPLAB Harmony Help Non-Volatile Memory (NVM) Driver Library
5-347
}
5.1.6.4.3.4 Client Block Data Operation
Client Block Data functionality provides advanced interface for the driver operation.
These block data functions depend heavily on the block sizes and boundaries of individual devices and the APIs are responsible
for keeping that information transparent from the application. These operations return the number of bytes of a successfully
executed operation.
Block Operations
Applications using the NVM block write functionality need to perform the following:
1. The system should have completed necessary initialization and DRV_NVM_Tasks should either be running in a polled
environment, or in an interrupt environment.
2. Open the driver using DRV_NVM_Open with the necessary intent.
3. Provide the desired mode of operation using the operation mode.
4. Provide the source and destination addresses and begin write using DRV_NVM_Write.
5. The client will be able to close itself using the DRV_NVM_Close when required.
DRV_HANDLE handle; // Returned from DRV_NVM_Open
char myBuffer[2 * DRV_NVM_ROW_SIZE];
// Destination address should be row aligned.
char *destAddress = (char *)NVM_BASE_ADDRESS_TO_WRITE;
unsigned int count = 2 * MY_BUFFER_SIZE;
DRV_NVM_BUFFER_HANDLE bufferHandle;
bufferHandle = DRV_NVM_Write(myNVMHandle, destAddress, &myBuffer[total], count);
if(DRV_NVM_BUFFER_HANDLE_INVALID == bufferHandle)
{
// Do error handling here
}
// Wait till the buffer completes. This should not
// be a while loop if a part of cooperative multi-tasking
// routine. In that case, it should be invoked in task
// state machine.
while(DRV_NVM_BufferStatus(bufferHandle) != DRV_NVM_BUFFER_COMPLETED);
Applications using the NVM block Read functionality need to perform the following:
1. The system should have completed necessary initialization and DRV_NVM_Tasks should either be running in a polled
environment, or in an interrupt environment.
2. Open the driver using DRV_NVM_Open with the necessary intent.
3. Provide the desired mode of operation using the operation mode.
4. Provide the source and destination addresses and begin write using DRV_NVM_ReadBlock.
5. The client will be able to close itself using the DRV_NVM_Close when required.
DRV_HANDLE handle; // Returned from DRV_NVM_Open
char myBuffer[MY_BUFFER_SIZE];
char *srcAddress = NVM_BASE_ADDRESS_TO_READ_FROM;
unsigned int count = MY_BUFFER_SIZE;
DRV_NVM_BUFFER_HANDLE bufferHandle;
bufferHandle = DRV_NVM_Read(myNVMHandle, &myBuffer[total], srcAddress, count);
if(DRV_NVM_BUFFER_HANDLE_INVALID == bufferHandle)
{
// Do error handling here
5.1 Driver Library Help MPLAB Harmony Help Non-Volatile Memory (NVM) Driver Library
5-348
}
// Wait till the buffer completes. This should not
// be a while loop if a part of cooperative multi-tasking
// routine. In that case, it should be invoked in task
// state machine.
while(DRV_NVM_BufferStatus(bufferHandle) != DRV_NVM_BUFFER_COMPLETED);
Internally, a buffer is maintained whose status can be obtained by calling API DRV_NVM_BufferStatus.
5.1.6.5 Configuring the Library
Macros
Name Description
DRV_NVM_BUFFER_OBJECT_NUMBER Selects the maximum number of buffer objects
DRV_NVM_CLIENTS_NUMBER Selects the maximum number of clients
DRV_NVM_ERASE_SIZE Specifies the NVM Driver Erase Page Size in bytes.
DRV_NVM_INSTANCES_NUMBER Selects the maximum number of Driver instances that can be
supported by the dynamic driver.
DRV_NVM_INTERRUPT_MODE Macro specifies operation of the driver to be in the interrupt mode or
polled mode
DRV_NVM_ROW_SIZE Specifies the NVM Driver Program Row Size in bytes.
DRV_NVM_UNLOCK_KEY1 Specifies the NVM Driver Program Unlock Key 1
DRV_NVM_UNLOCK_KEY2 Specifies the NVM Driver Program Unlock Key 2
Description
The configuration of the NVM Driver is based on the file sys_config.h
This header file contains the configuration selection for the NVM Driver. Based on the selections made, the NVM Driver will
support or not support selected features. These configuration settings will apply to all instances of the NVM Driver.
This header can be placed anywhere; however, the path of this header needs to be present in the include search path for a
successful build. Refer to the Applications Overview section for more details.
5.1.6.5.1 DRV_NVM_BUFFER_OBJECT_NUMBER Macro
C
#define DRV_NVM_BUFFER_OBJECT_NUMBER 5
Description
NVM Driver maximum number of buffer objects
This definition selects the maximum number of buffer objects. This indirectly also specifies the queue depth. The NVM Driver can
queue up DRV_NVM_BUFFER_OBJECT_NUMBER of read/write/erase requests before return a
DRV_NVM_BUFFER_HANDLE_INVALID due to the queue being full. Increasing this number increases the RAM requirement of
the driver.
Remarks
None.
5.1 Driver Library Help MPLAB Harmony Help Non-Volatile Memory (NVM) Driver Library
5-349
5.1.6.5.2 DRV_NVM_CLIENTS_NUMBER Macro
C
#define DRV_NVM_CLIENTS_NUMBER 1
Description
NVM maximum number of clients
This definition selects the maximum number of clients that the NVM driver can supported at run time.
Remarks
None.
5.1.6.5.3 DRV_NVM_ERASE_SIZE Macro
C
#define DRV_NVM_ERASE_SIZE 4096
Description
NVM Driver Erase Page Size.
This definition specifies the NVM Driver Erase Page Size in bytes. This parameter is device specific and should be obtained from
the device specific data sheet. The Erase Page Size is the minimum block size that can be erased in one erase operation.
Remarks
None.
5.1.6.5.4 DRV_NVM_INSTANCES_NUMBER Macro
C
#define DRV_NVM_INSTANCES_NUMBER 1
Description
NVM Driver instance configuration
This definition selects the maximum number of Driver instances that can be supported by the dynamic driver. In case of this
driver, multiple instances of the driver could use the same hardware instance.
Remarks
None
5.1.6.5.5 DRV_NVM_INTERRUPT_MODE Macro
C
#define DRV_NVM_INTERRUPT_MODE false
Description
NVM interrupt and polled mode operation control
This macro specifies operation of the driver to be in the interrupt mode or polled mode
5.1 Driver Library Help MPLAB Harmony Help Non-Volatile Memory (NVM) Driver Library
5-350
• true - Select if interrupt mode of NVM operation is desired
• false - Select if polling mode of NVM operation is desired
Not defining this option to true or false will result in build error.
Remarks
None.
5.1.6.5.6 DRV_NVM_ROW_SIZE Macro
C
#define DRV_NVM_ROW_SIZE 512
Description
NVM Driver Program Row Size.
This definition specifies the NVM Driver Program Row Size in bytes. This parameter is device specific and should be obtained
from the device specific data sheet. The Program Row Size is the minimum block size that can be programmed in one program
operation.
Remarks
None.
5.1.6.5.7 DRV_NVM_UNLOCK_KEY1 Macro
C
#define DRV_NVM_UNLOCK_KEY1 0xAA996655
Description
NVM Driver Program Unlock Key 1
This definition specifies the NVM Driver Program Unlock Key 1 parameter is device specific and should be obtained from the
device specific data sheet.
Remarks
None.
5.1.6.5.8 DRV_NVM_UNLOCK_KEY2 Macro
C
#define DRV_NVM_UNLOCK_KEY2 0x556699AA
Description
NVM Driver Program Unlock Key 2
This definition specifies the NVM Driver Program Unlock Key 2 parameter is device specific and should be obtained from the
device specific data sheet.
Remarks
None.
5.1 Driver Library Help MPLAB Harmony Help Non-Volatile Memory (NVM) Driver Library
5-351
5.1.6.6 Building the Library
This section list the files that are available in the \src of the NVM driver. It lists which files need to be included in the build based
on either a hardware feature present on the board or configuration option selected by the system.
5.1.6.7 Library Interface
Data Types and Constants
Name Description
DRV_NVM_BUFFER_HANDLE_INVALID This value defines the NVM Driver Buffer Invalid handle.
DRV_NVM_INDEX_0 NVM driver index definitions
DRV_NVM_INDEX_COUNT Number of valid NVM driver indices
DRV_NVM_BUFFER_HANDLE This type defines the NVM Driver Buffer handle.
DRV_NVM_BUFFER_STATUS Specifies the status of the buffer for the read, write and erase
opeartions.
DRV_NVM_CLIENT_STATUS Defines the client status
DRV_NVM_INIT Defines the data required to initialize or reinitialize the NVM driver
DRV_NVM_INDEX_1 This is macro DRV_NVM_INDEX_1.
Client Block Data Functions
Name Description
DRV_NVM_Erase Erase the specified number of pages in flash memory.
DRV_NVM_Read Reads a block of data from the specified address in memory.
DRV_NVM_Tasks Maintains the driver's erase and write state machine and implements its ISR.
DRV_NVM_Write Write a block of data to a specified address in memory.
Client Core Functions
Name Description
DRV_NVM_ClientStatus Gets current client-specific status the NVM driver
DRV_NVM_Close Closes an opened-instance of the NVM driver
DRV_NVM_Open Opens the specified timer driver instance and returns a handle to it
Miscellaneous Functions
Name Description
DRV_NVM_BufferStatus Gets the current status of the buffer.
System Functions
Name Description
DRV_NVM_Deinitialize Deinitializes the specified instance of the NVM driver module
DRV_NVM_Initialize Initializes the NVM instance for the specified driver index
DRV_NVM_Status Gets the current status of the NVM driver module.
Description
This section describes the Application Programming Interface (API) functions of the NVM Driver Library.
Refer to each section for a detailed description.
5.1 Driver Library Help MPLAB Harmony Help Non-Volatile Memory (NVM) Driver Library
5-352
5.1.6.7.1 System Functions
5.1.6.7.1.1 DRV_NVM_Deinitialize Function
C
void DRV_NVM_Deinitialize(
SYS_MODULE_OBJ object
);
Description
Deinitializes the specified instance of the NVM driver module, disabling its operation (and any hardware). Invalidates all the
internal data.
Preconditions
Function DRV_NVM_Initialize should have been called before calling this function.
Parameters
Parameters Description
object Driver object handle, returned from the DRV_NVM_Initialize routine
Returns
None.
Remarks
Once the Initialize operation has been called, the Deinitialize operation must be called before the Initialize operation can be
called again.
This routine will NEVER block waiting for hardware. If the operation requires time to allow the hardware to complete, this will be
reported by the DRV_NVM_Status operation. The system has to use DRV_NVM_Status to find out when the module is in the
ready state.
Example
// This code snippet shows an example
// of deinitializng the driver.
SYS_MODULE_OBJ object; // Returned from DRV_NVM_Initialize
SYS_STATUS status;
DRV_NVM_Deinitialize(object);
status = DRV_NVM_Status(object);
if (SYS_MODULE_DEINITIALIZED != status)
{
// Check again later if you need to know
// when the driver is deinitialized.
}
5.1.6.7.1.2 DRV_NVM_Initialize Function
C
SYS_MODULE_OBJ DRV_NVM_Initialize(
const SYS_MODULE_INDEX index,
const SYS_MODULE_INIT * const init
);
5.1 Driver Library Help MPLAB Harmony Help Non-Volatile Memory (NVM) Driver Library
5-353
Description
This routine initializes the NVM driver instance for the specified driver index, making it ready for clients to open and use it.
Preconditions
None.
Parameters
Parameters Description
index Identifier for the instance to be initialized also the type of memory used
init Pointer to a data structure containing any data necessary to initialize the driver.
Returns
If successful, returns a valid handle to a driver instance object. Otherwise, it returns SYS_MODULE_OBJ_INVALID.
Remarks
This routine must be called before any other NVM routine is called.
This routine should only be called once during system initialization unless DRV_NVM_Deinitialize is called to de-initialize the
driver instance.
This routine will NEVER block for hardware access. If the operation requires time to allow the hardware to re-initialize, it will be
reported by the DRV_NVM_Status operation. The system must use DRV_NVM_Status to find out when the driver is in the ready
state.
Build configuration options may be used to staticaly override options in the "init" sructure and will take precedance over
initialization data passed using this routine.
Example
// This code snippet shows an example
// of initializing the NVM Driver.
DRV_NVM_INIT NVMInitData;
SYS_MODULE_OBJ objectHandle;
NVMInitData.moduleInit.value = SYS_MODULE_POWER_RUN_FULL;
NVMInitData.moduleId = NVM_ID_0;
NVMInitData.flashInterruptSource = INT_SOURCE_FLASH_CONTROL;
//usage of DRV_NVM_INDEX_0 indicates usage of flash realted APIs
objectHandle = DRV_NVM_Initialize(DRV_NVM_INDEX_0, (SYS_MODULE_INIT*)NVMInitData);
if (SYS_MODULE_OBJ_INVALID == objectHandle)
{
// Handle error
}
5.1.6.7.1.3 DRV_NVM_Status Function
C
SYS_STATUS DRV_NVM_Status(
SYS_MODULE_OBJ object
);
Description
This routine provides the current status of the NVM driver module.
Preconditions
Function DRV_NVM_Initialize should have been called before calling this function.
5.1 Driver Library Help MPLAB Harmony Help Non-Volatile Memory (NVM) Driver Library
5-354
Parameters
Parameters Description
object Driver object handle, returned from the DRV_NVM_Initialize routine
Returns
SYS_STATUS_READY - Indicates that the driver is ready and accept requests for new operations.
Note Any value greater than SYS_STATUS_READY is also a normal running state in which the driver is ready to accept new
operations.
SYS_STATUS_BUSY - Indicates that the driver is busy with a previous system level operation and cannot start another
SYS_STATUS_ERROR - Indicates that the driver is in an error state
Remarks
Any value less than SYS_STATUS_ERROR is also an error state.
SYS_MODULE_DEINITIALIZED - Indicates that the driver has been de-initialized
This value is less than SYS_STATUS_ERROR
The this operation can be used to determine when any of the driver's module level operations has completed.
If the status operation returns SYS_STATUS_BUSY, the a previous operation has not yet completed. Once the status operation
returns SYS_STATUS_READY, any previous operations have completed.
The value of SYS_STATUS_ERROR is negative (-1). Any value less than that is also an error state.
This routine will NEVER block waiting for hardware.
If the Status operation returns an error value, the error may be cleared by calling the reinitialize operation. If that fails, the
deinitialize operation will need to be called, followed by the initialize operation to return to normal operations.
Example
SYS_MODULE_OBJ object; // Returned from DRV_NVM_Initialize
SYS_STATUS NVMStatus;
NVMStatus = DRV_NVM _Status(object);
else if (SYS_STATUS_ERROR >= NVMStatus)
{
// Handle error
}
5.1.6.7.2 Client Core Functions
5.1.6.7.2.1 DRV_NVM_ClientStatus Function
C
DRV_NVM_CLIENT_STATUS DRV_NVM_ClientStatus(
const DRV_HANDLE handle
);
Description
This routine gets the client-specfic status of the NVM driver associated with the given handle.
Preconditions
The DRV_NVM_Initialize routine must have been called.
DRV_NVM_Open must have been called to obtain a valid opened device handle.
5.1 Driver Library Help MPLAB Harmony Help Non-Volatile Memory (NVM) Driver Library
5-355
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open routine
Returns
A DRV_NVM_CLIENT_STATUS value describing the current status of the driver
Remarks
This routine will not block for hardware access and will immediately return the current status.
Example
DRV_HANDLE handle; // Returned from DRV_NVM_Open
DRV_NVM_CLIENT_STATUS clientStatus;
clientStatus = DRV_NVM_ClientStatus(handle);
if(DRV_NVM_CLIENT_STATUS_ERROR >= clientStatus)
{
// Handle the error
}
5.1.6.7.2.2 DRV_NVM_Close Function
C
void DRV_NVM_Close(
const DRV_HANDLE handle
);
Description
This routine closes an opened-instance of the NVM driver, invalidating the handle.
Preconditions
The DRV_NVM_Initialize routine must have been called for the specified NVM driver instance.
DRV_NVM_Open must have been called to obtain a valid opened device handle.
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open routine
Returns
None
Remarks
After calling this routine, the handle passed in "handle" must not be used with any of the remaining driver routines. A new handle
must be obtained by calling DRV_NVM_Open before the caller may use the driver again.
If DRV_IO_INTENT_BLOCKING was requested and the driver was built appropriately to support blocking behavior call may
block until the operation is complete.
If DRV_IO_INTENT_NON_BLOCKING request the driver client can call the DRV_NVM_Status operation to find out when the
module is in the ready state (the handle is no longer valid).
Usually there is no need for the driver client to verify that the Close operation has completed.
Example
DRV_HANDLE handle; // Returned from DRV_NVM_Open
5.1 Driver Library Help MPLAB Harmony Help Non-Volatile Memory (NVM) Driver Library
5-356
DRV_NVM_Close(handle);
5.1.6.7.2.3 DRV_NVM_Open Function
C
DRV_HANDLE DRV_NVM_Open(
const SYS_MODULE_INDEX index,
const DRV_IO_INTENT ioIntent
);
Description
This routine opens the specified NVM driver instance and provides a handle that must be provided to all other client-level
operations to identify the caller and the instance of the driver.
Preconditions
Function DRV_NVM_Initialize must have been called before calling this function.
Parameters
Parameters Description
drvIndex Identifier for the object instance to be opened
intent Zero or more of the values from the enumeration DRV_IO_INTENT "or'd" together
to indicate the intended use of the driver
Returns
If successful, the routine returns a valid open-instance handle (a number identifying both the caller and the module instance).
If an error occurs, the return value is DRV_HANDLE_INVALID.
Remarks
The handle returned is valid until the DRV_NVM_Close routine is called.
This routine will NEVER block waiting for hardware.
If the DRV_IO_INTENT_BLOCKING is requested and the driver was built appropriately to support blocking behavior, then other
client-level operations may block waiting on hardware until they are complete.
If DRV_IO_INTENT_NON_BLOCKING is requested the driver client can call the DRV_NVM_ClientStatus operation to find out
when the module is in the ready state.
If the requested intent flags are not supported, the routine will return DRV_HANDLE_INVALID.
Example
DRV_HANDLE handle;
handle = DRV_NVM_Open(DRV_NVM_INDEX_0, DRV_IO_INTENT_EXCLUSIVE);
if (DRV_HANDLE_INVALID == handle)
{
// Unable to open the driver
}
5.1.6.7.3 Client Block Data Functions
5.1.6.7.3.1 DRV_NVM_Erase Function
C
DRV_NVM_BUFFER_HANDLE DRV_NVM_Erase(
const DRV_HANDLE handle,
5.1 Driver Library Help MPLAB Harmony Help Non-Volatile Memory (NVM) Driver Library
5-357
uint8_t * targetbuffer,
const unsigned int numbytes
);
Description
This routine erases the specified number of pages in flash memory. It returns a buffer handle that can be queried by the
DRV_NVM_BufferStatus() function to check for completion of the operation. The target address should be aligned on a
DRV_NVM_PAGE_SIZE byte boundary. The number of bytes to write should be equal to or should be multiples of
DRV_NVM_PAGE_SIZE.
Preconditions
The DRV_NVM_Initialize routine must have been called for the specified NVM driver instance.
DRV_NVM_Open must have been called to obtain a valid opened device handle.
DRV_IO_INTENT_READ or DRV_IO_INTENT_READWRITE must have been specified in the DRV_NVM_Open call.
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open routine
targetBuffer Start address in NVM memory from where the erase should begin. Should be
aligned on a DRV_NVM_PAGE_SIZE byte boundary.
numbytes Total number of pages to be erased expressed in bytes. This should be equal to or
a multiple of DRV_NVM_PAGE_SIZE.
Returns
DRV_NVM_BUFFER_HANDLE_INVALID in case the operation was not successful. A valid handle otherwise.
Remarks
If the DRV_IO_INTENT_BLOCKING flag was given in the call to the DRV_NVM_Open routine and the driver was built to support
blocking behavior the call will block until the operation is complete.
If the DRV_IO_INTENT_NONBLOCKING flag was given in the call to the DRV_NVM_Open routine or the driver was built to only
support non-blocking behavior the call will return immediately.
Example
// Returned from DRV_NVM_Open
DRV_HANDLE handle;
// Destination address should be row aligned.
char *destAddress = (char *)NVM_BASE_ADDRESS_TO_ERASE;
unsigned int count = 2 * DRV_NVM_PAGE_SIZE;
DRV_NVM_BUFFER_HANDLE bufferHandle;
bufferHandle = DRV_NVM_Write(myNVMHandle, destAddress, count);
if(DRV_NVM_BUFFER_HANDLE_INVALID == bufferHandle)
{
// Do error handling here
}
// Wait till the buffer completes. This should not
// be a while loop if a part of cooperative multi-tasking
// routine. In that case, it should be invoked in task
// state machine.
while(DRV_NVM_BufferStatus(bufferHandle) != DRV_NVM_BUFFER_COMPLETED);
5.1 Driver Library Help MPLAB Harmony Help Non-Volatile Memory (NVM) Driver Library
5-358
5.1.6.7.3.2 DRV_NVM_Read Function
C
DRV_NVM_BUFFER_HANDLE DRV_NVM_Read(
const DRV_HANDLE handle,
uint8_t * targetBuffer,
uint8_t * srcAddress,
const unsigned int numbytes
);
Description
This routine reads a block of data from the specified address in memory. It returns a buffer handle that can be queried by the
DRV_NVM_BufferStatus() function to check for completion of the operation.
Preconditions
The DRV_NVM_Initialize routine must have been called for the specified NVM driver instance.
DRV_NVM_Open must have been called to obtain a valid opened device handle.
DRV_IO_INTENT_READ or DRV_IO_INTENT_READWRITE must have been specified in the DRV_NVM_Open call.
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open routine
targetBuffer Buffer into which the data read from the NVM instance will be placed.
srcAddress The base address in NVM memory from data read should begin
numbytes Total number of bytes that need to be read from the module instance (must be
equal to or less than the size of the buffer)
Returns
DRV_NVM_BUFFER_HANDLE_INVALID in case the operation was not successful. A valid handle otherwise.
Remarks
If the DRV_IO_INTENT_BLOCKING flag was given in the call to the DRV_NVM_Open routine and the driver was built to support
blocking behavior the call will block until the operation is complete.
If the DRV_IO_INTENT_NONBLOCKING flag was given in the call to the DRV_NVM_Open routine or the driver was built to only
support non-blocking behavior the call will return immediately, identifying how many bytes of data were actually copied into the
client's buffer and the client must call DRV_NVM_Read again with adjusted parameters as shown in the example.
Example
DRV_HANDLE handle; // Returned from DRV_NVM_Open
char myBuffer[MY_BUFFER_SIZE];
char *srcAddress = NVM_BASE_ADDRESS_TO_READ_FROM;
unsigned int count = MY_BUFFER_SIZE;
DRV_NVM_BUFFER_HANDLE bufferHandle;
bufferHandle = DRV_NVM_Read(myNVMHandle, &myBuffer[total], srcAddress, count);
if(DRV_NVM_BUFFER_HANDLE_INVALID == bufferHandle)
{
// Do error handling here
}
// Wait till the buffer completes. This should not
// be a while loop if a part of cooperative multi-tasking
// routine. In that case, it should be invoked in task
// state machine.
while(DRV_NVM_BufferStatus(bufferHandle) != DRV_NVM_BUFFER_COMPLETED);
5.1 Driver Library Help MPLAB Harmony Help Non-Volatile Memory (NVM) Driver Library
5-359
5.1.6.7.3.3 DRV_NVM_Tasks Function
C
void DRV_NVM_Tasks(
SYS_MODULE_OBJ object
);
Description
This routine is used to maintain the driver's internal write and erase state machine and implement its ISR for interrupt-driven
implementations.
Preconditions
The DRV_NVM_Initialize routine must have been called for the specified NVM driver instance.
Parameters
Parameters Description
object Object handle for the specified driver instance (returned from DRV_NVM_Initialize)
Returns
None.
Remarks
This routine is normally not called directly by an application. It is called by the system's Tasks routine (SYS_Tasks) or by the
apropriate raw ISR.
This routine may excute in an ISR context and will never block or access any resources that may cause it to block.
Example
SYS_MODULE_OBJ object; // Returned from DRV_NVM_Initialize
while (true)
{
DRV_NVM_Tasks (object);
// Do other tasks
}
5.1.6.7.3.4 DRV_NVM_Write Function
C
DRV_NVM_BUFFER_HANDLE DRV_NVM_Write(
DRV_HANDLE handle,
uint8_t * destination,
uint8_t * source,
const unsigned int nBytes
);
Description
This routine writes a block of data to a specified address in memory. It returns a buffer handle that can be queried by the
DRV_NVM_BufferStatus() function to check for completion of the operation. The contents of the source buffer should not be
changed while the operation is in progress. The target address should be aligned on a DRV_NVM_ROW_SIZE byte boundary.
The number of bytes to write should be equal to or should be multiples of DRV_NVM_ROW_SIZE.
Preconditions
The DRV_NVM_Initialize routine must have been called for the specified NVM driver instance.
DRV_NVM_Open must have been called to obtain a valid opened device handle.
5.1 Driver Library Help MPLAB Harmony Help Non-Volatile Memory (NVM) Driver Library
5-360
DRV_IO_INTENT_READ or DRV_IO_INTENT_READWRITE must have been specified in the DRV_NVM_Open call.
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open routine
targetBuffer Buffer in NVM memory where the data from srcAddress will be placed. Should be
aligned on a DRV_NVM_ROW_SIZE byte boundary.
srcAddress The source buffer containing data to programmed into NVM
numbytes Total number of bytes that need to be written to the NVM. This should be equal to
or a multiple of DRV_NVM_ROW_SIZE.
Returns
DRV_NVM_BUFFER_HANDLE_INVALID in case the operation was not successful. A valid handle otherwise.
Remarks
If the DRV_IO_INTENT_BLOCKING flag was given in the call to the DRV_NVM_Open routine and the driver was built to support
blocking behavior the call will block until the operation is complete.
If the DRV_IO_INTENT_NONBLOCKING flag was given in the call to the DRV_NVM_Open routine or the driver was built to only
support non-blocking behavior the call will return immediately.
Example
DRV_HANDLE handle; // Returned from DRV_NVM_Open
char myBuffer[2 * DRV_NVM_ROW_SIZE];
// Destination address should be row aligned.
char *destAddress = (char *)NVM_BASE_ADDRESS_TO_WRITE;
unsigned int count = 2 * MY_BUFFER_SIZE;
DRV_NVM_BUFFER_HANDLE bufferHandle;
bufferHandle = DRV_NVM_Write(myNVMHandle, destAddress, &myBuffer[total], count);
if(DRV_NVM_BUFFER_HANDLE_INVALID == bufferHandle)
{
// Do error handling here
}
// Wait till the buffer completes. This should not
// be a while loop if a part of cooperative multi-tasking
// routine. In that case, it should be invoked in task
// state machine.
while(DRV_NVM_BufferStatus(bufferHandle) != DRV_NVM_BUFFER_COMPLETED);
5.1.6.7.4 Client Basic Functions
5.1.6.7.5 Miscellaneous Functions
5.1.6.7.5.1 DRV_NVM_BufferStatus Function
C
DRV_NVM_BUFFER_STATUS DRV_NVM_BufferStatus(
DRV_HANDLE handle,
const DRV_HANDLE bufferHandle
);
5.1 Driver Library Help MPLAB Harmony Help Non-Volatile Memory (NVM) Driver Library
5-361
Description
This routine gets the current status of the buffer. The application must use this routine in case a polling based implementation is
desired.
Preconditions
The DRV_NVM_Initialize routine must have been called.
DRV_NVM_Open must have been called to obtain a valid opened device handle.
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open routine
Returns
A DRV_NVM_BUFFER_STATUS value describing the current status of the buffer
Remarks
This routine will not block for hardware access and will immediately return the current status.
Example
DRV_HANDLE handle; // Returned from DRV_NVM_Open
DRV_HANDLE bufferHandle;
DRV_NVM_BUFFER_STATUS status;
status = DRV_NVM_BufferStatus(handle, bufferHandle);
if(status == DRV_NVM_BUFFER_COMPLETED)
{
// Operation Done
}
5.1.6.7.6 Data Types and Constants
5.1.6.7.6.1 DRV_NVM_BUFFER_HANDLE_INVALID Macro
C
#define DRV_NVM_BUFFER_HANDLE_INVALID
Description
NVM Driver Buffer Invalid Handle
This value defines the NVM Driver Buffer Invalid handle. This value is returned by read/write/erase routines when the desired
operation could not be completed.
Remarks
None.
5.1.6.7.6.2 DRV_NVM_INDEX_0 Macro
C
#define DRV_NVM_INDEX_0 0
Description
Driver NVM Module Index reference
These constants provide NVM driver index definitions.
5.1 Driver Library Help MPLAB Harmony Help Non-Volatile Memory (NVM) Driver Library
5-362
Remarks
These constants should be used in place of hard-coded numeric literals.
These values should be passed into the DRV_NVM_Initialize and DRV_NVM_Open routines to identify the driver instance in use.
5.1.6.7.6.3 DRV_NVM_INDEX_COUNT Macro
C
#define DRV_NVM_INDEX_COUNT 1
Description
NVM Driver Module Index Count
This constant identifies NVM driver index definitions.
Remarks
This constant should be used in place of hard-coded numeric literals. This value is part-specific.
5.1.6.7.6.4 DRV_NVM_BUFFER_HANDLE Type
C
typedef uintptr_t DRV_NVM_BUFFER_HANDLE;
Description
NVM Driver Buffer Handle
This type defines the NVM Driver Buffer handle.
Remarks
None.
5.1.6.7.6.5 DRV_NVM_BUFFER_STATUS Enumeration
C
typedef enum {
DRV_NVM_BUFFER_COMPLETED = 0,
DRV_NVM_BUFFER_QUEUED = 1,
DRV_NVM_BUFFER_IN_PROGRESS = 2,
DRV_NVM_BUFFER_ERROR_UNKNOWN = -1
} DRV_NVM_BUFFER_STATUS;
Description
NVM Driver Buffer Status
This type specifies the status of the buffer for the read, write and erase opeartions.
Members
Members Description
DRV_NVM_BUFFER_COMPLETED = 0 Done OK and ready
DRV_NVM_BUFFER_QUEUED = 1 Scheduled but not started
DRV_NVM_BUFFER_IN_PROGRESS = 2 Currently being in transfer
DRV_NVM_BUFFER_ERROR_UNKNOWN
= -1
Unknown buffer
5.1 Driver Library Help MPLAB Harmony Help Non-Volatile Memory (NVM) Driver Library
5-363
Remarks
None.
5.1.6.7.6.6 DRV_NVM_CLIENT_STATUS Enumeration
C
typedef enum {
DRV_NVM_CLIENT_STATUS_READY,
DRV_NVM_CLIENT_STATUS_BUSY,
DRV_NVM_WRITE_TERMINATED,
DRV_NVM_ERASE_TERMINATED,
DRV_NVM_LOW_VOLTAGE_ERROR,
DRV_NVM_LOW_VOLTAGE_DETECT_ERROR,
DRV_NVM_STATUS_INVALID
} DRV_NVM_CLIENT_STATUS;
Description
NVM Client Status
Defines the various client status codes.
Members
Members Description
DRV_NVM_CLIENT_STATUS_READY Up and running, ready to start new operations
DRV_NVM_CLIENT_STATUS_BUSY Operation in progress, unable to start a new one
DRV_NVM_WRITE_TERMINATED Write operation terminated Occured
DRV_NVM_ERASE_TERMINATED Erase operation terminated Occured
DRV_NVM_LOW_VOLTAGE_ERROR Low voltage Error
DRV_NVM_LOW_VOLTAGE_DETECT_ERROR Low voltage Error
DRV_NVM_STATUS_INVALID Client Invalid
Remarks
None
5.1.6.7.6.7 DRV_NVM_INIT Structure
C
typedef struct {
SYS_MODULE_INIT moduleInit;
NVM_MODULE_ID nvmID;
INT_SOURCE interruptSource;
} DRV_NVM_INIT;
Description
NVM Driver Initialization Data
This data type defines the data required to initialize or reinitialize the NVM driver.
Members
Members Description
SYS_MODULE_INIT moduleInit; System module initialization
NVM_MODULE_ID nvmID; Identifies NVM hardware module (PLIB-level) ID
INT_SOURCE interruptSource; Interrupt Source for Write Interrupt
5.1 Driver Library Help MPLAB Harmony Help Non-Volatile Memory (NVM) Driver Library
5-364
Remarks
Not all the init features are available for all the microcontrollers
5.1.6.7.6.8 DRV_NVM_INDEX_1 Macro
C
#define DRV_NVM_INDEX_1 1
Description
This is macro DRV_NVM_INDEX_1.
5.1.6.8 Files
Files
Name Description
drv_nvm.h NVM Driver Interface Definition
drv_nvm_config_template.h NVM driver configuration definitions template
Description
5.1.6.8.1 drv_nvm.h
NVM Driver Interface Definition
The NVM device driver provides a simple interface to manage the NVM modules on Microchip microcontrollers. This file defines
the interface definition for the NVM driver.
Enumerations
Name Description
DRV_NVM_BUFFER_STATUS Specifies the status of the buffer for the read, write and erase opeartions.
DRV_NVM_CLIENT_STATUS Defines the client status
Functions
Name Description
DRV_NVM_BufferStatus Gets the current status of the buffer.
DRV_NVM_ClientStatus Gets current client-specific status the NVM driver
DRV_NVM_Close Closes an opened-instance of the NVM driver
DRV_NVM_Deinitialize Deinitializes the specified instance of the NVM driver module
DRV_NVM_Erase Erase the specified number of pages in flash memory.
DRV_NVM_Initialize Initializes the NVM instance for the specified driver index
DRV_NVM_Open Opens the specified timer driver instance and returns a handle to it
DRV_NVM_Read Reads a block of data from the specified address in memory.
DRV_NVM_Status Gets the current status of the NVM driver module.
DRV_NVM_Tasks Maintains the driver's erase and write state machine and implements its ISR.
DRV_NVM_Write Write a block of data to a specified address in memory.
5.1 Driver Library Help MPLAB Harmony Help Non-Volatile Memory (NVM) Driver Library
5-365
Macros
Name Description
DRV_NVM_BUFFER_HANDLE_INVALID This value defines the NVM Driver Buffer Invalid handle.
DRV_NVM_INDEX_0 NVM driver index definitions
DRV_NVM_INDEX_1 This is macro DRV_NVM_INDEX_1.
DRV_NVM_INDEX_COUNT Number of valid NVM driver indices
Structures
Name Description
DRV_NVM_INIT Defines the data required to initialize or reinitialize the NVM driver
Types
Name Description
DRV_NVM_BUFFER_HANDLE This type defines the NVM Driver Buffer handle.
File Name
drv_nvm.h
Company
Microchip Technology Incorported
5.1.6.8.2 drv_nvm_config_template.h
NVM Driver Configuration Definitions for the template version
These definitions statically define the driver's mode of operation.
Macros
Name Description
DRV_NVM_BUFFER_OBJECT_NUMBER Selects the maximum number of buffer objects
DRV_NVM_CLIENTS_NUMBER Selects the maximum number of clients
DRV_NVM_ERASE_SIZE Specifies the NVM Driver Erase Page Size in bytes.
DRV_NVM_INSTANCES_NUMBER Selects the maximum number of Driver instances that can be
supported by the dynamic driver.
DRV_NVM_INTERRUPT_MODE Macro specifies operation of the driver to be in the interrupt mode or
polled mode
DRV_NVM_ROW_SIZE Specifies the NVM Driver Program Row Size in bytes.
DRV_NVM_UNLOCK_KEY1 Specifies the NVM Driver Program Unlock Key 1
DRV_NVM_UNLOCK_KEY2 Specifies the NVM Driver Program Unlock Key 2
File Name
drv_NVM_config_template.h
Company
Microchip Technology Incorported
5.1 Driver Library Help MPLAB Harmony Help Parallel Master Port (PMP) Driver Library
5-366
5.1.7 Parallel Master Port (PMP) Driver Library
5.1.7.1 Introduction
PMP Driver Library
for
Microchip Microcontrollers
This library provides an interface to manage the Parallel Master Port (PMP) module on Microchip family of microcontrollers in
different modes of operation.
Description
The Parallel Master Port (PMP) is a parallel 8-bit/16-bit I/O module specifically designed to communicate with a wide variety of
parallel devices such as communications peripherals, LCDs, external memory devices and microcontrollers. Because the
interfaces to parallel peripherals vary significantly, the PMP module is highly configurable.
The following figure shows a generic block diagram of the ways PMP module can be used:
PMP module can be used in different modes. Master and Slave are the two modes which can further have sub-modes
depending on the different microcontroller families.
Master Mode: In master mode, the PMP module can provide a 8-bit or 16-bit data bus, up to 16 bits of address, and all the
necessary control signals to operate a variety of external parallel devices such as memory devices, peripherals and slave
microcontrollers. The PMP master modes provide a simple interface for reading and writing data, but not executing program
instructions from external devices, such as SRAM or Flash memories.
Slave Mode: Slave modes support 8-bit data only and the module control pins are automatically dedicated when this mode is
selected.
5.1.7.2 Release Notes
MPLAB Harmony Version: v0.70b PMP Driver Library Version : 0.01 Release Date: 18Nov2013
New This Release:
This is the first release of the library. The interface can change in the beta and\or 1.0 release.
5.1 Driver Library Help MPLAB Harmony Help Parallel Master Port (PMP) Driver Library
5-367
Known Issues:
Nothing to report in this release.
5.1.7.3 SW License Agreement
(c) 2013 Microchip Technology Inc.
Microchip licenses this software to you solely for use with Microchip products. The software is owned by Microchip and its
licensors, and is protected under applicable copyright laws. All rights reserved.
SOFTWARE IS PROVIDED "AS IS" MICROCHIP EXPRESSLY DISCLAIMS ANY WARRANTY OF ANY KIND, WHETHER
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL MICROCHIP BE LIABLE FOR
ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, HARM TO
YOUR EQUIPMENT, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS
BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR
CONTRIBUTION, OR OTHER SIMILAR COSTS.
To the fullest extent allowed by law, Microchip and its licensors liability shall not exceed the amount of fees, if any, that you have
paid directly to Microchip to use this software.
MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE TERMS.
5.1.7.4 Using the Library
This topic describes the basic architecture of the PMP Driver Library and provides information and examples on how to use it.
Interface Header File: drv_pmp.h
The interface to the PMP Driver library is defined in the "drv_pmp.h" header file. This file is included by the "drv.h" file. Any C
language source (.c) file that uses the PMP Driver Library should include "drv.h".
Library File: The PMP Driver Library archive (.a) file installed with MPLAB Harmony.
Please refer to the MPLAB Harmony Overview for how the driver interacts with the framework.
5.1.7.4.1 Abstraction Model
This library provides a low-level abstraction of the Parallel Master Port (PMP) module on Microchip's microcontrollers with a
convenient C language interface. This topic describes how that abstraction is modeled in software and introduces the library's
interface.
Description
Hardware Abstraction Model Description
The PMP module provides interface routines to interact with external peripherals such as LCD, EEPROM, Flash memory, etc.,
as shown in the following diagram. The diagram shows the PMP module acting as a master. The PMP module can be easily
configured to act as a slave. The address and data lines can be multiplexed to suit the application. The address and data buffers
are up to 2-byte (16-bit) buffers for data transmitted or received by the parallel interface to the PMP bus over the data and
address lines synchronized with control logic including the read and write strobe.
5.1 Driver Library Help MPLAB Harmony Help Parallel Master Port (PMP) Driver Library
5-368
PMP Hardware Abstraction Model Diagram
The desired timing wait states to suit different peripheral timings can also be programmed using the PMP module.
5.1.7.4.2 Library Overview
Refer to the section Driver Overview for how the driver operates in a system.
The library interface routines are divided into various sub-sections, each sub-section addresses one of the blocks or the overall
operation of the PMP module.
Library Interface
Section
Description
System Functions Provides system module interfaces, device initialization, deinitialization, re-initialization, tasks, and
status functions.
Client Interaction
Functions
Provides open, close, client status and client mode configuration functions.
Client Transfer
Functions
Provides interface for data transfer in master and slave mode.
Miscellaneous Provides driver miscellaneous functions, version identification functions etc.
5.1.7.4.3 How the Library Works
This section describes how the PMP Driver Library operates.
Description
Before the driver is ready for use, its should be configured (compile time configuration). Refer to the Configuring the Library
section for more details on how to configure the driver.
There are few run-time configuration items that are done during initialization of the driver instance, and a few that are
client-specific and are done using dedicated functions.
To use the PMP Driver, initialization and client functions should be invoked in a specific sequence to ensure correct operation.
The following is the sequence in which various routines should be called:
1. Call DRV_PMP_Init to initialize the PMP Driver. Note that this may be performed by the MPLAB Harmony system module.
The DRV_PMP_Status function may be used to check the status of the initialization.
2. Once initialization for a particular driver instance is done, the client wanting to use the driver can open it using API
DRV_PMP_Open.
3. The DRV_PMP_ModeConfig function should now be called, which will configure the driver for the exact mode of operation
required by that client.
5.1 Driver Library Help MPLAB Harmony Help Parallel Master Port (PMP) Driver Library
5-369
4. After configuring the mode, DRV_PMP_Write and/or DRV_PMP_Read can be called by the user application to Write/Read
using the PMP module. Calling these functions does not start the PMP transfer immediately in non-interrupt mode. Instead, all
of these transfer tasks are queued in an internal queue. Actual transfer starts only when the PMP Task function is called by
the system/user. In interrupt mode, although transfer tasks are queued, the actual transfer starts immediately.
5. PMP Write and Read functions return an ID of that particular transfer, which should be saved by user to get the status of that
transfer later.
6. The system will either call DRV_PMP_Tasks from the System Task Service (in a polled environment), or it will be called from
interrupt service routine of the PMP.
7. At any time status of the transfer can be obtained by using DRV_PMP_TransferStatus.
Note: Not all modes are available on all devices. Please refer to the specific device data sheet to determine the supported
modes.
5.1.7.4.3.1 System Initialization
This section describes initialization and reinitialization features.
Description
Initialization and Reinitialization
The system performs the initialization and the reinitialization of the device driver with settings that affect only the instance of the
device that is being initialized or reinitialized. During system initialization each instance of the PMP device will be initialized with
the following configuration settings:
Initialization
member
Description
moduleInit System module initialization of the power state.
pmpId PMP hardware module ID (peripheral library-level ID).
stopInIdle Decide whether or not the module should be stopped in Idle mode.
muxMode To select one of the different multiplexing modes possible for PMP module.
inputBuffer Select the type of Input Buffer will be of TTL or Schmitt Trigger.
polarity Select polarity of different PMP pins.
ports Set the pins the user wants to use as port or PMP pins.
The DRV_PMP_Initialize function returns an object handle of the type SYS_MODULE_OBJ. After this, the object handle
returned by the initialize interface would be used by the other system interfaces, such as DRV_PMP_Reinitialize,
DRV_PMP_Deinitialize, DRV_PMP_Status, and DRV_PMP_Tasks.
Example for PMP Initialization Through the DRV_PMP_INIT Structure
DRV_PMP_INIT init;
SYS_MODULE_OBJ object;
SYS_STATUS pmpStatus;
// populate the PMP init configuration structure
init.inputBuffer = PMP_INPUT_BUFFER_TTL;
init.polarity.addressLatchPolarity = PMP_POLARITY_ACTIVE_HIGH;
init.polarity.rwStrobePolarity = PMP_POLARITY_ACTIVE_LOW;
init.polarity.writeEnableStrobePolarity = PMP_POLARITY_ACTIVE_LOW;
init.polarity.chipselect1Polarity = PMP_POLARITY_ACTIVE_HIGH;
init.polarity.chipselect2Polarity = PMP_POLARITY_ACTIVE_LOW;
init.ports.addressPortsMask = PMP_PMA0_PORT | PMP_PMA1_PORT | PMP_PMA2_TO_PMA13_PORTS |
PMP_PMA14_PORT;
init.ports.readWriteStrobe = PORT_ENABLE;
init.ports.writeEnableStrobe = PORT_ENABLE;
5.1 Driver Library Help MPLAB Harmony Help Parallel Master Port (PMP) Driver Library
5-370
init.moduleInit.value = SYS_MODULE_POWER_RUN_FULL;
init.pmpID = PMP_ID_0;
init.stopInIdle = false;
init.muxMode = PMP_MUX_NONE;
object = DRV_PMP_Initialize (DRV_PMP_INDEX_0, (SYS_MODULE_INIT *)&init);
pmpStatus = DRV_PMP_Status(object);
if ( SYS_STATUS_READY != pmpStatus)
{
// Handle error
}
Deinitialization
Once the initialize operation has been called, the deinitialize operation must be called before the initialize operation can be called
again. This routine may block if the driver is running in an OS environment that supports blocking operations and the driver
requires system resources access. However, the function will never block for hardware PMP access. If the operation requires
time to allow the hardware to complete, which will be reported by DRV_PMP_Status.
Status
PMP status is available to query the module state before, during and after initialization, deinitialization, and reinitialization.
Tasks Routine
The DRV_PMP_Tasks function will see the queue status and perform the task of transferring the data accordingly. In the
Blocking mode when interrupts are disabled, it will finish one of the tasks completely (that means emptying one space in queue),
and then return back. Whereas in Non-Blocking mode, it will return back just after starting one word (8-bit or 16-bit) of transfer
(may not be emptying one space in the queue, as that task may not be completely finished).
The DRV_PMP_Tasks function can be called in two ways:
• By the system task service in a polled environment
• By the interrupt service routine of the PMP in an interrupt-based system
Example: Polling
int main( void )
{
SYS_MODULE_OBJ object;
object = DRV_PMP_Initialize( DRV_PMP_INDEX_0, (SYS_MODULE_INIT *) &initConf );
if( SYS_STATUS_READY != DRV_PMP_Status( object ) )
return 0;
while (1)
{
DRV_PMP_Tasks (object);
}
}
Example: Interrupt
int main( void )
{
SYS_MODULE_OBJ object;
object = DRV_PMP_Initialize( DRV_PMP_INDEX_0, (SYS_MODULE_INIT *) &initConf );
if( SYS_STATUS_READY != DRV_PMP_Status( object ) )
return 0;
while (1);
5.1 Driver Library Help MPLAB Harmony Help Parallel Master Port (PMP) Driver Library
5-371
}
/* Sample interrupt routine not specific to any device family */
void ISR PMPInterrupt(void)
{
//Call the PMP Tasks routine
DRV_PMP_Tasks(object);
}
Note: A PMP transfer in Blocking mode in an interrupt environment is not supported.
5.1.7.4.3.1.1 Transfer Operation
This section describes transfer operation.
Description
Once the PMP Driver is open and configured for a client, it is set to start Reading/Writing through DRV_PMP_Read and
DRV_PMP_Write. However, these functions will not directly start reading or writing. These will just put the relevant information in
a queue in non-interrupt mode and return an ID that can be used later for checking the transfer status. In Interrupt mode, the
Read/Write functions will trigger the transfer immediately after storing the transfer information in the queue.
The user must use a buffer pointing to character for data values.
The repeatCount parameter allows the user to repeatedly write the same nBytes of data into the slave devices.
Example:
unsigned char myReadBuffer[300], myWriteBuffer[100]; // has to be 'char' arrays
uint32_t deviceAddress, nBytes, repeatCount, i;
uint32_t writeID, readID;
DRV_HANDLE handle;
//initialize, open and configure the driver/client
/* ... */
deviceAddress = 0x0206;
nBytes = 100;
repeatCount = 0x01;
for (i=0; i= pmpStatus)
{
// Handle error
}
5.1.7.7.1.4 DRV_PMP_Status Function
C
SYS_STATUS DRV_PMP_Status(
const SYS_MODULE_OBJ pmpDriverObject
);
Description
This function provides the current status of the PMP driver module.
Preconditions
The DRV_PMP_Initialize function must have been called before calling this function.
Parameters
Parameters Description
pmpDriverObject Driver object handle, returned from the DRV_PMP_Initialize routine
Returns
SYS_STATUS_READY - Indicates that the driver is busy with a previous system level operation and cannot start another
Remarks
Any value greater than SYS_STATUS_READY is also a normal running state in which the driver is ready to accept new
operations.
SYS_STATUS_BUSY - Indicates that the driver is busy with a previous system level operation and cannot start another
SYS_STATUS_ERROR - Indicates that the driver is in an error state
5.1 Driver Library Help MPLAB Harmony Help Parallel Master Port (PMP) Driver Library
5-381
Any value less than SYS_STATUS_ERROR is also an error state.
SYS_MODULE_DEINITIALIZED - Indicates that the driver has been deinitialized
This value is less than SYS_STATUS_ERROR.
This operation can be used to determine when any of the driver's module level operations has completed.
If the status operation returns SYS_STATUS_BUSY, a previous operation has not yet completed. Once the status operation
returns SYS_STATUS_READY, any previous operations have completed.
The value of SYS_STATUS_ERROR is negative (-1). Any value less than that is also an error state.
This function will NEVER block waiting for hardware.
If the Status operation returns an error value, the error may be cleared by calling the reinitialize operation. If that fails, the
deinitialize operation will need to be called, followed by the initialize operation to return to normal operations.
Example
SYS_MODULE_OBJ pmpDriverObject; // Returned from DRV_PMP_Initialize
SYS_STATUS status;
status = DRV_PMP_Status(pmpDriverObject);
else if (SYS_STATUS_ERROR >= status)
{
// Handle error
}
5.1.7.7.1.5 DRV_PMP_Tasks Function
C
void DRV_PMP_Tasks(
SYS_MODULE_OBJ pmpDriverObject
);
Description
This function is used to maintain the queue and execute the tasks stored in the queue. It resides in the ISR of the PMP for
interrupt-driven implementations.
Preconditions
The DRV_PMP_Initialize function must have been called for the specified PMP driver instance.
Parameters
Parameters Description
pmpDriverObject Object handle for the specified driver instance (returned from DRV_PMP_Initialize)
Returns
None.
Remarks
This function is normally not called directly by an application. It is called by the system's Tasks routine (SYS_Tasks) or by the
appropriate raw ISR.
This function may excute in an ISR context and will never block or access any resources that may cause it to block.
Example
SYS_MODULE_OBJ pmpDriverObject; // Returned from DRV_PMP_Initialize
while (true)
{
5.1 Driver Library Help MPLAB Harmony Help Parallel Master Port (PMP) Driver Library
5-382
DRV_PMP_Tasks (pmpDriverObject);
// Do other tasks
}
5.1.7.7.2 Client Interaction Functions
5.1.7.7.2.1 DRV_PMP_ClientStatus Function
C
DRV_PMP_CLIENT_STATUS DRV_PMP_ClientStatus(
DRV_HANDLE hClient
);
Description
This function gets the client-specfic status of the PMP driver associated with the specified handle.
Preconditions
The DRV_PMP_Initialize routine must have been called.
DRV_PMP_Open must have been called to obtain a valid opened device handle.
Parameters
Parameters Description
hClient A valid open-instance handle, returned from the driver's open routine
Returns
A DRV_PMP_CLIENT_STATUS value describing the current status of the driver.
Remarks
This function will not block for hardware access and will immediately return the current status.
Example
DRV_HANDLE hClient; // Returned from DRV_PMP_Open
DRV_PMP_CLIENT_STATUS pmpClientStatus;
pmpClientStatus = DRV_PMP_ClientStatus(hClient);
if(DRV_PMP_CLIENT_STATUS_ERROR >= pmpClientStatus)
{
// Handle the error
}
5.1.7.7.2.2 DRV_PMP_Close Function
C
void DRV_PMP_Close(
const DRV_HANDLE hClient
);
Description
This function closes an opened instance of the PMP driver, invalidating the handle.
Preconditions
The DRV_PMP_Initialize routine must have been called for the specified PMP driver instance.
DRV_PMP_Open must have been called to obtain a valid opened device handle.
5.1 Driver Library Help MPLAB Harmony Help Parallel Master Port (PMP) Driver Library
5-383
Parameters
Parameters Description
hClient A valid open instance handle, returned from the driver's open routine
Returns
None
Remarks
After calling this function, the handle passed in "handle" must not be used with any of the remaining driver routines. A new
handle must be obtained by calling DRV_PMP_Open before the caller may use the driver again.
If DRV_IO_INTENT_BLOCKING was requested and the driver was built appropriately to support blocking behavior call may
block until the operation is complete.
If DRV_IO_INTENT_NON_BLOCKING request the driver client can call the DRV_PMP_Status operation to find out when the
module is in the ready state (the handle is no longer valid).
Usually there is no need for the driver client to verify that the Close operation has completed.
Example
DRV_HANDLE hClient; // Returned from DRV_PMP_Open
DRV_PMP_Close(hClient);
5.1.7.7.2.3 DRV_PMP_ModeConfig Function
C
void DRV_PMP_ModeConfig(
DRV_HANDLE hClient,
DRV_PMP_MODE_CONFIG config
);
Description
This function configures the modes for client in which it wants to operate. Different master-slave modes, 8/16 data bits selection,
address increment/decrement, interrupt mode, wait states, etc., can be configured through this function.
Preconditions
Function DRV_PMP_Initialize must have been called. DRV_PMP_Open must have been called to obtain a valid opened device
handle.
Parameters
Parameters Description
hClient Client handle obtained from DRV_PMP_Open API
config Structure which will have all the required PMP modes configuration
Returns
None.
Remarks
This function will NEVER block waiting for hardware. If this API is called more than once for a particular client handle, previous
config setting of that client will be overwritten.
Example
DRV_HANDLE hClient;
DRV_PMP_MODE_CONFIG config;
5.1 Driver Library Help MPLAB Harmony Help Parallel Master Port (PMP) Driver Library
5-384
config.chipSelect = PMCS1_AND_PMCS2_AS_CHIP_SELECT;
config.endianMode = LITTLE_ENDIAN;
config.incrementMode = PMP_ADDRESS_AUTO_INCREMENT;
config.intMode = PMP_INTERRUPT_NONE;
config.pmpMode = PMP_MASTER_READ_WRITE_STROBES_INDEPENDENT;
config.portSize = PMP_DATA_SIZE_8_BITS;
config.waitStates.dataHoldWait = PMP_DATA_HOLD_2;
config.waitStates.dataWait = PMP_DATA_WAIT_THREE;
config.waitStates.strobeWait = PMP_STROBE_WAIT_5;
DRV_PMP_ModeConfig ( hClient, config );
5.1.7.7.2.4 DRV_PMP_Open Function
C
DRV_HANDLE DRV_PMP_Open(
const SYS_MODULE_INDEX index,
const DRV_IO_INTENT intent
);
Description
This function opens the specified PMP driver instance and provides a handle that must be provided to all other client-level
operations to identify the caller and the instance of the driver.
Preconditions
The DRV_PMP_Initialize function must have been called before calling this function.
Parameters
Parameters Description
drvIndex Identifier for the object instance to be opened
intent Zero or more of the values from the enumeration DRV_IO_INTENT ORed together
to indicate the intended use of the driver
Returns
If successful, the function returns a valid open-instance handle (a number identifying both the caller and the module instance).
If an error occurs, the return value is DRV_HANDLE_INVALID.
Remarks
The handle returned is valid until the DRV_PMP_Close routine is called.
This function will NEVER block waiting for hardware.
If the DRV_IO_INTENT_BLOCKING is requested and the driver was built appropriately to support blocking behavior, other
client-level operations may block waiting on hardware until they are complete.
If DRV_IO_INTENT_NON_BLOCKING is requested the driver client can call the DRV_PMP_ClientStatus operation to find out
when the module is in the ready state.
If the requested intent flags are not supported, the routine will return DRV_HANDLE_INVALID.
Example
DRV_HANDLE hClient;
hClient = DRV_PMP_Open(DRV_PMP_INDEX_0, DRV_IO_INTENT_EXCLUSIVE);
if (DRV_HANDLE_INVALID == hClient)
{
// Unable to open the driver
}
5.1 Driver Library Help MPLAB Harmony Help Parallel Master Port (PMP) Driver Library
5-385
5.1.7.7.2.5 DRV_PMP_Read Function
C
QUEUE_ELEMENT_OBJECT* DRV_PMP_Read(
DRV_HANDLE hClient,
uint32_t address,
uint16_t* buffer,
uint32_t nBytes
);
Description
This function reads the given number of data bytes from the given address of the external device to the MCU buffer through the
selected PMP instance. This function should be used for all the master and slave modes. Proper configuration should be done
using DRV_PMP_ModeConfig before calling this function.
Preconditions
The DRV_PMP_Initialize routine must have been called. DRV_PMP_Open must have been called to obtain a valid opened
device handle. DRV_PMP_ModeConfig must have been called to configure the desired mode
Parameters
Parameters Description
hClient A valid open-instance handle, returned from the driver's open routine
address Starting address of the slave device from where data has to be read. It does not
have any significance for legacy slave mode and buffer mode. In PMP enhanced
slave mode i.e. addressable buffer slave mode, this parameter should be the
buffer number to be used.
buffer Pointer to the buffer into which the data read through the PMP instance will be
placed. Even if only one word has to be tranferred, pointer should be used.
nBytes Number of bytes that need to be read through the PMP instance
Returns
Returns the position number of the queue, where the data element was stored. Returns '0' when there is no place in the queue to
store the data.
Example
DRV_HANDLE hClient; // Returned from DRV_PMP_Open
uint32_t deviceAddress;
uint32_t nBytes;
unsigned char myBuffer[nBytes];
uint32_t transferID;
transferID = DRV_PMP_Read ( hClient, deviceAddress, &myBuffer, nBytes);
5.1.7.7.2.6 DRV_PMP_Write Function
C
QUEUE_ELEMENT_OBJECT* DRV_PMP_Write(
DRV_HANDLE* hClient,
bool address,
uint32_t * buffer,
uint32_t nBytes,
uint32_t repeatCount
);
Description
This function transfer the given number of data bytes from the MCU buffer location to the defined address of the external device
5.1 Driver Library Help MPLAB Harmony Help Parallel Master Port (PMP) Driver Library
5-386
through the selected PMP instance. It repeats the operation n (=repeatCount) number of times as well. This function should be
used for all the master and slave modes. Proper configuration should be done using DRV_PMP_ModeConfig before calling this
function.
Preconditions
The DRV_PMP_Initialize routine must have been called. DRV_PMP_Open must have been called to obtain a valid opened
device handle. DRV_PMP_ModeConfig must have been called to configure the desired mode.
Parameters
Parameters Description
hClient A valid open-instance handle, returned from the driver's open routine
address Starting address of the slave device where data has to be written. It does not have
any significance for legacy slave mode and buffer mode. In PMP enhanced slave
mode (i.e., addressable buffer slave mode), this parameter should be the buffer
number to be used.
buffer Pointer to MCU Buffer from which the data will be written through the PMP
instance. even if only one word has to be tranferred, pointer should be used.
nBytes Total number of bytes that need to be written through the PMP instance
repeatCount Number of times the data set (nBytes of data) to be repetedly written. This value
should be 0 if user does not want any repetation. If repeatCount is greater than 0,
then after writing every nBytes of data, the buffer starts pointing to its first element.
Ideally, PMP Address should be in auto increment/decrement mode for
repeatCount greater than 0.
Returns
Returns a 32-bit ID with which status of the transfer can be checked later. Returns '0' when there is no place in the queue to
store the data.
Example
DRV_HANDLE hClient; // Returned from DRV_PMP_Open
uint32_t deviceAddress;
uint32_t nBytes;
unsigned char myBuffer[nBytes];
uint32_t repeatCount;
uint32_t transferID;
transferID = DRV_PMP_MasterWrite ( hClient, deviceAddress, &myBuffer, nBytes, repeatCount);
5.1.7.7.3 Client Transfer Functions
5.1.7.7.3.1 DRV_PMP_TransferStatus Function
C
DRV_PMP_TRANSFER_STATUS DRV_PMP_TransferStatus(
QUEUE_ELEMENT_OBJECT* queueObject
);
Description
This function returns the status of a particular transfer whose ID has been specified as input.
Parameters
Parameters Description
drvIndex Identifier for the object instance to be opened
seqID A valid ID returned from read/write transfer functions
5.1 Driver Library Help MPLAB Harmony Help Parallel Master Port (PMP) Driver Library
5-387
Returns
A DRV_PMP_TRANSFER_STATUS value describing the current status of the transfer.
Example
uint32_8 seqID;
DRV_PMP_TRANSFER_STATUS transferStatus;
transferStatus = DRV_PMP_TransferStatus( DRV_PMP_INDEX_0, seqID);
5.1.7.7.4 Data Types and Constants
5.1.7.7.4.1 DRV_PMP_INDEX_COUNT Macro
C
#define DRV_PMP_INDEX_COUNT _PMP_EXISTS
Description
PMP Driver Module Index Count
This constant identifies the number of valid PMP driver indices.
Remarks
The value of "_PMP_EXISTS" is derived from device-specific header files defined as part of the peripheral libraries.
5.1.7.7.4.2 DRV_PMP_CHIPX_STROBE_MODE Enumeration
C
typedef enum {
PMP_RW_STROBE_WITH_ENABLE_STROBE,
PMP_READ_AND_WRITE_STROBES
} DRV_PMP_CHIPX_STROBE_MODE;
Description
PMP writeEnable/ReadWrite strobes
This enumeration provides ReadWrite/WriteEnable Strobe definitions.
Members
Members Description
PMP_RW_STROBE_WITH_ENABLE_STROBE One strobe for read/write and another for enable
PMP_READ_AND_WRITE_STROBES Separate strobes for read and write operations
5.1.7.7.4.3 DRV_PMP_CLIENT_STATUS Enumeration
C
typedef enum {
DRV_PMP_CLIENT_STATUS_INVALID,
PMP_CLIENT_STATUS_CLOSED,
DRV_PMP_CLIENT_STATUS_OPEN
} DRV_PMP_CLIENT_STATUS;
Description
PMP Client Status
This enumeration provides various client status possibilities.
5.1 Driver Library Help MPLAB Harmony Help Parallel Master Port (PMP) Driver Library
5-388
5.1.7.7.4.4 DRV_PMP_ENDIAN_MODE Enumeration
C
typedef enum {
LITTLE,
BIG
} DRV_PMP_ENDIAN_MODE;
Description
PMP Endian modes
This enumeration holds the endian configuration options.
Members
Members Description
LITTLE Little Endian
BIG Big Endian
5.1.7.7.4.5 DRV_PMP_INDEX Enumeration
C
typedef enum {
DRV_PMP_INDEX_0,
DRV_PMP_INDEX_1
} DRV_PMP_INDEX;
Description
PMP Driver Module Index Numbers
These constants provide PMP driver index definitions.
Members
Members Description
DRV_PMP_INDEX_0 First PMP instance
DRV_PMP_INDEX_1 Second PMP instance (not avaialble for now)
Remarks
These values should be passed into the DRV_PMP_Initialize and DRV_PMP_Open functions to identify the driver instance in
use.
5.1.7.7.4.6 DRV_PMP_INIT Structure
C
typedef struct {
SYS_MODULE_INIT moduleInit;
PMP_MODULE_ID pmpID;
bool stopInIdle;
PMP_MUX_MODE muxMode;
PMP_INPUT_BUFFER_TYPE inputBuffer;
DRV_PMP_POLARITY_OBJECT polarity;
DRV_PMP_PORTS ports;
} DRV_PMP_INIT;
Description
PMP Driver Initialize Data
5.1 Driver Library Help MPLAB Harmony Help Parallel Master Port (PMP) Driver Library
5-389
This data type defines data required to initialize or reinitialize the PMP driver.
Members
Members Description
SYS_MODULE_INIT moduleInit; module power state info
PMP_MODULE_ID pmpID; module PLIB ID
bool stopInIdle; Stop in Idle enable
PMP_MUX_MODE muxMode; MUX mode
PMP_INPUT_BUFFER_TYPE inputBuffer; Input buffer type to be used
DRV_PMP_POLARITY_OBJECT polarity; Polarity settings
DRV_PMP_PORTS ports; PMP port settings
Remarks
Not all the initialization features are available for all devices.
5.1.7.7.4.7 DRV_PMP_MODE_CONFIG Structure
C
typedef struct {
PMP_OPERATION_MODE pmpMode;
PMP_INTERRUPT_MODE intMode;
PMP_INCREMENT_MODE incrementMode;
DRV_PMP_ENDIAN_MODE endianMode;
PMP_DATA_SIZE portSize;
DRV_PMP_WAIT_STATES waitStates;
PMP_CHIPSELECT_FUNCTION chipSelect;
} DRV_PMP_MODE_CONFIG;
Description
PMP modes configuration
This data type controls the configuration of PMP modes.
Members
Members Description
PMP_OPERATION_MODE pmpMode; PMP Usage Mode Type
PMP_INTERRUPT_MODE intMode; Interrupt mode
PMP_INCREMENT_MODE
incrementMode;
should be appropriately selected based on read/write requirements and operation
mode setting */ address/buffer increment mode
DRV_PMP_ENDIAN_MODE endianMode; it does not have any significance in PMP slave mode or 8bit data mode */ Endian
modes
PMP_DATA_SIZE portSize; Data Port Size
DRV_PMP_WAIT_STATES waitStates; Wait states
PMP_CHIPSELECT_FUNCTION
chipSelect;
use this when plib is fixed
5.1.7.7.4.8 DRV_PMP_POLARITY_OBJECT Structure
C
typedef struct {
PMP_POLARITY_LEVEL addressLatchPolarity;
PMP_POLARITY_LEVEL byteEnablePolarity;
PMP_POLARITY_LEVEL rwStrobePolarity;
PMP_POLARITY_LEVEL writeEnableStrobePolarity;
5.1 Driver Library Help MPLAB Harmony Help Parallel Master Port (PMP) Driver Library
5-390
PMP_POLARITY_LEVEL chipselect1Polarity;
PMP_POLARITY_LEVEL chipselect2Polarity;
} DRV_PMP_POLARITY_OBJECT;
Description
PMP polarity object
This structure holds the polarities of different entities to be configured.
Members
Members Description
PMP_POLARITY_LEVEL
addressLatchPolarity;
Address latch polarity
PMP_POLARITY_LEVEL
byteEnablePolarity;
ByteEnable port polarity
PMP_POLARITY_LEVEL rwStrobePolarity; Read/Write strobe polarity
PMP_POLARITY_LEVEL
writeEnableStrobePolarity;
Write/Enable strobe polarity
PMP_POLARITY_LEVEL
chipselect1Polarity;
ChipSelect-1 Polarity
PMP_POLARITY_LEVEL
chipselect2Polarity;
chipSelect-2 Polarity
5.1.7.7.4.9 DRV_PMP_PORT_CONTROL Enumeration
C
typedef enum {
PORT_ENABLE,
PORT_DISABLE
} DRV_PMP_PORT_CONTROL;
Description
PMP port enable/disable.
This enumeration provides port enable/disable values.
Members
Members Description
PORT_ENABLE Enable the given port
PORT_DISABLE Disable the given port
5.1.7.7.4.10 DRV_PMP_PORTS Structure
C
typedef struct {
PMP_ADDRESS_PORT addressPortsMask;
PMP_PMBE_PORT byteEnablePort;
DRV_PMP_PORT_CONTROL readWriteStrobe;
DRV_PMP_PORT_CONTROL writeEnableStrobe;
} DRV_PMP_PORTS;
Description
PMP Ports
This structure holds the ports (including the address ports) to be configured by the application to function as general purpose I/O
(GPIO) or part of the PMP.
5.1 Driver Library Help MPLAB Harmony Help Parallel Master Port (PMP) Driver Library
5-391
Members
Members Description
PMP_ADDRESS_PORT
addressPortsMask;
User needs to put the address lines which he wants to use in OR'd fashion */
Address ports
PMP_PMBE_PORT byteEnablePort; Byte enable ports
DRV_PMP_PORT_CONTROL
readWriteStrobe;
READ/WRITE Strobe PORT
DRV_PMP_PORT_CONTROL
writeEnableStrobe;
WRITE/ENABLE strobe port
5.1.7.7.4.11 DRV_PMP_QUEUE_ELEMENT_OBJ Type
C
typedef struct _DRV_PMP_QUEUE_ELEMENT_OBJ DRV_PMP_QUEUE_ELEMENT_OBJ;
Description
PMP Driver Queue Element Object
This defines the object structure for each queue element of PMP. This object gets created for every Read/Write operations APIs.
Remarks
None
5.1.7.7.4.12 DRV_PMP_TRANSFER_STATUS Enumeration
C
typedef enum {
MASTER_8BIT_TRANSFER_IN_PROGRESS = PMP_DATA_SIZE_8_BITS,
MASTER_16BIT_TRANSFER_IN_PROGRESS = PMP_DATA_SIZE_16_BITS,
MASTER_8BIT_BUFFER_IN_PROGRESS,
MASTER_16BIT_BUFFER_IN_PROGRESS,
MASTER_8BIT_BUFFER_CONTINUE,
QUEUED_BUT_PMP_TRANSFER_NOT_STARTED,
PMP_TRANSFER_FINISHED
} DRV_PMP_TRANSFER_STATUS;
Description
Queue Element Transfer Status
This enumeration defines the PMP transfer status.
5.1.7.7.4.13 DRV_PMP_WAIT_STATES Structure
C
typedef struct {
PMP_DATA_HOLD_STATES dataHoldWait;
PMP_STROBE_WAIT_STATES strobeWait;
PMP_DATA_WAIT_STATES dataWait;
} DRV_PMP_WAIT_STATES;
Description
PMP wait states object
This structure holds the different wait states to be configured. Refer to the PMP PLIB help document for the possible values and
meaning of the different wait states.
5.1 Driver Library Help MPLAB Harmony Help Parallel Master Port (PMP) Driver Library
5-392
Members
Members Description
PMP_DATA_HOLD_STATES
dataHoldWait;
data hold wait states
PMP_STROBE_WAIT_STATES
strobeWait;
read/write strobe wait states
PMP_DATA_WAIT_STATES dataWait; data wait strobe wait sates
5.1.7.7.4.14 QUEUE_ELEMENT_OBJECT Type
C
typedef struct _QUEUE_ELEMENT_OBJECT QUEUE_ELEMENT_OBJECT;
Description
Queue Element Object
This defines the structure required for maintaining the queue element.
Remarks
None
5.1.7.7.4.15 MAX_NONBUFFERED_BYTE_COUNT Macro
C
#define MAX_NONBUFFERED_BYTE_COUNT 4 //After this number the PMP transfer should be polled to
gurantee data trasnfer
Description
After this number the PMP transfer should be polled to gurantee data trasnfer
5.1.7.7.4.16 DRV_PMP_TRANSFER_TYPE Enumeration
C
typedef enum {
ADDRESS,
READ,
WRITE,
BUFFERED_WRITE
} DRV_PMP_TRANSFER_TYPE;
Description
This is type DRV_PMP_TRANSFER_TYPE.
Members
Members Description
ADDRESS PMP Address needs to be updated
READ PMP Read Transfer
WRITE PMP Write Transfer
BUFFERED_WRITE PMP Array Write Transfer
5.1.7.7.5 Miscellaneous Functions
5.1 Driver Library Help MPLAB Harmony Help Parallel Master Port (PMP) Driver Library
5-393
5.1.7.7.5.1 DRV_PMP_VersionGet Function
C
unsigned int DRV_PMP_VersionGet(
const SYS_MODULE_INDEX drvIndex
);
Description
This function gets the PMP driver version. The version is encoded as major * 10000 + minor * 100 + patch. The stringed version
can be obtained using DRV_PMP_VersionStrGet().
Preconditions
None.
Parameters
Parameters Description
drvIndex Identifier for the driver instance to get the version for
Returns
Current driver version in numerical format.
Remarks
None.
Example
unsigned int version;
version = DRV_PMP_VersionGet( DRV_PMP_INDEX_0 );
if(version < 110200)
{
// Do Something
}
5.1.7.7.5.2 DRV_PMP_VersionStrGet Function
C
char * DRV_PMP_VersionStrGet(
const SYS_MODULE_INDEX drvIndex
);
Description
This function gets the PMP driver version. The version is returned as major.minor.path[type], where type is optional. The
numerical version can be obtained using DRV_PMP_VersionGet().
Preconditions
None.
Parameters
Parameters Description
drvIndex Identifier for the driver instance to get the version for
Returns
Current PMP driver version in the string format.
5.1 Driver Library Help MPLAB Harmony Help Parallel Master Port (PMP) Driver Library
5-394
Remarks
None.
Example
char *version;
version = DRV_PMP_VersionStrGet( DRV_PMP_INDEX_0 );
printf("%s", version);
5.1.7.8 Files
Files
Name Description
drv_pmp.h Parallel Master Port (PMP) device driver interface file.
drv_pmp_config.h PMP driver configuration definitions template
Description
5.1.7.8.1 drv_pmp.h
PMP Device Driver Interface
The PMP device driver provides a simple interface to manage the Parallel Master and Slave ports. This file defines the interface
definitions and prototypes for the PMP driver.
Enumerations
Name Description
DRV_PMP_CHIPX_STROBE_MODE PMP writeEnable/ReadWrite strobes.
DRV_PMP_CLIENT_STATUS PMP client status definitions.
DRV_PMP_ENDIAN_MODE PMP endian modes.
DRV_PMP_INDEX PMP driver index definitions.
DRV_PMP_PORT_CONTROL PMP port enable/disable definitions.
DRV_PMP_TRANSFER_STATUS Defines the PMP transfer status.
DRV_PMP_TRANSFER_TYPE This is type DRV_PMP_TRANSFER_TYPE.
Functions
Name Description
DRV_PMP_ClientStatus Gets the current client-specific status of the PMP driver.
DRV_PMP_Close Closes an opened instance of the PMP driver.
DRV_PMP_Deinitialize Deinitializes the specified instance of the PMP driver module
DRV_PMP_Initialize Initializes the PMP driver.
DRV_PMP_ModeConfig Configure the PMP modes.
DRV_PMP_Open Opens the specified PMP driver instance and returns a handle to it.
DRV_PMP_Read Read the data from external device.
DRV_PMP_Reinitialize Reinitializes the driver and refreshes any associated hardware settings.
DRV_PMP_Status Provides the current status of the PMP driver module.
DRV_PMP_Tasks Maintains the driver's state machine and implements its ISR.
5.1 Driver Library Help MPLAB Harmony Help Parallel Master Port (PMP) Driver Library
5-395
DRV_PMP_TransferStatus Returns the transfer status.
DRV_PMP_VersionGet Gets the PMP driver version in numerical format.
DRV_PMP_VersionStrGet Gets the PMP driver version in string format.
DRV_PMP_Write Transfers the data from the MCU to the external device.
Macros
Name Description
DRV_PMP_INDEX_COUNT Number of valid PMP driver indices.
MAX_NONBUFFERED_BYTE_COUNT After this number the PMP transfer should be polled to gurantee data
trasnfer
Structures
Name Description
DRV_PMP_INIT Defines the PMP driver initialization data.
DRV_PMP_MODE_CONFIG PMP modes configuration.
DRV_PMP_POLARITY_OBJECT PMP polarity object.
DRV_PMP_PORTS PMP port configuration.
DRV_PMP_WAIT_STATES PMP wait states object.
Types
Name Description
DRV_PMP_QUEUE_ELEMENT_OBJ Defines the object for PMP queue element.
QUEUE_ELEMENT_OBJECT Defines the structure required for maintaining the queue element.
Company
Microchip Technology Inc.
FileName: drv_pmp.h
5.1.7.8.2 drv_pmp_config.h
PMP Driver Configuration Definitions for the Template Version
These definitions statically define the driver's mode of operation.
Macros
Name Description
DRV_PMP_CLIENTS_NUMBER Selects the maximum number of clients.
DRV_PMP_INSTANCES_NUMBER Selects the maximum number of hardware instances that can be supported
by the dynamic driver.
DRV_PMP_QUEUE_SIZE PMP queue size for different instances.
File Name
drv_pmp_config_template.h
Company
Microchip Technology Inc.
5.1 Driver Library Help MPLAB Harmony Help Secure Digital (SD) Card Driver Library
5-396
5.1.8 Secure Digital (SD) Card Driver Library
5.1.8.1 Introduction
Secure Digital (SD) Card Driver Library
for
Microchip Microcontrollers
The SD Card driver provides the necessary interfaces to interact with an SD card. It provides the necessary abstraction for the
higher layer.
Description
A SD Card is a non-volatile memory (Flash memory) card designed to provide high-capacity memory in a small size. Its
applications are like digital video camcorders, digital cameras, handheld computers, audio players and mobile phones.
5.1.8.2 Release Notes
MPLAB Harmony Version: v0.70b SD Card Library Version : Release Date: 18Nov2013
New This Release:
5.1 Driver Library Help MPLAB Harmony Help Secure Digital (SD) Card Driver Library
5-397
• Non-blocking operation
• Layered architecture
• Interoperability
Known Issues:
• Tested only with SDHC cards (Card memory more than 2 GB)
• CARD detection mechanism is not so fine-tuned
• Card maximum Frequency detection is not automatic. Different cards will have specific specific frequency of operation and
that needs to be set in system_config.h
• Not tested the drivers operation with multiple SD cards
• Timeout and driver reset on failure case is not implemented
5.1.8.3 SW License Agreement
(c) 2013 Microchip Technology Inc. Microchip licenses this software to you solely for use with Microchip products. The software
is owned by Microchip and its licensors, and is protected under applicable copyright laws. All rights reserved.
SOFTWARE IS PROVIDED "AS IS" MICROCHIP EXPRESSLY DISCLAIMS ANY WARRANTY OF ANY KIND, WHETHER
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL MICROCHIP BE LIABLE FOR
ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, HARM TO
YOUR EQUIPMENT, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS
BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR
CONTRIBUTION, OR OTHER SIMILAR COSTS.
To the fullest extent allowed by law, Microchip and its licensors liability shall not exceed the amount of fees, if any, that you have
paid directly to Microchip to use this software.
MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE TERMS.
5.1.8.4 Using the Library
This topic describes the basic architecture of the SD Card Driver Library and provides information and examples on how to use it.
Interface Header File: drv_sdcard.h
The interface to the SD Card Driver library is defined in the "drv _sdcard.h" header file. This file is included by the "drv.h" file. Any
C language source (.c) file that uses the SD Card Driver library should include "drv.h".
Library File:
The SD Card Driver library archive (.a) file installed with MPLAB Harmony.
Please refer to the MPLAB Harmony Overview for how the Driver interacts with the framework.
5.1.8.4.1 Abstraction Model
SD Card Driver Software Abstraction Block Diagram
5.1 Driver Library Help MPLAB Harmony Help Secure Digital (SD) Card Driver Library
5-398
• SD Card driver comes in the layer below the Partition Manager in MPLAB Harmony file system architecture.
• It uses the SPI driver to interact with SD card.
5.1.8.4.2 Library Overview
Refer to the section Driver Overview for how the driver operates in a system.
The library interface routines are divided into various sub-sections, each of sub-section addresses one of the blocks or the
overall operation of the SD Card module.
Library Interface Section Description
System Level Functions Includes functions for initialize the module.
Client Level Functions Functions to open and close a client.
Operation Functions Functions for read and write operations
Module Information Functions Functions for information about the module.
Version Information Functions Functions to get the software version.
5.1.8.4.3 How the Library Works
Note: Not all modes are available on all devices. Please refer to the specific device data sheet to determine the supported
modes.
5.1 Driver Library Help MPLAB Harmony Help Secure Digital (SD) Card Driver Library
5-399
5.1.8.5 Configuring the Library
The configuration of the SD Card driver is based on the file sys_config.h
This header file contains the configuration selection for the SD Card driver. Based on the selections made, the SD Card driver
will support or not support selected features. These configuration settings will apply to all instances of the SD Card.
This header can be placed anywhere; however, the path of this header needs to be present in the include search path for a
successful build. Refer to the Applications Overview section for more details.
5.1.8.6 Building the Library
This section list the files that are available in the \src of the SD Card driver. It lists which files need to be included in the build
based on either a hardware feature present on the board or configuration option selected by the system.
5.1.8.7 Library Interface
Data Types and Constants
Name Description
DRV_SDCARD_INDEX_0 SD Card driver index definitions
DRV_SDCARD_INDEX_COUNT Number of valid SD Card driver indices
DRV_SDCARD_BUFFER_HANDLE Handle to a buffer added to the process queue.
DRV_SDCARD_CLIENT_STATUS Identifies the client-specific status of the SD card driver
DRV_SDCARD_INIT Contains all the data necessary to initialize the SD Card device
SYS_MEDIA_EVENT Defines the buffer status
SDCARD_MAX_LIMIT Maximum allowed SD card instances
DRV_SDCARD_INDEX_1 This is macro DRV_SDCARD_INDEX_1.
DRV_SDCARD_INDEX_2 This is macro DRV_SDCARD_INDEX_2.
DRV_SDCARD_INDEX_3 This is macro DRV_SDCARD_INDEX_3.
Client Level Functions
Name Description
DRV_SDCARD_ClientStatus Gets current client-specific status the SD Card driver
DRV_SDCARD_Close Closes an opened-instance of the SD Card driver
DRV_SDCARD_Open Opens the specified SD Card driver instance and returns a handle to it
Module Information Functions
Name Description
DRV_SDCARD_SectorsCountGet Gets the number of sectors present in the selected SD card device.
DRV_SDCARD_SectorSizeGet Gets the sector size of the selected SD card device.
DRV_SDCARD_WriteProtectionIsEnabled Gets the status of write protection.
Operation Functions
Name Description
DRV_SDCARD_SectorRead Reads data from the sectors of the SD card.
DRV_SDCARD_SectorWrite Writes sector(s) of data to an SD card.
5.1 Driver Library Help MPLAB Harmony Help Secure Digital (SD) Card Driver Library
5-400
DRV_SDCARD_BufferStatusGet Gets the status of an an SD card operation (read/write)
DRV_SDCARD_MediaStatusGet Gets the status of the device.
System Level Functions
Name Description
DRV_SDCARD_Deinitialize Deinitializes the specified instance of the SD Card driver module
DRV_SDCARD_Initialize Initializes the SD Card driver
DRV_SDCARD_Reinitialize Reinitializes the driver and refreshes any associated hardware settings
DRV_SDCARD_Status Provides the current status of the SD Card driver module
DRV_SDCARD_Tasks Maintains the driver's state machine
Version Information Functions
Name Description
DRV_SDCARD_VersionGet Gets SD card driver version in numerical format.
DRV_SDCARD_VersionStrGet Gets SD card driver version in string format.
Description
This section describes the Application Programming Interface (API) functions of the SD Card Driver.
Refer to each section for a detailed description.
5.1.8.7.1 System Level Functions
5.1.8.7.1.1 DRV_SDCARD_Deinitialize Function
C
void DRV_SDCARD_Deinitialize(
SYS_MODULE_OBJ object
);
Description
Deinitializes the specified instance of the SD Card driver module, disabling its operation (and any hardware). Invalidates all the
internal data.
Preconditions
Function DRV_SDCARD_Initialize must have been called before calling this routine and a valid SYS_MODULE_OBJ must have
been returned.
Parameters
Parameters Description
object Driver object handle, returned from the DRV_SDCARD_Initialize routine.
Returns
None.
Remarks
Once the Initialize operation has been called, the Deinitialize operation must be called before the Initialize operation can be
called again.
This routine will NEVER block waiting for hardware. If the operation requires time to allow the hardware to complete, this will be
reported by the DRV_SDCARD_Status operation. The system has to use DRV_SDCARD_Status to find out when the module is
5.1 Driver Library Help MPLAB Harmony Help Secure Digital (SD) Card Driver Library
5-401
in the ready state.
Example
SYS_MODULE_OBJ object; // Returned from DRV_SDCARD_Initialize
SYS_STATUS status;
DRV_SDCARD_Deinitialize(object);
status = DRV_SDCARD_Status(object);
if (SYS_MODULE_UNINITIALIZED == status)
{
// Check again later if you need to know
// when the driver is deinitialized.
}
5.1.8.7.1.2 DRV_SDCARD_Initialize Function
C
SYS_MODULE_OBJ DRV_SDCARD_Initialize(
const SYS_MODULE_INDEX index,
const SYS_MODULE_INIT * const init
);
Description
This routine initializes the SD Card driver, making it ready for clients to open and use it.
Preconditions
None.
Parameters
Parameters Description
drvIndex Index for the driver instance to be initialized
init Pointer to a data structure containing any data necessary to initialize the driver.
This pointer may be null if no data is required because static overrides have been
provided.
Returns
If successful, returns a valid handle to a driver object. Otherwise, it returns SYS_MODULE_OBJ_INVALID. The returned object
must be passed as argument to DRV_SDCARD_Reinitialize, DRV_SDCARD_Deinitialize, DRV_SDCARD_TaskRead,
DRV_SDCARD_TaskWrite and DRV_SDCARD_Status routines.
Remarks
This routine must be called before any other SD Card routine is called.
This routine should only be called once during system initialization unless DRV_SDCARD_Deinitialize is called to de-initialize the
driver instance.
This routine will NEVER block for hardware access. If the operation requires time to allow the hardware to re-initialize, it will be
reported by the DRV_SDCARD_Status operation. The system must use DRV_SDCARD_Status to find out when the driver is in
the ready state.
Build configuration options may be used to statically override options in the "init" structure and will take precedence over
initialization data passed using this routine.
Example
DRV_SDCARD_INIT init;
SYS_MODULE_OBJ objectHandle;
5.1 Driver Library Help MPLAB Harmony Help Secure Digital (SD) Card Driver Library
5-402
// Populate the SD Card initialization structure
init.moduleInit.value = SYS_MODULE_POWER_RUN_FULL;
init.baudRate = 100000;
init.spiId = SPI_ID_1;
// Do something
objectHandle = DRV_SDCARD_Initialize(DRV_SDCARD_INDEX_0, (SYS_MODULE_INIT*)&init);
if (SYS_MODULE_OBJ_INVALID == objectHandle)
{
// Handle error
}
5.1.8.7.1.3 DRV_SDCARD_Reinitialize Function
C
void DRV_SDCARD_Reinitialize(
SYS_MODULE_OBJ object,
const SYS_MODULE_INIT * const init
);
Description
This routine reinitializes the driver and refreshes any associated hardware settings using the initialization data given, but it will
not interrupt any ongoing operations.
Preconditions
Function DRV_SDCARD_Initialize must have been called before calling this routine and a valid SYS_MODULE_OBJ must have
been returned.
Parameters
Parameters Description
object Driver object handle, returned from the DRV_SDCARD_Initialize routine
init Pointer to the initialization data structure
Returns
None
Remarks
This function can be called multiple times to reinitialize the module.
This operation can be used to refresh any supported hardware registers as specified by the initialization data or to change the
power state of the module.
This routine will NEVER block for hardware access. If the operation requires time to allow the hardware to re-initialize, it will be
reported by the DRV_SDCARD_Status operation. The system must use DRV_SDCARD_Status to find out when the driver is in
the ready state.
Build configuration options may be used to statically override options in the "init" structure and will take precedence over
initialization data passed using this routine.
Example
DRV_SDCARD_INIT init;
SYS_MODULE_OBJ objectHandle;
// Populate the SD Card initialization structure
init.moduleInit.value = SYS_MODULE_POWER_RUN_FULL;
init.baudRate = 100000;
init.spiId = SPI_ID_1;
5.1 Driver Library Help MPLAB Harmony Help Secure Digital (SD) Card Driver Library
5-403
// Do something
5.1.8.7.1.4 DRV_SDCARD_Status Function
C
SYS_STATUS DRV_SDCARD_Status(
SYS_MODULE_OBJ object
);
Description
This routine provides the current status of the SD Card driver module.
Preconditions
Function DRV_SDCARD_Initialize must have been called before calling this
Parameters
Parameters Description
object Driver object handle, returned from the DRV_SDCARD_Initialize routine
Returns
SYS_STATUS_READY - Indicates that the driver is busy with a previous system level operation and cannot start another
Note Any value greater than SYS_STATUS_READY is also a normal running state in which the driver is ready to accept new
operations.
SYS_STATUS_BUSY - Indicates that the driver is busy with a previous system level operation and cannot start another
SYS_STATUS_ERROR - Indicates that the driver is in an error state
Remarks
Any value less than SYS_STATUS_ERROR is also an error state.
SYS_MODULE_DEINITIALIZED - Indicates that the driver has been de-initialized
This value is less than SYS_STATUS_ERROR
The this operation can be used to determine when any of the driver's module level operations has completed.
If the status operation returns SYS_STATUS_BUSY, the a previous operation has not yet completed. Once the status operation
returns SYS_STATUS_READY, any previous operations have completed.
The value of SYS_STATUS_ERROR is negative (-1). Any value less than that is also an error state.
This routine will NEVER block waiting for hardware.
If the Status operation returns an error value, the error may be cleared by calling the reinitialize operation. If that fails, the
deinitialize operation will need to be called, followed by the initialize operation to return to normal operations.
Example
SYS_MODULE_OBJ object; // Returned from DRV_SDCARD_Initialize
SYS_STATUS status;
status = DRV_SDCARD_Status(object);
else if (SYS_STATUS_ERROR >= status)
{
// Handle error
}
5.1 Driver Library Help MPLAB Harmony Help Secure Digital (SD) Card Driver Library
5-404
5.1.8.7.1.5 DRV_SDCARD_Tasks Function
C
void DRV_SDCARD_Tasks(
SYS_MODULE_OBJ object
);
Description
This routine is used to maintain the driver's internal state machine.
Preconditions
The DRV_SDCARD_Initialize routine must have been called for the specified SDCARD driver instance.
Parameters
Parameters Description
object Object handle for the specified driver instance (returned from
DRV_SDCARD_Initialize)
Returns
None
Remarks
This routine is normally not called directly by an application. It is called by the system's Tasks routine (SYS_Tasks) or by the
appropriate raw ISR.
This routine may execute in an ISR context and will never block or access any resources that may cause it to block.
Example
SYS_MODULE_OBJ object; // Returned from DRV_SDCARD_Initialize
while (true)
{
DRV_SDCARD_Tasks (object);
// Do other tasks
}
5.1.8.7.2 Client Level Functions
5.1.8.7.2.1 DRV_SDCARD_ClientStatus Function
C
DRV_SDCARD_CLIENT_STATUS DRV_SDCARD_ClientStatus(
DRV_HANDLE handle
);
Description
This routine gets the client-specific status of the SD Card driver associated with the given handle.
Preconditions
The DRV_SDCARD_Initialize routine must have been called.
DRV_SDCARD_Open must have been called to obtain a valid opened device handle.
5.1 Driver Library Help MPLAB Harmony Help Secure Digital (SD) Card Driver Library
5-405
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open routine
Returns
A DRV_SDCARD_CLIENT_STATUS value describing the current status of the driver
Remarks
This routine will not block for hardware access and will immediately return the current status.
Example
DRV_HANDLE sdcardHandle; // Returned from DRV_SDCARD_Open
DRV_SDCARD_CLIENT_STATUS sdcardClientStatus;
sdcardClientStatus = DRV_SDCARD_ClientStatus ( sdcardHandle );
if ( DRV_SDCARD_CLIENT_STATUS_ERROR >= sdcardClientStatus )
{
// Handle the error
}
5.1.8.7.2.2 DRV_SDCARD_Close Function
C
void DRV_SDCARD_Close(
DRV_HANDLE handle
);
Description
This routine closes an opened-instance of the SD Card driver, invalidating the handle.
Preconditions
The DRV_SDCARD_Initialize routine must have been called for the specified SD Card driver instance.
DRV_SDCARD_Open must have been called to obtain a valid opened device handle.
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open routine
Returns
None
Remarks
After calling this routine, the handle passed in "handle" must not be used with any of the remaining driver routines. A new handle
must be obtained by calling DRV_SDCARD_Open before the caller may use the driver again.
If DRV_IO_INTENT_BLOCKING was requested and the driver was built appropriately to support blocking behavior call may
block until the operation is complete.
If DRV_IO_INTENT_NON_BLOCKING request the driver client can call the DRV_SDCARD_Status operation to find out when
the module is in the ready state (the handle is no longer valid).
Usually there is no need for the driver client to verify that the Close operation has completed.
Example
DRV_HANDLE handle; // Returned from DRV_SDCARD_Open
5.1 Driver Library Help MPLAB Harmony Help Secure Digital (SD) Card Driver Library
5-406
DRV_SDCARD_Close ( handle );
5.1.8.7.2.3 DRV_SDCARD_Open Function
C
DRV_HANDLE DRV_SDCARD_Open(
const SYS_MODULE_INDEX drvIndex,
const DRV_IO_INTENT intent
);
Description
This routine opens the specified SD Card driver instance and provides a handle that must be provided to all other client-level
operations to identify the caller and the instance of the driver.
Preconditions
Function DRV_SDCARD_Initialize must have been called before calling this function.
Parameters
Parameters Description
drvIndex Identifier for the object instance to be opened
intent Zero or more of the values from the enumeration DRV_IO_INTENT "or'd" together
to indicate the intended use of the driver
Returns
If successful, the routine returns a valid open-instance handle (a number identifying both the caller and the module instance).
If an error occurs, the return value is DRV_HANDLE_INVALID.
Remarks
The handle returned is valid until the DRV_SDCARD_Close routine is called.
This routine will NEVER block waiting for hardware.
If the DRV_IO_INTENT_BLOCKING is requested and the driver was built appropriately to support blocking behavior, then other
client-level operations may block waiting on hardware until they are complete.
If DRV_IO_INTENT_NON_BLOCKING is requested the driver client can call the DRV_SDCARD_ClientStatus operation to find
out when the module is in the ready state.
If the requested intent flags are not supported, the routine will return DRV_HANDLE_INVALID.
Example
DRV_HANDLE handle;
handle = DRV_SDCARD_Open ( DRV_SDCARD_INDEX_0, DRV_IO_INTENT_EXCLUSIVE );
if ( DRV_HANDLE_INVALID == handle )
{
// Unable to open the driver
}
5.1.8.7.3 Operation Functions
5.1.8.7.3.1 DRV_SDCARD_SectorRead Function
C
SYS_FS_MEDIA_BUFFER_HANDLE DRV_SDCARD_SectorRead(
5.1 Driver Library Help MPLAB Harmony Help Secure Digital (SD) Card Driver Library
5-407
DRV_HANDLE handle,
uint8_t * buffer,
uint32_t sector_addr,
uint32_t sectorCount
);
Description
This function reads data from the sectors of the SD card starting from the sector address and stores it in the location pointed by
'buffer'.
Preconditions
The DRV_SDCARD_Initialize routine must have been called.
DRV_SDCARD_Open must have been called to obtain a valid opened device handle.
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open routine
sector_addr The address of the sector on the card.
sectorCount Number of sectors to be read.
buffer The buffer where the retrieved data will be stored. If buffer is NULL, do not store
the data anywhere.
Returns
SYS_FS_MEDIA_BUFFER_HANDLE - Buffer handle.
Remarks
This routine will not block for hardware access and will immediately return the current status.
Example
SYS_FS_MEDIA_BUFFER_HANDLE bufferHandle;
bufferHandle = DRV_SDCARD_SectorRead ( handle,
,readData //buffer
, 20 // Sector
, 1 // Number of Sectors
);
5.1.8.7.3.2 DRV_SDCARD_SectorWrite Function
C
SYS_FS_MEDIA_BUFFER_HANDLE DRV_SDCARD_SectorWrite(
DRV_HANDLE handle,
uint32_t sector_addr,
uint8_t * buffer,
uint32_t sectorCount
);
Description
This function writes sector(s) of data (512 bytes) of data from the location pointed to by 'buffer' to the specified sector of the SD
card.
Preconditions
The DRV_SDCARD_Initialize routine must have been called.
DRV_SDCARD_Open must have been called to obtain a valid opened device handle.
5.1 Driver Library Help MPLAB Harmony Help Secure Digital (SD) Card Driver Library
5-408
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open routine
sector_addr The address of the sector on the card.
buffer The buffer with the data to write.
Returns
SYS_FS_MEDIA_BUFFER_HANDLE - Buffer handle.
Remarks
The card expects the address field in the command packet to be a byte address. The sector_addr value is converted to a byte
address by shifting it left nine times (multiplying by 512).
Example
SYS_FS_MEDIA_BUFFER_HANDLE bufferHandle;
bufferHandle = DRV_SDCARD_SectorWrite ( handle,
,readData //buffer
, 20 // Sector
, 1 // Number of Sectors
);
5.1.8.7.3.3 DRV_SDCARD_BufferStatusGet Function
C
SYS_FS_MEDIA_BUFFER_STATUS DRV_SDCARD_BufferStatusGet(
DRV_HANDLE handle,
SYS_FS_MEDIA_BUFFER_HANDLE bufferHandle
);
Description
This function gets the status of an an SD card operation (read/write). To be called only after a read or write is scheduled.
Preconditions
The DRV_SDCARD_Initialize routine must have been called.
DRV_SDCARD_Open must have been called to obtain a valid opened device handle.
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open routine
bufferHandle Handle returned by a 'sector write' or a 'sector read' function.
Returns
SYS_FS_MEDIA_BUFFER_STATUS - Buffer status.
Remarks
None.
Example
int globalState = 0;
SYS_FS_MEDIA_BUFFER_HANDLE bufferHandle;
switch (globalState)
{
case 0:
5.1 Driver Library Help MPLAB Harmony Help Secure Digital (SD) Card Driver Library
5-409
bufferHandle = SYS_FS_MEDIA_MANAGER_SectorWrite ( handle,
,readData //buffer
, 20 // Sector
, 1 // Number of Sectors
);
globalState++;
break;
case 1:
if ( SYS_FS_MEDIA_MANAGER_BufferStatusGet(handle, bufferHandle) ==
SYS_FS_MEDIA_BUFFER_COMPLETED)
{
//Write complete
}
break;
5.1.8.7.3.4 DRV_SDCARD_MediaStatusGet Function
C
SYS_FS_MEDIA_STATUS DRV_SDCARD_MediaStatusGet(
DRV_HANDLE handle
);
Description
This function gets the status of the device ( attached/detached ).
Preconditions
The DRV_SDCARD_Initialize routine must have been called.
DRV_SDCARD_Open must have been called to obtain a valid opened device handle.
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open routine
Returns
SYS_FS_MEDIA_STATUS - Status of the device.
Remarks
None.
Example
DRV_HANDLE sdcardHandle; // Returned from DRV_SDCARD_Open
if( DRV_SDCARD_MediaStatusGet ( handle ) == SYS_FS_MEDIA_ATTACHED )
{
//Device is attached
}
5.1.8.7.4 Module Information Functions
5.1.8.7.4.1 DRV_SDCARD_SectorsCountGet Function
C
uint32_t DRV_SDCARD_SectorsCountGet(
DRV_HANDLE handle
);
5.1 Driver Library Help MPLAB Harmony Help Secure Digital (SD) Card Driver Library
5-410
Description
This function gets the number of sectors present in the selected SD card device.
Preconditions
The DRV_SDCARD_Initialize routine must have been called.
DRV_SDCARD_Open must have been called to obtain a valid opened device handle.
SD Card must have been detected and initialized by the task routine.
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open routine
Returns
The number of a sectors in the selected SD Card.
Remarks
This routine will not block for hardware access and will immediately return the current status.
Example
DRV_HANDLE sdcardHandle; // Returned from DRV_SDCARD_Open
DRV_SDCARD_CLIENT_STATUS sdcardClientStatus;
bool status;
5.1.8.7.4.2 DRV_SDCARD_SectorSizeGet Function
C
uint32_t DRV_SDCARD_SectorSizeGet(
DRV_HANDLE handle
);
Description
This function gets the card's sector size.
Preconditions
The DRV_SDCARD_Initialize routine must have been called.
DRV_SDCARD_Open must have been called to obtain a valid opened device handle.
SD Card must have been detected and initialized by the task routine.
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open routine
Returns
The size of a sector in the selected SD Card.
Remarks
This routine will not block for hardware access and will immediately return the current status.
Example
DRV_HANDLE sdcardHandle; // Returned from DRV_SDCARD_Open
DRV_SDCARD_CLIENT_STATUS sdcardClientStatus;
bool status;
5.1 Driver Library Help MPLAB Harmony Help Secure Digital (SD) Card Driver Library
5-411
5.1.8.7.4.3 DRV_SDCARD_WriteProtectionIsEnabled Function
C
bool DRV_SDCARD_WriteProtectionIsEnabled(
DRV_HANDLE handle
);
Description
This function returns 'true' if the write protection for the card is enabled.
Preconditions
The DRV_SDCARD_Initialize routine must have been called.
DRV_SDCARD_Open must have been called to obtain a valid opened device handle.
SD Card must have been detected and initialized by the task routine.
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open routine
Returns
true - Write protection is enabled. false - Write protection is disabled.
Remarks
This routine will not block for hardware access and will immediately return the current status.
Example
DRV_HANDLE sdcardHandle; // Returned from DRV_SDCARD_Open
bool writeProtectStatus;
//Call DRV_SDCARD_Open
writeProtectStatus = DRV_SDCARD_WriteProtectionIsEnabled(sdcardHandle);
5.1.8.7.5 Version Information Functions
5.1.8.7.5.1 DRV_SDCARD_VersionGet Function
C
unsigned int DRV_SDCARD_VersionGet(
const SYS_MODULE_INDEX drvIndex
);
Description
This routine gets the SD card driver version. The version is encoded as major * 10000 + minor * 100 + patch. The stringized
version can be obtained using DRV_SDCARD_VersionStrGet()
Preconditions
None.
Parameters
Parameters Description
drvIndex Identifier for the object instance to get the version for.
5.1 Driver Library Help MPLAB Harmony Help Secure Digital (SD) Card Driver Library
5-412
Returns
Current driver version in numerical format.
Remarks
None.
Example
unsigned int version;
version = DRV_SDCARD_VersionGet( DRV_SDCARD_INDEX_1 );
if(version < 110200)
{
// Do Something
}
5.1.8.7.5.2 DRV_SDCARD_VersionStrGet Function
C
char* DRV_SDCARD_VersionStrGet(
const SYS_MODULE_INDEX drvIndex
);
Description
This routine gets the SD card driver version. The version is returned as major.minor.path[type], where type is optional. The
numerical version can be obtained using DRV_SDCARD_VersionGet()
Preconditions
None.
Parameters
Parameters Description
drvIndex Identifier for the object instance to get the version for.
Returns
Current SD card driver version in the string format.
Remarks
None.
Example
char *version;
version = DRV_SDCARD_VersionStrGet( DRV_SDCARD_INDEX_1 );
printf("%s", version);
5.1.8.7.6 Data Types and Constants
5.1.8.7.6.1 DRV_SDCARD_INDEX_0 Macro
C
#define DRV_SDCARD_INDEX_0 0
5.1 Driver Library Help MPLAB Harmony Help Secure Digital (SD) Card Driver Library
5-413
Description
SD Card Driver Module Index Numbers
These constants provide SD Card driver index definitions.
Remarks
These constants should be used in place of hard-coded numeric literals.
These values should be passed into the DRV_SDCARD_Initialize and DRV_SDCARD_Open routines to identify the driver
instance in use.
5.1.8.7.6.2 DRV_SDCARD_INDEX_COUNT Macro
C
#define DRV_SDCARD_INDEX_COUNT DRV_SDCARD_INDEX_MAX
Description
SD Card Driver Module Index Count
This constant identifies number of valid SD Card driver indices.
Remarks
This constant should be used in place of hard-coded numeric literals.
This value is derived from part-specific header files defined as part of the peripheral libraries.
5.1.8.7.6.3 DRV_SDCARD_BUFFER_HANDLE Type
C
typedef uintptr_t DRV_SDCARD_BUFFER_HANDLE;
Description
SD Card Buffer Handle
This handle identifies the a buffer in the queue(read or write).
5.1.8.7.6.4 DRV_SDCARD_CLIENT_STATUS Enumeration
C
typedef enum {
DRV_SDCARD_CLIENT_STATUS_INVALID,
DRV_SDCARD_CLIENT_STATUS_ERROR,
DRV_SDCARD_CLIENT_STATUS_CLOSED,
DRV_SDCARD_CLIENT_STATUS_BUSY,
DRV_SDCARD_CLIENT_STATUS_READY,
DRV_SDCARD_CLIENT_STATUS_STOPPED
} DRV_SDCARD_CLIENT_STATUS;
Description
SD Card Driver Client Status
This enumeration identifies the client-specific status of the SD card driver.
Members
Members Description
DRV_SDCARD_CLIENT_STATUS_INVALID Client in an invalid state
5.1 Driver Library Help MPLAB Harmony Help Secure Digital (SD) Card Driver Library
5-414
DRV_SDCARD_CLIENT_STATUS_ERROR Unspecified error condition
DRV_SDCARD_CLIENT_STATUS_CLOSED Client is not open
DRV_SDCARD_CLIENT_STATUS_BUSY An operation is currently in progress
DRV_SDCARD_CLIENT_STATUS_READY Up and running, no operations running
DRV_SDCARD_CLIENT_STATUS_STOPPED SD Card stopped (not running), but ready to accept commands
Remarks
None.
5.1.8.7.6.5 DRV_SDCARD_INIT Type
C
typedef struct _DRV_SDCARD_INIT DRV_SDCARD_INIT;
Description
SD Card Device Driver Initialization Data
This structure contains all the data necessary to initialize the SD Card device.
Remarks
A pointer to a structure of this format containing the desired initialization data must be passed into the DRV_SDCARD_Initialize
routine.
5.1.8.7.6.6 SYS_MEDIA_EVENT Enumeration
C
typedef enum {
SYS_MEDIA_EVENT_SDCARD_ATTACHED,
SYS_MEDIA_EVENT_SDCARD_DETACHED
} SYS_MEDIA_EVENT;
Description
SD Card Buffer Status
Defines the states that an SD Card buffer can be in during its lifetime
Members
Members Description
SYS_MEDIA_EVENT_SDCARD_ATTACHED The media event is SD Card attach
SYS_MEDIA_EVENT_SDCARD_DETACHED The media event is SD Card detach
Remarks
As buffers may have a limited life span, so too have the associated handles and status info. Once a buffer transfer is completed
(and possibly notified and acknowledged) it will be discarded. The status of a discarded buffer is no longer maintained by the
driver.
5.1.8.7.6.7 SDCARD_MAX_LIMIT Macro
C
#define SDCARD_MAX_LIMIT 2
Description
SD Card Driver Maximum allowed limit
5.1 Driver Library Help MPLAB Harmony Help Secure Digital (SD) Card Driver Library
5-415
This constant identifies number of valid SD Card driver indices.
Remarks
This constant should be used in place of hard-coded numeric literals.
This value is derived from part-specific header files defined as part of the peripheral libraries.
5.1.8.7.6.8 DRV_SDCARD_INDEX_1 Macro
C
#define DRV_SDCARD_INDEX_1 1
Description
This is macro DRV_SDCARD_INDEX_1.
5.1.8.7.6.9 DRV_SDCARD_INDEX_2 Macro
C
#define DRV_SDCARD_INDEX_2 2
Description
This is macro DRV_SDCARD_INDEX_2.
5.1.8.7.6.10 DRV_SDCARD_INDEX_3 Macro
C
#define DRV_SDCARD_INDEX_3 3
Description
This is macro DRV_SDCARD_INDEX_3.
5.1.8.8 Files
Files
Name Description
drv_sdcard.h SD Card Device Driver Interface File
Description
5.1.8.8.1 drv_sdcard.h
SD Card Device Driver Interface
The SD Card device driver provides a simple interface to manage the "SD Card" peripheral. This file defines the interface
definitions and prototypes for the SD Card driver.
Enumerations
Name Description
DRV_SDCARD_CLIENT_STATUS Identifies the client-specific status of the SD card driver
SYS_MEDIA_EVENT Defines the buffer status
5.1 Driver Library Help MPLAB Harmony Help Secure Digital (SD) Card Driver Library
5-416
Functions
Name Description
DRV_SDCARD_BufferStatusGet Gets the status of an an SD card operation (read/write)
DRV_SDCARD_ClientStatus Gets current client-specific status the SD Card driver
DRV_SDCARD_Close Closes an opened-instance of the SD Card driver
DRV_SDCARD_Deinitialize Deinitializes the specified instance of the SD Card driver module
DRV_SDCARD_Initialize Initializes the SD Card driver
DRV_SDCARD_MediaStatusGet Gets the status of the device.
DRV_SDCARD_Open Opens the specified SD Card driver instance and returns a handle to it
DRV_SDCARD_Reinitialize Reinitializes the driver and refreshes any associated hardware settings
DRV_SDCARD_SectorRead Reads data from the sectors of the SD card.
DRV_SDCARD_SectorsCountGet Gets the number of sectors present in the selected SD card device.
DRV_SDCARD_SectorSizeGet Gets the sector size of the selected SD card device.
DRV_SDCARD_SectorWrite Writes sector(s) of data to an SD card.
DRV_SDCARD_Status Provides the current status of the SD Card driver module
DRV_SDCARD_Tasks Maintains the driver's state machine
DRV_SDCARD_VersionGet Gets SD card driver version in numerical format.
DRV_SDCARD_VersionStrGet Gets SD card driver version in string format.
DRV_SDCARD_WriteProtectionIsEnabled Gets the status of write protection.
Macros
Name Description
DRV_SDCARD_INDEX_0 SD Card driver index definitions
DRV_SDCARD_INDEX_1 This is macro DRV_SDCARD_INDEX_1.
DRV_SDCARD_INDEX_2 This is macro DRV_SDCARD_INDEX_2.
DRV_SDCARD_INDEX_3 This is macro DRV_SDCARD_INDEX_3.
DRV_SDCARD_INDEX_COUNT Number of valid SD Card driver indices
SDCARD_MAX_LIMIT Maximum allowed SD card instances
Types
Name Description
DRV_SDCARD_BUFFER_HANDLE Handle to a buffer added to the process queue.
DRV_SDCARD_INIT Contains all the data necessary to initialize the SD Card device
Company
Microchip Technology Incorporated
FileName: drv_sdcard.h
5.1.9 SPI Driver Library
5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library
5-417
5.1.9.1 Introduction
SPI Driver Library
for
Microchip Microcontrollers
This library provides an interface to manage the Serial Peripheral Interface (SPI) module on the Microchip family of
microcontrollers in different modes of operation.
Description
Overview
The SPI module is a full duplex synchronous serial interface useful for communicating with other peripherals or microcontrollers
in master/slave relationship and it can transfer data over short distances at high speeds. The peripheral devices may be serial
EEPROMs, shift registers, display drivers, analog-to-digital converters, etc. The SPI module is compatible with Motorola’s SPI
and SIOP interfaces.
During data transfer devices can work either in master or in Slave mode. The source of synchronization is the system clock,
which is generated by the master. The SPI module allows to connect one or more slave devices to a single master device via the
same bus.
The SPI serial interface consists of four pins, which are further sub-divided into data and control lines:
Data lines:
• MOSI – Master Data Output, Slave Data Input
• MISO – Master Data Input, Slave Data Output
Control lines:
• SCLK – Serial Clock
• /SS – Slave Select (no addressing)
SPI Master-Slave Relationship
The SPI module can be configured to operate using 2, 3 or 4 pins. In the 3-pin mode, slave select line is not used. In the 2-pin
mode, both MOSI and SS lines are not used.
5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library
5-418
Note: Third-party trademarks are property of their respective owners.
5.1.9.2 Release Notes
MPLAB Harmony Version: v0.70b SPI Driver Library Version : 0.01 Release Date: 18Nov2013
New This Release:
• Configurable baud rate at client level
• Interoperability
Known Issues:
• Does not work in the Slave mode of operation
• DMA is not supported
5.1.9.3 SW License Agreement
(c) 2013 Microchip Technology Inc.
Microchip licenses this software to you solely for use with Microchip products. The software is owned by Microchip and its
licensors, and is protected under applicable copyright laws. All rights reserved.
SOFTWARE IS PROVIDED AS IS MICROCHIP EXPRESSLY DISCLAIMS ANY WARRANTY OF ANY KIND, WHETHER
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL MICROCHIP BE LIABLE FOR
ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, HARM TO
YOUR EQUIPMENT, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS
BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR
CONTRIBUTION, OR OTHER SIMILAR COSTS.
To the fullest extent allowed by law, Microchip and its licensors liability shall not exceed the amount of fees, if any, that you have
paid directly to Microchip to use this software.
MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE TERMS.
5.1.9.4 Using the Library
This topic describes the basic architecture of the SPI Driver Library and provides information and examples on how to use it.
Interface Header File: drv_spi.h
The interface to the SPI Driver library is defined in the "drv_spi.h" header file. Any C language source (.c) file that uses the SPI
Driver library should include this header.
Library File:
The SPI Driver library archive (.a) file installed with MPLAB Harmony.
Please refer to the MPLAB Harmony Overview for how the Driver interacts with the framework.
5.1.9.4.1 Abstraction Model
Different types of SPIs are available on Microchip microcontrollers. Some have an internal buffer mechanism and some do not.
5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library
5-419
The buffer depth varies across part families. The SPI driver abstracts out these differences and provides a unified model for data
transfer across different types of SPIs available.
Both transmitter and receiver provides a buffer in the driver which transmits and receives data to/from the hardware. The SPI
driver provides a set of interfaces to perform the read and the write.
The diagrams below illustrates the model used by the SPI driver for transmitter and receiver.
Receiver Abstraction Model
Transmitter Abstraction Model
5.1.9.4.2 Library Overview
Refer to the section Driver Overview for how the driver operates in a system.
The library interface routines are divided into various subsections, each of the sub section addresses one of the blocks or the
overall operation of the SPI module.
Library Interface Section Description
System Interaction Functions Provides system module interfaces, device initialization, deinitialization,
reinitialization, tasks and status functions.
Client Setup Functions Provides open, close, status and other setup functions.
Chip Selects Provides chip select functions available in the configuration.
Client Data Transfer - Core Provides core data transfer functions available in the configuration.
[Standard/Single buffer transfer]
5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library
5-420
Client Data Transfer - Advanced Provides advanced data transfer functions available in the configuration.
[Enhanced/Multi buffer transfers]
Miscellaneous Provides driver miscellaneous functions, data transfer status function,
version identification functions etc.
5.1.9.4.3 How the Library Works
The library provides interfaces to support:
• System Functionality
• Client Functionality
Note: Not all modes are available on all microcontrollers, please refer to the specific device data sheet to the modes that are
supported for your device.
5.1.9.4.3.1 System Access
System Initialization and Re-initialization
The system performs the initialization and the re-initialization of the device driver with settings that affect only the instance of the
device that is being initialized or re-initialized. During system initialization each instance of the SPI module would be initialized
with the following configuration settings (either passed dynamically at run time using DRV_SPI_INIT or by using Initialization
Overrides) that are supported by the specific SPI device hardware:
• Device requested power state: one of the System Module Power States. For specific details please refer to the Data Types
section in this guide
• The actual peripheral ID enumerated as the PLIB level module ID. e.g SPI_ID_2.
• Defining the respective interrupt sources for Tx, Rx, and Error Interrupt.
The DRV_SPI_Initialize API returns an object handle of the type SYS_MODULE_OBJ. There on, the object handle returned by
the Initialize interface would be used by the other system interfaces like DRV_SPI_Reinitialize, DRV_SPI_Deinitialize,
DRV_SPI_Status and DRV_SPI_Tasks.
Note:The system initialization and the re-initialization settings, only effect the instance of the peripheral that is being initialized or
re-initialized.
Example:
DRV_SPI_INIT spiInitData;
SYS_MODULE_OBJ objectHandle;
spiInitData.moduleInit.value = SYS_MODULE_POWER_RUN_FULL;
spiInitData.spiId = SPI_ID_1;
spiInitData.spiMode = DRV_SPI_MODE_MASTER;
spiInitData.spiProtocolType = DRV_SPI_PROTOCOL_TYPE_STANDARD;
spiInitData.commWidth = SPI_COMMUNICATION_8BIT_WIDE;
spiInitData.baudRate = 5000;
spiInitData.bufferType = DRV_SPI_BUFFER_TYPE_STANDARD;
spiInitData.inputSamplePhase = SPI_INPUT_SAMPLING_PHASE_IN_MIDDLE;
spiInitData.clockMode = DRV_SPI_CLOCK_MODE_IDLE_LOW_EDGE_RISE;
spiInitData.txInterruptSource = INT_SOURCE_SPI_1_TRANSMIT; // INT_SOURCE_SPI_1_EVENT
spiInitData.rxInterruptSource = INT_SOURCE_SPI_1_RECEIVE; // INT_SOURCE_SPI_1_EVENT
spiInitData.errInterruptSource = INT_SOURCE_SPI_1_ERROR;
spiInitData.pinConfig.sdiPin = PIN_6; // RPI38
spiInitData.pinConfig.sdoPin = PIN_10; // RP21
spiInitData.pinConfig.sckPin = PIN_11; // RP26
objectHandle = DRV_SPI_Initialize(DRV_SPI_INDEX_1, (SYS_MODULE_INIT*)&spiInitData);
5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library
5-421
if (SYS_MODULE_OBJ_INVALID == objectHandle)
{
// Handle error
}
Tasks Routine
The system will either call DRV_SPI_Tasks, from System Task Service (in a polled environment) or DRV_SPI_Tasks will be
called from interrupt service routine of the SPI.
5.1.9.4.3.2 Client Access
General Client Operation
For the application to start using an instance of the module, it must call the DRV_SPI_Open function. This provides the
configuration required to open the SPI instance for operation. If the driver is de-initialized using the function
DRV_SPI_Deinitialize, the application must call the DRV_SPI_Open function again to setup the instance of the SPI. The function
DRV_SPI_Open need not be called again if the system is re-initialized using the DRV_SPI_Reinitialize function.
For the various options available for IO INTENT please refer to the Data Types section in this guide.
Example:
DRV_HANDLE handle;
// Configure the instance DRV_SPI_INDEX_1 with the configuration
handle = DRV_SPI_Open(DRV_SPI_INDEX_1, DRV_IO_INTENT_READWRITE);
if(handle == DRV_HANDLE_INVALID)
{
// Client cannot open the instance.
}
Communication Setup:
Communication entities like the SPI modes, input clock frequency, baud rates, clock mode, ports setup etc. can be configured
with the help of the driver function DRV_SPI_CommunicationSetup. This is a mandatory setup before doing any data transfer.
The callback function registered during the communication setup gets called after a successful data transfer.
Example:
DRV_HANDLE handle; // Returned from DRV_SPI_Open
DRV_SPI_COMM_CONFIG config;
// Populate the communication setup configuration structure
config.spiMode = DRV_SPI_MODE_MASTER;
config.baudRate = 5000;
config.inputSamplePhase = SPI_INPUT_SAMPLING_PHASE_IN_MIDDLE;
config.clockMode = DRV_SPI_CLOCK_MODE_IDLE_LOW_EDGE_RISE;
config.callback = &callBackFunction; // callback registered
DRV_SPI_CommunicationSetup( handle, &config );
Chip Select Control:
User can control the chip/slave select signals using the driver APIs DRV_SPI_ChipSelectActivate and
DRV_SPI_ChipSelectDeactivate with appropriate parameters.
Example:
// Activates/Enables Slave Select connected to Port A, bit 1
DRV_SPI_ChipSelectActivate( handle, PORT_CHANNEL_A, PORTS_BIT_POS_1 );
...
...
...
// Deactivates/Disables Slave Select connected to Port A, bit 1
5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library
5-422
DRV_SPI_ChipSelectDeactivate( handle, PORT_CHANNEL_A, PORTS_BIT_POS_1 );
5.1.9.4.3.3 Cient Transfer - Core
Client basic functionality provides a extremely basic interface for the driver operation.
This client transfer mechanism needs to be used for the devices which support the
'Standard' SPI mode of operation [Single Buffer]. This mechanism needs to be repeated in case of buffer
based data transfers for transferring multi bytes/words.
The diagram below illustrates the byte/word model used for the data transfer.
Note: It is not necessary to close and re-open the client between multiple transfers.
Client Byte/Word transfer Functionality
Application using the SPI byte/word functionality, needs to perform the following:
1. The system should have completed necessary initialization and the DRV_SPI_Tasks should either be running in polled
5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library
5-423
environment, or in an interrupt environment.
2. Open the driver using DRV_SPI_Open with the necessary intent
3. Setup the communication using the driver function DRV_SPI_CommunicationSetup
4. Enable/activate the slave using the function DRV_SPI_ChipSelectActivate
5. Put/Write a byte using DRV_SPI_Put, dummy byte in case of read only
6. Check for the current transfer status using DRV_SPI_TransferStatus until the transfer is in progress
DRV_SPI_TRANSFER_STATUS_IN_PROGRESS, call the DRV_SPI_Tasks in case of a polled environment until the transfer
is success
7. Get/Read the dummy/valid data using the function DRV_SPI_Get
8. Repeat from step 5 till 7 to handle buffer transmission and reception using standard mode
9. Disable/deactivate the slave using the function DRV_SPI_ChipSelectDeactivate
10. The client will be able to close the driver using the DRV_SPI_Close when required.
Example:
DRV_HANDLE handle; // Returned from DRV_SPI_Open
SPI_BUFFER myBuffer[MY_BUFFER_SIZE];
unsigned int numBytes;
DRV_SPI_COMM_CONFIG config;
// Pre-initialize myBuffer with MY_BUFFER_SIZE bytes of valid data.
while( 1 )
{
switch( state )
{
case APP_STATE_INIT:
/* Initialize the SPI Driver */
object = DRV_SPI_Initialize( sysIndex, ( SYS_MODULE_INIT * )&initConf );
/* Check for the System Status */
if( SYS_STATUS_READY != DRV_SPI_Status( object ) )
return 0;
/* Open the Driver */
clHandle = DRV_SPI_Open( sysIndex, DRV_IO_INTENT_EXCLUSIVE );
/* Check for the Client Open Status */
if( DRV_SPI_CLIENT_STATUS_READY != DRV_SPI_ClientStatus( clHandle ) )
return 0;
/* Set up the communication medium */
DRV_SPI_CommunicationSetup( clHandle, &commConf );
/* Update the state to transfer data */
state = APP_STATE_DATA_PUT;
break;
case APP_STATE_DATA_PUT:
/* Enable/Activate the CS */
DRV_SPI_ChipSelectActivate( handle, PORT_CHANNEL_A, PORTS_BIT_POS_1 );
/* Initiate the data transfer */
DRV_SPI_Put( clHandle, myBuffer[i++] );
/* Deactivates/Disables CS */
DRV_SPI_ChipSelectDeactivate( handle, PORT_CHANNEL_A, PORTS_BIT_POS_1 );
/* Update the state to status check */
state = APP_STATE_STATUS_CHECK;
break;
case APP_STATE_STATUS_CHECK:
5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library
5-424
/* Check for the successful data transfer */
if( DRV_SPI_TRANSFER_STATUS_IN_PROGRESS & DRV_SPI_TransferStatus( clHandle ) )
{
DRV_SPI_Tasks (object);
/* Stay here until the data transfer is executed */
state = APP_STATE_STATUS_CHECK;
}
else
{
/* Data transfer was successfull, get the data */
state = APP_STATE_DATA_GET;
}
break;
case APP_STATE_DATA_GET:
/* Read the data from the peripheral */
rxd_data = DRV_SPI_Get( clHandle );
/* Restart the process by jumping to the beginning state */
state = APP_STATE_DATA_PUT;
break;
default:
break;
}
}
Note: 'bufferType' attribute of the initialization structure or the configuration macro 'DRV_SPI_BUFFER_USAGE_TYPE' needs to
be updated as DRV_SPI_BUFFER_TYPE_STANDARD
5.1.9.4.3.4 Client Transfer - Advanced
Client basic functionality provides a extremely basic interface for the driver operation.
This client transfer mechanism needs to be used for the devices which support the
'Enhanced' SPI mode of operation [Internal FIFO or buffer].
The diagram below illustrates the buffer model used for the data transfer.
5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library
5-425
Note: It is not necessary to close and re-open the client between multiple transfers.
Client Byte/Word transfer Functionality
Application using the SPI byte/word functionality, needs to perform the following:
1. The system should have completed necessary initialization and the DRV_SPI_Tasks should either be running in polled
environment, or in an interrupt environment.
2. Open the driver using DRV_SPI_Open with the necessary intent
3. Setup the communication using the driver function DRV_SPI_CommunicationSetup
4. Enable/activate the slave using the function DRV_SPI_ChipSelectActivate
5. Put/Write a byte using DRV_SPI_PutBuffer, dummy byte in case of read only
6. Check for the current transfer status using DRV_SPI_TransferStatus until the transfer is in progress
DRV_SPI_TRANSFER_STATUS_IN_PROGRESS, call the DRV_SPI_Tasks in case of a polled environment until the transfer
is success
7. Get/Read the dummy/valid data using the function DRV_SPI_GetBuffer
5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library
5-426
8. Repeat from step 5 till 7 to handle multi buffer transmission and reception using enhanced mode
9. Disable/deactivate the slave using the function DRV_SPI_ChipSelectDeactivate
10. The client will be able to close the driver using the DRV_SPI_Close when required.
Example:
DRV_HANDLE handle; // Returned from DRV_SPI_Open
SPI_DATA_TYPE tx_buffer[DRV_SPI_BUFFER_SIZE] = { 0x0001, 0x0001, 0x0001, 0x0001 };
SPI_DATA_TYPE rx_buffer[DRV_SPI_BUFFER_SIZE];
unsigned int numBytes;
DRV_SPI_COMM_CONFIG config;
// Pre-initialize tx_buffer with DRV_SPI_BUFFER_SIZE bytes of valid data.
while( 1 )
{
switch( state )
{
case APP_STATE_INIT:
/* Initialize the SPI Driver */
object = DRV_SPI_Initialize( sysIndex, ( SYS_MODULE_INIT * )&initConf );
/* Check for the System Status */
if( SYS_STATUS_READY != DRV_SPI_Status( object ) )
return 0;
/* Open the Driver */
clHandle = DRV_SPI_Open( sysIndex, DRV_IO_INTENT_EXCLUSIVE );
/* Check for the Client Open Status */
if( DRV_SPI_CLIENT_STATUS_READY != DRV_SPI_ClientStatus( clHandle ) )
return 0;
/* Set up the communication medium */
DRV_SPI_CommunicationSetup( clHandle, &commConf );
/* Update the state to transfer data */
state = APP_STATE_BUFFER_PUT;
break;
case APP_STATE_BUFFER_PUT:
/* Initiate the data transfer */
DRV_SPI_PutBuffer( clHandle, &tx_buffer, sizeof( tx_buffer )/2 );
/* Update the state to status check */
state = APP_STATE_BUFFER_CHECK;
break;
case APP_STATE_BUFFER_CHECK:
/* Check for the successful data transfer */
if( DRV_SPI_TRANSFER_STATUS_IN_PROGRESS & DRV_SPI_TransferStatus( clHandle ) )
{
DRV_SPI_Tasks (object);
/* Stay here until the data transfer is executed */
state = APP_STATE_BUFFER_CHECK;
}
else
{
/* Data transfer was successfull, get the data */
state = APP_STATE_BUFFER_GET;
}
break;
case APP_STATE_BUFFER_GET:
/* Read the data from the peripheral */
DRV_SPI_GetBuffer( clHandle, &rx_buffer, sizeof( rx_buffer )/2 );
5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library
5-427
/* Restart the process by jumping to the beginning state */
state = APP_STATE_BUFFER_PUT;
break;
default:
break;
}
}
Note: 'bufferType' attribute of the initialization structure or the configuration macro 'DRV_SPI_BUFFER_USAGE_TYPE' needs to
be updated as DRV_SPI_BUFFER_TYPE_ENHANCED
5.1.9.5 Configuring the Library
The configuration of the SPI driver is based on the file sys_config.h
This header file contains the configuration selection for the SPI driver. Based on the selections made, the SPI driver will support
or not support selected features. These configuration settings will apply to all instances of the SPI driver.
This header can be placed anywhere, the path of this header needs to be present in the include search path for a successful
build. Refer to the Applications Overview section for more details.
5.1.9.5.1 Client Configuration
5.1.9.5.2 System Configuration
5.1.9.5.3 Miscellaneous Configuration
5.1.9.6 Building the Library
This section list the files that are available in the \src of the SPI driver. It lists which files need to be included in the build based
on either a hardware feature present on the board or configuration option selected by the system.
5.1.9.7 Library Interface
Data Types and Constants
Name Description
DRV_SPI_BAUD_RATE Controls the baud rate value of the SPI driver.
DRV_SPI_BAUD_RATE_CLOCK Selects the SPI baud rate clock.
DRV_SPI_BUFFER_HANDLE_INVALID Definition of an invalid buffer handle.
DRV_SPI_BUFFER_SIZE This is macro DRV_SPI_BUFFER_SIZE.
DRV_SPI_BUFFER_USAGE_TYPE Controls the buffer type of the SPI driver.
5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library
5-428
DRV_SPI_CLIENTS_NUMBER Selects the miximum number of clients.
DRV_SPI_CLOCK_OPERATION_MODE Controls the clock mode of the SPI driver.
DRV_SPI_COMMUNICATION_WIDTH Controls the communication width of the SPI driver.
DRV_SPI_FRAME_SYNC_PULSE_COUNT Selects the SPI frame sync pulse count.
DRV_SPI_FRAME_SYNC_PULSE_DIRECTION Selects the SPI frame sync pulse direction.
DRV_SPI_FRAME_SYNC_PULSE_EDGE Selects the SPI frame sync pulse edge.
DRV_SPI_FRAME_SYNC_PULSE_POLARITY Selects the SPI frame sync pulse polarity.
DRV_SPI_FRAME_SYNC_PULSE_WIDTH Selects the SPI frame sync pulse width.
DRV_SPI_INDEX SPI static index selection.
DRV_SPI_INDEX_0 SPI driver index definitions.
DRV_SPI_INDEX_COUNT Number of valid SPI driver indices.
DRV_SPI_INPUT_SAMPLE_PHASE Selects the SPI input sample phase.
DRV_SPI_INSTANCES_NUMBER Selects the maximum number of hardware instances that can be
supported by the dynamic driver .
DRV_SPI_INTERRUPT_MODE Controls operation of the driver in the interrupt or polled mode.
DRV_SPI_INTERRUPT_SOURCE_ERROR Defines the error interrupt source in case of static driver
DRV_SPI_INTERRUPT_SOURCE_RX Defines the receive interrupt source in case of static driver.
DRV_SPI_INTERRUPT_SOURCE_TX Defines the transmit/receive or transmit alone interrupt source in
case of static driver.
DRV_SPI_PERIPHERAL_ID SPI peripheral ID selection.
DRV_SPI_PORTS_REMAP_USAGE Selects the SPI pins remap.
DRV_SPI_POWER_STATE Controls the power state of the SPI driver.
DRV_SPI_PROTOCOL Controls the protocol type of the SPI driver.
DRV_SPI_USAGE_MODE Controls the usage mode of the SPI driver.
DRV_SPI_BUFFER_EVENT Identifies the possible events that can result from a buffer add
request.
DRV_SPI_BUFFER_EVENT_HANDLER Pointer to a SPI Driver Buffer Event handler function
DRV_SPI_BUFFER_HANDLE Handle identifying a read or write buffer passed to the driver.
DRV_SPI_BUFFER_TYPE Identifies the various buffer types of the SPI module.
DRV_SPI_CLIENT_SETUP Defines the data required to initialize an SPI client.
DRV_SPI_CLOCK_MODE Identifies the various clock modes of the SPI module.
DRV_SPI_INIT Defines the data required to initialize or reinitialize the SPI driver
DRV_SPI_MODE Identifies the various usage modes of the SPI module.
DRV_SPI_PROTOCOL_TYPE Identifies the various protocols of the SPI module.
Client Setup Functions
Name Description
DRV_SPI_BufferStatus Returns the transmitter and receiver transfer status.
DRV_SPI_ClientSetup Initializes a client.
DRV_SPI_Close Closes an opened instance of the SPI driver
DRV_SPI_Open Opens the specified SPI driver instance and returns a handle to it.
Miscellaneous Functions
Name Description
DRV_SPI_BufferAddRead Registers a buffer for a read operation. Actual transfer will happen in
the Task function.
5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library
5-429
DRV_SPI_BufferAddWrite Registers a buffer for a read operation. Actual transfer will happen in
the Task function.
DRV_SPI_BufferAddWriteRead Registers a buffer for a read operation. Actual transfer will happen in
the Task function.
DRV_SPI_VersionGet Gets the SPI driver version in numerical format.
DRV_SPI_VersionStrGet Gets the SPI driver version in string format.
DRV_SPI_INDEX_1 This is macro DRV_SPI_INDEX_1.
DRV_SPI_INDEX_2 This is macro DRV_SPI_INDEX_2.
DRV_SPI_INDEX_3 This is macro DRV_SPI_INDEX_3.
DRV_SPI_INDEX_4 This is macro DRV_SPI_INDEX_4.
DRV_SPI_INDEX_5 This is macro DRV_SPI_INDEX_5.
DRV_SPI_RX_FIFO_INTERRUPT_MODE This is macro DRV_SPI_RX_FIFO_INTERRUPT_MODE.
DRV_SPI_TX_FIFO_INTERRUPT_MODE This is macro DRV_SPI_TX_FIFO_INTERRUPT_MODE.
System Interaction Functions
Name Description
DRV_SPI_Deinitialize De-initializes the specified instance of the SPI driver module.
DRV_SPI_Initialize Initializes the SPI driver.
DRV_SPI_Status Provides the current status of the SPI driver module.
DRV_SPI_Tasks Maintains the driver's state machine and implements its ISR.
DRV_SPI_Read Gets/Reads byte(s) from SPI. The function will wait until the specified number of
bytes is received.
DRV_SPI_Write Writes the data to SPI. The function will wait until all the bytes are transmitted.
Description
This section describes the API functions of the SPI driver library.
Refer to each section for a detailed description.
5.1.9.7.1 System Interaction Functions
5.1.9.7.1.1 DRV_SPI_Deinitialize Function
C
void DRV_SPI_Deinitialize(
SYS_MODULE_OBJ object
);
Description
De-initializes the specified instance of the SPI driver module, disabling its operation (and any hardware) and invalidates all of the
internal data.
Preconditions
Function DRV_SPI_Initialize must have been called before calling this routine and a valid SYS_MODULE_OBJ must have been
returned.
Parameters
Parameters Description
object Driver object handle, returned from DRV_SPI_Initialize
5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library
5-430
Returns
None.
Remarks
Once the Initialize operation has been called, the De-initialize operation must be called before the Initialize operation can be
called again.
This function will NEVER block waiting for hardware. If the operation requires time to allow the hardware to complete, this will be
reported by the DRV_SPI_Status operation. The system has to use DRV_SPI_Status to find out when the module is in the ready
state.
Example
SYS_MODULE_OBJ object; // Returned from DRV_SPI_Initialize
SYS_STATUS status;
DRV_SPI_Deinitialize ( object );
status = DRV_SPI_Status( object );
if( SYS_MODULE_UNINITIALIZED == status )
{
// Check again later if you need to know
// when the driver is de-initialized.
}
5.1.9.7.1.2 DRV_SPI_Initialize Function
C
SYS_MODULE_OBJ DRV_SPI_Initialize(
const SYS_MODULE_INDEX index,
const SYS_MODULE_INIT * const init
);
Description
This function initializes the SPI driver, making it ready for clients to open and use.
Preconditions
None.
Parameters
Parameters Description
drvIndex Index for the driver instance to be initialized
init Pointer to a data structure containing any data necessary to initialize the driver.
This pointer may be null if no data is required because static overrides have been
provided.
Returns
If successful, a valid handle to a driver object is returned. Otherwise, it returns SYS_MODULE_OBJ_INVALID. The returned
object must be passed as an argument to the DRV_SPI_Reinitialize, DRV_SPI_Deinitialize, DRV_SPI_Tasks, and
DRV_SPI_Status functions.
Remarks
This function must be called before any other SPI routine is called.
This function should only be called once during system initialization unless DRV_SPI_Deinitialize is called to de-initialize the
driver instance.
This function will NEVER block for hardware access. If the operation requires time to allow the hardware to reinitialize, it will be
5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library
5-431
reported by the DRV_SPI_Status operation. The system must use DRV_SPI_Status to find out when the driver is in the ready
state.
Build configuration options may be used to statically override options in the "init" structure and will take precedence over
initialization data passed using this function.
Example
DRV_SPI_INIT init;
SYS_MODULE_OBJ objectHandle;
// Populate the SPI initialization structure
init.spiId = SPI_ID_1;
init.spiMode = DRV_SPI_MODE_MASTER;
init.spiProtocolType = DRV_SPI_PROTOCOL_TYPE_STANDARD;
init.commWidth = SPI_COMMUNICATION_8BIT_WIDE;
init.baudRate = 5000;
init.bufferType = DRV_SPI_BUFFER_TYPE_STANDARD;
init.inputSamplePhase = SPI_INPUT_SAMPLING_PHASE_IN_MIDDLE;
init.clockMode = DRV_SPI_CLOCK_MODE_IDLE_LOW_EDGE_RISE;
init.txInterruptSource = INT_SOURCE_SPI_1_TRANSMIT; // INT_SOURCE_SPI_1_EVENT
init.rxInterruptSource = INT_SOURCE_SPI_1_RECEIVE; // INT_SOURCE_SPI_1_EVENT
init.errInterruptSource = INT_SOURCE_SPI_1_ERROR;
// Do something
objectHandle = DRV_SPI_Initialize( DRV_SPI_INDEX_0, (SYS_MODULE_INIT*)&init );
if( SYS_MODULE_OBJ_INVALID == objectHandle )
{
// Handle error
}
5.1.9.7.1.3 DRV_SPI_Status Function
C
SYS_STATUS DRV_SPI_Status(
SYS_MODULE_OBJ object
);
Description
This function provides the current status of the SPI driver module.
Preconditions
The DRV_SPI_Initialize function must have been called before calling this function.
Parameters
Parameters Description
object Driver object handle, returned from DRV_SPI_Initialize
Returns
SYS_STATUS_READY - Indicates that the driver is busy with a previous system level operation and cannot start another
Remarks
Any value greater than SYS_STATUS_READY is also a normal running state in which the driver is ready to accept new
operations.
SYS_MODULE_DEINITIALIZED - Indicates that the driver has been de-initialized
This value is less than SYS_STATUS_ERROR.
This function can be used to determine when any of the driver's module level operations has completed.
5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library
5-432
If the status operation returns SYS_STATUS_BUSY, the previous operation has not yet completed. Once the status operation
returns SYS_STATUS_READY, any previous operations have completed.
The value of SYS_STATUS_ERROR is negative (-1). Any value less than that is also an error state.
This function will NEVER block waiting for hardware.
If the Status operation returns an error value, the error may be cleared by calling the reinitialize operation. If that fails, the
de-initialize operation will need to be called, followed by the initialize operation to return to normal operations.
Example
SYS_MODULE_OBJ object; // Returned from DRV_SPI_Initialize
SYS_STATUS status;
status = DRV_SPI_Status( object );
if( SYS_STATUS_READY != status )
{
// Handle error
}
5.1.9.7.1.4 DRV_SPI_Tasks Function
C
void DRV_SPI_Tasks(
SYS_MODULE_OBJ object
);
Description
This routine is used to maintain the driver's internal state machine and implement its transmit ISR for interrupt-driven
implementations. In polling mode, this function should be called from the SYS_Tasks() function. In interrupt mode, this function
should be called in the transmit interrupt service routine of the USART that is associated with this USART driver hardware
instance.
Preconditions
The DRV_SPI_Initialize routine must have been called for the specified SPI driver instance.
Parameters
Parameters Description
object Object handle for the specified driver instance (returned from DRV_SPI_Initialize)
Returns
None.
Remarks
This function is normally not called directly by an application. It is called by the system's Tasks routine (SYS_Tasks) or by the
appropriate raw ISR.
This function may execute in an ISR context and will never block or access any resources that may cause it to block.
Example
SYS_MODULE_OBJ object; // Returned from DRV_SPI_Initialize
while( true )
{
DRV_SPI_Tasks ( object );
// Do other tasks
}
5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library
5-433
5.1.9.7.1.5 DRV_SPI_Read Function
C
size_t DRV_SPI_Read(
DRV_HANDLE handle,
void* buffer,
size_t noOfBytes
);
Description
This function gets/reads byte(s) from SPI. The function will wait until the specified number of bytes is received.
Preconditions
The DRV_SPI_Initialize routine must have been called for the specified SPI driver instance.
DRV_SPI_Open must have been called to obtain a valid opened device handle.
DRV_IO_INTENT_READ or DRV_IO_INTENT_READWRITE must have been specified in the DRV_SPI_Open call.
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open routine
buffer Buffer to which the data should be written to.
noOfBytes Number of bytes to be received.
Returns
The number of bytes read.
Remarks
If the DRV_IO_INTENT_BLOCKING flag was given in the call to the DRV_SPI_Open function and the driver was built to support
blocking behavior the call will block until the operation is complete.
If the DRV_IO_INTENT_NONBLOCKING flag was given in the call to the DRV_SPI_Open function or the driver was built to only
support non-blocking behavior the call will return immediately. If data is not available, a zero ('0') value will be returned and an
underrun error status will be captured. To ensure that valid data is returned, the caller must first check the return value to
DRV_SPI_BufferStatus, as shown in the example.
Example
DRV_HANDLE handle; // Returned from DRV_SPI_Open
SPI_DATA_TYPE myBuffer[MY_BUFFER_SIZE];
unsigned int numberOfBytesRead;
numberOfBytesRead = DRV_SPI_Read ( handle, myBuffer, 10 );
if ( numberOfBytesWritten == 0 )
{
// Check for the error...
}
5.1.9.7.1.6 DRV_SPI_Write Function
C
size_t DRV_SPI_Write(
DRV_HANDLE handle,
void* buffer,
size_t noOfBytes
);
5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library
5-434
Description
This function Writes the data to SPI. The function will wait until all the bytes are transmitted.
Preconditions
The DRV_SPI_Initialize routine must have been called for the specified SPI driver instance.
DRV_SPI_Open must have been called to obtain a valid opened device handle.
DRV_IO_INTENT_WRITE or DRV_IO_INTENT_READWRITE must have been specified in the DRV_SPI_Open call.
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open routine
buffer Buffer which contains the data.
noOfBytes Number of bytes to be transmitted.
Returns
The number of bytes written.
Remarks
If the DRV_IO_INTENT_BLOCKING flag was given in the call to the DRV_SPI_Open function and the driver was built to support
blocking behavior the call will block until the operation is complete.
If the DRV_IO_INTENT_NONBLOCKING flag was given in the call to the DRV_SPI_Open function or the driver was built to only
support non-blocking behavior the call will return immediately. If the driver was not able to accept the data, an overrun error
status will be captured. To ensure that the driver is ready to accept data, the caller must first check the return value to
DRV_SPI_BufferStatus, as shown in the example.
Example
DRV_HANDLE handle; // Returned from DRV_SPI_Open
SPI_DATA_TYPE myBuffer[MY_BUFFER_SIZE];//fill the data
unsigned int numberOfBytesWritten;
numberOfBytesWritten = DRV_SPI_Write ( handle, myBuffer, 10 );
if ( numberOfBytesWritten == 0 )
{
// Check the error...
}
5.1.9.7.2 Client Setup Functions
5.1.9.7.2.1 DRV_SPI_BufferStatus Function
C
DRV_SPI_BUFFER_EVENT DRV_SPI_BufferStatus(
DRV_SPI_BUFFER_HANDLE bufferHandle
);
Description
This returns the transmitter and receiver transfer status.
Preconditions
The DRV_SPI_Initialize routine must have been called for the specified SPI driver instance.
DRV_SPI_Open must have been called to obtain a valid opened device handle.
5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library
5-435
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open routine
Returns
A DRV_SPI_BUFFER_STATUS value describing the current status of the transfer.
Remarks
The returned status may contain a value with more than one of the bits specified in the DRV_SPI_BUFFER_STATUS
enumeration set. The caller should perform an AND with the bit of interest and verify if the result is non-zero (as shown in the
example) to verify the desired status bit.
Example
DRV_HANDLE handle; // Returned from DRV_SPI_Open
if( DRV_SPI_BUFFER_STATUS_SUCCESS & DRV_SPI_BufferStatus( handle ) )
{
// All transmitter data has been sent.
}
5.1.9.7.2.2 DRV_SPI_ClientSetup Function
C
void DRV_SPI_ClientSetup(
DRV_HANDLE handle,
const DRV_SPI_CLIENT_SETUP * const clientSetup
);
Description
This function sets up the device communication parameters. Using this API user can have configurations like chip select and
baud rate specific to a client. The driver will be able to switch the between clients dynamically.
'DRV_SPI_CLIENT_SPECIFIC_CONTROL' must be defined in 'system_config.h'. This function is only useful for instance which
has got multiple slaves.
Preconditions
The DRV_SPI_Initialize routine must have been called.
DRV_SPI_Open must have been called to obtain a valid opened device handle.
Parameters
Parameters Description
handle A valid open instance handle, returned from the driver's open routine
clientSetup Communication parameters identified by DRV_SPI_CLIENT_SETUP
Returns
None
Remarks
This is an optional call. It is necessary only two clients using needs different configurations.
Example
DRV_HANDLE handle; // Returned from DRV_SPI_Open
DRV_SPI_CLIENT_SETUP clientSetup;
// Populate the communication setup configuration structure
5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library
5-436
clientSetup.baudRate = 5000;
clientSetup.inputSamplePhase = SPI_INPUT_SAMPLING_PHASE_IN_MIDDLE;
clientSetup.clockMode = DRV_SPI_CLOCK_MODE_IDLE_LOW_EDGE_RISE;
clientSetup.callback = &callBackFunction; // callback registered
DRV_SPI_ClientSetup ( handle, &clientSetup );
5.1.9.7.2.3 DRV_SPI_Close Function
C
void DRV_SPI_Close(
DRV_HANDLE handle
);
Description
This function closes an opened instance of the SPI driver, invalidating the handle.
Preconditions
The DRV_SPI_Initialize routine must have been called for the specified SPI driver instance.
DRV_SPI_Open must have been called to obtain a valid opened device handle.
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open routine
Returns
None
Remarks
After calling this routine, the handle passed in "handle" must not be used with any of the remaining driver routines. A new handle
must be obtained by calling DRV_USART_Open before the caller may use the driver again. This function is thread safe in a
RTOS application.
Usually there is no need for the driver client to verify that the Close operation has completed.
Example
DRV_HANDLE handle; // Returned from DRV_SPI_Open
DRV_SPI_Close ( handle );
5.1.9.7.2.4 DRV_SPI_Open Function
C
DRV_HANDLE DRV_SPI_Open(
const SYS_MODULE_INDEX drvIndex,
const DRV_IO_INTENT intent
);
Description
This routine opens the specified USART driver instance and provides a handle that must be provided to all other client-level
operations to identify the caller and the instance of the driver. The ioIntent parameter defines how the client interacts with this
driver instance.
The DRV_IO_INTENT_BLOCKING and DRV_IO_INTENT_NONBLOCKING ioIntent options additionally affect the behavior of
the DRV_USART_Read() and DRV_USART_Write() functions. If the ioIntent is DRV_IO_INTENT_NONBLOCKING, then these
function will not block even if the required amount of data could not be processed. If the ioIntent is
DRV_IO_INTENT_BLOCKING, these functions will block till the required amount of data is processed.
5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library
5-437
If ioIntent is DRV_IO_INTENT_READ, the client will only be read from the driver. If ioIntent is DRV_IO_INTENT_WRITE, the
client will only be able to write to the driver. If the ioIntent in DRV_IO_INTENT_READWRITE, the client will be able to do both,
read and write.
Specifying a DRV_IO_INTENT_EXCLUSIVE will cause the driver to provide exclusive access to this client. The driver cannot be
opened by any other client.
Preconditions
The DRV_SPI_Initialize function must have been called before calling this function.
Parameters
Parameters Description
drvIndex Identifier for the object instance to be opened
intent Zero or more of the values from the enumeration DRV_IO_INTENT ORed together
to indicate the intended use of the driver
Returns
If successful, the routine returns a valid open-instance handle (a number identifying both the caller and the module instance).
If an error occurs, the return value is DRV_HANDLE_INVALID. Error can occur
• if the number of client objects allocated via DRV_USART_CLIENTS_NUMBER is
insufficient.
• if the client is trying to open the driver but driver has been opened
exclusively by another client.
• if the driver hardware instance being opened is not initialized or is
invalid.
Remarks
The handle returned is valid until the DRV_USART_Close routine is called. This routine will NEVER block waiting for hardware.If
the requested intent flags are not supported, the routine will return DRV_HANDLE_INVALID. This function is thread safe in a
RTOS application. It should not be called in an ISR.
Example
DRV_HANDLE handle;
handle = DRV_SPI_Open( DRV_SPI_INDEX_0, DRV_IO_INTENT_EXCLUSIVE );
if( DRV_HANDLE_INVALID == handle )
{
// Unable to open the driver
}
5.1.9.7.3 Miscellaneous Functions
5.1.9.7.3.1 DRV_SPI_BufferAddRead Function
C
DRV_SPI_BUFFER_HANDLE DRV_SPI_BufferAddRead(
DRV_HANDLE handle,
void * rxBuffer,
size_t size
);
5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library
5-438
Description
Registers a buffer for a read operation. Actual transfer will happen in the Task function. The status of this operation can be
monitored using DRV_SPI_BufferStatus function.
Preconditions
The DRV_SPI_Initialize routine must have been called for the specified SPI driver instance.
DRV_SPI_Open must have been called to obtain a valid opened device handle.
DRV_IO_INTENT_WRITE or DRV_IO_INTENT_READWRITE must have been specified in the DRV_SPI_Open call.
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open routine
rxBuffer The buffer to which the data should be written to.
size Number of bytes to be read.
Returns
None.
Remarks
If the DRV_IO_INTENT_BLOCKING flag was given in the call to the DRV_SPI_Open function and the driver was built to support
blocking behavior the call will block until the operation is complete.
If the DRV_IO_INTENT_NONBLOCKING flag was given in the call to the DRV_SPI_Open function or the driver was built to only
support non-blocking behavior the call will return immediately. If the driver was not able to accept the data, an overrun error
status will be captured. To ensure that the driver is ready to accept data, the caller must first check the return value to
DRV_SPI_BufferStatus, as shown in the example.
Example
DRV_HANDLE handle; // Returned from DRV_SPI_Open
SPI_DATA_TYPE myBuffer[MY_BUFFER_SIZE];
// PUT API returns data in any case, upto the user to use it
DRV_SPI_BufferAddRead( handle, myBuffer, 10 );
if( DRV_SPI_BUFFER_STATUS_SUCCESS & DRV_SPI_BufferStatus( handle ) )
{
// All transmitter data has been sent.
}
5.1.9.7.3.2 DRV_SPI_BufferAddWrite Function
C
DRV_SPI_BUFFER_HANDLE DRV_SPI_BufferAddWrite(
DRV_HANDLE handle,
void * txBuffer,
size_t size
);
Description
Registers a buffer for a read operation. Actual transfer will happen in the Task function. The status of this operation can be
monitored using DRV_SPI_BufferStatus function.
Preconditions
The DRV_SPI_Initialize routine must have been called for the specified SPI driver instance.
5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library
5-439
DRV_SPI_Open must have been called to obtain a valid opened device handle.
DRV_IO_INTENT_WRITE or DRV_IO_INTENT_READWRITE must have been specified in the DRV_SPI_Open call.
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open routine
rxBuffer The buffer to which the data should be written to.
size Number of bytes to be read.
Returns
None.
Remarks
If the DRV_IO_INTENT_BLOCKING flag was given in the call to the DRV_SPI_Open function and the driver was built to support
blocking behavior the call will block until the operation is complete.
If the DRV_IO_INTENT_NONBLOCKING flag was given in the call to the DRV_SPI_Open function or the driver was built to only
support non-blocking behavior the call will return immediately. If the driver was not able to accept the data, an overrun error
status will be captured. To ensure that the driver is ready to accept data, the caller must first check the return value to
DRV_SPI_BufferStatus, as shown in the example.
Example
DRV_HANDLE handle; // Returned from DRV_SPI_Open
SPI_DATA_TYPE myBuffer[MY_BUFFER_SIZE];
unsigned int numBytes;
// Pre-initialize myBuffer with MY_BUFFER_SIZE bytes of valid data.
numBytes = 0;
// PUT API returns data in any case, upto the user to use it
DRV_SPI_BufferAddRead( handle, myBuffer, 10 );
if( DRV_SPI_BUFFER_STATUS_SUCCESS & DRV_SPI_BufferStatus( handle ) )
{
// All transmitter data has been sent.
}
5.1.9.7.3.3 DRV_SPI_BufferAddWriteRead Function
C
DRV_SPI_BUFFER_HANDLE DRV_SPI_BufferAddWriteRead(
DRV_HANDLE handle,
void * txBuffer,
void * rxBuffer,
size_t size
);
Description
Registers a buffer for a read operation. Actual transfer will happen in the Task function. The status of this operation can be
monitored using DRV_SPI_BufferStatus function.
Preconditions
The DRV_SPI_Initialize routine must have been called for the specified SPI driver instance.
DRV_SPI_Open must have been called to obtain a valid opened device handle.
DRV_IO_INTENT_WRITE or DRV_IO_INTENT_READWRITE must have been specified in the DRV_SPI_Open call.
5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library
5-440
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open routine
rxBuffer The buffer to which the data should be written to.
size Number of bytes to be read.
Returns
None.
Remarks
If the DRV_IO_INTENT_BLOCKING flag was given in the call to the DRV_SPI_Open function and the driver was built to support
blocking behavior the call will block until the operation is complete.
If the DRV_IO_INTENT_NONBLOCKING flag was given in the call to the DRV_SPI_Open function or the driver was built to only
support non-blocking behavior the call will return immediately. If the driver was not able to accept the data, an overrun error
status will be captured. To ensure that the driver is ready to accept data, the caller must first check the return value to
DRV_SPI_BufferStatus, as shown in the example.
Example
DRV_HANDLE handle; // Returned from DRV_SPI_Open
SPI_DATA_TYPE myBuffer[MY_BUFFER_SIZE];
unsigned int numBytes;
// Pre-initialize myBuffer with MY_BUFFER_SIZE bytes of valid data.
numBytes = 0;
// PUT API returns data in any case, upto the user to use it
DRV_SPI_BufferAddWriteRead( handle, myTxBuffer, myRxBuffer, 10 );
if( DRV_SPI_BUFFER_STATUS_SUCCESS & DRV_SPI_BufferStatus( handle ) )
{
// All transmitter data has been sent.
}
5.1.9.7.3.4 DRV_SPI_VersionGet Function
C
unsigned int DRV_SPI_VersionGet(
const SYS_MODULE_INDEX drvIndex
);
Description
This function gets the SPI driver version. The version is encoded as major * 10000 + minor * 100 + patch. The stringed version
can be obtained using DRV_SPI_VersionStrGet.
Preconditions
None.
Parameters
Parameters Description
drvIndex Identifier for the object instance to get the version for
Returns
Current driver version in numerical format.
5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library
5-441
Remarks
None.
Example
unsigned int version;
version = DRV_SPI_VersionGet( DRV_SPI_INDEX_0 );
if(version < 110200)
{
// Do Something
}
5.1.9.7.3.5 DRV_SPI_VersionStrGet Function
C
char * DRV_SPI_VersionStrGet(
const SYS_MODULE_INDEX drvIndex
);
Description
This function gets the SPI driver version. The version is returned as major.minor.path[type], where type is optional. The
numerical version can be obtained using DRV_SPI_VersionGet.
Preconditions
None.
Parameters
Parameters Description
drvIndex Identifier for the object instance to get the version for
Returns
Current the SPI driver version in the string format.
Remarks
None.
Example
char *version;
version = DRV_SPI_VersionStrGet( DRV_SPI_INDEX_0 );
printf("%s", version);
5.1.9.7.3.6 DRV_SPI_INDEX_1 Macro
C
#define DRV_SPI_INDEX_1 1
Description
This is macro DRV_SPI_INDEX_1.
5.1.9.7.3.7 DRV_SPI_INDEX_2 Macro
C
#define DRV_SPI_INDEX_2 2
5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library
5-442
Description
This is macro DRV_SPI_INDEX_2.
5.1.9.7.3.8 DRV_SPI_INDEX_3 Macro
C
#define DRV_SPI_INDEX_3 3
Description
This is macro DRV_SPI_INDEX_3.
5.1.9.7.3.9 DRV_SPI_INDEX_4 Macro
C
#define DRV_SPI_INDEX_4 4
Description
This is macro DRV_SPI_INDEX_4.
5.1.9.7.3.10 DRV_SPI_INDEX_5 Macro
C
#define DRV_SPI_INDEX_5 5
Description
This is macro DRV_SPI_INDEX_5.
5.1.9.7.3.11 DRV_SPI_RX_FIFO_INTERRUPT_MODE Macro
C
#define DRV_SPI_RX_FIFO_INTERRUPT_MODE SPI_FIFO_INTERRUPT_WHEN_RECEIVE_BUFFER_IS_FULL
Description
This is macro DRV_SPI_RX_FIFO_INTERRUPT_MODE.
5.1.9.7.3.12 DRV_SPI_TX_FIFO_INTERRUPT_MODE Macro
C
#define DRV_SPI_TX_FIFO_INTERRUPT_MODE SPI_FIFO_INTERRUPT_WHEN_TRANSMISSION_IS_COMPLETE
Description
This is macro DRV_SPI_TX_FIFO_INTERRUPT_MODE.
5.1.9.7.4 Data Types and Constants
5.1.9.7.4.1 DRV_SPI_BAUD_RATE Macro
C
#define DRV_SPI_BAUD_RATE 8000000
5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library
5-443
Description
SPI baud rate value configuration
This macro controls the baud rate value of the SPI driver.
Remarks
None.
5.1.9.7.4.2 DRV_SPI_BAUD_RATE_CLOCK Macro
C
#define DRV_SPI_BAUD_RATE_CLOCK SPI_BAUD_RATE_CLOCK_MCLK
Description
SPI baud rate clock selection
This macro selects the SPI baud rate clock.
Remarks
None.
5.1.9.7.4.3 DRV_SPI_BUFFER_HANDLE_INVALID Macro
C
#define DRV_SPI_BUFFER_HANDLE_INVALID ((DRV_SPI_BUFFER_HANDLE)(-1))
Description
SPI Driver Invalid Buffer Handle
This is the definition of an invalid buffer handle. An invalid buffer handle is returned by DRV_SPI_BufferAddRead() and
DRV_SPI_BufferAddWrite() function if the buffer add request was not successful.
Remarks
None
5.1.9.7.4.4 DRV_SPI_BUFFER_SIZE Macro
C
#define DRV_SPI_BUFFER_SIZE 8
Description
This is macro DRV_SPI_BUFFER_SIZE.
5.1.9.7.4.5 DRV_SPI_BUFFER_USAGE_TYPE Macro
C
#define DRV_SPI_BUFFER_USAGE_TYPE DRV_SPI_BUFFER_TYPE_STANDARD
Description
SPI buffer type configuration
This macro controls the buffer type of the SPI driver.
5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library
5-444
Remarks
None.
5.1.9.7.4.6 DRV_SPI_CLIENTS_NUMBER Macro
C
#define DRV_SPI_CLIENTS_NUMBER 1
Description
SPI maximum number of clients
This definition selects the maximum number of clients that the SPI driver can support at run time.
Remarks
None.
5.1.9.7.4.7 DRV_SPI_CLOCK_OPERATION_MODE Macro
C
#define DRV_SPI_CLOCK_OPERATION_MODE DRV_SPI_CLOCK_MODE_IDLE_LOW_EDGE_RISE
Description
SPI clock mode configuration
This macro controls the clock mode of the SPI driver.
Remarks
None.
5.1.9.7.4.8 DRV_SPI_COMMUNICATION_WIDTH Macro
C
#define DRV_SPI_COMMUNICATION_WIDTH SPI_COMMUNICATION_8BIT_WIDE
Description
SPI communication width configuration
This macro controls the communication width of the SPI driver.
Remarks
None.
5.1.9.7.4.9 DRV_SPI_FRAME_SYNC_PULSE_COUNT Macro
C
#define DRV_SPI_FRAME_SYNC_PULSE_COUNT SPI_FRAME_SYNC_PULSE_16_CHAR
Description
SPI frame sync pulse count selection
This macro selects the SPI frame sync pulse count.
Remarks
None.
5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library
5-445
5.1.9.7.4.10 DRV_SPI_FRAME_SYNC_PULSE_DIRECTION Macro
C
#define DRV_SPI_FRAME_SYNC_PULSE_DIRECTION SPI_FRAME_PULSE_DIRECTION_INPUT
Description
SPI frame sync pulse direction selection
This macro selects the SPI frame sync pulse direction.
Remarks
None.
5.1.9.7.4.11 DRV_SPI_FRAME_SYNC_PULSE_EDGE Macro
C
#define DRV_SPI_FRAME_SYNC_PULSE_EDGE SPI_FRAME_PULSE_EDGE_PRECEDES_FIRST_CLOCK
Description
SPI frame sync pulse edge selection
This macro selects the SPI frame sync pulse edge.
Remarks
None.
5.1.9.7.4.12 DRV_SPI_FRAME_SYNC_PULSE_POLARITY Macro
C
#define DRV_SPI_FRAME_SYNC_PULSE_POLARITY SPI_FRAME_PULSE_POLARITY_ACTIVE_HIGH
Description
SPI frame sync pulse polarity selection
This macro selects the SPI frame sync pulse polarity.
Remarks
None.
5.1.9.7.4.13 DRV_SPI_FRAME_SYNC_PULSE_WIDTH Macro
C
#define DRV_SPI_FRAME_SYNC_PULSE_WIDTH SPI_FRAME_PULSE_WIDTH_TO_ONE_WORD
Description
SPI frame sync pulse width selection
This macro selects the SPI frame sync pulse width.
Remarks
None.
5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library
5-446
5.1.9.7.4.14 DRV_SPI_INDEX Macro
C
#define DRV_SPI_INDEX DRV_SPI_INDEX_2
Description
SPI static index selection
This definition selects the SPI static index for the driver object reference.
Remarks
This index is required to make a reference to the driver object.
5.1.9.7.4.15 DRV_SPI_INDEX_0 Macro
C
#define DRV_SPI_INDEX_0 0
Description
SPI Driver Module Index Numbers
These constants provide the SPI driver index definitions.
Remarks
These constants should be used in place of hard-coded numeric literals.
These values should be passed into the DRV_SPI_Initialize and DRV_SPI_Open functions to identify the driver instance in use.
5.1.9.7.4.16 DRV_SPI_INDEX_COUNT Macro
C
#define DRV_SPI_INDEX_COUNT SPI_NUMBER_OF_MODULES
Description
SPI Driver Module Index Count
This constant identifies the number of valid SPI driver indices.
Remarks
This constant should be used in place of hard-coded numeric literals.
This value is derived from device-specific header files defined as part of the peripheral libraries.
5.1.9.7.4.17 DRV_SPI_INPUT_SAMPLE_PHASE Macro
C
#define DRV_SPI_INPUT_SAMPLE_PHASE SPI_INPUT_SAMPLING_PHASE_IN_MIDDLE
Description
SPI input sample phase selection
This macro selects the SPI input sample phase.
Remarks
None.
5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library
5-447
5.1.9.7.4.18 DRV_SPI_INSTANCES_NUMBER Macro
C
#define DRV_SPI_INSTANCES_NUMBER 1
Description
SPI hardware instance configuration
This definition selects the maximum number of hardware instances that can be supported by the dynamic driver.
Remarks
None.
5.1.9.7.4.19 DRV_SPI_INTERRUPT_MODE Macro
C
#define DRV_SPI_INTERRUPT_MODE false
Description
SPI interrupt and polled mode operation control
This macro controls the operation of the driver in the interrupt mode of operation. The possible values of this macro are:
• true - Select if interrupt mode of SPI operation is desired
• false - Select if polling mode of SPI operation is desired
Not defining this option to true or false will result in build error.
Remarks
None.
5.1.9.7.4.20 DRV_SPI_INTERRUPT_SOURCE_ERROR Macro
C
#define DRV_SPI_INTERRUPT_SOURCE_ERROR INT_SOURCE_SPI_1_ERROR
Description
SPI error interrupt source
Macro to define the error interrupt source in case of static driver.
Remarks
Refer to the INT PLIB document for more information on INT_SOURCE enumeration
5.1.9.7.4.21 DRV_SPI_INTERRUPT_SOURCE_RX Macro
C
#define DRV_SPI_INTERRUPT_SOURCE_RX INT_SOURCE_SPI_1_EVENT
Description
SPI receive interrupt source
This macro defines the receive interrupt source of the static driver.
5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library
5-448
Remarks
Refer to the Interrupt Peripheral Library documentation for more information on INT_SOURCE enumeration.
This should be specified in case the device does not have a dedicated receive interrupt source.
5.1.9.7.4.22 DRV_SPI_INTERRUPT_SOURCE_TX Macro
C
#define DRV_SPI_INTERRUPT_SOURCE_TX INT_SOURCE_SPI_1_EVENT
Description
SPI transmit/receive or transmit alone interrupt source
This macro defines the transmit/receive or transmit alone interrupt source of the static driver.
Remarks
Refer to the Interrupt Peripheral Library documentation for more information on the INT_SOURCE enumeration.
Some devices have a single interrupt source for both transmit and receive communication, while some have a dedicated transmit
interrupt source. These are handled through the DRV_SPI_INTERRUPT_SOURCE configuration switch.
5.1.9.7.4.23 DRV_SPI_PERIPHERAL_ID Macro
C
#define DRV_SPI_PERIPHERAL_ID SPI_ID_1
Description
SPI peripheral ID selection
This macro selects the SPI peripheral ID selection. This is an intialization override of the spiID member of the intialization
configuration.
Remarks
Some devices also support SPI_ID_0.
5.1.9.7.4.24 DRV_SPI_PORTS_REMAP_USAGE Macro
C
#define DRV_SPI_PORTS_REMAP_USAGE false
Description
SPI pins remap selection
This macro selects the SPI pins remap. The possible values of this macro are:
• true - Remap is required
• false - Remap is not required
Remarks
None.
5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library
5-449
5.1.9.7.4.25 DRV_SPI_POWER_STATE Macro
C
#define DRV_SPI_POWER_STATE SYS_MODULE_POWER_IDLE_STOP
Description
SPI power state configuration
This macro controls the power state of the SPI driver.
Remarks
This feature may not be available in the device or the SPI module selected.
5.1.9.7.4.26 DRV_SPI_PROTOCOL Macro
C
#define DRV_SPI_PROTOCOL DRV_SPI_PROTOCOL_TYPE_STANDARD
Description
SPI protocol type configuration
This macro controls the protocol type of the SPI driver.
Remarks
None.
5.1.9.7.4.27 DRV_SPI_USAGE_MODE Macro
C
#define DRV_SPI_USAGE_MODE DRV_SPI_MODE_MASTER
Description
SPI usage mode configuration
This macro controls the usage mode of the SPI driver.
Remarks
None.
5.1.9.7.4.28 DRV_SPI_BUFFER_EVENT Enumeration
C
typedef enum {
DRV_SPI_BUFFER_EVENT_PENDING,
DRV_SPI_BUFFER_EVENT_COMPLETE,
DRV_SPI_BUFFER_EVENT_ERROR
} DRV_SPI_BUFFER_EVENT;
Description
SPI Driver Buffer Events
This enumeration identifies the possible events that can result from a buffer add request caused by the client calling either the
DRV_NVM_BufferAddRead or DRV_NVM_BufferAddWrite functions.
5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library
5-450
Members
Members Description
DRV_SPI_BUFFER_EVENT_PENDING Buffer is pending to get processed
DRV_SPI_BUFFER_EVENT_COMPLETE All data from or to the buffer was transferred successfully.
DRV_SPI_BUFFER_EVENT_ERROR There was an error while processing the buffer transfer request.
Remarks
One of these values is passed in the "event" parameter of the event handling callback function that the client registered with the
driver by calling the DRV_NVM_BufferEventHandlerSet function when a buffer transfer request is completed.
5.1.9.7.4.29 DRV_SPI_BUFFER_EVENT_HANDLER Type
C
typedef void (* DRV_SPI_BUFFER_EVENT_HANDLER)(DRV_SPI_BUFFER_EVENT event,
DRV_SPI_BUFFER_HANDLE bufferHandle, uintptr_t context);
Description
SPI Driver Buffer Event Handler Function Pointer
This data type defines the required function signature for the SPI driver buffer event handling callback function. A client must
register a pointer to a buffer event handling function who's function signature (parameter and return value types) match the types
specified by this function pointer in order to receive buffer related event calls back from the driver.
The parameters and return values and return value are described here and a partial example implementation is provided.
Parameters
Parameters Description
event Identifies the type of event
bufferHandle Handle identifying the buffer to which the vent relates
context Value identifying the context of the application that registered the event handling
function.
Returns
None.
Remarks
If the event is DRV_SPI_BUFFER_EVENT_COMPLETE, it means that the data was transferred successfully.
If the event is DRV_SPI_BUFFER_EVENT_ERROR, it means that the data was not transferred successfully.
The bufferHandle parameter contains the buffer handle of the buffer that failed.
The context parameter contains the a handle to the client context, provided at the time the event handling function was
registered using the DRV_SPI_BufferEventHandlerSet function. This context handle value is passed back to the client as the
"context" parameter. It can be any value necessary to identify the client context or instance (such as a pointer to the client's data)
instance of the client that made the buffer add request.
The event handler function executes in an interrupt context when the driver is configured for interrupt mode operation. It is
recommended of the application to not perform process intensive operations with in this function.
Example
void APP_MyBufferEventHandler( DRV_SPI_BUFFER_EVENT event,
DRV_SPI_BUFFER_HANDLE bufferHandle,
uintptr_t context )
{
5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library
5-451
MY_APP_DATA_STRUCT pAppData = (MY_APP_DATA_STRUCT) context;
switch(event)
{
case DRV_SPI_BUFFER_EVENT_COMPLETE:
// Handle the completed buffer.
break;
case DRV_SPI_BUFFER_EVENT_ERROR:
default:
// Handle error.
break;
}
}
5.1.9.7.4.30 DRV_SPI_BUFFER_HANDLE Type
C
typedef uintptr_t DRV_SPI_BUFFER_HANDLE;
Description
SPI Driver Buffer Handle
A buffer handle value is returned by a call to the DRV_SPI_BufferAddRead()/ DRV_SPI_BufferAddWriteor
DRV_SPI_BufferAddReadWrite() functions. This handle is associated with the buffer passed into the function and it allows the
application to track the completion of the data from (or into) that buffer. The buffer handle value returned from the "buffer add"
function is returned back to the client by the "callback" function registered with the driver.
The buffer handle assigned to a client request expires when the client has been notified of the completion of the buffer transfer
(after event handler function that notifies the client returns) or after the buffer has been retired by the driver if no event handler
callback was set.
Remarks
None
5.1.9.7.4.31 DRV_SPI_BUFFER_TYPE Enumeration
C
typedef enum {
DRV_SPI_BUFFER_TYPE_STANDARD,
DRV_SPI_BUFFER_TYPE_ENHANCED
} DRV_SPI_BUFFER_TYPE;
Description
SPI Buffer Type Selection
This enumeration identifies the various buffer types of the SPI module.
Members
Members Description
DRV_SPI_BUFFER_TYPE_STANDARD SPI Buffer Type Standard
DRV_SPI_BUFFER_TYPE_ENHANCED SPI Enhanced Buffer Type
Remarks
None.
5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library
5-452
5.1.9.7.4.32 DRV_SPI_CLIENT_SETUP Type
C
typedef struct _DRV_SPI_CLIENT_SETUP DRV_SPI_CLIENT_SETUP;
Description
SPI Client Initialization Data
This structure lists the elements needed to set up an SPI client. Used by the function DRV_SPI_ClientSetup function. This data
type defines the data required to initialize an SPI client.
Remarks
None.
5.1.9.7.4.33 DRV_SPI_CLOCK_MODE Enumeration
C
typedef enum {
DRV_SPI_CLOCK_MODE_IDLE_LOW_EDGE_RISE,
DRV_SPI_CLOCK_MODE_IDLE_LOW_EDGE_FALL,
DRV_SPI_CLOCK_MODE_IDLE_HIGH_EDGE_FALL,
DRV_SPI_CLOCK_MODE_IDLE_HIGH_EDGE_RISE
} DRV_SPI_CLOCK_MODE;
Description
SPI Clock Mode Selection
This enumeration identifies the various clock modes of the SPI module.
Members
Members Description
DRV_SPI_CLOCK_MODE_IDLE_LOW_EDGE_RISE SPI Clock Mode 0 - Idle State Low & Sampling on Rising Edge
DRV_SPI_CLOCK_MODE_IDLE_LOW_EDGE_FALL SPI Clock Mode 1 - Idle State Low & Sampling on Falling Edge
DRV_SPI_CLOCK_MODE_IDLE_HIGH_EDGE_FALL SPI Clock Mode 2 - Idle State High & Sampling on Falling Edge
DRV_SPI_CLOCK_MODE_IDLE_HIGH_EDGE_RISE SPI Clock Mode 3 - Idle State High & Sampling on Rising Edge
Remarks
None.
5.1.9.7.4.34 DRV_SPI_INIT Type
C
typedef struct _DRV_SPI_INIT DRV_SPI_INIT;
Description
SPI Driver Initialization Data
This data type defines the data required to initialize or reinitialize the SPI driver. If the driver is built statically, the members of this
data structure are statically over-ridden by static override definitions in the system_config.h file.
Remarks
None.
5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library
5-453
5.1.9.7.4.35 DRV_SPI_MODE Enumeration
C
typedef enum {
DRV_SPI_MODE_MASTER,
DRV_SPI_MODE_SLAVE
} DRV_SPI_MODE;
Description
SPI Usage Modes Enumeration
This enumeration identifies the various usage modes of the SPI module.
Members
Members Description
DRV_SPI_MODE_MASTER SPI Mode Master
DRV_SPI_MODE_SLAVE SPI Mode Slave
Remarks
None.
5.1.9.7.4.36 DRV_SPI_PROTOCOL_TYPE Enumeration
C
typedef enum {
DRV_SPI_PROTOCOL_TYPE_STANDARD,
DRV_SPI_PROTOCOL_TYPE_FRAMED,
DRV_SPI_PROTOCOL_TYPE_AUDIO
} DRV_SPI_PROTOCOL_TYPE;
Description
SPI Protocols Enumeration
This enumeration identifies the various protocols of the SPI module.
Members
Members Description
DRV_SPI_PROTOCOL_TYPE_STANDARD SPI Protocol Type Standard
DRV_SPI_PROTOCOL_TYPE_FRAMED SPI Protocol Type Framed
DRV_SPI_PROTOCOL_TYPE_AUDIO SPi Protocol Type Audio
Remarks
None.
5.1.9.8 Files
Files
Name Description
drv_spi.h SPI device driver interface file.
drv_spi_config_template.h SPI Driver configuration definitions template.
5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library
5-454
Description
5.1.9.8.1 drv_spi.h
SPI Driver Interface
The SPI driver provides a simple interface to manage the SPI module. This file defines the interface definitions and prototypes
for the SPI driver.
Enumerations
Name Description
DRV_SPI_BUFFER_EVENT Identifies the possible events that can result from a buffer add request.
DRV_SPI_BUFFER_TYPE Identifies the various buffer types of the SPI module.
DRV_SPI_CLOCK_MODE Identifies the various clock modes of the SPI module.
DRV_SPI_MODE Identifies the various usage modes of the SPI module.
DRV_SPI_PROTOCOL_TYPE Identifies the various protocols of the SPI module.
Functions
Name Description
DRV_SPI_BufferAddRead Registers a buffer for a read operation. Actual transfer will happen in the Task
function.
DRV_SPI_BufferAddWrite Registers a buffer for a read operation. Actual transfer will happen in the Task
function.
DRV_SPI_BufferAddWriteRead Registers a buffer for a read operation. Actual transfer will happen in the Task
function.
DRV_SPI_BufferStatus Returns the transmitter and receiver transfer status.
DRV_SPI_ClientSetup Initializes a client.
DRV_SPI_Close Closes an opened instance of the SPI driver
DRV_SPI_Deinitialize De-initializes the specified instance of the SPI driver module.
DRV_SPI_Initialize Initializes the SPI driver.
DRV_SPI_Open Opens the specified SPI driver instance and returns a handle to it.
DRV_SPI_Read Gets/Reads byte(s) from SPI. The function will wait until the specified number of
bytes is received.
DRV_SPI_Status Provides the current status of the SPI driver module.
DRV_SPI_Tasks Maintains the driver's state machine and implements its ISR.
DRV_SPI_VersionGet Gets the SPI driver version in numerical format.
DRV_SPI_VersionStrGet Gets the SPI driver version in string format.
DRV_SPI_Write Writes the data to SPI. The function will wait until all the bytes are transmitted.
Macros
Name Description
DRV_SPI_BUFFER_HANDLE_INVALID Definition of an invalid buffer handle.
DRV_SPI_INDEX_0 SPI driver index definitions.
DRV_SPI_INDEX_1 This is macro DRV_SPI_INDEX_1.
DRV_SPI_INDEX_2 This is macro DRV_SPI_INDEX_2.
DRV_SPI_INDEX_3 This is macro DRV_SPI_INDEX_3.
DRV_SPI_INDEX_4 This is macro DRV_SPI_INDEX_4.
5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library
5-455
DRV_SPI_INDEX_5 This is macro DRV_SPI_INDEX_5.
DRV_SPI_INDEX_COUNT Number of valid SPI driver indices.
Types
Name Description
DRV_SPI_BUFFER_EVENT_HANDLER Pointer to a SPI Driver Buffer Event handler function
DRV_SPI_BUFFER_HANDLE Handle identifying a read or write buffer passed to the driver.
DRV_SPI_CLIENT_SETUP Defines the data required to initialize an SPI client.
DRV_SPI_INIT Defines the data required to initialize or reinitialize the SPI driver
File Name
drv_spi.h
Company
Microchip Technology Inc.
5.1.9.8.2 drv_spi_config_template.h
SPI Driver Configuration Definitions for the Template Version
These definitions statically define the driver's mode of operation.
Macros
Name Description
DRV_SPI_BAUD_RATE Controls the baud rate value of the SPI driver.
DRV_SPI_BAUD_RATE_CLOCK Selects the SPI baud rate clock.
DRV_SPI_BUFFER_SIZE This is macro DRV_SPI_BUFFER_SIZE.
DRV_SPI_BUFFER_USAGE_TYPE Controls the buffer type of the SPI driver.
DRV_SPI_CLIENTS_NUMBER Selects the miximum number of clients.
DRV_SPI_CLOCK_OPERATION_MODE Controls the clock mode of the SPI driver.
DRV_SPI_COMMUNICATION_WIDTH Controls the communication width of the SPI driver.
DRV_SPI_FRAME_SYNC_PULSE_COUNT Selects the SPI frame sync pulse count.
DRV_SPI_FRAME_SYNC_PULSE_DIRECTION Selects the SPI frame sync pulse direction.
DRV_SPI_FRAME_SYNC_PULSE_EDGE Selects the SPI frame sync pulse edge.
DRV_SPI_FRAME_SYNC_PULSE_POLARITY Selects the SPI frame sync pulse polarity.
DRV_SPI_FRAME_SYNC_PULSE_WIDTH Selects the SPI frame sync pulse width.
DRV_SPI_INDEX SPI static index selection.
DRV_SPI_INPUT_SAMPLE_PHASE Selects the SPI input sample phase.
DRV_SPI_INSTANCES_NUMBER Selects the maximum number of hardware instances that can be
supported by the dynamic driver .
DRV_SPI_INTERRUPT_MODE Controls operation of the driver in the interrupt or polled mode.
DRV_SPI_INTERRUPT_SOURCE_ERROR Defines the error interrupt source in case of static driver
DRV_SPI_INTERRUPT_SOURCE_RX Defines the receive interrupt source in case of static driver.
DRV_SPI_INTERRUPT_SOURCE_TX Defines the transmit/receive or transmit alone interrupt source in
case of static driver.
DRV_SPI_PERIPHERAL_ID SPI peripheral ID selection.
DRV_SPI_PORTS_REMAP_USAGE Selects the SPI pins remap.
DRV_SPI_POWER_STATE Controls the power state of the SPI driver.
5.1 Driver Library Help MPLAB Harmony Help SPI Driver Library
5-456
DRV_SPI_PROTOCOL Controls the protocol type of the SPI driver.
DRV_SPI_RX_FIFO_INTERRUPT_MODE This is macro DRV_SPI_RX_FIFO_INTERRUPT_MODE.
DRV_SPI_TX_FIFO_INTERRUPT_MODE This is macro DRV_SPI_TX_FIFO_INTERRUPT_MODE.
DRV_SPI_USAGE_MODE Controls the usage mode of the SPI driver.
File Name
drv_spi_config_template.h
Company
Microchip Technology Inc.
5.1.10 Timer Driver Library
5.1.10.1 Introduction
Timer Driver Library
for
Microchip Microcontrollers
This library provides an interface to manage the Timer module on the Microchip family of microcontrollers during different modes
of operation.
Description
Overview
Timers are useful for generating accurate time based periodic interrupts for software application or real time operating systems.
Other uses include counting external pulses or accurate timing measurement of external events using the timer's gate functions
and accurate hardware delays.
Please refer to the the Data Sheet for the part that is being used.
Note: Trademarks and Intellectual Property are property of their respective owners. Customers are responsible for obtaining
appropriate licensing or rights before using this software.
5.1.10.2 Release Notes
MPLAB Harmony Version: v0.70b Timer Driver Library Version : 0.02 Alpha Release Date: 18Nov2013
New This Release:
This is the first release of the library. The interface can change in the beta and\or 1.0 release.
Known Issues:
Nothing to report in this release.
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-457
5.1.10.3 SW License Agreement
© 2013 Microchip Technology Inc.
Microchip licenses this software to you solely for use with Microchip products. The software is owned by Microchip and its
licensors, and is protected under applicable copyright laws. All rights reserved.
SOFTWARE IS PROVIDED “AS IS.” MICROCHIP EXPRESSLY DISCLAIMS ANY WARRANTY OF ANY KIND, WHETHER
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL MICROCHIP BE LIABLE FOR
ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, HARM TO
YOUR EQUIPMENT, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS
BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR
CONTRIBUTION, OR OTHER SIMILAR COSTS.
To the fullest extent allowed by law, Microchip and its licensors liability shall not exceed the amount of fees, if any, that you have
paid directly to Microchip to use this software.
MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE TERMS.
5.1.10.4 Using the Library
This topic describes the basic architecture of the Timer Driver Library and provides information and examples on how to use it.
Interface Header File: drv_tmr.h
The interface to the Timer Driver Library is defined in the "drv_tmr.h" header file.
Please refer to the MPLAB Harmony Overview for how the driver interacts with the framework.
5.1.10.4.1 Abstraction Model
Microchip devices have two type of timers:
• Period-Match - When the counting timer matches the configured period, this timer is said to complete one iteration and an
interrupt is set
• Overflow - When the counting timer overflows/rolls over, interrupt is set and restarts from its previously set counter value. In
this case, the preset period value would be the maximum possible count value.
The Timer Driver abstracts this difference and provides a unified model for both of these types of timers.
Description
Abstraction Model
The abstraction model of the Timer Driver is explained in the following diagram:
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-458
The core functionality of the Timer allows access to both the counter and the period values.
The unified model allows user not to worry about whether the Timer currently being used is a overflow or period match-based.
The user simply updates the period and the driver automatically takes care of adjusting the respective Timer's periodicity. In case
a user needs any modification into the counter's initial value (i.e., to adjust for any errors in periodicity), they are allowed to do so
using the counter control interfaces.
5.1.10.4.2 Library Overview
Refer to the section Driver Overview for how the driver operates in a system.
The table below lists the interface section and its brief description.
Library Interface Section Description
Configuration Provides macros for configuring the system. It is required that the system configures
the driver to build correctly by choosing appropriate configuration options as listed in
this section. These macros enable different features or modes of the timer peripheral.
System Interaction Functions Provides interfaces to system layer to initialize, deinitialize and reinitialize the
module. This section also describes functions to query the status of the module.
Core Functions Provides interfaces for core functionality of the driver.
Alarm Functions Provides interfaces to handle alarm features, if alarm functionality is enabled.
Period Functions Provides interfaces to control the periodicity of the timers.
Counter Control Functions Provides interfaces to update the counter values.
Miscellaneous Functions Provides interfaces to get the version information, timer tick and operating
frequencies.
5.1.10.4.3 How the Library Works
The library provides interfaces to support:
• System Interaction
• Sync Mode Setup
• Period Modification
• Counter Modification
• Client Core Functionality
• Client Alarm Functionality (optional function, enabled using configuration options)
• Other Optional Functionality (enabled using configuration options)
Note: Any code segment pertaining to the driver interfaces will work for both the static or dynamic configurations. It is not
necessary to modify the code to move from one configuration to the other (i.e., from static or dynamic or static-multi).
5.1.10.4.3.1 System Interaction
This section describes Timer initialization and reinitialization.
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-459
Description
Initialization and Reinitialization
The system performs the initialization and the reinitialization of the device driver with settings that affect only the instance of the
device that is being initialized or re-initialized. During system initialization, each instance of the Timer module will be initialized
with the following configuration settings (either passed dynamically at run time using DRV_TMR_INIT or by using initialization
overrides) that are supported by the specific Timer module hardware:
Initialization
member
Configuration Name Description
moduleInit DRV_TMR_POWER_STATE System module initialization of the power state.
tmrId DRV_TMR_PERIPHERAL_ID Timer hardware module ID (peripheral library-level ID).
clockSource DRV_TMR_CLOCK_SOURCE Clock Source Selection, Enables either the internal or the external
clock, using one of the possible values from
TMR_CLOCK_SOURCE.
timerPeriod DRV_TMR_TIMER_PERIOD Timer period value.
prescale DRV_TMR_PRESCALE Sets up the prescaler, using one of the possible values from
TMR_PRESCALE.
sourceEdge DRV_TMR_SOURCE_EDGE Source edge selection, if supported by the hardware, selects either
the rising or falling edge, using one of the possible values from
TMR_CLOCK_SOURCE_EDGE.
postscale DRV_TMR_POSTSCALE Sets up the postscaler, if supported by the hardware, using one of
the possible values from TMR_POSTSCALE.
syncMode DRV_TMR_SYNCHRONIZATION_MODE Selects the operation mode of the instance using one of the
possible values from DRV_TMR_SYNC_MODE.
interruptSource DRV_TMR_INTERRUPT_SOURCE Interrupt source identifier for the Timer module being initialized,
which is available from the respective device's processor headers.
The DRV_TMR_Initialize function returns an object handle of the type SYS_MODULE_OBJ. After this, the object handle
returned by the Initialize interface would be used by the other system interfaces like DRV_TMR_Reinitialize,
DRV_TMR_Deinitialize, DRV_TMR_Status and DRV_TMR_Tasks.
Example: Timer Initialization Through DRV_TMR_INIT
DRV_TMR_INIT init;
SYS_MODULE_OBJ object;
SYS_STATUS tmrStatus;
// populate the TMR init configuration structure
init.moduleInit.value = SYS_MODULE_POWER_RUN_FULL;
init.tmrId = TMR_ID_2;
init.clockSource = TMR_CLOCK_SOURCE_PERIPHERAL_CLOCK;
init.prescale = TMR_PRESCALE_TX_VALUE_256;
init.syncMode = DRV_TMR_SYNC_MODE_SYNCHRONOUS_INTERNAL;
init.interruptSource = INT_SOURCE_TIMER_2;
init.timerPeriod = 0xABCD;
object = DRV_TMR_Initialize (DRV_TMR_INDEX_0, (SYS_MODULE_INIT *)&init);
tmrStatus = DRV_TMR_Status(object);
if ( SYS_STATUS_READY != tmrStatus)
{
// Handle error
}
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-460
Example: Timer initialization Through Configuration
Source file:
SYS_MODULE_OBJ object;
SYS_STATUS tmrStatus;
int main( void )
{
object = DRV_TMR_Initialize (DRV_TMR_INDEX_0, (SYS_MODULE_INIT *)NULL);
tmrStatus = DRV_TMR_Status(object);
if ( SYS_STATUS_READY != tmrStatus)
{
// Handle error
}
}
Configuration file: sys_config.h
#define DRV_TMR_POWER_STATE SYS_MODULE_POWER_RUN_FULL
#define DRV_TMR_PERIPHERAL_ID TMR_ID_3 // TMR_MODULE_ID
#define DRV_TMR_CLOCK_SOURCE TMR_CLOCK_SOURCE_PERIPHERAL_CLOCK
#define DRV_TMR_PRESCALE TMR_PRESCALE_TX_VALUE_256
#define DRV_TMR_SYNCHRONIZATION_MODE DRV_TMR_SYNC_MODE_SYNCHRONOUS_INTERNAL
#define DRV_TMR_INTERRUPT_SOURCE INT_SOURCE_TIMER_3
#define DRV_TMR_TIMER_PERIOD 0x0000F424 // 200ms
Deinitialization
Once the Initialize operation has been called, the Deinitialize operation must be called before the iIitialize operation can be called
again.This routine may block if the driver is running in an OS environment that supports blocking operations and the driver
requires system resources access. However, the routine will never block for hardware Timer access. If the operation requires
time to allow the hardware to complete, this will be reported by the DRV_TMR_Status operation.
Status
Timer status is available to query the module state before, during, and after initialization, deinitialization, and reinitialization.
Tasks Routine
The interface DRV_TMR_Tasks can be called in two ways:
• By the system task service in a polled environment
• By the interrupt service routine of the timer in an interrupt based system
Example: Polling
int main( void )
{
SYS_MODULE_OBJ object;
object = DRV_TMR_Initialize( DRV_TMR_INDEX_0, (SYS_MODULE_INIT *) &initConf );
if( SYS_STATUS_READY != DRV_TMR_Status( object ) )
return 0;
while (1)
{
DRV_TMR_Tasks (object);
}
}
Example: Interrupt
int main( void )
{
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-461
SYS_MODULE_OBJ object;
object = DRV_TMR_Initialize( DRV_TMR_INDEX_0, (SYS_MODULE_INIT *) &initConf );
if( SYS_STATUS_READY != DRV_TMR_Status( object ) )
return 0;
while (1);
}
/* Sample interrupt routine not specific to any device family */
void ISR T1Interrupt(void)
{
//Call the Timer Tasks routine
DRV_TMR_Tasks(object);
}
5.1.10.4.3.2 Client Interaction
This section describer general client operation.
Description
General Client Operation
For the application to begin using an instance of the Timer module, it must call the DRV_TMR_Open function. This provides the
configuration required to open the Timer instance for operation. If the driver is deinitialized using the function
DRV_TMR_Deinitialize, the application must call the DRV_TMR_Open function again to set up the instance of the Timer. The
function DRV_TMR_Open need not be called again if the system is reinitialized using the DRV_TMR_Reinitialize function.
The Timer Driver supports only the 'DRV_IO_INTENT_EXCLUSIVE' IO_INTENT.
Example:
DRV_HANDLE handle;
// Configure the instance DRV_TMR_INDEX_1 with the configuration
handle = DRV_TMR_Open(DRV_TMR_INDEX_1, DRV_IO_INTENT_EXCLUSIVE);
if( handle == DRV_HANDLE_INVALID )
{
// Client cannot open the instance.
}
The function DRV_TMR_Close closes an already opened instance of the Timer Driver, invalidating the handle. DRV_TMR_Open
must have been called to obtain a valid opened device handle.
Example:
DRV_HANDLE handle;
// Configure the instance DRV_TMR_INDEX_1 with the configuration
handle = DRV_TMR_Open(DRV_TMR_INDEX_1, DRV_IO_INTENT_EXCLUSIVE);
/*...*/
DRV_TMR_Close( handle );
The client has the option to check the status through the interface DRV_TMR_ClientStatus.
Example:
DRV_HANDLE handle;
// Configure the instance DRV_TMR_INDEX_1 with the configuration
handle = DRV_TMR_Open(DRV_TMR_INDEX_1, DRV_IO_INTENT_EXCLUSIVE);
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-462
if ( DRV_TMR_CLIENT_STATUS_READY != DRV_TMR_ClientStatus( handle ) )
return 0;
5.1.10.4.3.3 Sync Mode Selection
This section describes the Sync mode selection process.
Description
Sync Mode Selection
The Timer Driver can operate in various modes as described below. They can be changed using DRV_TMR_SyncModeSet, and
the current mode being using by the Timer can be retrieved using DRV_TMR_SyncModeGet/
DRV_TMR_SYNC_MODE_SYNCHRONOUS_INTERNAL - Synchronous Internal Clock Counter
• This mode can be used to provide the following capabilities:
• Create elapsed time measurements
• Create time delays
• Create periodic timer interrupts
• The input clock to the Timer is provided from the internal system clock
• The Timer increments in the effective delta time specified by the prescaler and the selected source clock
DRV_TMR_SYNC_MODE_SYNCHRONOUS_INTERNAL_GATED - Synchronous Internal Gated Counter
• In this mode, the operation is dependent on an external signal applied to a pin assigned as a gate. When the gate signal
remains high, the Timer increments. When the gate signal goes low, the operation terminates.
• Input clock to the timer is provided from the internal system clock
• The Timer increments in the effective delta time specified by the prescaler and the selected source clock
• Gated Timer mode is not possible when the Timer is set to use external clock source
DRV_TMR_SYNC_MODE_SYNCHRONOUS_EXTERNAL_WITHOUT_CLKSYNC - Synchronous External Clock Counter
• The Synchronous External Clock Counter operation provides the following capabilities:
• Counting periodic or non-periodic pulses
• Uses the external clock as the time base for Timers
• The selected Timer increments on every rising edge of the clock input on the TxCK pin
DRV_TMR_SYNC_MODE_SYNCHRONOUS_EXTERNAL_WITH_CLKSYNC - Synchronous External Clock Counter
• The clock source for the Timer is provided externally
• The selected Timer increments on every rising edge of the input on the TxCK pin
• External Clock sync is enabled to operate in the Synchronous mode
DRV_TMR_SYNC_MODE_ASYNCHRONOUS_EXTERNAL_WITHOUT_CLKSYNC - Asynchronous External Clock Counter
• The Asynchronous Timer operation provides the following capabilities:
• The Timer can operate during Sleep mode and can generate an interrupt on a period register match that will wake the
processor from Sleep or Idle modes.
• The Timer can be clocked from the secondary oscillator for real-time clock applications
• The clock source for the Timer is provided externally
• The selected Timer increments on every rising edge of the clock input on the TxCK pin
• Synchronization with the external clock is disabled
DRV_TMR_SYNC_MODE_ASYNCHRONOUS_EXTERNAL_WITH_CLKSYNC - Asynchronous External Clock Counter
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-463
• The clock source for the Timer is provided externally
• The selected Timer increments on every rising edge of the clock input on the TxCK pin
• Synchronization with the external clock is enabled
Changing the Sync Mode
Perform the following steps before changing the sync mode.
Preconditions: DRV_TMR_Open should have been called before calling this function and should have returned a valid handle.
1. Stop the TMR module using DRV_TMR_Stop.
2. Change the sync mode using DRV_TMR_SyncModeSet.
3. Update the counter using DRV_TMR_Counter[8Bit/16Bit/32Bit]Set, if applicable.
4. Start the TMR module using DRV_TMR_Start.
Example:
DRV_HANDLE handle;
/* Open the client */
handle = DRV_TMR_Open( DRV_TMR_INDEX_0, DRV_IO_INTENT_EXCLUSIVE );
/* Stop the timer */
DRV_TMR_Stop( handle );
/* Change the sync mode */
DRV_TMR_SyncModeSet( handle, DRV_TMR_SYNC_MODE_SYNCHRONOUS_INTERNAL );
/* Re-start the timer */
DRV_TMR_Start( handle );
Note: Not all modes are supported by all the Timer modules. Please refer the specific device data sheet to determine the
supported modes for your device.
5.1.10.4.3.4 Period Modification
This section describes Period modification for the different types of Timers (i.e., 8-/16-/32-bit).
Description
These set of functions help modify the Timer periodicity at the client level, regardless of whether it is an overflow or a period
match-based Timer.
This interface can be used to alter the already set periodicity at the system level interface DRV_TMR_Initialize.
Period Modification
Periodicity for the type of Timer (8-/16-/32-bit) can be controlled as follows:
• 8-bit timer periodicity can be modified using DRV_TMR_Period8BitSet and the current period value can be obtained using
DRV_TMR_Period8BitGet
• 16-bit timer periodicity can be modified using DRV_TMR_Period16BitSet and the current period value can be obtained using
DRV_TMR_Period16BitGet
• 32-bit timer periodicity can be modified using DRV_TMR_Period32BitSet and the current period value can be obtained using
DRV_TMR_Period32BitGet
Example:
DRV_HANDLE handle;
/* Open the client */
handle = DRV_TMR_Open( DRV_TMR_INDEX_0, DRV_IO_INTENT_EXCLUSIVE );
/* ... */
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-464
/* Update the new period */
DRV_TMR_Period16BitSet( handle, 0x0000C350);
5.1.10.4.3.5 Counter Modification
This section describes counter modification for the different types of Timers (i.e., 8-/16-/32-bit).
Description
These set of functions help modify the initial value of the Timer counters to help adjust any errors in the periodicity.
Counter Modification
Initial counter values can be controlled as follows:
• 8-bit timer initial value can be modified using DRV_TMR_Counter8BitSet and the current counter value can be obtained using
DRV_TMR_Counter8BitGet
• 16-bit timer initial value can be modified using DRV_TMR_Counter16BitSet and the current counter value can be obtained
using DRV_TMR_Counter16BitGet
• 32-bit timer initial value can be modified using DRV_TMR_Counter32BitSet and the current counter value can be obtained
using DRV_TMR_Counter32BitGet
Example:
DRV_HANDLE handle;
/* Open the client */
handle = DRV_TMR_Open( DRV_TMR_INDEX_0, DRV_IO_INTENT_EXCLUSIVE );
/* ... */
/* Update the counter value */
/* Following code updates the initial value from 0x0000 to 0x0010
to cover up any error in the previously set periodicity */
DRV_TMR_Counter16BitSet( handle, 0x0010);
5.1.10.4.3.6 Core Functionality
This section describes core functionality of the Timer Driver.
Description
Core functionality provides a extremely basic interface for the driver operation.
Applications using the core Timer core functionality, need to perform the following:
1. The system should have completed the necessary initialization and DRV_TMR_Tasks should either be running in a polled
environment, or in an interrupt environment.
2. Open the driver using DRV_TMR_Open. The Timer Driver supports exclusive access only.
3. The Timer period will have to be updated using DRV_TMR_Period[8Bit/16Bit/32Bit]Set if the client intends to override the
already preset value during the initialization. The previously set value can be retrieved using
DRV_TMR_Period[8Bit/16Bit/32Bit]Get.
4. Start the driver using DRV_TMR_Start.
5. Poll for the elapse status using DRV_TMR_ElapsedStatusGetAndClear and handle the rest of the processing based on the
status.
6. The client will be able to stop the started Timer instance using DRV_TMR_Stop at any time and will be able to close it using
DRV_TMR_Close when it is no longer required.
Example :
DRV_HANDLE handle;
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-465
/* Open the client */
handle = DRV_TMR_Open( DRV_TMR_INDEX_0, DRV_IO_INTENT_EXCLUSIVE );
while (1)
{
// Interrupt mode & hence the DRV_TMR_Tasks not being called
// client handle returned by the Open API
if (true == DRV_TMR_ElapsedStatusGetAndClear(handle))
{
// Do something
}
}
Notes:
1. The user needs to stop the Timer before any updates on the counter or period and restart it later.
2. The Timer elapsed status gets reset after any counter or period update.
3. The Timer elapse status remains unchanged if the user tries to stop and restart later.
5.1.10.4.3.7 Alarm Functionality
This section describes the Timer Driver alarm functionality.
Description
The Timer Driver provides alarm functionality. This is an optional advanced feature and needs to be enabled using the
configuration macros.
Applications using the Timer alarm functionality, need to perform the following:
1. The system should have completed the necessary initialization and DRV_TMR_Tasks should either be running in a polled
environment, or in an interrupt environment.
2. Open the driver using DRV_TMR_Open. The Timer Driver supports exclusive access only.
3. Configure the alarm using DRV_TMR_AlarmSet with DRV_TMR_ALARM_CONFIG.
4. Start the driver using DRV_TMR_Start.
5. If a callback is configured, the Timer Driver will call the callback function when the alarm expires.
6. The client will be able to stop the started Timer module instance using DRV_TMR_Stop at any time and will be able to close it
using DRV_TMR_Close when it is no longer required.
Precondition: For the callback to work, the switch DRV_TMR_ALARM_ENABLE needs to be defined in the configuration
header.
Example:
DRV_HANDLE handle;
DRV_TMR_ALARM_CONFIG alarmConfig;
uint32_t alarmCount;
/* Open the client */
handle = DRV_TMR_Open (DRV_TMR_INDEX_0, DRV_IO_INTENT_EXCLUSIVE);
/* Configure the timer alarm feature */
/* Callbacks are only allowed when the configuration switch
DRV_TMR_ALARM_ENABLE is defined */
alarmConfig.type = DRV_TMR_ALARM_TYPE_PERIODIC;
alarmConfig.callback = &Callback;
DRV_TMR_AlarmSet (handle, &alarmConfig);
// Get all the alarm counters based on the number of alarm objects configured
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-466
alarmCount = DRV_TMR_AlarmCountGet (handle);
// Clear the Alarm counters associated with the HW instance
DRV_TMR_AlarmCountClear (handle);
The callback function in the application will look like:
void Callback (void)
{
// Do something specific on an alarm event trigger
}
Note: The driver tasks function calls the client registered callback after the alarm expires.
5.1.10.4.3.8 Optional Interfaces
This section describes additional/optional client interfaces.
Description
Additional/Optional client interfaces include the following.
Get Operating Frequency
The function DRV_TMR_OperatingFrequencyGet provides the client with the information on the Timer operating frequency.
Example:
DRV_HANDLE handle;
uint32_t freq;
/* Open the client */
handle = DRV_TMR_Open (DRV_TMR_INDEX_0, DRV_IO_INTENT_EXCLUSIVE);
freq = DRV_TMR_OperatingFrequencyGet (handle);
Get Tick Frequency
The function DRV_TMR_TickFrequencyGet provides the client with the information on the Timer tick frequency.
Example:
DRV_HANDLE handle;
uint32_t freq;
/* Open the client */
handle = DRV_TMR_Open (DRV_TMR_INDEX_0, DRV_IO_INTENT_EXCLUSIVE);
freq = DRV_TMR_TickFrequencyGet (handle);
5.1.10.4.3.9 Example Usage of the Timer Driver
This section describes typical usage of the Timer Driver for various Timer modules in polling/interrupt advanced/core modes.
Description
Notes:
1. The interface calls remain the same whether using dynamic or static drivers.
2. There is a possibility that the user can pass NULL to the driver initialize interface. However, the respective configurations
matching the init [DRV_TMR_INIT] members need to be configured in the correct manner.
Example 1:
// Polling mode under 32-bit count mode for a PIC32 device using the alarm feature
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-467
SYS_MODULE_OBJ object;
// main
DRV_TMR_INIT init;
DRV_HANDLE handle;
DRV_TMR_ALARM_CONFIG alConf;
init.moduleInit.value = SYS_MODULE_POWER_RUN_FULL;
init.tmrId = TMR_ID_2;
init.clockSource = TMR_CLOCK_SOURCE_PERIPHERAL_CLOCK;
init.prescale = TMR_PRESCALE_TX_VALUE_256;
init.syncMode = DRV_TMR_SYNC_MODE_SYNCHRONOUS_INTERNAL;
init.interruptSource = INT_SOURCE_TIMER_3;
init.timerPeriod = 0xFF00;
object = DRV_TMR_Initialize (DRV_TMR_INDEX_0, (SYS_MODULE_INIT *)&init);
if ( SYS_STATUS_READY != DRV_TMR_Status(object))
return 0;
handle = DRV_TMR_Open (DRV_TMR_INDEX_0, DRV_IO_INTENT_EXCLUSIVE);
if ( DRV_TMR_STATUS_READY != DRV_TMR_ClientStatus(handle))
return 0;
alConf.alType = DRV_TMR_ALARM_TYPE_PERIODIC;
alConf.alCallback = &TestAlarmCallback;
DRV_TMR_AlarmSet (handle, &alConf);
DRV_TMR_Start (handle);
while (1)
{
DRV_TMR_Tasks (object);
}
DRV_TMR_Stop (handle);
DRV_TMR_Close (handle);
if ( DRV_TMR_STATUS_INVALID != DRV_TMR_ClientStatus(handle))
return 0;
DRV_TMR_Deinitialize (object);
// end main
void TestAlarmCallback (void)
{
// Do something specific on an alarm event trigger
}
Example 2:
// Polling mode under 16-bit count mode for a PIC32/PIC24 device using the alarm feature
SYS_MODULE_OBJ object;
// main
DRV_TMR_INIT init;
DRV_HANDLE handle;
DRV_TMR_ALARM_CONFIG alConf;
init.moduleInit.value = SYS_MODULE_POWER_RUN_FULL;
init.tmrId = TMR_ID_3;
init.clockSource = TMR_CLOCK_SOURCE_PERIPHERAL_CLOCK;
init.prescale = TMR_PRESCALE_TX_VALUE_256;
init.syncMode = DRV_TMR_SYNC_MODE_SYNCHRONOUS_INTERNAL;
init.interruptSource = INT_SOURCE_TIMER_3;
init.timerPeriod = 0xFF00;
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-468
object = DRV_TMR_Initialize (DRV_TMR_INDEX_0, (SYS_MODULE_INIT *)&init);
if ( SYS_STATUS_READY != DRV_TMR_Status(object))
return 0;
handle = DRV_TMR_Open (DRV_TMR_INDEX_0, DRV_IO_INTENT_EXCLUSIVE);
if ( DRV_TMR_STATUS_READY != DRV_TMR_ClientStatus(handle))
return 0;
alConf.alType = DRV_TMR_ALARM_TYPE_PERIODIC;
alConf.alCallback = &TestAlarmCallback;
DRV_TMR_AlarmSet (handle, &alConf);
DRV_TMR_Start (handle);
while (1)
{
DRV_TMR_Tasks (object);
}
DRV_TMR_Stop (handle);
DRV_TMR_Close (handle);
if ( DRV_TMR_STATUS_INVALID != DRV_TMR_ClientStatus(handle))
return 0;
DRV_TMR_Deinitialize (object);
// end main
void TestAlarmCallback (void)
{
// Do something specific on an alarm event trigger
}
Example 3:
// Polling mode under 16-bit count mode for a PIC18 device, with Timer3 using the alarm feature
SYS_MODULE_OBJ object;
// main
DRV_TMR_INIT init;
DRV_HANDLE handle;
DRV_TMR_ALARM_CONFIG alConf;
init.moduleInit.value = SYS_MODULE_POWER_RUN_FULL;
init.tmrId = TMR_ID_3;
init.clockSource = TMR_CLOCK_SOURCE_PERIPHERAL_CLOCK;
init.prescale = TMR_PRESCALE_T1_VALUE_8;
init.syncMode = DRV_TMR_SYNC_MODE_SYNCHRONOUS_INTERNAL;
init.interruptSource = INT_SOURCE_TIMER_3;
init.timerPeriod = 0xFF00;
object = DRV_TMR_Initialize (DRV_TMR_INDEX_0, (SYS_MODULE_INIT *)&init);
if ( SYS_STATUS_READY != DRV_TMR_Status(object))
return 0;
handle = DRV_TMR_Open (DRV_TMR_INDEX_0, DRV_IO_INTENT_EXCLUSIVE);
if ( DRV_TMR_STATUS_READY != DRV_TMR_ClientStatus(handle))
return 0;
alConf.alType = DRV_TMR_ALARM_TYPE_PERIODIC;
alConf.alCallback = &TestAlarmCallback;
DRV_TMR_AlarmSet (handle, &alConf);
DRV_TMR_Start (handle);
while (1)
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-469
{
DRV_TMR_Tasks (object);
}
DRV_TMR_Stop (handle);
DRV_TMR_Close (handle);
if ( DRV_TMR_STATUS_INVALID != DRV_TMR_ClientStatus(handle))
return 0;
DRV_TMR_Deinitialize (object);
// end main
void TestAlarmCallback (void)
{
// Do something specific on an alarm event trigger
}
Example 4:
// Interrupt mode under 32-bit count mode for a PIC32 device using the alarm feature
SYS_MODULE_OBJ object;
// main
DRV_TMR_INIT init;
DRV_HANDLE handle;
DRV_TMR_ALARM_CONFIG alConf;
SYS_INT_Initialize ();
init.moduleInit.value = SYS_MODULE_POWER_RUN_FULL;
init.tmrId = TMR_ID_2;
init.clockSource = TMR_CLOCK_SOURCE_PERIPHERAL_CLOCK;
init.prescale = TMR_PRESCALE_TX_VALUE_256;
init.syncMode = DRV_TMR_SYNC_MODE_SYNCHRONOUS_INTERNAL;
init.interruptSource = INT_SOURCE_TIMER_3;
init.timerPeriod = 0xFF00;
object = DRV_TMR_Initialize (DRV_TMR_INDEX_0, (SYS_MODULE_INIT *)&init);
if ( SYS_STATUS_READY != DRV_TMR_Status(object))
return 0;
handle = DRV_TMR_Open (DRV_TMR_INDEX_0, DRV_IO_INTENT_EXCLUSIVE);
if ( DRV_TMR_STATUS_READY != DRV_TMR_ClientStatus(handle))
return 0;
alConf.alType = DRV_TMR_ALARM_TYPE_PERIODIC;
alConf.alCallback = &TestAlarmCallback;
DRV_TMR_AlarmSet (handle, &alConf);
SYS_INT_PrioritySet (PLIB_INT_SOURCE_TIMER_3, PLIB_INT_PRIORITY_LEVEL1);
SYS_INT_SubprioritySet (PLIB_INT_SOURCE_TIMER_3, PLIB_INT_SUBPRIORITY_LEVEL1);
DRV_TMR_Start (handle);
while (1);
DRV_TMR_Stop (handle);
DRV_TMR_Close (handle);
if ( DRV_TMR_STATUS_INVALID != DRV_TMR_ClientStatus(handle))
return 0;
DRV_TMR_Deinitialize (object);
// end main
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-470
void TestAlarmCallback (void)
{
// Do something specific on an alarm event trigger
}
Example 5:
// Interrupt mode under 16-bit count mode for a PIC24 device using the alarm feature
SYS_MODULE_OBJ object;
// main
DRV_TMR_INIT init;
DRV_HANDLE handle;
DRV_TMR_ALARM_CONFIG alConf;
SYS_INT_Initialize ();
init.moduleInit.value = SYS_MODULE_POWER_RUN_FULL;
init.tmrId = TMR_ID_2;
init.clockSource = TMR_CLOCK_SOURCE_PERIPHERAL_CLOCK;
init.prescale = TMR_PRESCALE_TX_VALUE_256;
init.syncMode = DRV_TMR_SYNC_MODE_SYNCHRONOUS_INTERNAL;
init.interruptSource = INT_SOURCE_TIMER_2;
init.timerPeriod = 0xFF00;
object = DRV_TMR_Initialize (DRV_TMR_INDEX_0, (SYS_MODULE_INIT *)&init);
if ( SYS_STATUS_READY != DRV_TMR_Status(object))
return 0;
handle = DRV_TMR_Open (DRV_TMR_INDEX_0, DRV_IO_INTENT_EXCLUSIVE);
if ( DRV_TMR_STATUS_READY != DRV_TMR_ClientStatus(handle))
return 0;
alConf.alType = DRV_TMR_ALARM_TYPE_PERIODIC;
alConf.alCallback = &TestAlarmCallback;
DRV_TMR_AlarmSet (handle, &alConf);
SYS_INT_PrioritySet (PLIB_INT_SOURCE_TIMER_2, PLIB_INT_PRIORITY_LEVEL1);
DRV_TMR_Start (handle);
while (1);
DRV_TMR_Stop (handle);
DRV_TMR_Close (handle);
if ( DRV_TMR_STATUS_INVALID != DRV_TMR_ClientStatus(handle))
return 0;
DRV_TMR_Deinitialize (object);
//end main
void TestAlarmCallback (void)
{
// Do something specific on an alarm event trigger
}
Example 6:
// Polling mode under 32-bit count mode for a PIC32 device using core functionality
SYS_MODULE_OBJ object;
// main
DRV_TMR_INIT init;
DRV_HANDLE handle;
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-471
init.moduleInit.value = SYS_MODULE_POWER_RUN_FULL;
init.tmrId = TMR_ID_2;
init.clockSource = TMR_CLOCK_SOURCE_PERIPHERAL_CLOCK;
init.prescale = TMR_PRESCALE_TX_VALUE_256;
init.syncMode = DRV_TMR_SYNC_MODE_SYNCHRONOUS_INTERNAL;
init.interruptSource = INT_SOURCE_TIMER_3;
init.timerPeriod = 0xFF00;
object = DRV_TMR_Initialize (DRV_TMR_INDEX_0, (SYS_MODULE_INIT *)&init);
if ( SYS_STATUS_READY != DRV_TMR_Status(object))
return 0;
handle = DRV_TMR_Open (DRV_TMR_INDEX_0, DRV_IO_INTENT_EXCLUSIVE);
if ( DRV_TMR_STATUS_READY != DRV_TMR_ClientStatus(handle))
return 0;
DRV_TMR_Start (handle);
while (1)
{
DRV_TMR_Tasks (object);
if (true == DRV_TMR_ElapsedStatusGetAndClear(handle))
Callback();
}
DRV_TMR_Stop (handle);
DRV_TMR_Close (handle);
if ( DRV_TMR_STATUS_INVALID != DRV_TMR_ClientStatus(handle))
return 0;
DRV_TMR_Deinitialize (object);
// end main
void Callback (void)
{
// Do something specific
}
Example 7:
// Interrupt mode under 32-bit count mode for a PIC32 device using core functionality
SYS_MODULE_OBJ object;
// main
DRV_TMR_INIT init;
DRV_HANDLE handle;
DRV_TMR_ALARM_CONFIG alConf;
SYS_INT_Initialize ();
init.moduleInit.value = SYS_MODULE_POWER_RUN_FULL;
init.tmrId = TMR_ID_2;
init.clockSource = TMR_CLOCK_SOURCE_PERIPHERAL_CLOCK;
init.prescale = TMR_PRESCALE_TX_VALUE_256;
init.syncMode = DRV_TMR_SYNC_MODE_SYNCHRONOUS_INTERNAL;
init.interruptSource = INT_SOURCE_TIMER_3;
init.timerPeriod = 0xFF00;
object = DRV_TMR_Initialize (DRV_TMR_INDEX_0, (SYS_MODULE_INIT *)&init);
if ( SYS_STATUS_READY != DRV_TMR_Status(object))
return 0;
handle = DRV_TMR_Open (DRV_TMR_INDEX_0, DRV_IO_INTENT_EXCLUSIVE);
if ( DRV_TMR_STATUS_READY != DRV_TMR_ClientStatus(handle))
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-472
return 0;
SYS_INT_PrioritySet (PLIB_INT_SOURCE_TIMER_3, PLIB_INT_PRIORITY_LEVEL1);
SYS_INT_SubprioritySet (PLIB_INT_SOURCE_TIMER_3, PLIB_INT_SUBPRIORITY_LEVEL1);
DRV_TMR_Start (handle);
while (1)
{
if (true == DRV_TMR_ElapsedStatusGetAndClear(handle))
Callback();
}
DRV_TMR_Stop (handle);
DRV_TMR_Close (handle);
if ( DRV_TMR_STATUS_INVALID != DRV_TMR_ClientStatus(handle))
return 0;
DRV_TMR_Deinitialize (object);
// end main
void Callback (void)
{
// Do something specific
}
Example 8:
// Polling mode under 16-bit count mode for a PIC18 device, with Timer3 using core functionality
SYS_MODULE_OBJ object;
// main
DRV_TMR_INIT init;
DRV_HANDLE handle;
DRV_TMR_ALARM_CONFIG alConf;
init.moduleInit.value = SYS_MODULE_POWER_RUN_FULL;
init.tmrId = TMR_ID_3;
init.clockSource = TMR_CLOCK_SOURCE_PERIPHERAL_CLOCK;
init.prescale = TMR_PRESCALE_T1_VALUE_8;
init.syncMode = DRV_TMR_SYNC_MODE_SYNCHRONOUS_INTERNAL;
init.interruptSource = INT_SOURCE_TIMER_3;
init.timerPeriod = 0xFF00;
object = DRV_TMR_Initialize (DRV_TMR_INDEX_0, (SYS_MODULE_INIT *)&init);
if ( SYS_STATUS_READY != DRV_TMR_Status(object))
return 0;
handle = DRV_TMR_Open (DRV_TMR_INDEX_0, DRV_IO_INTENT_EXCLUSIVE);
if ( DRV_TMR_STATUS_READY != DRV_TMR_ClientStatus(handle))
return 0;
DRV_TMR_Start (handle);
while (1)
{
DRV_TMR_Tasks (object);
if (true == DRV_TMR_ElapsedStatusGetAndClear(handle))
Callback();
}
DRV_TMR_Stop (handle);
DRV_TMR_Close (handle);
if ( DRV_TMR_STATUS_INVALID != DRV_TMR_ClientStatus(handle))
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-473
return 0;
DRV_TMR_Deinitialize (object);
// end main
void Callback (void)
{
// Do something specific
}
5.1.10.5 Configuring the Library
The configuration of the Timer Device Library is based on the file sys_config.h
This header file contains the configuration selection for the Timer Driver Library build. Based on the selections made here and
the system setup, the Timer Driver driver may or may not support selected features. These configuration settings will apply to all
instances of the driver.
This header can be placed anywhere in the application-specific folders and the path of this header needs to be presented to the
include search for a successful build. Refer to the Applications Overview section for more details.
5.1.10.5.1 Initialization Overrides
Macros
Name Description
DRV_TMR_CLOCK_SOURCE Timer module clock source selection.
DRV_TMR_PERIPHERAL_ID Timer peripheral ID selection.
DRV_TMR_POSTSCALE Macro controls post scale of the TMR
DRV_TMR_PRESCALE Timer module prescale value.
DRV_TMR_SOURCE_EDGE Timer module source edge.
DRV_TMR_SYNCHRONIZATION_MODE Controls Synchronization mode of the Timer.
DRV_TMR_TIMER_PERIOD Timer period value for an overflow or a period match-based Timer.
Description
This section provides initialization overrides for the run time options that can be selected using DRV_TMR_INIT when passed
into DRV_TMR_Initialize and DRV_TMR_Reintiailize. When any of these options are defined, the build time override will be used.
5.1.10.5.1.1 DRV_TMR_CLOCK_SOURCE Macro
C
#define DRV_TMR_CLOCK_SOURCE TMR_CLOCK_SOURCE_PERIPHERAL_CLOCK
Description
TMR Clock Source
This macro selects the Timer module clock source based on the enumeration.
Remarks
If defined in the configuration, this takes priority over the initialization option.
Refer to the processor peripheral header for more information.
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-474
5.1.10.5.1.2 DRV_TMR_PERIPHERAL_ID Macro
C
#define DRV_TMR_PERIPHERAL_ID TMR_ID_1
Description
TMR Peripheral ID Selection
This macro selects the Timer peripheral ID. This is an intialization override of the tmrID member of the intialization configuration.
Remarks
Some devices also support TMR_ID_0.
5.1.10.5.1.3 DRV_TMR_POSTSCALE Macro
C
#define DRV_TMR_POSTSCALE TMR_POSTSCALE_1_TO_1
Description
TMR post scale configuration
This macro controls the post scale of the TMR
Remarks
This feature is not available in all modules/devices. Refer to the specific device data sheet for more information.
5.1.10.5.1.4 DRV_TMR_PRESCALE Macro
C
#define DRV_TMR_PRESCALE TMR_PRESCALE_TX_1_TO_256
Description
TMR Prescale
This macro defines the Timer module prescale value.
Remarks
If defined in the configuration, this takes priority over the initialization option.
Refer to the processor peripheral header for more information.
5.1.10.5.1.5 DRV_TMR_SOURCE_EDGE Macro
C
#define DRV_TMR_SOURCE_EDGE TMR_SOURCE_EDGE_INCREMENT_ON_LOW_TO_HIGH
Description
TMR Source Edge
This macro defines the Timer module source edge.
Remarks
If defined in the configuration, this takes priority over the initialization option.
Refer to the processor peripheral header for more information.
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-475
5.1.10.5.1.6 DRV_TMR_SYNCHRONIZATION_MODE Macro
C
#define DRV_TMR_SYNCHRONIZATION_MODE DRV_TMR_SYNC_MODE_SYNCHRONOUS_INTERNAL
Description
TMR Synchronization mode configuration
This macro controls the Synchronization mode of the Timer. It accepts one of the possible values of the enumeration
DRV_TMR_SYNC_MODE.
Remarks
If defined in the configuration, this takes priority over the initialization option.
5.1.10.5.1.7 DRV_TMR_TIMER_PERIOD Macro
C
#define DRV_TMR_TIMER_PERIOD 0x4567
Description
TMR period value
This macro defines the Timer period value for an overflow or a period match-based Timer.
Remarks
If defined in the configuration, this macro takes priority over the initialization option. In addition, the limit is the maximum possible
Timer count width.
The user is required to provide the count value. The driver will internally adjust the value as required for the Timer hardware
based on the overflow or period match functionality
5.1.10.5.2 System Config
Macros
Name Description
DRV_TMR_COUNT_WIDTH Controls the mode of the Timer.
DRV_TMR_INDEX Timer static index selection.
DRV_TMR_INDEX_0 Timer driver index definitions
DRV_TMR_INDEX_1 This is macro DRV_TMR_INDEX_1.
DRV_TMR_INDEX_2 This is macro DRV_TMR_INDEX_2.
DRV_TMR_INDEX_3 This is macro DRV_TMR_INDEX_3.
DRV_TMR_INDEX_4 This is macro DRV_TMR_INDEX_4.
DRV_TMR_INDEX_5 This is macro DRV_TMR_INDEX_5.
DRV_TMR_INDEX_COUNT Number of valid Timer driver indices.
DRV_TMR_INSTANCES_NUMBER Sets up the maximum number of hardware instances that can be supported
by the dynamic driver.
DRV_TMR_INTERRUPT_MODE Controls operation of the driver in the interrupt or polled mode.
Description
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-476
5.1.10.5.2.1 DRV_TMR_COUNT_WIDTH Macro
C
#define DRV_TMR_COUNT_WIDTH 16
Description
TMR mode configuration
This macro controls the mode of the Timer, and selects whether the timer is to support 8-bit, 16-bit or 32-bit mode. The
acceptable values of this configuration are:
• 8, (Use this for 8-bit timers)
• 16 (Use this for 16-bit timers)
• 32 (Use this for 32-bit timers)
Remarks
This is a mandatory configuration option, which enables the Timer count width.
5.1.10.5.2.2 DRV_TMR_INDEX Macro
C
#define DRV_TMR_INDEX DRV_TMR_INDEX_2
Description
TMR Static Index Selection
This definition selects the Timer Static Index for the driver object reference.
Remarks
This index is required to make a reference to the driver object.
5.1.10.5.2.3 DRV_TMR_INDEX_0 Macro
C
#define DRV_TMR_INDEX_0 0
Description
Timer Driver Module Index Numbers
These constants provide Timer driver index definitions.
Remarks
These constants should be used in place of hard-coded numeric literals.
These values should be passed into the DRV_TMR_Initialize and DRV_TMR_Open functions to identify the driver instance in
use.
5.1.10.5.2.4 DRV_TMR_INDEX_1 Macro
C
#define DRV_TMR_INDEX_1 1
Description
This is macro DRV_TMR_INDEX_1.
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-477
5.1.10.5.2.5 DRV_TMR_INDEX_2 Macro
C
#define DRV_TMR_INDEX_2 2
Description
This is macro DRV_TMR_INDEX_2.
5.1.10.5.2.6 DRV_TMR_INDEX_3 Macro
C
#define DRV_TMR_INDEX_3 3
Description
This is macro DRV_TMR_INDEX_3.
5.1.10.5.2.7 DRV_TMR_INDEX_4 Macro
C
#define DRV_TMR_INDEX_4 4
Description
This is macro DRV_TMR_INDEX_4.
5.1.10.5.2.8 DRV_TMR_INDEX_5 Macro
C
#define DRV_TMR_INDEX_5 5
Description
This is macro DRV_TMR_INDEX_5.
5.1.10.5.2.9 DRV_TMR_INDEX_COUNT Macro
C
#define DRV_TMR_INDEX_COUNT TMR_NUMBER_OF_MODULES
Description
Timer Driver Module Index Count
This constant identifies Timer driver index definitions.
Remarks
This constant should be used in place of hard-coded numeric literals.
This value is device-specific.
5.1.10.5.2.10 DRV_TMR_INSTANCES_NUMBER Macro
C
#define DRV_TMR_INSTANCES_NUMBER 1
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-478
Description
Hardware instances support
This definition sets up the maximum number of hardware instances that can be supported by the dynamic driver.
Remarks
None
5.1.10.5.2.11 DRV_TMR_INTERRUPT_MODE Macro
C
#define DRV_TMR_INTERRUPT_MODE true
Description
TMR Interrupt And Polled Mode Operation Control
This macro controls the operation of the driver in the interrupt mode of operation. The possible values of this macro are:
• true - Select if interrupt mode of timer operation is desired
• false - Select if polling mode of timer operation is desired
Not defining this option to true or false will result in a build error.
Remarks
None.
5.1.10.5.3 Alarm Config
Macros
Name Description
DRV_TMR_ALARM_ENABLE Enables alarm functionality.
DRV_TMR_ALARM_PERIODIC Alarm type configuration.
Description
5.1.10.5.3.1 DRV_TMR_ALARM_ENABLE Macro
C
#define DRV_TMR_ALARM_ENABLE
Description
Alarm feature configuration option
This feature enables the alarm functionality inside the Timer driver.
Remarks
This is an optional feature. If the user wants to be called after a time elapse, alarm callback registration is mandatory.
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-479
5.1.10.5.3.2 DRV_TMR_ALARM_PERIODIC Macro
C
#define DRV_TMR_ALARM_PERIODIC true
Description
Alarm type configuration option
This macro if defined, makes the alarm periodic. This macro can accept the following values:
• true - Configures the alarm in periodic mode
• false - Configures the alarm in one shot mode
Remarks
This is an optional feature, which is enabled when using this configuration.
5.1.10.5.4 Client Config
Macros
Name Description
DRV_TMR_CLIENTS_NUMBER Selects the maximum number of clients
Description
5.1.10.5.4.1 DRV_TMR_CLIENTS_NUMBER Macro
C
#define DRV_TMR_CLIENTS_NUMBER 1
Description
Client support
This definition select the maximum number of clients that the Timer driver can support at run time.
Remarks
None.
5.1.10.5.5 Miscellaneous Config
Macros
Name Description
DRV_TMR_ASYNC_WRITE_ENABLE Controls Asynchronous Write mode of the Timer.
DRV_TMR_PRESCALER_ENABLE Controls prescaler assignment of the Timer.
Description
These configuration options control the functionality and setup of the Timer Driver.
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-480
5.1.10.5.5.1 DRV_TMR_ASYNC_WRITE_ENABLE Macro
C
#define DRV_TMR_ASYNC_WRITE_ENABLE false
Description
TMR Asynchronous write mode configuration
This macro controls the Asynchronous Write mode of the Timer. This macro accepts the following values:
• true - Configures the Timer to enable async write control
• false - Configures the Timer to disable async write control
• DRV_CONFIG_NOT_SUPPORTED - When the feature is not supported on the instance.
Remarks
This feature is not available in all modules/devices. Refer to the specific device data sheet for more information.
5.1.10.5.5.2 DRV_TMR_PRESCALER_ENABLE Macro
C
#define DRV_TMR_PRESCALER_ENABLE false
Description
TMR prescaler assignment configuration
This macro controls the prescaler assignment of the TMR. This macro accepts the following values:
• true - Configures the Timer for enable prescaler assignment
• false - Configures the Timer for disable prescaler assignment
• DRV_CONFIG_NOT_SUPPORTED - When the feature is not supported on the instance
Remarks
This feature is not available in all modules/devices. Refer to the specific device data sheet for more information.
5.1.10.5.6 Alarm Functionality Examples
Files
Name Description
drv_tmr_config_alarm.h Timer driver configuration definitions for the alarm feature.
Description
5.1.10.5.6.1 drv_tmr_config_alarm.h
TMR Driver Configuration Definitions for Alarm feature
These definitions set up the driver for the alarm feature.
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-481
File Name
drv_tmr_config_alarm.h
Company
Microchip Technology Inc.
5.1.10.6 Building the Library
This section list the files that are available in the \src of the timer driver. It lists which files need to be included in the build based
on either a hardware feature present on the board or configuration option selected by the system.
5.1.10.7 Library Interface
Data Types and Constants
Name Description
DRV_TMR_ALARM_CONFIG Timer module alarm configuration.
DRV_TMR_ALARM_TYPE Timer driver type enumeration.
DRV_TMR_CALLBACK Pointer to a Timer driver callback function data type.
DRV_TMR_CLIENT_STATUS Identifies the client-specific status of the Timer driver
DRV_TMR_INIT Defines the Timer driver initialization data.
DRV_TMR_SYNC_MODE Identifies the synchronous modes for the Timer driver.
Macros
Name Description
DRV_TMR_INTERRUPT_SOURCE Defines the interrupt source of the static driver.
DRV_TMR_POWER_STATE Controls the power state of the Timer.
DRV_TMR_UNIFIED Sets up the driver functionlity in either split or the unified mode.
Alarm Functions
Name Description
DRV_TMR_AlarmCountClear Clears the alarm elapse counter.
DRV_TMR_AlarmCountGet Provides the number of times the alarm has elapsed since the last time it was
cleared.
DRV_TMR_AlarmSet Initializes an alarm.
Core Functions
Name Description
DRV_TMR_ClientStatus Gets current client-specific status of the Timer driver.
DRV_TMR_Close Closes an opened instance of the Timer driver
DRV_TMR_ElapsedStatusGetAndClear Provides and clears the Timer's elapse count.
DRV_TMR_Open Opens the specified Timer driver instance and returns a handle to it.
DRV_TMR_Start Starts the Timer counting.
DRV_TMR_Stop Stops the Timer from counting.
DRV_TMR_SyncModeGet Provides the Timer's current synchronization mode.
DRV_TMR_SyncModeSet Changes the Timer's synchronization mode.
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-482
Counter Control Functions
Name Description
DRV_TMR_Counter16BitGet Provides the 16-bit Timer's current counter value.
DRV_TMR_Counter16BitSet Updates the 16-bit Timer's initial count value.
DRV_TMR_Counter32BitGet Provides the 32-bit Timer's current counter value.
DRV_TMR_Counter32BitSet Updates the 32-bit Timer's initial count value.
DRV_TMR_Counter8BitGet Provides the 8-bit Timer's current counter value.
DRV_TMR_Counter8BitSet Updates the 8-bit Timer's initial count value
Miscellaneous Functions
Name Description
DRV_TMR_OperatingFrequencyGet Provides the Timer operating frequency.
DRV_TMR_TickFrequencyGet Provides the Timer's counter "tick" frequency.
DRV_TMR_VersionGet Gets the Timer driver version in numerical format.
DRV_TMR_VersionStrGet Gets the Timer driver version in string format.
Period Functions
Name Description
DRV_TMR_Period16BitGet Provides the 16-bit Timer's period
DRV_TMR_Period16BitSet Updates the 16-bit Timer's period.
DRV_TMR_Period32BitGet Provides the 32-bit Timer's period
DRV_TMR_Period32BitSet Updates the 32-bit Timer's period.
DRV_TMR_Period8BitGet Provides the 8-bit Timer's period.
DRV_TMR_Period8BitSet Updates the 8-bit timer's period
System Interaction Functions
Name Description
DRV_TMR_Deinitialize Deinitializes the specified instance of the Timer driver.
DRV_TMR_Initialize Initializes the Timer driver .
DRV_TMR_Reinitialize Reinitializes the driver and refreshes any associated hardware settings.
DRV_TMR_Status Provides the current status of the Timer driver.
DRV_TMR_Tasks Maintains the driver's state machine and implements its ISR.
Description
This section describes the functions of the Timer Driver Library.
Refer to each section for a detailed description.
5.1.10.7.1 System Interaction Functions
5.1.10.7.1.1 DRV_TMR_Deinitialize Function
C
void DRV_TMR_Deinitialize(
SYS_MODULE_OBJ object
);
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-483
Description
Deinitializes the specified instance of the Timer driver, disabling its operation (and any hardware). All internal data is invalidated.
Preconditions
The DRV_TMR_Initialize function must have been called before calling this function and a valid SYS_MODULE_OBJ must have
been returned.
Parameters
Parameters Description
object Driver object handle, returned from DRV_TMR_Initialize
Returns
None.
Remarks
Once the Initialize operation has been called, the Deinitialize operation must be called before the Initialize operation can be
called again.
This function will NEVER block waiting for hardware. If the operation requires time to allow the hardware to complete, this will be
reported by the DRV_TMR_Status operation. The system has to use DRV_TMR_Status to find out when the module is in the
ready state.
Example
SYS_MODULE_OBJ object; // Returned from DRV_TMR_Initialize
SYS_STATUS status;
DRV_TMR_Deinitialize(object);
status = DRV_TMR_Status(object);
if (SYS_MODULE_DEINITIALIZED == status)
{
// Check again later if you need to know
// when the driver is deinitialized.
}
5.1.10.7.1.2 DRV_TMR_Initialize Function
C
SYS_MODULE_OBJ DRV_TMR_Initialize(
const SYS_MODULE_INDEX drvIndex,
const SYS_MODULE_INIT * const init
);
Description
This function initializes the Timer driver, making it ready for clients to open and use it.
Preconditions
None.
Parameters
Parameters Description
drvIndex Index for the driver instance to be initialized
init Pointer to a data structure containing any data necessary to initialize the driver.
This pointer may be null if the user wants to provide the information via the
respective configuration macros.
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-484
Returns
If successful, returns a valid handle to a driver object. Otherwise, it returns SYS_MODULE_OBJ_INVALID. The returned object
must be passed as argument to DRV_TMR_Reinitialize, DRV_TMR_Deinitialize, DRV_TMR_Tasks and DRV_TMR_Status
functions.
Remarks
This function must be called before any other Timer function is called.
This function should only be called once during system initialization unless DRV_TMR_Deinitialize is called to deinitialize the
driver instance.
This function will NEVER block for hardware access. If the operation requires time to allow the hardware to reinitialize, it will be
reported by the DRV_TMR_Status operation. The system must use DRV_TMR_Status to find out when the driver is in the ready
state.
Build configuration options may be used to staticaly override options in the "init" sructure and will take precedance over
initialization data passed using this function.
Example
DRV_TMR_INIT init;
SYS_MODULE_OBJ objectHandle;
// Populate the timer initialization structure
init.moduleInit.value = SYS_MODULE_POWER_RUN_FULL;
init.tmrId = TMR_ID_2;
init.clockSource = TMR_CLOCK_SOURCE_PERIPHERAL_CLOCK;
init.prescale = TMR_PRESCALE_TX_VALUE_256;
init.syncMode = DRV_TMR_SYNC_MODE_SYNCHRONOUS_INTERNAL;
init.interruptSource = INT_SOURCE_TIMER_2;
init.timerPeriod = 0xABCD;
// Do something
objectHandle = DRV_TMR_Initialize(DRV_TMR_INDEX_0, (SYS_MODULE_INIT*)&init);
if (SYS_MODULE_OBJ_INVALID == objectHandle)
{
// Handle error
}
5.1.10.7.1.3 DRV_TMR_Reinitialize Function
C
void DRV_TMR_Reinitialize(
SYS_MODULE_OBJ object,
const SYS_MODULE_INIT* const init
);
Description
This function reinitializes the driver and refreshes any associated hardware settings using the initialization data given, but it will
not interrupt any ongoing operations.
Preconditions
The DRV_TMR_Initialize function must have been called before calling this function and a valid SYS_MODULE_OBJ must have
been returned.
Parameters
Parameters Description
object Driver object handle, returned from DRV_TMR_Initialize
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-485
init Pointer to the initialization data structure
Returns
None
Remarks
This function can be called multiple times to reinitialize the module.
This operation can be used to refresh any supported hardware registers as specified by the initialization data or to change the
power state of the module.
This function will NEVER block for hardware access. If the operation requires time to allow the hardware to reinitialize, it will be
reported by the DRV_TMR_Status operation. The system must use DRV_TMR_Status to find out when the driver is in the ready
state.
Build configuration options may be used to staticaly override options in the "init" sructure and will take precedance over
initialization data passed using this function.
Example
DRV_TMR_INIT init;
SYS_MODULE_OBJ objectHandle; // Returned from DRV_TMR_Initialize
SYS_STATUS tmrStatus;
// Iopulate the timer initialization structure
init.moduleInit.value = SYS_MODULE_POWER_RUN_FULL;
init.tmrId = TMR_ID_2;
init.clockSource = TMR_CLOCK_SOURCE_PERIPHERAL_CLOCK;
init.prescale = TMR_PRESCALE_TX_VALUE_256;
init.syncMode = DRV_TMR_SYNC_MODE_SYNCHRONOUS_INTERNAL;
init.interruptSource = INT_SOURCE_TIMER_3;
init.timerPeriod = 0xABCD;
DRV_TMR_Reinitialize(objectHandle, (SYS_MODULE_INIT*)&init);
tmrStatus = DRV_TMR_Status(object);
if (SYS_STATUS_BUSY == tmrStatus)
{
// Check again later to ensure the driver is ready
}
else if (SYS_STATUS_ERROR >= tmrStatus)
{
// Handle error
}
5.1.10.7.1.4 DRV_TMR_Status Function
C
SYS_STATUS DRV_TMR_Status(
SYS_MODULE_OBJ object
);
Description
This function provides the current status of the Timer driver.
Preconditions
The DRV_TMR_Initialize functino must have been called before calling this function.
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-486
Parameters
Parameters Description
object Driver object handle, returned from DRV_TMR_Initialize
Returns
SYS_STATUS_READY - Indicates that the driver is busy with a previous system level operation and cannot start another
Remarks
Any value greater than SYS_STATUS_READY is also a normal running state in which the driver is ready to accept new
operations.
SYS_STATUS_BUSY - Indicates that the driver is busy with a previous system level operation and cannot start another
SYS_STATUS_ERROR - Indicates that the driver is in an error state
Any value less than SYS_STATUS_ERROR is also an error state.
SYS_MODULE_DEINITIALIZED - Indicates that the driver has been deinitialized
This value is less than SYS_STATUS_ERROR.
The this operation can be used to determine when any of the driver's module level operations has completed.
If the status operation returns SYS_STATUS_BUSY, the a previous operation has not yet completed. Once the status operation
returns SYS_STATUS_READY, any previous operations have completed.
The value of SYS_STATUS_ERROR is negative (-1). Any value less than that is also an error state.
This function will NEVER block waiting for hardware.
If the Status operation returns an error value, the error may be cleared by calling the reinitialize operation. If that fails, the
deinitialize operation will need to be called, followed by the initialize operation to return to normal operations.
Example
SYS_MODULE_OBJ object; // Returned from DRV_TMR_Initialize
SYS_STATUS tmrStatus;
tmrStatus = DRV_TMR_Status(object);
else if (SYS_STATUS_ERROR >= tmrStatus)
{
// Handle error
}
5.1.10.7.1.5 DRV_TMR_Tasks Function
C
void DRV_TMR_Tasks(
SYS_MODULE_OBJ object
);
Description
This function is used to maintain the driver's internal state machine and implement its ISR for interrupt-driven implementations.
Preconditions
The DRV_TMR_Initialize function must have been called for the specified Timer driver instance.
Parameters
Parameters Description
object Object handle for the specified driver instance (returned from DRV_TMR_Initialize)
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-487
Returns
None
Remarks
This function is normally not called directly by an application. It is called by the system's Tasks routine (SYS_Tasks) or by the
appropriate raw ISR.
This function may excute in an ISR context and will never block or access any resources that may cause it to block.
Example
SYS_MODULE_OBJ object; // Returned from DRV_TMR_Initialize
while (true)
{
DRV_TMR_Tasks (object);
// Do other tasks
}
5.1.10.7.2 Core Functions
5.1.10.7.2.1 DRV_TMR_ClientStatus Function
C
DRV_TMR_CLIENT_STATUS DRV_TMR_ClientStatus(
DRV_HANDLE handle
);
Description
This function gets the client-specfic status of the Timer driver associated with the specified handle.
Preconditions
The DRV_TMR_Initialize function must have been called.
DRV_TMR_Open must have been called to obtain a valid opened device handle.
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open routine
Returns
A DRV_TMR_CLIENT_STATUS value describing the current status of the driver
Remarks
This function will not block for hardware access and will immediately return the current status.
Example
DRV_HANDLE handle; // Returned from DRV_TMR_Open
DRV_TMR_CLIENT_STATUS tmrClientStatus;
tmrClientStatus = DRV_TMR_ClientStatus(tmrHandle);
if(DRV_TMR_CLIENT_STATUS_ERROR >= tmrClientStatus)
{
// Handle the error
}
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-488
5.1.10.7.2.2 DRV_TMR_Close Function
C
void DRV_TMR_Close(
DRV_HANDLE handle
);
Description
This function closes an opened instance of the Timer driver, invalidating the handle.
Preconditions
The DRV_TMR_Initialize function must have been called for the specified Timer driver instance.
DRV_TMR_Open must have been called to obtain a valid opened device handle.
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open routine
Returns
None
Remarks
After calling this function, the handle passed in "handle" must not be used with any of the remaining driver functions. A new
handle must be obtained by calling DRV_TMR_Open before the caller may use the driver again.
If DRV_IO_INTENT_BLOCKING was requested and the driver was built appropriately to support blocking behavior, the call may
block until the operation is complete.
If DRV_IO_INTENT_NON_BLOCKING request the driver client can call the DRV_TMR_Status operation to find out when the
module is in the ready state (the handle is no longer valid).
Usually there is no need for the driver client to verify that the Close operation has completed.
Example
DRV_HANDLE handle; // Returned from DRV_TMR_Open
DRV_TMR_Close(handle);
5.1.10.7.2.3 DRV_TMR_ElapsedStatusGetAndClear Function
C
bool DRV_TMR_ElapsedStatusGetAndClear(
DRV_HANDLE handle
);
Description
This function provides the Timer's elapse count and resets it to zero (0).
Preconditions
The DRV_TMR_Initialize function must have been called.
DRV_TMR_Open must have been called to obtain a valid opened device handle.
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-489
Parameters
Parameters Description
handle A valid handle, returned from the DRV_TMR_Open
Returns
• true - The Timer has elapsed
• false - The Timer has not yet elapsed
Remarks
None.
Example
DRV_HANDLE handle; // Returned from DRV_TMR_Open
bool elapseStatus;
elapseStatus = DRV_TMR_ElapsedStatusGetAndClear(handle);
if (elapseStatus > 0)
{
// The counter period has elapsed.
}
5.1.10.7.2.4 DRV_TMR_Open Function
C
DRV_HANDLE DRV_TMR_Open(
const SYS_MODULE_INDEX drvIndex,
const DRV_IO_INTENT intent
);
Description
This function opens the specified Timer driver instance and provides a handle that must be provided to all other client-level
operations to identify the caller and the instance of the driver.
Preconditions
The DRV_TMR_Initialize functino must have been called before calling this function.
Parameters
Parameters Description
drvIndex Identifier for the object instance to be opened
intent Zero or more of the values from the enumeration DRV_IO_INTENT ORed together
to indicate the intended use of the driver
Returns
If successful, the function returns a valid open instance handle (a number identifying both the caller and the module instance).
If an error occurs, the return value is DRV_HANDLE_INVALID.
Remarks
The handle returned is valid until the DRV_TMR_Close function is called.
This function will NEVER block waiting for hardware.
If the DRV_IO_INTENT_BLOCKING is requested and the driver was built appropriately to support blocking behavior, other
client-level operations may block waiting on hardware until they are complete.
If DRV_IO_INTENT_NON_BLOCKING is requested the driver client can call the DRV_TMR_ClientStatus operation to find out
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-490
when the module is in the ready state.
If the requested intent flags are not supported, the function will return DRV_HANDLE_INVALID.
The Timer driver does not support DRV_IO_INTENT_SHARED. It must be opened with DRV_IO_INTENT_EXCLUSIVE in the
"intent" parameter.
Example
DRV_HANDLE handle;
handle = DRV_TMR_Open(DRV_TMR_INDEX_0, DRV_IO_INTENT_EXCLUSIVE);
if (DRV_HANDLE_INVALID == handle)
{
// Unable to open the driver
}
5.1.10.7.2.5 DRV_TMR_Start Function
C
void DRV_TMR_Start(
DRV_HANDLE handle
);
Description
This function starts the Timer counting.
Preconditions
The DRV_TMR_Initialize function must have been called.
DRV_TMR_Open must have been called to obtain a valid opened device handle.
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open routine
Returns
None.
Remarks
None.
Example
DRV_HANDLE handle; // Returned from DRV_TMR_Open
DRV_TMR_Start (handle);
5.1.10.7.2.6 DRV_TMR_Stop Function
C
void DRV_TMR_Stop(
DRV_HANDLE handle
);
Description
This function stops the running Timer from counting.
Preconditions
The DRV_TMR_Initialize function must have been called.
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-491
DRV_TMR_Open must have been called to obtain a valid opened device handle.
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open routine
Returns
None.
Remarks
None.
Example
DRV_HANDLE handle; // Returned from DRV_TMR_Open
DRV_TMR_Stop(handle);
5.1.10.7.2.7 DRV_TMR_SyncModeGet Function
C
DRV_TMR_SYNC_MODE DRV_TMR_SyncModeGet(
DRV_HANDLE handle
);
Description
This function provides the Timer's current synchronization mode.
Preconditions
The DRV_TMR_Initialize function must have been called.
DRV_TMR_Open must have been called to obtain a valid opened device handle.
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open routine
Returns
Possible values from the enumeration DRV_TMR_SYNC_MODE.
Remarks
None.
Example
DRV_HANDLE handle; // Returned from DRV_TMR_Open
DRV_TMR_SYNC_MODE mode;
mode = DRV_TMR_SyncModeGet(handle);
5.1.10.7.2.8 DRV_TMR_SyncModeSet Function
C
void DRV_TMR_SyncModeSet(
DRV_HANDLE handle,
DRV_TMR_SYNC_MODE newMode
);
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-492
Description
This function changes the Timer's synchronization mode.
Preconditions
The DRV_TMR_Initialize function must have been called.
DRV_TMR_Open must have been called to obtain a valid opened device handle.
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open routine
mode Possible values from the enumeration DRV_TMR_SYNC_MODE
Returns
None.
Remarks
The caller should stop the Timer/Counter before changing the synchronization mode and restart it afterward.
Example
DRV_HANDLE handle; // Returned from DRV_TMR_Open
DRV_TMR_Stop(handle);
DRV_TMR_SyncModeSet(handle, DRV_TMR_SYNC_MODE_SYNCHRONOUS_INTERNAL);
5.1.10.7.3 Alarm Functions
5.1.10.7.3.1 DRV_TMR_AlarmCountClear Function
C
void DRV_TMR_AlarmCountClear(
DRV_HANDLE handle
);
Description
This function clears the alarm elapse counter.
Preconditions
The DRV_TMR_Initialize function must have been called.
DRV_TMR_Open must have been called to obtain a valid opened device handle.
Parameters
Parameters Description
handle A valid handle, returned from DRV_TMR_Open
Returns
None.
Remarks
None.
Example
DRV_HANDLE handle; // Returned from DRV_TMR_Open
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-493
DRV_TMR_AlarmCountClear(handle);
5.1.10.7.3.2 DRV_TMR_AlarmCountGet Function
C
unsigned int DRV_TMR_AlarmCountGet(
DRV_HANDLE handle
);
Description
This function provides the number of times the alarm is generated since the last time it was cleared.
Preconditions
The DRV_TMR_Initialize function must have been called.
DRV_TMR_Open must have been called to obtain a valid opened device handle.
Parameters
Parameters Description
handle A valid handle, returned from DRV_TMR_Open
Returns
Alarm count value.
Remarks
None.
Example
DRV_HANDLE handle; // Returned from DRV_TMR_Open
unsigned int alarmCount;
alarmCount = DRV_TMR_AlarmCountGet (handle);
5.1.10.7.3.3 DRV_TMR_AlarmSet Function
C
void DRV_TMR_AlarmSet(
DRV_HANDLE handle,
const DRV_TMR_ALARM_CONFIG * config
);
Description
This function initializes an alarm, allowing the client to receive a callback from the driver when the counter period elapses.
Alarms can be one-shot or periodic.
Preconditions
The DRV_TMR_Initialize function must have been called.
DRV_TMR_Open must have been called to obtain a valid opened device handle.
Parameters
Parameters Description
handle A valid handle, returned from DRV_TMR_Open
config Pointer to the alarm configuration structure containing any data necessary to
initialize timer alarms
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-494
Returns
None
Remarks
None.
Example
DRV_HANDLE handle; // Returned from DRV_TMR_Open
DRV_TMR_ALARM_CONFIG alarmConfig;
alarmConfig.type = DRV_TMR_ALARM_TYPE_PERIODIC; // Periodic Alarm
alarmConfig.callback = &callBackFunction; // callback registered
DRV_TMR_AlarmSet(handle, config);
5.1.10.7.4 Period Functions
5.1.10.7.4.1 DRV_TMR_Period16BitGet Function
C
uint16_t DRV_TMR_Period16BitGet(
DRV_HANDLE handle
);
Description
This function provides the 16-bit tTmer's period.
Preconditions
The DRV_TMR_Initialize function must have been called.
DRV_TMR_Open must have been called to obtain a valid opened device handle.
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open routine
Returns
16-bit timer period value
Remarks
None.
Example
DRV_HANDLE handle; // Returned from DRV_TMR_Open
uint16_t value;
value = DRV_TMR_Period16BitGet(handle);
5.1.10.7.4.2 DRV_TMR_Period16BitSet Function
C
void DRV_TMR_Period16BitSet(
DRV_HANDLE handle,
uint16_t value
);
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-495
Description
This function updates the 16-bit Timer's period.
Preconditions
The DRV_TMR_Initialize function must have been called.
DRV_TMR_Open must have been called to obtain a valid opened device handle.
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open routine
value 16-bit Period value
Returns
None.
Remarks
None.
Example
DRV_HANDLE handle; // Returned from DRV_TMR_Open
DRV_TMR_Period16BitSet(handle, 0x1000);
5.1.10.7.4.3 DRV_TMR_Period32BitGet Function
C
uint32_t DRV_TMR_Period32BitGet(
DRV_HANDLE handle
);
Description
This function provides the 32-bit Timer's period.
Preconditions
The DRV_TMR_Initialize function must have been called.
DRV_TMR_Open must have been called to obtain a valid opened device handle.
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open routine
Returns
32-bit Timer period value.
Remarks
None.
Example
DRV_HANDLE handle; // Returned from DRV_TMR_Open
uint32_t value;
value = DRV_TMR_Period32BitGet(handle);
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-496
5.1.10.7.4.4 DRV_TMR_Period32BitSet Function
C
void DRV_TMR_Period32BitSet(
DRV_HANDLE handle,
uint32_t value
);
Description
This function updates the 32-bit Timer's period.
Preconditions
The DRV_TMR_Initialize unction must have been called.
DRV_TMR_Open must have been called to obtain a valid opened device handle.
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open routine
value 32-bit Period value
Returns
None.
Remarks
None.
Example
DRV_HANDLE handle; // Returned from DRV_TMR_Open
DRV_TMR_Period32BitSet(handle, 0xFFFFFFFF);
5.1.10.7.4.5 DRV_TMR_Period8BitGet Function
C
uint8_t DRV_TMR_Period8BitGet(
DRV_HANDLE handle
);
Description
This function provides the 8-bit Timer's period.
Preconditions
The DRV_TMR_Initialize function must have been called.
DRV_TMR_Open must have been called to obtain a valid opened device handle.
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open routine
Returns
8-bit timer period value.
Remarks
None.
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-497
Example
DRV_HANDLE handle; // Returned from DRV_TMR_Open
uint8_t value;
value = DRV_TMR_Period8BitGet(handle);
5.1.10.7.4.6 DRV_TMR_Period8BitSet Function
C
void DRV_TMR_Period8BitSet(
DRV_HANDLE handle,
uint8_t value
);
Description
This function updates the 8-bit timer's period.
Preconditions
The DRV_TMR_Initialize function must have been called.
DRV_TMR_Open must have been called to obtain a valid opened device handle.
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open routine
value 8-bit Period value
Returns
None.
Remarks
None.
Example
DRV_HANDLE handle; // Returned from DRV_TMR_Open
DRV_TMR_Period8BitSet(handle, 0x10);
5.1.10.7.5 Counter Control Functions
5.1.10.7.5.1 DRV_TMR_Counter16BitGet Function
C
uint16_t DRV_TMR_Counter16BitGet(
DRV_HANDLE handle
);
Description
This function provides the 16-bit Timer's current counter value.
Preconditions
The DRV_TMR_Initialize function must have been called.
DRV_TMR_Open must have been called to obtain a valid opened device handle.
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-498
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open routine
Returns
16-bit Timer's current counter value
Remarks
None.
Example
DRV_HANDLE handle; // Returned from DRV_TMR_Open
uint16_t value;
value = DRV_TMR_Counter16BitGet(handle);
5.1.10.7.5.2 DRV_TMR_Counter16BitSet Function
C
void DRV_TMR_Counter16BitSet(
DRV_HANDLE handle,
uint16_t value
);
Description
This function updates the 16-bit Timer's initial count value.
Preconditions
The DRV_TMR_Initialize function must have been called.
DRV_TMR_Open must have been called to obtain a valid opened device handle.
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open routine
value 16-bit Counter value
Returns
None.
Remarks
None.
Example
DRV_HANDLE handle; // Returned from DRV_TMR_Open
DRV_TMR_Counter16BitSet(handle, 0x1000);
5.1.10.7.5.3 DRV_TMR_Counter32BitGet Function
C
uint32_t DRV_TMR_Counter32BitGet(
DRV_HANDLE handle
);
Description
This function provides the 32-bit Timer's current counter value.
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-499
Preconditions
The DRV_TMR_Initialize function must have been called.
DRV_TMR_Open must have been called to obtain a valid opened device handle.
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open routine
Returns
32-bit Timer's current counter value.
Remarks
None.
Example
DRV_HANDLE handle; // Returned from DRV_TMR_Open
uint32_t value;
value = DRV_TMR_Counter32BitGet(handle);
5.1.10.7.5.4 DRV_TMR_Counter32BitSet Function
C
void DRV_TMR_Counter32BitSet(
DRV_HANDLE handle,
uint32_t value
);
Description
This function updates the 32-bit Timer's initial count value.
Preconditions
The DRV_TMR_Initialize function must have been called.
DRV_TMR_Open must have been called to obtain a valid opened device handle.
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open routine
value 32-bit Counter value
Returns
None.
Remarks
None.
Example
DRV_HANDLE handle; // Returned from DRV_TMR_Open
DRV_TMR_Counter32BitSet(handle, 0xFFFFFFFF);
5.1.10.7.5.5 DRV_TMR_Counter8BitGet Function
C
uint8_t DRV_TMR_Counter8BitGet(
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-500
DRV_HANDLE handle
);
Description
This function provides the 8-bit Timer's current counter value.
Preconditions
The DRV_TMR_Initialize function must have been called.
DRV_TMR_Open must have been called to obtain a valid opened device handle.
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open routine
Returns
8-bit Timer's current counter value.
Remarks
None.
Example
DRV_HANDLE handle; // Returned from DRV_TMR_Open
uint8_t value;
value = DRV_TMR_Counter8BitGet(handle);
5.1.10.7.5.6 DRV_TMR_Counter8BitSet Function
C
void DRV_TMR_Counter8BitSet(
DRV_HANDLE handle,
uint8_t value
);
Description
This function updates the 8-bit Timer's initial count value.
Preconditions
The DRV_TMR_Initialize function must have been called.
DRV_TMR_Open must have been called to obtain a valid opened device handle.
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open routine
value 8-bit Counter value
Returns
None.
Remarks
None.
Example
DRV_HANDLE handle; // Returned from DRV_TMR_Open
DRV_TMR_Counter8BitSet(handle, 0x10);
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-501
5.1.10.7.6 Miscellaneous Functions
5.1.10.7.6.1 DRV_TMR_OperatingFrequencyGet Function
C
uint32_t DRV_TMR_OperatingFrequencyGet(
DRV_HANDLE handle
);
Description
This function provides the Timer operating frequency.
Preconditions
The DRV_TMR_Initialize function must have been called.
DRV_TMR_Open must have been called to obtain a valid opened device handle.
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open routine
Returns
32-bit value corresponding to the running frequency.
Remarks
On most processers, the Timer's base frequency is the same as the peripheral bus clock.
Example
DRV_HANDLE handle; // Returned from DRV_TMR_Open
uint32_t clkFreq;
clkFreq = DRV_TMR_OperatingFrequencyGet(handle);
5.1.10.7.6.2 DRV_TMR_TickFrequencyGet Function
C
uint32_t DRV_TMR_TickFrequencyGet(
DRV_HANDLE handle
);
Description
This function provides the Timer's counter "tick" frequency.
Preconditions
The DRV_TMR_Initialize function must have been called.
DRV_TMR_Open must have been called to obtain a valid opened device handle.
Parameters
Parameters Description
handle A valid handle, returned from the DRV_TMR_Open
Returns
Clock frequency value in cycles per second (Hertz).
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-502
Remarks
None.
Example
DRV_HANDLE handle; // Returned from DRV_TMR_Open
uint32_t clkFreq;
clkFreq = DRV_TMR_TickFrequencyGet(handle);
5.1.10.7.6.3 DRV_TMR_VersionGet Function
C
unsigned int DRV_TMR_VersionGet(
const SYS_MODULE_INDEX drvIndex
);
Description
This function gets the Timer driver version. The version is encoded as major * 10000 + minor * 100 + patch. The stringed version
can be obtained using DRV_TMR_VersionStrGet()
Preconditions
None.
Parameters
Parameters Description
drvIndex Identifier for the object instance to get the version for
Returns
Current driver version in numerical format.
Remarks
None.
Example
unsigned int version;
version = DRV_TMR_VersionGet( DRV_TMR_INDEX_0 );
if(version < 110200)
{
// Do Something
}
5.1.10.7.6.4 DRV_TMR_VersionStrGet Function
C
char * DRV_TMR_VersionStrGet(
const SYS_MODULE_INDEX drvIndex
);
Description
This function gets the Timer driver version. The version is returned as major.minor.path[type], where type is optional. The
numerical version can be obtained using DRV_TMR_VersionGet.
Preconditions
None.
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-503
Parameters
Parameters Description
drvIndex Identifier for the object instance to get the version for
Returns
Current Timer driver version in the string format.
Remarks
None.
Example
char *version;
version = DRV_TMR_VersionStrGet( DRV_TMR_INDEX_0 );
printf("%s", version);
5.1.10.7.7 Data Types and Constants
5.1.10.7.7.1 DRV_TMR_ALARM_CONFIG Structure
C
typedef struct {
DRV_TMR_ALARM_TYPE type;
DRV_TMR_CALLBACK callback;
} DRV_TMR_ALARM_CONFIG;
Description
TMR Alarm configuration
This data type controls the configuration of the alarm.
Members
Members Description
DRV_TMR_ALARM_TYPE type; Type of the alarm one shot or periodic
DRV_TMR_CALLBACK callback; Alarm callback
Remarks
Not all modes are available on all devices.
5.1.10.7.7.2 DRV_TMR_ALARM_TYPE Enumeration
C
typedef enum {
DRV_TMR_ALARM_TYPE_ONE_SHOT,
DRV_TMR_ALARM_TYPE_PERIODIC
} DRV_TMR_ALARM_TYPE;
Description
Timer Alarm Type Enumeration
This data type identifies the Timer alarm type.
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-504
Members
Members Description
DRV_TMR_ALARM_TYPE_ONE_SHOT One Shot Alarm
DRV_TMR_ALARM_TYPE_PERIODIC Periodic Alarm
Remarks
Not all modes are available on all devices.
5.1.10.7.7.3 DRV_TMR_CALLBACK Type
C
typedef void (* DRV_TMR_CALLBACK)(void);
Description
Timer Driver Callback Function Pointer
This data type defines a pointer to a Timer driver callback function.
Remarks
Useful only when timer alarm callback support is enabled by defining the DRV_TMR_ALARM_ENABLE configuration option.
5.1.10.7.7.4 DRV_TMR_CLIENT_STATUS Enumeration
C
typedef enum {
DRV_TMR_CLIENT_STATUS_INVALID,
DRV_TMR_CLIENT_STATUS_ERROR,
DRV_TMR_CLIENT_STATUS_BUSY,
DRV_TMR_CLIENT_STATUS_READY,
DRV_TMR_CLIENT_STATUS_STOPPED,
DRV_TMR_CLIENT_STATUS_STARTED
} DRV_TMR_CLIENT_STATUS;
Description
Timer Driver Client Status
This enumeration identifies the client-specific status of the Timer driver.
Members
Members Description
DRV_TMR_CLIENT_STATUS_INVALID Client in an invalid (or unopened) state
DRV_TMR_CLIENT_STATUS_ERROR Unspecified error condition
DRV_TMR_CLIENT_STATUS_BUSY An operation is currently in progress
DRV_TMR_CLIENT_STATUS_READY Up and running, no operations running
DRV_TMR_CLIENT_STATUS_STOPPED Timer stopped (not running), but ready to accept commands
DRV_TMR_CLIENT_STATUS_STARTED Timer started and running, processing transactions
Remarks
None.
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-505
5.1.10.7.7.5 DRV_TMR_INIT Structure
C
typedef struct {
SYS_MODULE_INIT moduleInit;
TMR_MODULE_ID tmrId;
TMR_CLOCK_SOURCE clockSource;
uint32_t timerPeriod;
TMR_PRESCALE prescale;
TMR_CLOCK_SOURCE_EDGE sourceEdge;
uint8_t postscale;
DRV_TMR_SYNC_MODE syncMode;
INT_SOURCE interruptSource;
} DRV_TMR_INIT;
Description
Timer Driver Initialize Data
This data type defines data required to initialize or reinitialize the Timer driver.
Members
Members Description
SYS_MODULE_INIT moduleInit; System module initialization
TMR_MODULE_ID tmrId; Identifies timer hardware module (PLIB-level) ID
TMR_CLOCK_SOURCE clockSource; Clock Source select enumeration
uint32_t timerPeriod; Timer Period Value
TMR_PRESCALE prescale; Prescaler Selection from the processor enumeration
TMR_CLOCK_SOURCE_EDGE
sourceEdge;
TMR Source Edge Selection
uint8_t postscale; Post Scale Selection
DRV_TMR_SYNC_MODE syncMode; Timer Sync Mode
INT_SOURCE interruptSource; Interrupt Source for TMR module
Remarks
Not all initialization features are available on all devices.
5.1.10.7.7.6 DRV_TMR_SYNC_MODE Enumeration
C
typedef enum {
DRV_TMR_SYNC_MODE_SYNCHRONOUS_INTERNAL,
DRV_TMR_SYNC_MODE_SYNCHRONOUS_INTERNAL_GATED,
DRV_TMR_SYNC_MODE_SYNCHRONOUS_EXTERNAL_WITHOUT_CLKSYNC,
DRV_TMR_SYNC_MODE_SYNCHRONOUS_EXTERNAL_WITH_CLKSYNC,
DRV_TMR_SYNC_MODE_ASYNCHRONOUS_EXTERNAL_WITHOUT_CLKSYNC,
DRV_TMR_SYNC_MODE_ASYNCHRONOUS_EXTERNAL_WITH_CLKSYNC,
DRV_TMR_SYNC_MODE_IDLE
} DRV_TMR_SYNC_MODE;
Description
Timer Synchronous Modes
This data type identifies the synchronous modes for the Timer driver.
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-506
Members
Members Description
DRV_TMR_SYNC_MODE_SYNCHRONOUS_INTERNAL Synchronous Internal Clock Counter
DRV_TMR_SYNC_MODE_SYNCHRONOUS_INTERNAL_GATED Synchronous Internal Gated Counter
DRV_TMR_SYNC_MODE_SYNCHRONOUS_EXTERNAL_WITHOUT_CLKSYNC Synchronous External Clock Counter
DRV_TMR_SYNC_MODE_SYNCHRONOUS_EXTERNAL_WITH_CLKSYNC Synchronous External Clock Counter
DRV_TMR_SYNC_MODE_ASYNCHRONOUS_EXTERNAL_WITHOUT_CLKSYNC Asynchronous External Clock Counter
DRV_TMR_SYNC_MODE_ASYNCHRONOUS_EXTERNAL_WITH_CLKSYNC Asynchronous External Clock Counter
DRV_TMR_SYNC_MODE_IDLE Timer Idle Mode
Remarks
Not all modes are available on all devices.
5.1.10.7.8 Macros
5.1.10.7.8.1 DRV_TMR_INTERRUPT_SOURCE Macro
C
#define DRV_TMR_INTERRUPT_SOURCE INT_SOURCE_TIMER_1
Description
TMR Interrupt Source
This macro defines the interrupt source of the static driver.
Remarks
Refer to the Interrupt Peripheral Library documentation for more information on the INT_SOURCE enumeration.
5.1.10.7.8.2 DRV_TMR_POWER_STATE Macro
C
#define DRV_TMR_POWER_STATE SYS_MODULE_POWER_IDLE_STOP
Description
TMR power state configuration
This macro controls the power state of the Timer.
Remarks
This feature is not available in all modules/devices. Refer to the specific device data sheet for more information.
5.1.10.7.8.3 DRV_TMR_UNIFIED Macro
C
#define DRV_TMR_UNIFIED false
Description
TMR driver configuration
This definition sts up the driver functionlity in either split or the unified mode.
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-507
Remarks
None.
5.1.10.8 Files
Files
Name Description
drv_tmr.h Timer device driver interface header.
drv_tmr_config_template.h Timer driver configuration definitions for the template version.
Description
5.1.10.8.1 drv_tmr.h
Timer Device Driver Interface Definition
This header file contains the function prototypes and definitions of the data types and constants that make up the interface to the
Timer device driver.
Enumerations
Name Description
DRV_TMR_ALARM_TYPE Timer driver type enumeration.
DRV_TMR_CLIENT_STATUS Identifies the client-specific status of the Timer driver
DRV_TMR_SYNC_MODE Identifies the synchronous modes for the Timer driver.
Functions
Name Description
DRV_TMR_AlarmCountClear Clears the alarm elapse counter.
DRV_TMR_AlarmCountGet Provides the number of times the alarm has elapsed since the last time it
was cleared.
DRV_TMR_AlarmSet Initializes an alarm.
DRV_TMR_ClientStatus Gets current client-specific status of the Timer driver.
DRV_TMR_Close Closes an opened instance of the Timer driver
DRV_TMR_Counter16BitGet Provides the 16-bit Timer's current counter value.
DRV_TMR_Counter16BitSet Updates the 16-bit Timer's initial count value.
DRV_TMR_Counter32BitGet Provides the 32-bit Timer's current counter value.
DRV_TMR_Counter32BitSet Updates the 32-bit Timer's initial count value.
DRV_TMR_Counter8BitGet Provides the 8-bit Timer's current counter value.
DRV_TMR_Counter8BitSet Updates the 8-bit Timer's initial count value
DRV_TMR_Deinitialize Deinitializes the specified instance of the Timer driver.
DRV_TMR_ElapsedStatusGetAndClear Provides and clears the Timer's elapse count.
DRV_TMR_Initialize Initializes the Timer driver .
DRV_TMR_Open Opens the specified Timer driver instance and returns a handle to it.
DRV_TMR_OperatingFrequencyGet Provides the Timer operating frequency.
DRV_TMR_Period16BitGet Provides the 16-bit Timer's period
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-508
DRV_TMR_Period16BitSet Updates the 16-bit Timer's period.
DRV_TMR_Period32BitGet Provides the 32-bit Timer's period
DRV_TMR_Period32BitSet Updates the 32-bit Timer's period.
DRV_TMR_Period8BitGet Provides the 8-bit Timer's period.
DRV_TMR_Period8BitSet Updates the 8-bit timer's period
DRV_TMR_Reinitialize Reinitializes the driver and refreshes any associated hardware settings.
DRV_TMR_Start Starts the Timer counting.
DRV_TMR_Status Provides the current status of the Timer driver.
DRV_TMR_Stop Stops the Timer from counting.
DRV_TMR_SyncModeGet Provides the Timer's current synchronization mode.
DRV_TMR_SyncModeSet Changes the Timer's synchronization mode.
DRV_TMR_Tasks Maintains the driver's state machine and implements its ISR.
DRV_TMR_TickFrequencyGet Provides the Timer's counter "tick" frequency.
DRV_TMR_VersionGet Gets the Timer driver version in numerical format.
DRV_TMR_VersionStrGet Gets the Timer driver version in string format.
Macros
Name Description
DRV_TMR_INDEX_0 Timer driver index definitions
DRV_TMR_INDEX_1 This is macro DRV_TMR_INDEX_1.
DRV_TMR_INDEX_2 This is macro DRV_TMR_INDEX_2.
DRV_TMR_INDEX_3 This is macro DRV_TMR_INDEX_3.
DRV_TMR_INDEX_4 This is macro DRV_TMR_INDEX_4.
DRV_TMR_INDEX_5 This is macro DRV_TMR_INDEX_5.
DRV_TMR_INDEX_COUNT Number of valid Timer driver indices.
Structures
Name Description
DRV_TMR_ALARM_CONFIG Timer module alarm configuration.
DRV_TMR_INIT Defines the Timer driver initialization data.
Types
Name Description
DRV_TMR_CALLBACK Pointer to a Timer driver callback function data type.
File Name
drv_tmr.h
Company
Microchip Technology Inc.
5.1.10.8.2 drv_tmr_config_template.h
Timer Driver Configuration Definitions for the Template Version
These definitions set up the driver for the default mode of operation of the driver.
5.1 Driver Library Help MPLAB Harmony Help Timer Driver Library
5-509
Macros
Name Description
DRV_TMR_ALARM_ENABLE Enables alarm functionality.
DRV_TMR_ALARM_PERIODIC Alarm type configuration.
DRV_TMR_ASYNC_WRITE_ENABLE Controls Asynchronous Write mode of the Timer.
DRV_TMR_CLIENTS_NUMBER Selects the maximum number of clients
DRV_TMR_CLOCK_SOURCE Timer module clock source selection.
DRV_TMR_COUNT_WIDTH Controls the mode of the Timer.
DRV_TMR_INDEX Timer static index selection.
DRV_TMR_INSTANCES_NUMBER Sets up the maximum number of hardware instances that can be
supported by the dynamic driver.
DRV_TMR_INTERRUPT_MODE Controls operation of the driver in the interrupt or polled mode.
DRV_TMR_INTERRUPT_SOURCE Defines the interrupt source of the static driver.
DRV_TMR_PERIPHERAL_ID Timer peripheral ID selection.
DRV_TMR_POSTSCALE Macro controls post scale of the TMR
DRV_TMR_POWER_STATE Controls the power state of the Timer.
DRV_TMR_PRESCALE Timer module prescale value.
DRV_TMR_PRESCALER_ENABLE Controls prescaler assignment of the Timer.
DRV_TMR_SOURCE_EDGE Timer module source edge.
DRV_TMR_SYNCHRONIZATION_MODE Controls Synchronization mode of the Timer.
DRV_TMR_TIMER_PERIOD Timer period value for an overflow or a period match-based Timer.
DRV_TMR_UNIFIED Sets up the driver functionlity in either split or the unified mode.
File Name
drv_tmr_config_template.h
Company
Microchip Technology Inc.
5.1.11 USART Driver Library
5.1.11.1 Introduction
USART Driver Library
for
Microchip Microcontrollers
This library provides an interface to manage the USART module on Microchip family of micro controllers in different modes of
operation.
Overview of USART
The Universal Synchronous Asynchronous Receiver/Transmitter (USART) controller is the key component of the serial
5.1 Driver Library Help MPLAB Harmony Help USART Driver Library
5-510
communications subsystem of many embedded systems.
The USART driver can support following modes of operation. (Refer to the Device Specific data sheet to determine which modes
are supported on the part being used.)
1. RS232
RS232 is an asynchronous full duplex serial communication protocol. It uses separate lines for transmitting and receiving data,
point-to-point, between a Data Terminal Equipment (DTE) item and a Data Communication Equipment (DCE) item at a maximum
speed of 20 kbps with a maximum cable length of 50 feet.
2. RS485
RS485 is a multi-point communications network. It provides bi-directional, half-duplex, data transmission that allows multiple
receivers and drivers in "bus" configurations. The standard specifies up to 32 drivers and 32 receivers on a single (2-wire) bus.
With the introduction of "automatic" repeaters and high-impedance drivers and receivers this "limitation" can be extended to
hundreds (or even thousands) of nodes on a network.
3. IrDA
Some Microchip micro controllers provide an Infrared (IR) encoder and decoder and can also interface with external IR encoders
and decoders.
4. Interdevice Communication
USART module can be used for communication(without any external transceiver) between two devices. The maximum
communication speed in this case is
determined by the maximum Baud supported by the device.
5. Synchronous Master/Slave
Synchronous serial transmission requires that the sender and receiver share a clock with one another or that the sender provide
a strobe or other timing signal so that the receiver knows when to latch the next bit of the data. It is typically used in systems with
a single master and one or more slaves. The master device contains the necessary circuitry for baud rate generation and
supplies the clock for all devices in the system.
Note: if a USART does not support a synchronous mode, it is called UART. However, UARTs are still controlled by the USART
driver.
5.1.11.2 Release Notes
MPLAB Harmony Version: v0.70b USART Driver Library Version : 0.050b Alpha Release Date: 18Nov2013
New This Release:
The USART Driver supports the following modes of operation.
Modes of operation
• Polling Mode
• Interrupt Mode
Configuration modes
• Asynchronous Transmit & Receive(i.e. RS232, RS485)
• IrDA Mode
• Loop Back Mode
5.1 Driver Library Help MPLAB Harmony Help USART Driver Library
5-511
Handshake modes
• Flow Control Mode
• No Handshake Mode
Line Control modes
• 8 bit, No Parity, 1 stop bit Mode
• 9 bit, No Parity, 1 stop bit Mode
• 8 bit, Even Parity, 1 stop bit Mode
• 8 bit, Even Parity, 2 stop bits Mode
• 8 bit, Odd Parity, 1 stop bit Mode
• 8 bit, Odd Parity, 2 stop bits Mode
Interrupt Modes
• Wakeup On Start Enable
• Auto Baud enable
Following demo shows how to use USART Driver
• usart_echo (\apps\driver\usart\drv_usart_demo)
Known Issues:
The following are the known issues in this release.
• Although implementation exists, the driver doesn’t work in the following line control modes:
• 8 bit, Even Parity, 1 stop bit Mode
• 8 bit, Even Parity, 2 stop bits Mode
• 8 bit, Odd Parity, 1 stop bit Mode
• 8 bit, Odd Parity, 2 stop bits Mode
• Deinitialize API of the driver doesn’t work. This means that the application cannot initialize the driver after deinitializing it.
• When UART driver is configured for 115200 baud rate, there could be no data received or received data is corrupted
• More than one client is not supported
• The USART Driver does not support “Odd” and “Even” parity settings
5.1.11.3 SW License Agreement
© 2013 Microchip Technology Inc.
Microchip licenses this software to you solely for use with Microchip products. The software is owned by Microchip and its
licensors, and is protected under applicable copyright laws. All rights reserved.
SOFTWARE IS PROVIDED “AS IS.” MICROCHIP EXPRESSLY DISCLAIMS ANY WARRANTY OF ANY KIND, WHETHER
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL MICROCHIP BE LIABLE FOR
ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, HARM TO
YOUR EQUIPMENT, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS
BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR
CONTRIBUTION, OR OTHER SIMILAR COSTS.
To the fullest extent allowed by law, Microchip and its licensors liability shall not exceed the amount of fees, if any, that you have
5.1 Driver Library Help MPLAB Harmony Help USART Driver Library
5-512
paid directly to Microchip to use this software.
MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE TERMS.
5.1.11.4 Using the Library
This topic describes the basic architecture of the USART Driver Library and provides information and examples on how to use it.
Interface Header File: drv_usart.h
The interface to the USART library is defined in the "drv_usart.h" header file
Please refer to the MPLAB Harmony Overview for how the driver interacts with the framework.
5.1.11.4.1 Abstraction Model
Different types of USARTs are available on Microchip microcontrollers. Some have a FIFO and some do not. The FIFO depth
varies across part families. The USART driver abstracts out these differences and provides a unified model for data transfer
across different types of USARTS available.
Both transmitter and receiver provide a buffer in the driver which transmits and receives data to/from the hardware. The USART
driver provides a set of interfaces to perform the read and the write.
The diagrams below illustrates the model used by the USART driver for transmitter and receiver.
Receiver Abstraction Model
Transmitter Abstraction Model
5.1 Driver Library Help MPLAB Harmony Help USART Driver Library
5-513
5.1.11.4.2 Library Overview
Refer to the section Driver Overview for how the driver operates in a system.
The table below lists the interface section and its brief description.
Library Interface Section Description
Data Types and Constants Provides macros for configuring the system. It is required that the system
configures the driver to build correctly by choosing appropriate
configuration options as listed in this section.
System Initialization Functions Provides system module interfaces, Device initialization, de-initialization,
re-initialization and status functions.
Setup and Status Functions Provides open, close and other setup functions
Data Transfer Functions Provides data transfer functions available in the core configuration
5.1.11.4.3 How the Library Works
The library provides interfaces to support:
• System Interaction
• Client Core Functionality
5.1.11.4.3.1 System Initialization
System Initialization and Reinitialization
The system performs the initialization and the reinitialization of the device driver with settings that affect only the instance of the
device that is being initialized or re-initialized. During system initialization each instance of the USART device will be initialized
with the following configuration settings (either passed dynamically at run time using DRV_USART_INIT or by using Initialization
Overrides) that are supported by the specific USART device hardware:
• Device requested power state: one of the System Module Power States. For specific details please refer to the Data Types
section in this guide
• The actual peripheral ID enumerated as the PLIB level module ID. e.g USART_ID_2.
• Operation Mode: Select the operation mode of the instance using one of the possible values from
DRV_USART_OPERATION_MODES. Make sure that the operation mode support is enabled in the driver configuration setup.
Also for RS485 operation mode, select the address to which the module instance should respond to.
• Line Control Mode: Setup the line control mode using one of the possible values from
5.1 Driver Library Help MPLAB Harmony Help USART Driver Library
5-514
DRV_USART_LINE_CONTROL_MODES
• Baud Rate Setup: Setup the baud rate by either providing the baud rate value or enabling the auto baud setup.
• Configuration of the RS485 mode if enabled.
• Enabling the handshake signals.e.g. Simplex, FlowControl. For specifics please refer the Data Types section in this guide.
• Defining the respective interrupt sources for Tx, Rx, and Error Interrupt.
The DRV_USART_Initialize API returns an object handle of the type SYS_MODULE_OBJ. There on, the object handle returned
by the Initialize interface would be used by the other system interfaces like DRV_USART_Reinitialize, DRV_USART_Deinitialize,
DRV_USART_Status and DRV_USART_TasksTX, DRV_USART_TasksRX.
Note:The system initialization and the re-initialization settings, only effect the instance of the peripheral that is being initialized or
re-initialized.
Example:
DRV_USART_INIT usartInitData;
//Alternatively NULL can be passed to Initialize which then
//makes sure that static overrides as selected by the user
//will be used as default values
SYS_MODULE_OBJ objectHandle;
usartInitData.moduleInit.value = SYS_MODULE_POWER_RUN_FULL;
usartInitData.moduleId = USART_ID_2;
usartInitData.operationMode = DRV_USART_OPERATION_MODE_RS232;
usartInitData.initFlags = 0;
usartInitData.lineControlMode = DRV_USART_LINE_CONTROL_MODE_8NONE1;
usartInitData.brgClock = 4000000;
usartInitData.brgValue = 9600;
usartInitData.operationModeInit = 0;
usartInitData.handShakeMode = DRV_USART_HANDSHAKE_MODE_FLOWCONTROL;
usartInitData.txInterruptSource = INT_SOURCE_USART_2_TRANSMIT;
usartInitData.rxInterruptSource = INT_SOURCE_USART_2_RECEIVE;
usartInitData.errorInterruptSource = INT_SOURCE_USART_2_ERROR;
usartInitData.txQueueSize = 3;
usartInitData.rxQueueSize = 3;
objectHandle = DRV_USART_Initialize(DRV_USART_INDEX_1, (SYS_MODULE_INIT*)usartInitData);
if (SYS_MODULE_OBJ_INVALID == objectHandle)
{
// Handle error
}
Tasks Routine
The system will either call DRV_USART_TasksTX, DRV_USART_TasksRX, from System Task Service (in a polled environment)
or DRV_USART_TasksTX, DRV_USART_TasksRX will be called from interrupt service routine of the USART.
5.1.11.4.3.2 Core Functionality
Core functionality provides a extremely basic interface for the driver operation.
Core Transmitter Functionality
Application using the USART core functionality, needs to perform the following:
1. The system should have completed necessary initialization and the DRV_USART_TasksTX should either be running in polled
environment, or in an interrupt environment.
2. Open the driver using DRV_USART_Open, timer driver supports exclusive access only.
3. Write a byte using DRV_USART_WriteByte.
4. The client will be able to close itself using the DRV_USART_Close when required.
5.1 Driver Library Help MPLAB Harmony Help USART Driver Library
5-515
Example :
DRV_HANDLE handle; // Returned from DRV_USART_Open
bool status;
// Pre-initialize myBuffer with MY_BUFFER_SIZE bytes of valid data.
status = DRV_USART_WriteByte(handle, myBuffer[numBytes++]);
// Do something else...
}
Core Receiver Functionality
Application using the USART core functionality, needs to perform the following:
1. The system should have completed necessary initialization and the DRV_USART_TasksRX should either be running in polled
environment, or in an interrupt environment.
2. Open the driver using DRV_USART_Open, timer driver supports exclusive access only.
3. Write a byte using DRV_USART_ReadByte.
4. The client will be able to close itself using the DRV_USART_Close when required.
Example :
DRV_HANDLE handle; // Returned from DRV_USART_Open
bool status;
char byte;
bool = DRV_USART_ReadByte(handle, &byte);
// Do something else...
5.1.11.4.3.3 Client Access
For the application to start using an instance of the module, it must call the DRV_USART_Open function. This provides the
configuration required to open the USART instance for operation. If the driver is de-initialized using the function
DRV_USART_Deinitialize, the application must call the DRV_USART_Open function again to setup the instance of the USART.
The function DRV_USART_Open need not be called again if the system is re-initialized using the DRV_USART_Reinitialize
function.
//This i have to mod
For the various options available for I/O INTENT please refer to the Data Types and Constants section.
Example:
DRV_HANDLE handle;
handle = DRV_USART_Open(DRV_USART_INDEX_1, DRV_IOINTENT_READWRITE);// Configure the instance
USART_ID_1 with the above configuration
if(handle == DRV_HANDLE_INVALID)
{
// Client cannot open the instance.
}
5.1.11.4.3.4 Data Transfer
In the basic data transfer mode, the USART device driver allows the client to perform simple read or write operation on the
USART. The client (who is this) has to provide a buffer where the transfer data is/will be stored.
Example : Read in the RS-232 mode
5.1 Driver Library Help MPLAB Harmony Help USART Driver Library
5-516
// USART is operating in RS-232 Mode
// Assume that DRV_USART_Open operation was called with DRV_IO_INTENT_NONBLOCKING parameter
char myBuffer[MY_BUFFER_SIZE];
size_t total;
size_t count;
DRV_HANDLE drvHandle; // device handle obtained by a call to DRV_USART_Open
// Start the transfer
total = 0;
do
{
count = DRV_USART_Read(drvHandle, myBuffer, MY_BUFFER_SIZE - total);
total += count;
// Do something else...
} while(total < MY_BUFFER_SIZE);
Example : Write in the RS-485 mode
// USART is operating in RS-485 Mode
// Assume that DRV_USART_Open operation was called with DRV_IO_INTENT_NONBLOCKING parameter
char myBuffer[MY_BUFFER_SIZE];
size_t total;
size_t count;
DRV_HANDLE drvHandle; // device handle obtained by a call to DRV_USART_Open
// Start the transfer
total = 0;
do
{
count = DRV_USART_WriteToAddress(drvHandle, 0x07, myBuffer, MY_BUFFER_SIZE - total); //
Write the string "writestring" to the communications channel
total += count;
// Do something else...
} while(total < MY_BUFFER_SIZE);
5.1.11.4.3.5 Advanced Data Transfer
USART device client transfer is composed if various buffers that are queued internally by the driver.
Each buffer is described by a buffer descriptor which contains the transfer buffer, size and an address
Each buffer has associated flags that specify the behavior that the device driver has to take once that particular segment
reaches a particular stage of processing.
The client can add segments to the transfer by using DRV_USART_BufferAdd for adding the Read and write buffers.
The client can query the status of the buffer using the function DRV_USART_BufferStatus and also can query how many bytes
of the buffer are read or written if the buffer is in progress using the function DRV_USART_BufferTransferStatus.
The diagram below illustrates the buffer model used by the advanced data transfer.
5.1 Driver Library Help MPLAB Harmony Help USART Driver Library
5-517
Example:
void Callback(void);
uint8_t mybuffer[MY_BUFFER_SIZE];
uint8_t bytesWritten = 0;
DRV_BUFFER_HANDLE bufferHandle = NULL;
DRV_USART_IO_BUFFER buffer1;
void Callback(void)
{
Nop();
}
buffer1.buffer = writeBuffer2;
buffer1.bufferSize = sizeof(writeBuffer2);
buffer1.xferCallback = Callback;
buffer1.flags = DRV_USART_BUFFER_FLAG_WRITE;
// myUSARTHandle is the handle returned by the DRV_USART_Open function.
bufferHandle = DRV_USART_BufferAdd(myUSARThandle, &buffer1);
bufferStatus = DRV_USART_BufferStatus ( uartHandle, uartBufferHandle );
if ( DRV_USART_BUFFER_COMPLETED == bufferStatus )
{
// Handle Buffer Complete
}else
{
// Handle other
}
Example:
void Callback(void);
uint8_t mybuffer[MY_BUFFER_SIZE];
uint8_t bytesWritten = 0;
DRV_BUFFER_HANDLE bufferHandle = NULL;
DRV_USART_IO_BUFFER buffer1;
void Callback(void)
{
Nop();
}
buffer1.buffer = readBuffer2;
buffer1.bufferSize = sizeof(readBuffer2);
buffer1.xferCallback = Callback;
buffer1.flags = DRV_USART_BUFFER_FLAG_READ;
5.1 Driver Library Help MPLAB Harmony Help USART Driver Library
5-518
// myUSARTHandle is the handle returned by the DRV_USART_Open function.
bufferHandle = DRV_USART_BufferAdd(myUSARThandle, &buffer1);
bufferStatus = DRV_USART_BufferStatus ( uartHandle, uartBufferHandle );
if ( DRV_USART_BUFFER_COMPLETED == bufferStatus )
{
// Handle Buffer Complete
}else
{
// Handle other
}
5.1.11.5 Configuring the Library
The configuration of the USART device driver is based on the file sys_config.h
This header file contains the configuration selection for the USART device driver build. Based on the selections made here and
the system setup the USART device driver will support or not selected features. These configuration settings will apply to all
instances of the device driver.
This header can be placed anywhere in the application specific folders and the path of this header needs to be presented to the
include search for a successful build. Refer to the Applications Overview section for more details.
Initialization overrides not supported in this version.
5.1.11.6 Building the Library
This section list the files that are available in the \src of the timer driver. It lists which files need to be included in the build based
on either a hardware feature present on the board or configuration option selected by the system.
5.1.11.7 Library Interface
Data Types and Constants
Name Description
DRV_USART_AUTO_BAUD_ENABLE Macro configures enabling the auto baud.
DRV_USART_BAUD_RATE Macro controls operation of the driver for Baud rate configuration
DRV_USART_BYTE_Q_SIZE_RX Macro controls operation of the driver for defining the size of the
Rx buffer
DRV_USART_BYTE_Q_SIZE_TX Macro controls operation of the driver for defining the size of the
Tx buffer
DRV_USART_CLIENTS_NUMBER Sets up the maximum number of clients that can be connected to
any hardware instance.
DRV_USART_HANDSHAKE_MODE Configures the handshake mode
DRV_USART_INDEX USART Static Index selection
DRV_USART_INDEX_0 USART driver index definitions
DRV_USART_INDEX_1 This is macro DRV_USART_INDEX_1.
DRV_USART_INDEX_2 This is macro DRV_USART_INDEX_2.
DRV_USART_INDEX_3 This is macro DRV_USART_INDEX_3.
DRV_USART_INDEX_4 This is macro DRV_USART_INDEX_4.
5.1 Driver Library Help MPLAB Harmony Help USART Driver Library
5-519
DRV_USART_INDEX_5 This is macro DRV_USART_INDEX_5.
DRV_USART_INDEX_COUNT Number of valid USART driver indices
DRV_USART_INSTANCES_NUMBER Sets up the maximum number of hardware instances that can be
supported
DRV_USART_INTERRUPT_MODE Macro controls operation of the driver in the interrupt mode
DRV_USART_INTERRUPT_SOURCE_ERROR Defines the interrupt source for the error interrupt
DRV_USART_INTERRUPT_SOURCE_RX Macro to define the Rx interrupt source in case of static driver
DRV_USART_INTERRUPT_SOURCE_TX Macro to define the Tx interrupt source in case of static driver
DRV_USART_LINE_CONTROL Macro defines the line control mode
DRV_USART_OPERATION_MODE Defines the mode to be used for the USART driver
DRV_USART_PERIPHERAL_ID Configures the PLIB id
DRV_USART_POLARITY_INVERTED_RX Defines the polarity of the RX pin.
DRV_USART_POLARITY_INVERTED_TX Defines the polarity of the TX pin.
DRV_USART_POWER_STATE Macro controls power state of the USART
DRV_USART_WAKE_ON_START_ENABLE Macro configures that the peripheral should wake up on start
DRV_USART_XFER_BUFFER_NUMBER Transfer buffer depth
DRV_USART_BUFFER_FLAGS Defines the IO types that can be serviced by the USART driver
DRV_USART_BUFFER_STATUS Defines the buffer status
DRV_USART_CALLBACK Pointer to a USART callback function
DRV_USART_CLIENT_STATUS Defines the client status
DRV_USART_HANDSHAKE_MODES Identifies the handshaking modes available on the USART
DRV_USART_INIT Defines the data required to initialize or reinitialize the USART
driver
DRV_USART_INIT_FLAGS Defines specific initialization features
DRV_USART_IO_BUFFER IO buffer information structure
DRV_USART_LINE_CONTROL_MODES Identifies the line control modes available
DRV_USART_OPERATION_MODE_INIT Defines the initialization data required for different operation
modes of USART
DRV_USART_OPERATION_MODES Identifies the modes of the operation of the USART module
DRV_USART_TRANSFER_STATUS Specifies the status of the receive or transmit
DRV_USART_XFER_HANDLE Handle for requested transfer..
Data Transfer Functions
Name Description
DRV_USART_BufferAdd Starts the writes to the communication channel.
DRV_USART_BufferStatus Provides the status of the given buffer
DRV_USART_Read Reads data from the USART
DRV_USART_ReadByte Reads a byte of data from the USART
DRV_USART_TransferStatus Returns the transmitter and receiver transfer status
DRV_USART_Write Writes data to the USART
DRV_USART_WriteByte Writes a byte of data to the USART
Setup and Status Functions
Name Description
DRV_USART_BufferTransferStatus Gets the number of bytes which are written or read
DRV_USART_ClientStatus Gets current client-specific status the USART driver
DRV_USART_Close Closes an opened-instance of the USART driver
5.1 Driver Library Help MPLAB Harmony Help USART Driver Library
5-520
DRV_USART_Open Opens the specified timer driver instance and returns a handle to it
DRV_USART_Status Gets the current status of the USART driver module.
System Initialization Functions
Name Description
DRV_USART_Deinitialize Deinitializes the specified instance of the USART driver module
DRV_USART_Initialize Initializes the USART instance for the specified driver index
DRV_USART_Reinitialize Reinitializes the USART driver and refreshes any associated hardware settings
DRV_USART_TasksError Maintains the driver's error-handling state machine and implements its ISR
DRV_USART_TasksRX Maintains the driver's receiver state machine and implements its ISR
DRV_USART_TasksTX Maintains the driver's tramsmitter state machine and implements its ISR
Description
This section describes the functions of the USART Driver Library.
Refer to each section for a detailed description.
5.1.11.7.1 System Initialization Functions
5.1.11.7.1.1 DRV_USART_Deinitialize Function
C
void DRV_USART_Deinitialize(
SYS_MODULE_OBJ object
);
Description
Deinitializes the specified instance of the USART driver module, disabling its operation (and any hardware). Invalidates all the
internal data.
Preconditions
Function DRV_USART_Initialize should have been called before calling this function.
Parameters
Parameters Description
object Driver object handle, returned from the DRV_USART_Initialize routine
Returns
None.
Remarks
Once the Initialize operation has been called, the Deinitialize operation must be called before the Initialize operation can be
called again.
This routine will NEVER block waiting for hardware. If the operation requires time to allow the hardware to complete, this will be
reported by the DRV_USART_Status operation. The system has to use DRV_USART_Status to find out when the module is in
the ready state.
Example
SYS_MODULE_OBJ object; // Returned from DRV_USART_Initialize
SYS_STATUS status;
5.1 Driver Library Help MPLAB Harmony Help USART Driver Library
5-521
DRV_USART_Deinitialize(object);
status = DRV_USART_Status(object);
if (SYS_MODULE_DEINITIALIZED != status)
{
// Check again later if you need to know
// when the driver is deinitialized.
}
5.1.11.7.1.2 DRV_USART_Initialize Function
C
SYS_MODULE_OBJ DRV_USART_Initialize(
const SYS_MODULE_INDEX index,
const SYS_MODULE_INIT * const init
);
Description
This routine initializes the USART driver instance for the specified driver index, making it ready for clients to open and use it.
Preconditions
None.
Parameters
Parameters Description
index Identifier for the instance to be initialized
init Pointer to a data structure containing any data necessary to initialize the drivver.
This pointer may be null if no data is required because static overrides have been
provided.
Returns
If successful, returns a valid handle to a driver instance object. Otherwise, it returns SYS_MODULE_OBJ_INVALID.
Remarks
This routine must be called before any other USART routine is called.
This routine should only be called once during system initialization unless DRV_USART_Deinitialize is called to de-initialize the
driver instance.
This routine will NEVER block for hardware access. If the operation requires time to allow the hardware to re-initialize, it will be
reported by the DRV_USART_Status operation. The system must use DRV_USART_Status to find out when the driver is in the
ready state.
Build configuration options may be used to staticaly override options in the "init" sructure and will take precedance over
initialization data passed using this routine.
Example
DRV_USART_INIT usartInitData;
//Alternatively NULL can be passed to Initialize which then
//makes sure that static overrides as selected by the user
//will be used as default values
SYS_MODULE_OBJ objectHandle;
usartInitData.moduleInit.value = SYS_MODULE_POWER_RUN_FULL;
usartInitData.moduleId = USART_ID_2;
usartInitData.operationMode = DRV_USART_OPERATION_MODE_RS232;
usartInitData.initFlags = 0;
usartInitData.lineControlMode = DRV_USART_LINE_CONTROL_MODE_8NONE1;
usartInitData.brgClock = 4000000;
5.1 Driver Library Help MPLAB Harmony Help USART Driver Library
5-522
usartInitData.brgValue = 9600;
usartInitData.operationModeInit = 0;
usartInitData.handShakeMode = DRV_USART_HANDSHAKE_MODE_FLOWCONTROL;
usartInitData.txInterruptSource = INT_SOURCE_USART_2_TRANSMIT;
usartInitData.rxInterruptSource = INT_SOURCE_USART_2_RECEIVE;
usartInitData.errorInterruptSource = INT_SOURCE_USART_2_ERROR;
usartInitData.txQueueSize = 3;
usartInitData.rxQueueSize = 3;
objectHandle = DRV_USART_Initialize(DRV_USART_INDEX_1, (SYS_MODULE_INIT*)usartInitData);
if (SYS_MODULE_OBJ_INVALID == objectHandle)
{
// Handle error
}
5.1.11.7.1.3 DRV_USART_Reinitialize Function
C
void DRV_USART_Reinitialize(
SYS_MODULE_OBJ object,
const SYS_MODULE_INIT * const init
);
Description
This routine reinitializes the driver and refreshes any associated hardware settings using the initialization data given, but it will
not interrupt any ongoing operations.
Preconditions
Function DRV_USART_Initialize must have been called before calling this routine and a valid SYS_MODULE_OBJ must have
been returned.
Parameters
Parameters Description
object Driver object handle, returned from the DRV_USART_Initialize routine
init Pointer to the initialization data structure
Returns
None.
Remarks
This function can be called multiple times to reinitialize the module.
This operation can be used to refresh any supported hardware registers as specified by the initialization data or to change the
power state of the module.
This routine will NEVER block for hardware access. If the operation requires time to allow the hardware to re-initialize, it will be
reported by the DRV_USART_Status operation. The system must use DRV_USART_Status to find out when the driver is in the
ready state.
Build configuration options may be used to staticaly override options in the "init" sructure and will take precedance over
initialization data passed using this routine.
Example
DRV_USART_INIT usartInitData;
//Alternatively NULL can be passed to Initialize which then
//makes sure that static overrides as selected by the user
//will be used as default values
SYS_STATUS usartStatus;
5.1 Driver Library Help MPLAB Harmony Help USART Driver Library
5-523
SYS_MODULE_OBJ object;
usartInitData.moduleInit.value = SYS_MODULE_POWER_RUN_FULL;
usartInitData.moduleId = USART_ID_2;
usartInitData.operationMode = DRV_USART_OPERATION_MODE_RS232;
usartInitData.initFlags = 0;
usartInitData.lineControlMode = DRV_USART_LINE_CONTROL_MODE_8NONE1;
usartInitData.brgClock = 4000000;
usartInitData.brgValue = 9600;
usartInitData.operationModeInit = 0;
usartInitData.handShakeMode = DRV_USART_HANDSHAKE_MODE_FLOWCONTROL;
usartInitData.txInterruptSource = INT_SOURCE_USART_2_TRANSMIT;
usartInitData.rxInterruptSource = INT_SOURCE_USART_2_RECEIVE;
usartInitData.errorInterruptSource = INT_SOURCE_USART_2_ERROR;
DRV_USART_Reinitialize(object, (SYS_MODULE_INIT*)usartInitData);
usartStatus = DRV_USART_Status(object);
if (SYS_STATUS_BUSY == usartStatus)
{
// Check again later to ensure the driver is ready
}
else if (SYS_STATUS_ERROR >= usartStatus)
{
// Handle error
}
5.1.11.7.1.4 DRV_USART_TasksError Function
C
void DRV_USART_TasksError(
SYS_MODULE_OBJ object
);
Description
This routine is used to maintain the driver's internal error-handling state machine and implement its ISR for interrupt-driven
implementations.
Preconditions
The DRV_USART_Initialize routine must have been called for the specified USART driver instance.
Parameters
Parameters Description
object Object handle for the specified driver instance (returned from
DRV_USART_Initialize)
Returns
None.
Remarks
This routine is normally not called directly by an application. It is called by the system's Tasks routine (SYS_Tasks) or by the
apropriate raw ISR.
This routine may excute in an ISR context and will never block or access any resources that may cause it to block.
Example
SYS_MODULE_OBJ object; // Returned from DRV_USART_Initialize
while (true)
{
DRV_USART_TasksError (object);
5.1 Driver Library Help MPLAB Harmony Help USART Driver Library
5-524
// Do other tasks
}
5.1.11.7.1.5 DRV_USART_TasksRX Function
C
void DRV_USART_TasksRX(
SYS_MODULE_OBJ object
);
Description
This routine is used to maintain the driver's internal receiver state machine and implement its ISR for interrupt-driven
implementations.
Preconditions
The DRV_USART_Initialize routine must have been called for the specified USART driver instance.
Parameters
Parameters Description
object Object handle for the specified driver instance (returned from
DRV_USART_Initialize)
Returns
None.
Remarks
This routine is normally not called directly by an application. It is called by the system's Tasks routine (SYS_Tasks) or by the
apropriate raw ISR.
This routine may excute in an ISR context and will never block or access any resources that may cause it to block.
Example
SYS_MODULE_OBJ object; // Returned from DRV_USART_Initialize
while (true)
{
DRV_USART_TasksRX (object);
// Do other tasks
}
5.1.11.7.1.6 DRV_USART_TasksTX Function
C
void DRV_USART_TasksTX(
SYS_MODULE_OBJ object
);
Description
This routine is used to maintain the driver's internal transmitter state machine and implement its ISR for interrupt-driven
implementations.
Preconditions
The DRV_USART_Initialize routine must have been called for the specified USART driver instance.
5.1 Driver Library Help MPLAB Harmony Help USART Driver Library
5-525
Parameters
Parameters Description
object Object handle for the specified driver instance (returned from
DRV_USART_Initialize)
Returns
None.
Remarks
This routine is normally not called directly by an application. It is called by the system's Tasks routine (SYS_Tasks) or by the
apropriate raw ISR.
This routine may excute in an ISR context and will never block or access any resources that may cause it to block.
Example
SYS_MODULE_OBJ object; // Returned from DRV_USART_Initialize
while (true)
{
DRV_USART_TasksTX (object);
// Do other tasks
}
5.1.11.7.2 Data Transfer Functions
5.1.11.7.2.1 DRV_USART_BufferAdd Function
C
DRV_HANDLE DRV_USART_BufferAdd(
const DRV_HANDLE handle,
DRV_USART_IO_BUFFER * bufferObject
);
Description
Starts the writes to the communication channel.
Preconditions
The DRV_USART_Initialize routine must have been called for the specified USART device instance and the
DRV_USART_Status must have returned SYS_STATUS_READY.
DRV_USART_Open must have been called to obtain a valid opened device handle.
DRV_IO_INTENT_READ or DRV_IO_INTENT_WRITE or DRV_IO_INTENT_READWRITE must have been specified in the
DRV_USART_Open call.
Parameters
Parameters Description
handle Handle of the communication channel as return by the DRV_USART_Open
function.
bufferObject Buffer Object that needs to be specified for the buffer that needs to be read or
written.
Returns
The buffer handle, which should be used to query how many bytes have been written or read using the function
5.1 Driver Library Help MPLAB Harmony Help USART Driver Library
5-526
DRV_USART_OperationStatus
Remarks
If the DRV_IO_INTENT_BLOCKING is requested and the driver was built appropriately to support blocking behavior in an OS
environment the call will block until the operation is complete.
For DRV_IO_INTENT_NONBLOCKING request the driver client can call the DRV_USART_ClientStatus operation to find out
when the module is in the ready state.
In any circumstance, the client supplied buffer has to be non-volatile and it is not allowed to go out of scope until the operation
completes.
Affected by the following configuration options:
• DRV_USART_CONFIG_SUPPORT_CLIENT_ACCESS_BLOCKING
• DRV_USART_CONFIG_BUFFER_QUEUE_SLOTS_MAX
• DRV_USART_CONFIG_SUPPORT_BUFFERQ
Example
void Callback(void);
uint8_t mybuffer[MY_BUFFER_SIZE];
int8_t bytesWritten = 0;
DRV_BUFFER_HANDLE bufferHandle = NULL;
DRV_USART_IO_BUFFER buffer1;
void Callback(void)
{
Nop();
}
buffer1.buffer = writeBuffer2;
buffer1.bufferSize = sizeof(writeBuffer2);
buffer1.xferCallback = Callback;
buffer1.flags = DRV_USART_BUFFER_FLAG_WRITE;
// myUSARTHandle is the handle returned by the DRV_USART_Open function.
bufferHandle = DRV_USART_BufferAdd(myUSARThandle, &buffer1);
while(bytesWritten < MY_BUFFER_SIZE)
{
bytesWritten = DRV_USART_BufferTransferStatus(handle, bufferHandle);
}
5.1.11.7.2.2 DRV_USART_BufferStatus Function
C
DRV_USART_BUFFER_STATUS DRV_USART_BufferStatus(
DRV_HANDLE handle,
const DRV_HANDLE bufferHandle
);
Description
This function provides the current status of the buffer identified by the given buffer handle.
Preconditions
The DRV_USART_Initialize routine must have been called for the specified USART device instance and the
DRV_USART_Status must have returned SYS_STATUS_READY.
DRV_USART_Open must have been called to obtain a valid opened device handle.
DRV_IO_INTENT_READ or DRV_IO_INTENT_WRITE or DRV_IO_INTENT_READWRITE must have been specified in the
5.1 Driver Library Help MPLAB Harmony Help USART Driver Library
5-527
DRV_USART_Open call.
The "bufferHandle parameter must be the return value from a call to the "DRV_USART_BufferAdd" function.
Parameters
Parameters Description
handle Handle of the communication channel as return by the DRV_USART_Open
function.
bufferHandle Handle to the buffer in question. Must be the return value from a call to the
"DRV_USART_BufferAdd" function.
Returns
The current status of the given buffer.
Remarks
See the definition of "DRV_USART_BUFFER_STATUS" for a complete description of all possible status values.
Example
DRV_USART_BUFFER_STATUS bufferStatus;
bufferStatus = DRV_USART_BufferStatus ( uartHandle, uartBufferHandle );
if ( DRV_USART_BUFFER_COMPLETED == bufferStatus )
{
// Handle Buffer Complete
}else
{
// Handle other
}
5.1.11.7.2.3 DRV_USART_Read Function
C
int DRV_USART_Read(
const DRV_HANDLE handle,
uint8_t * buffer,
const unsigned int numbytes
);
Description
This routine reads data from the USART.
Preconditions
The DRV_USART_Initialize routine must have been called for the specified USART driver instance.
DRV_USART_Open must have been called to obtain a valid opened device handle.
DRV_IO_INTENT_READ or DRV_IO_INTENT_READWRITE must have been specified in the DRV_USART_Open call.
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open routine
buffer Buffer into which the data read from the USART instance will be placed.
numbytes Total number of bytes that need to be read from the module instance (must be
equal to or less than the size of the buffer)
Returns
Number of bytes actually copied into the caller's buffer or -1 if there is an error (call DRV_USART_ClientStatus to identify the
error).
5.1 Driver Library Help MPLAB Harmony Help USART Driver Library
5-528
Remarks
If the DRV_IO_INTENT_BLOCKING flag was given in the call to the DRV_USART_Open routine and the driver was built to
support blocking behavior the call will block until the operation is complete.
If the DRV_IO_INTENT_NONBLOCKING flag was given in the call to the DRV_USART_Open routine or the driver was built to
only support non-blocking behavior the call will return immediately, identifying how many bytes of data were actually copied into
the client's buffer and the client must call DRV_USART_Read again with adjusted parameters as shown in the example.
Example
DRV_HANDLE handle; // Returned from DRV_USART_Open
char myBuffer[MY_BUFFER_SIZE];
unsigned int count;
unsigned int total;
total = 0;
do
{
count = DRV_USART_Read(myUSARTHandle, &myBuffer[total], MY_BUFFER_SIZE - total);
total += count;
// Do something else...
} while( total < MY_BUFFER_SIZE );
5.1.11.7.2.4 DRV_USART_ReadByte Function
C
bool DRV_USART_ReadByte(
const DRV_HANDLE handle,
char * byte
);
Description
This routine reads a byte of data from the USART.
Preconditions
The DRV_USART_Initialize routine must have been called for the specified USART driver instance.
DRV_USART_Open must have been called to obtain a valid opened device handle.
DRV_IO_INTENT_READ or DRV_IO_INTENT_READWRITE must have been specified in the DRV_USART_Open call.
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open routine
byte A variable in which data is read into
Returns
true - Read successful false - Read failed
Remarks
If the DRV_IO_INTENT_BLOCKING flag was given in the call to the DRV_USART_Open routine and the driver was built to
support blocking behavior the call will block until the operation is complete.
If the DRV_IO_INTENT_NONBLOCKING flag was given in the call to the DRV_USART_Open routine or the driver was built to
only support non-blocking behavior the call will return immediately. If data is not available, a zero (0) value will be returned and
an underrun error status will be captured. To ensure that valid data is returned, the caller must first check the return value to
DRV_USART_TransferStatus as shown in the example.
5.1 Driver Library Help MPLAB Harmony Help USART Driver Library
5-529
Example
DRV_HANDLE handle; // Returned from DRV_USART_Open
bool status;
char byte;
bool = DRV_USART_ReadByte(handle, &byte);
// Do something else...
5.1.11.7.2.5 DRV_USART_TransferStatus Function
C
DRV_USART_TRANSFER_STATUS DRV_USART_TransferStatus(
const DRV_HANDLE handle
);
Description
This returns the transmitter and receiver transfer status.
Preconditions
The DRV_USART_Initialize routine must have been called for the specified USART driver instance.
DRV_USART_Open must have been called to obtain a valid opened device handle.
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open routine
Returns
A DRV_USART_TRANSFER_STATUS value describing the current status of the transfer.
Remarks
The returned status may contain a value with more than one of the bits specified in the DRV_USART_TRANSFER_STATUS
enumeration set. The caller should perform an "AND" with the bit of interest and verify if the result is non-zero (as shown in the
example) to verify the desired status bit.
Example
DRV_HANDLE handle; // Returned from DRV_USART_Open
if (DRV_USART_TRANSFER_STATUS_TX_EMPTY & DRV_USART_TransferStatus(handle) )
{
// All transmitter data has been sent.
}
5.1.11.7.2.6 DRV_USART_Write Function
C
bool DRV_USART_Write(
const DRV_HANDLE handle,
const uint8_t * buffer,
const uint32_t numbytes
);
Description
This routine writes data to the USART.
5.1 Driver Library Help MPLAB Harmony Help USART Driver Library
5-530
Preconditions
The DRV_USART_Initialize routine must have been called for the specified USART driver instance.
DRV_USART_Open must have been called to obtain a valid opened device handle.
DRV_IO_INTENT_WRITE or DRV_IO_INTENT_READWRITE must have been specified in the DRV_USART_Open call.
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open routine
buffer Buffer containing the data write to the USART instance
numbytes Total number of bytes that to write to the USART instance (must be equal to or
less than the size of the buffer)
Returns
Number of bytes actually written to the USART or -1 if there is an error (call DRV_USART_ClientStatus to identify the error)
Remarks
If the DRV_IO_INTENT_BLOCKING flag was given in the call to the DRV_USART_Open routine and the driver was built to
support blocking behavior the call will block until the operation is complete.
If the DRV_IO_INTENT_NONBLOCKING flag was given in the call to the DRV_USART_Open routine or the driver was built to
only support non-blocking behavior the call will return immediately, identifying how many bytes of data were actually written to
the USART and the client must call DRV_USART_Write again with adjusted parameters as shown in the example.
Example
DRV_HANDLE handle; // Returned from DRV_USART_Open
char myBuffer[MY_BUFFER_SIZE];
unsigned int count;
unsigned int total;
total = 0;
do
{
count = DRV_USART_Write(myUSARTHandle, &myBuffer[total], MY_BUFFER_SIZE - total);
total += count;
// Do something else...
} while( total < MY_BUFFER_SIZE );
5.1.11.7.2.7 DRV_USART_WriteByte Function
C
bool DRV_USART_WriteByte(
const DRV_HANDLE handle,
const uint8_t byte
);
Description
This routine writes a byte of data to the USART.
Preconditions
The DRV_USART_Initialize routine must have been called for the specified USART driver instance.
DRV_USART_Open must have been called to obtain a valid opened device handle.
DRV_IO_INTENT_WRITE or DRV_IO_INTENT_READWRITE must have been specified in the DRV_USART_Open call.
5.1 Driver Library Help MPLAB Harmony Help USART Driver Library
5-531
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open routine
byte Data byte to write to the USART
Returns
true - Write successful. false - Write failed.
Remarks
If the DRV_IO_INTENT_BLOCKING flag was given in the call to the DRV_USART_Open routine and the driver was built to
support blocking behavior the call will block until the operation is complete.
If the DRV_IO_INTENT_NONBLOCKING flag was given in the call to the DRV_USART_Open routine or the driver was built to
only support non-blocking behavior the call will return immediately. If the driver was not able to accept the data, an overrun error
status will be captured. To ensure that the driver is ready to accept data, the caller must first check the return value to
DRV_USART_TransferStatus as shown in the example.
Example
DRV_HANDLE handle; // Returned from DRV_USART_Open
bool status;
// Pre-initialize myBuffer with MY_BUFFER_SIZE bytes of valid data.
status = DRV_USART_WriteByte(handle, myBuffer[numBytes++]);
// Do something else...
}
5.1.11.7.3 Setup and Status Functions
5.1.11.7.3.1 DRV_USART_BufferTransferStatus Function
C
int8_t DRV_USART_BufferTransferStatus(
const DRV_HANDLE handle,
const DRV_HANDLE bufferHandle
);
Description
Gets the number of bytes which are written or read for the transaction handle
Preconditions
The DRV_USART_Initialize routine must have been called for the specified USART device instance and the
DRV_USART_Status must have returned SYS_STATUS_READY.
DRV_USART_Open must have been called to obtain a valid opened device handle.
The function DRV_USART_BufferAdd should be called before calling this function and should have returned a valid buffer
handle.
Parameters
Parameters Description
handle Handle of the communication channel as return by the DRV_USART_Open
function.
5.1 Driver Library Help MPLAB Harmony Help USART Driver Library
5-532
bufferHandle Handle of the buffer returned by the DRV_USART_BufferAdd
Returns
The number of bytes read if the buffer id is DRV_IO_BUFFER_READ or number of bytes written when the buffer id is
DRV_IO_BUFFER_WRITE. If -1 is returned
Remarks
None.
Example
void Callback(void);
uint8_t mybuffer[MY_BUFFER_SIZE];
int8_t bytesWritten = 0;
DRV_BUFFER_HANDLE bufferHandle = NULL;
DRV_USART_IO_BUFFER buffer1;
void Callback(void)
{
Nop();
}
buffer1.buffer = writeBuffer2;
buffer1.bufferSize = sizeof(writeBuffer2);
buffer1.xferCallback = Callback;
buffer1.flags = DRV_USART_BUFFER_FLAG_WRITE;
// myUSARTHandle is the handle returned by the DRV_USART_Open function.
bufferHandle = DRV_USART_BufferAdd(myUSARThandle, &buffer1);
while(bytesWritten < MY_BUFFER_SIZE)
{
bytesWritten = DRV_USART_BufferTransferStatus(handle, bufferHandle);
}
5.1.11.7.3.2 DRV_USART_ClientStatus Function
C
DRV_USART_CLIENT_STATUS DRV_USART_ClientStatus(
const DRV_HANDLE handle
);
Description
This routine gets the client-specfic status of the USART driver associated with the given handle.
Preconditions
The DRV_USART_Initialize routine must have been called.
DRV_USART_Open must have been called to obtain a valid opened device handle.
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open routine
Returns
A DRV_USART_CLIENT_STATUS value describing the current status of the driver
Remarks
This routine will not block for hardware access and will immediately return the current status.
5.1 Driver Library Help MPLAB Harmony Help USART Driver Library
5-533
Example
DRV_HANDLE handle; // Returned from DRV_USART_Open
DRV_USART_CLIENT_STATUS clientStatus;
clientStatus = DRV_USART_ClientStatus(handle);
if(DRV_USART_CLIENT_STATUS_ERROR >= clientStatus)
{
// Handle the error
}
5.1.11.7.3.3 DRV_USART_Close Function
C
void DRV_USART_Close(
const DRV_HANDLE handle
);
Description
This routine closes an opened-instance of the USART driver, invalidating the handle.
Preconditions
The DRV_USART_Initialize routine must have been called for the specified USART driver instance.
DRV_USART_Open must have been called to obtain a valid opened device handle.
Parameters
Parameters Description
handle A valid open-instance handle, returned from the driver's open routine
Returns
None
Remarks
After calling this routine, the handle passed in "handle" must not be used with any of the remaining driver routines. A new handle
must be obtained by calling DRV_USART_Open before the caller may use the driver again.
If DRV_IO_INTENT_BLOCKING was requested and the driver was built appropriately to support blocking behavior call may
block until the operation is complete.
If DRV_IO_INTENT_NON_BLOCKING request the driver client can call the DRV_USART_Status operation to find out when the
module is in the ready state (the handle is no longer valid).
Usually there is no need for the driver client to verify that the Close operation has completed.
Example
DRV_HANDLE handle; // Returned from DRV_USART_Open
DRV_USART_Close(handle);
5.1.11.7.3.4 DRV_USART_Open Function
C
DRV_HANDLE DRV_USART_Open(
const SYS_MODULE_INDEX index,
const DRV_IO_INTENT ioIntent
);
5.1 Driver Library Help MPLAB Harmony Help USART Driver Library
5-534
Description
This routine opens the specified USART driver instance and provides a handle that must be provided to all other client-level
operations to identify the caller and the instance of the driver.
Preconditions
Function DRV_USART_Initialize must have been called before calling this function.
Parameters
Parameters Description
drvIndex Identifier for the object instance to be opened
intent Zero or more of the values from the enumeration DRV_IO_INTENT "or'd" together
to indicate the intended use of the driver
Returns
If successful, the routine returns a valid open-instance handle (a number identifying both the caller and the module instance).
If an error occurs, the return value is DRV_HANDLE_INVALID.
Remarks
The handle returned is valid until the DRV_USART_Close routine is called.
This routine will NEVER block waiting for hardware.
If the DRV_IO_INTENT_BLOCKING is requested and the driver was built appropriately to support blocking behavior, then other
client-level operations may block waiting on hardware until they are complete.
If DRV_IO_INTENT_NON_BLOCKING is requested the driver client can call the DRV_USART_ClientStatus operation to find out
when the module is in the ready state.
If the requested intent flags are not supported, the routine will return DRV_HANDLE_INVALID.
Example
DRV_HANDLE handle;
handle = DRV_USART_Open(DRV_USART_INDEX_0, DRV_IO_INTENT_EXCLUSIVE);
if (DRV_HANDLE_INVALID == handle)
{
// Unable to open the driver
}
5.1.11.7.3.5 DRV_USART_Status Function
C
SYS_STATUS DRV_USART_Status(
SYS_MODULE_OBJ object
);
Description
This routine provides the current status of the USART driver module.
Preconditions
Function DRV_USART_Initialize should have been called before calling this function.
Parameters
Parameters Description
object Driver object handle, returned from the DRV_USART_Initialize routine
5.1 Driver Library Help MPLAB Harmony Help USART Driver Library
5-535
Returns
SYS_STATUS_READY - Indicates that the driver is busy with a previous system level operation and cannot start another
Note Any value greater than SYS_STATUS_READY is also a normal running state in which the driver is ready to accept new
operations.
SYS_STATUS_BUSY - Indicates that the driver is busy with a previous system level operation and cannot start another
SYS_STATUS_ERROR - Indicates that the driver is in an error state
Remarks
Any value less than SYS_STATUS_ERROR is also an error state.
SYS_MODULE_DEINITIALIZED - Indicates that the driver has been de-initialized
This value is less than SYS_STATUS_ERROR
The this operation can be used to determine when any of the driver's module level operations has completed.
If the status operation returns SYS_STATUS_BUSY, the a previous operation has not yet completed. Once the status operation
returns SYS_STATUS_READY, any previous operations have completed.
The value of SYS_STATUS_ERROR is negative (-1). Any value less than that is also an error state.
This routine will NEVER block waiting for hardware.
If the Status operation returns an error value, the error may be cleared by calling the reinitialize operation. If that fails, the
deinitialize operation will need to be called, followed by the initialize operation to return to normal operations.
Example
SYS_MODULE_OBJ object; // Returned from DRV_USART_Initialize
SYS_STATUS usartStatus;
usartStatus = DRV_USART _Status(object);
else if (SYS_STATUS_ERROR >= usartStatus)
{
// Handle error
}
5.1.11.7.4 Data Types and Constants
5.1.11.7.4.1 DRV_USART_AUTO_BAUD_ENABLE Macro
C
#define DRV_USART_AUTO_BAUD_ENABLE true
Description
Auto Baud enable
This macro configures enabling the auto baud. This is a static override of initialization parameter. This is the static override of the
dynamic intialization passed using DRV_USART_INIT. The possible values it can take:
• true - Enables Auto Baud
• false - Disable Auto Baud
5.1 Driver Library Help MPLAB Harmony Help USART Driver Library
5-536
5.1.11.7.4.2 DRV_USART_BAUD_RATE Macro
C
#define DRV_USART_BAUD_RATE
Description
USART Baud Rate configuration
This macro controls the operation of the driver for Baud rate configuration. This is the static override of the dynamic intialization
passed using DRV_USART_INIT.
5.1.11.7.4.3 DRV_USART_BYTE_Q_SIZE_RX Macro
C
#define DRV_USART_BYTE_Q_SIZE_RX 16
Description
USART Byte mode internal buffer Rx size configuration
This macro controls the operation of the driver for defining the size of the Rx buffer
5.1.11.7.4.4 DRV_USART_BYTE_Q_SIZE_TX Macro
C
#define DRV_USART_BYTE_Q_SIZE_TX 16
Description
USART Byte mode internal buffer Tx size configuration
This macro controls the operation of the driver for defining the size of the Tx buffer
5.1.11.7.4.5 DRV_USART_CLIENTS_NUMBER Macro
C
#define DRV_USART_CLIENTS_NUMBER 2
Description
USART Client Count Configuration
Sets up the maximum number of clients that can be connected to any hardware instance.
Remarks
None
5.1.11.7.4.6 DRV_USART_HANDSHAKE_MODE Macro
C
#define DRV_USART_HANDSHAKE_MODE
Description
Hand Shake Mode
This macro configures the handshake mode. This is the static override of the dynamic intialization passed using
DRV_USART_INIT. The possible values that it can take are
5.1 Driver Library Help MPLAB Harmony Help USART Driver Library
5-537
• DRV_USART_HANDSHAKE_MODE_FLOWCONTROL
• DRV_USART_HANDSHAKE_MODE_SIMPLEX
• DRV_USART_HANDSHAKE_MODE_NONE
5.1.11.7.4.7 DRV_USART_INDEX Macro
C
#define DRV_USART_INDEX DRV_USART_INDEX_2
Description
Index - Used for static drivers
USART Static Index selection for the driver object reference
Remarks
This index is required to make a reference to the driver object
5.1.11.7.4.8 DRV_USART_INDEX_0 Macro
C
#define DRV_USART_INDEX_0 0
Description
Driver USART Module Index reference
These constants provide timer driver index definitions.
Remarks
These constants should be used in place of hard-coded numeric literals.
These values should be passed into the DRV_USART_Initialize and DRV_USART_Open routines to identify the driver instance
in use.
5.1.11.7.4.9 DRV_USART_INDEX_1 Macro
C
#define DRV_USART_INDEX_1 1
Description
This is macro DRV_USART_INDEX_1.
5.1.11.7.4.10 DRV_USART_INDEX_2 Macro
C
#define DRV_USART_INDEX_2 2
Description
This is macro DRV_USART_INDEX_2.
5.1.11.7.4.11 DRV_USART_INDEX_3 Macro
C
#define DRV_USART_INDEX_3 3
5.1 Driver Library Help MPLAB Harmony Help USART Driver Library
5-538
Description
This is macro DRV_USART_INDEX_3.
5.1.11.7.4.12 DRV_USART_INDEX_4 Macro
C
#define DRV_USART_INDEX_4 4
Description
This is macro DRV_USART_INDEX_4.
5.1.11.7.4.13 DRV_USART_INDEX_5 Macro
C
#define DRV_USART_INDEX_5 5
Description
This is macro DRV_USART_INDEX_5.
5.1.11.7.4.14 DRV_USART_INDEX_COUNT Macro
C
#define DRV_USART_INDEX_COUNT USART_NUMBER_OF_MODULES
Description
USART Driver Module Index Count
This constant identifies USART driver index definitions.
Remarks
This constant should be used in place of hard-coded numeric literals.
This value is part-specific.
5.1.11.7.4.15 DRV_USART_INSTANCES_NUMBER Macro
C
#define DRV_USART_INSTANCES_NUMBER 2
Description
USART driver objects configuration
Sets up the maximum number of hardware instances that can be supported
Remarks
None
5.1.11.7.4.16 DRV_USART_INTERRUPT_MODE Macro
C
#define DRV_USART_INTERRUPT_MODE
5.1 Driver Library Help MPLAB Harmony Help USART Driver Library
5-539
Description
USART Interrupt Mode Operation Control
This macro controls the operation of the driver in the interrupt mode of operation.The possible values it can take are
• true - Enables the interrupt mode
• false - Enables the polling mode
5.1.11.7.4.17 DRV_USART_INTERRUPT_SOURCE_ERROR Macro
C
#define DRV_USART_INTERRUPT_SOURCE_ERROR INT_SOURCE_USART_2_ERROR
Description
Error Interrupt Source
This macro defines the interrupt source for the error interrupt. This is the static override of the dynamic intialization passed using
DRV_USART_INIT.
5.1.11.7.4.18 DRV_USART_INTERRUPT_SOURCE_RX Macro
C
#define DRV_USART_INTERRUPT_SOURCE_RX INT_SOURCE_USART_2_RECEIVE
Description
RX Interrupt Source
Macro to define the Rx interrupt source in case of static driver
Remarks
Refer to the INT PLIB document for more information on INT_SOURCE enumeration
5.1.11.7.4.19 DRV_USART_INTERRUPT_SOURCE_TX Macro
C
#define DRV_USART_INTERRUPT_SOURCE_TX INT_SOURCE_USART_2_TRANSMIT
Description
TX Interrupt Source
Macro to define the Tx interrupt source in case of static driver
Remarks
Refer to the INT PLIB document for more information on PLIB_INT_SOURCE enumeration
5.1.11.7.4.20 DRV_USART_LINE_CONTROL Macro
C
#define DRV_USART_LINE_CONTROL DRV_USART_LINE_CONTROL_8N1
Description
Line Control Mode
This macro defines the line control mode as 8 data bits, even parity and 1 stop bit. It provides a static override of the initialization
configuration of the line control mode. The possible values it can take are:
5.1 Driver Library Help MPLAB Harmony Help USART Driver Library
5-540
• DRV_USART_LINE_CONTROL_8E1
• DRV_USART_LINE_CONTROL_8E2
• DRV_USART_LINE_CONTROL_8O1
• DRV_USART_LINE_CONTROL_8O2
• DRV_USART_LINE_CONTROL_8N1
• DRV_USART_LINE_CONTROL_8N2
• DRV_USART_LINE_CONTROL_9N1
5.1.11.7.4.21 DRV_USART_OPERATION_MODE Macro
C
#define DRV_USART_OPERATION_MODE DRV_USART_OPERATION_MODE_RS232
Description
USART mode
This macro controls support modes of the USART driver . The possible values it can take are:
• DRV_USART_OPERATION_MODE_IRDA
• DRV_USART_OPERATION_MODE_RS232
• DRV_USART_OPERATION_MODE_RS485
• DRV_USART_OPERATION_MODE_SYNC_MASTER
• DRV_USART_OPERATION_MODE_SYNC_SLAVE
• DRV_USART_OPERATION_MODE_LOOPBACK
Remarks
None
5.1.11.7.4.22 DRV_USART_PERIPHERAL_ID Macro
C
#define DRV_USART_PERIPHERAL_ID
Description
Plib id
This macro configures the PLIB Id for the driver. This is the static override of the dynamic intialization passed using
DRV_USART_INIT.
5.1.11.7.4.23 DRV_USART_POLARITY_INVERTED_RX Macro
C
#define DRV_USART_POLARITY_INVERTED_RX true
Description
USART RX Polarity Mode.
This macro defines the polarity of the RX pin. The possible values it can take are
• true - polarity is inverted
• false - polarity is not inverted
5.1 Driver Library Help MPLAB Harmony Help USART Driver Library
5-541
Remarks
None.
5.1.11.7.4.24 DRV_USART_POLARITY_INVERTED_TX Macro
C
#define DRV_USART_POLARITY_INVERTED_TX true
Description
USART TX Polarity Mode.
This macro defines the polarity of the TX pin. The possible values it can take are
• true - polarity is inverted
• false - polarity is not inverted
Remarks
None
5.1.11.7.4.25 DRV_USART_POWER_STATE Macro
C
#define DRV_USART_POWER_STATE SYS_MODULE_POWER_IDLE_STOP
Description
USART power state configuration
This macro controls the power state of the USART
Remarks
This feature may not be available in the device or the USART module selected
5.1.11.7.4.26 DRV_USART_WAKE_ON_START_ENABLE Macro
C
#define DRV_USART_WAKE_ON_START_ENABLE
Description
Wake on start enable
This macro configures that the peripheral should wake up on start.
5.1.11.7.4.27 DRV_USART_XFER_BUFFER_NUMBER Macro
C
#define DRV_USART_XFER_BUFFER_NUMBER 10
Description
USART transfer buffer configuration
This macro controls the transfer buffer depth
Remarks
This feature may not be available in the device or the USART module selected
5.1 Driver Library Help MPLAB Harmony Help USART Driver Library
5-542
5.1.11.7.4.28 DRV_USART_BUFFER_FLAGS Enumeration
C
typedef enum {
DRV_USART_BUFFER_FLAG_WRITE,
DRV_USART_BUFFER_FLAG_WRITE_AFTER_BREAK,
DRV_USART_BUFFER_FLAG_WRITE_TO_ADDRESS,
DRV_USART_BUFFER_FLAG_READ_FROM_ADDRESS,
DRV_USART_BUFFER_FLAG_READ,
DRV_USART_BUFFER_FLAG_STOP_ON_ERROR
} DRV_USART_BUFFER_FLAGS;
Description
USART IO Types
This enumeration defines the IO types that can be serviced by the USART driver.
Members
Members Description
DRV_USART_BUFFER_FLAG_WRITE Write Buffer
DRV_USART_BUFFER_FLAG_WRITE_AFTER_BREAK Write Buffer After Sending Break
DRV_USART_BUFFER_FLAG_WRITE_TO_ADDRESS Write Buffer to the address
DRV_USART_BUFFER_FLAG_READ_FROM_ADDRESS Raed Buffer from the address
DRV_USART_BUFFER_FLAG_READ Read Buffer
DRV_USART_BUFFER_FLAG_STOP_ON_ERROR Instructs the driver to stop processing if error is encountered
Remarks
None
5.1.11.7.4.29 DRV_USART_BUFFER_STATUS Enumeration
C
typedef enum {
DRV_USART_BUFFER_COMPLETED,
DRV_USART_BUFFER_QUEUED,
DRV_USART_BUFFER_IN_PROGRESS,
DRV_USART_BUFFER_ERROR_UNKNOWN,
DRV_USART_BUFFER_ERROR_RX_OVERFLOW
} DRV_USART_BUFFER_STATUS;
Description
USART Buffer Status
Defines the states that an USART buffer can be in during its lifetime
Members
Members Description
DRV_USART_BUFFER_COMPLETED Done OK and ready
DRV_USART_BUFFER_QUEUED Scheduled but not started
DRV_USART_BUFFER_IN_PROGRESS Currently being in transfer
DRV_USART_BUFFER_ERROR_UNKNOWN Unknown buffer
DRV_USART_BUFFER_ERROR_RX_OVERFLOW Read data lost: rx process not fast enough
5.1 Driver Library Help MPLAB Harmony Help USART Driver Library
5-543
Remarks
As buffers may have a limited life span, so too have the associated handles and status info. Once a buffer transfer is completed
(and possibly notified and acknowledged) it will be discarded. The status of a discarded buffer is no longer maintained by the
driver.
5.1.11.7.4.30 DRV_USART_CALLBACK Type
C
typedef void (* DRV_USART_CALLBACK)(void);
Description
USART Callback Function
This data type defines a pointer callback function.
Remarks
A USART callback function must have the following function signature:
void MyCallBack ( DRV_USART_BUFFER_HANDLE *bufferHandle );
Where "MyCallBack" can be any name desired as the routine is called through the pointer.
A pointer of this type is passed into the DRV_USART_RegisterCallbacks routine.
5.1.11.7.4.31 DRV_USART_CLIENT_STATUS Enumeration
C
typedef enum {
DRV_USART_CLIENT_STATUS_READY,
DRV_USART_CLIENT_STATUS_BUSY,
DRV_USART_OVERRUN_ERROR,
DRV_USART_PARITY_ERROR,
DRV_USART_FRAMING_ERROR,
DRV_USART_STATUS_INVALID
} DRV_USART_CLIENT_STATUS;
Description
USART Client Status
Defines the various client status codes.
Members
Members Description
DRV_USART_CLIENT_STATUS_READY Up and running, ready to start new operations
DRV_USART_CLIENT_STATUS_BUSY Operation in progress, unable to start a new one
DRV_USART_OVERRUN_ERROR Overrun Error Occured
DRV_USART_PARITY_ERROR Parity Error
DRV_USART_FRAMING_ERROR Framing Error
DRV_USART_STATUS_INVALID client Invalid
Remarks
None
5.1 Driver Library Help MPLAB Harmony Help USART Driver Library
5-544
5.1.11.7.4.32 DRV_USART_HANDSHAKE_MODES Enumeration
C
typedef enum {
DRV_USART_HANDSHAKE_MODE_FLOWCONTROL,
DRV_USART_HANDSHAKE_MODE_SIMPLEX,
DRV_USART_HANDSHAKE_MODE_NONE
} DRV_USART_HANDSHAKE_MODES;
Description
USART Handshake Modes
This data type identifies the handshaking modes available on the USART module.
Members
Members Description
DRV_USART_HANDSHAKE_MODE_FLOWCONTROL Handshaking occurs in Flow Control Mode
DRV_USART_HANDSHAKE_MODE_SIMPLEX Handshaking occurs in Simplex Mode
DRV_USART_HANDSHAKE_MODE_NONE No Handshaking
Remarks
Not all modes are available on all micro-controllers.
5.1.11.7.4.33 DRV_USART_INIT Structure
C
typedef struct {
SYS_MODULE_INIT moduleInit;
USART_MODULE_ID usartID;
uint8_t operationMode;
uint8_t initFlags;
DRV_USART_LINE_CONTROL_MODES lineControlMode;
uint32_t brgValue;
DRV_USART_OPERATION_MODE_INIT operationModeInit;
DRV_USART_HANDSHAKE_MODES handShakeMode;
uint32_t txInterruptSource;
uint32_t rxInterruptSource;
uint32_t errorInterruptSource;
uint32_t rxQueueSize;
uint32_t txQueueSize;
} DRV_USART_INIT;
Description
USART Driver Initialization Data
This data type defines the data required to initialize or reinitialize the USART driver.
Members
Members Description
SYS_MODULE_INIT moduleInit; System module initialization
USART_MODULE_ID usartID; Identifies USART hardware module (PLIB-level) ID
uint8_t operationMode; Operation Modes of the driver
uint8_t initFlags; Flags for the usart initialization
DRV_USART_LINE_CONTROL_MODES
lineControlMode;
Control the line control configuration
5.1 Driver Library Help MPLAB Harmony Help USART Driver Library
5-545
uint32_t brgValue; Baud Rate value to be used, if not using auto baud
DRV_USART_OPERATION_MODE_INIT
operationModeInit;
Operation mode initialization data
DRV_USART_HANDSHAKE_MODES
handShakeMode;
Handshake Mode
uint32_t txInterruptSource; Interrupt Source for TX Interrupt INT_SOURCE txInterruptSource;
uint32_t rxInterruptSource; Interrupt Source for RX Interrupt INT_SOURCE rxInterruptSource;
uint32_t errorInterruptSource; Interrupt Source for Error Interrupt INT_SOURCE errorInterruptSource;
Remarks
Not all the init features are available for all the microcontrollers
5.1.11.7.4.34 DRV_USART_INIT_FLAGS Enumeration
C
typedef enum {
DRV_USART_INIT_FLAG_WAKE_ON_START_ENABLE,
DRV_USART_INIT_FLAG_AUTO_BAUD_ENABLE
} DRV_USART_INIT_FLAGS;
Description
USART Initialization flags
Defines the various flags which determine specific modes
Members
Members Description
DRV_USART_INIT_FLAG_WAKE_ON_START_ENABLE Flag to setup Wake on Start Operation
DRV_USART_INIT_FLAG_AUTO_BAUD_ENABLE Flag to enable auto baud detection enable.
Remarks
None
5.1.11.7.4.35 DRV_USART_IO_BUFFER Structure
C
typedef struct {
DRV_USART_BUFFER_FLAGS flags;
char * buffer;
uint32_t bufferSize;
uint8_t address;
DRV_USART_CALLBACK xferCallback;
} DRV_USART_IO_BUFFER;
Description
USART Driver IO Buffer
This structure holds information that the client must pass the driver to enqueue a buffer to be transferred by a read or write
operation.
Members
Members Description
DRV_USART_BUFFER_FLAGS flags; Defines the IO Type this buffer is associated with
char * buffer; The buffer which needs to be read or written
5.1 Driver Library Help MPLAB Harmony Help USART Driver Library
5-546
uint32_t bufferSize; The size of the buffer which needs to be read or written
uint8_t address; The address which needs to be written
Remarks
A pointer to an instance of this structure must be passed to the DRV_USART_BufferAdd routine.
5.1.11.7.4.36 DRV_USART_LINE_CONTROL_MODES Enumeration
C
typedef enum {
DRV_USART_LINE_CONTROL_MODE_8NONE1,
DRV_USART_LINE_CONTROL_MODE_9NONE1,
DRV_USART_LINE_CONTROL_MODE_8EVEN1,
DRV_USART_LINE_CONTROL_MODE_8EVEN2,
DRV_USART_LINE_CONTROL_MODE_8ODD1,
DRV_USART_LINE_CONTROL_MODE_8ODD2
} DRV_USART_LINE_CONTROL_MODES;
Description
USART Line Control Modes
This data type identifies the line control modes available
Members
Members Description
DRV_USART_LINE_CONTROL_MODE_8NONE1 8 Data Bits, No Parity, 1 Stop Bits
DRV_USART_LINE_CONTROL_MODE_9NONE1 9 Data Bits, No Parity, 1 Stop Bits
DRV_USART_LINE_CONTROL_MODE_8EVEN1 8 Data Bits, Even Parity, 1 Stop Bits
DRV_USART_LINE_CONTROL_MODE_8EVEN2 8 Data Bits, Even Parity, 2 Stop Bits
DRV_USART_LINE_CONTROL_MODE_8ODD1 8 Data Bits, Odd Parity, 1 Stop Bits
DRV_USART_LINE_CONTROL_MODE_8ODD2 8 Data Bits, Odd Parity, 2 Stop Bits
Remarks
None
5.1.11.7.4.37 DRV_USART_OPERATION_MODE_INIT Union
C
typedef union {
struct {
uint8_t address;
} RS485Init;
} DRV_USART_OPERATION_MODE_INIT;
Description
Operation Mode Initialization
This data type defines the initialization data required for different operation modes of USART.
Members
Members Description
struct {
uint8_t address;
} RS485Init;
Initialization for RS485 mode
5.1 Driver Library Help MPLAB Harmony Help USART Driver Library
5-547
uint8_t address; Address of the device.
Remarks
None
5.1.11.7.4.38 DRV_USART_OPERATION_MODES Enumeration
C
typedef enum {
DRV_USART_OPERATION_MODE_IRDA = (1 << 0),
DRV_USART_OPERATION_MODE_RS232,
DRV_USART_OPERATION_MODE_RS485,
DRV_USART_OPERATION_MODE_SYNCHRONOUS_MASTER,
DRV_USART_OPERATION_MODE_SYNCHRONOUS_SLAVE,
DRV_USART_OPERATION_MODE_LOOPBACK
} DRV_USART_OPERATION_MODES;
Description
USART Modes of Operation
This data type identifies the modes of the operation of the USART module.
Members
Members Description
DRV_USART_OPERATION_MODE_RS232 RS232 Mode (Asynchronous Mode of Operation)
DRV_USART_OPERATION_MODE_RS485 RS485 Mode (Asynchronous Mode of Operation)
DRV_USART_OPERATION_MODE_SYNCHRONOUS_MASTER Synchronous Master Mode
DRV_USART_OPERATION_MODE_SYNCHRONOUS_SLAVE Synchronous Slave Mode
DRV_USART_OPERATION_MODE_LOOPBACK Loopback Mode
Remarks
Not all modes are available on all microcontrollers. Refer to the data sheet for the microcontroller in use.
5.1.11.7.4.39 DRV_USART_TRANSFER_STATUS Enumeration
C
typedef enum {
DRV_USART_TRANSFER_STATUS_RX_FULL,
DRV_USART_TRANSFER_STATUS_RX_DATA_PRESENT,
DRV_USART_TRANSFER_STATUS_RX_EMPTY,
DRV_USART_TRANSFER_STATUS_TX_FULL,
DRV_USART_TRANSFER_STATUS_TX_EMPTY
} DRV_USART_TRANSFER_STATUS;
Description
USART Driver Transfer Flags
This type specifies the status of the receive or transmit operation.
Members
Members Description
DRV_USART_TRANSFER_STATUS_RX_FULL Indicates that the core driver buffer is full
DRV_USART_TRANSFER_STATUS_RX_DATA_PRESENT Indicates that at least one byte of Data has been received
DRV_USART_TRANSFER_STATUS_RX_EMPTY Indicates that the core driver receiver buffer is empty
5.1 Driver Library Help MPLAB Harmony Help USART Driver Library
5-548
DRV_USART_TRANSFER_STATUS_TX_FULL Indicates that the core driver transmitter buffer is full
DRV_USART_TRANSFER_STATUS_TX_EMPTY Indicates that the core driver transmitter buffer is empty
Remarks
More than one of these values may be OR'd together to create a complete status value. To test a value of this type, the bit of
interrest must be AND'ed with value and checked to see if the result is non-zero.
5.1.11.7.4.40 DRV_USART_XFER_HANDLE Type
C
typedef uintptr_t DRV_USART_XFER_HANDLE;
Description
USART Transfer Handle
Handle for requested transfer..
Remarks
None
5.1.11.8 Files
Files
Name Description
drv_usart.h USART Driver Interface Definition
drv_usart_config_template.h USART Driver Configuration Template.
Description
5.1.11.8.1 drv_usart.h
USART Driver Interface Definition
The USART device driver provides a simple interface to manage the USART or UART modules on Microchip microcontrollers.
This file defines the interface definition for the USART driver.
Enumerations
Name Description
DRV_USART_BUFFER_FLAGS Defines the IO types that can be serviced by the USART driver
DRV_USART_BUFFER_STATUS Defines the buffer status
DRV_USART_CLIENT_STATUS Defines the client status
DRV_USART_HANDSHAKE_MODES Identifies the handshaking modes available on the USART
DRV_USART_INIT_FLAGS Defines specific initialization features
DRV_USART_LINE_CONTROL_MODES Identifies the line control modes available
DRV_USART_OPERATION_MODES Identifies the modes of the operation of the USART module
DRV_USART_TRANSFER_STATUS Specifies the status of the receive or transmit
5.1 Driver Library Help MPLAB Harmony Help USART Driver Library
5-549
Functions
Name Description
DRV_USART_BufferAdd Starts the writes to the communication channel.
DRV_USART_BufferStatus Provides the status of the given buffer
DRV_USART_BufferTransferStatus Gets the number of bytes which are written or read
DRV_USART_ClientStatus Gets current client-specific status the USART driver
DRV_USART_Close Closes an opened-instance of the USART driver
DRV_USART_Deinitialize Deinitializes the specified instance of the USART driver module
DRV_USART_Initialize Initializes the USART instance for the specified driver index
DRV_USART_Open Opens the specified timer driver instance and returns a handle to it
DRV_USART_Read Reads data from the USART
DRV_USART_ReadByte Reads a byte of data from the USART
DRV_USART_Reinitialize Reinitializes the USART driver and refreshes any associated hardware
settings
DRV_USART_Status Gets the current status of the USART driver module.
DRV_USART_TasksError Maintains the driver's error-handling state machine and implements its ISR
DRV_USART_TasksRX Maintains the driver's receiver state machine and implements its ISR
DRV_USART_TasksTX Maintains the driver's tramsmitter state machine and implements its ISR
DRV_USART_TransferStatus Returns the transmitter and receiver transfer status
DRV_USART_Write Writes data to the USART
DRV_USART_WriteByte Writes a byte of data to the USART
Macros
Name Description
DRV_USART_INDEX_0 USART driver index definitions
DRV_USART_INDEX_1 This is macro DRV_USART_INDEX_1.
DRV_USART_INDEX_2 This is macro DRV_USART_INDEX_2.
DRV_USART_INDEX_3 This is macro DRV_USART_INDEX_3.
DRV_USART_INDEX_4 This is macro DRV_USART_INDEX_4.
DRV_USART_INDEX_5 This is macro DRV_USART_INDEX_5.
DRV_USART_INDEX_COUNT Number of valid USART driver indices
Structures
Name Description
DRV_USART_INIT Defines the data required to initialize or reinitialize the USART driver
DRV_USART_IO_BUFFER IO buffer information structure
Types
Name Description
DRV_USART_CALLBACK Pointer to a USART callback function
DRV_USART_XFER_HANDLE Handle for requested transfer..
Unions
Name Description
DRV_USART_OPERATION_MODE_INIT Defines the initialization data required for different operation modes of
USART
5.1 Driver Library Help MPLAB Harmony Help USART Driver Library
5-550
File Name
drv_usart.h
Company
Microchip Technology Incorported
5.1.11.8.2 drv_usart_config_template.h
USART Driver Configuration Template
These file provides the list of all the configurations that can be used with the driver. This file should not be included in the driver.
Macros
Name Description
DRV_USART_AUTO_BAUD_ENABLE Macro configures enabling the auto baud.
DRV_USART_BAUD_RATE Macro controls operation of the driver for Baud rate configuration
DRV_USART_BYTE_Q_SIZE_RX Macro controls operation of the driver for defining the size of the
Rx buffer
DRV_USART_BYTE_Q_SIZE_TX Macro controls operation of the driver for defining the size of the
Tx buffer
DRV_USART_CLIENTS_NUMBER Sets up the maximum number of clients that can be connected to
any hardware instance.
DRV_USART_HANDSHAKE_MODE Configures the handshake mode
DRV_USART_INDEX USART Static Index selection
DRV_USART_INSTANCES_NUMBER Sets up the maximum number of hardware instances that can be
supported
DRV_USART_INTERRUPT_MODE Macro controls operation of the driver in the interrupt mode
DRV_USART_INTERRUPT_SOURCE_ERROR Defines the interrupt source for the error interrupt
DRV_USART_INTERRUPT_SOURCE_RX Macro to define the Rx interrupt source in case of static driver
DRV_USART_INTERRUPT_SOURCE_TX Macro to define the Tx interrupt source in case of static driver
DRV_USART_LINE_CONTROL Macro defines the line control mode
DRV_USART_OPERATION_MODE Defines the mode to be used for the USART driver
DRV_USART_PERIPHERAL_ID Configures the PLIB id
DRV_USART_POLARITY_INVERTED_RX Defines the polarity of the RX pin.
DRV_USART_POLARITY_INVERTED_TX Defines the polarity of the TX pin.
DRV_USART_POWER_STATE Macro controls power state of the USART
DRV_USART_WAKE_ON_START_ENABLE Macro configures that the peripheral should wake up on start
DRV_USART_XFER_BUFFER_NUMBER Transfer buffer depth
File Name
drv_usart_config_template.h
Company
Microchip Technology Incorported
5.1 Driver Library Help MPLAB Harmony Help USB Driver Library
5-551
5.1.12 USB Driver Library
5.1.12.1 Introduction
USB Device Driver Library
for
Microchip Microcontrollers
This library provides an interface to manage the USB module on Microchip family of micro controllers during different modes of
operation.
Description
Overview of the USB Module
The USB module implements the physical layer in a USB based system. In that, it allows the USB stack software to access and
control the USB. The USB module on Microchip's micro controllers are compliant with the USB 2.0 specification. This help file
only provides relevant information about the operation of the USB. The reader is encouraged to refer to the USB 2.0 specification
available at www.usb.org for complete information about the USB.
Not all Microchip microcontrollers feature a USB module. Among the ones that do, the supported features may vary. Please refer
to the device specific data sheet for details on the availability of the USB module and the supported features.
Note: Trademarks and Intellectual Property are property of their respective owners. Customers are responsible for obtaining
appropriate licensing or rights before using this software.
5.1.12.2 Release Notes
MPLAB Harmony Version: v0.70b USB Driver Library Version : 1.0 Release Date: 18Nov2013
New This Release:
• Supports all four (Control, Bulk, Interrupt and Isochronous) USB Transfers.
• Control transfers supported on endpoint 0 only.
• Endpoint 0 pipe is always bidirectional. All other endpoint pipes require Receive and Transmit pipes to be opened separately.
• Supports multiple clients. Device function drivers can communicate on the USB directly via the USB Driver.
• Setup packet reception is automatic and does not require client intervention or scheduling. Clients receive notification when a
Setup packet is received.
• The static multi client version of the driver support one transfer object per Control, Bulk and Interrupt Pipe and supports 2
transfer objects per Isochronous Pipe.
Known Issues:
• Nothing to report in this release
5.1 Driver Library Help MPLAB Harmony Help USB Driver Library
5-552
5.1.12.3 SW License Agreement
(c) 2013 Microchip Technology Inc.
Microchip licenses this software to you solely for use with Microchip products. The software is owned by Microchip and its
licensors, and is protected under applicable copyright laws. All rights reserved.
SOFTWARE IS PROVIDED "AS IS" MICROCHIP EXPRESSLY DISCLAIMS ANY WARRANTY OF ANY KIND, WHETHER
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL MICROCHIP BE LIABLE FOR
ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, HARM TO
YOUR EQUIPMENT, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS
BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR
CONTRIBUTION, OR OTHER SIMILAR COSTS.
To the fullest extent allowed by law, Microchip and its licensors liability shall not exceed the amount of fees, if any, that you have
paid directly to Microchip to use this software.
MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE TERMS.
5.1.12.4 Using the Library
This topic describes the basic architecture of the USB Driver Library and provides information and examples on how to use it.
Interface Header File: drv_usb.h
The interface to the USB Driver library is defined in the "drv_usb.h" header file.
Please refer to the MPLAB Harmony Overview for how the Driver interacts with the framework.
5.1.12.4.1 Library Overview
Refer to the section Driver Overview for how the driver operates in a system. The library interface routines are divided into
various subsections, each of the sub section addresses one of the blocks or the overall operation of the USB module.
Library Interface Section Description
System Functions These routines are typically invoked by the MPLAB Harmony system
module.
Client Functions These routines are used by the driver clients to access driver functionality
Pipe Functions These routines allow clients to manage pipes
Transfer Functions These routines allow clients to manage transfers
Other Functions These routines represent the rest of the driver functionality
Data Types and Constants These data types and constants are required while interacting and
configuring the driver
5.1.12.4.2 Abstraction Model
Figure 1: USB Driver Device Mode Model
Figure 1 shows the functioning of the USB Driver in device mode. In this mode, the driver offers services required to operate the
5.1 Driver Library Help MPLAB Harmony Help USB Driver Library
5-553
USB module as a USB device. The USB Driver supports multiple clients. Each client can receive notifications about USB events
via callback functions. Typical clients could be the Device Layer firmware and one or more function drivers. The Device layer
firmware and the function drivers communicate on the USB via pipes. A pipe is an association between the device's endpoint
and host stack software. An Endpoint 0 Pipe is always bi-directional and is a message pipe. Communication on this pipe is
defined by the USB specification. All other endpoints support stream pipes. The format of the data on a stream pipe is not
specified by the USB specification. Stream pipes are uni-directional. Therefore, two pipes are required to transmit and receive
data on a non-zero endpoint.
Clients schedule USB transfers through a pipe. Transfers on non-zero endpoint pipes can be queued. The USB driver manages
the transactions required to complete the transfer. This is transparent to the clients. Clients can either get an event notification or
can poll to check the completion status of a transfer. Clients can register callback functions to receive USB events notification. A
Transfer complete callback function can be registered while requesting a transfer. This function will be called when the transfer is
terminated. While operating in device mode, the first client of the USB Driver should always be the USB Device Stack Device
layer. Only the first client can schedule control transfers on endpoint 0 (via a pipe) and receive the Setup Token and Setup
Handshake events (along with the other events). Other clients may or may not register an event call back function.
The USB Driver uses configuration macros that control among other things, functional aspects such as maximum number of
clients and maximum pipes.
5.1.12.4.3 How the Library Works
Before the driver is ready for use, its should be configured. Refer to the Configuring the Library section for more details on how
to configure the driver.
To use the USB Driver, initialization and client functions should be invoked in a specific sequence to ensure correct operation.
The following is the sequence in which various routines should be called:
1. Call the DRV_USB_Init() function to initialize the USB Driver. Note that this may be performed by the MPLAB Harmony
system module.
2. In USB device mode operation, the first client should always be the USB Device Stack Device Layer. The Device Layer first
opens the driver via the DRV_USB_Open() function.
3. The Device layer registers an event call back function via the DRV_USB_Device_EventCallBackSet() function.
4. The Device layer assigns a setup packet buffer by using the DRV_USB_Device_SetupPacketBufferAssign() function. The
driver stores the received setup packet in this buffer. Calling this function also enables the USB Device Mode and at this point
the device will attach to the host and be ready to receive setup tokens from the host.
5. The Device Layer waits for the Reset Event. In this event, the device layer creates an endpoint 0 pipe by using the
DRV_USB_Device_PipeSetup() function. The Device layer can optionally register a transfer complete call back function. This
function will be called when a transfer on the endpoint zero is complete.
6. Based on the device enumeration process and the selected configuration, other function drivers may open the driver by using
the DRV_USB_Open() function.
It is strongly recommended that the above sequence be followed for correct operation on the driver.
Note: Not all modes are available on all the devices, please refer to the specific device data sheet for the set of modes
supported.
5.1.12.4.3.1 Driver Initialization
At the time of initialization, the DRV_USB_Initialize() function requires DRV_MODULE_INIT data structure that provides
information required for the function of the driver. The following data is needed:
1. Maximum number of endpoints to be supported by the driver. In case endpoints are skipped, the largest endpoint number
5.1 Driver Library Help MPLAB Harmony Help USB Driver Library
5-554
should be used. For example, if the application uses endpoints 0,1 and 2, then maximum number of endpoints should 3. If the
application uses endpoints 0,1 and 5, then maximum number of endpoints should 6. The latter configuration is not recommended.
2. Maximum side of the endpoint 0. This should match the maximum size that is reported to the host during enumeration.
3. Pointer to byte array whose size is defined DRV_USB_WORKING_BUFFER_SIZE(nEndpoint, maxEP0Size), where
nEndpoint is the maximum number of endpoint as described in point 1 above and maxEP0Size is the maximum endpoint 0 size
as described in point 2 above. These values should match usbInitData.ep0MaxSize and usbInitData.nEndpoints.
4. The PLIB peripheral ID of the USB module to associated with the driver object being initialized.
5. The operation mode of the driver (host, device or OTG). Refer to the Release Notes for supported modes.
5. The ping pong mode to be used by internal endpoint buffers. Refer to the device specific data sheet for supported ping pong
modes.
6. Behavior of the USB module when the microcontroller device enters IDLE mode.
7. Behavior of the USB module when the microcontroller device enters SLEEP mode.
8. Power state of the USB module.
9. USB module interrupts to be enabled. These include the general, error and OTG interrupts. Refer to the USB PLIB
documentation for available module interrupts.
10. The interrupt source of the USB module to be used with the driver instance. Refer to the USB PLIB documentation for
available module interrupts.
The following code snippet shows an example initialization of the driver.
/* The following code snippet shows an example initialization of the
* driver. The USB module to be used in USB1. The maximum number of
* endpoints to be used is 3 i.e endpoint 0,1 and 2. Maximum size of
* endpoint 0 is 64. The module should not automatically suspend when the
* micro-controller enters Sleep mode. The module should continue
* operation when the module enters Idle mode. The ping pong setting
* is set to full ping pong (both RX and TX endpoints have ping
* pong buffers). The power state is set to run at full clock speeds.*/
DRV_USB_INIT moduleInit;
uint8_t internalBuffer[[DRV_USB_WORKING_BUFFER_SIZE(3,64)]
__attribute__((aligned(512)));
usbInitData.usbID = USB_ID_1;
usbInitData.usbModuleSetup.OpMode = USB_OPMODE_DEVICE;
usbInitData.usbModuleSetup.ppMode = USB_PING_PONG__FULL_PING_PONG;
usbInitData.usbModuleSetup.StopInIdle = false;
usbInitData.usbModuleSetup.SuspendInSleep = false;
usbInitData.usbModuleSetup.otgInterruptEnables = ~USB_OTG_INT_ALL ;
usbInitData.usbModuleSetup.generalInterruptEnables = USB_INT_ALL & ~USB_INT_SOF ;
usbInitData.usbModuleSetup.errorInterruptEnables = USB_ERR_INT_ALL ;
usbInitData.workingBuffer = internalBuffer;
usbInitData.ep0MaxSize = 64;
usbInitData.nEndpoints = 3;
usbInitData.sysModuleInit.powerState = SYS_MODULE_POWER_RUN_FULL ;
usbInitData.interruptSource = INT_SOURCE_USB_1;
/* This is how this data structure is passed to the initialize
* function. */
5.1 Driver Library Help MPLAB Harmony Help USB Driver Library
5-555
DRV_USB_Initialize(DRV_USB_INDEX_0, (SYS_MODULE_INIT *) &usbInitData);
5.1.12.4.3.2 Opening the Driver
Once the driver is initialized for device mode, it can be opened by clients. The client must specify which driver instance it wants
to be a client to and IO mode in which the driver should be opened. The USB Device Driver while operating in USB device mode
only supports non-blocking, read write and shared client access I/O intent mode. Trying to open the driver in any other mode will
cause the open routine to fail.
The driver treats the first client that opens it, differently from the other clients. This first client must open a bi-directional pipe on
endpoint zero. It must then register a Setup Packet Buffer with the driver. The driver uses this buffer to store the 8 byte Setup
command details received during the Setup stage of a Control transfer. While all clients can register a USB event callback
function, only the first client receives the USB_DEVICE_SETUP_TOKEN and the USB_DEVICE_SETUP_HANDSHAKE event in
its callback routine.
Typically (and it is recommended that) the first client to open the driver should be the USB Device Stack Device Layer Firmware.
The Device Layer firmware is responsible for enumerating the USB device and responding to host requests on the Endpoint 0
message pipe. The first client should register a USB event callback function (by using the
DRV_USB_Device_EventCallbackSet() function) and Setup Packet Buffer (by using the
DRV_USB_Device_SetupPacketBufferAssign() function) with the Driver. Both of these are essential for operation of the driver.
Registering a Setup Packet Buffer via the DRV_USB_Device_SetupPacketBufferAssign() also enables the USB device
(activates the USB module pull up resistors) for operation on the USB.
The following code snippet shows an example of how a USB Device Stack Device Layer should open the driver and perform
other functions.
/* In this example, the USB Device Layer (myUSBDevice) opens
* the USB Driver. It is assumed that the Driver is already
* initialized */
myUSBDevice.usbDriverHandle = DRV_USB_Open(DRV_USB_INDEX_0,
DRV_IO_INTENT_NONBLOCKING|DRV_IO_INTENT_READWRITE|DRV_IO_INTENT_SHARED );
if(DRV_HANDLE_INVALID == myUSBDevice.usbDriverHandle)
{
/* The open function failed. We can find out why */
if(USB_CLIENT_NOTAVAIL == DRV_USB_Device_DriverClientErrorGet(DRV_USB_INDEX_0))
{
/* This means that there is no space for another client.
* The driver configuration needs to be modified to support
* more clients. This can be done by increasing the value
* of DRV_USB_CLIENTS_NUMBER */
while(1);
}
}
/* Set the client event callback for the Device Layer.
* The USBDeviceLayerEventHandler() function is the event
* handler. When this event handler is invoked by the
* driver, the driver returns back the second argument
* specified in the below function (which in this case
* is the device layer data structure). This allows the
* application firmware to identify, as an example, the
* device layer object associated with this callback
*/
DRV_USB_Device_EventCallBackSet(myUSBDevice.usbDriverHandle, (void *)&myUSBDevice,
USBDeviceLayerEventHandler);
/* Device Layer register setup packet buffer. The Setup Packet Bufffer
* size is 8 bytes and is of the type uint8_t. Calling this function
5.1 Driver Library Help MPLAB Harmony Help USB Driver Library
5-556
* enables the device and the device is ready to receive a Setup token
* from the host. */
DRV_USB_Device_SetupPacketBufferAssign(myUSBDevice.usbDriverHandle, setupPacketBuffer);
/* Device Layer opens a endpoint 0 pipe. Refer to Setting
* up a Pipe section for more details on how to set up the
* pipe. This may be done in the reset event.*/
myUSBDevice.ep0Pipe = DRV_USB_Device_PipeSetup(myUSBDevice.usbDriverHandle, 0,
USB_EP_TX_RX,
64, 1, USB_CONTROL_PIPE);
A function driver may open the driver for use based on the configuration set by the host. Function drivers may or may not require
USB Event notification and so may not need to register a USB Event Callback function. The user application can also open the
driver. This allows the user application to track USB events and also communicate directly on the bus. The following code
snippet shows an example of how a function driver can open the USB Driver.
/* This code snippet shows an example of how the
* a function driver, say CDC, could open the USB Driver.
* Note that this should happen on a set configuration
* event from the host. */
cdc.usbDriverHandle = DRV_USB_Open(DRV_USB_INDEX_0,
DRV_IO_INTENT_NONBLOCKING|DRV_IO_INTENT_READWRITE );
if(DRV_HANDLE_INVALID == cdc.usbDriverHandle)
{
/* The open function failed. We can find out why */
if(USB_CLIENT_NOTAVAIL == DRV_USB_Device_DriverClientErrorGet(DRV_USB_INDEX_0))
{
/* This means that there is no space for another client.
* The driver configuration needs to be modified to support
* more clients.This can be done by increasing the value
* of DRV_USB_CLIENTS_NUMBER */ */
while(1);
}
}
/* Set the USB Event handler for CDC. Note that
* this optional and should be done only if the
* function driver requires USB Events notification. */
DRV_USB_Device_EventCallBackSet(cdc.usbDriverHandle, (void *)&cdc,
CDCDeviceUSBEventHandler);
/* CDC Function driver opens a TX and RX bulk pipe on
* endpoint 1. */
cdc.bulkRxPipe = DRV_USB_Device_PipeSetup(cdc.usbDriverHandle, 1,
USB_EP_RX, 64, 3, USB_BULK_PIPE);
cdc.bulkTxPipe = DRV_USB_Device_PipeSetup(cdc.usbDriverHandle, 1,
USB_EP_TX, 64, 3, USB_BULK_PIPE);
5.1.12.4.3.3 Endpoint Pipes
A client must open a pipe in order to schedule transfers on the USB. This is done by using the DRV_USB_Device_PipeSetup()
function. From a USB perspective, an endpoint 0 pipe is a message pipe (or a control pipe). The data flowing through this pipe
has a structure which defined by the USB specification. Pipes on non-zero endpoints are stream pipes and need not follow a
specific format. A Pipe connects a device's endpoint to a Host Driver software. Endpoint 0 pipe is always needed and must be
created for the USB device to enumerate and hence operate correctly. Non-zero endpoint pipes are created based on the
configuration set by the Host.
5.1 Driver Library Help MPLAB Harmony Help USB Driver Library
5-557
5.1.12.4.3.3.1 Pipe Setup
The DRV_USB_Device_PipeSetup() function creates a pipe. The following points should be noted while using this function to
create a pipe.
1. The pipeDirection argument specifies the pipe direction. An endpoint 0 pipe is always bi-directional. So this parameter is
ignored when the nEndpoint parameter is 0. All other pipes must be unidirectional. Specifying USB_EP_TX as the pipe direction
sets up the pipe to send data from device to host (host Read transfers). Specifying USB_EP_RX as the pipe direction sets up the
pipe to receive data from host (host Write transfers).
2. The nBytesMaxSize parameter specifies the maximum size of the data packet in a transaction on that pipe. It should not
exceed the maximum endpoint size communicated to the host during enumeration. Depending on the type of the USB transfer
that the pipe will handle and the speed of the USB, the maximum size of the data packet may vary. If the size of the read transfer
(device to host) scheduled on the pipe is greater than nBytesMaxSize, the driver will respond correctly multiple transactions that
are issued by the host to complete the transfer.
3. The nXferQueueSize parameter defines the size of the transfers that can be queued up this pipe. The minimum queue size
should be 1. The control pipe (endpoint 0 pipe) always has queue size of 1. Control transfers on the endpoint 0 pipe cannot be
queued. Refer to the Transfer Request section for more information on how transfers are scheduled. Other non-zero endpoint
pipes can have a queue size greater than or equal to 1.
4. An endpoint and direction of communication cannot be shared between two pipes. For example if a client opens a RX pipe on
endpoint 1, another RX pipe on endpoint 1 cannot be opened.
5. The pipeType parameter specified the type of transfers that this pipe will handle.
The client can check the return value of the DRV_USB_Device_PipeSetup() for the result. If the pipe was not setup successfully,
the function returns DRV_HANDLE_INVALID. The client can then use the DRV_USB_Device_ClientPipeErrorGet() function to
find out the reason for the failure.
The following code snippet shows how endpoint 0 pipe and non-zero endpoint pipes are created.
/* This is an example of how an endpoint 0 pipe is created.
* Note that this pipe is always bi-directional and the
* queue size is always 1. The maximum data packet size in this
* case is 64. The pipe type is set to handle control transfers */
myUSBDevice.ep0Pipe = DRV_USB_Device_PipeSetup(myUSBDevice.usbDriverHandle, 0,
USB_EP_TX_RX,
64, 1, USB_CONTROL_PIPE);
if(DRV_HANDLE_INVALID == myUSBDevice.ep0Pipe)
{
switch(DRV_USB_Device_ClientPipeErrorGet(myUSBDevice.usbDriverHandle))
{
case USB_PIPE_QUEUE_NOT_AVAILABLE:
/* This means that queue size is small. Increase
* the value of DRV_USB_XFERS_NUMBER. */
break;
case USB_PIPE_BAD_ENDPT:
/* The specified endpoint is greater than the
* the maximum end points that driver is configured
* to handle. */
break;
case USB_PIPE_TAKEN:
5.1 Driver Library Help MPLAB Harmony Help USB Driver Library
5-558
/* The specified endpoint and direction are already
* in use with another pipe. A non-zero endpoint
* can have only one pipe in a direction. Endpoint
* 0 can have one bi-directional pipe.*/
break;
case USB_PIPE_NOTAVAIL:
/* No pipes are available. Increase the number of pipes
* by increasing the value of DRV_USB_PIPES_NUMBER. */
break;
case USB_PIPE_BAD_DIRECTION:
/* Non zero endpoint cannot be bi-directional. */
break;
}
/* This is an example of how a client creates a non-zero endpoint pipe.
* In this case a TX and a RX pipe are opened on endpoint 1. The
* transfer schedule queue size is 4 and maximum data packet size
* is 64. Note that the maximum data packet size should match endpoint
* size specified in the endpoint configuration. */
cdc.bulkRxPipe = DRV_USB_Device_PipeSetup(cdc.usbDriverHandle, 1, USB_EP_RX, 64, 3,
USB_BULK_PIPE);
/* Optionally check for error here by using the
* DRV_USB_Device_ClientPipeErrorGet() function */
cdc.bulkTxPipe = DRV_USB_Device_PipeSetup(cdc.usbDriverHandle, 1, USB_EP_TX, 64, 3,
USB_BULK_PIPE);
/* Optionally check for error here by using the
* DRV_USB_Device_ClientPipeErrorGet() function */
/* The following usage of DRV_USB_Device_PipeSetup() is INCORRECT and
* will not work. The client must create separate TX and RX pipes for
* non-zero endpoints. This function will return DRV_HANDLE_INVALID
* and the DRV_USB_Device_ClientPipeErrorGet()function will return
* USB_PIPE_BAD_DIRECTION. */
someDevice.bulkPipe = DRV_USB_Device_PipeSetup(someDevice.usbDriverHandle, 1,
USB_EP_TX_RX, 64, 3, USB_BULK_PIPE); // Will not work!
5.1.12.4.3.3.2 Pipe Status
The client can use the DRV_USB_Device_PipeStatusGet() function to obtain the status of the pipe. The client can use this
information to find if a pipe is ready for transfers or if the pipe can be or is stalled. The following code snippet shows an example
of the DRV_USB_Device_PipeStatusGet() function along with all the possible return values.
/* This code example assumes the DRV_USB_DevicePipeSetup() function
* was used to open a pipe */
DRV_USB_PIPE_HANDLE pipeHandle;
DRV_USB_PIPE_STATUS pipeStatus;
if(DRV_HANDLE_INVALID != pipeHandle)
{
pipeStatus = DRV_USB_Device_PipeStatusGet(pipeHandle);
switch (pipeStatus)
{
case USB_PIPE_CLOSED:
5.1 Driver Library Help MPLAB Harmony Help USB Driver Library
5-559
/* The pipe was open and has been closed.
* This pipe should not be used for transferring
* data */
break;
case USB_PIPE_XFER_IN_PROGRESS:
/* There is a transfer in progress on the USB
* through this pipe.
*/
break;
case USB_PIPE_READY:
/* Pipe is ready for transferring data. Also
* indicates that there is no transfer in progress
* on the USB through this pipe
*/
break;
case USB_PIPE_STALLED:
/* Pipe is stalled. No transfers will take place.
*/
break;
}
}
5.1.12.4.3.3.3 Pipe Close
An open pipe can be closed by using the DRV_USB_Device_PipeRelease() function. Calling this function performs the following
function
1. It aborts all transfers that are in queue. If a transfer is in progress on the USB, it is cancelled.
2. It de-allocates its transfer queue and returns it to the driver.
3. It de-allocates the pipe and returns its to the driver.
The DRV_USB_Device_PipeRelease() may be called when the device stack detects detach from the host, or when a USB reset
event had been detected. Because this function aborts transfers that are in progress on the USB, it is possible that calling this
function while a transfer is in progress can cause the USB protocol to be violated. To avoid this, the client can use the
DRV_USB_Device_PipeStatusGet() function to get the status of the pipe before closing it. In case of a USB reset event, the
client can close the pipe without checking pipe status as the driver itself will cancel all transfer that are in progress.
The following code snippet shows example usage of the DRV_USB_Device_PipeRelease() function.
/* This code snippet assumes that this is not a reset
* event. In such a case, it is recommended that any
* transfers through the pipe be allowed to complete.
*/
while(DRV_USB_Device_PipeStatusGet(pipeHandle) == USB_PIPE_XFER_IN_PROGRESS);
/* Close the pipe */
DRV_USB_Device_PipeRelease(pipeHandle);
5.1.12.4.3.3.4 Pipe Transfer Queue
A pipe provides a queue for transfer requests. Clients can use the queue to reduce wait times and hence increase data
throughput through the pipe. If the pipe queue size is greater than one, the transfer requests on the pipe will be added to the
queue if a transfer is already in progress on the pipe. The size of queue is specified via the nXferQueueSize parameter in the
DRV_USB_Device_PipeSetup() function. The queue contains transfer objects that hold information about the requested
transfers. Multiple driver instance share one aggregate queue. The size of aggregate queue is defined by the
DRV_USB_XFERS_NUMBER macro in the driver configuration. Pipe specific queues are formed from this aggregate queue.
Figure 2 shows how this works.
Figure 2: Pipe Transfer Queues.
5.1 Driver Library Help MPLAB Harmony Help USB Driver Library
5-560
Figure 2a shows the aggregate driver queue. In this case, all the transfer objects in the queue are available for use. In figure 2b,
the client creates a pipe (pipe 0) with a queue size of 1. This results in the first transfer object on the queue forming a single
element queue for pipe 0. In figure 2c, the client creates a pipe (pipe 1) with a queue size of 3. This results in the next three
transfer objects on the queue forming a 3 element queue for pipe 1. In figure 2d, the client creates a pipe (pipe 2) with a queue
size of 4. This results in the next four transfer objects on the queue forming a 4 element queue for pipe 2. At this point, if a client
tries to create another pipe with queue size of say 4, the pipe will not be created as there isn't enough space available in the
queue.
The size of the aggregate queue should be decided in such a way as to meet the application's dynamic requirements while
taking the memory availability into consideration.
5.1.12.4.3.3.5 Pipe Stall
The client can stall a pipe in response to USB events. When a pipe is stalled, it returns a STALL PID on the USB. The USB
device firmware may stall endpoint 0 pipe when control requests from the host fail or are not supported. The driver automatically
clears an endpoint 0 pipe stall when the host sends a SETUP packet. A non-zero endpoint pipe may be stalled when the
endpoint's Halt feature is set. This is a functional stall. In this case the endpoint cannot send or receive data. Endpoint 0 pipe
may not need to support functional stalls (although they can but this is rarely done). A pipe is stalled using the
DRV_USB_Device_PipeStall() function and a pipe stall is cleared using the DRV_USB_Device_PipeStallClear() function.
There are 3 execution threads where the driver client can stall a pipe.
1. A pipe can be stalled in the client event handler.
The client can stall the pipe after receiving the USB_DEVICE_SETUP_TOKEN event. This is relevant to control transfer on
endpoint 0 pipe. The firmware can stall the pipe if it does not support the command received in the Setup packet. It is
recommended that both direction of the endpoint 0 pipe be stalled (this is possible because endpoint 0 pipe is always
bi-directional). Figure 3 shows the transaction related to this case.
Figure 3: Stalling Endpoint 0 pipe on a Control Read Transfer. Pipe is stalled after USB_DEVICE_SETUP_TOKEN event.
The stall on the receive direction of the pipe will get cleared when the host issues a Setup token. The stall on the TX direction of
the pipe needs to cleared by using the DRV_USB_Device_PipeStallClear() function. For endpoint 0 pipe, it is recommend that
the stall on both directions be cleared. Note that is also possible to stall non-zero pipes in the USB_DEVICE_SETUP_TOKEN
event. See code example below.
void USBEventHandler (void * referenceHandle,
5.1 Driver Library Help MPLAB Harmony Help USB Driver Library
5-561
DRV_USB_EVENT eventType, DRV_USB_EVENT_DATA * eventData )
{
switch ( eventType )
{
/* There could be other events here as well. Only
* the USB_DEVICE_SETUP_TOKEN is shown in this eaxample
* for the sake of clarity */
case USB_DEVICE_SETUP_TOKEN:
// Setup token received from host
if(ProcessSetupPacket(eventData->setupEventData.pSetupPktBuffer) == false)
{
/* This means the command received in the setup packet is
* not supported. The endpoint should be stalled. While
* stalling endpoint 0, both directions should be stalled.
* This ensures that both data stage and handshake stage
* of the control transfer get stalled. */
DRV_USB_Device_PipeStall(pipe0, USB_EP_TX_RX);
}
else
{
/* Setup packet command can be processed */
if(DRV_USB_Device_PipeStatusGet(pipe0) == USB_PIPE_STALLED)
{
/* Clear the pipe stall */
DRV_USB_Device_PipeStallClear(pipe0, USB_EP_TX_RX);
}
}
break;
}
}
2. A pipe can be stalled in the transfer complete event handler.
This is more relevant to Control Write transfers. In the case of Control Write transfers, the transfer complete event handler is
called after the data stage of the control transfer. If the firmware does not support the contents of the data stage, it can stall the
pipe. This will result in the handshake stage of the control write transfer getting stalled. Figure 4 shows the transactions related
to this case.
Figure 4: Stalling Endpoint 0 pipe on a Control Write Transfer. Pipe is stalled in the Transfer Complete Callback
Function.
The following code snippet shows an example of this:
void USBDeviceLayerXferCallback( void * referenceData,
DRV_USB_PIPE_HANDLE hPipe,
DRV_USB_XFER_HANDLE hTransfer,
unsigned short int transferByteCount ,
DRV_USB_DEVICE_XFER_STATUS statusTransfer )
{
/* Note that the transfer call contains the pipe
* handle. This pipe handle can be used to
* stall the pipe */
DRV_USB_Device_PipeStall(hPipe, USB_EP_TX_RX);
}
3. A pipe can be stalled asynchronous of driver events.
The client can stall a pipe based on device firmware logic. This is more applicable to non-zero endpoint pipes. Since these pipes
are uni-directional, the client must specify the stall direction (USB_EP_TX or USB_EP_RX) while calling the
DRV_USB_Device_PipeStall() function. Using the USB_EP_TX parameter will stall read transfers (IN tokens). Using the
5.1 Driver Library Help MPLAB Harmony Help USB Driver Library
5-562
USB_EP_RX parameter will stall write transfers (OUT tokens).
5.1.12.4.3.4 Event Handling
Any client that opens the driver can register to receive USB events. These USB events can be used by the clients to achieve the
desired functionality of the USB device. The first client to open the driver (typically the USB Stack device layer firmware) will
receive additional events. The client uses the DRV_USB_Device_EventCallBackSet() to set the client event call back function.
The following code snippet shows a client event handler function.
/* This is the client event handler */
void ClientEventHandler (void * referenceHandle,
DRV_USB_EVENT eventType,
DRV_USB_EVENT_DATA * eventData )
{
switch ( eventType )
{
case USB_ERROR:
// Bus error occurred and was reported in error interrupts
break;
case USB_DEVICE_RESET:
// Host has commanded a device reset
break;
case USB_DEVICE_RESUME:
// Resume detected while USB in suspend mode
break;
case USB_IDLE_DETECT:
// Idle detected
break;
case USB_STALL:
// Stall handshake has occurred
break;
case USB_DEVICE_SETUP_TOKEN:
// A Setup token was received
break;
case USB_DEVICE_SETUP_HANDSHAKE:
// Handshake stage of the control
// transfer is completed.
break;
// Device received a Start of Frame
case USB_DEVICE_GOT_SOF
break;
default:
break;
}
}
/* The client register the event handler
* after it has opened the driver. referenceData
* will be passed back to the event callback function
* whenever it is invoked. */
DRV_USB_Device_EventCallBackSet(clientHandle, referenceData, ClientEventHandler);
The eventData argument in the event callback function should be interpreted according to the event. The following table shows
all the possible events and the value of eventData for each event.
Event Type Event Details Interpretation of eventData
USB_ERROR This event occurs when the USB module
has detected an error on the bus
eventData.usbErrorData.errorType contains
a bitmap of errors (defined by
USB_ERROR_TYPE) that have occurred.
USB_DEVICE_RESET This event occurs when the USB module
has detected a USB Reset
NULL
5.1 Driver Library Help MPLAB Harmony Help USB Driver Library
5-563
USB_DEVICE_RESUME This event occurs when the USB module
has detected Resume Signalling
NULL
USB_IDLE_DETECT This event occurs when the USB module
has not detected any bus activity
NULL
USB_STALL This event occurs when a stalled
endpoint has received a token
eventData.stalledEnpoint.endpoint contains
the stalled endpoint that recevied a token.
USB_DEVICE_SETUP_TOKEN This event occurs when endpoint 0 has
received a SETUP token
eventData.setupEventData.pSetupPktBuffer
points to a 8 byte array that contains the
setup command that was received.
USB_DEVICE_SETUP_HANDSHAKE This event occurs when the handshake
stage of a Control Write Transfer has
completed.
NULL
USB_DEVICE_GOT_SOF This event occurs when the USB module
has received a start of frame.
NULL
The following code snippet shows the different USB errors that can occur
USB_ERROR_TYPE error = eventData.usbErrorData.errorType;
/* These are the possible errors that can occur.
* Refer to the device specific data sheet for
* more details on these errors. */
if (errorType & USB_ERR_INT_PID_CHECK_FAILURE)
{
/* Invalid or unsupported PID received */
}
if ( errorType & USB_ERR_INT_BAD_CRC5)
{
/* A CRC 5 error was encountered */
}
if ( errorType & USB_ERR_INT_BAD_CRC16)
{
/* A CRC 16 error was encountered */
}
if ( errorType & USB_ERR_INT_BAD_DATA_FIELD_SIZE)
{
/* Unsupported data field size was encountered */
}
if ( errorType & USB_ERR_INT_BUS_TURNAROUND_TIMEOUT)
{
/* A bus turn around timeout was encountered */
}
if ( errorType & USB_ERR_INT_DMA_ERROR)
{
/* A USB DMA error was encountered */
}
if ( errorType &= USB_ERR_INT_BUS_MATRIX_ERROR)
{
/* A Bus matrix error was encountered */
}
if ( errorType & USB_ERR_INT_BIT_STUFF_ERROR)
{
/* A bit stuffing error was encountered */
}
5.1 Driver Library Help MPLAB Harmony Help USB Driver Library
5-564
5.1.12.4.3.5 Transfer Requests
A USB Driver (operating in Device mode) client can receive and transmit data from the USB Host after creating a pipe. Data is
transferred by using the DRV_USB_Device_TransferRequest() function. Four types of USB transfers are supported: Control,
Bulk, Interrupt and Isochronous. The choice of transfer type depends on the nature of desired communication and the target
functionality of the USB device. Requesting a transfer will cause the USB driver to schedule the transfer. The actual data
communication takes place when the host has requested for the data. In cases where a transfer is already in progress and space
is available on the pipe transfer queue, the transfer request is added to the queue and processed in turn. Transfers that are not
in progress (pending in the queue) can be aborted by using the DRV_USB_Device_TransferAbort() function.
Depending on the size of the endpoint and the amount of data to be transferred, the host may complete the transfer through
multiple transactions. This process is handled by the driver and is transparent to the client. The client can register a transfer
complete event callback function for each transfer request. This function is called when the transfer is terminated, either because
its completed or aborted. Optionally the client can call the DRV_USB_Device_TransferStatusGet() function to poll the status of
the transfer. The transfer complete event callback function need not be registered in this case.
The DRV_USB_Device_TransferRequest() function also accepts flags that affect the processing of the transfer. The flag options
are transfer type specific.
The following section provides more details on how the four different transfer types can be requested:
5.1.12.4.3.5.1 Control Transfers
The USB Driver supports Control Read and Write Transfers on a endpoint 0 pipe only. A control transfer (either read or write)
occurs in stages:
1. The SETUP stage provides a setup command which among other things also defines if the transfer is a Control Read (data
moves from device to host) or a Control Write transfer (data moves from host to device).
2. The DATA stage transports data related to the setup command in the SETUP stage. Depending on the size of the endpoint,
the data stage could comprise of multiple IN or OUT transactions. A data stage may or may not be present in Control Write
transfers.
3. The HANDSHAKE stage completes the Control transfer.
Control Transfers should only be requested in response to a setup packet from the host. The USB Driver notifies its first client
(via the client event call back function) when a SETUP packet has been received. Only the first client receives this,
USB_DEVICE_SETUP_TOKEN, event. The driver generates USB_DEVICE_SETUP_HANDSHAKE client event at the
completion of the handshake stage of the control write transfer. Refer to Event Handling section on more details on handling
events.
The client parses the 8-byte setup command available from the USB_DEVICE_SETUP_TOKEN, event. It then has the following
options:
1. The client can request a control read transfer.
2. The client can request a control write transfer.
3. The client may not do anything and return from the event handler. In this case, the control transfer is treated as having no data
stage and the transfer moves to the handshake stage. Note that a Control Read transfer must always have a data stage.
4. The client can stall the pipe.
These cases are described here in detail.
1. Requesting a Control Read Transfer:
The code snippet below shows an example of how a Control Read Transfer can be requested. In this transfer, data moves from
the device to the host.
5.1 Driver Library Help MPLAB Harmony Help USB Driver Library
5-565
/* This is an example of a Control Read Transfer. A control read
* or Write transfer should be requested in response to a
* USB_DEVICE_SETUP_TOKEN event. The transfer request function is
* called in the USB event handler. In this example, the amount of
* data to be transferred is 18 bytes. The transfer is requested
* over endpoint 0 pipe. The USBDeviceLayerXferCallback() function
* will be called when the transfer is terminated. The myUSBDevice
* object will be passed back to the USBDeviceLayerXferCallback()
* function. The USB_XFER_REGULAR indicates to the driver that this
* transfer does not need a data stage ZLP */
DRV_USB_XFER_HANDLE xferHandle;
void USBEventHandler (void * referenceHandle,
DRV_USB_EVENT eventType, DRV_USB_EVENT_DATA * eventData )
{
switch ( eventType )
{
/* There could be other events here as well. Only
* the USB_DEVICE_SETUP_TOKEN is shown in this eaxample
* for the sake of clarity */
case USB_DEVICE_SETUP_TOKEN:
// Setup token received from host
ProcessSetupPacket(eventData->setupEventData.pSetupPktBuffer);
xferHandle = DRV_USB_Device_TransferRequest(myUSBDevice.ep0Pipe,
USB_XFER_CONTROL_READ, deviceDescriptor,18,
USB_XFER_REGULAR, myUSBDevice,
USBDeviceLayerXferCallback);
if(DRV_HANDLE_INVALID == xferHandle)
{
/* If the transfer request failed, the
* client can find out why. */
switch(DRV_USB_Device_PipeXferErrorGet(myUSBDevice.ep0Pipe))
{
case USB_XFER_WRONG_PIPE:
/* This means that either the transfer type or
* does not match the pipe type or direction */
break;
case USB_XFER_QUEUE_FULL:
/* This means that the transfer queue on this
* pipe is full. Either increase the queue size
* by increasing the value of DRV_USB_XFERS_NUMBER
* or wait for a slot on the queue to be available. */
break;
default:
break;
}
}
}
}
In a case where the data to be transferred is more than the endpoint size reported to the host (also specified at the time when
the control endpoint pipe is setup), the host will break up the data stage of the transfer into multiple transactions. This process is
transparent to the client. If at any point a SETUP packet is received while the transfer was in progress, the transfer is aborted
and client receives USB_DEVICE_SETUP_TOKEN event. If a transfer complete callback function was registered in the transfer
request function, this callback function is called with transfer status as USB_XFER_ABORT. Figure 5 shows the generation of
different events during the Control Read Transaction
5.1 Driver Library Help MPLAB Harmony Help USB Driver Library
5-566
Figure 5: Control Read Transfer. Data size is 18 bytes. Maximum Endpoint size is 64 bytes (> 18 bytes).
A Control read transfer must have a data stage. In cases of control read transfers where the amount of data to be transferred is
less than that requested by the host, the USB_XFER_SEND_ZLP flag must be specified. The driver will then check if the transfer
size is an exact multiple of the endpoint size and then send a data stage zero length packet (ZLP). This indicates to the host that
the device does not have any more data. There are two cases where specifying the USB_XFER_SEND_ZLP flag does not
cause the driver to send a ZLP.
- When the size of the transfer is less than requested size but is not an exact multiple of the maximum endpoint size.
- The size of the transfer is less than maximum endpoint size.
The following code snippet shows an example of a transfer request which sends a ZLP to the host.
/* This is an example of a Control Read Transfer with the ZLP
* option. Endpoint 0 maximum size is 8 bytes. The host has
* requested 32 bytes but the device has only 24 bytes to send.
* Specifying the USB_XFER_SEND_ZLP flag will cause the driver
* to send a ZLP to the host in the fourth data transaction.
*/
DRV_USB_XFER_HANDLE xferHandle;
xferHandle = DRV_USB_Device_TransferRequest(myUSBDevice.ep0Pipe, USB_XFER_CONTROL_READ,
deviceDescriptor,24,USB_XFER_SEND_ZLP,
myUSBDevice, USBDeviceLayerXferCallback);
Figure 6 shows the generation of different events and the additional ZLP sent in data stage in a multi transaction Control Read
Transfer.
Figure 6: Multi Transaction Control Read Transfer with ZLP. Data size is 24 bytes and maximum endpoint size is 8 bytes.
5.1 Driver Library Help MPLAB Harmony Help USB Driver Library
5-567
2. Requesting a Control Write Transfer:
The code snippet below shows an example of how a Control Write Transfer can be requested. In this transfer, data moves from
the host to device. The code example below shows an example of how a control write transfer is requested. Figure 7 shows the
generation of different events related to the control write transfer.
/* This is an example of a Control Write Transfer. A control read
* or Write transfer should be requested in response to a
* USB_DEVICE_SETUP_TOKEN event. The transfer request function is
* called in the USB event handler. In this example, the amount of
* data to be transferred is 32 bytes. The transfer is requested
* over endpoint 0 pipe. The USBDeviceLayerXferCallback() function
* will be called when the transfer is terminated. The myUSBDevice
* object will be passed back to the USBDeviceLayerXferCallback()
* function. The Control Write Transfer only supports the
* USB_XFER_REGULAR flag. */
DRV_USB_XFER_HANDLE xferHandle;
void USBDeviceLayerXferCallback( void * referenceData,
DRV_USB_PIPE_HANDLE hPipe,
DRV_USB_XFER_HANDLE hTransfer,
unsigned short int transferByteCount ,
DRV_USB_DEVICE_XFER_STATUS statusTransfer )
{
/* This function will be called when the transfer is complete.
* In this case, the referenceData argument will point to the
* myUSBDevice data object that was specified in the Transfer
* request function. */
}
void USBEventHandler (void * referenceHandle,
DRV_USB_EVENT eventType, DRV_USB_EVENT_DATA * eventData )
{
switch ( eventType )
{
/* There could be other events here as well. Only
* the USB_DEVICE_SETUP_TOKEN is shown in this eaxample
* for the sake of clarity */
case USB_DEVICE_SETUP_TOKEN:
// Setup token received from host
ProcessSetupPacket(eventData->setupEventData.pSetupPktBuffer);
xferHandle = DRV_USB_Device_TransferRequest(myUSBDevice.ep0Pipe,
USB_XFER_CONTROL_WRITE, buffer,32,
USB_XFER_REGULAR, myUSBDevice,
USBDeviceLayerXferCallback);
if(DRV_HANDLE_INVALID == xferHandle)
{
/* The DRV_USB_Device_PipeXferErrorGet() can be used to
* find the error cause */
}
}
}
In addition to the USB_DEVICE_SETUP_TOKEN event, the driver generates the USB_DEVICE_SETUP_HANDSHAKE event
when the Control Write Handshake stage is complete. This event is generated even when the Control Write transfer does not
have a data stage.
5.1 Driver Library Help MPLAB Harmony Help USB Driver Library
5-568
Figure 7: Example of Control Write Transfer. Data size is 18 bytes and maximum endpoint size is 64 bytes (> 18 bytes).
3. Control Write Transfers with Zero Data Stage.
A control write transfer can have zero data stages. One example of this is the SET ADDRESS command that the USB host send
to the device during enumeration. In cases where no data stages are needed, the client should not request any transfer and
return from the USB event handler. This will cause the driver to move the control transfer to the handshake stage. The
USB_DEVICE_SETUP_HANDSHAKE can be used to track when the handshake stage of the transfer completes. In case of the
SET ADDRESS command, the device layer firmware can change the device USB address in response to this event. The code
example below shows an example of how this is done.
/* This is an example of zero data stage Control Write transfer.
* This is done by not issuing a transfer request after the
* USB_DEVICE_SETUP_TOKEN event is received. */
DRV_USB_XFER_HANDLE xferHandle;
void USBEventHandler (void * referenceHandle,
DRV_USB_EVENT eventType, DRV_USB_EVENT_DATA * eventData )
{
switch ( eventType )
{
/* There could be other events here as well. Only
* the USB_DEVICE_SETUP_TOKEN is shown in this eaxample
* for the sake of clarity */
case USB_DEVICE_SETUP_TOKEN:
/* Setup token received from host. In this case we assume
* that this is the SET ADDRESS command. This command does
* not have a data stage. So the client does not do a
* transfer request*/
ProcessSetupPacket(eventData->setupEventData.pSetupPktBuffer);
break;
case USB_DEVICE_SETUP_HANDSHAKE:
/* The last control write transfer request is complete.
* In this example, the client can change the device USB address
* now. */
DRV_USB_Device_AddressSet(deviceLayer, address);
break;
default:
break;
}
}
Figure 8 shows the generation of different events related to the transfer.
5.1 Driver Library Help MPLAB Harmony Help USB Driver Library
5-569
Figure 8: Example of Zero data stage Control Write Transfer.
4.Stalling the Pipe:
Refer to Pipe Stall section for more details on how a pipe can be stalled.
5.1.12.4.3.5.2 Bulk and Interrupt Transfers
The driver can process Bulk and Interrupt transfers. On the USB, both Bulk and Interrupt transfers have the same packet
structure. The following discussion therefore applies to both Bulk and Interrupt transfers. A client should use the
DRV_USB_Device_TransferRequest() function to schedule Bulk and Interrupt transfers. The following sections describe
Bulk/Interrupt Read Transfers and Bulk/Interrupt Write Transfers.
1. Bulk/Interrupt Read Transfers:
In this transfer, data moves from device to host. The client can request a bulk/interrupt read transfer with a byte size greater than
the maximum endpoint size. In this case the driver will complete the transfer and invoke the transfer complete callback function if
provided. If the USB_XFER_SEND_ZLP flag is specified, the driver sends a ZLP after the last transaction if the transfer size was
an exact multiple of the endpoint size.
The following code snippet shows an example of a Bulk/Interrupt read transfer can be requested
/* This code snippet shows an example of how a Bulk/Interrupt
* read transfer can be requested */
DRV_USB_XFER_HANDLE transferHandle;
transferHandle = DRV_USB_Device_TransferRequest(pipe1, USB_XFER_BULK_READ,
data,120,USB_XFER_REGULAR, someReferenceData ,XferCompleteCallback);
/* This transfer directs the driver to send a ZLP
* after the last transaction */
transferHandle = DRV_USB_Device_TransferRequest(pipe1, USB_XFER_BULK_READ,
data,128,USB_XFER_SEND_ZLP, someReferenceData ,XferCompleteCallback);
Figure 9 shows a regular bulk/interrupt read transfer. Figure 10 shows a bulk/interrupt read transfer with a ZLP.
Figure 9: Example of Bulk/Interrupt Read Transfer. Requested transfer size is 120 bytes. Maximum endpoint size 64
Figure 10: Example of Bulk/Interrupt Read Transfer with ZLP. Requested transfer size is 128 bytes. Maximum endpoint
5.1 Driver Library Help MPLAB Harmony Help USB Driver Library
5-570
size 64
2. Bulk/Interrupt Write Transfers:
In this transfer, data moves from host to device. These transfers only support USB_XFER_REGULAR flag. The client can
request a bulk/interrupt write transfer with a byte size greater than the maximum endpoint size. . In this case however, the driver
will invoke the transfer complete callback function when a transaction completes. The callback thus gets invoked whenever the
host sends any amount of data. Since the amount of data that the host sends in one transaction will not exceed the maximum
endpoint size, specifying a transfer size greater than maximum endpoint size will not have any effect. The client must schedule
another transfer to receive more data from the host. The following code snippet shows an example of bulk/interrupt write transfer.
/* This code snippet shows an example of how a Bulk/Interrupt
* write transfer can be requested. Note the data size is
* equal the size of the endpoint. The client has queued up
* multiple transfers.*/
DRV_USB_XFER_HANDLE transferHandle1;
DRV_USB_XFER_HANDLE transferHandle1;
transferHandle1 = DRV_USB_Device_TransferRequest(pipe2, USB_XFER_BULK_WRITE,
data,64,USB_XFER_REGULAR, someReferenceData ,XferCompleteCallback);
transferHandle1 = DRV_USB_Device_TransferRequest(pipe2, USB_XFER_BULK_WRITE,
data,64,USB_XFER_REGULAR, someReferenceData ,XferCompleteCallback);
Figure 11 shows a bulk/interrupt write transfer with related events
Figure 11: Example of Bulk/Interrupt Write Transfer. Client has scheduled two tranfers Maximum endpoint size 64
5.1.12.4.3.5.3 Isochronous Transfers
A client can request Isochronous transfers by using the DRV_USB_Device_TransferRequest() function. On the USB,
Isochronous transfers are characterized by the absence of the handshake stage. The driver supports USB_XFER_REGULAR
and USB_XFER_PERSIST flags for Isochronous transfers. While using the USB_XFER_REGULAR flag, the transfer request
behavior is similar to Bulk and Interrupt Read/Write Transfer Requests. In that, a new transfer will require the client to call the
DRV_USB_Device_TransferRequest() function.
By using the USB_XFER_PERSIST flag, the driver will not discard the transfer after the transfer is complete. Instead, after the
transfer is complete, the transfer is rescheduled in the queue. This way the client does not have to schedule another transfer. If
the client has scheduled two Isochronous transfers with the USB_XFER_PERSIST flag, the driver will ping pong between these
transfers. The transfer complete callback function is called when the transfer is completed.
The code snippet below shows an example of setting up two Isochronous read transfers to create a ping pong type of transfer
system.
DRV_USB_XFER_HANDLE pingTransferHandle;
DRV_USB_XFER_HANDLE pongTransferHandle;
/* Request two transfers. Note how the USB_XFER_PERSIST flag
* is specified. Note also how the pingData and pongData buffer
* pointers are specified as reference data. This will make
* processing in the transfer complete call back easier.. */
pingTransferHandle = DRV_USB_Device_TransferRequest(pipe0, USB_XFER_CONTROL_READ,
pingData,64,USB_XFER_PERSIST, pingData ,PingXferCompleteCallback);
pongTransferHandle = DRV_USB_Device_TransferRequest(pipe0, USB_XFER_CONTROL_READ,
pongData,40,USB_XFER_PERSIST, pongData ,PongXferCompleteCallback);
/* This is the Ping transfer Complete callback */
void PingCompleteCallback( void * referenceData,
DRV_USB_PIPE_HANDLE hPipe,
DRV_USB_XFER_HANDLE hTransfer,
5.1 Driver Library Help MPLAB Harmony Help USB Driver Library
5-571
unsigned short int transferByteCount ,
DRV_USB_DEVICE_XFER_STATUS statusTransfer )
{
/* Note that we dont schedule one more request here.
* We just add data to the buffer and return. This
* same transfer will be processed again. The referenceData
* points to the ping data buffer (as set in the transfer request
* function. */
void * data = referenceData;
UpdateBuffer(data);
}
/* This is the Ping transfer Complete callback */
void PongCompleteCallback( void * referenceData,
DRV_USB_PIPE_HANDLE hPipe,
DRV_USB_XFER_HANDLE hTransfer,
unsigned short int transferByteCount ,
DRV_USB_DEVICE_XFER_STATUS statusTransfer )
{
/* Note that we dont schedule one more request here.
* We just add data to the buffer and return. This
* same transfer will be processed again. The referenceData
* points to the pong data buffer (as set in the transfer request
* function. */
void * data = referenceData;
UpdateBuffer(data);
}
5.1.12.4.3.5.4 Transfer Status
The driver offers to different interface to track the status of a transfer, a polling interface and a callback interface. Both these
interfaces can be invoked by the application. The two interfaces are discussed here:
1. Polling interface:
The client can access the polling interface by using the DRV_USB_Device_XferStatusGet() function. This interface does not
provide information when a transfer is aborted. The following code snippet shows how DRV_USB_Device_XferStatusGet() is
used.
/* This code snippet shows the different
* values that the DRV_USB_Device_XferStatusGet()
* function. This function implements the polling
* interface for the transfer status.
*/
DRV_USB_DEVICE_XFER_STATUS transferStatus;
transferStatus = DRV_USB_Device_XferStatusGet(transferHandle);
switch(transferStatus)
{
case USB_XFER_PENDING:
/* This means the transfer is still in the transfer
* queue. This transfer can be aborted.*/
case USB_XFER_IN_PROGRESS:
/* This means the transfers is currently in progress
* on the bus. This transfer cannot be aborted. */
case USB_XFER_COMPLETED:
/* This measn the transfer is complete */
default:
break;
}
5.1 Driver Library Help MPLAB Harmony Help USB Driver Library
5-572
2. Callback interface:
The callback interface to track the status of the transfer is implemented by using Transfer Complete Callback function. The client
should specify the Transfer Complete Callback function when calling DRV_USB_Device_TransferRequest() function. The driver
call this function when a transfer has terminated, either due to the transfer completing or the transfer aborting. The Transfer
Complete Callback function should be of the type DRV_USB_XFER_COMPLETE_CALLBACK. The driver returns the following
information while calling the Transfer Complete Callback function.
1. Handle to the pipe that contained this transfer
2. Handle to the transfer
3. Number of bytes read or written
4. A reference to a data object that was specified in the DRV_USB_Device_TransferRequest() for this transfer.
5. Transfer termination status
The following code snippet shows an example of how a Transfer Complete Callback function can be used.
/* This code snippet shows an example of how to use the
* transfer complete callback */
DRV_USB_XFER_HANDLE transferHandle;
/* Request a transfer. Note that the reference data pointer is set
* to dataBuffer and the transfer complete callback function
* XferCompleteCallback is specified. */
transferHandle = DRV_USB_Device_TransferRequest(pipe0, USB_XFER_CONTROL_READ,
dataBuffer,18,false, dataBuffer ,XferCompleteCallback);
/* This is the transfer Complete callback */
void XferCompleteCallback( void * referenceData,
DRV_USB_PIPE_HANDLE hPipe,
DRV_USB_XFER_HANDLE hTransfer,
unsigned short int transferByteCount ,
DRV_USB_DEVICE_XFER_STATUS statusTransfer )
{
/* The referenceData variable (the value of which
* is specified in the transfer request function)
* points to the data buffer associate with the
* transfer. */
void * dataBuffer = referenceData;
if(transferStatus == USB_XFER_COMPLETED)
{
ProcessDataBuffer(dataBuffer, transferByteCount);
}
else if(transferStatus == USB_XFER_ABORTED)
{
/* This transfer was not successful. Take any
* remedial action as needed. */
}
}
5.1.12.4.3.5.5 Transfer Abort
A client can abort a USB transfer that it requested. This is achieved by using the DRV_USB_Device_TransferAbort() function. A
Control read or write transfer can automatically get aborted when the host issues a SETUP token out of turn. The
DRV_USB_Device_TransferAbort() will not abort a transfer if it is already in progress. Closing the pipe will however abort
transfers that are in progress.
5.1 Driver Library Help MPLAB Harmony Help USB Driver Library
5-573
When a transfer is aborted, the Transfer Complete Callback function associated with the transfer is not invoked. If the Control
Read or Write transfer was aborted due to a out of turn SETUP token from the host, Transfer Complete Callback function will be
called and transfer status will be USB_XFER_ABORTED.
5.1.12.5 Configuring the Library
The configuration of the USB Driver is based on the file sys_config.h
This header file contains the configuration selection for the USB Driver. Based on the selections made, the USB Driver will
support or not support selected features. Some configuration settings will apply to all instances of the USB Driver while some
configurations settings are applicable only if the driver is built for a static mode.
This header can be placed anywhere, the path of this header needs to be present in the include search path for a successful
build. Refer to the Applications Overview section for more details.
5.1.12.5.1 Initialization Overrides
This section lists out the macros that need to be configured when building the static version of the driver. These values should be
defined for correction operation of the driver, when the driver is built statically. Commenting the
DRV_USB_INSTANCES_NUMBER macro will cause the driver to be built in a static mode.
5.1.12.5.2 Others
These macros affect all instances and all build types of the driver.
5.1.12.6 Building the Library
The following table lists the USB Driver files to be included in the project for the available features
Features File Path Comments
Needed for all
features
driver/usb/drv_usb.h Must be included in every source code file that access
the driver API.
Dynamic Build driver/usb/src/dynamic/drv_usb.c Must be included when using the dynamic version of
the driver
Static Multi-Client
Build
driver/usb/src/static_multi/drv_usb_static_multi.c Must be included when using the static multi client
version of the driver
5.1.12.7 Library Interface
Data Types and Constants
Name Description
DRV_USB_ENDPOINT_TABLE_ENTRY_SIZE
DRV_USB_HOST_PIPE_HANDLE_INVALID Defines the USB Driver Host Pipe Invalid handle
DRV_USB_INDEX This is macro DRV_USB_INDEX.
DRV_USB_INDEX_0 USB driver index definitions
DRV_USB_INTERRUPT_SOURCE This is macro DRV_USB_INTERRUPT_SOURCE.
5.1 Driver Library Help MPLAB Harmony Help USB Driver Library
5-574
DRV_USB_PERIPHERAL_ID This is macro DRV_USB_PERIPHERAL_ID.
DRV_USB_EVENT Identifies the different events that the USB Driver provides.
DRV_USB_EVENT_CALLBACK Type of the USB event callback function
DRV_USB_HOST_PIPE_HANDLE Defines the USB Driver Host Pipe handle type
DRV_USB_INIT Contains all the data necessary to initialize the USB device
Client Functions
Name Description
DRV_USB_Close Closes an opened-instance of the USB driver
DRV_USB_Open Opens the specified USB driver instance and returns a handle to it
Other Functions
Name Description
DRV_USB_ClientEventCallBackSet This function sets up the event callback function that is invoked by the
USB controller driver to notify the a client of USB bus events.
DRV_USB_DEVICE_AddressSet This function will set the USB module address that is obtained from
the host.
DRV_USB_DEVICE_Attach This function will attach the device to the USB.
DRV_USB_DEVICE_CurrentSpeedGet This function will return the USB speed at which device is operating.
DRV_USB_DEVICE_Detach This function will detach the device from the USB.
DRV_USB_DEVICE_EndpointDisable This function disables an endpoint.
DRV_USB_DEVICE_EndpointDisableAll This function disables all provisioned non-zero endpoints.
DRV_USB_DEVICE_EndpointEnable This function enables a endpoint for the specified direction and
endpoint size.
DRV_USB_DEVICE_EndpointIsEnabled This function returns the enable/ disable status of the specified
endpoint and direction.
DRV_USB_DEVICE_EndpointIsStalled This function returns the stall status of the specified endpoint and
direction.
DRV_USB_DEVICE_EndpointStall This function stalls an endpoint in the specified direction.
DRV_USB_DEVICE_EndpointStallClear This function clears the stall on an endpoint in the specified direction.
DRV_USB_DEVICE_IRPCancelAll This function cancels all IRPs that are queued and in progress at the
specified endpoint.
DRV_USB_DEVICE_IRPSubmit This function submits a I/O Request Packet (IRP) for processing to
the USB Driver.
DRV_USB_HOST_BusResetControl This is function DRV_USB_HOST_BusResetControl.
DRV_USB_HOST_DeviceCurrentSpeedGet This is function DRV_USB_HOST_DeviceCurrentSpeedGet.
DRV_USB_HOST_IRPCancel This is function DRV_USB_HOST_IRPCancel.
DRV_USB_HOST_IRPSubmit This is function DRV_USB_HOST_IRPSubmit.
DRV_USB_HOST_OperationEnable This is function DRV_USB_HOST_OperationEnable.
DRV_USB_HOST_StartOfFrameControl This is function DRV_USB_HOST_StartOfFrameControl.
DRV_USB_HOST_TimerIsComplete This is function DRV_USB_HOST_TimerIsComplete.
DRV_USB_HOST_TimerReset This is function DRV_USB_HOST_TimerReset.
DRV_USB_HOST_TimerStart This is function DRV_USB_HOST_TimerStart.
DRV_USB_Tasks Maintains the driver's state machine when the driver is configured for
polled mode.
5.1 Driver Library Help MPLAB Harmony Help USB Driver Library
5-575
Pipe Functions
Name Description
DRV_USB_HOST_PipeSetup This is function DRV_USB_HOST_PipeSetup.
DRV_USB_HOST_PipeClose This is function DRV_USB_HOST_PipeClose.
System Functions
Name Description
DRV_USB_Initialize Initializes the USB driver
DRV_USB_Status Provides the current status of the USB driver module
DRV_USB_Tasks_ISR Maintains the driver's state machine and implements its ISR
DRV_USB_HOST_OperationIsEnabled This is function DRV_USB_HOST_OperationIsEnabled.
Description
This section describes the APIs of the USB Driver. Refer to each section for a detailed description.
5.1.12.7.1 System Functions
5.1.12.7.1.1 DRV_USB_Initialize Function
C
SYS_MODULE_OBJ DRV_USB_Initialize(
const SYS_MODULE_INDEX drvIndex,
const SYS_MODULE_INIT * const init
);
Description
This routine initializes the USB driver, making it ready for clients to open and use it.
Preconditions
None.
Parameters
Parameters Description
drvIndex Ordinal number of driver instance to be initialized
init Pointer to a data structure containing any data necessary to initialize the driver.
This should be a DRV_USB_INIT structure reference type casted to
SYS_MODULE_INIT reference.
Returns
If successful, returns a valid handle to a driver object. Otherwise, it returns SYS_MODULE_OBJ_INVALID. The returned object
must be passed as argument to DRV_USB_Status routines.
Remarks
This routine must be called before any other USB routine is called. This routine should only be called once during system
initialization unless DRV_USB_Deinitialize is called to de-initialize the driver instance. If the driver is built for static mode, then
the initialization data structure is ignored. The static overrides provided in system_config.h are considered instead.
Example
// The following code snippet shows an example initialization of the
// driver. The USB module to be used is USB1. The module should not
// automatically suspend when the microcontroller enters Sleep mode.
5.1 Driver Library Help MPLAB Harmony Help USB Driver Library
5-576
// The module should continue operation when the module enters Idle
// mode. The power state is set to run at full clock speeds. Device
// Mode operation should be at FULL speed.
DRV_USB_INIT moduleInit;
usbInitData.usbID = USB_ID_1;
usbInitData.opMode = DRV_USB_OPERATION_MODE_DEVICE;
usbInitData.pingpongMode = USB_PING_PONG_FULL_PING_PONG;
usbInitData.stopInIdle = false;
usbInitData.suspendInSleep = false;
usbInitData.operationSpeed = USB_SPEED_FULL;
usbInitData.interruptSource = INT_SOURCE_USB;
usbInitData.sysModuleInit.powerState = SYS_MODULE_POWER_RUN_FULL ;
// This is how this data structure is passed to the initialize
// function.
DRV_USB_Initialize(DRV_USB_INDEX_0, (SYS_MODULE_INIT *) &usbInitData);
5.1.12.7.1.2 DRV_USB_Status Function
C
SYS_STATUS DRV_USB_Status(
SYS_MODULE_OBJ object
);
Description
This routine provides the current status of the USB driver module.
Preconditions
Function DRV_USB_Initialize must have been called before calling this
Parameters
Parameters Description
object Driver object handle, returned from the DRV_USB_Initialize routine
Returns
• SYS_STATUS_READY - Indicates that the driver is ready
• SYS_STATUS_UNINITIALIZED - Indicates that the driver has never been initialized
Remarks
None.
Example
SYS_MODULE_OBJ object; // Returned from DRV_USB_Initialize
SYS_STATUS status;
DRV_USB_INIT moduleInit;
usbInitData.usbID = USB_ID_1;
usbInitData.opMode = DRV_USB_OPERATION_MODE_DEVICE;
usbInitData.stopInIdle = false;
usbInitData.suspendInSleep = false;
usbInitData.operationSpeed = USB_SPEED_FULL;
usbInitData.interruptSource = INT_SOURCE_USB;
usbInitData.sysModuleInit.powerState = SYS_MODULE_POWER_RUN_FULL ;
// This is how this data structure is passed to the initialize
5.1 Driver Library Help MPLAB Harmony Help USB Driver Library
5-577
// function.
object = DRV_USB_Initialize(DRV_USB_INDEX_0,
(SYS_MODULE_INIT *) &usbInitData);
status = DRV_USB_Status(object);
if(SYS_STATUS_READY == status)
{
// Driver is ready to be opened.
}
5.1.12.7.1.3 DRV_USB_Tasks_ISR Function
C
void DRV_USB_Tasks_ISR(
SYS_MODULE_OBJ object
);
Description
This routine is used to maintain the driver's internal state machine and implement its ISR for interrupt-driven implementations.
Preconditions
The DRV_USB_Initialize routine must have been called for the specified USB driver instance.
Parameters
Parameters Description
object Object handle for the specified driver instance (returned from DRV_USB_Initialize)
Returns
None
Remarks
This routine should be called from the USB interrupt service routine. In case of multiple USB modules, it should be ensured that
the correct USB driver system module object is passed to the this routine.
Example
SYS_MODULE_OBJ object; // Returned from DRV_USB_Initialize
while (true)
{
DRV_USB_Tasks_ISR (object);
// Do other tasks
}
5.1.12.7.1.4 DRV_USB_HOST_OperationIsEnabled Function
C
bool DRV_USB_HOST_OperationIsEnabled(
DRV_HANDLE hClient
);
Description
This is function DRV_USB_HOST_OperationIsEnabled.
5.1.12.7.2 Client Functions
5.1 Driver Library Help MPLAB Harmony Help USB Driver Library
5-578
5.1.12.7.2.1 DRV_USB_Close Function
C
void DRV_USB_Close(
DRV_HANDLE handle
);
Description
This routine closes an opened-instance of the USB driver, invalidating the handle.
Preconditions
The DRV_USB_Initialize routine must have been called for the specified USB driver instance. DRV_USB_Open must have been
called to obtain a valid opened device handle.
Parameters
Parameters Description
handle Client's driver handle (returned from DRV_USB_Open)
Returns
None
Remarks
After calling this routine, the handle passed in "handle" must not be used with any of the remaining driver routines. A new handle
must be obtained by calling DRV_USB_Open before the caller may use the driver again.
Example
DRV_HANDLE handle; // Returned from DRV_USB_Open
DRV_USB_Close(handle);
5.1.12.7.2.2 DRV_USB_Open Function
C
DRV_HANDLE DRV_USB_Open(
const SYS_MODULE_INDEX drvIndex,
const DRV_IO_INTENT intent
);
Description
This routine opens the specified USB driver instance and provides a handle that must be provided to all other client-level
operations to identify the caller and the instance of the driver. The intent flag should always be
DRV_IO_INTENT_EXCLUSIVE|DRV_IO_INTENT_READWRITE|DRV_IO_INTENT_NON_BLOCKING. Anyother setting of the
intent flag will return a invalid driver handle. A driver instance can only support one client. Trying to open a driver that has an
existing client will result in an unsuccessful function call.
Preconditions
Function DRV_USB_Initialize must have been called before calling this function.
Parameters
Parameters Description
drvIndex Driver instance that client will use
intent Should always be
DRV_IO_INTENT_EXCLUSIVE|DRV_IO_INTENT_READWRITE|
DRV_IO_INTENT_NON_BLOCKING.
5.1 Driver Library Help MPLAB Harmony Help USB Driver Library
5-579
Returns
If successful, valid driver handle for the client to use when interfacing with the driver. If an error occurs, the return value is
DRV_HANDLE_INVALID.
Remarks
The handle returned is valid until the DRV_USB_Close routine is called.
Example
// Shows an example of how to open the driver.
SYS_MODULE_OBJ object; // Returned from DRV_USB_Initialize
SYS_STATUS status;
DRV_USB_INIT moduleInit;
DRV_HANDLE handle;
usbInitData.usbID = USB_ID_1;
usbInitData.opMode = DRV_USB_OPERATION_MODE_DEVICE;
usbInitData.stopInIdle = false;
usbInitData.operationSpeed = USB_SPEED_FULL;
usbInitData.suspendInSleep = false;
usbInitData.interruptSource = INT_SOURCE_USB;
usbInitData.sysModuleInit.powerState = SYS_MODULE_POWER_RUN_FULL ;
// This is how this data structure is passed to the initialize
// function.
object = DRV_USB_Initialize(DRV_USB_INDEX_0,
(SYS_MODULE_INIT *) &usbInitData);
status = DRV_USB_Status(object);
if(SYS_STATUS_READY == status)
{
// Driver is ready to be opened.
handle = DRV_USB_Open(DRV_USB_INDEX_0,
DRV_IO_INTENT_EXCLUSIVE|
DRV_IO_INTENT_READWRITE|
DRV_IO_INTENT_NON_BLOCKING);
SYS_ASSERT(DRV_HANDLE_INVALID != handle,"Bad handle returned");
}
5.1.12.7.3 Pipe Functions
5.1.12.7.3.1 DRV_USB_HOST_PipeSetup Function
C
DRV_USB_HOST_PIPE_HANDLE DRV_USB_HOST_PipeSetup(
DRV_HANDLE client,
uint8_t deviceAddress,
USB_ENDPOINT endpointAndDirection,
uint8_t hubAddress,
uint8_t hubPort,
USB_TRANSFER_TYPE pipeType,
uint8_t bInterval,
uint16_t wMaxPacketSize,
USB_SPEED speed
);
Description
This is function DRV_USB_HOST_PipeSetup.
5.1 Driver Library Help MPLAB Harmony Help USB Driver Library
5-580
5.1.12.7.3.2 DRV_USB_HOST_PipeClose Function
C
void DRV_USB_HOST_PipeClose(
DRV_USB_HOST_PIPE_HANDLE pipeHandle
);
Description
This is function DRV_USB_HOST_PipeClose.
5.1.12.7.4 Transfer Functions
5.1.12.7.5 Other Functions
5.1.12.7.5.1 DRV_USB_ClientEventCallBackSet Function
C
void DRV_USB_ClientEventCallBackSet(
DRV_HANDLE handle,
uintptr_t hReferenceData,
DRV_USB_EVENT_CALLBACK myEventCallBack
);
Description
This function sets up the event callback function that is envoked by the USB controller driver to notify the client of USB bus
events. The call back is disabled by not calling this function after a USB_DRV_Open or by passing NULL for the
myEventCallBack argument. When the callback function is called, the hReferenceData argument is returned.
Preconditions
None.
Parameters
Parameters Description
handle Client's driver handle (returned from DRV_USB_Open)
hReferenceData object (could be a pointer) that is returned with the callback.
myEventCallBack Call back function for all USB events.
Returns
None.
Remarks
Typical usage of the USB Driver requires a client to register a callback.
Example
// Set the client event callback for the Device Layer.
// The USBDeviceLayerEventHandler() function is the event
// handler. When this event handler is invoked by the
// driver, the driver returns back the second argument
// specified in the below function (which in this case
// is the device layer data structure). This allows the
// application firmware to identify, as an example, the
// device layer object associated with this callback
//
5.1 Driver Library Help MPLAB Harmony Help USB Driver Library
5-581
DRV_USB_ClientEventCallBackSet(myUSBDevice.usbDriverHandle,
(uintptr_t)&myUSBDevice,
USBDeviceLayerEventHandler);
5.1.12.7.5.2 DRV_USB_DEVICE_AddressSet Function
C
void DRV_USB_DEVICE_AddressSet(
DRV_HANDLE handle,
uint8_t address
);
Description
This function will set the USB module address that is obtained from the host in a setup transaction. The address is obtained from
the SET_ADDRESS command issued by the host. The primary (first) client of the driver uses this function to set the module's
USB address after decoding the setup transaction from the host.
Preconditions
None.
Parameters
Parameters Description
handle Client's driver handle (returned from DRV_USB_Open)
address The address of this module on the USB bus
Returns
None.
Remarks
None.
Example
// This function should be called by the first client of the driver,
// which is typically the device layer. The address to set is obtained
// from the host during enumeration.
DRV_USB_DEVICE_AddressSet(deviceLayer, 4);
5.1.12.7.5.3 DRV_USB_DEVICE_Attach Function
C
void DRV_USB_DEVICE_Attach(
DRV_HANDLE handle
);
Description
This function will attach the device to the USB. It does this by enabling the pull up resistors on the D+ or D- lines. This function
should be called when the driver client is ready to receive communication from the host (typically after all initialization is
complete).
Preconditions
Client handle should be valid.
5.1 Driver Library Help MPLAB Harmony Help USB Driver Library
5-582
Parameters
Parameters Description
handle Client's driver handle (returned from DRV_USB_Open)
Returns
None.
Remarks
None.
Example
// Open the device driver and attach the device to the USB.
SYS_MODULE_OBJ object; // Returned from DRV_USB_Initialize
SYS_STATUS status;
DRV_USB_INIT moduleInit;
DRV_HANDLE handle;
usbInitData.usbID = USB_ID_1;
usbInitData.opMode = DRV_USB_OPERATION_MODE_DEVICE;
usbInitData.stopInIdle = false;
usbInitData.suspendInSleep = false;
usbInitData.operationSpeed = USB_SPEED_FULL;
usbInitData.interruptSource = INT_SOURCE_USB;
usbInitData.sysModuleInit.powerState = SYS_MODULE_POWER_RUN_FULL ;
// This is how this data structure is passed to the initialize
// function.
object = DRV_USB_Initialize(DRV_USB_INDEX_0,
(SYS_MODULE_INIT *) &usbInitData);
status = DRV_USB_Status(object);
if(SYS_STATUS_READY == status)
{
// Driver is ready to be opened.
handle = DRV_USB_Open(DRV_USB_INDEX_0,
DRV_IO_INTENT_EXCLUSIVE|
DRV_IO_INTENT_READWRITE|
DRV_IO_INTENT_NON_BLOCKING);
SYS_ASSERT(DRV_HANDLE_INVALID != handle,"Bad handle returned");
// Register a callback
DRV_USB_ClientEventCallBackSet(handle, (uintptr_t)&myDeviceLayer,
MyDeviceLayerEventCallback);
// Perform any other initialization here and then attach the device
// to the bus.
DRV_USB_DEVICE_Attach(handle);
}
5.1.12.7.5.4 DRV_USB_DEVICE_CurrentSpeedGet Function
C
USB_SPEED DRV_USB_DEVICE_CurrentSpeedGet(
DRV_HANDLE handle
);
Description
This function will return the USB speed at which device is operating.
5.1 Driver Library Help MPLAB Harmony Help USB Driver Library
5-583
Preconditions
Only valid after device is attached to host.
Parameters
Parameters Description
handle Client's driver handle (returned from DRV_USB_Open)
Returns
Returns a member of the USB_SPEED type.
Remarks
None.
Example
// Get the current speed.
USB_SPEED deviceSpeed;
deviceSpeed = DRV_USB_DEVICE_CurrentSpeedGet(deviceLayer);
if(deviceLayer == USB_SPEED_HIGH)
{
// Possibly adjust buffers for higher throughput.
}
5.1.12.7.5.5 DRV_USB_DEVICE_Detach Function
C
void DRV_USB_DEVICE_Detach(
DRV_HANDLE handle
);
Description
This function will detach the device from the USB. It does this by disabling the pull up resistors on the D+ or D- lines. This
function should be called when the application wants to disconnect the device from the bus (typically to implement a soft detach
or switch to host mode operation).
Preconditions
Client handle should be valid.
Parameters
Parameters Description
handle Client's driver handle (returned from DRV_USB_Open)
Returns
None.
Remarks
None.
Example
// Detach the device from the USB
DRV_USB_DEVICE_Detach(handle);
5.1 Driver Library Help MPLAB Harmony Help USB Driver Library
5-584
5.1.12.7.5.6 DRV_USB_DEVICE_EndpointDisable Function
C
USB_ERROR DRV_USB_DEVICE_EndpointDisable(
DRV_HANDLE handle,
USB_ENDPOINT endpointAndDirection
);
Description
This function disables an endpoint. If the endpoint type is control type then both directions are disabled. For non-control
endpoints, the function disables one direction at a time.
Preconditions
Client handle should be valid.
Parameters
Parameters Description
handle Client's driver handle (returned from DRV_USB_Open)
endpointAndDirection Specifies the endpoint and direction.
Returns
USB_ERROR_NONE - The endpoint was successfully enabled. USB_ERROR_DEVICE_ENDPOINT_INVALID - If the endpoint
that is being accessed is is out of the valid endpoint defined for this driver instance.
Remarks
None.
Example
// This code snippet shows an example of how to disable
// a control endpoint. Note that the direction parameter is ignored.
// For a control endpoinnt, both the directions are disabled.
USB_ENDPOINT ep;
ep = USB_ENDPOINT_AND_DIRECTION(USB_DATA_DIRECTION_DEVICE_TO_HOST, 0);
DRV_USB_DEVICE_EndpointDisable(handle, ep );
// This code snippet shows an example of how to disable a BULK IN
// endpoint
USB_ENDPOINT ep;
ep = USB_ENDPOINT_AND_DIRECTION(USB_DATA_DIRECTION_DEVICE_TO_HOST, 1);
DRV_USB_DEVICE_EndpointDisable(handle, ep );
5.1.12.7.5.7 DRV_USB_DEVICE_EndpointDisableAll Function
C
USB_ERROR DRV_USB_DEVICE_EndpointDisableAll(
DRV_HANDLE handle
);
Description
This function disables all provisioned endpoints in both directions.
5.1 Driver Library Help MPLAB Harmony Help USB Driver Library
5-585
Preconditions
Client handle should be valid.
Parameters
Parameters Description
handle Client's driver handle (returned from DRV_USB_Open)
Returns
None.
Remarks
This function is typically called by the USB Device Layer to disable all endpoints on detecting bus reset.
Example
// This code snippet shows an example of how to disable
// all endpoints.
DRV_USB_DEVICE_EndpointDisableAll(handle);
5.1.12.7.5.8 DRV_USB_DEVICE_EndpointEnable Function
C
USB_ERROR DRV_USB_DEVICE_EndpointEnable(
DRV_HANDLE handle,
USB_ENDPOINT endpointAndDirection,
USB_TRANSFER_TYPE transferType,
uint16_t endpointSize
);
Description
This function enables a endpoint for the specified direction and endpoint size. The function will enable the endpoint for
communication in one direction at a time. It must be called twice if the endpoint is required to communicate in both the directions,
except for control endpoints. If the endpoint type is a control endpoint, the endpoint is always bi-directional and the function
needs to be called only once. The size of the endpoint must match the wMaxPacketSize reported in the endpoint descriptor for
this endpoint. The function does not check if the endpoint is already in use. It is the client's responsibility to make sure that a
endpoint is not accidently re-used.
Preconditions
Client handle should be valid.
Parameters
Parameters Description
handle Client's driver handle (returned from DRV_USB_Open)
endpointAndDirection Specifies the endpoint and direction.
transferType Should be USB_TRANSFER_TYPE_CONTROL for control endpoint,
USB_TRANSFER_TYPE_BULK for bulk endpoint,
USB_TRANSFER_TYPE_INTERRUPT for interrupt endpoint and
USB_TRANSFER_TYPE_ISOCHRONOUS for isochronous endpoint.
endpointSize Maximum size (in bytes) of the endpoint as reported in the endpoint descriptor.
Returns
USB_ERROR_NONE - The endpoint was successfully enabled. USB_ERROR_DEVICE_ENDPOINT_INVALID - If the endpoint
that is being accessed is is out of the valid endpoint defined for this driver instance.
5.1 Driver Library Help MPLAB Harmony Help USB Driver Library
5-586
Remarks
None.
Example
// This code snippet shows an example of how to enable endpoint
// 0 for control transfers. Note that for a control endpoint, the
// direction parameter is ignored. A control endpoint is always
// bi-directional. Endpoint sizeis 64 bytes.
uint8_t ep;
ep = USB_ENDPOINT_AND_DIRECTION(USB_DATA_DIRECTION_DEVICE_TO_HOST, 0);
DRV_USB_DEVICE_EndpointEnable(handle, ep, USB_TRANSFER_TYPE_CONTROL, 64);
// This code snippet shows an example of how to set up a endpoint
// for BULK IN transfer. For an IN transfer, data moves from device
// to host. In this example, endpoint 1 is enabled. The maximum
// packet size is 64.
uint8_t ep;
ep = USB_ENDPOINT_AND_DIRECTION(USB_DATA_DIRECTION_DEVICE_TO_HOST, 1);
DRV_USB_DEVICE_EndpointEnable(handle, ep, USB_TRANSFER_TYPE_BULK, 64);
// If endpoint 1 must also be set up for BULK OUT, then the enable
// function must be called again, as shown here.
ep = USB_ENDPOINT_AND_DIRECTION(USB_DATA_DIRECTION_HOST_TO_DEVICE, 1);
DRV_USB_DEVICE_EndpointEnable(handle, ep, USB_TRANSFER_TYPE_BULK, 64);
5.1.12.7.5.9 DRV_USB_DEVICE_EndpointIsEnabled Function
C
bool DRV_USB_DEVICE_EndpointIsEnabled(
DRV_HANDLE client,
USB_ENDPOINT endpointAndDirection
);
Description
This function returns the enable/ disable status of the specified endpoint and direction.
Preconditions
Client handle should be valid.
Parameters
Parameters Description
handle Client's driver handle (returned from DRV_USB_Open)
endpointAndDirection Specifies the endpoint and direction.
Returns
Returns true if the endpoint is enabled, false otherwise.
Remarks
None.
5.1 Driver Library Help MPLAB Harmony Help USB Driver Library
5-587
Example
// This code snippet shows an example of how the
// DRV_USB_DEVICE_EndpointIsEnabled() function can be used to obtain the
// status of the endpoint 1 and IN direction.
USB_ENDPOINT ep;
ep = USB_ENDPOINT_AND_DIRECTION(USB_DATA_DIRECTION_DEVICE_TO_HOST, 1);
if(DRV_USB_ENDPOINT_STATE_DISABLED ==
DRV_USB_DEVICE_EndpointIsEnabled(handle, ep))
{
// Endpoint is disabled. Enaable endpoint.
DRV_USB_DEVICE_EndpointEnable(handle, ep, USB_ENDPOINT_TYPE_BULK, 64);
}
5.1.12.7.5.10 DRV_USB_DEVICE_EndpointIsStalled Function
C
bool DRV_USB_DEVICE_EndpointIsStalled(
DRV_HANDLE client,
USB_ENDPOINT endpoint
);
Description
This function returns the stall status of the specified endpoint and direction.
Preconditions
Client handle should be valid.
Parameters
Parameters Description
handle Client's driver handle (returned from DRV_USB_Open)
endpointAndDirection Specifies the endpoint and direction.
Returns
Returns true if endpoint is stalled, false otherwise.
Remarks
None.
Example
// This code snippet shows an example of how the
// DRV_USB_DEVICE_EndpointIsStalled() function can be used to obtain the
// stall status of the endpoint 1 and IN direction.
USB_ENDPOINT ep;
ep = USB_ENDPOINT_AND_DIRECTION(USB_DATA_DIRECTION_DEVICE_TO_HOST, 1);
if(true == DRV_USB_DEVICE_EndpointIsStalled (handle, ep))
{
// Endpoint stall is enabled. Clear the stall.
DRV_USB_DEVICE_EndpointStallClear(handle, ep);
}
5.1 Driver Library Help MPLAB Harmony Help USB Driver Library
5-588
5.1.12.7.5.11 DRV_USB_DEVICE_EndpointStall Function
C
USB_ERROR DRV_USB_DEVICE_EndpointStall(
DRV_HANDLE handle,
USB_ENDPOINT endpointAndDirection
);
Description
This function stalls an endpoint in the specified direction.
Preconditions
Client handle should be valid.
Parameters
Parameters Description
handle Client's driver handle (returned from DRV_USB_Open)
endpointAndDirection Specifies the endpoint and direction.
Returns
USB_ERROR_NONE - The endpoint was successfully enabled. USB_ERROR_DEVICE_ENDPOINT_INVALID - If the endpoint
that is being accessed is is out of the valid endpoint defined for this driver instance.
Remarks
None.
Example
// This code snippet shows an example of how to stall an endpoint. In
// this case , endpoint 1 IN direction is stalled.
USB_ENDPOINT ep;
ep = USB_ENDPOINT_AND_DIRECTION(USB_DATA_DIRECTION_DEVICE_TO_HOST, 1);
DRV_USB_DEVICE_EndpointStall(handle, ep);
5.1.12.7.5.12 DRV_USB_DEVICE_EndpointStallClear Function
C
USB_ERROR DRV_USB_DEVICE_EndpointStallClear(
DRV_HANDLE handle,
USB_ENDPOINT endpointAndDirection
);
Description
This function clears the stall on an endpoint in the specified direction.
Preconditions
Client handle should be valid.
Parameters
Parameters Description
handle Client's driver handle (returned from DRV_USB_Open)
endpointAndDirection Specifies the endpoint and direction.
5.1 Driver Library Help MPLAB Harmony Help USB Driver Library
5-589
Returns
USB_ERROR_NONE - The endpoint was successfully enabled. USB_ERROR_DEVICE_ENDPOINT_INVALID - If the endpoint
that is being accessed is is out of the valid endpoint defined for this driver instance.
Remarks
None.
Example
// This code snippet shows an example of how to clear a stall. In this
// example. the stall on endpoint 1 IN direction is cleared.
USB_ENDPOINT ep;
ep = USB_ENDPOINT_AND_DIRECTION(USB_DATA_DIRECTION_DEVICE_TO_HOST, 1);
DRV_USB_DEVICE_EndpointStallClear(handle, ep);
5.1.12.7.5.13 DRV_USB_DEVICE_IRPCancelAll Function
C
USB_ERROR DRV_USB_DEVICE_IRPCancelAll(
DRV_HANDLE client,
USB_ENDPOINT endpointAndDirection
);
Description
This function cancels all IRPs that are queued and in progress at the specified endpoint.
Preconditions
Client handle should be valid.
Parameters
Parameters Description
handle Client's driver handle (returned from DRV_USB_Open)
endpointAndDirection Specifies the endpoint and direction.
Returns
USB_ERROR_NONE - The endpoint was successfully enabled. USB_ERROR_DEVICE_ENDPOINT_INVALID - If the endpoint
that is being accessed is is out of the valid endpoint defined for this driver instance.
Remarks
None.
Example
// This code snippet shows an exampl of how to cancel all IRPs.
void MyIRPCallback(USB_DEVICE_IRP * irp)
{
// Check if this is setup command
if(irp->status == USB_DEVICE_IRP_STATUS_SETUP)
{
if(IsSetupCommandSupported(irp->data) == false)
{
// This means that this setup command is not
// supported. Stall the endpoint.
DRV_USB_DEVICE_IRPCancelAll(handle, ep);
5.1 Driver Library Help MPLAB Harmony Help USB Driver Library
5-590
DRV_USB_DEVICE_EndpointStall(handle, ep);
}
}
}
5.1.12.7.5.14 DRV_USB_DEVICE_IRPSubmit Function
C
USB_ERROR DRV_USB_DEVICE_IRPSubmit(
DRV_HANDLE client,
USB_ENDPOINT endpointAndDirection,
USB_DEVICE_IRP * irp
);
Description
This function submits a I/O Request Packet (IRP) for processing to the USB Driver. The IRP allows a client to send and receive
data from the USB Host. The data will sent or received through the specified endpoint. The direction of the data transfer is
indicated by the direction flag in the endpointAndDirection structure. Submitting an IRP arms the endpoint to either send data to
or receive data from the host. If an IRP is under progress on the endpoint, then the subsequent IRP submit operation will result
in the IRPs getting queued. The contents of the IRP should not be changed till the IRP has been processed.
Particular attention should be paid to the size parameter of IRP. The following should be noted:
• The size parameter while sending data to the host can be less than, greater than, equal to or be an exact multiple of
maximum packet size for the endpoint. The maximum packet size for the endpoint determines the number of transactions
required to process the IRP.
• If the size parameter while sending data to the host is less than maximum packet size, the transfer will complete in one
transaction.
• If the size parameter while sending data to the host is greater than maximum packet size, the IRP will be processed in
mulitple transactions.
• If the size parameter while sending data to the host is equal to or an exact multiple of the maximum packet size, the client can
optionally ask the driver to send a Zero Length packet by specifying the USB_DEVICE_IRP_FLAG_DATA_COMPLETE flag
as the flag parameter.
• The size parameter while receiving data from the host must be an exact multiple of the maximum packet size of the endpoint.
If this is not the case, the driver will return a USB_ERROR_IRP_SIZE_INVALID result. If while processing the IRP, the driver
receives less than maximum packet size or a ZLP from the host, the driver considers the IRP as processed. The size
paramter at this point contains the actual amount of data received from the host. The IRP status is returned as
USB_DEVICE_IRP_STATUS_COMPLETED_SHORT.
• If a ZLP needs to be sent to host, the IRP size should be specified as 0 and flag should be set as
USB_DEVICE_IRP_FLAG_DATA_COMPLETE.
• If the IRP size is an exact multiple of endpoint size, the client can request the driver to not send a ZLP, by specifying the
USB_DEVICE_IRP_FLAG_DATA_PENDING. This flag indicates that there is more data pending in this transfer.
• Specifying a size less than endpoint size along with the USB_DEVICE_IRP_FLAG_DATA_PENDING flag will cause the driver
to return a USB_ERROR_IRP_SIZE_INVALID.
• If the size id greater than endpoint size, and the flag is specified as USB_DEVICE_IRP_FLAG_DATA_PENDING, the driver
will send multiple of endpoint size data.
Preconditions
Client handle should be valid.
5.1 Driver Library Help MPLAB Harmony Help USB Driver Library
5-591
Parameters
Parameters Description
handle Client's driver handle (returned from DRV_USB_Open)
endpointAndDirection Specifies the endpoint and direction.
irp Pointer to the USB_DEVICE_IRP structure.
Returns
USB_ERROR_NONE - if the IRP was submitted successful. USB_ERROR_IRP_SIZE_INVALID - if the size parameter of the
IRP is not correct. USB_ERROR_IRP_QUEUE_FULL - if the driver IRP queue is full.
Remarks
None.
Example
// The following code snippet shows an example of how to schedule a
// IRP to send data from device to host. Assume that max packet size
// is 64 and endpoint is 1. In this example, the transfer is
// processed as 3 transactions of 64, 64 and 2 bytes.
USB_ENDPOINT ep;
USB_DEVICE_IRP irp;
ep.direction = USB_ENDPOINT_AND_DIRECTION(USB_DATA_DIRECTION_DEVICE_TO_HOST, 1);
irp.data = myDataBufferToSend;
irp.size = 130;
irp.flags = USB_DEVICE_IRP_FLAG_DATA_COMPLETE;
irp.callback = MyIRPCompletionCallback;
irp.referenceData = (uintptr_t)&myDeviceLayerObj;
if (DRV_USB_DEVICE_IRPSubmit(handle, ep, irp)
!= USB_ERROR_NONE)
{
// This means there was an error.
}
else
{
// The status of the IRP can be checked.
while(irp.status != USB_DEVICE_IRP_STATUS_COMPLETED)
{
// Wait or run a task routine.
}
}
// The following code snippet shows how the client can request
// the driver to send a ZLP when the size is an exact multiple of
// end point size.
irp.data = myDataBufferToSend;
irp.size = 128;
irp.flags = USB_DEVICE_IRP_FLAG_DATA_COMPLETE;
irp.callback = MyIRPCompletionCallback;
irp.referenceData = (uintptr_t)&myDeviceLayerObj;
// Note that while receiving data from the host, the size should
// be an exact multiple maximum packet size of the endpoint. In the
// example below, the DRV_USB_DEVICE_IRPSubmit() function will
// return a USB_DEVICE_IRP_SUBMIT_RESULT_INVALID_SIZE value.
ep = USB_ENDPOINT_AND_DIRECTION(USB_DATA_DIRECTION_HOST_TO_DEVICE, 1);
5.1 Driver Library Help MPLAB Harmony Help USB Driver Library
5-592
irp.data = myDataBufferToSend;
irp.size = 60; // THIS SIZE IS NOT CORRECT
irp.flags = USB_DEVICE_IRP_FLAG_DATA_COMPLETE;
irp.callback = MyIRPCompletionCallback;
irp.referenceData = (uintptr_t)&myDeviceLayerObj;
5.1.12.7.5.15 DRV_USB_HOST_BusResetControl Function
C
void DRV_USB_HOST_BusResetControl(
DRV_HANDLE client,
bool control
);
Description
This is function DRV_USB_HOST_BusResetControl.
5.1.12.7.5.16 DRV_USB_HOST_DeviceCurrentSpeedGet Function
C
USB_SPEED DRV_USB_HOST_DeviceCurrentSpeedGet(
DRV_HANDLE client
);
Description
This is function DRV_USB_HOST_DeviceCurrentSpeedGet.
5.1.12.7.5.17 DRV_USB_HOST_IRPCancel Function
C
void DRV_USB_HOST_IRPCancel(
USB_HOST_IRP * inputIRP
);
Description
This is function DRV_USB_HOST_IRPCancel.
5.1.12.7.5.18 DRV_USB_HOST_IRPSubmit Function
C
USB_ERROR DRV_USB_HOST_IRPSubmit(
DRV_USB_HOST_PIPE_HANDLE hPipe,
USB_HOST_IRP * inputIRP
);
Description
This is function DRV_USB_HOST_IRPSubmit.
5.1.12.7.5.19 DRV_USB_HOST_OperationEnable Function
C
void DRV_USB_HOST_OperationEnable(
DRV_HANDLE hClient,
bool enable
);
5.1 Driver Library Help MPLAB Harmony Help USB Driver Library
5-593
Description
This is function DRV_USB_HOST_OperationEnable.
5.1.12.7.5.20 DRV_USB_HOST_StartOfFrameControl Function
C
void DRV_USB_HOST_StartOfFrameControl(
DRV_HANDLE client,
bool control
);
Description
This is function DRV_USB_HOST_StartOfFrameControl.
5.1.12.7.5.21 DRV_USB_HOST_TimerIsComplete Function
C
bool DRV_USB_HOST_TimerIsComplete(
DRV_HANDLE client
);
Description
This is function DRV_USB_HOST_TimerIsComplete.
5.1.12.7.5.22 DRV_USB_HOST_TimerReset Function
C
void DRV_USB_HOST_TimerReset(
DRV_HANDLE client
);
Description
This is function DRV_USB_HOST_TimerReset.
5.1.12.7.5.23 DRV_USB_HOST_TimerStart Function
C
bool DRV_USB_HOST_TimerStart(
DRV_HANDLE client,
uint32_t periodInMilliseconds
);
Description
This is function DRV_USB_HOST_TimerStart.
5.1.12.7.5.24 DRV_USB_Tasks Function
C
void DRV_USB_Tasks(
SYS_MODULE_OBJ object
);
Description
Maintains the driver's state machine when the driver is configured for polled mode. This function should be called from the
5.1 Driver Library Help MPLAB Harmony Help USB Driver Library
5-594
system tasks routine.
Preconditions
The DRV_USB_Initialize routine must have been called for the specified USB driver instance.
Parameters
Parameters Description
object Object handle for the specified driver instance (returned from DRV_USB_Initialize)
Returns
None
Remarks
This routine is normally not called directly by an application. It is called by the system's Tasks routine (SYS_Tasks). This function
will never block.
Example
SYS_MODULE_OBJ object; // Returned from DRV_USB_Initialize
while (true)
{
DRV_USB_Tasks(object);
// Do other tasks
}
5.1.12.7.6 Data Types and Constants
5.1.12.7.6.1 DRV_USB_ENDPOINT_TABLE_ENTRY_SIZE Macro
C
#define DRV_USB_ENDPOINT_TABLE_ENTRY_SIZE
5.1.12.7.6.2 DRV_USB_HOST_PIPE_HANDLE_INVALID Macro
C
#define DRV_USB_HOST_PIPE_HANDLE_INVALID ((DRV_USB_HOST_PIPE_HANDLE)(-1))
Description
USB Driver Host Pipe Handle Invalid
Defines the USB Driver Host Pipe Invalid handle
Remarks
None.
5.1.12.7.6.3 DRV_USB_INDEX Macro
C
#define DRV_USB_INDEX 0
Description
This is macro DRV_USB_INDEX.
5.1 Driver Library Help MPLAB Harmony Help USB Driver Library
5-595
5.1.12.7.6.4 DRV_USB_INDEX_0 Macro
C
#define DRV_USB_INDEX_0 0
Description
USB Driver Module Index Numbers
These constants provide USB driver index definitions.
Remarks
These constants should be used in place of hard-coded numeric literals and should be passed into the DRV_USB_Initialize and
DRV_USB_Open routines to identify the driver instance in use. These are not indicative of the number of modules that are
actually supported by the microcontroller.
5.1.12.7.6.5 DRV_USB_INTERRUPT_SOURCE Macro
C
#define DRV_USB_INTERRUPT_SOURCE INT_SOURCE_USB_1
Description
This is macro DRV_USB_INTERRUPT_SOURCE.
5.1.12.7.6.6 DRV_USB_PERIPHERAL_ID Macro
C
#define DRV_USB_PERIPHERAL_ID USB_ID_1
Description
This is macro DRV_USB_PERIPHERAL_ID.
5.1.12.7.6.7 DRV_USB_EVENT Enumeration
C
typedef enum {
DRV_USB_EVENT_ERROR = 1,
DRV_USB_EVENT_RESET_DETECT,
DRV_USB_EVENT_RESUME_DETECT,
DRV_USB_EVENT_IDLE_DETECT,
DRV_USB_EVENT_STALL,
DRV_USB_EVENT_SOF_DETECT,
DRV_USB_EVENT_HOST_ATTACH,
DRV_USB_EVENT_HOST_DETACH
} DRV_USB_EVENT;
Description
USB Driver Events Enumeration
Identifies the different events that the USB Driver provides.
Members
Members Description
DRV_USB_EVENT_ERROR = 1 Bus error occurred and was reported
DRV_USB_EVENT_RESET_DETECT Host has issued a device reset
5.1 Driver Library Help MPLAB Harmony Help USB Driver Library
5-596
DRV_USB_EVENT_RESUME_DETECT Resume detected while USB in suspend mode
DRV_USB_EVENT_IDLE_DETECT Idle detected
DRV_USB_EVENT_STALL Stall handshake has occurred
5.1.12.7.6.8 DRV_USB_EVENT_CALLBACK Type
C
typedef void (* DRV_USB_EVENT_CALLBACK)(uintptr_t hClient, DRV_USB_EVENT eventType, void *
eventData);
Description
Type of the USB Event Callback Function
Type of the USB event callback function. The client should register an event callback function of this type when it intends to
receive events from the USB driver. The event callback function is registered using the DRV_USB_ClientEventCallBackSet()
function.
Parameters
Parameters Description
hClient handle to driver client that registered this callback function.
eventType Event type
eventData Event relevant data.
Returns
None.
Remarks
None.
5.1.12.7.6.9 DRV_USB_HOST_PIPE_HANDLE Type
C
typedef uintptr_t DRV_USB_HOST_PIPE_HANDLE;
Description
USB Driver Host Pipe Handle
Defines the USB Driver Host Pipe handle type
Remarks
None.
5.1.12.7.6.10 DRV_USB_INIT Structure
C
typedef struct {
SYS_MODULE_INIT moduleInit;
USB_MODULE_ID usbID;
bool stopInIdle;
bool suspendInSleep;
INT_SOURCE interruptSource;
USB_SPEED operationSpeed;
USB_OPMODES operationMode;
void * endpointTable;
} DRV_USB_INIT;
5.1 Driver Library Help MPLAB Harmony Help USB Driver Library
5-597
Description
USB Device Driver Initialization Data
This structure contains all the data necessary to initialize the USB driver.
Members
Members Description
SYS_MODULE_INIT moduleInit; System module initialization
USB_MODULE_ID usbID; Identifies peripheral (PLIB-level) ID
bool stopInIdle; Boolean flag: true -> Stop USB module in Idle Mode
bool suspendInSleep; Boolean flag: true -> Suspend USB in Sleep Mode
INT_SOURCE interruptSource; Interrupt Source for USB module
USB_SPEED operationSpeed; USB Operation speed
USB_OPMODES operationMode; USB module operating mode
void * endpointTable; Endpoint Descriptor Table buffer
Remarks
A pointer to a structure of this format containing the desired initialization data must be passed into the DRV_USB_Initialize
routine.
5.1.12.8 Files
Files
Name Description
drv_usb.h USB Device Driver Interface File
drv_usb_config_template.h USB driver configuration definitions template
Description
5.1.12.8.1 drv_usb.h
USB Device Driver Interface
The USB device driver provides a simple interface to manage the "USB" peripheral. This file defines the interface definitions and
prototypes for the USB driver.
Enumerations
Name Description
DRV_USB_EVENT Identifies the different events that the USB Driver provides.
Functions
Name Description
DRV_USB_ClientEventCallBackSet This function sets up the event callback function that is invoked by the
USB controller driver to notify the a client of USB bus events.
DRV_USB_Close Closes an opened-instance of the USB driver
DRV_USB_DEVICE_AddressSet This function will set the USB module address that is obtained from
the host.
5.1 Driver Library Help MPLAB Harmony Help USB Driver Library
5-598
DRV_USB_DEVICE_Attach This function will attach the device to the USB.
DRV_USB_DEVICE_CurrentSpeedGet This function will return the USB speed at which device is operating.
DRV_USB_DEVICE_Detach This function will detach the device from the USB.
DRV_USB_DEVICE_EndpointDisable This function disables an endpoint.
DRV_USB_DEVICE_EndpointDisableAll This function disables all provisioned non-zero endpoints.
DRV_USB_DEVICE_EndpointEnable This function enables a endpoint for the specified direction and
endpoint size.
DRV_USB_DEVICE_EndpointIsEnabled This function returns the enable/ disable status of the specified
endpoint and direction.
DRV_USB_DEVICE_EndpointIsStalled This function returns the stall status of the specified endpoint and
direction.
DRV_USB_DEVICE_EndpointStall This function stalls an endpoint in the specified direction.
DRV_USB_DEVICE_EndpointStallClear This function clears the stall on an endpoint in the specified direction.
DRV_USB_DEVICE_IRPCancelAll This function cancels all IRPs that are queued and in progress at the
specified endpoint.
DRV_USB_DEVICE_IRPSubmit This function submits a I/O Request Packet (IRP) for processing to
the USB Driver.
DRV_USB_HOST_BusResetControl This is function DRV_USB_HOST_BusResetControl.
DRV_USB_HOST_DeviceCurrentSpeedGet This is function DRV_USB_HOST_DeviceCurrentSpeedGet.
DRV_USB_HOST_IRPCancel This is function DRV_USB_HOST_IRPCancel.
DRV_USB_HOST_IRPSubmit This is function DRV_USB_HOST_IRPSubmit.
DRV_USB_HOST_OperationEnable This is function DRV_USB_HOST_OperationEnable.
DRV_USB_HOST_OperationIsEnabled This is function DRV_USB_HOST_OperationIsEnabled.
DRV_USB_HOST_PipeClose This is function DRV_USB_HOST_PipeClose.
DRV_USB_HOST_PipeSetup This is function DRV_USB_HOST_PipeSetup.
DRV_USB_HOST_StartOfFrameControl This is function DRV_USB_HOST_StartOfFrameControl.
DRV_USB_HOST_TimerIsComplete This is function DRV_USB_HOST_TimerIsComplete.
DRV_USB_HOST_TimerReset This is function DRV_USB_HOST_TimerReset.
DRV_USB_HOST_TimerStart This is function DRV_USB_HOST_TimerStart.
DRV_USB_Initialize Initializes the USB driver
DRV_USB_Open Opens the specified USB driver instance and returns a handle to it
DRV_USB_Status Provides the current status of the USB driver module
DRV_USB_Tasks Maintains the driver's state machine when the driver is configured for
polled mode.
DRV_USB_Tasks_ISR Maintains the driver's state machine and implements its ISR
Macros
Name Description
DRV_USB_ENDPOINT_TABLE_ENTRY_SIZE
DRV_USB_HOST_PIPE_HANDLE_INVALID Defines the USB Driver Host Pipe Invalid handle
DRV_USB_INDEX_0 USB driver index definitions
Structures
Name Description
DRV_USB_INIT Contains all the data necessary to initialize the USB device
5.1 Driver Library Help MPLAB Harmony Help USB Driver Library
5-599
Types
Name Description
DRV_USB_EVENT_CALLBACK Type of the USB event callback function
DRV_USB_HOST_PIPE_HANDLE Defines the USB Driver Host Pipe handle type
Company
Microchip Technology Incorported
FileName: drv_usb.h
5.1.12.8.2 drv_usb_config_template.h
USB Driver Configuration Definitions for the template version
These definitions statically define the driver's mode of operation.
Macros
Name Description
DRV_USB_INDEX This is macro DRV_USB_INDEX.
DRV_USB_INTERRUPT_SOURCE This is macro DRV_USB_INTERRUPT_SOURCE.
DRV_USB_PERIPHERAL_ID This is macro DRV_USB_PERIPHERAL_ID.
File Name
drv_usb_config_template.h
Company
Microchip Technology Incorported
5.1.13 MRF24W Wi-Fi Driver Library
MRF24W Wi-Fi Driver Library
for
Microchip Microcontrollers
This library provides an interface to manage the Wi-Fi module on the MRF24W family of Microchip microcontrollers in different
modes of operation.
Description
Content pending.
5.1.13.1 Introduction
MRF24W Wi-Fi Driver Library
for
Microchip Microcontrollers
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-600
This library provides a low-level abstraction of the MRF24W Wi-Fi Driver Library that is available on the Microchip family of
microcontrollers with a convenient C language interface. It can be used to simplify low-level access to the module without the
necessity of interacting directly with the module's registers, there by hiding differences from one microcontroller variant to
another.
Description
Note: This information was not available at time of release and will be added in a future release of MPLAB Harmony.
5.1.13.2 Release Notes
MPLAB Harmony Version: v0.70b MRF24W Wi-Fi Driver Library Version : 3.0.0 Release Date: 18Nov2013
New This Release:
Nothing to report in this release.
Known Issues:
• No W-iFi demonstrations are available for PIC32MZ
• Webserver demonstration:
• Mpfsupload of image requires system boot upon completion
• EasyConfig Demonstration (Explorer 16 Development Board and PIC32 Ethernet Starter Kit)
• Mpfsupload of image requires system boot upon completion
• Ad-Hoc mode – cannot retrieve scan info/cannot redirect network
• Security (minor problem)
• WEP Shared Key is not supported
• Stack
• Heap memory leak
• TCP network traffic (Max TX Packet error detect)
• Heap allocation failure
• Services not verified
• DNS Server
• DNS Client
• Dynamic DNS
• Zero Conf
• IPv6
• SNMPv1, SNMP2, SNMP3
• FTP
• Data throughput in open air (throughput is still lower than v5 stack)
• IPerf TCP RX/TX (320/102 Kbps)
• IPerf UDP RX/TX (570/468 Kbps)
5.1.13.2.1 v0.51.01b
Release notes for MRF24WG Wi-Fi Driver v0.51.01b
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-601
Description
Due to a special circumstance for this release the MRF24WG Wi-Fi driver will compile and work with legacy peripheral drivers
(plib.h), and not with the MPLAB Harmony peripheral (peripheral.h). This MRF24WG Wi-F idriver compiling issue will be fixed in
a future release. Applications can still take advantage of the V6 stack features and services in this B1U dot release, along with
Wi-Fi connectivity.
Known Issues:
1) Stack ASSERT condition while waiting for RAW_MOVE_TO_COMPLETE
2) Web Server Demo hang or irresponsive to HTTP query
Software Requirements:
(1) MPLAB X IDE 1.80
(2) XC32 compiler v1.21 and later
Applicable Product:
(1) MRF24WG
Supported Application Demos:
(1) Web Server Demo
a. SNMPv3, multi-port connection (Ethernet + Wi-Fi)
b. Network type supported: Infrastructure (Client STA)
c. Security mode supported: Open , WEP 64/128 Open, WPS, WPA/WPA2 PSK TKIP/AES
Project Files:
To run with Explorer 16 Development Board (EX16)
Directory folder - “.\apps\tcpip\web_server\firmware\pic32_ex16.X”
To run with PIC32 IO Expansion Board with Ethernet Starter Kit (ESK)
Directory folder - “.\apps\tcpip\web_server\firmware\pic32_esk_mrf24w.X”
(2) Console Demo
a. Network benchmark debug/test support such as iPerf, etc via system command line access.
b. Network type supported: Infrastructure (Client STA), Ad-Hoc, Wi-Fi Direct
If testing Wifi-Direct, use RF module FW version 0x3107.
RF module FW version 0x3108 does NOT have support for Wi-Fi Direct.
Project File:
To run with Explorer 16 Development Board (EX16)
Directory
“.\apps\tcpip\wifi_console\firmware\pic32_ex16_mrf24w.X”
(3) EasyConfig Demo
a. Network provision allowing configurations of an embedded decide on a wireless network. (SoftAP, Ad-Hoc)
b. Network type supported: SoftAP, Ad-Hoc
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-602
Project File:
To run with Explorer 16 Development Board (EX16)
Directory
“.\apps\tcpip\wifi_easyconf\firmware\pic32_ex16.X”
Key Features:
Verified:
(1) SNMPv3
(2) DHCP Server/Client - server supports up to max 4 IPs
(3) SoftAP is able to support up to max 4 clients (STAs)
Requires RF module FW version 0x3108.
RF module FW version 0x3107 only supports 1 client for SoftAP.
(4) Ad-Hoc network with support for up to max 4 STAs
(5) Multi-Ethernet ports (Ethernet and Wi-Fi)
(6) Serial console 115,200 baud
Supported:
(1) ZeroConfig/Bonjour (with mDNS)
(2) SNMP v1, 2c, v3
(3) SMTP
(4) SSL (512, 1024, 2048-bit)
(5) HTTP2
(6) ICMP
(7) DNS
(8) NBNS
(9) Iperf
(10) TCP/UDP modules
(11) TCPIP Network Commands
(12) TCPIP Storage Service
(13) Announce
(14) ARP (Gratuitous)
(15) Berkeley API
(16) ZeroConfig/Bonjour (with mDNS)
(17) Power management / Power Save
• Active mode (Known as normal mode in v5 stack)
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-603
• Doze mode (Known as PS-Polling mode in v5 stack)
Supported But Not Verified:
(1) Telnet
(2) TFTP
(3) SNTP
(4) Reboot Server
(5) IPV6 : This is currently not supported due to a defect of software multicast filter of MRF24WG 3107 or the older FW. The
problem will be fixed with upcoming 3108 FW, and thereby the IPv6 will get supported for Wi-Fi.
(6) FTP
To test ESK board:
• Ethernet Starter Kit (ESK) is valid for Web server demo
• ESK + MRF24WG
• Please note that in order to use the MRF24WG module with the PIC32ESK you need to use an I/O Expansion board
(DM320002) and insert the MRF24WG module in one of the PICtail Plus slots (SPI1 position is the default).
• You need to connect the J10/PMPA4/56 and J10/INT1/37 pins on the I/O Expansion board so that the MRF24WG interrupt
signal reaches the PIC32 processor. For this configuration the MRF24WG driver uses a CN (change notice) interrupt.
5.1.13.2.2 v0.51b
Release notes for MRF24WG Wi-Fi driver v0.51b.
Description
V6 MPLAB Harmony (v0.51b) Beta Release is limited release to demonstrate V6 stack capabilities, and was verified on one
Development Board:
(1) Explorer16 Development Board, with PIC32MX795F512L PIM, and MRF24WG PICtail (FW 0x3108 only)
There are two Application Demos included to demonstrate some Stack services:
(1) Web Server Demo (Infrastructure mode)
(2) EasyConfig Demo (SoftAP and Ad-Hoc modes)
a. Over-air system configuration
For development work and running the above Demos, will require:
(1) MPLAB X IDE v1.85
(2) XC32 compiler v1.21 or later
(3) MPLAB ICD 3
(4) Windows XP SP3 or 7 PC with serial port, USB port.
(5) Development boards mentioned above.
(6) And MLA Stack V6 Harmony (MPLAB Harmony v0_51b) Beta Release package.
Specific V6 Beta Stack features supported and demonstration included: (verified)
(1) SoftAP with support for 4 STA Clients.
(2) DHCP Server/Client. DHCP Server supports up to 4 clients.
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-604
(3) Ad-Hoc network with support for up to 4 STAs (joiners).
(4) Wi-Fi over-air system configuration
(5) MRF24G supporting 802.11b/g mixed
(6) 115,200 baud SPI interface
(7) MPLAB X IDE and X32C compiler
(8) ZeroConfig/Bonjour (with mDNS)
Other V6 Stack services: (included, verified)
(1) IPV4
(2) IPV6 (with Ping only)
(3) SMTP
(4) SSL (512, 1024, 2048-bit)
(5) HTTP
(6) ICMP
(7) NBNS
(8) IPerf
(9) ARP (Gratuitous)
(10) TCP/UDP modules
(11) TCPIP Network Commands
(12) TCPIP Storage Service
Other V6 Stack services: (included, NOT VERIFIED)
(1) SNMP v1, 2c
(2) SNMPv3
(3) SNTP
(4) DNS Client/Server
(5) Telnet
(6) FTP
(7) TFTP
(8) Announce
(9) AutoIP
(10) Berkeley API
(11) Reboot Server
Specific Stack/Wi-Fi Connection Agent supports:
(1) Wi-Fi Specific Features:
a. ENABLE_SOFTWARE_MULTICAST_FILTER
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-605
b. RETRIEVE_BINARY_KEY (not support in Beta)
c. SAVE_WPS_CONFIDENTIALS (not support in Beta)
d. DISABLE_MODULE_FW_CONNECT_MANAGER_IN_INFRASTRUCTURE
e. DERIVE_KEY_FROM_PASSPHRASE_IN_HOST
f. MY_DEFAULT_MAC_ADDRESS
(2) Network Type:
a. 802.11 b/g mixed
b. 802.11 b-only
c. 802.11 legacy
(3) Network Mode:
a. Infrastructure (Open , WEP 64/128 Open/Shared Key), WPS, WPA/WPA2 PSK TKIP/AES)
b. Ad-Hoc (Open, WEP 64/128 Open/Shared Key)
c. SoftAP (Open, WEP 64/128 Open Key)
(4) Power Save
a. Normal
b. PS-Poll
MLA STACK V6 MPLAB Harmony (v0.51b) Beta Release PACKAGE
DEMO APPLICATION & MICROCHIP DEVELOPMENT BOARD
Single Port (Wi-Fi only) - WEB Server and EasyConfig Demos
Development Board Configuration:
Explorer16 Development Board
MRF24WG PICtail (FW 0x3108 only)
PIC32MX795F512L PIM
WEB Server Demo project:
“…\software\isp_root\apps\tcpip\tcpip_web_server_demo_app\firmware\pic32_ex16.X”
EasyConfig Demo project:
“…\software\isp_root\apps\tcpip\tcpip_wifi_easyconfig_app\firmware\pic32_ex16.X”
DEMO CONFIGURATION
Refer to WF_Config.h and TCPIP_Config.h files in respective MPLAB X IDE demo project for network configuration and setup
information.
5.1.13.3 SW License Agreement
(c) 2013 Microchip Technology Inc.
Microchip licenses this software to you solely for use with Microchip products. The software is owned by Microchip and its
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-606
licensors, and is protected under applicable copyright laws. All rights reserved.
SOFTWARE IS PROVIDED "AS IS" MICROCHIP EXPRESSLY DISCLAIMS ANY WARRANTY OF ANY KIND, WHETHER
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL MICROCHIP BE LIABLE FOR
ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, HARM TO
YOUR EQUIPMENT, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS
BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR
CONTRIBUTION, OR OTHER SIMILAR COSTS.
To the fullest extent allowed by law, Microchip and its licensors liability shall not exceed the amount of fees, if any, that you have
paid directly to Microchip to use this software.
MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE TERMS.
5.1.13.4 Using the Library
This topic describes the basic architecture of the MRF24W Wi-Fi Driver Library and provides information and examples on how
to use it.
Interface Header File: drv_wifi.h
The interface to the ADC Driver Library is defined in the "drv_wifi.h" header file.
Please refer to the MPLAB Harmony Overview for how the driver interacts with the framework.
5.1.13.4.1 Abstraction Model
This library provides a low-level abstraction of the Wi-Fi module on Microchip's microcontrollers with a convenient C language
interface. This topic describes how that abstraction is modeled in software and introduces the library's interface.
Description
Content pending.
5.1.13.4.2 Library Overview
Refer to the section Driver Overview for how the driver operates in a system.
The library interface routines are divided into various sub-sections, each sub-section addresses one of the blocks or the overall
operation of the Wi-Fi module.
Library Interface
Section
Description
System Functions and
System Configuration
Functions
Provides system module interfaces, device initialization, deinitialization, re-initialization, tasks, and
status functions.
Miscellaneous Provides driver miscellaneous functions, version identification functions etc.
5.1.13.4.3 How the Library Works
This section describes how the Wi-Fi Driver Library operates.
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-607
Description
Before the driver is ready for use, its should be configured (compile time configuration). Refer to the Configuring the Library
section for more details on how to configure the driver.
There are few run-time configuration items that are done during initialization of the driver instance, and a few that are
client-specific and are done using dedicated functions.
To use the Wi-Fi Driver, initialization and client functions should be invoked in a specific sequence to ensure correct operation.
The following is the sequence in which various routines should be called:
Content pending.
5.1.13.4.3.1 System Initialization
This section describes initialization and reinitialization features.
Description
Content pending.
5.1.13.4.3.2 Client Functionality
This section describes core operation.
Description
Content pending.
5.1.13.4.3.3 Other Functionality
This section describes other functionality.
Description
Content pending.
5.1.13.5 Configuring the Library
The configuration of the MRF24W Wi-Fi driver is based on the file drv_wifi_config.h
This header file contains the configuration selection for the Wi-Fi Driver. Based on the selections made, the Wi-Fi Driver will
support or not support selected features. These configuration settings will apply to all instances of the Wi-Fi Driver.
This header can be placed anywhere; however, the path of this header needs to be present in the include search path for a
successful build. Refer to the Applications Overview section for more details.
5.1.13.5.1 Initialization Overrides
Drag and Drop Initialization overrides
5.1.13.5.2 Files
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-608
5.1.13.5.3 Others
Drag and Drop other configuration options
5.1.13.5.4 Examples - Sample Functionality
Drag the example configuration header file.
5.1.13.6 Building the Library
This section list the files that are available in the \src of the MRF24W Wi-Fi driver. It lists which files need to be included in the
build based on either a hardware feature present on the board or configuration option selected by the system.
5.1.13.7 Library Interface
Data Types and Constants
Name Description
DRV_WIFI_BSSID_LENGTH This is macro DRV_WIFI_BSSID_LENGTH.
DRV_WIFI_DEAUTH_REASONCODE_MASK This is macro
DRV_WIFI_DEAUTH_REASONCODE_MASK.
DRV_WIFI_DEFAULT_ADHOC_BEACON_PERIOD ms
DRV_WIFI_DEFAULT_ADHOC_HIDDEN_SSID Default values for WiFi AdHoc settings
DRV_WIFI_DEFAULT_ADHOC_MODE This is macro
DRV_WIFI_DEFAULT_ADHOC_MODE.
DRV_WIFI_DEFAULT_PS_DTIM_ENABLED DTIM wake-up enabled (normally the case)
DRV_WIFI_DEFAULT_PS_DTIM_INTERVAL number of beacon periods
DRV_WIFI_DEFAULT_PS_LISTEN_INTERVAL 100ms multiplier, e.g. 1 * 100ms = 100ms
DRV_WIFI_DEFAULT_SCAN_COUNT Default values for WiFi scan context
DRV_WIFI_DEFAULT_SCAN_MAX_CHANNEL_TIME ms
DRV_WIFI_DEFAULT_SCAN_MIN_CHANNEL_TIME ms
DRV_WIFI_DEFAULT_SCAN_PROBE_DELAY us
DRV_WIFI_DEFAULT_WEP_KEY_TYPE see DRV_WIFI_SecurityWepSet() and
DRV_WIFI_WEP_CONTEXT
DRV_WIFI_DISABLED Do not make this an enumerated type!
DRV_WIFI_DISASSOC_REASONCODE_MASK This is macro
DRV_WIFI_DISASSOC_REASONCODE_MASK.
DRV_WIFI_ENABLED This is macro DRV_WIFI_ENABLED.
DRV_WIFI_MAX_CHANNEL_LIST_LENGTH This is macro
DRV_WIFI_MAX_CHANNEL_LIST_LENGTH.
DRV_WIFI_MAX_NUM_RATES This is macro DRV_WIFI_MAX_NUM_RATES.
DRV_WIFI_MAX_SECURITY_KEY_LENGTH This is macro
DRV_WIFI_MAX_SECURITY_KEY_LENGTH.
DRV_WIFI_MAX_SSID_LENGTH This is macro DRV_WIFI_MAX_SSID_LENGTH.
DRV_WIFI_MAX_WEP_KEY_LENGTH This is macro
DRV_WIFI_MAX_WEP_KEY_LENGTH.
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-609
DRV_WIFI_MAX_WPA_PASS_PHRASE_LENGTH must include string terminator
DRV_WIFI_MAX_WPA2_PASS_PHRASE_LENGTH This is macro
DRV_WIFI_MAX_WPA2_PASS_PHRASE_LENGT
H.
DRV_WIFI_MIN_WPA_PASS_PHRASE_LENGTH Key size defines
DRV_WIFI_NETWORK_TYPE_ADHOC This is macro
DRV_WIFI_NETWORK_TYPE_ADHOC.
DRV_WIFI_NETWORK_TYPE_INFRASTRUCTURE Selection of different WiFi network types
DRV_WIFI_NETWORK_TYPE_P2P not supported
DRV_WIFI_NETWORK_TYPE_SOFT_AP This is macro
DRV_WIFI_NETWORK_TYPE_SOFT_AP.
DRV_WIFI_NO_ADDITIONAL_INFO eventInfo define for DRV_WIFI_ProcessEvent()
when no additional info is supplied
DRV_WIFI_RETRY_ADHOC This is macro DRV_WIFI_RETRY_ADHOC.
DRV_WIFI_RETRY_FOREVER This is macro DRV_WIFI_RETRY_FOREVER.
DRV_WIFI_RTS_THRESHOLD_MAX maximum RTS threshold size in bytes
DRV_WIFI_SECURITY_EAP This is macro DRV_WIFI_SECURITY_EAP.
DRV_WIFI_SECURITY_OPEN Selection of different WiFi security types
DRV_WIFI_SECURITY_WEP_104 This is macro DRV_WIFI_SECURITY_WEP_104.
DRV_WIFI_SECURITY_WEP_40 This is macro DRV_WIFI_SECURITY_WEP_40.
DRV_WIFI_SECURITY_WPA_AUTO_WITH_KEY This is macro
DRV_WIFI_SECURITY_WPA_AUTO_WITH_KEY.
DRV_WIFI_SECURITY_WPA_AUTO_WITH_PASS_PHRASE This is macro
DRV_WIFI_SECURITY_WPA_AUTO_WITH_PASS
_PHRASE.
DRV_WIFI_SECURITY_WPA_WITH_KEY This is macro
DRV_WIFI_SECURITY_WPA_WITH_KEY.
DRV_WIFI_SECURITY_WPA_WITH_PASS_PHRASE This is macro
DRV_WIFI_SECURITY_WPA_WITH_PASS_PHRA
SE.
DRV_WIFI_SECURITY_WPA2_WITH_KEY This is macro
DRV_WIFI_SECURITY_WPA2_WITH_KEY.
DRV_WIFI_SECURITY_WPA2_WITH_PASS_PHRASE This is macro
DRV_WIFI_SECURITY_WPA2_WITH_PASS_PHR
ASE.
DRV_WIFI_SECURITY_WPS_PIN This is macro DRV_WIFI_SECURITY_WPS_PIN.
DRV_WIFI_SECURITY_WPS_PUSH_BUTTON This is macro
DRV_WIFI_SECURITY_WPS_PUSH_BUTTON.
DRV_WIFI_VERSION_NUMBER WiFi Driver Version Number
DRV_WIFI_WEP104_KEY_LENGTH 4 keys of 13 bytes each
DRV_WIFI_WEP40_KEY_LENGTH 4 keys of 5 bytes each
DRV_WIFI_WPA_KEY_LENGTH This is macro DRV_WIFI_WPA_KEY_LENGTH.
DRV_WIFI_WPA2_KEY_LENGTH This is macro DRV_WIFI_WPA2_KEY_LENGTH.
DRV_WIFI_WPS_PIN_LENGTH 7 digits + checksum byte
DRV_WIFI_ADHOC_MODES Selection of different AdHoc connection modes
DRV_WIFI_ADHOC_NETWORK_CONTEXT Contains data pertaining to WiFi AdHoc context
DRV_WIFI_CONNECTION_CONTEXT Contains data pertaining to MRF24WG connection
context
DRV_WIFI_CONNECTION_STATES Wifi Connection states
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-610
DRV_WIFI_DEVICE_INFO Contains data pertaining to MRF24WG device type
and version number
DRV_WIFI_DEVICE_TYPES Codes for WiFi device types
DRV_WIFI_DOMAIN_CODES Regional domain codes.
DRV_WIFI_EVENT_CONN_TEMP_LOST_CODES Selection of different codes when WiFi connection
is temporarily lost.
DRV_WIFI_EVENT_INFO Selection of different EventInfo types
DRV_WIFI_EVENTS Selections for events that can occur.
DRV_WIFI_GENERAL_ERRORS This is type DRV_WIFI_GENERAL_ERRORS.
DRV_WIFI_HIBERNATE_STATE This is type DRV_WIFI_HIBERNATE_STATE.
DRV_WIFI_HIBERNATE_STATES Wifi Hibernate states
DRV_WIFI_MAC_STATS Wifi MIB states
DRV_WIFI_MGMT_ERRORS Error codes returned when a mgmt message is
sent to the MRF24W
DRV_WIFI_MGMT_INDICATE_SOFT_AP_EVENT Contains data pertaining to WiFi Soft AP event
DRV_WIFI_MULTICAST_FILTER_IDS Selections for software Multicast filter ID's
DRV_WIFI_MULTICAST_FILTERS Selections for Software Multicast Filters.
DRV_WIFI_POWER_SAVE_STATES Wifi Power Save states
DRV_WIFI_PS_POLL_CONTEXT Contains data pertaining to WiFi PS-Poll context
DRV_WIFI_REASON_CODES Selection of different codes when a deauth or
disassociation event has occurred.
DRV_WIFI_RECONNECT_MODES Selection of different Reconnection modes
DRV_WIFI_SCAN_CONTEXT Contains data pertaining to WiFi scan context
DRV_WIFI_SCAN_RESULT Contains data pertaining to WiFi scan results
DRV_WIFI_SCAN_TYPES Selection of different WiFi scan types
DRV_WIFI_SECURITY_CONTEXT Contains data pertaining to WiFi security.
DRV_WIFI_SOFT_AP_EVENT_REASON_CODES This is type
DRV_WIFI_SOFT_AP_EVENT_REASON_CODES.
DRV_WIFI_SOFT_AP_STATES This is type DRV_WIFI_SOFT_AP_STATES.
DRV_WIFI_STATUS_CODES Selection of different codes when WiFi connection
fails due to association or authentication failure.
DRV_WIFI_SWMULTICAST_CONFIG Contains data pertaining to WiFi software multicast
filter configuration
DRV_WIFI_TX_MODES Selections for WiFi Tx mode
DRV_WIFI_WEP_CONTEXT Contains data pertaining to WiFi WEP context
DRV_WIFI_WEP_KEY_TYPE Selections for WEP key type when using WEP
security.
DRV_WIFI_WPA_CONTEXT Contains data pertaining to WiFi WPA.
DRV_WIFI_WPA_KEY_INFO Contains data pertaining to WiFi WPA Key
DRV_WIFI_WPS_AUTH_TYPES This is type DRV_WIFI_WPS_AUTH_TYPES.
DRV_WIFI_WPS_CONTEXT Contains data pertaining to WiFi WPS security.
DRV_WIFI_WPS_CREDENTIAL Contains data pertaining to WiFi WPS Credentials
DRV_WIFI_WPS_ENCODE_TYPES This is type DRV_WIFI_WPS_ENCODE_TYPES.
adhocMode Selection of different AdHoc connection modes
ENABLE_P2P_PRINTS not supported
ENABLE_WPS_PRINTS This is macro ENABLE_WPS_PRINTS.
PA6_IO debug, remove later
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-611
PA6_TRISTATE This is macro PA6_TRISTATE.
SET_PA6_AS_OUTPUT This is macro SET_PA6_AS_OUTPUT.
WF_WPS_PIN_LENGTH WPS PIN Length
Miscellaneous Functions
Name Description
DRV_WIFI_ConfigDataErase Erases configuration data from the board EEPROM.
DRV_WIFI_ConfigDataLoad Loads configuration data from the board EEPROM.
DRV_WIFI_ConfigDataPrint Outputs to console the configuration data from the board EEPROM.
DRV_WIFI_ConfigDataSave Save configuration data to the board EEPROM.
DRV_WIFI_ProcessEvent Processes WiFi event
DRV_WIFI_ScanGetResult Read selected scan results back from MRF24W.
DRV_WIFI_SetLinkDownThreshold Sets number of consecutive WiFi Tx failures before link is considered down.
DRV_WIFI_SetPSK Sets the binary WPA PSK code in WPS.
DRV_WIFI_SWMultiCastFilterEnable Forces the MRF24WG to use software multicast filters instead of hardware
multicast filters.
DRV_WIFI_YieldPassphraseToHost Allows host to get WPS WPA-PSK passphrase and convert to binary key.
System Configuration Functions
Name Description
DRV_WIFI_Connect Directs the MRF24WG to connect to a WiFi network.
DRV_WIFI_Deinitialize Initializes the MRF24WG WiFi driver.
DRV_WIFI_Disconnect Directs the MRF24WG to disconnect from a WiFi network.
DRV_WIFI_Initialize Initializes the MRF24WG WiFi driver.
DRV_WIFI_Scan Commands the MRF24W to start a scan operation. This will generate the
WF_EVENT_SCAN_RESULTS_READY event.
System Functions
Name Description
DRV_WIFI_BssidGet Sets the the BSSID set in DRV_WIFI_BssidSet().
DRV_WIFI_BssidSet Sets the the Basic Service Set Identifier (BSSID).
DRV_WIFI_ChannelListGet Gets the the channel list.
DRV_WIFI_ChannelListSet Sets the the channel list.
DRV_WIFI_ConnectContextGet Gets the current WiFi connection context
DRV_WIFI_ConnectionStateGet Gets the current WiFi connection state
DRV_WIFI_DeviceInfoGet Retrieves MRF24WG device information
DRV_WIFI_HWMulticastFilterGet Gets a multicast address filter from one of the two multicast filters.
DRV_WIFI_HWMulticastFilterSet Sets a multicast address filter using one of the two hardware multicast filters.
DRV_WIFI_MacAddressGet Retrieves the MRF24WG MAC address
DRV_WIFI_MacAddressSet Uses a different MAC address for the MRF24W
DRV_WIFI_MacStatsGet Gets MAC statistics.
DRV_WIFI_NetworkTypeGet Gets the WiFi network type
DRV_WIFI_NetworkTypeSet Sets the WiFi network type
DRV_WIFI_PowerSaveStateGet Gets the current power-save state.
DRV_WIFI_ReconnectModeGet Gets the WiFi reconnection mode.
DRV_WIFI_ReconnectModeSet Sets the WiFi reconnection mode.
DRV_WIFI_RegionalDomainGet Retrieves the MRF24WG Regional domain
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-612
DRV_WIFI_RtsThresholdGet Gets the RTS Threshold
DRV_WIFI_RtsThresholdSet Sets the RTS Threshold.
DRV_WIFI_ScanContextGet Gets the WiFi scan context.
DRV_WIFI_ScanContextSet Sets the WiFi scan context.
DRV_WIFI_SecurityGet Gets the current WiFi security setting
DRV_WIFI_SecurityOpenSet Sets WiFi security to open (no security)
DRV_WIFI_SecurityWepSet Sets WiFi security to use WEP.
DRV_WIFI_SecurityWpaSet Sets WiFi security to use WPA or WPA2
DRV_WIFI_SecurityWpsSet Sets WiFi security to use WPS
DRV_WIFI_SoftApEventInfoGet Gets the stored Soft AP event info
DRV_WIFI_SsidGet Sets the SSID
DRV_WIFI_SsidSet Sets the SSID
DRV_WIFI_SWMulticastFilterSet Sets a multicast address filter using one of the software multicast filters.
DRV_WIFI_TxModeGet Gets 802.11 Tx mode
DRV_WIFI_TxModeSet Configures 802.11 Tx mode
DRV_WIFI_TxPowerFactoryMaxGet Retrieves the factory-set max Tx power from the MRF24W.
DRV_WIFI_TxPowerMaxGet Gets the Tx max power on the MRF24WG0M.
DRV_WIFI_TxPowerMaxSet Sets the Tx max power on the MRF24WG0M.
DRV_WIFI_WepKeyTypeGet Gets the Wep Key type
DRV_WIFI_WPSCredentialsGet Gets the WPS credentials
DRV_WIFI_AdhocContextSet Sets the AdHoc context.
DRV_WIFI_RssiGet Gets RSSI value set in DRV_WIFI_RssiSet()
DRV_WIFI_RssiSet Sets RSSI restrictions when connecting
DRV_WIFI_GratuitousArpStart Starts a periodic gratuitous ARP response
DRV_WIFI_GratuitousArpStop Stops a periodic gratuitous ARP.
DRV_WIFI_HibernateEnable Puts the MRF24WG into hibernate mode.
DRV_WIFI_isHibernateEnable Checks if MRF24W is in hibernate mode
DRV_WIFI_PsPollDisable Disables PS-Poll mode.
DRV_WIFI_PsPollEnable Enables PS Poll mode.
Description
This section describes the Application Programming Interface (API) functions of the MRF24W Wi-Fi Driver.
Refer to each section for a detailed description.
5.1.13.7.1 System Functions
5.1.13.7.1.1 DRV_WIFI_BssidGet Function
C
void DRV_WIFI_BssidGet(
uint8_t * p_bssid
);
Description
Retrieves the BSSID set in the previous call to DRV_WIFI_BssidSet().
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-613
Preconditions
WiFi initialization must be complete.
Parameters
Parameters Description
p_context pointer to where BSSID will be written.
Returns
None
Remarks
None
Example
uint8_t bssid[6];
DRV_WIFI_BssidGet(bssid);
5.1.13.7.1.2 DRV_WIFI_BssidSet Function
C
void DRV_WIFI_BssidSet(
uint8_t * p_bssid
);
Description
This sets 6 byte (48-bit) MAC address of the Access Point that is being scanned for. It is optional to use this. Where it is useful is
if there are two AP's with the same ID; the BSSID is used to connect to the specified AP. This setting can be used in lieu of the
SSID. Set each byte to 0xFF (default) if the BSSID is not being used. Not typically needed.
Preconditions
WiFi initialization must be complete.
Parameters
Parameters Description
p_context pointer to BSSID
Returns
None
Remarks
None
Example
uint8_t bssid[6];
bssid[0] = 0x00;
bssid[1] = 0xe8;
bssid[2] = 0xc0;
bssid[3] = 0x11;
bssid[4] = 0x22;
bssid[5] = 0x33;
DRV_WIFI_BssidSet(bssid);
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-614
5.1.13.7.1.3 DRV_WIFI_ChannelListGet Function
C
void DRV_WIFI_ChannelListGet(
uint8_t * p_channelList,
uint8_t * p_numChannels
);
Description
This function gets the current channel list.
Preconditions
WiFi initialization must be complete.
Parameters
Parameters Description
p_channelList pointer to where channel list will be written
numChannels pointer to where number of channels in the list will be written.
Returns
None
Remarks
None
Example
uint8_t channelList[DRV_WIFI_MAX_CHANNEL_LIST_LENGTH];
uint8_t numChannels;
DRV_WIFI_ChannelListGet(channelList, &numChannels);
5.1.13.7.1.4 DRV_WIFI_ChannelListSet Function
C
void DRV_WIFI_ChannelListSet(
uint8_t * p_channelList,
uint8_t numChannels
);
Description
This function sets the channel list that the MRF24WG will use when scanning or connecting.
Preconditions
WiFi initialization must be complete.
Parameters
Parameters Description
p_channelList list of channels
numChannels number of channels in list; if set to 0, then MRF24WG will set its channel list to all
valid channels in its regional domain.
Returns
None
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-615
Remarks
None
Example
uint8_t channelList[1,6,11];
DRV_WIFI_ChannelListSet(channelList, sizeof(channelList));
5.1.13.7.1.5 DRV_WIFI_ConnectContextGet Function
C
void DRV_WIFI_ConnectContextGet(
DRV_WIFI_CONNECTION_CONTEXT * p_ctx
);
Description
This function gets the current WiFi connection context.
Preconditions
WiFi initialization must be complete
Parameters
Parameters Description
p_ctx pointer to where connection context is written. See
DRV_WIFI_CONNECTION_CONTEXT structure.
Returns
None
Remarks
None
Example
DRV_WIFI_CONNECTION_CONTEXT ctx;
DRV_WIFI_ConnectContextGet(&ctx);
5.1.13.7.1.6 DRV_WIFI_ConnectionStateGet Function
C
void DRV_WIFI_ConnectionStateGet(
uint8_t * p_state
);
Description
This function gets the current WiFi connection state.
*p_state Description
DRV_WIFI_CSTATE_NOT_CONNECTED No WiFi connection exists
DRV_WIFI_CSTATE_CONNECTION_IN_PROGRESS WiFi connection in progress
DRV_WIFI_CSTATE_CONNECTED_INFRASTRUCTURE WiFi connected in infrastructure mode
DRV_WIFI_CSTATE_CONNECTED_ADHOC WiFi connected in adhoc mode
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-616
DRV_WIFI_CSTATE_RECONNECTION_IN_PROGRESS WiFi in process of reconnecting
DRV_WIFI_CSTATE_CONNECTION_PERMANENTLY_LOST WiFi connection permanently lost
Preconditions
WiFi initialization must be complete
Parameters
Parameters Description
p_state pointer to where state is written (see description)
Returns
None
Remarks
None
Example
uint8_t state;
DRV_WIFI_ConnectionStateGet(&state);
5.1.13.7.1.7 DRV_WIFI_DeviceInfoGet Function
C
void DRV_WIFI_DeviceInfoGet(
DRV_WIFI_DEVICE_INFO * p_deviceInfo
);
Description
This function retrieves MRF24WG device information. See DRV_WIFI_DEVICE_INFO structure.
Preconditions
WiFi initialization must be complete.
Parameters
Parameters Description
p_deviceInfo Pointer where device info will be written
Returns
None.
Remarks
None.
Example
DRV_WIFI_DEVICE_INFO info;
DRV_WIFI_DeviceInfoGet(&info);
5.1.13.7.1.8 DRV_WIFI_HWMulticastFilterGet Function
C
void DRV_WIFI_HWMulticastFilterGet(
uint8_t multicastFilterId,
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-617
uint8_t multicastAddress[6]
);
Description
Gets the current state of the specified Multicast Filter.
Preconditions
WiFi initialization must be complete.
Parameters
Parameters Description
multicastFilterId DRV_WIFI_MULTICAST_FILTER_1 or DRV_WIFI_MULTICAST_FILTER_2
multicastAddress pointer to where 6-byte multicast filter is written.
Returns
None.
Remarks
None.
Example
uint8_t filterAddress[6];
DRV_WIFI_HWMulticastFilterGet(DRV_WIFI_MULTICAST_FILTER_1, filterAddress);
5.1.13.7.1.9 DRV_WIFI_HWMulticastFilterSet Function
C
void DRV_WIFI_HWMulticastFilterSet(
uint8_t multicastFilterId,
uint8_t multicastAddress[6]
);
Description
This function allows the application to configure up to two hardware Multicast Address Filters on the MRF24W. If two active
multicast filters are set up they are OR’d together – the MRF24W will receive and pass to the Host CPU received packets from
either multicast address. The allowable values for the multicast filter are:
• DRV_WIFI_MULTICAST_FILTER_1
• DRV_WIFI_MULTICAST_FILTER_2
By default, both Multicast Filters are inactive.
Preconditions
WiFi initialization must be complete.
Parameters
Parameters Description
multicastFilterId DRV_WIFI_MULTICAST_FILTER_1 or DRV_WIFI_MULTICAST_FILTER_2
multicastAddress 6-byte address (all 0xFF will inactivate the filter)
Returns
None.
Remarks
Cannot mix hardware and software multicast filters.
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-618
Example
uint8_t multicastFilterId = DRV_WIFI_MULTICAST_FILTER_1;
uint8_t filterAddress[6] = {0x00 0x01, 0x5e, 0x11, 0x22, 0x33};
DRV_WIFI_HWMulticastFilterSet(multicastFilterId, filterAddress);
5.1.13.7.1.10 DRV_WIFI_MacAddressGet Function
C
void DRV_WIFI_MacAddressGet(
uint8_t * p_mac
);
Description
This function retrieves the MRF24WG MAC address.
Preconditions
WiFi initialization must be complete.
Parameters
Parameters Description
p_mac Pointer where mac address will be written (must point to a 6-byte buffer)
Returns
None.
Remarks
None.
Example
uint8_t mac[6];
DRV_WIFI_MacAddressGet(mac);
5.1.13.7.1.11 DRV_WIFI_MacAddressSet Function
C
void DRV_WIFI_MacAddressSet(
uint8_t * p_mac
);
Description
Directs the MRF24W to use the input MAC address instead of its factory-default MAC address. This function does not overwrite
the factory default, which is in FLASH memory.
Preconditions
WiFi initialization must be complete. Cannot be called when the MRF24W is in a connected state.
Parameters
Parameters Description
p_mac Pointer to 6-byte MAC that will be sent to MRF24WG
Returns
None.
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-619
Remarks
None.
Example
uint8_t mac[6] = {0x00, 0x1e, 0xc0, 0x11, 0x22, 0x33};
DRV_WIFI_MacAddressSet(mac);
5.1.13.7.1.12 DRV_WIFI_MacStatsGet Function
C
void DRV_WIFI_MacStatsGet(
DRV_WIFI_MAC_STATS * p_macStats
);
Description
This function gets the various MAC layer stats as maintained by the MRF24WG.
Preconditions
WiFi initialization must be complete.
Parameters
Parameters Description
p_macStats Pointer to where MAC statistics are written. See DRV_WIFI_MAC_STATS
structure.
Returns
None.
Remarks
None.
Example
DRV_WIFI_MAC_STATS macStats;
DRV_WIFI_MacStatsGet(&macStats);
5.1.13.7.1.13 DRV_WIFI_NetworkTypeGet Function
C
void DRV_WIFI_NetworkTypeGet(
uint8_t * p_networkType
);
Description
This function gets the WiFi network type.
Preconditions
WiFi initialization must be complete.
Parameters
Parameters Description
p_networkType Pointer to where the network type will be written.
One of the following DRV_WIFI_NETWORK_TYPE_INFRASTRUCTURE
DRV_WIFI_NETWORK_TYPE_ADHOC
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-620
DRV_WIFI_NETWORK_TYPE_P2P not supported DRV_WIFI_NETWORK_TYPE_SOFT_AP
Returns
None
Remarks
None
Example
uint8_t networkType;
DRV_WIFI_NetworkTypeGet(&networkType);
5.1.13.7.1.14 DRV_WIFI_NetworkTypeSet Function
C
void DRV_WIFI_NetworkTypeSet(
uint8_t networkType
);
Description
This function selects the WiFi network type.
Preconditions
WiFi initialization must be complete.
Parameters
Parameters Description
networkType One of the following: DRV_WIFI_NETWORK_TYPE_INFRASTRUCTURE
DRV_WIFI_NETWORK_TYPE_ADHOC
DRV_WIFI_NETWORK_TYPE_P2P not supported DRV_WIFI_NETWORK_TYPE_SOFT_AP
Returns
None
Remarks
None
Example
DRV_WIFI_NetworkTypeSet(DRV_WIFI_NETWORK_TYPE_INFRASTRUCTURE);
5.1.13.7.1.15 DRV_WIFI_PowerSaveStateGet Function
C
void DRV_WIFI_PowerSaveStateGet(
uint8_t * p_powerSaveState
);
Description
This function gets the current MRF24WG power save state.
powerSaveState Definition
DRV_WIFI_PS_HIBERNATE MRF24W in hibernate state
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-621
DRV_WIFI_PS_PS_POLL_DTIM_ENABLED MRF24W in PS-Poll mode with DTIM enabled
DRV_WIFI_PS_PS_POLL_DTIM_DISABLED MRF24W in PS-Poll mode with DTIM disabled
DRV_WIFI_PS_POLL_OFF MRF24W is not in any power-save state
Preconditions
WiFi initialization must be complete.
Parameters
Parameters Description
p_powerSaveState Pointer to where power state is written (see description)
Returns
None.
Remarks
None.
Example
uint8_t state;
DRV_WIFI_PowerSaveStateGet(&state);
5.1.13.7.1.16 DRV_WIFI_ReconnectModeGet Function
C
void DRV_WIFI_ReconnectModeGet(
uint8_t * p_retryCount,
uint8_t * p_deauthAction,
uint8_t * p_beaconTimeout,
uint8_t * p_beaconTimeoutAction
);
Description
This function gets the reconnection mode parameters set in DRV_WIFI_ReconnectModeGet().
Preconditions
WiFi initialization must be complete.
Parameters
Parameters Description
p_retryCount Pointer where retry count is written
p_deauthAction Pointer where deauth action is written
p_beaconTimeout Pointer where beacon timeout is written
p_beaconTimeoutAction Pointer where beacon timeout action is written.
Returns
None
Remarks
None
Example
uint8_t retryCount, deauthAction, beaconTimeout, beaconTimeoutAction;
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-622
DRV_WIFI_ReconnectModeGet(&retryCount,
&deauthAction,
&beaconTimeout,
&beaconTimeoutAction);
5.1.13.7.1.17 DRV_WIFI_ReconnectModeSet Function
C
void DRV_WIFI_ReconnectModeSet(
uint8_t retryCount,
uint8_t deauthAction,
uint8_t beaconTimeout,
uint8_t beaconTimeoutAction
);
Description
This function controls how the MRF24WG behaves when an existing WiFi connection is lost. The MRF24WG can lose an
existing connection in one of two ways: 1) Beacon timeout 2) Deauth received from AP
There are two options with respect to regaining a lost WiFi connection: 1) MRF24WG informs the host that the connection was
temporarily lost and then the MRF24WG retries N times (or forever) to regain the connection. 2) MRF24WG simply informs the
host application that the connection is lost, and it is up to the host to regain the connection via the API.
Preconditions
WiFi initialization must be complete.
Parameters
Parameters Description
retryCount Number of times the MRF24WG should try to regain the connection (see
description)
deauthAction In the event of a deauth from the AP, the action the MRF24WG should take (see
description)
beaconTimeout Number of missed beacons before the MRF24WG designates the connection as
lost (see description)
beaconTimeoutAction In the event of a beacon timeout, the action the MRF24WG should take (see
description)
Returns
None
Remarks
The retryCount parameter also applies when initially connecting. That is, the retryCount tells the MRF24WG how many time to
try to connect to a WiFi network before giving up and generating the DRV_WIFI_EVENT_CONNECTION_FAILED event.
'retryCount'
field
Description
0 Do not try to regain a connection (simply report event to host)
1:254 Number of times MRF24WG should try to regain the connection
255 MRF24WG will retry forever (do not use for AdHoc connections)
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-623
'deauthAction' field Description
DRV_WIFI_DO_NOT_ATTEMPT_TO_RECONNECT Do not attempt to reconnect after a deauth
DRV_WIFI_ATTEMPT_TO_RECONNECT Attempt to reconnect after a deauth
'beaconTimeout'
field
Description
0 MRF24WG will not monitor the beacon timeout condition
1:255 Number of missed beacons before designating the connection as lost.
'beaconTimeoutAction' field Description
DRV_WIFI_DO_NOT_ATTEMPT_TO_RECONNECT Do not attempt to reconnect after a beacon timeout
DRV_WIFI_ATTEMPT_TO_RECONNECT Attempt to reconnect after a beacon timeout
None
Example
// Example 1: MRF24WG should retry forever if either a deauth or beacon
// timeout occurs (beacon timeout is 3 beacon periods).
DRV_WIFI_ReconnectModeSet(WF_RETRY_FOREVER,
WF_ATTEMPT_TO_RECONNECT,
3,
WF_ATTEMPT_TO_RECONNECT);
// Example 2: MRF24WG should not do any connection retries and only report
// deauth events to the host.
DRV_WIFI_ReconnectModeSet(0,
WF_DO_NOT_ATTEMPT_TO_RECONNECT,
0,
WF_DO_NOT_ATTEMPT_TO_RECONNECT);
// Example 3: MRF24WG should not do any connection retries, but report deauth
// and beacon timeout events to host. Beacon timeout should be 5 beacon periods.
DRV_WIFI_ReconnectModeSet(0,
WF_DO_NOT_ATTEMPT_TO_RECONNECT,
5,
WF_DO_NOT_ATTEMPT_TO_RECONNECT);
// Example 4: MRF24WG should ignore beacon timeouts, but attempt to
// reconnect 3 times if a deauth occurs.
DRV_WIFI_ReconnectModeSet(3,
WF_ATTEMPT_TO_RECONNECT,
0,
WF_DO_NOT_ATTEMPT_TO_RECONNECT);
5.1.13.7.1.18 DRV_WIFI_RegionalDomainGet Function
C
void DRV_WIFI_RegionalDomainGet(
uint8_t * p_regionalDomain
);
Description
Gets the regional domain on the MRF24W. Values are:
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-624
• DRV_WIFI_DOMAIN_FCC
• DRV_WIFI_DOMAIN_ETSI
• DRV_WIFI_DOMAIN_JAPAN
• DRV_WIFI_DOMAIN_OTHER
Preconditions
WiFi initialization must be complete.
Parameters
Parameters Description
p_regionalDomain Pointer where the regional domain value will be written
Returns
None.
Remarks
None.
Example
uint8_t domain;
DRV_WIFI_RegionalDomainGet(&domain);
5.1.13.7.1.19 DRV_WIFI_RtsThresholdGet Function
C
void DRV_WIFI_RtsThresholdGet(
uint16_t * p_rtsThreshold
);
Description
Gets the RTS/CTS packet size threshold.
Preconditions
WiFi initialization must be complete.
Parameters
Parameters Description
p_rtsThreshold Pointer to where RTS threshold is written
Returns
None.
Remarks
None.
Example
uint16_t threshold;
DRV_WIFI_RtsThresholdGet(&threshold);
5.1.13.7.1.20 DRV_WIFI_RtsThresholdSet Function
C
void DRV_WIFI_RtsThresholdSet(
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-625
uint16_t rtsThreshold
);
Description
Sets the RTS/CTS packet size threshold for when RTS/CTS frame will be sent. The default is 2347 bytes – the maximum for
802.11. It is recommended that the user leave the default at 2347 until they understand the performance and power ramifications
of setting it smaller. Valid values are from 0 to DRV_WIFI_RTS_THRESHOLD_MAX (2347).
Preconditions
WiFi initialization must be complete.
Parameters
Parameters Description
rtsThreshold Value of the packet size threshold
Returns
None.
Remarks
None.
Example
DRV_WIFI_RtsThresholdSet(DRV_WIFI_RTS_THRESHOLD_MAX);
5.1.13.7.1.21 DRV_WIFI_ScanContextGet Function
C
void DRV_WIFI_ScanContextGet(
DRV_WIFI_SCAN_CONTEXT * p_context
);
Description
This function gets the WiFi scan context.
Preconditions
WiFi initialization must be complete.
Parameters
Parameters Description
p_context Pointer to where scan context will be written. See DRV_WIFI_SCAN_CONTEXT
structure.
Returns
None.
Remarks
None.
Example
DRV_WIFI_SCAN_CONTEXT context;
DRV_WIFI_ScanContextSet(&context);
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-626
5.1.13.7.1.22 DRV_WIFI_ScanContextSet Function
C
void DRV_WIFI_ScanContextSet(
DRV_WIFI_SCAN_CONTEXT * p_context
);
Description
This function sets the WiFi scan context. The MRF24WG defaults are fine for most applications, but they can be changed by this
function.
Preconditions
WiFi initialization must be complete.
Parameters
Parameters Description
p_context Pointer to scan context. See DRV_WIFI_SCAN_CONTEXT structure.
Returns
None.
Remarks
None.
Example
DRV_WIFI_SCAN_CONTEXT context;
context.scantype = DRV_WIFI_ACTIVE_SCAN;
context.scanCount = 1;
context.minChannelTime = 200; // ms
context.maxChannelTime = 400; // ms
context.probeDelay = 20; // uS
DRV_WIFI_ScanContextSet(&context);
5.1.13.7.1.23 DRV_WIFI_SecurityGet Function
C
void DRV_WIFI_SecurityGet(
uint8_t * p_securityType,
uint8_t * p_securityKey,
uint8_t * p_securityKeyLength
);
Description
This function gets the current WiFi security setting.
'securityType' Field Key Length
DRV_WIFI_SECURITY_OPEN N/A N/A
DRV_WIFI_SECURITY_WEP_40 binary 4 keys, 5 bytes each (total of 20 bytes)
DRV_WIFI_SECURITY_WEP_104 binary 4 keys, 13 bytes each (total of 52 bytes)
DRV_WIFI_SECURITY_WPA_WITH_KEY binary 32 bytes
DRV_WIFI_SECURITY_WPA_WITH_PASS_PHRASE ascii 8-63 ascii characters
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-627
DRV_WIFI_SECURITY_WPA2_WITH_KEY binary 32 bytes
DRV_WIFI_SECURITY_WPA2_WITH_PASS_PHRASE ascii 8-63 ascii characters
DRV_WIFI_SECURITY_WPA_AUTO_WITH_KEY binary 32 bytes
DRV_WIFI_SECURITY_WPA_AUTO_WITH_PASS_PHRASE ascii 8-63 ascii characters
Preconditions
WiFi initialization must be complete.
Parameters
Parameters Description
p_securityType Value corresponding to the security type desired (see description)
p_securityKey Binary key or passphrase (not used if security is DRV_WIFI_SECURITY_OPEN)
p_securityKeyLength Number of bytes in p_securityKey (not used if security is
DRV_WIFI_SECURITY_OPEN)
Returns
None.
Remarks
If security was initially set with a passphrase that the MRF24WG used to generate a binary key, this function returns the binary
key, not the passphrase.
Example
uint8_t securityType;
uint8_t securityKey[DRV_WIFI_MAX_SECURITY_KEY_LENGTH];
uint8_t keyLength;
DRV_WIFI_SecurityGet(&securityType, securityKey, &keyLength);
5.1.13.7.1.24 DRV_WIFI_SecurityOpenSet Function
C
void DRV_WIFI_SecurityOpenSet();
Description
This function sets the WiFi security to open. One can only connect to an AP that is running in open mode.
Preconditions
WiFi initialization must be complete. Must be in an unconnected state.
Returns
None
Remarks
None
Example
DRV_WIFI_SecurityOpenSet();
5.1.13.7.1.25 DRV_WIFI_SecurityWepSet Function
C
void DRV_WIFI_SecurityWepSet(
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-628
DRV_WIFI_WEP_CONTEXT* p_context
);
Description
This function sets the WiFi security to WEP. One can only connect to an AP that is running the same WEP mode.
Preconditions
WiFi initialization must be complete. Must be in an unconnected state.
Parameters
Parameters Description
p_context desired WEP context. See DRV_WIFI_WEP_CONTEXT structure.
Returns
None
Remarks
None
Example
DRV_WIFI_WEP_CONTEXT context;
context.wepSecurityType = DRV_WIFI_SECURITY_WEP_40;
context.wepKey[] = {0x5a, 0xfb, 0x6c, 0x8e, 0x77,
0xc1, 0x04, 0x49, 0xfd, 0x4e,
0x43, 0x18, 0x2b, 0x33, 0x88,
0xb0, 0x73, 0x69, 0xf4, 0x78};
context.wepKeyLength = 20;
context.wepKeyType = DRV_WIFI_SECURITY_WEP_OPENKEY;
DRV_WIFI_SecurityOpenSet(&context);
5.1.13.7.1.26 DRV_WIFI_SecurityWpaSet Function
C
void DRV_WIFI_SecurityWpaSet(
DRV_WIFI_WPA_CONTEXT* p_context
);
Description
This function sets the WiFi security to WPA or WPA2. One can only connect to an AP that is running the same WPA mode.
Preconditions
WiFi initialization must be complete. Must be in an unconnected state.
Parameters
Parameters Description
p_context desired WPA context. See DRV_WIFI_WPA_CONTEXT structure.
Returns
None
Remarks
None
Example
DRV_WIFI_WPA_CONTEXT context;
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-629
context.wpaSecurityType = DRV_WIFI_SECURITY_WPA2_WITH_PASS_PHRASE;
context.keyInfo.key[] = "MySecretWPA2PassPhrase";
context.keyInfo.keyLenth = strlen(context.keyInfo.key);
DRV_WIFI_SecurityWpaSet(&context);
5.1.13.7.1.27 DRV_WIFI_SecurityWpsSet Function
C
void DRV_WIFI_SecurityWpsSet(
DRV_WIFI_WPS_CONTEXT * p_context
);
Description
This function sets the WiFi security to WPS. One can only connect to an AP that supports WPS.
Preconditions
WiFi initialization must be complete. Must be in an unconnected state.
Parameters
Parameters Description
p_context desired WPA context. See DRV_WIFI_WPS_CONTEXT structure.
Returns
None
Remarks
None
Example
DRV_WIFI_WPS_CONTEXT context;
uint8_t wpsPin[8] = {1, 2, 3, 9, 0, 2, 1, 2};
context.wpsSecurityType = DRV_WIFI_SECURITY_WPS_PUSH_BUTTON;
memcpy(context.wpsPin, wpsPin, sizeof(wpsPin));
context.wpsPinLength = 8;
DRV_WIFI_SecurityWpsSet(&context);
5.1.13.7.1.28 DRV_WIFI_SoftApEventInfoGet Function
C
DRV_WIFI_MGMT_INDICATE_SOFT_AP_EVENT * DRV_WIFI_SoftApEventInfoGet();
Description
This function retrieves the additional event info after a Soft AP event has occurred.
Preconditions
Soft AP event must have occurred
Returns
None.
Remarks
None.
Example
DRV_WIFI_MGMT_INDICATE_SOFT_AP_EVENT info;;
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-630
DRV_WIFI_WPSCredentialsGet(&info);
5.1.13.7.1.29 DRV_WIFI_SsidGet Function
C
void DRV_WIFI_SsidGet(
uint8_t * p_ssid,
uint8_t * p_ssidLength
);
Description
Gets the SSID and SSID Length.
Preconditions
WiFi initialization must be complete.
Parameters
Parameters Description
p_ssid Pointer to buffer where SSID will be written
ssidLength number of bytes in SSID
Returns
None
Remarks
None
Example
uint8_t ssid[DRV_WIFI_MAX_SSID_LENGTH];
uint8_t ssidLength;
DRV_WIFI_SsidGet(ssid, &ssidLength);
5.1.13.7.1.30 DRV_WIFI_SsidSet Function
C
void DRV_WIFI_SsidSet(
uint8_t * p_ssid,
uint8_t ssidLength
);
Description
Sets the SSID and SSID Length. Note that an Access Point can have either a visible or hidden SSID. If an Access Point uses a
hidden SSID then an active scan must be used.
Preconditions
WiFi initialization must be complete.
Parameters
Parameters Description
p_ssid Pointer to SSID buffer
ssidLength number of bytes in SSID
Returns
None
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-631
Remarks
Do not include a string terminator in the SSID length. SSID's are case- sensitive. SSID length must be less than or equal to
DRV_WIFI_MAX_SSID_LENGTH.
Example
uint8_t ssid[] = "MySSIDName";
uint8_t ssidLength = strlen(ssid);
DRV_WIFI_SsidSet(ssid, ssidLength);
5.1.13.7.1.31 DRV_WIFI_SWMulticastFilterSet Function
C
void DRV_WIFI_SWMulticastFilterSet(
DRV_WIFI_SWMULTICAST_CONFIG * p_config
);
Description
This function allows the application to configure up to two Multicast Address Filters on the MRF24W. If two active multicast filters
are set up they are OR’d together – the MRF24W will receive and pass to the Host CPU received packets from either multicast
address. The allowable values in p_config are:
filterId -- DRV_WIFI_MULTICAST_FILTER_1 thru DRV_WIFI_MULTICAST_FILTER_16
action -- DRV_WIFI_MULTICAST_DISABLE_ALL (default) The Multicast Filter discards all received multicast messages – they
will not be forwarded to the Host PIC. The remaining fields in this structure are ignored.
DRV_WIFI_MULTICAST_ENABLE_ALL The Multicast Filter forwards all received multicast messages to the Host PIC. The
remaining fields in this structure are ignored.
DRV_WIFI_MULTICAST_USE_FILTERS The MAC filter will be used and the remaining fields in this structure configure which
Multicast messages are forwarded to the Host PIC.
macBytes -- Array containing the MAC address to filter on (using the destination address of each incoming 802.11 frame).
Specific bytes with the MAC address can be designated as ‘don’t care’ bytes. See macBitMask. This field in only used if action =
DRV_WIFI_MULTICAST_USE_FILTERS.
macBitMask -- A byte where bits 5:0 correspond to macBytes[5:0]. If the bit is zero then the corresponding MAC byte must be an
exact match for the frame to be forwarded to the Host PIC. If the bit is one then the corresponding MAC byte is a ‘don’t care’ and
not used in the Multicast filtering process. This field in only used if action = DRV_WIFI_MULTICAST_USE_FILTERS.
Preconditions
WiFi initialization must be complete. DRV_WIFI_SWMultiCastFilterEnable() must have been called previously.
Returns
None.
Remarks
Cannot mix hardware and software multicast filters..
Example
DRV_WIFI_SWMULTICAST_CONFIG config;
uint8_t macMask[] = {01, 00, 5e, ff, ff, ff}; // (0xff are the don't care bytes)
// configure software multicast filter 1 to filter multicast addresses that
// start with 01:00:5e
config.action = DRV_WIFI_MULTICAST_USE_FILTERS;
config->filterId = DRV_WIFI_MULTICAST_FILTER_1;
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-632
memcpy(config->macBytes, macMask, 6);
config->macBitMask = 0x38; // bits 5:3 = 1 (don't care on bytes 3,4,5)
// bits 2:0 = 0 (exact match required on bytes
0,1,2)
5.1.13.7.1.32 DRV_WIFI_TxModeGet Function
C
void DRV_WIFI_TxModeGet(
uint8_t * p_mode
);
Description
This function gets the MRF24WG Tx mode.
Preconditions
WiFi initialization must be complete
Returns
None.
Remarks
None.
Example
uint8_t mode;
DRV_WIFI_TxModeGet(&mode);
5.1.13.7.1.33 DRV_WIFI_TxModeSet Function
C
void DRV_WIFI_TxModeSet(
uint8_t mode
);
Description
This function sets the MRF24WG Tx mode.
mode Description
DRV_WIFI_TXMODE_G_RATES Use all 802.11g rates (default)
DRV_WIFI_TXMODE_B_RATES Use only 802.11b rates
DRV_WIFI_TXMODE_LEGACY_RATES Use only 1 and 2 mbps rates
Preconditions
WiFi initialization must be complete
Parameters
Parameters Description
mode Tx mode value (see description)
Returns
None.
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-633
Remarks
None.
Example
DRV_WIFI_TxModeSet(DRV_WIFI_TXMODE_G_RATES);
5.1.13.7.1.34 DRV_WIFI_TxPowerFactoryMaxGet Function
C
void DRV_WIFI_TxPowerFactoryMaxGet(
int8_t * p_factoryMaxTxPower
);
Description
This function retrieves the factory-set max tx power from the MRF24WG.
Preconditions
WiFi initialization must be complete.
Parameters
Parameters Description
p_factoryMaxTxPower pointer to where factory max power is written (dbM)
Returns
None.
Remarks
None.
Example
int8_t maxPower;
DRV_WIFI_TxPowerFactoryMaxGet(&maxPower);
5.1.13.7.1.35 DRV_WIFI_TxPowerMaxGet Function
C
void DRV_WIFI_TxPowerMaxGet(
int8_t * p_maxTxPower
);
Description
Gets the Tx max power setting from the MRF24WG.
Preconditions
WiFi initialization must be complete.
Parameters
Parameters Description
p_maxTxPower pointer to where max power setting is written (dBm).
Returns
None.
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-634
Remarks
None
Example
int8_t maxPower;
DRV_WIFI_TxPowerMaxGet(&maxPower);
5.1.13.7.1.36 DRV_WIFI_TxPowerMaxSet Function
C
void DRV_WIFI_TxPowerMaxSet(
int8_t maxTxPower
);
Description
After initialization the MRF24WG0M max Tx power is determined by a factory-set value. This function can set a different
maximum Tx power levels. However, this function can never set a maximum Tx power greater than the factory-set value, which
can be read via DRV_WIFI_TxPowerFactoryMaxGet().
Preconditions
WiFi initialization must be complete.
Parameters
Parameters Description
maxTxPower valid range (0 to 17 dBm)
Returns
None.
Remarks
No conversion of units needed, input to MRF24WG0M is in dBm.
Example
DRV_WIFI_TxPowerMaxSet(8); // set max Tx power to 8dBm
5.1.13.7.1.37 DRV_WIFI_WepKeyTypeGet Function
C
void DRV_WIFI_WepKeyTypeGet(
uint8_t * p_wepKeyType
);
Description
This function gets the WEP key type:
• DRV_WIFI_SECURITY_WEP_SHAREDKEY
• DRV_WIFI_SECURITY_WEP_OPENKEY
Preconditions
WiFi initialization must be complete.
Returns
None.
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-635
Remarks
None.
Example
uint8_t wepKeyType;
DRV_WIFI_WepKeyTypeGet(&wepKeyType);
5.1.13.7.1.38 DRV_WIFI_WPSCredentialsGet Function
C
void DRV_WIFI_WPSCredentialsGet(
DRV_WIFI_WPS_CREDENTIAL * p_cred
);
Description
This function gets the WPS credentials from the MRF24WG
Preconditions
WiFi initialization must be complete.
Returns
None.
Remarks
None.
Example
DRV_WIFI_WPS_CREDENTIAL cred;;
DRV_WIFI_WPSCredentialsGet(&cred);
5.1.13.7.1.39 DRV_WIFI_AdhocContextSet Function
C
void DRV_WIFI_AdhocContextSet(
DRV_WIFI_ADHOC_NETWORK_CONTEXT * p_context
);
Description
This function sets the AdHoc context. It is only applicable when the DRV_WIFI_NETWORK_TYPE_ADHOC has been selected
in DRV_WIFI_NetworkTypeSet().
Preconditions
WiFi initialization must be complete.
Parameters
Parameters Description
p_context pointer to AdHoc context data; see definition for the
DRV_WIFI_ADHOC_NETWORK_CONTEXT structure.
Returns
None
Remarks
None
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-636
Example
DRV_WIFI_ADHOC_NETWORK_CONTEXT adHocContext;
adHocContext.mode = DRV_WIFI_ADHOC_CONNECT_THEN_START;
adHocContext.hiddenSsid = false;
adHocContext.beaconPeriod = DRV_WIFI_DEFAULT_ADHOC_BEACON_PERIOD;
DRV_WIFI_AdhocContextSet(&adHocContext);
5.1.13.7.1.40 DRV_WIFI_RssiGet Function
C
void DRV_WIFI_RssiGet(
uint8_t * p_rssi
);
Description
This function retrieves the value set in Gets RSSI value set in DRV_WIFI_RssiSet(). It does not retrieve the current connection
RSSI value. The scan result will yield the current RSSI.
Preconditions
WiFi initialization must be complete
Parameters
Parameters Description
p_rssi pointer where rssi value is written
Returns
None
Remarks
None
Example
uint8_t rssi;
DRV_WIFI_RssiGet(&rssi);
5.1.13.7.1.41 DRV_WIFI_RssiSet Function
C
void DRV_WIFI_RssiSet(
uint8_t rssi
);
Description
This setting is only used if: 1) Neither an SSID or BSSID has been configured or 2) An SSID is defined and multiple AP's are
discovered with the same SSID
rssi Description
0 Connect to first network found
1-254 Only connect to network if the RSSI is greater or equal to this value
255 Connect to the highest RSSI found (default)
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-637
Preconditions
WiFi initialization must be complete
Parameters
Parameters Description
rssi See description
Returns
None
Remarks
Rarely needed
Example
DRV_WIFI_RssiSet(255);
5.1.13.7.1.42 DRV_WIFI_GratuitousArpStart Function
C
void DRV_WIFI_GratuitousArpStart(
uint8_t period
);
Description
This function starts a gratuitous ARP response to be periodically transmitted.
Preconditions
WiFi initialization must be complete. Connection process must be complete.
Parameters
Parameters Description
period period between gratuitous ARP, in seconds
Returns
None.
Remarks
None.
Example
DRV_WIFI_GratuitousArpStart(10); // begin sending gratuitous ARP's every
// 10 seconds.
5.1.13.7.1.43 DRV_WIFI_GratuitousArpStop Function
C
void DRV_WIFI_GratuitousArpStop();
Description
This function stops a gratuitous ARP.
Preconditions
WiFi initialization must be complete.
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-638
Returns
None.
Remarks
None.
Example
DRV_WIFI_GratuitousArpStop();
5.1.13.7.1.44 DRV_WIFI_HibernateEnable Function
C
void DRV_WIFI_HibernateEnable();
Description
Enables Hibernate mode on the MRF24W, which effectively turns off the device for maximum power savings.
MRF24W state is not maintained when it transitions to hibernate mode.
Preconditions
WiFi initialization must be complete.
Returns
None.
Remarks
None
Example
DRV_WIFI_HibernateEnable();
5.1.13.7.1.45 DRV_WIFI_isHibernateEnable Function
C
bool DRV_WIFI_isHibernateEnable();
Description
Checks if MRF24W is in hibernate mode
Preconditions
WiFi initialization must be complete.
Returns
true or false
Remarks
None
Example
bool flag;
flag = DRV_WIFI_isHibernateEnable();
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-639
5.1.13.7.1.46 DRV_WIFI_PsPollDisable Function
C
void DRV_WIFI_PsPollDisable();
Description
Disables PS Poll mode. The MRF24W will stay active and not go sleep.
Preconditions
WiFi initialization must be complete.
Returns
None.
Remarks
None.
Example
DRV_WIFI_PsPollDisable(&context);
5.1.13.7.1.47 DRV_WIFI_PsPollEnable Function
C
void DRV_WIFI_PsPollEnable(
DRV_WIFI_PS_POLL_CONTEXT * p_context
);
Description
Enables PS Poll mode. PS-Poll (Power-Save Poll) is a mode allowing for longer battery life. The MRF24W coordinates with the
Access Point to go to sleep and wake up at periodic intervals to check for data messages, which the Access Point will buffer.
The listenInterval in the Connection Algorithm defines the sleep interval. By default, PS-Poll mode is disabled.
When PS Poll is enabled, the WF Host Driver will automatically force the MRF24W to wake up each time the Host sends Tx data
or a control message to the MRF24W. When the Host message transaction is complete the MRF24W driver will automatically
re-enable PS Poll mode.
When the application is likely to experience a high volume of data traffic then PS-Poll mode should be disabled for two reasons:
1. No power savings will be realized in the presence of heavy data traffic.
2. Performance will be impacted adversely as the WiFi Host Driver continually activates and deactivates PS-Poll mode via SPI
messages.
Preconditions
WiFi initialization must be complete.
Parameters
Parameters Description
p_context Pointer to ps poll context. See DRV_WIFI_PS_POLL_CONTEXT structure.
Returns
None.
Remarks
None.
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-640
Example
DRV_WIFI_PS_POLL_CONTEXT context;
context.listenInterval = DRV_WIFI_DEFAULT_PS_LISTEN_INTERVAL;
context.dtimInterval = DRV_WIFI_DEFAULT_PS_DTIM_INTERVAL;
context.useDtim = DRV_WIFI_DEFAULT_PS_DTIM_ENABLED;
DRV_WIFI_PsPollEnable(&context);
5.1.13.7.2 System Configuration Functions
5.1.13.7.2.1 DRV_WIFI_Connect Function
C
void DRV_WIFI_Connect();
Description
This function causes the MRF24WG to connect to a WiFi network. Upon connection, or a failure to connect, an event will be
generated.
Preconditions
WiFi initialization must be complete and relevant connection parameters must have been set.
Returns
None
Remarks
None
Example
DRV_WIFI_Connect();
5.1.13.7.2.2 DRV_WIFI_Deinitialize Function
C
bool DRV_WIFI_Deinitialize();
Description
This function deinitializes the MRF24WG driver. It also saves the WiFi parameters in non-volatile storage.
Preconditions
None.
Returns
If successful returns true, else false.
Remarks
None
5.1.13.7.2.3 DRV_WIFI_Disconnect Function
C
uint16_t DRV_WIFI_Disconnect();
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-641
Description
This function causes the MRF24WG to disconnect from a WiFi network. No event is generated when a connection is terminated
via the function call.
Preconditions
WiFi initialization must be complete and a connection must be in progress.
Returns
DRV_WIFI_SUCCESS or DRV_WIFI_ERROR_DISCONNECT_FAILED
Remarks
None
Example
DRV_WIFI_Disconnect();
5.1.13.7.2.4 DRV_WIFI_Initialize Function
C
bool DRV_WIFI_Initialize(
void* pNetIf
);
Description
Initialization Functions
-----------------------
***************************************************************************
This function initializes the MRF24WG driver, making it ready for clients to use.
Preconditions
None.
Parameters
Parameters Description
pNetIf Pointer to network interface
Returns
If successful returns true, else false.
Remarks
This function must be called before any other WiFi routine is called. Currently, this function performs no work, but that may
change in the future. The WiFi initialization takes place in a state machine called by MRF24W_MACInit().
5.1.13.7.2.5 DRV_WIFI_Scan Function
C
uint16_t DRV_WIFI_Scan(
bool scanAll
);
Description
Directs the MRF24W to initiate a scan operation. The Host Application will be notified that the scan results are ready when it
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-642
receives the WF_EVENT_SCAN_RESULTS_READY event. The eventInfo field for this event will contain the number of scan
results. Once the scan results are ready they can be retrieved with DRV_WIFI_ScanGetResult().
Scan results are retained on the MRF24W until:
1. Calling DRV_WIFI_Scan() again (after scan results returned from previous call).
2. MRF24W reset.
Preconditions
WiFi initialization must be complete.
Parameters
Parameters Description
5.1.13.7.3 Miscellaneous Functions
5.1.13.7.3.1 DRV_WIFI_ConfigDataErase Function
C
bool DRV_WIFI_ConfigDataErase();
Description
This function erases configuration data from the board EEPROM.
Preconditions
TCPIP stack should be initialized.
Returns
None
Remarks
None.
5.1.13.7.3.2 DRV_WIFI_ConfigDataLoad Function
C
bool DRV_WIFI_ConfigDataLoad();
Description
This function loads configuration data from the board EEPROM. If not present or corrupted then default values will be used.
Preconditions
TCPIP stack should be initialized.
Returns
None
Remarks
None.
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-643
5.1.13.7.3.3 DRV_WIFI_ConfigDataPrint Function
C
void DRV_WIFI_ConfigDataPrint();
Description
This function outputs configuration data from the board EEPROM.
Preconditions
TCPIP stack should be initialized.
Returns
None
Remarks
None.
5.1.13.7.3.4 DRV_WIFI_ConfigDataSave Function
C
bool DRV_WIFI_ConfigDataSave();
Description
This function saves configuration data to the board EEPROM.
Preconditions
TCPIP stack should be initialized.
Returns
None
Remarks
None.
5.1.13.7.3.5 DRV_WIFI_ProcessEvent Function
C
void DRV_WIFI_ProcessEvent(
uint16_t event,
uint16_t eventInfo
);
Description
This function is called to process a WiFi event,
Preconditions
TCPIP stack should be initialized.
Parameters
Parameters Description
event event code
eventInfo additional information about the event. Not all events have associated info, in
which case this value will be set to DRV_WIFI_NO_ADDITIONAL_INFO (0xff)
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-644
Returns
None
Remarks
None.
5.1.13.7.3.6 DRV_WIFI_ScanGetResult Function
C
void DRV_WIFI_ScanGetResult(
uint8_t listIndex,
DRV_WIFI_SCAN_RESULT * p_scanResult
);
Description
After a scan has completed this function is used to read one scan result at a time from the MRF24WG.
Preconditions
WiFi initialization must be complete. WF_EVENT_SCAN_RESULTS_READY event must have already occurrerd.
Parameters
Parameters Description
listIndex Index (0-based list) of the scan entry to retrieve.
p_scanResult Pointer to where scan result is written. See DRV_WIFI_SCAN_RESULT structure.
Returns
None.
Remarks
None.
Example
DRV_WIFI_SCAN_RESULT scanResult;
DRV_WIFI_ScanGetResult(0, &scanResult); // get first scan result in list
5.1.13.7.3.7 DRV_WIFI_SetLinkDownThreshold Function
C
void DRV_WIFI_SetLinkDownThreshold(
uint8_t threshold
);
Description
This function allows the application to set the number of MRF24W consecutive Tx failures before the connection failure event
(DRV_WIFI_LINK_LOST) is reported to the host application.
Preconditions
WiFi initialization must be complete
Parameters
Parameters Description
threshold -- 0 disabled (default)
1-255 number of consecutive Tx failures before connection failure event is reported
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-645
Returns
None.
Remarks
None.
Example
DRV_WIFI_SetLinkDownThreshold(0); // disable link down threshold
5.1.13.7.3.8 DRV_WIFI_SetPSK Function
C
void DRV_WIFI_SetPSK(
uint8_t * p_psk
);
Description
This function is used in conjunction with DRV_WIFI_YieldPassphraseToHost(). It sends the binary key to the MRF24WG after
the host has converted an ASCII passphrase to a binary key.
Preconditions
WiFi initialization must be complete.
Parameters
Parameters Description
p_psk pointer to the binary key
Returns
None.
Remarks
None.
Example
DRV_WIFI_YieldPassphraseToHost(&info);
5.1.13.7.3.9 DRV_WIFI_SWMultiCastFilterEnable Function
C
void DRV_WIFI_SWMultiCastFilterEnable();
Description
This function allows the application to configure up to max 16 software multicast address Filters on the MRF24WG0MA/B.
Preconditions
WiFi initialization must be complete.
Returns
None.
Remarks
Cannot mix hardware and software multicast filters..
Example
DRV_WIFI_SWMultiCastFilterEnable();
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-646
5.1.13.7.3.10 DRV_WIFI_YieldPassphraseToHost Function
C
void DRV_WIFI_YieldPassphraseToHost();
Description
During WPS the MRF24WG will receive a passphrase. That passphrase must be converted to a binary key. The MRF24WG can
do this, but it will take 20-30 seconds. The host MCU will be able to convert the passphrase to a binary key much faster. If that is
desired, then this function should be called to request the MRF24WG to signal the
DRV_WIFI_EVENT_KEY_CALCULATION_REQUEST event when the passphrase is ready. Then the host can retrieve the
passphrase (see DRV_WIFI_WPSCredentialsGet()), convert to a binary key (see DRV_WIFI_ConvPassphraseToKey()), and
send it back to the MRF24WG via the DRV_WIFI_SetPSK() function.
Preconditions
WiFi initialization must be complete.
Returns
None.
Remarks
None.
Example
DRV_WIFI_YieldPassphraseToHost(&info);
5.1.13.7.4 Data Types and Constants
5.1.13.7.4.1 DRV_WIFI_BSSID_LENGTH Macro
C
#define DRV_WIFI_BSSID_LENGTH (6)
Description
This is macro DRV_WIFI_BSSID_LENGTH.
5.1.13.7.4.2 DRV_WIFI_DEAUTH_REASONCODE_MASK Macro
C
#define DRV_WIFI_DEAUTH_REASONCODE_MASK ((uint8_t)0x80)
Description
This is macro DRV_WIFI_DEAUTH_REASONCODE_MASK.
5.1.13.7.4.3 DRV_WIFI_DEFAULT_ADHOC_BEACON_PERIOD Macro
C
#define DRV_WIFI_DEFAULT_ADHOC_BEACON_PERIOD (100) // ms
Description
ms
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-647
5.1.13.7.4.4 DRV_WIFI_DEFAULT_ADHOC_HIDDEN_SSID Macro
C
#define DRV_WIFI_DEFAULT_ADHOC_HIDDEN_SSID false
Description
WiFi AdHoc default settings
These defines identify various default WiFi AdHoc settings that can be used in the DRV_WIFI_ADHOC_NETWORK_CONTEXT
structure.
5.1.13.7.4.5 DRV_WIFI_DEFAULT_ADHOC_MODE Macro
C
#define DRV_WIFI_DEFAULT_ADHOC_MODE DRV_WIFI_ADHOC_CONNECT_THEN_START
Description
This is macro DRV_WIFI_DEFAULT_ADHOC_MODE.
5.1.13.7.4.6 DRV_WIFI_DEFAULT_PS_DTIM_ENABLED Macro
C
#define DRV_WIFI_DEFAULT_PS_DTIM_ENABLED true // DTIM wake-up enabled (normally
the case)
Description
DTIM wake-up enabled (normally the case)
5.1.13.7.4.7 DRV_WIFI_DEFAULT_PS_DTIM_INTERVAL Macro
C
#define DRV_WIFI_DEFAULT_PS_DTIM_INTERVAL ((uint16_t)2) // number of beacon periods
Description
number of beacon periods
5.1.13.7.4.8 DRV_WIFI_DEFAULT_PS_LISTEN_INTERVAL Macro
C
#define DRV_WIFI_DEFAULT_PS_LISTEN_INTERVAL ((uint16_t)1) // 100ms multiplier, e.g. 1 *
100ms = 100ms
Description
100ms multiplier, e.g. 1 * 100ms = 100ms
5.1.13.7.4.9 DRV_WIFI_DEFAULT_SCAN_COUNT Macro
C
#define DRV_WIFI_DEFAULT_SCAN_COUNT (1)
Description
WiFi Scan Context default settings
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-648
This enumeration identifies the default WiFi scan context values that can be used in the DRV_WIFI_SCAN_CONTEXT structure.
5.1.13.7.4.10 DRV_WIFI_DEFAULT_SCAN_MAX_CHANNEL_TIME Macro
C
#define DRV_WIFI_DEFAULT_SCAN_MAX_CHANNEL_TIME (400) // ms
Description
ms
5.1.13.7.4.11 DRV_WIFI_DEFAULT_SCAN_MIN_CHANNEL_TIME Macro
C
#define DRV_WIFI_DEFAULT_SCAN_MIN_CHANNEL_TIME (200) // ms
Description
ms
5.1.13.7.4.12 DRV_WIFI_DEFAULT_SCAN_PROBE_DELAY Macro
C
#define DRV_WIFI_DEFAULT_SCAN_PROBE_DELAY (20) // us
Description
us
5.1.13.7.4.13 DRV_WIFI_DEFAULT_WEP_KEY_TYPE Macro
C
#define DRV_WIFI_DEFAULT_WEP_KEY_TYPE DRV_WIFI_SECURITY_WEP_OPENKEY
Description
see DRV_WIFI_SecurityWepSet() and DRV_WIFI_WEP_CONTEXT
5.1.13.7.4.14 DRV_WIFI_DISABLED Macro
C
#define DRV_WIFI_DISABLED (0)
Description
Do not make this an enumerated type!
5.1.13.7.4.15 DRV_WIFI_DISASSOC_REASONCODE_MASK Macro
C
#define DRV_WIFI_DISASSOC_REASONCODE_MASK ((uint8_t)0x40)
Description
This is macro DRV_WIFI_DISASSOC_REASONCODE_MASK.
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-649
5.1.13.7.4.16 DRV_WIFI_ENABLED Macro
C
#define DRV_WIFI_ENABLED (1)
Description
This is macro DRV_WIFI_ENABLED.
5.1.13.7.4.17 DRV_WIFI_MAX_CHANNEL_LIST_LENGTH Macro
C
#define DRV_WIFI_MAX_CHANNEL_LIST_LENGTH (14)
Description
This is macro DRV_WIFI_MAX_CHANNEL_LIST_LENGTH.
5.1.13.7.4.18 DRV_WIFI_MAX_NUM_RATES Macro
C
#define DRV_WIFI_MAX_NUM_RATES (8)
Description
This is macro DRV_WIFI_MAX_NUM_RATES.
5.1.13.7.4.19 DRV_WIFI_MAX_SECURITY_KEY_LENGTH Macro
C
#define DRV_WIFI_MAX_SECURITY_KEY_LENGTH (64)
Description
This is macro DRV_WIFI_MAX_SECURITY_KEY_LENGTH.
5.1.13.7.4.20 DRV_WIFI_MAX_SSID_LENGTH Macro
C
#define DRV_WIFI_MAX_SSID_LENGTH (32)
Description
This is macro DRV_WIFI_MAX_SSID_LENGTH.
5.1.13.7.4.21 DRV_WIFI_MAX_WEP_KEY_LENGTH Macro
C
#define DRV_WIFI_MAX_WEP_KEY_LENGTH (DRV_WIFI_WEP104_KEY_LENGTH)
Description
This is macro DRV_WIFI_MAX_WEP_KEY_LENGTH.
5.1.13.7.4.22 DRV_WIFI_MAX_WPA_PASS_PHRASE_LENGTH Macro
C
#define DRV_WIFI_MAX_WPA_PASS_PHRASE_LENGTH (64) // must include string terminator
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-650
Description
must include string terminator
5.1.13.7.4.23 DRV_WIFI_MAX_WPA2_PASS_PHRASE_LENGTH Macro
C
#define DRV_WIFI_MAX_WPA2_PASS_PHRASE_LENGTH (64)
Description
This is macro DRV_WIFI_MAX_WPA2_PASS_PHRASE_LENGTH.
5.1.13.7.4.24 DRV_WIFI_MIN_WPA_PASS_PHRASE_LENGTH Macro
C
#define DRV_WIFI_MIN_WPA_PASS_PHRASE_LENGTH (8)
Description
Key size defines
5.1.13.7.4.25 DRV_WIFI_NETWORK_TYPE_ADHOC Macro
C
#define DRV_WIFI_NETWORK_TYPE_ADHOC (2)
Description
This is macro DRV_WIFI_NETWORK_TYPE_ADHOC.
5.1.13.7.4.26 DRV_WIFI_NETWORK_TYPE_INFRASTRUCTURE Macro
C
#define DRV_WIFI_NETWORK_TYPE_INFRASTRUCTURE (1)
Description
WiFi Network Types
This enumeration identifies the WiFi network types that can be selected. Do NOT make these an enumerated type as they are
used as a compile switch.
5.1.13.7.4.27 DRV_WIFI_NETWORK_TYPE_P2P Macro
C
#define DRV_WIFI_NETWORK_TYPE_P2P (3) /* not supported */
Description
not supported
5.1.13.7.4.28 DRV_WIFI_NETWORK_TYPE_SOFT_AP Macro
C
#define DRV_WIFI_NETWORK_TYPE_SOFT_AP (4)
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-651
Description
This is macro DRV_WIFI_NETWORK_TYPE_SOFT_AP.
5.1.13.7.4.29 DRV_WIFI_NO_ADDITIONAL_INFO Macro
C
#define DRV_WIFI_NO_ADDITIONAL_INFO ((uint16_t)0xffff)
Description
eventInfo define for DRV_WIFI_ProcessEvent() when no additional info is supplied
5.1.13.7.4.30 DRV_WIFI_RETRY_ADHOC Macro
C
#define DRV_WIFI_RETRY_ADHOC (3)
Description
This is macro DRV_WIFI_RETRY_ADHOC.
5.1.13.7.4.31 DRV_WIFI_RETRY_FOREVER Macro
C
#define DRV_WIFI_RETRY_FOREVER (255)
Description
This is macro DRV_WIFI_RETRY_FOREVER.
5.1.13.7.4.32 DRV_WIFI_RTS_THRESHOLD_MAX Macro
C
#define DRV_WIFI_RTS_THRESHOLD_MAX (2347) /* maximum RTS threshold size in bytes */
Description
maximum RTS threshold size in bytes
5.1.13.7.4.33 DRV_WIFI_SECURITY_EAP Macro
C
#define DRV_WIFI_SECURITY_EAP (11)
Description
This is macro DRV_WIFI_SECURITY_EAP.
5.1.13.7.4.34 DRV_WIFI_SECURITY_OPEN Macro
C
#define DRV_WIFI_SECURITY_OPEN (0)
Description
WiFi Security Types
This enumeration identifies the WiFi security types that can be selected. Do NOT make these an enumerated type as they are
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-652
used as a compile switch.
5.1.13.7.4.35 DRV_WIFI_SECURITY_WEP_104 Macro
C
#define DRV_WIFI_SECURITY_WEP_104 (2)
Description
This is macro DRV_WIFI_SECURITY_WEP_104.
5.1.13.7.4.36 DRV_WIFI_SECURITY_WEP_40 Macro
C
#define DRV_WIFI_SECURITY_WEP_40 (1)
Description
This is macro DRV_WIFI_SECURITY_WEP_40.
5.1.13.7.4.37 DRV_WIFI_SECURITY_WPA_AUTO_WITH_KEY Macro
C
#define DRV_WIFI_SECURITY_WPA_AUTO_WITH_KEY (7)
Description
This is macro DRV_WIFI_SECURITY_WPA_AUTO_WITH_KEY.
5.1.13.7.4.38 DRV_WIFI_SECURITY_WPA_AUTO_WITH_PASS_PHRASE Macro
C
#define DRV_WIFI_SECURITY_WPA_AUTO_WITH_PASS_PHRASE (8)
Description
This is macro DRV_WIFI_SECURITY_WPA_AUTO_WITH_PASS_PHRASE.
5.1.13.7.4.39 DRV_WIFI_SECURITY_WPA_WITH_KEY Macro
C
#define DRV_WIFI_SECURITY_WPA_WITH_KEY (3)
Description
This is macro DRV_WIFI_SECURITY_WPA_WITH_KEY.
5.1.13.7.4.40 DRV_WIFI_SECURITY_WPA_WITH_PASS_PHRASE Macro
C
#define DRV_WIFI_SECURITY_WPA_WITH_PASS_PHRASE (4)
Description
This is macro DRV_WIFI_SECURITY_WPA_WITH_PASS_PHRASE.
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-653
5.1.13.7.4.41 DRV_WIFI_SECURITY_WPA2_WITH_KEY Macro
C
#define DRV_WIFI_SECURITY_WPA2_WITH_KEY (5)
Description
This is macro DRV_WIFI_SECURITY_WPA2_WITH_KEY.
5.1.13.7.4.42 DRV_WIFI_SECURITY_WPA2_WITH_PASS_PHRASE Macro
C
#define DRV_WIFI_SECURITY_WPA2_WITH_PASS_PHRASE (6)
Description
This is macro DRV_WIFI_SECURITY_WPA2_WITH_PASS_PHRASE.
5.1.13.7.4.43 DRV_WIFI_SECURITY_WPS_PIN Macro
C
#define DRV_WIFI_SECURITY_WPS_PIN (10)
Description
This is macro DRV_WIFI_SECURITY_WPS_PIN.
5.1.13.7.4.44 DRV_WIFI_SECURITY_WPS_PUSH_BUTTON Macro
C
#define DRV_WIFI_SECURITY_WPS_PUSH_BUTTON (9)
Description
This is macro DRV_WIFI_SECURITY_WPS_PUSH_BUTTON.
5.1.13.7.4.45 DRV_WIFI_VERSION_NUMBER Macro
C
#define DRV_WIFI_VERSION_NUMBER "3.0.0"
Description
WiFi Driver Version Number
5.1.13.7.4.46 DRV_WIFI_WEP104_KEY_LENGTH Macro
C
#define DRV_WIFI_WEP104_KEY_LENGTH (52) // 4 keys of 13 bytes each
Description
4 keys of 13 bytes each
5.1.13.7.4.47 DRV_WIFI_WEP40_KEY_LENGTH Macro
C
#define DRV_WIFI_WEP40_KEY_LENGTH (20) // 4 keys of 5 bytes each
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-654
Description
4 keys of 5 bytes each
5.1.13.7.4.48 DRV_WIFI_WPA_KEY_LENGTH Macro
C
#define DRV_WIFI_WPA_KEY_LENGTH (32)
Description
This is macro DRV_WIFI_WPA_KEY_LENGTH.
5.1.13.7.4.49 DRV_WIFI_WPA2_KEY_LENGTH Macro
C
#define DRV_WIFI_WPA2_KEY_LENGTH (32)
Description
This is macro DRV_WIFI_WPA2_KEY_LENGTH.
5.1.13.7.4.50 DRV_WIFI_WPS_PIN_LENGTH Macro
C
#define DRV_WIFI_WPS_PIN_LENGTH (8) // 7 digits + checksum byte
Description
7 digits + checksum byte
5.1.13.7.4.51 DRV_WIFI_ADHOC_MODES Enumeration
C
typedef enum adhocMode {
DRV_WIFI_ADHOC_CONNECT_THEN_START = 0,
DRV_WIFI_ADHOC_CONNECT_ONLY = 1,
DRV_WIFI_ADHOC_START_ONLY = 2
} DRV_WIFI_ADHOC_MODES;
Description
AdHoc Modes
This enumeration identifies the AdHoc modes that can be selelcted when connecting in AdHoc mode.
Members
Members Description
DRV_WIFI_ADHOC_CONNECT_THEN_START
= 0
try to connect existing AdHoc network, if not found then start network
DRV_WIFI_ADHOC_CONNECT_ONLY = 1 only connect to existing AdHoc network
DRV_WIFI_ADHOC_START_ONLY = 2 only start a new AdHoc network
5.1.13.7.4.52 DRV_WIFI_ADHOC_NETWORK_CONTEXT Structure
C
typedef struct {
uint8_t mode;
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-655
bool hiddenSsid;
uint16_t beaconPeriod;
} DRV_WIFI_ADHOC_NETWORK_CONTEXT;
Description
WiFi AdHoc Context
This structure contains MRF24WG AdHoc context data. See DRV_WIFI_AdhocContextSet().
Members
Members Description
uint8_t mode; Defines how to start the AdHoc network. See DRV_WIFI_ADHOC_MODE. Default
is DRV_WIFI_ADHOC_CONNECT_THEN_START.
bool hiddenSsid; When starting an AdHoc network, the SSID can be hidden in the beacons. Set
true to hide the SSID, else false. Default is false.
uint16_t beaconPeriod; Sets the beacon period, in ms. Default is 100ms
5.1.13.7.4.53 DRV_WIFI_CONNECTION_CONTEXT Structure
C
typedef struct {
uint8_t channel;
uint8_t bssid[6];
} DRV_WIFI_CONNECTION_CONTEXT;
Description
WiFi Connection Context
This structure contains MRF24WG connection context data. See DRV_WIFI_ConnectContextGet().
Members
Members Description
uint8_t channel; channel number of current connection
uint8_t bssid[6]; bssid of connected AP
5.1.13.7.4.54 DRV_WIFI_CONNECTION_STATES Enumeration
C
typedef enum {
DRV_WIFI_CSTATE_NOT_CONNECTED = 1,
DRV_WIFI_CSTATE_CONNECTION_IN_PROGRESS = 2,
DRV_WIFI_CSTATE_CONNECTED_INFRASTRUCTURE = 3,
DRV_WIFI_CSTATE_CONNECTED_ADHOC = 4,
DRV_WIFI_CSTATE_RECONNECTION_IN_PROGRESS = 5,
DRV_WIFI_CSTATE_CONNECTION_PERMANENTLY_LOST = 6
} DRV_WIFI_CONNECTION_STATES;
Description
WiFi Connection States
This enumeration identifies WiFi Connection states states. See DRV_WIFI_ConnectionStateGet().
Members
Members Description
DRV_WIFI_CSTATE_NOT_CONNECTED = 1 No WiFi connection exists
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-656
DRV_WIFI_CSTATE_CONNECTION_IN_PROGRESS = 2 WiFi connection in progress
DRV_WIFI_CSTATE_CONNECTED_INFRASTRUCTURE = 3 WiFi connected in infrastructure mode
DRV_WIFI_CSTATE_CONNECTED_ADHOC = 4 WiFi connected in adhoc mode
DRV_WIFI_CSTATE_RECONNECTION_IN_PROGRESS = 5 WiFi in process of reconnecting
DRV_WIFI_CSTATE_CONNECTION_PERMANENTLY_LOST
= 6
WiFi connection permanently lost
5.1.13.7.4.55 DRV_WIFI_DEVICE_INFO Structure
C
typedef struct {
uint8_t deviceType;
uint8_t romVersion;
uint8_t patchVersion;
} DRV_WIFI_DEVICE_INFO;
Description
WiFi Device Type/Version
This structure contains MRF24WG device type and version number. See DRV_WIFI_DeviceInfoGet().
Members
Members Description
uint8_t deviceType; MRF24W_DEVICE_TYPE
uint8_t romVersion; MRF24WG ROM version number
uint8_t patchVersion; MRF24WG patch version number
5.1.13.7.4.56 DRV_WIFI_DEVICE_TYPES Enumeration
C
typedef enum {
DRV_WIFI_MRF24WB0M_DEVICE = 1,
DRV_WIFI_MRF24WG0M_DEVICE = 2
} DRV_WIFI_DEVICE_TYPES;
Description
WiFi devices types
This enumeration identifies WiFi device types. The only device supported with this driver is DRV_WIFI_MRF24WG0M_DEVICE
5.1.13.7.4.57 DRV_WIFI_DOMAIN_CODES Enumeration
C
typedef enum {
DRV_WIFI_DOMAIN_FCC = 0,
DRV_WIFI_DOMAIN_ETSI = 2,
DRV_WIFI_DOMAIN_JAPAN = 7,
DRV_WIFI_DOMAIN_OTHER = 7
} DRV_WIFI_DOMAIN_CODES;
Description
WiFi regional domain codes
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-657
This enumeration identifies WiFi regional domain codes. The regional domain can be determined by calling
DRV_WIFI_RegionalDomainGet().
Members
Members Description
DRV_WIFI_DOMAIN_FCC = 0 FCC, available channels: 1 - 11
DRV_WIFI_DOMAIN_ETSI = 2 ESTI, available Channels: 1 - 13
DRV_WIFI_DOMAIN_JAPAN = 7 Japan, available Channels: 1 - 14
DRV_WIFI_DOMAIN_OTHER = 7 Other, available Channels: 1 - 14
5.1.13.7.4.58 DRV_WIFI_EVENT_CONN_TEMP_LOST_CODES Enumeration
C
typedef enum {
DRV_WIFI_BEACON_TIMEOUT = 1,
DRV_WIFI_DEAUTH_RECEIVED = 2,
DRV_WIFI_DISASSOCIATE_RECEIVED = 3
} DRV_WIFI_EVENT_CONN_TEMP_LOST_CODES;
Description
'Connection Temporarily Lost' event codes
This enumeration identifies the codes for a connection temporarily lost. These codes are used in DRV_WIFI_ProcessEvent(),
case DRV_WIFI_EVENT_CONNECTION_TEMPORARILY_LOST.
Members
Members Description
DRV_WIFI_BEACON_TIMEOUT = 1 connection temporarily lost due to beacon timeout
DRV_WIFI_DEAUTH_RECEIVED = 2 connection temporarily lost due to deauth received from AP
DRV_WIFI_DISASSOCIATE_RECEIVED =
3
connection temporarily lost due to disassociation received from AP
5.1.13.7.4.59 DRV_WIFI_EVENT_INFO Enumeration
C
typedef enum {
DRV_WIFI_JOIN_FAILURE = 2,
DRV_WIFI_AUTHENTICATION_FAILURE = 3,
DRV_WIFI_ASSOCIATION_FAILURE = 4,
DRV_WIFI_WEP_HANDSHAKE_FAILURE = 5,
DRV_WIFI_PSK_CALCULATION_FAILURE = 6,
DRV_WIFI_PSK_HANDSHAKE_FAILURE = 7,
DRV_WIFI_ADHOC_JOIN_FAILURE = 8,
DRV_WIFI_SECURITY_MISMATCH_FAILURE = 9,
DRV_WIFI_NO_SUITABLE_AP_FOUND_FAILURE = 10,
DRV_WIFI_RETRY_FOREVER_NOT_SUPPORTED_FAILURE = 11,
DRV_WIFI_LINK_LOST = 12,
DRV_WIFI_TKIP_MIC_FAILURE = 13,
DRV_WIFI_RSN_MIXED_MODE_NOT_SUPPORTED = 14,
DRV_WIFI_RECV_DEAUTH = 15,
DRV_WIFI_RECV_DISASSOC = 16,
DRV_WIFI_WPS_FAILURE = 17,
DRV_WIFI_P2P_FAILURE = 18
} DRV_WIFI_EVENT_INFO;
Description
EventInfo types
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-658
This enumeration identifies the eventInfo types used in DRV_WIFI_ProcessEvent(), case
DRV_WIFI_EVENT_CONNECTION_FAILED.
Members
Members Description
DRV_WIFI_P2P_FAILURE = 18 not supported
5.1.13.7.4.60 DRV_WIFI_EVENTS Enumeration
C
typedef enum {
DRV_WIFI_EVENT_NONE = 0,
DRV_WIFI_EVENT_CONNECTION_SUCCESSFUL = 1,
DRV_WIFI_EVENT_CONNECTION_FAILED = 2,
DRV_WIFI_EVENT_CONNECTION_TEMPORARILY_LOST = 3,
DRV_WIFI_EVENT_CONNECTION_PERMANENTLY_LOST = 4,
DRV_WIFI_EVENT_CONNECTION_REESTABLISHED = 5,
DRV_WIFI_EVENT_FLASH_UPDATE_SUCCESSFUL = 6,
DRV_WIFI_EVENT_FLASH_UPDATE_FAILED = 7,
DRV_WIFI_EVENT_KEY_CALCULATION_REQUEST = 8,
DRV_WIFI_EVENT_SCAN_RESULTS_READY = 9,
DRV_WIFI_EVENT_IE_RESULTS_READY = 10,
DRV_WIFI_EVENT_INVALID_WPS_PIN = 12,
DRV_WIFI_EVENT_SOFT_AP = 13,
DRV_WIFI_EVENT_DISCONNECT_DONE = 14,
DRV_WIFI_EVENT_ERROR = 15
} DRV_WIFI_EVENTS;
Description
WiFi Events
This enumeration identifies the WiFi events that can occur and will be sent to DRV_WIFI_ProcessEvent().
Members
Members Description
DRV_WIFI_EVENT_NONE = 0 No event has occurred
DRV_WIFI_EVENT_CONNECTION_SUCCESSFUL = 1 Connection attempt to network successful
DRV_WIFI_EVENT_CONNECTION_FAILED = 2 Connection attempt failed
DRV_WIFI_EVENT_CONNECTION_TEMPORARILY_LOST
= 3
Connection lost; MRF24W attempting to reconnect
DRV_WIFI_EVENT_CONNECTION_PERMANENTLY_LOST
= 4
Connection lost; MRF24W no longer trying to connect
DRV_WIFI_EVENT_CONNECTION_REESTABLISHED = 5 Connection has been reestablished
DRV_WIFI_EVENT_FLASH_UPDATE_SUCCESSFUL = 6 Update to FLASH successful
DRV_WIFI_EVENT_FLASH_UPDATE_FAILED = 7 Update to FLASH failed
DRV_WIFI_EVENT_KEY_CALCULATION_REQUEST = 8 Key calculation is required
DRV_WIFI_EVENT_SCAN_RESULTS_READY = 9 scan results are ready
DRV_WIFI_EVENT_IE_RESULTS_READY = 10 IE data ready
DRV_WIFI_EVENT_INVALID_WPS_PIN = 12 Invalid WPS pin was entered
DRV_WIFI_EVENT_SOFT_AP = 13 Client connection events
DRV_WIFI_EVENT_DISCONNECT_DONE = 14 Disconnect done event
DRV_WIFI_EVENT_ERROR = 15 WiFi error event occurred
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-659
5.1.13.7.4.61 DRV_WIFI_GENERAL_ERRORS Enumeration
C
typedef enum {
DRV_WIFI_ERROR_IN_HIBERNATE_MODE = 100
} DRV_WIFI_GENERAL_ERRORS;
Description
This is type DRV_WIFI_GENERAL_ERRORS.
Members
Members Description
DRV_WIFI_ERROR_IN_HIBERNATE_MODE
= 100
invalid operation while MRF24WG is in hibernate mode
5.1.13.7.4.62 DRV_WIFI_HIBERNATE_STATE Structure
C
typedef struct {
uint8_t state;
uint8_t wakeup_notice;
} DRV_WIFI_HIBERNATE_STATE;
Description
This is type DRV_WIFI_HIBERNATE_STATE.
5.1.13.7.4.63 DRV_WIFI_HIBERNATE_STATES Enumeration
C
typedef enum {
DRV_WIFI_HB_NO_SLEEP = 0,
DRV_WIFI_HB_ENTER_SLEEP = 1,
DRV_WIFI_HB_WAIT_WAKEUP = 2
} DRV_WIFI_HIBERNATE_STATES;
Description
WiFi Hibernate states
This enumeration identifies WiFi hibernate states.
5.1.13.7.4.64 DRV_WIFI_MAC_STATS Structure
C
typedef struct {
uint32_t MibWEPExcludeCtr;
uint32_t MibTxBytesCtr;
uint32_t MibTxMulticastCtr;
uint32_t MibTxFailedCtr;
uint32_t MibTxRtryCtr;
uint32_t MibTxMultRtryCtr;
uint32_t MibTxSuccessCtr;
uint32_t MibRxDupCtr;
uint32_t MibRxCtsSuccCtr;
uint32_t MibRxCtsFailCtr;
uint32_t MibRxAckFailCtr;
uint32_t MibRxBytesCtr;
uint32_t MibRxFragCtr;
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-660
uint32_t MibRxMultCtr;
uint32_t MibRxFCSErrCtr;
uint32_t MibRxWEPUndecryptCtr;
uint32_t MibRxFragAgedCtr;
uint32_t MibRxMICFailureCtr;
} DRV_WIFI_MAC_STATS;
Description
WiFi MIB states
This structure contains all the MIB data returned from the MRF24WG when DRV_WIFI_MacStatsGet() is called.
Members
Members Description
uint32_t MibWEPExcludeCtr; Number of frames received with the Protected Frame subfield of the Frame
Control field set to zero and the value of dot11ExcludeUnencrypted causes that
frame to be discarded.
uint32_t MibTxBytesCtr; Total number of Tx bytes that have been transmitted
uint32_t MibTxMulticastCtr; Number of frames successfully transmitted that had the multicast bit set in the
destination MAC address
uint32_t MibTxFailedCtr; Number of Tx frames that failed due to the number of transmits exceeding the
retry count
uint32_t MibTxRtryCtr; Number of times a transmitted frame needed to be retried
uint32_t MibTxMultRtryCtr; Number of times a frame was successfully transmitted after more than one
retransmission.
uint32_t MibTxSuccessCtr; Number of Tx frames successfully transmitted.
uint32_t MibRxDupCtr; Number of frames received where the Sequence Control field indicates a duplicate.
uint32_t MibRxCtsSuccCtr; Number of CTS frames received in response to an RTS frame.
uint32_t MibRxCtsFailCtr; Number of times an RTS frame was not received in response to a CTS frame.
uint32_t MibRxAckFailCtr; Number of times an Ack was not received in response to a Tx frame.
uint32_t MibRxBytesCtr; Total number of Rx bytes received.
uint32_t MibRxFragCtr; Number of successful received frames (management or data)
uint32_t MibRxMultCtr; Number of frames received with the multicast bit set in the destination MAC
address.
uint32_t MibRxFCSErrCtr; Number of frames received with an invalid Frame Checksum (FCS).
uint32_t MibRxWEPUndecryptCtr; Number of frames received where the Protected Frame subfield of the Frame
Control Field is set to one and the WEPOn value for the key mapped to the
transmitter?s MAC address indicates the frame should not have been encrypted.
uint32_t MibRxFragAgedCtr; Number of times that fragments aged out, or were not received in the allowable
time.
uint32_t MibRxMICFailureCtr; Number of MIC failures that have occurred.
5.1.13.7.4.65 DRV_WIFI_MGMT_ERRORS Enumeration
C
typedef enum {
DRV_WIFI_SUCCESS = 1,
DRV_WIFI_ERROR_INVALID_SUBTYPE = 2,
DRV_WIFI_ERROR_OPERATION_CANCELLED = 3,
DRV_WIFI_ERROR_FRAME_END_OF_LINE_OCCURRED = 4,
DRV_WIFI_ERROR_FRAME_RETRY_LIMIT_EXCEEDED = 5,
DRV_WIFI_ERROR_EXPECTED_BSS_VALUE_NOT_IN_FRAME = 6,
DRV_WIFI_ERROR_FRAME_SIZE_EXCEEDS_BUFFER_SIZE = 7,
DRV_WIFI_ERROR_FRAME_ENCRYPT_FAILED = 8,
DRV_WIFI_ERROR_INVALID_PARAM = 9,
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-661
DRV_WIFI_ERROR_AUTH_REQ_ISSUED_WHILE_IN_AUTH_STATE = 10,
DRV_WIFI_ERROR_ASSOC_REQ_ISSUED_WHILE_IN_ASSOC_STATE = 11,
DRV_WIFI_ERROR_INSUFFICIENT_RESOURCES = 12,
DRV_WIFI_ERROR_TIMEOUT_OCCURRED = 13,
DRV_WIFI_ERROR_BAD_EXCHANGE_ENCOUNTERED_IN_FRAME_RECEPTION = 14,
DRV_WIFI_ERROR_AUTH_REQUEST_REFUSED = 15,
DRV_WIFI_ERROR_ASSOCIATION_REQUEST_REFUSED = 16,
DRV_WIFI_ERROR_PRIOR_MGMT_REQUEST_IN_PROGRESS = 17,
DRV_WIFI_ERROR_NOT_IN_JOINED_STATE = 18,
DRV_WIFI_ERROR_NOT_IN_ASSOCIATED_STATE = 19,
DRV_WIFI_ERROR_NOT_IN_AUTHENTICATED_STATE = 20,
DRV_WIFI_ERROR_SUPPLICANT_FAILED = 21,
DRV_WIFI_ERROR_UNSUPPORTED_FEATURE = 22,
DRV_WIFI_ERROR_REQUEST_OUT_OF_SYNC = 23,
DRV_WIFI_ERROR_CP_INVALID_ELEMENT_TYPE = 24,
DRV_WIFI_ERROR_CP_INVALID_PROFILE_ID = 25,
DRV_WIFI_ERROR_CP_INVALID_DATA_LENGTH = 26,
DRV_WIFI_ERROR_CP_INVALID_SSID_LENGTH = 27,
DRV_WIFI_ERROR_CP_INVALID_SECURITY_TYPE = 28,
DRV_WIFI_ERROR_CP_INVALID_SECURITY_KEY_LENGTH = 29,
DRV_WIFI_ERROR_CP_INVALID_WEP_KEY_ID = 30,
DRV_WIFI_ERROR_CP_INVALID_NETWORK_TYPE = 31,
DRV_WIFI_ERROR_CP_INVALID_ADHOC_MODE = 32,
DRV_WIFI_ERROR_CP_INVALID_SCAN_TYPE = 33,
DRV_WIFI_ERROR_CP_INVALID_CP_LIST = 34,
DRV_WIFI_ERROR_CP_INVALID_CHANNEL_LIST_LENGTH = 35,
DRV_WIFI_ERROR_NOT_CONNECTED = 36,
DRV_WIFI_ERROR_ALREADY_CONNECTING = 37,
DRV_WIFI_ERROR_DISCONNECT_FAILED = 38,
DRV_WIFI_ERROR_NO_STORED_BSS_DESCRIPTOR = 39,
DRV_WIFI_ERROR_INVALID_MAX_POWER = 40,
DRV_WIFI_ERROR_CONNECTION_TERMINATED = 41,
DRV_WIFI_ERROR_HOST_SCAN_NOT_ALLOWED = 42,
DRV_WIFI_ERROR_INVALID_WPS_PIN = 44
} DRV_WIFI_MGMT_ERRORS;
Description
Mgmt Msg Error Codes
This enumeration identifies the errors that can occur when a DRV_WIFI API function call results in a mgmt message being sent,
via SPI, to the MRF24W.
Members
Members Description
DRV_WIFI_ERROR_DISCONNECT_FAILED = 38 Disconnect failed. Disconnect is allowed only when module is in
connected state
DRV_WIFI_ERROR_NO_STORED_BSS_DESCRIPTOR
= 39
No stored scan results
DRV_WIFI_ERROR_HOST_SCAN_NOT_ALLOWED =
42
Host Scan Failed. Host scan is allowed only in idle or connected
state
DRV_WIFI_ERROR_INVALID_WPS_PIN = 44 WPS pin was invalid
5.1.13.7.4.66 DRV_WIFI_MGMT_INDICATE_SOFT_AP_EVENT Structure
C
typedef struct {
uint8_t reason;
uint8_t address[6];
} DRV_WIFI_MGMT_INDICATE_SOFT_AP_EVENT;
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-662
Description
WiFi Soft AP Event Information
This structure contains data pertaining to Soft AP event. See DRV_WIFI_SoftApEventInfoGet().
Members
Members Description
uint8_t reason; reason code
uint8_t address[6]; MAC address
5.1.13.7.4.67 DRV_WIFI_MULTICAST_FILTER_IDS Enumeration
C
typedef enum {
DRV_WIFI_MULTICAST_FILTER_1 = 4,
DRV_WIFI_MULTICAST_FILTER_2 = 5,
DRV_WIFI_MULTICAST_FILTER_3 = 6,
DRV_WIFI_MULTICAST_FILTER_4 = 7,
DRV_WIFI_MULTICAST_FILTER_5 = 8,
DRV_WIFI_MULTICAST_FILTER_6 = 9,
DRV_WIFI_MULTICAST_FILTER_7 = 10,
DRV_WIFI_MULTICAST_FILTER_8 = 11,
DRV_WIFI_MULTICAST_FILTER_9 = 12,
DRV_WIFI_MULTICAST_FILTER_10 = 13,
DRV_WIFI_MULTICAST_FILTER_11 = 14,
DRV_WIFI_MULTICAST_FILTER_12 = 15,
DRV_WIFI_MULTICAST_FILTER_13 = 16,
DRV_WIFI_MULTICAST_FILTER_14 = 17,
DRV_WIFI_MULTICAST_FILTER_15 = 18,
DRV_WIFI_MULTICAST_FILTER_16 = 19
} DRV_WIFI_MULTICAST_FILTER_IDS;
Description
Multicast Filter ID's
This enumeration identifies the multicast filters that can be selected. See DRV_WIFI_SWMulticastFilterSet().
5.1.13.7.4.68 DRV_WIFI_MULTICAST_FILTERS Enumeration
C
typedef enum {
DRV_WIFI_MULTICAST_DISABLE_ALL = 0,
DRV_WIFI_MULTICAST_ENABLE_ALL = 1,
DRV_WIFI_MULTICAST_USE_FILTERS = 2
} DRV_WIFI_MULTICAST_FILTERS;
Description
Multicast Filter Modes
This enumeration identifies the mode of multicast filters that can be selected. See DRV_WIFI_SWMulticastFilterSet().
Members
Members Description
DRV_WIFI_MULTICAST_DISABLE_ALL =
0
Discard all received multicast messages
DRV_WIFI_MULTICAST_ENABLE_ALL = 1 forward all multicast messages to host MCU
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-663
DRV_WIFI_MULTICAST_USE_FILTERS =
2
Use the MAC filtering capability for multicast messages
5.1.13.7.4.69 DRV_WIFI_POWER_SAVE_STATES Enumeration
C
typedef enum {
DRV_WIFI_PS_HIBERNATE = 1,
DRV_WIFI_PS_PS_POLL_DTIM_ENABLED = 2,
DRV_WIFI_PS_PS_POLL_DTIM_DISABLED = 3,
DRV_WIFI_PS_OFF = 4
} DRV_WIFI_POWER_SAVE_STATES;
Description
WiFi Power Save states
This enumeration identifies WiFi Power save states. See DRV_WIFI_PsPollEnable().
Members
Members Description
DRV_WIFI_PS_HIBERNATE = 1 enable hibernate mode
DRV_WIFI_PS_PS_POLL_DTIM_ENABLED
= 2
enable power save mode with DTIM enabled
DRV_WIFI_PS_PS_POLL_DTIM_DISABLED
= 3
enable power save mode with DTIM disabled
DRV_WIFI_PS_OFF = 4 disable Power Save mode
5.1.13.7.4.70 DRV_WIFI_PS_POLL_CONTEXT Structure
C
typedef struct {
uint16_t listenInterval;
uint16_t dtimInterval;
bool useDtim;
} DRV_WIFI_PS_POLL_CONTEXT;
Description
WiFi PS-Poll Context
This structure contains MRF24WG PS-Poll context data. See DRV_WIFI_PsPollEnable().
Members
Members Description
uint16_t listenInterval; Number of 100ms intervals between instances when the MRF24WG wakes up to
received buffered messages from the network. Each count represents 100ms. For
example, 1 = 100ms, 2 = 200ms, etc. The default is 1 (100ms).
uint16_t dtimInterval; Only used if useDtim is true. The DTIM period indicates how often clients serviced
by the access point should check for buffered multicast or broadcast messages
awaiting pickup on the access point. The DTIM interval is measured in number of
beacon periods. Default for DTIM period is 2.
bool useDtim; True: (default) check for buffered multicast or broadcast messages on the
dtimInterval. False: check for buffered multicast or broadcast messages on the
listenInterval
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-664
5.1.13.7.4.71 DRV_WIFI_REASON_CODES Enumeration
C
typedef enum {
DRV_WIFI_UNSPECIFIED = 1,
DRV_WIFI_REASON_PREV_AUTH_NOT_VALID = 2,
DRV_WIFI_DEAUTH_LEAVING = 3,
DRV_WIFI_DISASSOC_DUE_TO_INACTIVITY = 4,
DRV_WIFI_DISASSOC_AP_BUSY = 5,
DRV_WIFI_CLASS2_FRAME_FROM_NONAUTH_STA = 6,
DRV_WIFI_CLASS3_FRAME_FROM_NONASSOC_STA = 7,
DRV_WIFI_DISASSOC_STA_HAS_LEFT = 8,
DRV_WIFI_STA_REQ_ASSOC_WITHOUT_AUTH = 9,
DRV_WIFI_INVALID_IE = 13,
DRV_WIFI_MIC_FAILURE = 14,
DRV_WIFI_4WAY_HANDSHAKE_TIMEOUT = 15,
DRV_WIFI_GROUP_KEY_HANDSHAKE_TIMEOUT = 16,
DRV_WIFI_IE_DIFFERENT = 17,
DRV_WIFI_INVALID_GROUP_CIPHER = 18,
DRV_WIFI_INVALID_PAIRWISE_CIPHER = 19,
DRV_WIFI_INVALID_AKMP = 20,
DRV_WIFI_UNSUPP_RSN_VERSION = 21,
DRV_WIFI_INVALID_RSN_IE_CAP = 22,
DRV_WIFI_IEEE8021X_FAILED = 23,
DRV_WIFI_CIPHER_SUITE_REJECTED = 24
} DRV_WIFI_REASON_CODES;
Description
Deauth/Disassociate Reason Codes
This enumeration identifies the reason codes for a connection lost due to a deauthorization or disassociation from the AP.
5.1.13.7.4.72 DRV_WIFI_RECONNECT_MODES Enumeration
C
typedef enum {
DRV_WIFI_DO_NOT_ATTEMPT_TO_RECONNECT = 0,
DRV_WIFI_ATTEMPT_TO_RECONNECT = 1
} DRV_WIFI_RECONNECT_MODES;
Description
WiFi Reconnect Modes
This enumeration identifies the reconnection modes that can be used in DRV_WIFI_ReconnectModeSet().
5.1.13.7.4.73 DRV_WIFI_SCAN_CONTEXT Structure
C
typedef struct {
uint8_t scanType;
uint8_t scanCount;
uint16_t minChannelTime;
uint16_t maxChannelTime;
uint16_t probeDelay;
} DRV_WIFI_SCAN_CONTEXT;
Description
WiFi Scan Context
This structure contains MRF24WG scan context data. See DRV_WIFI_ScanContextSet().
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-665
Members
Members Description
uint8_t scanType; 802.11 allows for active scanning, where the device sends out a broadcast probe
request seeking an access point. Also allowed is passive scanning where the
device only listens to beacons being broadcast from access points. Set to
DRV_WIFI_ACTIVE_SCAN (default) or DRV_WIFI_PASSIVE_SCAN
uint8_t scanCount; The number of times to scan a channel while attempting to find a particular access
point. Default is 1
uint16_t minChannelTime; The minimum time (in milliseconds) the MRF24WG will wait for a probe response
after sending a probe request. If no probe responses are received in
minChannelTime then the MRF24WG will go on to the next channel, if any are left
to scan, or quit. Default is 200ms.
uint16_t maxChannelTime; If a probe response is received within minChannelTime then the MRF24WG will
continue to collect any additional probe responses up to maxChannelTime before
going to the next channel in the channelList. Units are in milliseconds. Default is
400ms.
uint16_t probeDelay; The number of microseconds to delay before transmitting a probe request
following the channel change during scanning. Default is 20uS.
5.1.13.7.4.74 DRV_WIFI_SCAN_RESULT Structure
C
typedef struct {
uint8_t bssid[DRV_WIFI_BSSID_LENGTH];
uint8_t ssid[DRV_WIFI_MAX_SSID_LENGTH];
uint8_t apConfig;
uint8_t reserved;
uint16_t beaconPeriod;
uint16_t atimWindow;
uint8_t basicRateSet[DRV_WIFI_MAX_NUM_RATES];
uint8_t rssi;
uint8_t numRates;
uint8_t DtimPeriod;
uint8_t bssType;
uint8_t channel;
uint8_t ssidLen;
} DRV_WIFI_SCAN_RESULT;
Description
WiFi Scan Results
This structure contains the result of WiFi scan operation. See DRV_WIFI_ScanGetResult().
apConfig Bit Mask
Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
WPA2 WPA Preamble Privacy Reserved Reserved Reserved IE
IE 1 if AP broadcasting one or more Information Elements, else 0
Privacy 0 : AP is open (no security) 1: AP using security, if neither WPA and WPA2 set then security is WEP.
Preamble 0: AP transmitting with short preamble 1: AP transmitting with long preamble
WPA Only valid if Privacy is 1. 0: AP does not support WPA 1: AP supports WPA
WPA2 Only valid if Privacy is 1. 0: AP does not support WPA2 1: AP supports WPA2
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-666
Members
Members Description
uint8_t bssid[DRV_WIFI_BSSID_LENGTH]; Network BSSID value
uint8_t ssid[DRV_WIFI_MAX_SSID_LENGTH]; Network SSID value
uint8_t apConfig; Access Point config (see description)
uint8_t reserved; not used
uint16_t beaconPeriod; Network beacon interval
uint16_t atimWindow; Only valid if bssType = DRV_WIFI_NETWORK_TYPE_INFRASTRUCTURE
5.1.13.7.4.75 DRV_WIFI_SCAN_TYPES Enumeration
C
typedef enum {
DRV_WIFI_ACTIVE_SCAN = 1,
DRV_WIFI_PASSIVE_SCAN = 2
} DRV_WIFI_SCAN_TYPES;
Description
WiFi Scan Types
This enumeration identifies the WiFi scan types that can be selected.
5.1.13.7.4.76 DRV_WIFI_SECURITY_CONTEXT Union
C
typedef union {
DRV_WIFI_WEP_CONTEXT wepContext;
DRV_WIFI_WPA_CONTEXT wpaContext;
DRV_WIFI_WPS_CONTEXT wpsContext;
} DRV_WIFI_SECURITY_CONTEXT;
Description
WiFi security context
Structure/union can be used in functions DRV_WIFI_SecurityWepSet, DRV_WIFI_SecurityWpaSet, and
DRV_WIFI_SecurityWpsSet
Members
Members Description
DRV_WIFI_WEP_CONTEXT wepContext; set WEP security context
DRV_WIFI_WPA_CONTEXT wpaContext; set WPA security context
DRV_WIFI_WPS_CONTEXT wpsContext; set WPS security context
5.1.13.7.4.77 DRV_WIFI_SOFT_AP_EVENT_REASON_CODES Enumeration
C
typedef enum {
DRV_WIFI_SOFTAP_EVENT_LINK_LOST = 0,
DRV_WIFI_SOFTAP_EVENT_RECEIVED_DEAUTH = 1
} DRV_WIFI_SOFT_AP_EVENT_REASON_CODES;
Description
This is type DRV_WIFI_SOFT_AP_EVENT_REASON_CODES.
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-667
5.1.13.7.4.78 DRV_WIFI_SOFT_AP_STATES Enumeration
C
typedef enum {
DRV_WIFI_SOFTAP_EVENT_CONNECTED = 0,
DRV_WIFI_SOFTAP_EVENT_DISCONNECTED = 1
} DRV_WIFI_SOFT_AP_STATES;
Description
This is type DRV_WIFI_SOFT_AP_STATES.
5.1.13.7.4.79 DRV_WIFI_STATUS_CODES Enumeration
C
typedef enum {
DRV_WIFI_UNSPECIFIED_FAILURE = 1,
DRV_WIFI_CAPS_UNSUPPORTED = 10,
DRV_WIFI_REASSOC_NO_ASSOC = 11,
DRV_WIFI_ASSOC_DENIED_UNSPEC = 12,
DRV_WIFI_NOT_SUPPORTED_AUTH_ALG = 13,
DRV_WIFI_UNKNOWN_AUTH_TRANSACTION = 14,
DRV_WIFI_CHALLENGE_FAIL = 15,
DRV_WIFI_AUTH_TIMEOUT = 16,
DRV_WIFI_AP_UNABLE_TO_HANDLE_NEW_STA = 17,
DRV_WIFI_ASSOC_DENIED_RATES = 18,
DRV_WIFI_ASSOC_DENIED_NOSHORTPREAMBLE = 19,
DRV_WIFI_ASSOC_DENIED_NOPBCC = 20,
DRV_WIFI_ASSOC_DENIED_NOAGILITY = 21,
DRV_WIFI_ASSOC_DENIED_NOSHORTTIME = 25,
DRV_WIFI_ASSOC_DENIED_NODSSSOFDM = 26,
DRV_WIFI_S_INVALID_IE = 40,
DRV_WIFI_S_INVALID_GROUPCIPHER = 41,
DRV_WIFI_S_INVALID_PAIRWISE_CIPHER = 42,
DRV_WIFI_S_INVALID_AKMP = 43,
DRV_WIFI_UNSUPPORTED_RSN_VERSION = 44,
DRV_WIFI_S_INVALID_RSN_IE_CAP = 45,
DRV_WIFI_S_CIPHER_SUITE_REJECTED = 46,
DRV_WIFI_TIMEOUT = 47
} DRV_WIFI_STATUS_CODES;
Description
status codes for connection for association or authentication failure
This enumeration identifies the codes for a connection failure due to association or authentication failure. These codes are used
in DRV_WIFI_ProcessEvent(), case DRV_WIFI_EVENT_CONNECTION_FAILED.
5.1.13.7.4.80 DRV_WIFI_SWMULTICAST_CONFIG Structure
C
typedef struct {
uint8_t filterId;
uint8_t action;
uint8_t macBytes[6];
uint8_t macBitMask;
} DRV_WIFI_SWMULTICAST_CONFIG;
Description
WiFi SW Multicast Filter Config
This structure contains data pertaining to the configuration of the software multicast config filter.
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-668
'action' Field Description
DRV_WIFI_MULTICAST_DISABLE_ALL Multicast filter discards all received multicast messages.
DRV_WIFI_MULTICAST_ENABLE_ALL Multicast filter forwards all received multicast messages to host.
DRV_WIFI_MULTICAST_USE_FILTERS The MAC filter will be used and the remaining fields define the filter.
Members
Members Description
uint8_t filterId; DRV_WIFI_MULTICAST_FILTER_1 thru DRV_WIFI_MULTICAST_FILTER_16
uint8_t action; configures the multicast filter (see description)
uint8_t macBytes[6]; Array containing the MAC address to filter on (using the destination address of
each incoming 802.11 frame). Specific bytes within the MAC address can be
designated as ?don?t care? bytes. See macBitMask. This field in only used if
action = WF_MULTICAST_USE_FILTERS.
uint8_t macBitMask; A byte where bits 5:0 correspond to macBytes[5:0]. If the bit is zero then the
corresponding MAC byte must be an exact match for the frame to be forwarded to
the Host PIC. If the bit is one then the corresponding MAC byte is a ?don?t care?
and not used in the Multicast filtering process. This field in only used if action =
WF_MULTICAST_USE_FILTERS.
5.1.13.7.4.81 DRV_WIFI_TX_MODES Enumeration
C
typedef enum {
DRV_WIFI_TXMODE_G_RATES = 0,
DRV_WIFI_TXMODE_B_RATES = 1,
DRV_WIFI_TXMODE_LEGACY_RATES = 2
} DRV_WIFI_TX_MODES;
Description
Tx Modes
This enumeration identifies the choices the MRF24W Tx mode. It is recommended to use the DRV_WIFI_TXMODE_G_RATES
for best performance. See DRV_WIFI_TxModeSet().
Members
Members Description
DRV_WIFI_TXMODE_G_RATES = 0 Use 802.11 'g' rates
DRV_WIFI_TXMODE_B_RATES = 1 Use only 802.11 'b' rates
DRV_WIFI_TXMODE_LEGACY_RATES =
2
Use only 1 and 2 mbps rates
5.1.13.7.4.82 DRV_WIFI_WEP_CONTEXT Structure
C
typedef struct {
uint8_t wepSecurityType;
uint8_t wepKey[DRV_WIFI_MAX_WEP_KEY_LENGTH];
uint8_t wepKeyLength;
uint8_t wepKeyType;
} DRV_WIFI_WEP_CONTEXT;
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-669
Description
WiFi Wep Security Context
This structure contains MRF24WG WEP context. See DRV_WIFI_SecurityWepSet().
Members
Members Description
uint8_t wepSecurityType; DRV_WIFI_SECURITY_WEP_40 or DRV_WIFI_SECURITY_WEP_104
uint8_t
wepKey[DRV_WIFI_MAX_WEP_KEY_LENGTH];
Array containing four WEP binary keys. This will be four, 5-byte keys for
WEP-40 or four, thirteen-byte keys for WEP-104.
uint8_t wepKeyLength; number of bytes pointed to by p_wepKey
uint8_t wepKeyType; DRV_WIFI_SECURITY_WEP_OPENKEY (default) or
DRV_WIFI_SECURITY_WEP_SHAREDKEY
5.1.13.7.4.83 DRV_WIFI_WEP_KEY_TYPE Enumeration
C
typedef enum {
DRV_WIFI_SECURITY_WEP_SHAREDKEY = 0,
DRV_WIFI_SECURITY_WEP_OPENKEY = 1
} DRV_WIFI_WEP_KEY_TYPE;
Description
WEP Key Types
This enumeration identifies the choices for the WEP key type when using WEP security. The recommended key type (and
default) is Open key.
Members
Members Description
DRV_WIFI_SECURITY_WEP_SHAREDKEY
= 0
use WEP shared key
DRV_WIFI_SECURITY_WEP_OPENKEY =
1
use WEP open key (default)
5.1.13.7.4.84 DRV_WIFI_WPA_CONTEXT Structure
C
typedef struct {
uint8_t wpaSecurityType;
DRV_WIFI_WPA_KEY_INFO keyInfo;
} DRV_WIFI_WPA_CONTEXT;
Description
WiFi WPA context
This structure contains MRF24WG WPA context. See DRV_WIFI_SecurityWpaSet().
wpaSecurityType Description
DRV_WIFI_SECURITY_WPA_WITH_KEY WPA binary key
DRV_WIFI_SECURITY_WPA_WITH_PASS_PHRASE WPA passphrase
DRV_WIFI_SECURITY_WPA2_WITH_KEY WPA2 binary key
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-670
DRV_WIFI_SECURITY_WPA2_WITH_PASS_PHRASE WPA2 passphrase
DRV_WIFI_SECURITY_WPA_AUTO_WITH_KEY Auto-select between WPA/WPA2 with binary key
DRV_WIFI_SECURITY_WPA_AUTO_WITH_PASS_PHRASE Auto-select between WPA/WPA2 with passphrase
Members
Members Description
uint8_t wpaSecurityType; desired security type (see description)
DRV_WIFI_WPA_KEY_INFO keyInfo; see DRV_WIFI_WPA_KEY_INFO
5.1.13.7.4.85 DRV_WIFI_WPA_KEY_INFO Structure
C
typedef struct {
uint8_t key[DRV_WIFI_MAX_WPA2_PASS_PHRASE_LENGTH];
uint8_t keyLength;
} DRV_WIFI_WPA_KEY_INFO;
Description
WiFi WPA Key context
This structure contains MRF24WG WPA key info. This structure is used in the DRV_WIFI_WPA_CONTEXT and
DRV_WIFI_WPS_CONTEXT structures.
Members
Members Description
uint8_t
key[DRV_WIFI_MAX_WPA2_PASS_PHRASE_LENGTH];
binary key or passphrase
uint8_t keyLength; number of bytes in binary key (always 32) or passphrase
5.1.13.7.4.86 DRV_WIFI_WPS_AUTH_TYPES Enumeration
C
typedef enum {
DRV_WIFI_WPS_AUTH_OPEN = 0x01,
DRV_WIFI_WPS_AUTH_WPA_PSK = 0x02,
DRV_WIFI_WPS_AUTH_SHARED = 0x04,
DRV_WIFI_WPS_AUTH_WPA = 0x08,
DRV_WIFI_WPS_AUTH_WPA2 = 0x10,
DRV_WIFI_WPS_AUTH_WPA2_PSK = 0x20
} DRV_WIFI_WPS_AUTH_TYPES;
Description
This is type DRV_WIFI_WPS_AUTH_TYPES.
5.1.13.7.4.87 DRV_WIFI_WPS_CONTEXT Structure
C
typedef struct {
uint8_t wpsSecurityType;
uint8_t wpsPin[DRV_WIFI_WPS_PIN_LENGTH];
uint8_t wpsPinLength;
bool getPassPhrase;
DRV_WIFI_WPA_KEY_INFO * p_keyInfo;
} DRV_WIFI_WPS_CONTEXT;
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-671
Description
WiFi WPS security context
This structure contains MRF24WG WPS security context. See DRV_WIFI_SecurityWpsSet().
Members
Members Description
uint8_t wpsSecurityType; DRV_WIFI_SECURITY_WPS_PUSH_BUTTON or
DRV_WIFI_SECURITY_WPS_PIN
uint8_t
wpsPin[DRV_WIFI_WPS_PIN_LENGTH];
if using DRV_WIFI_SECURITY_WPS_PIN then pointer to 8-digit pin
uint8_t wpsPinLength; should always be 8
bool getPassPhrase; True if ASCII passphrase should be sent back to host so host can (more quickly)
calculate binary key. False if the MRF24WG should calculate the binary key
DRV_WIFI_WPA_KEY_INFO * p_keyInfo; pointer to where the WiFi driver will store passphrase info (must be global memory)
5.1.13.7.4.88 DRV_WIFI_WPS_CREDENTIAL Structure
C
typedef struct {
uint8_t ssid[32];
uint8_t netKey[64];
uint16_t authType;
uint16_t encType;
uint8_t netIdx;
uint8_t ssidLen;
uint8_t keyIdx;
uint8_t keyLen;
uint8_t bssid[6];
} DRV_WIFI_WPS_CREDENTIAL;
Description
WiFi WPS Credentials
This structure contains data pertaining to the configuration of the WiFi WPS credentials.
'authType' Field Description
DRV_WIFI_WPS_AUTH_OPEN open security
DRV_WIFI_WPS_AUTH_WPA_PSK WPA with PSK
DRV_WIFI_WPS_AUTH_SHARED Shared key
DRV_WIFI_WPS_AUTH_WPA WPA
DRV_WIFI_WPS_AUTH_WPA2 WPA2
DRV_WIFI_WPS_AUTH_WPA2_PSK WPA2 with PSK
'encType' Field Description
DRV_WIFI_WPS_ENC_NONE No encoding
DRV_WIFI_WPS_ENC_WEP WEP encoding
DRV_WIFI_WPS_ENC_TKIP WPS/TKIP encodingShared key
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-672
DRV_WIFI_ENC_AES AES encoding
Members
Members Description
uint8_t ssid[32]; network SSID
uint8_t netKey[64]; binary security key (not used if security is open)
uint16_t authType; WPS authorization type (see description)
uint16_t encType; Encoding type (see description)
uint8_t netIdx; not used
uint8_t ssidLen; number of bytes in SSID
uint8_t keyIdx; Only valid encType = WF_ENC_WEP. This is the index of the WEP key being
used.
uint8_t keyLen; number of bytes in netKey
uint8_t bssid[6]; MAC address of AP
5.1.13.7.4.89 DRV_WIFI_WPS_ENCODE_TYPES Enumeration
C
typedef enum {
DRV_WIFI_WPS_ENC_NONE = 0x01,
DRV_WIFI_WPS_ENC_WEP = 0x02,
DRV_WIFI_WPS_ENC_TKIP = 0x04,
DRV_WIFI_ENC_AES = 0x08
} DRV_WIFI_WPS_ENCODE_TYPES;
Description
This is type DRV_WIFI_WPS_ENCODE_TYPES.
5.1.13.7.4.90 ENABLE_P2P_PRINTS Macro
C
#define ENABLE_P2P_PRINTS ((uint8_t)(1 << 1)) /* not supported */
Description
not supported
5.1.13.7.4.91 ENABLE_WPS_PRINTS Macro
C
#define ENABLE_WPS_PRINTS ((uint8_t)(1 << 0))
Description
This is macro ENABLE_WPS_PRINTS.
5.1.13.7.4.92 PA6_IO Macro
C
#define PA6_IO LATAbits.LATA6
Description
debug, remove later
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-673
5.1.13.7.4.93 PA6_TRISTATE Macro
C
#define PA6_TRISTATE TRISAbits.TRISA6
Description
This is macro PA6_TRISTATE.
5.1.13.7.4.94 SET_PA6_AS_OUTPUT Macro
C
#define SET_PA6_AS_OUTPUT TRISAbits.TRISA6 = 0
Description
This is macro SET_PA6_AS_OUTPUT.
5.1.13.7.4.95 WF_WPS_PIN_LENGTH Macro
C
#define WF_WPS_PIN_LENGTH 8
Description
WPS PIN Length
5.1.13.8 Files
Files
Name Description
drv_wifi.h WiFi-specific MAC function prototypes called by TCP/IP stack.
Description
5.1.13.8.1 drv_wifi.h
WiFi MAC interface functions
The functions in this header file are accessed by the TCP/IP stack via function pointers.
Enumerations
Name Description
adhocMode Selection of different AdHoc connection modes
DRV_WIFI_ADHOC_MODES Selection of different AdHoc connection modes
DRV_WIFI_CONNECTION_STATES Wifi Connection states
DRV_WIFI_DEVICE_TYPES Codes for WiFi device types
DRV_WIFI_DOMAIN_CODES Regional domain codes.
DRV_WIFI_EVENT_CONN_TEMP_LOST_CODES Selection of different codes when WiFi connection is
temporarily lost.
DRV_WIFI_EVENT_INFO Selection of different EventInfo types
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-674
DRV_WIFI_EVENTS Selections for events that can occur.
DRV_WIFI_GENERAL_ERRORS This is type DRV_WIFI_GENERAL_ERRORS.
DRV_WIFI_HIBERNATE_STATES Wifi Hibernate states
DRV_WIFI_MGMT_ERRORS Error codes returned when a mgmt message is sent to the
MRF24W
DRV_WIFI_MULTICAST_FILTER_IDS Selections for software Multicast filter ID's
DRV_WIFI_MULTICAST_FILTERS Selections for Software Multicast Filters.
DRV_WIFI_POWER_SAVE_STATES Wifi Power Save states
DRV_WIFI_REASON_CODES Selection of different codes when a deauth or disassociation
event has occurred.
DRV_WIFI_RECONNECT_MODES Selection of different Reconnection modes
DRV_WIFI_SCAN_TYPES Selection of different WiFi scan types
DRV_WIFI_SOFT_AP_EVENT_REASON_CODES This is type
DRV_WIFI_SOFT_AP_EVENT_REASON_CODES.
DRV_WIFI_SOFT_AP_STATES This is type DRV_WIFI_SOFT_AP_STATES.
DRV_WIFI_STATUS_CODES Selection of different codes when WiFi connection fails due to
association or authentication failure.
DRV_WIFI_TX_MODES Selections for WiFi Tx mode
DRV_WIFI_WEP_KEY_TYPE Selections for WEP key type when using WEP security.
DRV_WIFI_WPS_AUTH_TYPES This is type DRV_WIFI_WPS_AUTH_TYPES.
DRV_WIFI_WPS_ENCODE_TYPES This is type DRV_WIFI_WPS_ENCODE_TYPES.
Functions
Name Description
DRV_WIFI_AdhocContextSet Sets the AdHoc context.
DRV_WIFI_BssidGet Sets the the BSSID set in DRV_WIFI_BssidSet().
DRV_WIFI_BssidSet Sets the the Basic Service Set Identifier (BSSID).
DRV_WIFI_ChannelListGet Gets the the channel list.
DRV_WIFI_ChannelListSet Sets the the channel list.
DRV_WIFI_ConfigDataErase Erases configuration data from the board EEPROM.
DRV_WIFI_ConfigDataLoad Loads configuration data from the board EEPROM.
DRV_WIFI_ConfigDataPrint Outputs to console the configuration data from the board EEPROM.
DRV_WIFI_ConfigDataSave Save configuration data to the board EEPROM.
DRV_WIFI_Connect Directs the MRF24WG to connect to a WiFi network.
DRV_WIFI_ConnectContextGet Gets the current WiFi connection context
DRV_WIFI_ConnectionStateGet Gets the current WiFi connection state
DRV_WIFI_Deinitialize Initializes the MRF24WG WiFi driver.
DRV_WIFI_DeviceInfoGet Retrieves MRF24WG device information
DRV_WIFI_Disconnect Directs the MRF24WG to disconnect from a WiFi network.
DRV_WIFI_GratuitousArpStart Starts a periodic gratuitous ARP response
DRV_WIFI_GratuitousArpStop Stops a periodic gratuitous ARP.
DRV_WIFI_HibernateEnable Puts the MRF24WG into hibernate mode.
DRV_WIFI_HWMulticastFilterGet Gets a multicast address filter from one of the two multicast filters.
DRV_WIFI_HWMulticastFilterSet Sets a multicast address filter using one of the two hardware multicast filters.
DRV_WIFI_Initialize Initializes the MRF24WG WiFi driver.
DRV_WIFI_isHibernateEnable Checks if MRF24W is in hibernate mode
DRV_WIFI_MacAddressGet Retrieves the MRF24WG MAC address
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-675
DRV_WIFI_MacAddressSet Uses a different MAC address for the MRF24W
DRV_WIFI_MacStatsGet Gets MAC statistics.
DRV_WIFI_NetworkTypeGet Gets the WiFi network type
DRV_WIFI_NetworkTypeSet Sets the WiFi network type
DRV_WIFI_PowerSaveStateGet Gets the current power-save state.
DRV_WIFI_ProcessEvent Processes WiFi event
DRV_WIFI_PsPollDisable Disables PS-Poll mode.
DRV_WIFI_PsPollEnable Enables PS Poll mode.
DRV_WIFI_ReconnectModeGet Gets the WiFi reconnection mode.
DRV_WIFI_ReconnectModeSet Sets the WiFi reconnection mode.
DRV_WIFI_RegionalDomainGet Retrieves the MRF24WG Regional domain
DRV_WIFI_RssiGet Gets RSSI value set in DRV_WIFI_RssiSet()
DRV_WIFI_RssiSet Sets RSSI restrictions when connecting
DRV_WIFI_RtsThresholdGet Gets the RTS Threshold
DRV_WIFI_RtsThresholdSet Sets the RTS Threshold.
DRV_WIFI_Scan Commands the MRF24W to start a scan operation. This will generate the
WF_EVENT_SCAN_RESULTS_READY event.
DRV_WIFI_ScanContextGet Gets the WiFi scan context.
DRV_WIFI_ScanContextSet Sets the WiFi scan context.
DRV_WIFI_ScanGetResult Read selected scan results back from MRF24W.
DRV_WIFI_SecurityGet Gets the current WiFi security setting
DRV_WIFI_SecurityOpenSet Sets WiFi security to open (no security)
DRV_WIFI_SecurityWepSet Sets WiFi security to use WEP.
DRV_WIFI_SecurityWpaSet Sets WiFi security to use WPA or WPA2
DRV_WIFI_SecurityWpsSet Sets WiFi security to use WPS
DRV_WIFI_SetLinkDownThreshold Sets number of consecutive WiFi Tx failures before link is considered down.
DRV_WIFI_SetPSK Sets the binary WPA PSK code in WPS.
DRV_WIFI_SoftApEventInfoGet Gets the stored Soft AP event info
DRV_WIFI_SsidGet Sets the SSID
DRV_WIFI_SsidSet Sets the SSID
DRV_WIFI_SWMultiCastFilterEnable Forces the MRF24WG to use software multicast filters instead of hardware
multicast filters.
DRV_WIFI_SWMulticastFilterSet Sets a multicast address filter using one of the software multicast filters.
DRV_WIFI_TxModeGet Gets 802.11 Tx mode
DRV_WIFI_TxModeSet Configures 802.11 Tx mode
DRV_WIFI_TxPowerFactoryMaxGet Retrieves the factory-set max Tx power from the MRF24W.
DRV_WIFI_TxPowerMaxGet Gets the Tx max power on the MRF24WG0M.
DRV_WIFI_TxPowerMaxSet Sets the Tx max power on the MRF24WG0M.
DRV_WIFI_WepKeyTypeGet Gets the Wep Key type
DRV_WIFI_WPSCredentialsGet Gets the WPS credentials
DRV_WIFI_YieldPassphraseToHost Allows host to get WPS WPA-PSK passphrase and convert to binary key.
Macros
Name Description
DRV_WIFI_BSSID_LENGTH This is macro DRV_WIFI_BSSID_LENGTH.
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-676
DRV_WIFI_DEAUTH_REASONCODE_MASK This is macro
DRV_WIFI_DEAUTH_REASONCODE_MASK.
DRV_WIFI_DEFAULT_ADHOC_BEACON_PERIOD ms
DRV_WIFI_DEFAULT_ADHOC_HIDDEN_SSID Default values for WiFi AdHoc settings
DRV_WIFI_DEFAULT_ADHOC_MODE This is macro
DRV_WIFI_DEFAULT_ADHOC_MODE.
DRV_WIFI_DEFAULT_PS_DTIM_ENABLED DTIM wake-up enabled (normally the case)
DRV_WIFI_DEFAULT_PS_DTIM_INTERVAL number of beacon periods
DRV_WIFI_DEFAULT_PS_LISTEN_INTERVAL 100ms multiplier, e.g. 1 * 100ms = 100ms
DRV_WIFI_DEFAULT_SCAN_COUNT Default values for WiFi scan context
DRV_WIFI_DEFAULT_SCAN_MAX_CHANNEL_TIME ms
DRV_WIFI_DEFAULT_SCAN_MIN_CHANNEL_TIME ms
DRV_WIFI_DEFAULT_SCAN_PROBE_DELAY us
DRV_WIFI_DEFAULT_WEP_KEY_TYPE see DRV_WIFI_SecurityWepSet() and
DRV_WIFI_WEP_CONTEXT
DRV_WIFI_DISABLED Do not make this an enumerated type!
DRV_WIFI_DISASSOC_REASONCODE_MASK This is macro
DRV_WIFI_DISASSOC_REASONCODE_MASK.
DRV_WIFI_ENABLED This is macro DRV_WIFI_ENABLED.
DRV_WIFI_MAX_CHANNEL_LIST_LENGTH This is macro
DRV_WIFI_MAX_CHANNEL_LIST_LENGTH.
DRV_WIFI_MAX_NUM_RATES This is macro DRV_WIFI_MAX_NUM_RATES.
DRV_WIFI_MAX_SECURITY_KEY_LENGTH This is macro
DRV_WIFI_MAX_SECURITY_KEY_LENGTH.
DRV_WIFI_MAX_SSID_LENGTH This is macro DRV_WIFI_MAX_SSID_LENGTH.
DRV_WIFI_MAX_WEP_KEY_LENGTH This is macro
DRV_WIFI_MAX_WEP_KEY_LENGTH.
DRV_WIFI_MAX_WPA_PASS_PHRASE_LENGTH must include string terminator
DRV_WIFI_MAX_WPA2_PASS_PHRASE_LENGTH This is macro
DRV_WIFI_MAX_WPA2_PASS_PHRASE_LENGT
H.
DRV_WIFI_MIN_WPA_PASS_PHRASE_LENGTH Key size defines
DRV_WIFI_NETWORK_TYPE_ADHOC This is macro
DRV_WIFI_NETWORK_TYPE_ADHOC.
DRV_WIFI_NETWORK_TYPE_INFRASTRUCTURE Selection of different WiFi network types
DRV_WIFI_NETWORK_TYPE_P2P not supported
DRV_WIFI_NETWORK_TYPE_SOFT_AP This is macro
DRV_WIFI_NETWORK_TYPE_SOFT_AP.
DRV_WIFI_NO_ADDITIONAL_INFO eventInfo define for DRV_WIFI_ProcessEvent()
when no additional info is supplied
DRV_WIFI_RETRY_ADHOC This is macro DRV_WIFI_RETRY_ADHOC.
DRV_WIFI_RETRY_FOREVER This is macro DRV_WIFI_RETRY_FOREVER.
DRV_WIFI_RTS_THRESHOLD_MAX maximum RTS threshold size in bytes
DRV_WIFI_SECURITY_EAP This is macro DRV_WIFI_SECURITY_EAP.
DRV_WIFI_SECURITY_OPEN Selection of different WiFi security types
DRV_WIFI_SECURITY_WEP_104 This is macro DRV_WIFI_SECURITY_WEP_104.
DRV_WIFI_SECURITY_WEP_40 This is macro DRV_WIFI_SECURITY_WEP_40.
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-677
DRV_WIFI_SECURITY_WPA_AUTO_WITH_KEY This is macro
DRV_WIFI_SECURITY_WPA_AUTO_WITH_KEY.
DRV_WIFI_SECURITY_WPA_AUTO_WITH_PASS_PHRASE This is macro
DRV_WIFI_SECURITY_WPA_AUTO_WITH_PASS
_PHRASE.
DRV_WIFI_SECURITY_WPA_WITH_KEY This is macro
DRV_WIFI_SECURITY_WPA_WITH_KEY.
DRV_WIFI_SECURITY_WPA_WITH_PASS_PHRASE This is macro
DRV_WIFI_SECURITY_WPA_WITH_PASS_PHRA
SE.
DRV_WIFI_SECURITY_WPA2_WITH_KEY This is macro
DRV_WIFI_SECURITY_WPA2_WITH_KEY.
DRV_WIFI_SECURITY_WPA2_WITH_PASS_PHRASE This is macro
DRV_WIFI_SECURITY_WPA2_WITH_PASS_PHR
ASE.
DRV_WIFI_SECURITY_WPS_PIN This is macro DRV_WIFI_SECURITY_WPS_PIN.
DRV_WIFI_SECURITY_WPS_PUSH_BUTTON This is macro
DRV_WIFI_SECURITY_WPS_PUSH_BUTTON.
DRV_WIFI_VERSION_NUMBER WiFi Driver Version Number
DRV_WIFI_WEP104_KEY_LENGTH 4 keys of 13 bytes each
DRV_WIFI_WEP40_KEY_LENGTH 4 keys of 5 bytes each
DRV_WIFI_WPA_KEY_LENGTH This is macro DRV_WIFI_WPA_KEY_LENGTH.
DRV_WIFI_WPA2_KEY_LENGTH This is macro DRV_WIFI_WPA2_KEY_LENGTH.
DRV_WIFI_WPS_PIN_LENGTH 7 digits + checksum byte
ENABLE_P2P_PRINTS not supported
ENABLE_WPS_PRINTS This is macro ENABLE_WPS_PRINTS.
PA6_IO debug, remove later
PA6_TRISTATE This is macro PA6_TRISTATE.
SET_PA6_AS_OUTPUT This is macro SET_PA6_AS_OUTPUT.
WF_WPS_PIN_LENGTH WPS PIN Length
Structures
Name Description
DRV_WIFI_ADHOC_NETWORK_CONTEXT Contains data pertaining to WiFi AdHoc context
DRV_WIFI_CONNECTION_CONTEXT Contains data pertaining to MRF24WG connection context
DRV_WIFI_DEVICE_INFO Contains data pertaining to MRF24WG device type and
version number
DRV_WIFI_HIBERNATE_STATE This is type DRV_WIFI_HIBERNATE_STATE.
DRV_WIFI_MAC_STATS Wifi MIB states
DRV_WIFI_MGMT_INDICATE_SOFT_AP_EVENT Contains data pertaining to WiFi Soft AP event
DRV_WIFI_PS_POLL_CONTEXT Contains data pertaining to WiFi PS-Poll context
DRV_WIFI_SCAN_CONTEXT Contains data pertaining to WiFi scan context
DRV_WIFI_SCAN_RESULT Contains data pertaining to WiFi scan results
DRV_WIFI_SWMULTICAST_CONFIG Contains data pertaining to WiFi software multicast filter
configuration
DRV_WIFI_WEP_CONTEXT Contains data pertaining to WiFi WEP context
DRV_WIFI_WPA_CONTEXT Contains data pertaining to WiFi WPA.
DRV_WIFI_WPA_KEY_INFO Contains data pertaining to WiFi WPA Key
DRV_WIFI_WPS_CONTEXT Contains data pertaining to WiFi WPS security.
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-678
DRV_WIFI_WPS_CREDENTIAL Contains data pertaining to WiFi WPS Credentials
Unions
Name Description
DRV_WIFI_SECURITY_CONTEXT Contains data pertaining to WiFi security.
File Name
drv_wifi_mac.h
5.1 Driver Library Help MPLAB Harmony Help MRF24W Wi-Fi Driver Library
5-679
5.2 Graphics Library Help
5.2.1 Graphics Library Porting Guide
5.2.1.1 Introduction
Porting to the MPLAB Harmony Graphics Library
This help file provides information for porting from the Microchip Library of Applications (MLA) version of the Graphics Library to
the Graphics Library within MPLAB Harmony.
5.2.1.2 Release Notes
MPLAB Harmony Version: v0.70b Release Date: Graphics Library: 4.00 18Nov2013
New This Release:
This is the first release of the library.
Known Issues:
Nothing to report in this release.
5.2.1.3 SW License Agreement
© 2013 Microchip Technology Inc.
Microchip licenses this software to you solely for use with Microchip products. The software is owned by Microchip and its
licensors, and is protected under applicable copyright laws. All rights reserved.
SOFTWARE IS PROVIDED “AS IS.” MICROCHIP EXPRESSLY DISCLAIMS ANY WARRANTY OF ANY KIND, WHETHER
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL MICROCHIP BE LIABLE FOR
ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, HARM TO
YOUR EQUIPMENT, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS
BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR
CONTRIBUTION, OR OTHER SIMILAR COSTS.
To the fullest extent allowed by law, Microchip and its licensors liability shall not exceed the amount of fees, if any, that you have
paid directly to Microchip to use this software.
MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE TERMS.
5.2 Graphics Library Help MPLAB Harmony Help Graphics Library Porting Guide
5-680
5.2.1.4 Upgrading from the MLA Graphics Library to the MPLAB
Harmony Graphics Library
The MPLAB Harmony Graphics Library is a completely new distribution, which is included as part of the MPLAB Harmony
installation. No files need to be maintained from an existing MLA Graphics Library installation.
5.2.1.4.1 MPLAB Harmony Graphics Library Key Features
This topic provides a description of the key features of the MPLAB Harmony Graphics Library.
Description
Note: The MPLAB Harmony Graphics Library does not support any Microchip 16-bit family devices.
The following are the key features of the MPLAB Harmony Graphics Library:
• Multiple interfaces
• Fully dynamic:
• Stack initialization/deinitialization
• Resource management
• Configurable
• Improved modularity and stack layout
• Interrupt driven operation
• RTOS friendly, with easy RTOS integration
5.2.1.4.2 MPLAB Harmony Graphics Library Structure
This topic describes the structure of the MPLAB Harmony Graphics Library.
Description
The MPLAB Harmony Graphics Library consists of a graphic widget and primitive library, a display layer, a graphics driver, and
demonstration applications, all of which support the following structure:
• Lowercase file names
• Underscores are used
• System services are used instead of direct access to peripherals
• Interrupts
• Drivers
• Timer Services
• File System
• Board Support Package (BSP)
By default, the Graphics Library and its corresponding display drivers and demonstration applications are placed into the
following locations during installation of MPLAB Harmony:
• ./microchip/harmony//framework/gfx
• ./microchip/harmony//framework/driver/gfx
5.2 Graphics Library Help MPLAB Harmony Help Graphics Library Porting Guide
5-681
• ./microchip/harmony//apps/gfx
5.2.1.4.3 MPLAB Harmony Graphics Library Design
This topic discusses the design of the MPLAB Harmony Graphics Library.
Description
The MPLAB Harmony Graphics Library is designed as a part of a system running other applications, middleware, etc. Therefore,
it makes use of the system services that are available to other modules in the system or to the application, such as:
• File system
• System interrupts
• System driver services
• System timers
• System device drivers
• System command processor
• System console
• System debug services
Refer to the ./framework/gfx/src/system folder for the header files that expose the system wide available API.
5.2.1.4.4 MPLAB Harmony Graphics Library API Changes
This topic discusses the reasons behind the API changes to the MPLAB Harmony Graphics Library.
Description
The API is backward compatible in functionality only. All function names and type definitions have changed to reflect the MPLAB
Harmony philosophy.
The changes in the library API have been minimized so that the porting process is straightforward and integration with other
dependents is made simple. New functionality has been added because of new features, such as dynamic configuration and
non-block of the library. Other than these new features, the changes to the API were also made to support commonality between
the MPLAB Harmony Graphics Library and the 16-bit Graphics Library.
The API changes are at all layers of the Graphics Library which include the GOL, Primitive, and Driver layers.
5.2.1.4.5 MPLAB Harmony Graphics Library Access Changes
This topic describes the stack access updates that were made to the MPLAB Harmony Graphics Library.
Description
The Graphics Library no longer initializes the display driver, but requires the application to initialize the driver before calling any
Graphics Library functions. For example: GFX_DRV_lcc_Initialize()
Direct access to the Graphics Driver has been removed.
5.2.1.4.5.1 Graphic Primitive Layer Changes
This topic discusses the changes made to the MLA Graphics Library primitive.h file to produce the equivalent MPLAB
Harmony Graphics Library gfx_primitive.h file.
5.2 Graphics Library Help MPLAB Harmony Help Graphics Library Porting Guide
5-682
Description
Changes
The changes are as follows:
• Prefix:
• GFX_ is the generic prefix for functions
• gfx_ is the generic prefix for primitive level files
• Non-blocking support - A task queue has been added to ensure that functions do not block execution of other non-graphics
time-critical tasks
• GFX_Initialize - This function replaces the InitGraph function. The GFX_Initialize function does the following:
• Sets the line type to SOLID_LINE
• Sets the current drawing color to WHITE
• Sets the graphic cursor position to the upper left corner of the screen
• Sets active and visual pages to page 0
• Clears the active page and disables clipping
The GFX_Initialize function should be called before using the Graphics Primitive Layer.
5.2.1.4.5.2 Graphic Object Layer (GOL) Changes
This topic discusses the changes made to the MLA Graphics Library GOL.h file to produce the equivalent MPLAB Harmony
Graphics Library gfx_gol.h file.
Description
Changes
The changes are as follows.
• Prefix:
• GFX_GOL_ is the generic prefix for all Graphic Object Level functions
• gfx_gol_ is the generic prefix for all Graphic Object Level files
• Non-blocking support – a task queue has been added to ensure that functions do not block execution of other non-graphics
time-critical tasks
• GFX_Initialize – This function replaces the MLA GOL_Init function, which overrides the equivalent primitive function.
This function initializes the graphics library and creates a default style scheme with default settings referenced by the global
scheme pointer. GFX_Initialize must be called before GOL functions can be used.
5.2.1.4.5.3 Graphic Display Driver Layer Changes
This topic discusses the changes made to the DisplayDriver.h file.
This topic discusses the changes made to the MLA Graphics Library DisplayDriver.h file to produce the equivalent MPLAB
Harmony Graphics Library drv_gfx_display.h file.
Description
Changes
The changes are as follows:
• Prefix:
5.2 Graphics Library Help MPLAB Harmony Help Graphics Library Porting Guide
5-683
• DRV_GFX is the generic prefix for all Graphics Driver level functions
• drv_gfx is the generic prefix for all Graphics Driver level files
• Common API Interface – This interface establishes the basic set of driver functions and parameters required by the Graphics
Primitive Layer to display graphics content on a Liquid Crystal Display. It also lists the initialization and deinitialization
functions and parameters required by the application to establish a driver.
5.2.1.4.6 MPLAB Harmony Graphics Library Initialization Changes
This topic describes the initialization updates to the MPLAB Harmony Graphics Library.
Description
The Graphics Library include header files, gfx_gol.h and gfx_primitive.h, have been updated as follows.
To initialize the library the call is now: GFX_Initialize()
The default Graphics Library configuration is provided with the library distribution and consists of:
• drv_gfx__config_template.h
• gfx_config_template.h
An example of the graphics initialization can be observed in each of the graphics demonstration distributions.
Note: Both the GOL and primitive layers implement the GFX_Initialize() function; however, the primitive layer function will
be over-ridden and not used if gfx_gol.c is compiled.
5.2.1.4.7 New MPLAB Harmony Graphics Library API Functions
This topic describes some of the important new API functions in the MPLAB Harmony Graphics Library.
Description
There are many new functions available that have been introduced to support the MPLAB Harmony philosophy. However, there
is no concern for the porting process regarding the new API calls as the previous library implementation did not support this kind
of service.
Existing applications will not port without using the new APIs:
• Initialization
• Steady-State
5.2.1.4.7.1 Main Program Changes
This topic describes the main program changes in the MPLAB Harmony Graphics Library.
Description
Main Program Changes
There are few changes that must be taken care of by the main program loop. A full working example is given with the file,
main.c, which is provided in all of the Graphics Library demonstrations.
The main program should call the following functions:
• SYS_Initialize()
• SYS_Tasks()
• GFX_GOL_ObjectListDraw()
5.2 Graphics Library Help MPLAB Harmony Help Graphics Library Porting Guide
5-684
5.2.1.4.8 MPLAB Harmony Graphics Library Configuration Changes
This topic describes the configuration changes in the MPLAB Harmony Graphics Library.
Description
The stack configuration has a completely new structure. Each project has its own configuration folder that stores multiple
configurations based on CPU platforms and hardware boards.
Note: The MLA Hardware_Profile.h file cannot be reused in the MPLAB Harmony Graphics Library.
The following is a list of the most important features:
• system_config.h – This file contains the working set of configuration definitions
• gfx_config_template.h – This file lists the entire possible graphics configuration definitions
• bsp – This is the parent directory that contains hardware configuration settings for particular Microchip development boards
5.2.1.4.8.1 MPLAB Harmony Graphics Library Configuration
This topic provides information on the configuration of the MPLAB Harmony Graphics Library.
Description
MPLAB Harmony Graphics Library Configuration
Note: This content was not available at time of release and will be added in a future release of MPLAB Harmony.
5.2.1.4.8.2 MPLAB Harmony Graphics Library BSP Configuration
This topic provides information on the BSP configuration of the MPLAB Harmony Graphics Library.
Description
MPLAB Harmony Graphics Library BSP Configuration
The MPLAB Harmony Graphics Library references the following BSP configurations:
• bsp/meb - contains board support content for the Multimedia Expansion Board and the Multimedia Expansion Board II (MEB II)
• bsp/pcap - contains board support content for the PIC32 mTouch Capacitive Touch Evaluation Board
• bsp/pictail - contains board support content for PICtail and subtending connectable liquid crystal displays (LCDs)
5.2.1.4.9 MPLAB Harmony Graphics Library Utilities
This topic describes the MPLAB Harmony Graphics Library utilities.
Description
The MPLAB Harmony Graphics Library includes the following utilities:
• Graphics Display Designer X (GDDX) - This utility can be used for designing and building graphical user interfaces (GUIs)
from graphics objects
• Graphics Resource Converter (GRC) - This utility can be used for converting data into logically deployable entities that can be
used in a graphics application
5.2 Graphics Library Help MPLAB Harmony Help Graphics Library Porting Guide
5-685
5.2.1.5 Porting Applications from the MLA Graphics Library to the
MPLAB Harmony Graphics Library
Porting an application from the MLA Graphics Library into the Graphics Library within MPLAB Harmony consists of updating
existing Graphics Library function names in your application to the new MPLAB Harmony function names.
5.2.1.5.1 MPLAB Harmony Graphics Library File Name Compliance
This topic provides header file name mapping tables that show the MLA Graphics Library file name and the compliant name
within the MPLAB Harmony Graphics Library.
Description
The replacement names chosen to make existing Graphics Library functions compliant with MPLAB Harmony are shown in
individual tables per header file name.
The files listed in the tables are located in the following two MPLAB Harmony installation folders:
.\harmony\\framework\gfx
.\harmony\\framework\gfx\src
The following table shows the original and new names used. Note that other than name changes, no other modifications were
made to the middleware functions.
MLA Graphics Library File Name MPLAB Harmony Graphics Library File Name
AnalogClock.h gfx_gol_analog_clock.h
Button.h gfx_gol_button.h
Chart.h gfx_gol_chart.h
CheckBox.h gfx_gol_check_box.h
DigitalMeter.h gfx_gol_digital_meter.h
EditBox.h gfx_gol_edit_box.h
GOL.h gfx_gol.h
Graphics.h gfx.h
Grid.h gfx_gol_grid.h (not supported in this release)
GroupBox.h gfx_gol_group_box.h
ListBox.h gfx_gol_list_box.h
Meter.h gfx_gol_meter.h
Palette.h gfx_palette.h
Picture.h gfx_picture.h
Primitive.h gfx_primitive.h
ProgressBar.h gfx_gol_progress_bar.h
Radiobutton.h gfx_gol_radio_button.h
RoundDial.h gfx_gol_round_dial.h
Slider.h gfx_gol_scrollbar.h
StaticText.h gfx_gol_static_text.h
5.2 Graphics Library Help MPLAB Harmony Help Graphics Library Porting Guide
5-686
TextEntry.h gfx_gol_text_entry.h
Transitions.h gfx_transitions.h
Window.h gfx_gol_window.h
5.2.1.5.2 MPLAB Harmony Graphics Library Function Name Compliance
This topic provides header file function mapping tables that show the MLA Graphics Library function name and the compliant
name within the MPLAB Harmony Graphics Library.
Description
The replacement function names chosen to make the existing MLA Graphics Library function compliant with MPLAB Harmony
are shown in individual tables per header file name.
The files listed in the tables are located in the following MPLAB Harmony installation folder:
.\harmony\