SAM4N8 / SAM4N16 Atmel | SMART ARM-based MCU DATASHEET Description The Atmel ® | SMART SAM4N series is a member of a family of Flash microcontrollers based on the high performance 32-bit ARM® Cortex®-M4 RISC processor. It operates at a maximum speed of 100 MHz and features up to 1024 Kbytes of Flash and up to 80 Kbytes of SRAM. The peripheral set includes 3 USARTs, 4 UARTs, 3 TWIs, 1 SPI, as well as 1 PWM timer, 2 three-channel general-purpose 16-bit timers (with stepper motor and quadrature decoder logic support), a low-power RTC, a low-power RTT, 256-bit general purpose backup registers, a 10-bit ADC (up to 12-bit with digital averaging) and a 10-bit DAC with an internal voltage reference. The SAM4N devices have three software-selectable low-power modes: Sleep, Wait and Backup. In Sleep mode, the processor is stopped while all other functions can be kept running. In Wait mode, all clocks and functions are stopped but some peripherals can be configured to wake up the system based on predefined conditions. In Backup mode, only the RTC, RTT, and wake-up logic are running. The Real-time Event Managment allows peripherals to receive, react to and send events in Active and Sleep modes without processor intervention. The SAM4N device is a medium range general purpose microcontroller with the best ratio in terms of reduced power consumption, processing power and peripheral set. This enables the SAM4N to sustain a wide range of applications including industrial automation and M2M (machine-to-machine), energy metering, consumer and appliance, building and home control. It operates from 1.62V to 3.6V and is available in 48, 64, and 100-pin QFP, 48 and 64-pin QFN, and 100-ball BGA packages. The SAM4N series offers pin-to-pin compatibility with Atmel SAM4S, SAM3S, SAM3N and SAM7S devices, facilitating easy migration within the portfolio. The SAM4N series is the ideal migration path from the SAM4S for applications that require a reduced BOM cost. Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 1. 2 Features Core ̶ ARM Cortex-M4 running at up to 100 MHz ̶ Memory Protection Unit (MPU) ̶ Thumb®-2 instruction Set Pin-to-pin compatible with SAM3N, SAM3S products (48/64/100-pin versions), SAM4S (64/100-pin versions) and SAM7S legacy products (64-pin version) Memories ̶ Up to 1024 Kbytes embedded Flash ̶ Up to 80 Kbytes embedded SRAM ̶ 8 Kbytes ROM with embedded boot loader routines (UART) and IAP routines, single-cycle access at maximum speed System ̶ Embedded voltage regulator for single supply operation ̶ Power-on-Reset (POR), Brown-out Detector (BOD) and Watchdog for safe operation ̶ Quartz or ceramic resonator oscillators: 3 to 20 MHz main power with Failure Detection and optional low power 32.768 kHz for RTC or device clock ̶ High precision 8/12 MHz factory trimmed internal RC oscillator with 4 MHz default frequency for device startup. In-application trimming access for frequency adjustment ̶ Slow Clock Internal RC oscillator as permanent low-power mode device clock ̶ PLL up to 240 MHz for device clock ̶ Temperature Sensor ̶ Up to 23 peripheral DMA (PDC) channels Low-power Modes ̶ Sleep, Wait, and Backup modes, down to 0.7 µA in Backup mode with RTC, RTT, and GPBR Peripherals ̶ Up to 3 USARTs with ISO7816, IrDA (only USART0), RS-485, and SPI Mode ̶ Up to 4 two-wire UARTs ̶ Up to 3 Two-wire Interfaces (TWI) ̶ 1 SPI ̶ 2 Three-channel 16-bit Timer Counter blocks with capture, waveform, compare and PWM mode, Quadrature Decoder Logic and 2-bit Gray Up/Down for Stepper Motor ̶ 1 Four-channel 16-bit PWM ̶ 32-bit low-power Real-time Timer (RTT) and low-power Real-time Clock (RTC) with calendar and alarm features ̶ 256-bit General Purpose Backup Registers (GPBR) I/Os ̶ Up to 79 I/O lines with external interrupt capability (edge or level sensitivity), debouncing, glitch filtering and ondie Series Resistor Termination. Individually Programmable Open-drain, Pull-up and Pull-down resistor and Synchronous Output ̶ Three 32-bit Parallel Input/Output Controllers Analog ̶ One 10-bit ADC up to 510 ksps, with Digital Averaging Function providing Enhanced Resolution Mode up to 12bit, up to 16-channels ̶ One 10-bit DAC up to 1 msps ̶ Internal voltage reference, 3V typ SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 1.1 Packages ̶ 100-lead LQFP – 14 x 14 mm, pitch 0.5 mm ̶ 100-ball TFBGA – 9 x 9 mm, pitch 0.8 mm ̶ 100-ball VFBGA – 7 x 7 mm, pitch 0.65 mm ̶ 64-lead LQFP – 10 x 10 mm, pitch 0.5 mm ̶ 64-pad QFN – 9 x 9 mm, pitch 0.5 mm ̶ 48-lead LQFP – 7 x7 mm, pitch 0.5 mm ̶ 48-pad QFN – 7 x 7 mm, pitch 0.5 mm Configuration Summary The SAM4N series devices differ in memory size, package and features. Table 1-1 summarizes the configurations of the device family. Table 1-1. Configuration Summary Feature SAM4N16C SAM4N16B SAM4N8C SAM4N8B SAM4N8A Flash 1024 Kbytes 1024 Kbytes 512 Kbytes 512 Kbytes 512 Kbytes SRAM 80 Kbytes 80 Kbytes 64 Kbytes 64 Kbytes 64 Kbytes Package LQFP100 TFBGA100 VFBGA100 LQFP64 QFN64 LQFP100 TFBGA100 VFBGA100 LQFP64 QFN64 LQFP48 QFN48 Number of PIOs 79 47 79 47 34 (1) 10-bit ADC 17 ch 10-bit DAC 1 ch 11 ch (1) 1 ch 1 ch 11 ch (1) 1 ch – 6 6 6 6 6(5) PDC Channels 23 23 23 23 23 USART/UART 3/4 2/4 3/4 2/4 1/4 (3) (3) (3) (3) 2(3) Notes: 4 3 4 (2) 9 ch (1) 16-bit Timer SPI (2) 17 ch (1) 3 TWI 3 3 3 3 3 PWM 7(4) 4(4) 7(4) 4(4) 4(4) 1. 2. 3. 4. 5. Includes Temperature Sensor Only 3 channels output USARTs with SPI mode are taken into account. Timer Counter in PWM mode is taken into account Only 2 channels output SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 3 4 2. Block Diagram See Table 1-1 for detailed configurations of memory size, package and features of the SAM4N devices. UT DO VD VD DI N TD I TD O TM S TC /S K/ WD SW IO CL JT K AG SE L SAM4N 100-pin Version Block Diagram System Controller TST XIN XOUT Voltage Regulator 3–20 MHz Oscillator PCK[2:0] JTAG and Serial Wire RC Oscillator 4/8/12 MHz Flash Unique ID In-Circuit Emulator PMC Cortex-M4 Processor fMAX 100 MHz PLL ROM SRAM 8 Kbytes 80 Kbytes 64 Kbytes 1024 Kbytes 512 Kbytes S S S Flash 24-bit SysTick Counter NVIC WKUP[15:0] SUPC XIN32 XOUT32 32K Osc ERASE 32K RC 8 GPBR RTC RTT M M POR 3-layer Bus Matrix fMAX 100 MHz RSTC NRST SM S WDT M PDC Peripheral Bridge PIO A/B/C PIO Timer Counter 0 Timer Counter 1 10-bit ADC 10-bit DACC PDC SPI PWM Temp. Sensor PW M 0. .3 3x USART PDC DA DA C0 TR G M IS M O O S NP SP I CS CK 0. .3 X UT D3 XD 3 UR X UT D0 XD ..2 0. .2 UR UART3 PDC PDC PI PI O OD DC 0 PI EN ..7 O 1 DC ..2 CL K TC LK TI 0. O .2 TI A0. O .2 B0 ..2 TC LK TI 3. O .5 TI A3. O .5 B3 ..5 AD T AD RG 0. .1 5 UART0 UART1 UART2 3x TWI PDC P PDC EF PDC SC K TX 0..2 D RX 0.. D 2 RT 0.. S 2 CT 0.. S0 2 ..2 PDC VR VDDPLL VDDIO VDDCORE I/D S AD RTCOUT0 MPU Tamper Detection TW TW D 0 CK ..2 0. .2 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Figure 2-1. 3. Signals Description Table 3-1 gives details on signal names classified by peripheral. Table 3-1. Signal Name Signal Description List Function Type Active Level Voltage Reference Comments Power Supplies VDDIO Peripherals I/O Lines Power Supply Power 1.62V to 3.6V VDDIN Voltage Regulator, ADC and DAC Power Supply Power 1.6V to 3.6V VDDOUT Voltage Regulator Output Power 1.2V Output VDDPLL Oscillator Power Supply Power 1.08V to 1.32V VDDCORE Core Chip Power Supply Power 1.08V to 1.32V Connected externally to VDDOUT GND Ground Ground Clocks, Oscillators and PLLs XIN Main Oscillator Input Input XOUT Main Oscillator Output XIN32 Slow Clock Oscillator Input XOUT32 Slow Clock Oscillator Output Output PCK0–PCK2 Programmable Clock Output Output VDDIO Output Input VDDIO ICE and JTAG TCK Test Clock Input VDDIO No pull-up resistor TDI Test Data In Input VDDIO No pull-up resistor TDO Test Data Out Output VDDIO TRACESWO Trace Asynchronous Data Out Output VDDIO SWDIO Serial Wire Input/Output I/O VDDIO SWCLK Serial Wire Clock Input VDDIO TMS Test Mode Select Input VDDIO No pull-up resistor JTAGSEL JTAG Selection Input High VDDIO Pull-down resistor High VDDIO Pull-down (15 kΩ) resistor Low VDDIO Pull-up resistor VDDIO Pull-down resistor Flash Memory ERASE Flash and NVM Configuration Bits Erase Command Input Reset/Test NRST Microcontroller Reset TST Test Mode Select I/O Input Universal Asynchronous Receiver Transmitter - UARTx URXDx UART Receive Data Input UTXDx UART Transmit Data Output SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 5 Table 3-1. Signal Description List (Continued) Signal Name Function Type Active Level Voltage Reference Comments PIO Controller - PIOA - PIOB - PIOC PA0–PA31 Parallel IO Controller A I/O VDDIO Pulled-up input at reset PB0–PB14 Parallel IO Controller B I/O VDDIO Pulled-up input at reset PC0–PC31 Parallel IO Controller C I/O VDDIO Pulled-up input at reset Universal Synchronous Asynchronous Receiver Transmitter USARTx SCKx USARTx Serial Clock I/O TXDx USARTx Transmit Data I/O RXDx USARTx Receive Data Input RTSx USARTx Request To Send CTSx USARTx Clear To Send Output Input Timer Counter - TCx TCLKx TC Channel x External Clock Input Input TIOAx TC Channel x I/O Line A I/O TIOBx TC Channel x I/O Line B I/O Pulse Width Modulation Controller - PWMC PWM PWM Waveform Output for channel Output Serial Peripheral Interface - SPI MISO Master In Slave Out I/O MOSI Master Out Slave In I/O SPCK SPI Serial Clock I/O NPCS0 SPI Peripheral Chip Select 0 I/O Low NPCS1–NPCS3 SPI Peripheral Chip Select Output Low Two-wire Interface - TWIx TWDx TWIx Two-wire Serial Data I/O TWCKx TWIx Two-wire Serial Clock I/O Analog ADVREFP (1) ADC and DAC Reference Analog 10-bit Analog-to-Digital Converter - ADC AD0–AD15 Analog Inputs Analog ADTRG ADC Trigger Input Digital-to-Analog Converter - DAC DAC0 DAC Channel Analog Output DACTRG DAC Trigger 6 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Analog Input Table 3-1. Signal Description List (Continued) Signal Name Function Type Active Level Voltage Reference Comments Fast Flash Programming Interface - FFPI PGMEN0–PGMEN2 Programming Enabling Input VDDIO PGMM0–PGMM3 Programming Mode Input VDDIO PGMD0–PGMD15 Programming Data I/O VDDIO PGMRDY Programming Ready Output High VDDIO PGMNVALID Data Direction Output Low VDDIO PGMNOE Programming Read Input Low VDDIO PGMCK Programming Clock Input PGMNCMD Programming Command Input Note: VDDIO Low VDDIO 1. “ADVREFP” is named “ADVREF” in Section 17. “Supply Controller (SUPC)” and in Section 34. “Analog-to-Digital Converter (ADC)”. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 7 4. Package and Pinout SAM4N devices are pin-to-pin compatible with SAM3N4. Table 4-1. 4.1 SAM4N Packages Device 100 Pins/Balls 64 Pins/Balls 48 Pins/Balls SAM4N16 LQFP, TFBGA and VFBGA LQFP and QFN – SAM4N8 LQFP, TFBGA and VFBGA LQFP and QFN LQFP and QFN Overview of the 100-lead LQFP Package Figure 4-1. Orientation of the 100-lead LQFP Package 75 51 76 50 100 26 1 25 Refer to Section 37. “SAM4N Mechanical Characteristics” for mechanical drawings and specifications. 4.2 Overview of the 100-ball TFBGA Package The 100-ball TFBGA package respects the Green Standards. Figure 4-2. Orientation of the 100-ball TFBGA Package TOP VIEW 10 9 8 7 6 5 4 3 2 1 BALL A1 A B C D E F G H J K Refer to Section 37. “SAM4N Mechanical Characteristics” for mechanical drawings and specifications. 8 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 4.3 Overview of the 100-ball VFBGA Package (7 x 7 x 1 mm - 0.65 mm ball pitch) The 100-ball VFBGA package respects the Green Standards. Figure 4-3. Orientation of the 100-ball VFBGA Package Top View Refer to Section 37. “SAM4N Mechanical Characteristics” for mechanical drawings and specifications. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 9 4.4 100-lead LQFP, TFBGA and VFBGA Pinout Table 4-2. SAM4N8/16 100-lead LQFP Pinout 1 ADVREFP 26 GND 51 TDI/PB4 76 TDO/TRACESWO/PB5 2 GND 27 VDDIO 52 PA6/PGMNOE 77 JTAGSEL 3 PB0/AD4 28 PA16/PGMD4 53 PA5/PGMRDY 78 PC18 4 PC29/AD13 29 PC7 54 PC28 79 TMS/SWDIO/PB6 5 PB1/AD5 30 PA15/PGMD3 55 PA4/PGMNCMD 80 PC19 6 PC30/AD14 31 PA14/PGMD2 56 VDDCORE 81 PA31 7 PB2/AD6 32 PC6 57 PA27 82 PC20 8 PC31/AD15 33 PA13/PGMD1 58 PC8 83 TCK/SWCLK/PB7 9 PB3/AD7 34 PA24 59 PA28 84 PC21 10 VDDIN 35 PC5 60 NRST 85 VDDCORE 11 VDDOUT 36 VDDCORE 61 TST 86 PC22 12 PA17/PGMD5/AD0 37 PC4 62 PC9 87 ERASE/PB12 13 PC26 38 PA25 63 PA29 88 PB10 14 PA18/PGMD6/AD1 39 PA26 64 PA30 89 PB11 15 PA21/AD8 40 PC3 65 PC10 90 PC23 16 VDDCORE 41 PA12/PGMD0 66 PA3 91 VDDIO 17 PC27 42 PA11/PGMM3 67 PA2/PGMEN2 92 PC24 18 PA19/PGMD7/AD2 43 PC2 68 PC11 93 PB13/DAC0 19 PC15/AD11 44 PA10/PGMM2 69 VDDIO 94 PC25 20 PA22/AD9 45 GND 70 GND 95 GND 21 PC13/AD10 46 PA9/PGMM1 71 PC14 96 PB8/XOUT 22 PA23 47 PC1 72 PA1/PGMEN1 97 PB9/PGMCK/XIN 23 PC12/AD12 48 PA8/XOUT32/PGMM0 73 PC16 98 VDDIO 24 PA20/AD3 49 PA7/XIN32/PGMNVALID 74 PA0/PGMEN0 99 PB14 25 PC0 50 VDDIO 75 PC17 100 VDDPLL 10 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Table 4-3. SAM4N8/16 100-ball TFBGA Pinout A1 PB1/AD5 C6 TCK/SWCLK/PB7 F1 PA18/PGMD6/AD1 H6 PC4 A2 PC29/AD13 C7 PC16 F2 PC26 H7 PA11/PGMM3 A3 VDDIO C8 PA1/PGMEN1 F3 VDDOUT H8 PC1 A4 PB9/PGMCK/XIN C9 PC17 F4 GND H9 PA6/PGMNOE A5 PB8/XOUT C10 PA0/PGMEN0 F5 VDDIO H10 TDI/PB4 A6 PB13/DAC0 D1 PB3/AD7 F6 PA27 J1 PC15/AD11 A7 PB11 D2 PB0/AD4 F7 PC8 J2 PC0 A8 PB10 D3 PC24 F8 PA28 J3 PA16/PGMD4 A9 TMS/SWDIO/PB6 D4 PC22 F9 TST J4 PC6 A10 JTAGSEL D5 GND F10 PC9 J5 PA24 B1 PC30 D6 GND G1 PA21/AD8 J6 PA25 B2 ADVREFP D7 VDDCORE G2 PC27 J7 PA10/PGMM2 B3 GND D8 PA2/PGMEN2 G3 PA15/PGMD3 J8 GND B4 PB14 D9 PC11 G4 VDDCORE J9 VDDCORE B5 PC21 D10 PC14 G5 VDDCORE J10 VDDIO B6 PC20 E1 PA17/PGMD5/ AD0 G6 PA26 K1 PA22/AD9 B7 PA31 E2 PC31 G7 PA12/PGMD0 K2 PC13/AD10 B8 PC19 E3 VDDIN G8 PC28 K3 PC12/AD12 B9 PC18 E4 GND G9 PA4/PGMNCMD K4 PA20/AD3 B10 TDO/TRACESWO/ PB5 E5 GND G10 PA5/PGMRDY K5 PC5 C1 PB2/AD6 E6 NRST H1 PA19/PGMD7/ AD2 K6 PC3 C2 VDDPLL E7 PA29 H2 PA23 K7 PC2 C3 PC25 E8 PA30/AD14 H3 PC7 K8 PA9/PGMM1 C4 PC23 E9 PC10 H4 PA14/PGMD2 K9 PA8/XOUT32/ PGMM0 C5 ERASE/PB12 E10 PA3 H5 PA13/PGMD1 K10 PA7/XIN32/ PGMNVALID SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11 Table 4-4. SAM4N8/16 100-ball VFBGA Pinout A1 ADVREFP C6 PC9 F1 VDDOUT H6 PA12/PGMD0 A2 VDDPLL C7 TMS/SWDIO/PB6 F2 PA18/PGMD6/AD1 H7 PA9/PGMM1 A3 PB9/PGMCK/XIN C8 PA1/PGMEN1 F3 PA17/PGMD5/AD0 H8 VDDCORE A4 PB8/XOUT C9 PA0/PGMEN0 F4 GND H9 PA6/PGMNOE A5 JTAGSEL C10 PC16 F5 GND H10 PA5/PGMRDY A6 PB11 D1 PB1/AD5 F6 PC26 J1 PA20/AD3 A7 PB10 D2 PC30 F7 PA4/PGMNCMD J2 PC12/AD12 A8 PC20 D3 PC31 F8 PA28 J3 PA16/PGMD4 A9 PC19 D4 PC22 F9 TST J4 PC6 A10 TDO/TRACESWO/ PB5 D5 PC5 F10 PC8 J5 PA24 B1 GND D6 PA29 G1 PC15/AD11 J6 PA25 B2 PC25 D7 PA30/AD14 G2 PA19/PGMD7/AD2 J7 PA11/PGMM3 B3 PB14 D8 GND G3 PA21/PGMD9/AD8 J8 VDDCORE B4 PB13/DAC0 D9 PC14 G4 PA15/PGMD3 J9 VDDCORE B5 PC23 D10 PC11 G5 PC3 J10 TDI/PB4 B6 PC21 E1 VDDIN G6 PA10/PGMM2 K1 PA23 B7 TCK/SWCLK/PB7 E2 PB3/AD7 G7 PC1 K2 PC0 B8 PA31 E3 PB2/AD6 G8 PC28 K3 PC7 B9 PC18 E4 GND G9 NRST K4 PA13/PGMD1 B10 PC17 E5 GND G10 PA27 K5 PA26 C1 PB0/AD4 E6 GND H1 PC13/AD10 K6 PC2 C2 PC29/AD13 E7 VDDIO H2 PA22/AD9 K7 VDDIO C3 PC24 E8 PC10 H3 PC27 K8 VDDIO C4 ERASE/PB12 E9 PA2/PGMEN2 H4 PA14/PGMD2 K9 PA8/XOUT32/ PGMM0 C5 VDDCORE E10 PA3 H5 PC4 K10 PA7/XIN32/ PGMNVALID 12 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 4.5 Overview of the 64-lead LQFP Package Figure 4-4. Orientation of the 64-lead LQFP Package 33 48 49 32 64 17 16 1 Refer to Section 37. “SAM4N Mechanical Characteristics” for mechanical drawings and specifications. 4.6 Overview of the 64-lead QFN Package Figure 4-5. Orientation of the 64-lead QFN Package 64 49 1 48 16 33 32 17 TOP VIEW Refer to Section 37. “SAM4N Mechanical Characteristics” for mechanical drawings and specifications. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 13 4.7 64-lead LQFP and QFN Pinout Table 4-5. 64-pin SAM4N8/16 Pinout 1 ADVREFP 17 GND 33 TDI/PB4 49 TDO/TRACESWO/PB5 2 GND 18 VDDIO 34 PA6/PGMNOE 50 JTAGSEL 3 PB0/AD4 19 PA16/PGMD4 35 PA5/PGMRDY 51 TMS/SWDIO/PB6 4 PB1/AD5 20 PA15/PGMD3 36 PA4/PGMNCMD 52 PA31 5 PB2/AD6 21 PA14/PGMD2 37 PA27/PGMD15 53 TCK/SWCLK/PB7 6 PB3/AD7 22 PA13/PGMD1 38 PA28 54 VDDCORE 7 VDDIN 23 PA24/PGMD12 39 NRST 55 ERASE/PB12 8 VDDOUT 24 VDDCORE 40 TST 56 PB10 9 PA17/PGMD5/AD0 25 PA25/PGMD13 41 PA29 57 PB11 10 PA18/PGMD6/AD1 26 PA26/PGMD14 42 PA30 58 VDDIO 11 PA21/PGMD9/AD8 27 PA12/PGMD0 43 PA3 59 PB13/DAC0 12 VDDCORE 28 PA11/PGMM3 44 PA2/PGMEN2 60 GND 13 PA19/PGMD7/AD2 29 PA10/PGMM2 45 VDDIO 61 XOUT/PB8 14 PA22/PGMD10/AD9 30 PA9/PGMM1 46 GND 62 XIN/PGMCK/PB9 15 PA23/PGMD11 31 PA8/XOUT32/PGMM0 47 PA1/PGMEN1 63 PB14 16 PA20/PGMD8/AD3 32 PA7/XIN32/XOUT32/ PGMNVALID 48 PA0/PGMEN0 64 VDDPLL Note: The bottom pad of the QFN package must be connected to ground. 14 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 4.8 Overview of the 48-lead LQFP Package Figure 4-6. Orientation of the 48-lead LQFP Package 25 36 37 24 48 13 12 1 Refer to Section 37. “SAM4N Mechanical Characteristics” for mechanical drawings and specifications. 4.9 Overview of the 48-lead QFN Package Figure 4-7. Orientation of the 48-lead QFN Package 48 37 1 36 12 25 24 13 TOP VIEW Refer to Section 37. “SAM4N Mechanical Characteristics” for mechanical drawings and specifications. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 15 4.10 48-lead LQFP and QFN Pinout Table 4-6. 48-pin SAM4N8 Pinout 1 ADVREFP 13 VDDIO 25 TDI/PB4 37 TDO/TRACESWO/PB5 2 GND 14 PA16/PGMD4 26 PA6/PGMNOE 38 JTAGSEL 3 PB0/AD4 15 PA15/PGMD3 27 PA5/PGMRDY 39 TMS/SWDIO/PB6 4 PB1/AD5 16 PA14/PGMD2 28 PA4/PGMNCMD 40 TCK/SWCLK/PB7 5 PB2/AD6 17 PA13/PGMD1 29 NRST 41 VDDCORE 6 PB3/AD7 18 VDDCORE 30 TST 42 ERASE/PB12 7 VDDIN 19 PA12/PGMD0 31 PA3 43 PB10 8 VDDOUT 20 PA11/PGMM3 32 PA2/PGMEN2 44 PB11 9 PA17/PGMD5/AD0 21 PA10/PGMM2 33 VDDIO 45 XOUT/PB8 10 PA18/PGMD6/AD1 22 PA9/PGMM1 34 GND 46 XIN/P/PB9/GMCK 11 PA19/PGMD7/AD2 23 PA8/XOUT32/PGMM0 35 PA1/PGMEN1 47 VDDIO 12 PA20/AD3 24 PA7/XIN32/PGMNVALID 36 PA0/PGMEN0 48 VDDPLL Note: The bottom pad of the QFN package must be connected to ground. 16 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 5. Power Considerations 5.1 Power Supplies The SAM4N8/16 product has several types of power supply pins: VDDCORE pins: power the core, including the processor, the embedded memories and the peripherals; voltage ranges from 1.08V to 1.32V. VDDIO pins: power the Peripherals I/O lines; voltage ranges from 1.62V to 3.6V. VDDIN pin: Voltage Regulator, ADC and DAC power supply; voltage ranges from 1.6V to 3.6V for Voltage Regulator, ADC and DAC. VDDPLL pin: powers the Main Oscillator; voltage ranges from 1.08V to 1.32V. 5.2 Power-up Considerations 5.2.1 VDDIO Versus VDDCORE VDDIO must always be higher than or equal to VDDCORE. VDDIO must reach its minimum operating voltage (1.62 V) before VDDCORE has reached VDDCORE(min). The minimum slope for VDDCORE is defined by (VDDCORE(min) - VT+) / tRST. If VDDCORE rises at the same time as VDDIO, the VDDIO rising slope must be higher than or equal to 8.8 V/ms. If VDDCORE is powered by the internal regulator, all power-up considerations are met Figure 5-1. VDDCORE and VDDIO Constraints at Startup Supply (V) VDDIO VDDIO(min) VDDCORE VDDCORE(min) VT+ Time (t) tRST Core supply POR output SLCK 5.2.2 VDDIO Versus VDDIN At power-up, VDDIO needs to reach 0.6 V before VDDIN reaches 1.0 V. VDDIO voltage needs to be equal to or below (VDDIN voltage + 0.5 V). SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 17 5.3 Voltage Regulator The SAM4N embeds a core voltage regulator that is managed by the Supply Controller and that supplies the Cortex-M4 core, internal memories (SRAM, ROM and Flash logic) and the peripherals. An internal adaptive biasing adjusts the regulator quiescent current depending on the required load current. For adequate input and output power supply decoupling/bypassing, refer to Table 36-3, “1.2V Voltage Regulator Characteristics,” on page 795. 5.4 Typical Powering Schematics The SAM4N8/16 supports a 1.62–3.6 V single supply mode. The internal regulator input connected to the source and its output feeds VDDCORE. Figure 5-2 shows the power schematics. As VDDIN powers voltage regulator and ADC/DAC, when the user does not want to use the embedded voltage regulator, he can disable it by software via the SUPC (note that it is different from backup mode). Figure 5-2. Single Supply VDDIO Main Supply (1.62–3.6 V) VDDIN Voltage Regulator VDDOUT VDDCORE VDDPLL Note: 18 For temperature sensor, VDDIO needs to be greater than 2.4V. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Figure 5-3. Core Externally Supplied Main Supply (1.62–3.6 V) ADC/DAC Supply (1.62–3.6 V) VDDIO VDDIN Voltage Regulator VDDOUT VDDCORE Supply (1.08–1.32 V) VDDCORE VDDPLL Note: For temperature sensor, VDDIO needs to be greater than 2.4V. Figure 5-4 provides an example of the powering scheme when using a backup battery. Since the PIO state is preserved when in backup mode, any free PIO line can be used to switch off the external regulator by driving the PIO line at low level (PIO is input, pull-up enabled after backup reset). External wake-up of the system can be from a push button or any signal, see Section 5.7 “Wake-up Sources” for further details. Figure 5-4. Core Externally Supplied (Backup Battery) VDDIO IOs Backup battery ADC, DAC, Analog Comp. VDDIN Main Supply VDDOUT Voltage Regulator 3.3V LDO VDDCORE VDDPLL External wakeup signal Note: The two diodes provide a “switchover circuit (for illustration purpose) between the backup battery and the main supply when the system is put in backup mode. Note: For temperature sensor, VDDIO needs to be greater than 2.4V. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 19 5.5 Active Mode Active mode is the normal running mode with the core clock running from the fast RC oscillator, the main crystal oscillator or the PLL. The power management controller can be used to adapt the frequency and to disable the peripheral clocks. 5.6 Low-power Modes The SAM4N has the following low-power modes: Backup, Wait, and Sleep. Note: The Wait For Event instruction (WFE) of the Cortex-M4 core can be used to enter any of the low-power modes, however, this may add complexity in the design of application state machines. This is due to the fact that the WFE instruction goes along with an event flag of the Cortex core (cannot be managed by the software application). The event flag can be set by interrupts, a debug event or an event signal from another processor. Since it is possible for an interrupt to occur just before the execution of WFE, WFE takes into account events that happened in the past. As a result, WFE prevents the device from entering Wait mode if an interrupt event has occurred. Atmel has made provisions to avoid using the WFE instruction. The workarounds to ease application design are as follows: - For Backup mode, switch off the voltage regulator and configure the VROFF bit in the Supply Controller Control Register (SUPC_CR). - For Wait mode, configure the WAITMODE bit in the PMC Clock Generator Main Oscillator Register of the Power Management Controller (PMC) - For Sleep mode, use the Wait for Interrupt (WFI) instruction. Complete information is available in Table 5-1 “Low Power Mode Configuration Summary”. 5.6.1 Backup Mode The purpose of Backup mode is to achieve the lowest power consumption possible in a system which is performing periodic wake-ups to perform tasks but not requiring fast startup time. Total current consumption is 1 µA typical (VDDIO = 1.8V at 25°C). The Supply Controller, zero-power power-on reset, RTT, RTC, backup registers and 32 kHz oscillator (RC or crystal oscillator selected by software in the Supply Controller) are running. The regulator and the core supply are off. The SAM4N can be awakened from this mode using the pins WKUP0–15, the supply monitor (SM), the RTT or RTC wake-up event. Backup mode can be entered by using the VROFF bit in the Supply Controller Control Register (SUPC_CR) or by using the WFE instruction. The corresponding procedures are described below. The procedure to enter Backup mode using the VROFF bit is the following: Write a 1 to the VROFF bit in SUPC_CR (SUPC_CR.KEY field value must be configured correctly; refer to Section 17.5.3 “Supply Controller Control Register”). The procedure to enter Backup mode using the WFE instruction is the following: 1. Write a 1 to the SLEEPDEEP bit in the Cortex-M4 processor System Control Register (SBC_SCR) (refer to Section 11.9.1.6 “System Control Register”). 2. Execute the WFE instruction of the processor. In both cases, exit from Backup mode happens if one of the following enable wake-up events occurs: 20 Level transition, configurable debouncing on pins WKUPEN0–15 Supply Monitor alarm RTC alarm RTT alarm SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 5.6.2 Wait Mode The purpose of the Wait mode is to achieve very low power consumption while maintaining the whole device in a powered state for a startup time of less than 10 µs. Current consumption in wait mode is typically 32 µA (total current consumption) if the internal voltage regulator is used. In this mode, the clocks of the core, peripherals and memories are stopped. However, the core, peripherals and memories power supplies are still powered. From this mode, a fast startup is available. This mode is entered by setting the WAITMODE bit in the PMC Clock Generator Main Oscillator Register (CKGR_MOR) in conjunction with configuring the Flash Low Power Mode field (FLPM = 00 or 01) in the PMC Fast Startup Mode Register (PMC_FSMR) or by the WFE instruction. The Cortex-M4 is able to handle external events or internal events in order to wake up the core. This is done by configuring the external lines WKUP0–15 as fast startup wake-up pins (refer to Section 5.8 “Fast Startup”). RTC or RTT alarm can be used to wake up the CPU. The procedure to enter Wait mode using the WAITMODE bit is the following: 1. Select the 4/8/12 MHz fast RC oscillator as source of MCK Clock 2. Configure the FLPM field in PMC_FSMR 3. Set Flash wait state to 0 4. Set the WAITMODE bit in CKGR_MOR 5. Wait for Master Clock Ready MCKRDY = 1 in the PMC Status Register (PMC_SR) The procedure to enter Wait mode using the WFE instruction is the following: 1. Select the 4/8/12 MHz fast RC oscillator as Main Clock. 2. Set the FLPM field in the PMC_FSMR. 3. Set Flash wait state to 0. 4. Set the LPM bit in the PMC_FSMR. 5. Execute the WFE instruction of the processor. In both cases, depending on the value of the field FLPM, the Flash enters one of three different modes: FLPM = 0 in Standby mode (low consumption) FLPM = 1 in Deep power-down mode (extra low consumption) FLPM = 2 in Idle mode. Memory ready for Read access Table 5-1 summarizes the power consumption, wake-up time and system state in Wait mode. 5.6.3 Sleep Mode The purpose of Sleep mode is to optimize power consumption of the device versus response time. In this mode, only the core clock is stopped. The peripheral clocks can be enabled. The current consumption in this mode is application dependent. This mode is entered via WFI or WFE instructions with bit LPM = 0 in PMC_FSMR. The processor can be awakened from an interrupt if the WFI instruction of the Cortex-M4 is used or from an event if the WFE instruction is used. 5.6.4 Low Power Mode Summary Table The modes detailed above are the main low power modes. Each part can be set to on or off separately and wakeup sources can be individually configured. Table 5-1 shows a summary of the configurations of the low power modes. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 21 22 Table 5-1. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Mode Low Power Mode Configuration Summary SUPC, 32 kHz Osc., RTC, RTT, GPBR, POR Core Memory (VDDBU Region) Regulator Peripherals Mode Entry VROFF = 1 Backup Mode Wait Mode w/Flash in Standby Mode ON OFF + SLEEPDEEP = 1 Pins WKUP0–15 SM alarm RTC alarm RTT alarm WAITMODE = 1 + FLPM = 0 Any event from: OFF or (Not powered) WFE or ON ON Powered (Not clocked) WFE + SLEEPDEEP = 0 + LPM = 1 + FLPM = 0 WAITMODE = 1 + FLPM = 1 Wait Mode w/Flash in Deep Power Down Mode or ON ON Potential Wake-up Sources Powered (Not clocked) WFE + SLEEPDEEP = 0 + LPM = 1 + FLPM = 1 - Fast startup through pins WKUP0–15 - RTC alarm - RTT alarm PIO State Core at while in Low- PIO State at Consumption Wake-up (2) (3) Time(1) Wake-up power Mode Wake-up Reset PIOA & PIOB & Previous state PIOC saved Inputs with pull-ups 0.9 µA typ(4) < 1 ms Clocked back Previous state Unchanged saved 28.4 µA(5) < 10 µs Clocked back Previous state Unchanged saved 23.9 µA(5) < 100 µs Clocked back Previous state Unchanged saved (6) (6) Any event from: - Fast startup through pins WKUP0–15 - RTC alarm - RTT alarm Entry mode = WFI WFE Sleep Mode Notes: ON ON or Powered(7) (Not clocked) WFI + SLEEPDEEP = 0 + LPM = 0 Interrupt only; any enabled interrupt Entry mode = WFE Any enabled interrupt and/or any event from: - Fast startup through pins WKUP0–15 - RTC alarm - RTT alarm 1. When considering wake-up time, the time required to start the PLL is not taken into account. Once started, the device works with the 4/8/12 MHz fast RC oscillator. The user has to add the PLL startup time if it is needed in the system. The wake-up time is defined as the time taken for wake-up until the first instruction is fetched. 2. The external loads on PIOs are not taken into account in the calculation. 3. BOD current consumption is not included. 4. Total consumption 0.9 µA typ at 1.8V on VDDIO at 25°C. 5. Total consumption (VDDIO + VDDIN) 6. Depends on MCK frequency. 7. In this mode the core is supplied and not clocked but some peripherals can be clocked. 5.7 Wake-up Sources The wake-up events allow the device to exit the Backup mode. When a wake-up event is detected, the Supply Controller performs a sequence which automatically reenables the core power supply and the SRAM power supply, if they are not already enabled. See Figure 17-4, "Wake-up Sources" on page 311. 5.8 Fast Startup The SAM4N8/16 allows the processor to restart in a few microseconds while the processor is in Wait mode. A fast startup can occur upon detection of a low level on one of the 18 wake-up inputs (WKUP0 to 15 + RTC + RTT). The fast restart circuitry (shown in Figure 25-3, "Fast Start-up Circuitry" on page 401) is fully asynchronous and provides a fast startup signal to the Power Management Controller. As soon as the fast startup signal is asserted, the PMC automatically restarts the embedded 4/18/12 MHz fast RC oscillator, switches the master clock on this 4 MHz clock by default and reenables the processor clock. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 23 6. Input/Output Lines The SAM4N8/16 has several kinds of input/output (I/O) lines such as general purpose I/Os (GPIO) and system I/Os. GPIOs can have alternate functionality due to multiplexing capabilities of the PIO controllers. The same PIO line can be used whether in I/O mode or by the multiplexed peripheral. System I/Os include pins such as test pins, oscillators, erase or analog inputs. 6.1 General Purpose I/O Lines GPIO lines are managed by PIO controllers. All I/Os have several input or output modes such as pull-up or pulldown, input Schmitt triggers, multi-drive (open-drain), glitch filters, debouncing or input change interrupt. Programming of these modes is performed independently for each I/O line through the PIO controller user interface. For more details, refer to Section 27. “Parallel Input/Output (PIO) Controller”. Some GPIOs can have alternate function as analog input. When the GPIO is set in analog mode, all digital features of the I/O are disabled. The input/output buffers of the PIO lines are supplied through VDDIO power supply rail. The SAM4N8/16 embeds high-speed pads. See Section 36.10 “AC Characteristics” for more details. Each I/O line also embeds an ODT (On-Die Termination) (see Figure 6-1). It consists of an internal series resistor termination scheme for impedance matching between the driver output (SAM4N) and the PCB track impedance, preventing signal reflection. The series resistor helps to reduce IOs switching current (di/dt) thereby reducing in turn, EMI. It also decreases overshoot and undershoot (ringing) due to inductance of interconnect between devices or between boards. In conclusion, ODT helps diminish signal integrity issues. Figure 6-1. On-die Termination Z0 ~ ZO + RODT ODT 36 Ω Typ. RODT Receiver SAM4 Driver with ZO ~ 10 Ω 24 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 PCB Track Z0 ~ 50 Ω 6.2 System I/O Lines Table 6-1 lists the SAM4N system I/O lines shared with PIO lines. These pins are software configurable as general purpose I/O or system pins. At startup, the default function of these pins is always used. Table 6-1. System I/O Configuration CCFG_SYSIO Bit No. Default Function after Reset Other Function Constraints for Normal Start 12 ERASE PB12 Low level at startup(1) 7 TCK/SWCLK PB7 – 6 TMS/SWDIO PB6 – 5 TDO/TRACESWO PB5 – 4 TDI PB4 – – PA7 XIN32 – – PA8 XOUT32 – – PB9 XIN – – PB8 XOUT – Configuration In Matrix User Interface Registers (Refer to System I/O Configuration Register in Section 22. “Bus Matrix (MATRIX)”.) (2) (3) Notes: 1. If PB12 is used as PIO input in user applications, a low level must be ensured at startup to prevent Flash erase before the user application sets PB12 into PIO mode. 2. Refer to Section 17.4.2 “Slow Clock Generator”. 3. Refer to Section 24.5.3 “3 to 20 MHz Crystal or Ceramic Resonator-based Oscillator”. 6.2.1 Serial Wire JTAG Debug Port (SWJ-DP) Pins The SWJ-DP pins are TCK/SWCLK, TMS/SWDIO, TDO/TRACESWO, TDI and commonly provided on a standard 20-pin JTAG connector defined by ARM. For more details about voltage reference and reset state, refer to Table 3-1 on page 5. At startup, SWJ-DP pins are configured in SWJ-DP mode to allow connection with debugging probe. Please refer to Section 12. “Debug and Test Features”. SWJ-DP pins can be used as standard I/Os to provide users more general input/output pins when the debug port is not needed in the end application. Mode selection between SWJ-DP mode (system IO mode) and general IO mode is performed through the AHB Matrix Special Function Registers (MATRIX_SFR). Configuration of the pad for pull-up, triggers, debouncing and glitch filters is possible regardless of the mode. The JTAGSEL pin is used to select the JTAG boundary scan when asserted at a high level. It integrates a permanent pull-down resistor of about 15 kΩ to GND, so that it can be left unconnected for normal operations. By default, the JTAG Debug Port is active. If the debugger host wants to switch to the Serial Wire Debug Port, it must provide a dedicated JTAG sequence on TMS/SWDIO and TCK/SWCLK which disables the JTAG-DP and enables the SW-DP. When the Serial Wire Debug Port is active, TDO/TRACESWO can be used for trace. The asynchronous TRACE output (TRACESWO) is multiplexed with TDO. So the asynchronous trace can only be used with SW-DP, not JTAG-DP. For more information about SW-DP and JTAG-DP switching, please refer to Section 12. “Debug and Test Features”. 6.3 Test Pin The TST pin is used for JTAG Boundary Scan Manufacturing Test or Fast Flash programming mode of the SAM4N series. The TST pin integrates a permanent pull-down resistor of about 15 kΩ to GND, so that it can be left unconnected for normal operations. To enter fast programming mode, see Section 20. “Fast Flash Programming Interface (FFPI)”. For more on the manufacturing and test mode, refer to Section 12. “Debug and Test Features”. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 25 6.4 NRST Pin The NRST pin is bidirectional. It is handled by the on-chip reset controller and can be driven low to provide a reset signal to the external components or asserted low externally to reset the microcontroller. It will reset the core and the peripherals except the backup region (RTC, RTT and Supply Controller). There is no constraint on the length of the reset pulse and the reset controller can guarantee a minimum pulse length. The NRST pin integrates a permanent pull-up resistor to VDDIO of about 100 kΩ. By default, the NRST pin is configured as an input. 6.5 ERASE Pin The ERASE pin is used to reinitialize the Flash content (and some of its NVM bits) to an erased state (all bits read as logic level 1). The ERASE pin and the ROM code ensure an in-situ re-programmability of the Flash content without the use of a debug tool. When the security bit is activated, the ERASE pin provides a capability to reprogram the Flash array. It integrates a pull-down resistor of about 100 kΩ to GND, so that it can be left unconnected for normal operations. This pin is debounced by SCLK to improve the glitch tolerance. To avoid unexpected erase at power-up, a minimum ERASE pin assertion time is required. This time is defined in Table 36-46 "AC Flash Characteristics". The ERASE pin is a system I/O pin and can be used as a standard I/O. At startup, the ERASE pin is not configured as a PIO pin. If the ERASE pin is used as a standard I/O, startup level of this pin must be low to prevent unwanted erasing. Refer to Section 10.2 “Peripherals Signals Multiplexing on I/O Lines” on page 36. Also, if the ERASE pin is used as a standard I/O output, asserting the pin to low does not erase the Flash. 6.6 Anti-tamper Pins/Low-power Tamper Detection WKUP0 and WKUP1 generic wake-up pins can be used as anti-tamper pins. Anti-tamper pins detect intrusion, for example, into a housing box. Upon detection through a tamper switch, automatic, asynchronous and immediate clear of registers in the backup area will be performed. Anti-tamper pins can be used in all power modes (Backup/Wait/Sleep/Active). Anti-tampering events can be programmed so that half of the General Purpose Backup Registers (GPBR) are erased automatically. See Section 17. “Supply Controller (SUPC)” for further description. 26 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 7. Memories 7.1 Product Mapping Figure 7-1. SAM4N8/16 Product Mapping 0x00000000 Address memory space Code 0x00000000 0x400E0000 System Controller Boot Memory Code Reserved 0x00400000 0x400E0200 Internal Flash 0x20000000 MATRIX 0x00800000 0x400E0400 Internal ROM PMC 0x00C00000 Internal SRAM 5 0x400E0600 Reserved UART0 0x1FFFFFFF 0x40000000 Peripherals 0x20000000 8 0x400E0740 CHIPID Internal SRAM 0x400E0800 SRAM 0x60000000 UART1 9 0x400E0A00 0x20080000 Undefined (Abort) Reserved EFC 0x40000000 0xE0000000 6 0x400E0C00 Reserved Peripherals 0x40000000 0x400E0E00 Reserved System PIOA 0x40004000 11 0x400E1000 Reserved PIOB 0x40008000 0xFFFFFFFF 12 0x400E1200 SPI PIOC 21 0x4000C000 0x400E1400 Reserved offset block 0x40010000 peripheral ID (+ : wired-or) +0x40 +0x80 0x40014000 +0x40 +0x80 TC0 +0x10 TC0 23 TC0 24 TC0 +0x90 TC4 27 TC1 +0x60 TC3 26 TC1 +0x50 TC2 25 TC1 +0x30 TC1 13 SYSC RSTC 1 SYSC SYSC SUPC RTT 3 SYSC WDT 4 SYSC RTC 2 SYSC GPBR 0x400E1600 TC5 Reserved 28 0x40018000 0x4007FFFF TWI0 19 0x4001C000 TWI1 20 0x40020000 PWM 31 0x40024000 USART0 14 0x40028000 USART1 15 0x4002C000 USART2 17 0x40030000 Reserved 0x40034000 Reserved 0x40038000 ADC 29 0x4003C000 DACC 30 0x40040000 TWI2 22 0x40044000 UART2 10 0x40048000 UART3 16 0x4004C000 Reserved 0x400E0000 System Controller 0x400E2600 Reserved 0x60000000 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 27 7.2 Embedded Memories 7.2.1 Internal SRAM The SAM4N8 product embeds a total of 64-Kbytes high-speed SRAM. The SAM4N16 product embeds a total of 80-Kbytes high-speed SRAM. The SRAM is accessible over system Cortex-M4 bus at address 0x2000 0000. The SRAM is in the bit band region. The bit band alias region is from 0x2200 0000 to 0x23FF FFFF. RAM size must be configurable by calibration fuses. 7.2.2 Internal ROM The SAM4N8/16 product embeds an Internal ROM, which contains the SAM Boot Assistant (SAM-BA® ), In Application Programming (IAP) routines and Fast Flash Programming Interface (FFPI). At any time, the ROM is mapped at address 0x0080 0000. 7.2.3 Embedded Flash 7.2.3.1 Flash Overview The memory is organized in sectors. Each sector has a size of 64 Kbytes. The first sector of 64 Kbytes is divided into three smaller sectors. The three smaller sectors are organized to consist of two sectors of 8 Kbytes and one sector of 48 Kbytes. Refer to Figure 7-2 “Global Flash Organization”. Figure 7-2. Global Flash Organization Flash Organization Sector size 28 Sector name 8 Kbytes Small sector 0 8 Kbytes Small sector 1 48 Kbytes Larger sector 64 Kbytes Sector 1 64 Kbytes Sector n SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Sector 0 Each sector is organized in pages of 512 bytes. For sector 0: The smaller sector 0 has 16 pages of 512 bytes The smaller sector 1 has 16 pages of 512 bytes The larger sector has 96 pages of 512 bytes From sector 1 to n: The rest of the array is composed of 64 Kbytes sectors each of 128 pages of 512 bytes. Refer to Figure 7-3 “Flash Sector Organization”. Figure 7-3. Flash Sector Organization Flash Sector Organization A sector size is 64 Kbytes Sector 0 Sector n 16 pages of 512 bytes Smaller sector 0 16 pages of 512 bytes Smaller sector 1 96 pages of 512 bytes Larger sector 128 pages of 512 bytes Flash size varies by product: SAM4N16 the Flash size is 1024 Kbytes SAM4N8 the Flash size is 512 Kbytes Figure 7-4 “Flash Size” illustrates the Flash organization by size. Figure 7-4. Flash Size Flash 1 Mbyte Flash 512 Kbytes 2 * 8 Kbytes 2 * 8 Kbytes 1 * 48 Kbytes 1 * 48 Kbytes 15 * 64 Kbytes 7 * 64 Kbytes Erasing the memory can be performed as follows: Note: On a 512-byte page inside a sector of 8 Kbytes EWP and EWPL commands can be only used in 8 Kbytes sectors. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 29 Note: Note: On a 4-Kbyte block inside a sector of 8 Kbytes/48 Kbytes/64 Kbytes Erase Page commands can be only used with FARG[1:0] = 1 On a sector of 8 Kbytes/48 Kbytes/64 Kbytes Erase Page commands can be only used with FARG[1:0] = 2 On chip The memory has one additional reprogrammable page that can be used as page signature by the user. It is accessible through specific modes, for erase, write and read operations. Erase pin assertion will not erase the User Signature page. 7.2.3.2 Enhanced Embedded Flash Controller The Enhanced Embedded Flash Controller manages accesses performed by the masters of the system. It enables reading the Flash and writing the write buffer. It also contains a User Interface, mapped on the APB. The Enhanced Embedded Flash Controller ensures the interface of the Flash block. It manages the programming, erasing, locking and unlocking sequences of the Flash using a full set of commands. One of the commands returns the embedded Flash descriptor definition that informs the system about the Flash organization, thus making the software generic. 7.2.3.3 Flash Speed The user needs to set the number of wait states depending on the frequency used: For more details, refer to Section 36.10 “AC Characteristics”. 7.2.3.4 Lock Regions Several lock bits are used to protect write and erase operations on lock regions. A lock region is composed of several consecutive pages, and each lock region has its associated lock bit. Table 7-1. Lock Bit Number Product Number of Lock Bits Lock Region Size SAM4N8 64 8 Kbytes SAM4N16 128 8 Kbytes If a locked-region’s erase or program command occurs, the command is aborted and the EEFC triggers an interrupt. The lock bits are software programmable through the EEFC User Interface. The “Set Lock Bit” command enables the protection. The “Clear Lock Bit” command unlocks the lock region. Asserting the ERASE pin clears the lock bits, thus unlocking the entire Flash. 7.2.3.5 Security Bit Feature The SAM4N8/16 features a security bit, based on a specific General Purpose NVM bit (GPNVM bit 0). When the security is enabled, any access to the Flash, SRAM, Core Registers and Internal Peripherals either through the ICE interface or through the Fast Flash Programming Interface (FFPI), is forbidden. This ensures the confidentiality of the code programmed in the Flash. This security bit can only be enabled, through the “Set General Purpose NVM Bit 0” command of the EEFC User Interface. Disabling the security bit can only be achieved by asserting the ERASE pin at 1, and after a full Flash erase is performed. When the security bit is deactivated, all accesses to the Flash, SRAM, Core Registers, Internal Peripherals are permitted. It is important to note that the assertion of the ERASE pin should always be longer than 200 ms. 30 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 As the ERASE pin integrates a permanent pull-down, it can be left unconnected during normal operation. However, it is safer to connect it directly to GND for the final application. 7.2.3.6 Calibration Bits NVM bits are used to calibrate the brownout detector and the voltage regulator. These bits are factory configured and cannot be changed by the user. The ERASE pin has no effect on the calibration bits. 7.2.3.7 Unique Identifier Each device integrates its own 128-bit unique identifier. These bits are factory configured and cannot be changed by the user. The ERASE pin has no effect on the unique identifier. 7.2.3.8 Fast Flash Programming Interface (FFPI) The FFPI allows programming the device through either a serial JTAG interface or through a multiplexed fullyhandshaked parallel port. It allows gang programming with market-standard industrial programmers. The FFPI supports read, page program, page erase, full erase, lock, unlock and protect commands. The FFPI is enabled and the Fast Programming mode is entered when TST and PA0 and PA1 are tied low. 7.2.3.9 SAM-BA Boot The SAM-BA Boot is a default Boot Program which provides an easy way to program in-situ the on-chip Flash memory. The SAM-BA Boot Assistant supports serial communication via the UART0. The SAM-BA Boot provides an interface with SAM-BA Graphic User Interface (GUI). The SAM-BA Boot is in ROM and is mapped in Flash at address 0x0 when GPNVM bit 1 is set to 0. 7.2.3.10 GPNVM Bits The SAM4N features two GPNVM bits that can be cleared or set respectively through the “Clear GPNVM Bit” and “Set GPNVM Bit” commands of the EEFC User Interface. Table 7-2. 7.2.4 General-purpose Non-volatile Memory Bits GPNVM Bit[#] Function 0 Security bit 1 Boot mode selection Boot Strategies The system always boots at address 0x0. To ensure a maximum boot possibilities the memory layout can be changed via GPNVM. A General Purpose NVM (GPNVM) bit is used to boot either on the ROM (default) or from the Flash. The GPNVM bit can be cleared or set respectively through the "Clear General-purpose NVM Bit" and "Set General-purpose NVM Bit" commands of the EEFC User Interface. Setting the GPNVM Bit 1 selects the boot from the Flash, clearing it selects the boot from the ROM. Asserting ERASE clears the GPNVM Bit 1 and thus selects the boot from the ROM by default. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 31 8. Real-time Event Management The events generated by peripherals are designed to be directly routed to peripherals managing/using these events without processor intervention. Peripherals receiving events contain logic by which to determine and perform the action required. 8.1 8.2 Embedded Characteristics Timers, IO peripherals generate event triggers which are directly routed to event managers such as ADC, DACC, for example, to start measurement/conversion without processor intervention. UART, USART, SPI, TWI, ADC, DACC, PIO also generate event triggers directly connected to Peripheral DMA Controller (PDC) for data transfer without processor intervention. PMC security event (clock failure detection) can be programmed to switch the MCK on reliable main RC internal clock without processor intervention. Real-time Event Mapping List Table 8-1. 32 Real-time Event Mapping List Event Generator Event Manager IO (WKUP0/1) General Purpose Backup Register (GPBR) Power Management Controller (PMC) PMC IO (ADTRG) Analog-to-Digital Converter (ADC) Trigger for measurement. Selection in ADC module TC Output 0 ADC Trigger for measurement. Selection in ADC module TC Output 1 ADC Trigger for measurement. Selection in ADC module TC Output 2 ADC Trigger for measurement. Selection in ADC module IO (DATRG) Digital-Analog Converter Controller (DACC) Trigger for conversion. Selection in DAC module TC Output 0 DACC Trigger for conversion. Selection in DAC module TC Output 1 DACC Trigger for conversion. Selection in DAC module TC Output 2 DACC Trigger for conversion. Selection in DAC module SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Function Security / Immediate GPBR clear (asynchronous) on tamper detection through WKUP0/1 IO pins Safety / Automatic switch to reliable main RC oscillator in case of main crystal clock failure 9. System Controller The System Controller is a set of peripherals which allow handling of key elements of the system, such as but not limited to power, resets, clocks, time, interrupts, and watchdog. 9.1 System Controller and Peripherals Mapping Please refer to Figure 7-1 “SAM4N8/16 Product Mapping”. All the peripherals are in the bit band region and are mapped in the bit band alias region. 9.2 Power-on-Reset, Brownout and Supply Monitor The SAM4N embeds three features to monitor, warn and/or reset the chip: 9.2.1 Power-on-Reset on VDDIO Brownout Detector on VDDCORE Supply Monitor on VDDIO Power-on-Reset on VDDIO The Power-on-Reset monitors VDDIO. It is always activated and monitors voltage at startup but also during power down. If VDDIO goes below the threshold voltage, the entire chip is reset. For more information, refer to Section 36. “SAM4N Electrical Characteristics”. 9.2.2 Brownout Detector on VDDCORE The Brownout Detector monitors VDDCORE. It is active by default. It can be deactivated by software through the Supply Controller Mode Register (SUPC_MR). It is especially recommended to disable it during low-power modes such as wait or sleep modes. If VDDCORE goes below the threshold voltage, the reset of the core is asserted. For more information, refer to Section 17. “Supply Controller (SUPC)” and Section 36. “SAM4N Electrical Characteristics”. 9.2.3 Supply Monitor on VDDIO The Supply Monitor monitors VDDIO. It is not active by default. It can be activated by software and is fully programmable with 16 steps for the threshold (between 1.6V to 3.4V). It is controlled by the Supply Controller (SUPC). A sample mode is possible. It allows to divide the supply monitor power consumption by a factor of up to 2048. For more information, refer to Section 17. “Supply Controller (SUPC)” and Section 36. “SAM4N Electrical Characteristics”. 9.3 SysTick Timer 24-bit down counter Self-reload capability Flexible system timer SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 33 10. Peripherals 10.1 Peripheral Identifiers Table 10-1 defines the peripheral identifiers of the SAM4N8/16. A peripheral identifier is required for the control of the peripheral interrupt with the Nested Vectored Interrupt Controller and for the control of the peripheral clock with the Power Management Controller. Table 10-1. Peripheral Identifiers Instance ID Instance Name NVIC Interrupt 0 SUPC X Supply Controller 1 RSTC X Reset Controller 2 RTC X Real-time Clock 3 RTT X Real-time Timer 4 WDT X Watchdog Timer 5 PMC X Power Management Controller 6 EFC X Enhanced Flash Controller 7 – – – Reserved 8 UART0 X X Universal Asynchronous Receiver Transmitter 0 9 UART1 X X Universal Asynchronous Receiver Transmitter 1 10 UART2 X X Universal Asynchronous Receiver Transmitter 2 11 PIOA X X Parallel I/O Controller A 12 PIOB X X Parallel I/O Controller B 13 PIOC X X Parallel I/O Controller C 14 USART0 X X Universal Synchronous Asynchronous Receiver Transmitter 0 15 USART1 X X Universal Synchronous Asynchronous Receiver Transmitter 1 16 UART3 X X Universal Asynchronous Receiver Transmitter 3 17 USART2 X X Universal Synchronous Asynchronous Receiver Transmitter 2 18 – – – Reserved 19 TWI0 X X Two-wire Interface 0 20 TWI1 X X Two-wire Interface 1 21 SPI X X Serial Peripheral Interface 22 TWI2 X X Two-wire Interface 2 23 TC0 X X Timer Counter Channel 0 24 TC1 X X Timer Counter Channel 1 25 TC2 X X Timer Counter Channel 2 26 TC3 X X Timer Counter Channel 3 27 TC4 X X Timer Counter Channel 4 28 TC5 X X Timer Counter Channel 5 34 PMC Clock Control SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Instance Description Table 10-1. Peripheral Identifiers (Continued) Instance ID Instance Name NVIC Interrupt PMC Clock Control 29 ADC X X Analog-to-Digital Converter 30 DACC X X Digital-to-Analog Converter Controller 31 PWM X X Pulse Width Modulation Instance Description SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 35 10.2 Peripherals Signals Multiplexing on I/O Lines The SAM4N8/16 product features two PIO (48-pin and 64-pin version) or three PIO (100-pin version) controllers, PIOA, PIOB and PIOC, which multiplex the I/O lines of the peripheral set. Each PIO Controller controls up to 32 lines. Each line can be assigned to one of three peripheral functions: A, B or C. The following multiplexing tables define how the I/O lines of the peripherals A, B and C are multiplexed on the PIO controllers. Note that some output-only peripheral functions might be duplicated within the tables. 36 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 10.2.1 PIO Controller A Multiplexing Table 10-2. I/O Line PA0 Multiplexing on PIO Controller A (PIOA) Peripheral A PWM0 Peripheral B Peripheral C TIOA0 PA1 PWM1 TIOB0 PA2 PWM2 SCK0 PA3 TWD0 NPCS3 DATRG Extra Function System Function Comments WKUP0 (1) High Drive WKUP1 (1) High Drive WKUP2(1) High Drive High Drive (1) PA4 TWCK0 TCLK0 WKUP3 PA5 RXD0 NPCS3 WKUP4(1) PA6 TXD0 PCK0 PA7 RTS0 PWM3 PA8 CTS0 ADTRG WKUP5(1) PA9 URXD0 NPCS1 WKUP6(1) PA10 UTXD0 NPCS2 PA11 NPCS0 PWM0 PA12 MISO PWM1 PA13 MOSI PWM2 PA14 SPCK PWM3 WKUP8(1) PA15 UTXD2 TIOA1 WKUP14(1) PA16 URXD2 TIOB1 WKUP15(1) PA17 PCK1 AD0(3) PA18 PCK2 AD1(3) XIN32(2) XOUT32(2) WKUP7(1) PA19 AD2/WKUP9(4) PA20 AD3/WKUP10(4) PA21 RXD1 PCK1 AD8(3) 64/100 pins versions PA22 TXD1 NPCS3 AD9(3) 64/100 pins versions PA23 SCK1 PWM0 64/100 pins versions PA24 RTS1 PWM1 64/100 pins versions PA25 CTS1 PWM2 64/100 pins versions PA26 TIOA2 64/100 pins versions PA27 TIOB2 64/100 pins versions PA28 TCLK1 64/100 pins versions PA29 TCLK2 64/100 pins versions PA30 NPCS2 PA31 Notes: NPCS1 1. 2. 3. 4. WKUP11(1) PCK2 64/100 pins versions 64/100 pins versions WKUPx can be used if PIO controller defines the I/O line as "input". Refer to Section 6.2 “System I/O Lines”. To select this extra function, refer to Section 34.5.3 “Analog Inputs”. Analog input has priority over WKUPx pin. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 37 10.2.2 PIO Controller B Multiplexing Table 10-3. I/O Line Multiplexing on PIO Controller B (PIOB) Peripheral A Peripheral B Peripheral C Extra Function System Function PB0 PWM0 TWD2 PB1 PWM1 TWCK2 AD5(1) PB2 URXD1 NPCS2 AD6/WKUP12(2) PB3 UTXD1 PCK2 AD7(1) PB4 TWD1 PWM2 PB5 TWCK1 AD4 TDI(3) WKUP13(4) TDO/TRACESWO(3) PB6 TMS/SWDIO(3) PB7 TCK/SWCLK(3) PB8 XOUT(3) PB9 XIN(3) PB10 URXD3 PB11 UTXD3 ERASE(3) PB12 PB13 PCK0 PB14 Notes: 38 Comments (1) NPCS1 1. 2. 3. 4. 5. DAC0(5) PWM3 To select this extra function, refer to Section 34.5.3 “Analog Inputs”. Analog input has priority over WKUPx pin. Refer to Section 6.2 “System I/O Lines”. WKUPx can be used if PIO controller defines the I/O line as "input". DAC0 is enabled when DACC_MR.DACEN is set. See Section 35.7.2 “DACC Mode Register”. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 64/100 pins versions 64/100 pins versions 10.2.3 PIO Controller C Multiplexing Table 10-4. I/O Line Multiplexing on PIO Controller C (PIOC) Peripheral A Peripheral B Peripheral C Extra Function System Function Comments PC0 100 pins version PC1 100 pins version PC2 100 pins version PC3 100 pins version PC4 NPCS1 100 pins version PC5 100 pins version PC6 100 pins version PC7 NPCS2 100 pins version PC8 PWM0 100 pins version PC9 RXD2 PWM1 100 pins version PC10 TXD2 PWM2 100 pins version PC11 PWM3 PC12 PC13 PC14 SCK2 100 pins version AD12 (1) 100 pins version AD10 (1) 100 pins version PCK2 100 pins version (1) PC15 AD11 100 pins version PC16 RTS2 PCK0 100 pins version PC17 CTS2 PCK1 100 pins version PC18 PWM0 100 pins version PC19 PWM1 100 pins version PC20 PWM2 100 pins version PC21 PWM3 100 pins version PC22 PWM0 100 pins version PC23 TIOA3 100 pins version PC24 TIOB3 100 pins version PC25 TCLK3 100 pins version PC26 TIOA4 100 pins version PC27 TIOB4 100 pins version PC28 TCLK4 100 pins version (1) 100 pins version PC29 TIOA5 AD13 PC30 TIOB5 AD14(1) 100 pins version TCLK5 (1) 100 pins version PC31 Notes: AD15 1. To select this extra function, refer to Section 34.5.3 “Analog Inputs”. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 39 10.3 Embedded Peripherals Overview 10.3.1 Analog Mux The Analog Mux is used to enable any of the 16 ADC analog inputs and the temperature sensor by means of the ADC Channel Enable Register (ADC_CHER). The temperature sensor is internally connected to the 17th input of the analog mux. 10.3.2 Voltage Reference Block The ADC/DAC cell features one internal voltage reference block 3V typ., 2V to 3.6V supply voltage operation Power by analog power supply voltage 20 µA typ. current consumption 4 bits trimmable output value from 1.6V to 3.4V, 121 mV steps 3 bits trimmable temperature compensation Low noise in the 10 Hz–100 kHz bandwidth (-74 dBV typ.), usable for a 10-bit ADC reference PSRR DC higher than 60 dB typ. 3.6 kΩ/100 nF load availability Sense pin for VREF output Only one external component needed (100 nF decoupling) Direct reference connection to the supply voltage possible using force control pin Level shifters with reset included (for digital supply detection flat) Five output currents available (one 1 µA, three 2 µA and one 10 µA PTAT sourced form analog power supply) and can be activated independently from the VREF buffer 10.3.3 Peripheral DMA Controller (PDC) Handles data transfer between peripherals and memories Twenty-three channels ̶ Six for USART0/1/2 ̶ Six for the UART0/1/2 ̶ Six for Two-wire Interface (TWI0/1/2) ̶ Two for Serial Peripheral Interface (SPI) ̶ One for Timer Counter 0 ̶ One for Analog-to-Digital Converter ̶ One for the Digital-to-Analog Converter Low bus arbitration overhead ̶ One Master Clock cycle needed for a transfer from memory to peripheral ̶ Two Master Clock cycles needed for a transfer from peripheral to memory Next pointer management for reducing interrupt latency requirement The PDC handles transfer requests from the channel according to the priorities (low to high priorities) defined in Table 10-5. 40 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Table 10-5. Peripheral DMA Controller Instance Name Channel T/R TWI0 Transmit TWI1 Transmit TWI2 Transmit UART0 Transmit UART1 Transmit UART2 Transmit USART0 Transmit USART1 Transmit USART2 Transmit DACC Transmit SPI Transmit TC0–TC2 Receive TWI0 Receive TWI1 Receive TWI2 Receive UART0 Receive UART1 Receive UART2 Receive USART0 Receive USART1 Receive USART2 Receive ADC Receive SPI Receive SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 41 11. ARM Cortex-M4 11.1 Description The Cortex-M4 processor is a high performance 32-bit processor designed for the microcontroller market. It offers significant benefits to developers, including outstanding processing performance combined with fast interrupt handling, enhanced system debug with extensive breakpoint and trace capabilities, efficient processor core, system and memories, ultra-low power consumption with integrated sleep modes, and platform security robustness, with integrated memory protection unit (MPU). The Cortex-M4 processor is built on a high-performance processor core, with a 3-stage pipeline Harvard architecture, making it ideal for demanding embedded applications. The processor delivers exceptional power efficiency through an efficient instruction set and extensively optimized design, providing high-end processing hardware including a range of single-cycle and SIMD multiplication and multiply-with-accumulate capabilities, saturating arithmetic and dedicated hardware division. To facilitate the design of cost-sensitive devices, the Cortex-M4 processor implements tightly-coupled system components that reduce processor area while significantly improving interrupt handling and system debug capabilities. The Cortex-M4 processor implements a version of the Thumb® instruction set based on Thumb-2 technology, ensuring high code density and reduced program memory requirements. The Cortex-M4 instruction set provides the exceptional performance expected of a modern 32-bit architecture, with the high code density of 8-bit and 16-bit microcontrollers. The Cortex-M4 processor closely integrates a configurable NVIC, to deliver industry-leading interrupt performance. The NVIC includes a non-maskable interrupt (NMI), and provides up to 256 interrupt priority levels. The tight integration of the processor core and NVIC provides fast execution of interrupt service routines (ISRs), dramatically reducing the interrupt latency. This is achieved through the hardware stacking of registers, and the ability to suspend load-multiple and store-multiple operations. Interrupt handlers do not require wrapping in assembler code, removing any code overhead from the ISRs. A tail-chain optimization also significantly reduces the overhead when switching from one ISR to another. To optimize low-power designs, the NVIC integrates with the sleep modes, that include a deep sleep function that enables the entire device to be rapidly powered down while still retaining program state. 11.1.1 System Level Interface The Cortex-M4 processor provides multiple interfaces using AMBA® technology to provide high speed, low latency memory accesses. It supports unaligned data accesses and implements atomic bit manipulation that enables faster peripheral controls, system spinlocks and thread-safe Boolean data handling. The Cortex-M4 processor has a Memory Protection Unit (MPU) that provides fine grain memory control, enabling applications to utilize multiple privilege levels, separating and protecting code, data and stack on a task-by-task basis. Such requirements are becoming critical in many embedded applications such as automotive. 11.1.2 Integrated Configurable Debug The Cortex-M4 processor implements a complete hardware debug solution. This provides high system visibility of the processor and memory through either a traditional JTAG port or a 2-pin Serial Wire Debug (SWD) port that is ideal for microcontrollers and other small package devices. For system trace the processor integrates an Instrumentation Trace Macrocell (ITM) alongside data watchpoints and a profiling unit. To enable simple and cost-effective profiling of the system events these generate, a Serial Wire Viewer (SWV) can export a stream of software-generated messages, data trace, and profiling information through a single pin. The Flash Patch and Breakpoint Unit (FPB) provides up to 8 hardware breakpoint comparators that debuggers can use. The comparators in the FPB also provide remap functions of up to 8 words in the program code in the CODE 42 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 memory region. This enables applications stored on a non-erasable, ROM-based microcontroller to be patched if a small programmable memory, for example flash, is available in the device. During initialization, the application in ROM detects, from the programmable memory, whether a patch is required. If a patch is required, the application programs the FPB to remap a number of addresses. When those addresses are accessed, the accesses are redirected to a remap table specified in the FPB configuration, which means the program in the non-modifiable ROM can be patched. 11.2 Embedded Characteristics Tight integration of system peripherals reduces area and development costs Thumb instruction set combines high code density with 32-bit performance Code-patch ability for ROM system updates Power control optimization of system components Integrated sleep modes for low power consumption Fast code execution permits slower processor clock or increases sleep mode time Hardware division and fast digital-signal-processing oriented multiply accumulate Saturating arithmetic for signal processing Deterministic, high-performance interrupt handling for time-critical applications Memory Protection Unit (MPU) for safety-critical applications Extensive debug and trace capabilities: ̶ 11.3 Serial Wire Debug and Serial Wire Trace reduce the number of pins required for debugging, tracing, and code profiling. Block Diagram Figure 11-1. TTypical Cortex-M4 Implementation Cortex-M4 Processor NVIC Debug Access Port Processor Core Serial Wire Viewer Memory Protection Unit Flash Patch Data Watchpoints Bus Matrix Code Interface SRAM and Peripheral Interface SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 43 11.4 Cortex-M4 Models 11.4.1 Programmers Model This section describes the Cortex-M4 programmers model. In addition to the individual core register descriptions, it contains information about the processor modes and privilege levels for software execution and stacks. 11.4.1.1 Processor Modes and Privilege Levels for Software Execution The processor modes are: Thread mode Used to execute application software. The processor enters the Thread mode when it comes out of reset. Handler mode Used to handle exceptions. The processor returns to the Thread mode when it has finished exception processing. The privilege levels for software execution are: Unprivileged The software: ̶ Has limited access to the MSR and MRS instructions, and cannot use the CPS instruction ̶ Cannot access the System Timer, NVIC, or System Control Block ̶ Might have a restricted access to memory or peripherals. Unprivileged software executes at the unprivileged level. Privileged The software can use all the instructions and has access to all resources. Privileged software executes at the privileged level. In Thread mode, the CONTROL register controls whether the software execution is privileged or unprivileged, see “CONTROL Register” . In Handler mode, software execution is always privileged. Only privileged software can write to the CONTROL register to change the privilege level for software execution in Thread mode. Unprivileged software can use the SVC instruction to make a supervisor call to transfer control to privileged software. 11.4.1.2 Stacks The processor uses a full descending stack. This means the stack pointer holds the address of the last stacked item in memory When the processor pushes a new item onto the stack, it decrements the stack pointer and then writes the item to the new memory location. The processor implements two stacks, the main stack and the process stack, with a pointer for each held in independent registers, see “Stack Pointer” . In Thread mode, the CONTROL register controls whether the processor uses the main stack or the process stack, see “CONTROL Register” . In Handler mode, the processor always uses the main stack. The options for processor operations are: Table 11-1. Summary of processor mode, execution privilege level, and stack use options Processor Mode Privilege Level for Software Execution Thread Applications Privileged or unprivileged Handler Exception handlers Always privileged Note: 44 Used to Execute 1. See “CONTROL Register” . SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Stack Used (1) Main stack or process stack(1) Main stack 11.4.1.3 Core Registers Figure 11-2. Processor Core Registers R0 R1 R2 R3 Low registers R4 R5 R6 General-purpose registers R7 R8 R9 High registers R10 R11 R12 Stack Pointer SP (R13) Link Register LR (R14) Program Counter PC (R15) PSR PSP‡ MSP‡ ‡ Banked version of SP Program status register PRIMASK FAULTMASK Exception mask registers Special registers BASEPRI CONTROL Table 11-2. CONTROL register Core Processor Registers Register Name Access(1) Required Privilege(2) Reset General-purpose registers R0-R12 Read-write Either Unknown Stack Pointer MSP Read-write Privileged See description Stack Pointer PSP Read-write Either Unknown Link Register LR Read-write Either 0xFFFFFFFF Program Counter PC Read-write Either See description Program Status Register PSR Read-write Privileged 0x01000000 Application Program Status Register APSR Read-write Either 0x00000000 Interrupt Program Status Register IPSR Read-only Privileged 0x00000000 Execution Program Status Register EPSR Read-only Privileged 0x01000000 Priority Mask Register PRIMASK Read-write Privileged 0x00000000 Fault Mask Register FAULTMASK Read-write Privileged 0x00000000 Base Priority Mask Register BASEPRI Read-write Privileged 0x00000000 CONTROL register CONTROL Read-write Privileged 0x00000000 Notes: 1. Describes access type during program execution in thread mode and Handler mode. Debug access can differ. 2. An entry of Either means privileged and unprivileged software can access the register. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 45 11.4.1.4 General-purpose Registers R0-R12 are 32-bit general-purpose registers for data operations. 11.4.1.5 Stack Pointer The Stack Pointer (SP) is register R13. In Thread mode, bit[1] of the CONTROL register indicates the stack pointer to use: 0 = Main Stack Pointer (MSP). This is the reset value. 1 = Process Stack Pointer (PSP). On reset, the processor loads the MSP with the value from address 0x00000000. 11.4.1.6 Link Register The Link Register (LR) is register R14. It stores the return information for subroutines, function calls, and exceptions. On reset, the processor loads the LR value 0xFFFFFFFF. 11.4.1.7 Program Counter The Program Counter (PC) is register R15. It contains the current program address. On reset, the processor loads the PC with the value of the reset vector, which is at address 0x00000004. Bit[0] of the value is loaded into the EPSR T-bit at reset and must be 1. 46 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.4.1.8 Program Status Register Name: PSR Access: Read-write Reset: 0x000000000 31 N 30 Z 29 C 28 V 27 Q 26 23 22 21 20 25 24 T 19 18 17 16 12 11 10 9 – 8 ISR_NUMBER 4 3 2 1 0 ICI/IT – 15 14 13 ICI/IT 7 6 5 ISR_NUMBER The Program Status Register (PSR) combines: Application Program Status Register (APSR) Interrupt Program Status Register (IPSR) Execution Program Status Register (EPSR). These registers are mutually exclusive bitfields in the 32-bit PSR. The PSR register accesses these registers individually or as a combination of any two or all three registers, using the register name as an argument to the MSR or MRS instructions. For example: Read of all the registers using PSR with the MRS instruction Write to the APSR N, Z, C, V and Q bits using APSR_nzcvq with the MSR instruction. The PSR combinations and attributes are: Name Access Combination (1)(2) PSR Read-write APSR, EPSR, and IPSR IEPSR Read-only EPSR and IPSR IAPSR Read-write(1) EAPSR Notes: (2) Read-write APSR and IPSR APSR and EPSR 1. The processor ignores writes to the IPSR bits. 2. Reads of the EPSR bits return zero, and the processor ignores writes to these bits See the instruction descriptions “MRS” and “MSR” for more information about how to access the program status registers. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 47 11.4.1.9 Application Program Status Register Name: APSR Access: Read-write Reset: 0x000000000 31 N 30 Z 23 22 29 C 28 V 27 Q 26 21 20 19 18 – 15 14 25 – 24 17 16 GE[3:0] 13 12 11 10 9 8 3 2 1 0 – 7 6 5 4 – The APSR contains the current state of the condition flags from previous instruction executions. • N: Negative Flag 0: Operation result was positive, zero, greater than, or equal 1: Operation result was negative or less than. • Z: Zero Flag 0: Operation result was not zero 1: Operation result was zero. • C: Carry or Borrow Flag Carry or borrow flag: 0: Add operation did not result in a carry bit or subtract operation resulted in a borrow bit 1: Add operation resulted in a carry bit or subtract operation did not result in a borrow bit. • V: Overflow Flag 0: Operation did not result in an overflow 1: Operation resulted in an overflow. • Q: DSP Overflow and Saturation Flag Sticky saturation flag: 0: Indicates that saturation has not occurred since reset or since the bit was last cleared to zero 1: Indicates when an SSAT or USAT instruction results in saturation. This bit is cleared to zero by software using an MRS instruction. • GE[19:16]: Greater Than or Equal Flags See “SEL” for more information. 48 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.4.1.10 Interrupt Program Status Register Name: IPSR Access: Read-write Reset: 0x000000000 31 30 29 28 27 26 25 24 19 18 17 16 – 23 22 21 20 – 15 14 13 12 – 11 10 9 8 ISR_NUMBER 7 6 5 4 3 2 1 0 ISR_NUMBER The IPSR contains the exception type number of the current Interrupt Service Routine (ISR). • ISR_NUMBER: Number of the Current Exception 0 = Thread mode 1 = Reserved 2 = NMI 3 = Hard fault 4 = Memory management fault 5 = Bus fault 6 = Usage fault 7-10 = Reserved 11 = SVCall 12 = Reserved for Debug 13 = Reserved 14 = PendSV 15 = SysTick 16 = IRQ0 45 = IRQ29 See “Exception Types” for more information. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 49 11.4.1.11 Execution Program Status Register Name: EPSR Access: Read-write Reset: 0x000000000 31 30 23 22 29 – 28 21 20 27 26 25 24 T 16 ICI/IT 19 18 17 11 10 9 – 15 14 13 12 ICI/IT 7 6 5 8 – 4 3 2 1 0 – The EPSR contains the Thumb state bit, and the execution state bits for either the If-Then (IT) instruction, or the Interruptible-Continuable Instruction (ICI) field for an interrupted load multiple or store multiple instruction. Attempts to read the EPSR directly through application software using the MSR instruction always return zero. Attempts to write the EPSR using the MSR instruction in the application software are ignored. Fault handlers can examine the EPSR value in the stacked PSR to indicate the operation that is at fault. See “Exception Entry and Return” • ICI: Interruptible-continuable Instruction When an interrupt occurs during the execution of an LDM, STM, PUSH, POP, VLDM, VSTM, VPUSH, or VPOP instruction, the processor: – Stops the load multiple or store multiple instruction operation temporarily – Stores the next register operand in the multiple operation to EPSR bits[15:12]. After servicing the interrupt, the processor: – Returns to the register pointed to by bits[15:12] – Resumes the execution of the multiple load or store instruction. When the EPSR holds the ICI execution state, bits[26:25,11:10] are zero. • IT: If-Then Instruction Indicates the execution state bits of the IT instruction. The If-Then block contains up to four instructions following an IT instruction. Each instruction in the block is conditional. The conditions for the instructions are either all the same, or some can be the inverse of others. See “IT” for more information. • T: Thumb State The Cortex-M4 processor only supports the execution of instructions in Thumb state. The following can clear the T bit to 0: – Instructions BLX, BX and POP{PC} – Restoration from the stacked xPSR value on an exception return – Bit[0] of the vector value on an exception entry or reset. Attempting to execute instructions when the T bit is 0 results in a fault or lockup. See “Lockup” for more information. 50 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.4.1.12 Exception Mask Registers The exception mask registers disable the handling of exceptions by the processor. Disable exceptions where they might impact on timing critical tasks. To access the exception mask registers use the MSR and MRS instructions, or the CPS instruction to change the value of PRIMASK or FAULTMASK. See “MRS” , “MSR” , and “CPS” for more information. 11.4.1.13 Priority Mask Register Name: PRIMASK Access: Read-write Reset: 0x000000000 31 30 29 28 27 26 25 24 19 18 17 16 11 10 9 8 3 2 1 0 PRIMASK – 23 22 21 20 – 15 14 13 12 – 7 6 5 4 – The PRIMASK register prevents the activation of all exceptions with a configurable priority. • PRIMASK 0: No effect 1: Prevents the activation of all exceptions with a configurable priority. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 51 11.4.1.14 Fault Mask Register Name: FAULTMASK Access: Read-write Reset: 0x000000000 31 30 29 28 27 26 25 24 19 18 17 16 11 10 9 8 3 2 1 0 FAULTMASK – 23 22 21 20 – 15 14 13 12 – 7 6 5 4 – The FAULTMASK register prevents the activation of all exceptions except for Non-Maskable Interrupt (NMI). • FAULTMASK 0: No effect. 1: Prevents the activation of all exceptions except for NMI. The processor clears the FAULTMASK bit to 0 on exit from any exception handler except the NMI handler. 52 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.4.1.15 Base Priority Mask Register Name: BASEPRI Access: Read-write Reset: 0x000000000 31 30 29 28 27 26 25 24 19 18 17 16 11 10 9 8 3 2 1 0 – 23 22 21 20 – 15 14 13 12 – 7 6 5 4 BASEPRI The BASEPRI register defines the minimum priority for exception processing. When BASEPRI is set to a nonzero value, it prevents the activation of all exceptions with same or lower priority level as the BASEPRI value. • BASEPRI Priority mask bits: 0x0000 = No effect. Nonzero = Defines the base priority for exception processing. The processor does not process any exception with a priority value greater than or equal to BASEPRI. This field is similar to the priority fields in the interrupt priority registers. The processor implements only bits[7:4] of this field, bits[3:0] read as zero and ignore writes. See “Interrupt Priority Registers” for more information. Remember that higher priority field values correspond to lower exception priorities. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 53 11.4.1.16 CONTROL Register Name: CONTROL Access: Read-write Reset: 0x000000000 31 30 29 28 27 26 25 24 19 18 17 16 11 10 9 8 3 2 – 1 SPSEL 0 nPRIV – 23 22 21 20 – 15 14 13 12 – 7 6 5 – 4 The CONTROL register controls the stack used and the privilege level for software execution when the processor is in Thread mode. • SPSEL: Active Stack Pointer Defines the current stack: 0: MSP is the current stack pointer. 1: PSP is the current stack pointer. In Handler mode, this bit reads as zero and ignores writes. The Cortex-M4 updates this bit automatically on exception return. • nPRIV: Thread Mode Privilege Level Defines the Thread mode privilege level: 0: Privileged. 1: Unprivileged. Handler mode always uses the MSP, so the processor ignores explicit writes to the active stack pointer bit of the CONTROL register when in Handler mode. The exception entry and return mechanisms update the CONTROL register based on the EXC_RETURN value. In an OS environment, ARM recommends that threads running in Thread mode use the process stack, and the kernel and exception handlers use the main stack. By default, the Thread mode uses the MSP. To switch the stack pointer used in Thread mode to the PSP, either: • Use the MSR instruction to set the Active stack pointer bit to 1, see “MSR” , or • Perform an exception return to Thread mode with the appropriate EXC_RETURN value, see Table 11-10. Note: When changing the stack pointer, the software must use an ISB instruction immediately after the MSR instruction. This ensures that instructions after the ISB execute using the new stack pointer. See “ISB” . 54 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.4.1.17 Exceptions and Interrupts The Cortex-M4 processor supports interrupts and system exceptions. The processor and the Nested Vectored Interrupt Controller (NVIC) prioritize and handle all exceptions. An exception changes the normal flow of software control. The processor uses the Handler mode to handle all exceptions except for reset. See “Exception Entry” and “Exception Return” for more information. The NVIC registers control interrupt handling. See “Nested Vectored Interrupt Controller (NVIC)” for more information. 11.4.1.18 Data Types The processor supports the following data types: 32-bit words 16-bit halfwords 8-bit bytes The processor manages all data memory accesses as little-endian. Instruction memory and Private Peripheral Bus (PPB) accesses are always little-endian. See “Memory Regions, Types and Attributes” for more information. 11.4.1.19 Cortex Microcontroller Software Interface Standard (CMSIS) For a Cortex-M4 microcontroller system, the Cortex Microcontroller Software Interface Standard (CMSIS) defines: A common way to: ̶ Access peripheral registers ̶ Define exception vectors The names of: ̶ The registers of the core peripherals ̶ The core exception vectors A device-independent interface for RTOS kernels, including a debug channel. The CMSIS includes address definitions and data structures for the core peripherals in the Cortex-M4 processor. The CMSIS simplifies the software development by enabling the reuse of template code and the combination of CMSIS-compliant software components from various middleware vendors. Software vendors can expand the CMSIS to include their peripheral definitions and access functions for those peripherals. This document includes the register names defined by the CMSIS, and gives short descriptions of the CMSIS functions that address the processor core and the core peripherals. Note: This document uses the register short names defined by the CMSIS. In a few cases, these differ from the architectural short names that might be used in other documents. The following sections give more information about the CMSIS: Section 11.5.3 “Power Management Programming Hints” Section 11.6.2 “CMSIS Functions” Section 11.8.2.1 “NVIC Programming Hints”. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 55 11.4.2 Memory Model This section describes the processor memory map, the behavior of memory accesses, and the bit-banding features. The processor has a fixed memory map that provides up to 4GB of addressable memory. Figure 11-3. Memory Map 0xFFFFFFFF Vendor-specific memory 511MB Private peripheral 1.0MB bus External device 0xE0100000 0xE00FFFFF 0xE000 0000 0x DFFFFFFF 1.0GB 0xA0000000 0x9FFFFFFF External RAM 0x43FFFFFF 1.0GB 32 MB Bit band alias 0x60000000 0x5FFFFFFF 0x42000000 0x400FFFFF 0x40000000 Peripheral 0.5GB 1 MB Bit Band region 0x40000000 0x3FFFFFFF 0x23FFFFFF 32 MB Bit band alias SRAM 0.5GB 0x20000000 0x1FFFFFFF 0x22000000 Code 0x200FFFFF 0x20000000 1 MB Bit Band region 0.5GB 0x00000000 The regions for SRAM and peripherals include bit-band regions. Bit-banding provides atomic operations to bit data, see “Bit-banding” . The processor reserves regions of the Private peripheral bus (PPB) address range for core peripheral registers. This memory mapping is generic to ARM Cortex-M4 products. To get the specific memory mapping of this product, refer to the Memories section of the datasheet. 56 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.4.2.1 Memory Regions, Types and Attributes The memory map and the programming of the MPU split the memory map into regions. Each region has a defined memory type, and some regions have additional memory attributes. The memory type and attributes determine the behavior of accesses to the region. Memory Types Normal The processor can re-order transactions for efficiency, or perform speculative reads. Device The processor preserves transaction order relative to other transactions to Device or Strongly-ordered memory. Strongly-ordered The processor preserves transaction order relative to all other transactions. The different ordering requirements for Device and Strongly-ordered memory mean that the memory system can buffer a write to Device memory, but must not buffer a write to Strongly-ordered memory. Additional Memory Attributes Shareable For a shareable memory region, the memory system provides data synchronization between bus masters in a system with multiple bus masters, for example, a processor with a DMA controller. Strongly-ordered memory is always shareable. If multiple bus masters can access a non-shareable memory region, the software must ensure data coherency between the bus masters. Execute Never (XN) Means the processor prevents instruction accesses. A fault exception is generated only on execution of an instruction executed from an XN region. 11.4.2.2 Memory System Ordering of Memory Accesses For most memory accesses caused by explicit memory access instructions, the memory system does not guarantee that the order in which the accesses complete matches the program order of the instructions, providing this does not affect the behavior of the instruction sequence. Normally, if correct program execution depends on two memory accesses completing in program order, the software must insert a memory barrier instruction between the memory access instructions, see “Software Ordering of Memory Accesses” . However, the memory system does guarantee some ordering of accesses to Device and Strongly-ordered memory. For two memory access instructions A1 and A2, if A1 occurs before A2 in program order, the ordering of the memory accesses is described below. Table 11-3. Ordering of the Memory Accesses Caused by Two Instructions A2 Device Access Normal Access Non-shareable Shareable Strongly-ordered Access Normal Access – – – – Device access, non-shareable – < – < Device access, shareable – – < < Strongly-ordered access – < < < A1 Where: – Means that the memory system does not guarantee the ordering of the accesses. < Means that accesses are observed in program order, that is, A1 is always observed before A2. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 57 11.4.2.3 Behavior of Memory Accesses The behavior of accesses to each region in the memory map is: Table 11-4. Memory Access Behavior Address Range Memory Region Memory Type XN Description 0x00000000 - 0x1FFFFFFF Code Normal(1) - Executable region for program code. Data can also be put here. 0x20000000 - 0x3FFFFFFF SRAM Normal (1) - 0x40000000 - 0x5FFFFFFF Peripheral Device (1) XN This region includes bit band and bit band alias areas, see Table 11-6. 0x60000000 - 0x9FFFFFFF External RAM Normal (1) - Executable region for data. XN External Device memory Executable region for data. Code can also be put here. (1) This region includes bit band and bit band alias areas, see Table 11-6. 0xA0000000 - 0xDFFFFFFF External device Device 0xE0000000 - 0xE00FFFFF Private Peripheral Bus Stronglyordered (1) XN This region includes the NVIC, System timer, and system control block. 0xE0100000 - 0xFFFFFFFF Reserved Device (1) XN Reserved Note: 1. See “Memory Regions, Types and Attributes” for more information. The Code, SRAM, and external RAM regions can hold programs. However, ARM recommends that programs always use the Code region. This is because the processor has separate buses that enable instruction fetches and data accesses to occur simultaneously. The MPU can override the default memory access behavior described in this section. For more information, see “Memory Protection Unit (MPU)” . Additional Memory Access Constraints For Shared Memory When a system includes shared memory, some memory regions have additional access constraints, and some regions are subdivided, as Table 11-5 shows: Table 11-5. Memory Region Shareability Policies Address Range Memory Region Memory Type Shareability 0x00000000- 0x1FFFFFFF Code Normal (1) - (2) 0x20000000- 0x3FFFFFFF SRAM Normal (1) - (2) 0x40000000- 0x5FFFFFFF Peripheral Device (1) - External RAM Normal (1) - External device Device (1) 0xE0000000- 0xE00FFFFF Private Peripheral Bus Strongly- ordered(1) Shareable (1) - 0xE0100000- 0xFFFFFFFF Vendor-specific device Device (1) - - 0x60000000- 0x7FFFFFFF WBWA (2) 0x80000000- 0x9FFFFFFF 0xA0000000- 0xBFFFFFFF 0xC0000000- 0xDFFFFFFF Notes: 58 1. 2. WT (2) Shareable (1) Non-shareable (1) - See “Memory Regions, Types and Attributes” for more information. WT = Write through, no write allocate. WBWA = Write back, write allocate. See the “Glossary” for more information. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Instruction Prefetch and Branch Prediction The Cortex-M4 processor: Prefetches instructions ahead of execution Speculatively prefetches from branch target addresses. 11.4.2.4 Software Ordering of Memory Accesses The order of instructions in the program flow does not always guarantee the order of the corresponding memory transactions. This is because: The processor can reorder some memory accesses to improve efficiency, providing this does not affect the behavior of the instruction sequence. The processor has multiple bus interfaces Memory or devices in the memory map have different wait states Some memory accesses are buffered or speculative. “Memory System Ordering of Memory Accesses” describes the cases where the memory system guarantees the order of memory accesses. Otherwise, if the order of memory accesses is critical, the software must include memory barrier instructions to force that ordering. The processor provides the following memory barrier instructions: DMB The Data Memory Barrier (DMB) instruction ensures that outstanding memory transactions complete before subsequent memory transactions. See “DMB” . DSB The Data Synchronization Barrier (DSB) instruction ensures that outstanding memory transactions complete before subsequent instructions execute. See “DSB” . ISB The Instruction Synchronization Barrier (ISB) ensures that the effect of all completed memory transactions is recognizable by subsequent instructions. See “ISB” . MPU Programming Use a DSB followed by an ISB instruction or exception return to ensure that the new MPU configuration is used by subsequent instructions 11.4.2.5 Bit-banding A bit-band region maps each word in a bit-band alias region to a single bit in the bit-band region. The bit-band regions occupy the lowest 1 MB of the SRAM and peripheral memory regions. The memory map has two 32 MB alias regions that map to two 1 MB bit-band regions: Accesses to the 32 MB SRAM alias region map to the 1 MB SRAM bit-band region, as shown in Table 11-6. Accesses to the 32 MB peripheral alias region map to the 1 MB peripheral bit-band region, as shown in Table 11-7. Table 11-6. SRAM Memory Bit-banding Regions Address Range 0x200000000x200FFFFF 0x220000000x23FFFFFF Memory Region Instruction and Data Accesses SRAM bit-band region Direct accesses to this memory range behave as SRAM memory accesses, but this region is also bit-addressable through bit-band alias. SRAM bit-band alias Data accesses to this region are remapped to bit-band region. A write operation is performed as read-modify-write. Instruction accesses are not remapped. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 59 Table 11-7. Peripheral Memory Bit-banding Regions Address Range 0x400000000x400FFFFF 0x420000000x43FFFFFF Notes: 1. 2. Memory Region Instruction and Data Accesses Peripheral bit-band alias Direct accesses to this memory range behave as peripheral memory accesses, but this region is also bit-addressable through bit-band alias. Peripheral bit-band region Data accesses to this region are remapped to bit-band region. A write operation is performed as read-modify-write. Instruction accesses are not permitted. A word access to the SRAM or peripheral bit-band alias regions map to a single bit in the SRAM or peripheral bitband region. Bit-band accesses can use byte, halfword, or word transfers. The bit-band transfer size matches the transfer size of the instruction making the bit-band access. The following formula shows how the alias region maps onto the bit-band region: bit_word_offset = (byte_offset x 32) + (bit_number x 4) bit_word_addr = bit_band_base + bit_word_offset where: Bit_word_offset is the position of the target bit in the bit-band memory region. Bit_word_addr is the address of the word in the alias memory region that maps to the targeted bit. Bit_band_base is the starting address of the alias region. Byte_offset is the number of the byte in the bit-band region that contains the targeted bit. Bit_number is the bit position, 0-7, of the targeted bit. Figure 11-4 shows examples of bit-band mapping between the SRAM bit-band alias region and the SRAM bitband region: 60 The alias word at 0x23FFFFE0 maps to bit[0] of the bit-band byte at 0x200FFFFF: 0x23FFFFE0 = 0x22000000 + (0xFFFFF*32) + (0*4). The alias word at 0x23FFFFFC maps to bit[7] of the bit-band byte at 0x200FFFFF: 0x23FFFFFC = 0x22000000 + (0xFFFFF*32) + (7*4). The alias word at 0x22000000 maps to bit[0] of the bit-band byte at 0x20000000: 0x22000000 = 0x22000000 + (0*32) + (0 *4). The alias word at 0x2200001C maps to bit[7] of the bit-band byte at 0x20000000: 0x2200001C = 0x22000000+ (0*32) + (7*4). SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Figure 11-4. Bit-band Mapping 32 MB alias region 0x23FFFFFC 0x23FFFFF8 0x23FFFFF4 0x23FFFFF0 0x23FFFFEC 0x23FFFFE8 0x23FFFFE4 0x23FFFFE0 0x2200001C 0x22000018 0x22000014 0x22000010 0x2200000C 0x22000008 0x22000004 0x22000000 1 MB SRAM bit-band region 7 6 5 4 3 2 1 0 7 6 0x200FFFFF 7 6 5 4 3 2 5 4 3 2 1 0 7 6 0x200FFFFE 1 0 7 6 0x20000003 5 4 3 2 0x20000002 5 4 3 2 1 0 7 6 0x200FFFFD 1 0 7 6 5 4 3 2 0x20000001 5 4 3 2 1 0 1 0 0x200FFFFC 1 0 7 6 5 4 3 2 0x20000000 Directly Accessing an Alias Region Writing to a word in the alias region updates a single bit in the bit-band region. Bit[0] of the value written to a word in the alias region determines the value written to the targeted bit in the bitband region. Writing a value with bit[0] set to 1 writes a 1 to the bit-band bit, and writing a value with bit[0] set to 0 writes a 0 to the bit-band bit. Bits[31:1] of the alias word have no effect on the bit-band bit. Writing 0x01 has the same effect as writing 0xFF. Writing 0x00 has the same effect as writing 0x0E. Reading a word in the alias region: 0x00000000 indicates that the targeted bit in the bit-band region is set to 0 0x00000001 indicates that the targeted bit in the bit-band region is set to 1 Directly Accessing a Bit-band Region “Behavior of Memory Accesses” describes the behavior of direct byte, halfword, or word accesses to the bit-band regions. 11.4.2.6 Memory Endianness The processor views memory as a linear collection of bytes numbered in ascending order from zero. For example, bytes 0-3 hold the first stored word, and bytes 4-7 hold the second stored word. “Little-endian Format” describes how words of data are stored in memory. Figure 11-5. Little-endian Format In little-endian format, the processor stores the least significant byte of a word at the lowest-numbered byte, and the most significant byte at the highest-numbered byte. For example: SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 61 Figure 11-6. Little-endian Format Memory 7 Register 0 31 Address A B0 A+1 B1 A+2 B2 A+3 B3 lsbyte 24 23 B3 16 15 B2 8 7 B1 0 B0 msbyte 11.4.2.7 Synchronization Primitives The Cortex-M4 instruction set includes pairs of synchronization primitives. These provide a non-blocking mechanism that a thread or process can use to obtain exclusive access to a memory location. The software can use them to perform a guaranteed read-modify-write memory update sequence, or for a semaphore mechanism. A pair of synchronization primitives comprises: A Load-exclusive Instruction, used to read the value of a memory location, requesting exclusive access to that location. A Store-Exclusive instruction, used to attempt to write to the same memory location, returning a status bit to a register. If this bit is: 0: It indicates that the thread or process gained exclusive access to the memory, and the write succeeds, 1: It indicates that the thread or process did not gain exclusive access to the memory, and no write is performed. The pairs of Load-Exclusive and Store-Exclusive instructions are: The word instructions LDREX and STREX The halfword instructions LDREXH and STREXH The byte instructions LDREXB and STREXB. The software must use a Load-Exclusive instruction with the corresponding Store-Exclusive instruction. To perform an exclusive read-modify-write of a memory location, the software must: 1. Use a Load-Exclusive instruction to read the value of the location. 2. Update the value, as required. 3. Use a Store-Exclusive instruction to attempt to write the new value back to the memory location 4. Test the returned status bit. If this bit is: 0: The read-modify-write completed successfully. 1: No write was performed. This indicates that the value returned at step 1 might be out of date. The software must retry the read-modify-write sequence. The software can use the synchronization primitives to implement a semaphore as follows: 1. Use a Load-Exclusive instruction to read from the semaphore address to check whether the semaphore is free. 2. If the semaphore is free, use a Store-Exclusive instruction to write the claim value to the semaphore address. 3. 62 If the returned status bit from step 2 indicates that the Store-Exclusive instruction succeeded then the software has claimed the semaphore. However, if the Store-Exclusive instruction failed, another process might have claimed the semaphore after the software performed the first step. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 The Cortex-M4 includes an exclusive access monitor, that tags the fact that the processor has executed a LoadExclusive instruction. If the processor is part of a multiprocessor system, the system also globally tags the memory locations addressed by exclusive accesses by each processor. The processor removes its exclusive access tag if: It executes a CLREX instruction It executes a Store-Exclusive instruction, regardless of whether the write succeeds. An exception occurs. This means that the processor can resolve semaphore conflicts between different threads. In a multiprocessor implementation: Executing a CLREX instruction removes only the local exclusive access tag for the processor Executing a Store-Exclusive instruction, or an exception, removes the local exclusive access tags, and all global exclusive access tags for the processor. For more information about the synchronization primitive instructions, see “LDREX and STREX” and “CLREX” . 11.4.2.8 Programming Hints for the Synchronization Primitives ISO/IEC C cannot directly generate the exclusive access instructions. CMSIS provides intrinsic functions for generation of these instructions: Table 11-8. CMSIS Functions for Exclusive Access Instructions Instruction CMSIS Function LDREX uint32_t __LDREXW (uint32_t *addr) LDREXH uint16_t __LDREXH (uint16_t *addr) LDREXB uint8_t __LDREXB (uint8_t *addr) STREX uint32_t __STREXW (uint32_t value, uint32_t *addr) STREXH uint32_t __STREXH (uint16_t value, uint16_t *addr) STREXB uint32_t __STREXB (uint8_t value, uint8_t *addr) CLREX void __CLREX (void) The actual exclusive access instruction generated depends on the data type of the pointer passed to the intrinsic function. For example, the following C code generates the required LDREXB operation: __ldrex((volatile char *) 0xFF); SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 63 11.4.3 Exception Model This section describes the exception model. 11.4.3.1 Exception States Each exception is in one of the following states: Inactive The exception is not active and not pending. Pending The exception is waiting to be serviced by the processor. An interrupt request from a peripheral or from software can change the state of the corresponding interrupt to pending. Active An exception is being serviced by the processor but has not completed. An exception handler can interrupt the execution of another exception handler. In this case, both exceptions are in the active state. Active and Pending The exception is being serviced by the processor and there is a pending exception from the same source. 11.4.3.2 Exception Types The exception types are: Reset Reset is invoked on power up or a warm reset. The exception model treats reset as a special form of exception. When reset is asserted, the operation of the processor stops, potentially at any point in an instruction. When reset is deasserted, execution restarts from the address provided by the reset entry in the vector table. Execution restarts as privileged execution in Thread mode. Non Maskable Interrupt (NMI) A non maskable interrupt (NMI) can be signalled by a peripheral or triggered by software. This is the highest priority exception other than reset. It is permanently enabled and has a fixed priority of -2. NMIs cannot be: Masked or prevented from activation by any other exception. Preempted by any exception other than Reset. Hard Fault A hard fault is an exception that occurs because of an error during exception processing, or because an exception cannot be managed by any other exception mechanism. Hard Faults have a fixed priority of -1, meaning they have higher priority than any exception with configurable priority. Memory Management Fault (MemManage) A Memory Management Fault is an exception that occurs because of a memory protection related fault. The MPU or the fixed memory protection constraints determines this fault, for both instruction and data memory transactions. This fault is used to abort instruction accesses to Execute Never (XN) memory regions, even if the MPU is disabled. Bus Fault A Bus Fault is an exception that occurs because of a memory related fault for an instruction or data memory transaction. This might be from an error detected on a bus in the memory system. 64 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Usage Fault A Usage Fault is an exception that occurs because of a fault related to an instruction execution. This includes: An undefined instruction An illegal unaligned access An invalid state on instruction execution An error on exception return. The following can cause a Usage Fault when the core is configured to report them: An unaligned address on word and halfword memory access A division by zero. SVCall A supervisor call (SVC) is an exception that is triggered by the SVC instruction. In an OS environment, applications can use SVC instructions to access OS kernel functions and device drivers. PendSV PendSV is an interrupt-driven request for system-level service. In an OS environment, use PendSV for context switching when no other exception is active. SysTick A SysTick exception is an exception the system timer generates when it reaches zero. Software can also generate a SysTick exception. In an OS environment, the processor can use this exception as system tick. Interrupt (IRQ) A interrupt, or IRQ, is an exception signalled by a peripheral, or generated by a software request. All interrupts are asynchronous to instruction execution. In the system, peripherals use interrupts to communicate with the processor. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 65 Table 11-9. Properties of the Different Exception Types Exception Number (1) Irq Number (1) Exception Type Priority Vector Address or Offset (2) Activation 1 - Reset -3, the highest 0x00000004 Asynchronous 2 -14 NMI -2 0x00000008 Asynchronous 3 -13 Hard fault -1 0x0000000C - 4 -12 Memory management fault Configurable (3) 0x00000010 Synchronous (3) 0x00000014 Synchronous when precise, asynchronous when imprecise 5 -11 Bus fault Configurable 6 -10 Usage fault Configurable (3) 0x00000018 Synchronous 7-10 - - - Reserved - 11 -5 SVCall Configurable (3) 0x0000002C Synchronous 12-13 - - - 14 -2 PendSV Reserved - Configurable (3) 0x00000038 Asynchronous (3) 0x0000003C Asynchronous 0x00000040 and above (5) Asynchronous 15 -1 SysTick Configurable 16 and above 0 and above Interrupt (IRQ) Configurable(4) Notes: 1. To simplify the software layer, the CMSIS only uses IRQ numbers and therefore uses negative values for exceptions other than interrupts. The IPSR returns the Exception number, see “Interrupt Program Status Register” . 2. See “Vector Table” for more information 3. See “System Handler Priority Registers” 4. See “Interrupt Priority Registers” 5. Increasing in steps of 4. For an asynchronous exception, other than reset, the processor can execute another instruction between when the exception is triggered and when the processor enters the exception handler. Privileged software can disable the exceptions that Table 11-9 shows as having configurable priority, see: “System Handler Control and State Register” “Interrupt Clear-enable Registers” . For more information about hard faults, memory management faults, bus faults, and usage faults, see “Fault Handling” . 11.4.3.3 Exception Handlers The processor handles exceptions using: 66 Interrupt Service Routines (ISRs) Interrupts IRQ0 to IRQ29 are the exceptions handled by ISRs. Fault Handlers Hard fault, memory management fault, usage fault, bus fault are fault exceptions handled by the fault handlers. System Handlers NMI, PendSV, SVCall SysTick, and the fault exceptions are all system exceptions that are handled by system handlers. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.4.3.4 Vector Table The vector table contains the reset value of the stack pointer, and the start addresses, also called exception vectors, for all exception handlers. Figure 11-7 shows the order of the exception vectors in the vector table. The least-significant bit of each vector must be 1, indicating that the exception handler is Thumb code. Figure 11-7. Vector Table Exception number IRQ number 255 239 . . . 18 2 17 1 16 0 15 -1 14 -2 13 IRQ239 0x03FC . . . 0x004C . . . IRQ2 0x0048 IRQ1 0x0044 IRQ0 0x0040 SysTick 0x003C PendSV 0x0038 Reserved Reserved for Debug 12 11 Vector Offset -5 10 SVCall 0x002C 9 Reserved 8 7 6 -10 5 -11 4 -12 3 -13 2 -14 1 Usage fault 0x0018 0x0014 0x0010 Bus fault Memory management fault Hard fault 0x000C NMI 0x0008 0x0004 0x0000 Reset Initial SP value On system reset, the vector table is fixed at address 0x00000000. Privileged software can write to the SCB_VTOR register to relocate the vector table start address to a different memory location, in the range 0x00000080 to 0x3FFFFF80, see “Vector Table Offset Register” . 11.4.3.5 Exception Priorities As Table 11-9 shows, all exceptions have an associated priority, with: A lower priority value indicating a higher priority Configurable priorities for all exceptions except Reset, Hard fault and NMI. If the software does not configure any priorities, then all exceptions with a configurable priority have a priority of 0. For information about configuring exception priorities see “System Handler Priority Registers” , and “Interrupt Priority Registers” . Note: Configurable priority values are in the range 0-15. This means that the Reset, Hard fault, and NMI exceptions, with fixed negative priority values, always have higher priority than any other exception. For example, assigning a higher priority value to IRQ[0] and a lower priority value to IRQ[1] means that IRQ[1] has higher priority than IRQ[0]. If both IRQ[1] and IRQ[0] are asserted, IRQ[1] is processed before IRQ[0]. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 67 If multiple pending exceptions have the same priority, the pending exception with the lowest exception number takes precedence. For example, if both IRQ[0] and IRQ[1] are pending and have the same priority, then IRQ[0] is processed before IRQ[1]. When the processor is executing an exception handler, the exception handler is preempted if a higher priority exception occurs. If an exception occurs with the same priority as the exception being handled, the handler is not preempted, irrespective of the exception number. However, the status of the new interrupt changes to pending. 11.4.3.6 Interrupt Priority Grouping To increase priority control in systems with interrupts, the NVIC supports priority grouping. This divides each interrupt priority register entry into two fields: An upper field that defines the group priority A lower field that defines a subpriority within the group. Only the group priority determines preemption of interrupt exceptions. When the processor is executing an interrupt exception handler, another interrupt with the same group priority as the interrupt being handled does not preempt the handler. If multiple pending interrupts have the same group priority, the subpriority field determines the order in which they are processed. If multiple pending interrupts have the same group priority and subpriority, the interrupt with the lowest IRQ number is processed first. For information about splitting the interrupt priority fields into group priority and subpriority, see “Application Interrupt and Reset Control Register” . 11.4.3.7 Exception Entry and Return Descriptions of exception handling use the following terms: Preemption When the processor is executing an exception handler, an exception can preempt the exception handler if its priority is higher than the priority of the exception being handled. See “Interrupt Priority Grouping” for more information about preemption by an interrupt. When one exception preempts another, the exceptions are called nested exceptions. See “Exception Entry” more information. Return This occurs when the exception handler is completed, and: There is no pending exception with sufficient priority to be serviced The completed exception handler was not handling a late-arriving exception. The processor pops the stack and restores the processor state to the state it had before the interrupt occurred. See “Exception Return” for more information. Tail-chaining This mechanism speeds up exception servicing. On completion of an exception handler, if there is a pending exception that meets the requirements for exception entry, the stack pop is skipped and control transfers to the new exception handler. Late-arriving This mechanism speeds up preemption. If a higher priority exception occurs during state saving for a previous exception, the processor switches to handle the higher priority exception and initiates the vector fetch for that exception. State saving is not affected by late arrival because the state saved is the same for both exceptions. Therefore the state saving continues uninterrupted. The processor can accept a late arriving exception until the first instruction of the exception handler of the original exception enters the execute stage of the processor. On return from the exception handler of the late-arriving exception, the normal tail-chaining rules apply. 68 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Exception Entry An Exception entry occurs when there is a pending exception with sufficient priority and either the processor is in Thread mode, or the new exception is of a higher priority than the exception being handled, in which case the new exception preempts the original exception. When one exception preempts another, the exceptions are nested. Sufficient priority means that the exception has more priority than any limits set by the mask registers, see “Exception Mask Registers” . An exception with less priority than this is pending but is not handled by the processor. When the processor takes an exception, unless the exception is a tail-chained or a late-arriving exception, the processor pushes information onto the current stack. This operation is referred as stacking and the structure of eight data words is referred to as stack frame. Figure 11-8. Exception Stack Frame ... {aligner} FPSCR S15 S14 S13 S12 S11 S10 S9 S8 S7 S6 S5 S4 S3 S2 S1 S0 xPSR PC LR R12 R3 R2 R1 R0 Exception frame with floating-point storage Pre-IRQ top of stack Decreasing memory address IRQ top of stack ... {aligner} xPSR PC LR R12 R3 R2 R1 R0 Pre-IRQ top of stack IRQ top of stack Exception frame without floating-point storage Immediately after stacking, the stack pointer indicates the lowest address in the stack frame. The alignment of the stack frame is controlled via the STKALIGN bit of the Configuration Control Register (CCR). The stack frame includes the return address. This is the address of the next instruction in the interrupted program. This value is restored to the PC at exception return so that the interrupted program resumes. In parallel to the stacking operation, the processor performs a vector fetch that reads the exception handler start address from the vector table. When stacking is complete, the processor starts executing the exception handler. At the same time, the processor writes an EXC_RETURN value to the LR. This indicates which stack pointer corresponds to the stack frame and what operation mode the processor was in before the entry occurred. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 69 If no higher priority exception occurs during the exception entry, the processor starts executing the exception handler and automatically changes the status of the corresponding pending interrupt to active. If another higher priority exception occurs during the exception entry, the processor starts executing the exception handler for this exception and does not change the pending status of the earlier exception. This is the late arrival case. Exception Return An Exception return occurs when the processor is in Handler mode and executes one of the following instructions to load the EXC_RETURN value into the PC: An LDM or POP instruction that loads the PC An LDR instruction with the PC as the destination. A BX instruction using any register. EXC_RETURN is the value loaded into the LR on exception entry. The exception mechanism relies on this value to detect when the processor has completed an exception handler. The lowest five bits of this value provide information on the return stack and processor mode. Table 11-10 shows the EXC_RETURN values with a description of the exception return behavior. All EXC_RETURN values have bits[31:5] set to one. When this value is loaded into the PC, it indicates to the processor that the exception is complete, and the processor initiates the appropriate exception return sequence. Table 11-10. Exception Return Behavior EXC_RETURN[31:0] Description 0xFFFFFFF1 Return to Handler mode, exception return uses non-floating-point state from the MSP and execution uses MSP after return. 0xFFFFFFF9 Return to Thread mode, exception return uses non-floating-point state from MSP and execution uses MSP after return. 0xFFFFFFFD Return to Thread mode, exception return uses non-floating-point state from the PSP and execution uses PSP after return. 11.4.3.8 Fault Handling Faults are a subset of the exceptions, see “Exception Model” . The following generate a fault: A bus error on: ̶ An instruction fetch or vector table load ̶ A data access An internally-detected error such as an undefined instruction An attempt to execute an instruction from a memory region marked as Non-Executable (XN). A privilege violation or an attempt to access an unmanaged region causing an MPU fault. Fault Types Table 11-11 shows the types of fault, the handler used for the fault, the corresponding fault status register, and the register bit that indicates that the fault has occurred. See “Configurable Fault Status Register” for more information about the fault status registers. 70 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Table 11-11. Faults Fault Handler Bus error on a vector read Bit Name Fault Status Register VECTTBL Hard fault “Hard Fault Status Register” Fault escalated to a hard fault FORCED MPU or default memory map mismatch: - on instruction access - IACCVIOL Memory management fault on data access during exception stacking DACCVIOL(2) during exception unstacking MUNSKERR during lazy floating-point state preservation MLSPERR Bus error: “MMFSR: Memory Management Fault Status Subregister” MSTKERR - - during exception stacking STKERR during exception unstacking UNSTKERR during instruction prefetch Bus fault IBUSERR “BFSR: Bus Fault Status Subregister” during lazy floating-point state preservation LSPERR Precise data bus error PRECISERR Imprecise data bus error IMPRECISERR Attempt to access a coprocessor NOCP Undefined instruction Attempt to enter an invalid instruction set state UNDEFINSTR (1) INVSTATE Usage fault “UFSR: Usage Fault Status Subregister” Invalid EXC_RETURN value INVPC Illegal unaligned load or store UNALIGNED Divide By 0 DIVBYZERO Notes: 1. Occurs on an access to an XN region even if the processor does not include an MPU or the MPU is disabled. 2. Attempt to use an instruction set other than the Thumb instruction set, or return to a non load/store-multiple instruction with ICI continuation. Fault Escalation and Hard Faults All faults exceptions except for hard fault have configurable exception priority, see “System Handler Priority Registers” . The software can disable the execution of the handlers for these faults, see “System Handler Control and State Register” . Usually, the exception priority, together with the values of the exception mask registers, determines whether the processor enters the fault handler, and whether a fault handler can preempt another fault handler, as described in “Exception Model” . SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 71 In some situations, a fault with configurable priority is treated as a hard fault. This is called priority escalation, and the fault is described as escalated to hard fault. Escalation to hard fault occurs when: A fault handler causes the same kind of fault as the one it is servicing. This escalation to hard fault occurs because a fault handler cannot preempt itself; it must have the same priority as the current priority level. A fault handler causes a fault with the same or lower priority as the fault it is servicing. This is because the handler for the new fault cannot preempt the currently executing fault handler. An exception handler causes a fault for which the priority is the same as or lower than the currently executing exception. A fault occurs and the handler for that fault is not enabled. If a bus fault occurs during a stack push when entering a bus fault handler, the bus fault does not escalate to a hard fault. This means that if a corrupted stack causes a fault, the fault handler executes even though the stack push for the handler failed. The fault handler operates but the stack contents are corrupted. Note: Only Reset and NMI can preempt the fixed priority hard fault. A hard fault can preempt any exception other than Reset, NMI, or another hard fault. Fault Status Registers and Fault Address Registers The fault status registers indicate the cause of a fault. For bus faults and memory management faults, the fault address register indicates the address accessed by the operation that caused the fault, as shown in Table 11-12. Table 11-12. Fault Status and Fault Address Registers Handler Status Register Name Address Register Name Register Description Hard fault SCB_HFSR - “Hard Fault Status Register” Memory management fault MMFSR SCB_MMFAR “MMFSR: Memory Management Fault Status Subregister” “MemManage Fault Address Register” Bus fault BFSR SCB_BFAR Usage fault UFSR - “BFSR: Bus Fault Status Subregister” “Bus Fault Address Register” “UFSR: Usage Fault Status Subregister” Lockup The processor enters a lockup state if a hard fault occurs when executing the NMI or hard fault handlers. When the processor is in lockup state, it does not execute any instructions. The processor remains in lockup state until either: It is reset An NMI occurs It is halted by a debugger. Note: 72 If the lockup state occurs from the NMI handler, a subsequent NMI does not cause the processor to leave the lockup state. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.5 Power Management The Cortex-M4 processor sleep modes reduce the power consumption: Sleep mode stops the processor clock Deep sleep mode stops the system clock and switches off the PLL and flash memory. The SLEEPDEEP bit of the SCR selects which sleep mode is used; see “System Control Register” . This section describes the mechanisms for entering sleep mode, and the conditions for waking up from sleep mode. 11.5.1 Entering Sleep Mode This section describes the mechanisms software can use to put the processor into sleep mode. The system can generate spurious wakeup events, for example a debug operation wakes up the processor. Therefore, the software must be able to put the processor back into sleep mode after such an event. A program might have an idle loop to put the processor back to sleep mode. 11.5.1.1 Wait for Interrupt The wait for interrupt instruction, WFI, causes immediate entry to sleep mode. When the processor executes a WFI instruction it stops executing instructions and enters sleep mode. See “WFI” for more information. 11.5.1.2 Sleep-on-exit If the SLEEPONEXIT bit of the SCR is set to 1 when the processor completes the execution of an exception handler, it returns to Thread mode and immediately enters sleep mode. Use this mechanism in applications that only require the processor to run when an exception occurs. 11.5.2 Wakeup from Sleep Mode The conditions for the processor to wake up depend on the mechanism that cause it to enter sleep mode. 11.5.2.1 Wakeup from WFI or Sleep-on-exit Normally, the processor wakes up only when it detects an exception with sufficient priority to cause exception entry. Some embedded systems might have to execute system restore tasks after the processor wakes up, and before it executes an interrupt handler. To achieve this, set the PRIMASK bit to 1 and the FAULTMASK bit to 0. If an interrupt arrives that is enabled and has a higher priority than the current exception priority, the processor wakes up but does not execute the interrupt handler until the processor sets PRIMASK to zero. For more information about PRIMASK and FAULTMASK, see “Exception Mask Registers” . 11.5.3 Power Management Programming Hints ISO/IEC C cannot directly generate the WFI instructions. The CMSIS provides the following functions for these instructions: void __WFI(void) // Wait for Interrupt SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 73 11.6 Cortex-M4 Instruction Set 11.6.1 Instruction Set Summary The processor implements a version of the Thumb instruction set. Table 11-13 lists the supported instructions. Angle brackets, <>, enclose alternative forms of the operand Braces, {}, enclose optional operands The Operands column is not exhaustive Op2 is a flexible second operand that can be either a register or a constant Most instructions can use an optional condition code suffix. For more information on the instructions and operands, see the instruction descriptions. Table 11-13. Cortex-M4 Instructions Mnemonic Operands Description Flags ADC, ADCS {Rd,} Rn, Op2 Add with Carry N,Z,C,V ADD, ADDS {Rd,} Rn, Op2 Add N,Z,C,V ADD, ADDW {Rd,} Rn, #imm12 Add N,Z,C,V ADR Rd, label Load PC-relative address - AND, ANDS {Rd,} Rn, Op2 Logical AND N,Z,C ASR, ASRS Rd, Rm, <Rs|#n> Arithmetic Shift Right N,Z,C B label Branch - BFC Rd, #lsb, #width Bit Field Clear - BFI Rd, Rn, #lsb, #width Bit Field Insert - BIC, BICS {Rd,} Rn, Op2 Bit Clear N,Z,C BKPT #imm Breakpoint - BL label Branch with Link - BLX Rm Branch indirect with Link - BX Rm Branch indirect - CBNZ Rn, label Compare and Branch if Non Zero - CBZ Rn, label Compare and Branch if Zero - CLREX - Clear Exclusive - CLZ Rd, Rm Count leading zeros - CMN Rn, Op2 Compare Negative N,Z,C,V CMP Rn, Op2 Compare N,Z,C,V CPSID i Change Processor State, Disable Interrupts - CPSIE i Change Processor State, Enable Interrupts - DMB - Data Memory Barrier - DSB - Data Synchronization Barrier - EOR, EORS {Rd,} Rn, Op2 Exclusive OR N,Z,C ISB - Instruction Synchronization Barrier - IT - If-Then condition block - LDM Rn{!}, reglist Load Multiple registers, increment after - 74 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Table 11-13. Cortex-M4 Instructions (Continued) Mnemonic Operands Description Flags LDMDB, LDMEA Rn{!}, reglist Load Multiple registers, decrement before - LDMFD, LDMIA Rn{!}, reglist Load Multiple registers, increment after - LDR Rt, [Rn, #offset] Load Register with word - LDRB, LDRBT Rt, [Rn, #offset] Load Register with byte - LDRD Rt, Rt2, [Rn, #offset] Load Register with two bytes - LDREX Rt, [Rn, #offset] Load Register Exclusive - LDREXB Rt, [Rn] Load Register Exclusive with byte - LDREXH Rt, [Rn] Load Register Exclusive with halfword - LDRH, LDRHT Rt, [Rn, #offset] Load Register with halfword - LDRSB, DRSBT Rt, [Rn, #offset] Load Register with signed byte - LDRSH, LDRSHT Rt, [Rn, #offset] Load Register with signed halfword - LDRT Rt, [Rn, #offset] Load Register with word - LSL, LSLS Rd, Rm, <Rs|#n> Logical Shift Left N,Z,C LSR, LSRS Rd, Rm, <Rs|#n> Logical Shift Right N,Z,C MLA Rd, Rn, Rm, Ra Multiply with Accumulate, 32-bit result - MLS Rd, Rn, Rm, Ra Multiply and Subtract, 32-bit result - MOV, MOVS Rd, Op2 Move N,Z,C MOVT Rd, #imm16 Move Top - MOVW, MOV Rd, #imm16 Move 16-bit constant N,Z,C MRS Rd, spec_reg Move from special register to general register - MSR spec_reg, Rm Move from general register to special register N,Z,C,V MUL, MULS {Rd,} Rn, Rm Multiply, 32-bit result N,Z MVN, MVNS Rd, Op2 Move NOT N,Z,C NOP - No Operation - ORN, ORNS {Rd,} Rn, Op2 Logical OR NOT N,Z,C ORR, ORRS {Rd,} Rn, Op2 Logical OR N,Z,C PKHTB, PKHBT {Rd,} Rn, Rm, Op2 Pack Halfword - POP reglist Pop registers from stack - PUSH reglist Push registers onto stack - QADD {Rd,} Rn, Rm Saturating double and Add Q QADD16 {Rd,} Rn, Rm Saturating Add 16 - QADD8 {Rd,} Rn, Rm Saturating Add 8 - QASX {Rd,} Rn, Rm Saturating Add and Subtract with Exchange - QDADD {Rd,} Rn, Rm Saturating Add Q QDSUB {Rd,} Rn, Rm Saturating double and Subtract Q QSAX {Rd,} Rn, Rm Saturating Subtract and Add with Exchange - QSUB {Rd,} Rn, Rm Saturating Subtract Q SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 75 Table 11-13. Cortex-M4 Instructions (Continued) Mnemonic Operands Description Flags QSUB16 {Rd,} Rn, Rm Saturating Subtract 16 - QSUB8 {Rd,} Rn, Rm Saturating Subtract 8 - RBIT Rd, Rn Reverse Bits - REV Rd, Rn Reverse byte order in a word - REV16 Rd, Rn Reverse byte order in each halfword - REVSH Rd, Rn Reverse byte order in bottom halfword and sign extend - ROR, RORS Rd, Rm, <Rs|#n> Rotate Right N,Z,C RRX, RRXS Rd, Rm Rotate Right with Extend N,Z,C RSB, RSBS {Rd,} Rn, Op2 Reverse Subtract N,Z,C,V SADD16 {Rd,} Rn, Rm Signed Add 16 GE SADD8 {Rd,} Rn, Rm Signed Add 8 and Subtract with Exchange GE SASX {Rd,} Rn, Rm Signed Add GE SBC, SBCS {Rd,} Rn, Op2 Subtract with Carry N,Z,C,V SBFX Rd, Rn, #lsb, #width Signed Bit Field Extract - SDIV {Rd,} Rn, Rm Signed Divide - SEL {Rd,} Rn, Rm Select bytes - SEV - Send Event - SHADD16 {Rd,} Rn, Rm Signed Halving Add 16 - SHADD8 {Rd,} Rn, Rm Signed Halving Add 8 - SHASX {Rd,} Rn, Rm Signed Halving Add and Subtract with Exchange - SHSAX {Rd,} Rn, Rm Signed Halving Subtract and Add with Exchange - SHSUB16 {Rd,} Rn, Rm Signed Halving Subtract 16 - SHSUB8 {Rd,} Rn, Rm Signed Halving Subtract 8 - SMLABB, SMLABT, SMLATB, SMLATT Rd, Rn, Rm, Ra Signed Multiply Accumulate Long (halfwords) Q SMLAD, SMLADX Rd, Rn, Rm, Ra Signed Multiply Accumulate Dual Q SMLAL RdLo, RdHi, Rn, Rm Signed Multiply with Accumulate (32 x 32 + 64), 64-bit result - SMLALBB, SMLALBT, SMLALTB, SMLALTT RdLo, RdHi, Rn, Rm Signed Multiply Accumulate Long, halfwords - SMLALD, SMLALDX RdLo, RdHi, Rn, Rm Signed Multiply Accumulate Long Dual - SMLAWB, SMLAWT Rd, Rn, Rm, Ra Signed Multiply Accumulate, word by halfword Q SMLSD Rd, Rn, Rm, Ra Signed Multiply Subtract Dual Q SMLSLD RdLo, RdHi, Rn, Rm Signed Multiply Subtract Long Dual SMMLA Rd, Rn, Rm, Ra Signed Most significant word Multiply Accumulate - SMMLS, SMMLR Rd, Rn, Rm, Ra Signed Most significant word Multiply Subtract - SMMUL, SMMULR {Rd,} Rn, Rm Signed Most significant word Multiply - SMUAD {Rd,} Rn, Rm Signed dual Multiply Add Q 76 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Table 11-13. Cortex-M4 Instructions (Continued) Mnemonic Operands Description Flags SMULBB, SMULBT SMULTB, SMULTT {Rd,} Rn, Rm Signed Multiply (halfwords) - SMULL RdLo, RdHi, Rn, Rm Signed Multiply (32 x 32), 64-bit result - SMULWB, SMULWT {Rd,} Rn, Rm Signed Multiply word by halfword - SMUSD, SMUSDX {Rd,} Rn, Rm Signed dual Multiply Subtract - SSAT Rd, #n, Rm {,shift #s} Signed Saturate Q SSAT16 Rd, #n, Rm Signed Saturate 16 Q SSAX {Rd,} Rn, Rm Signed Subtract and Add with Exchange GE SSUB16 {Rd,} Rn, Rm Signed Subtract 16 - SSUB8 {Rd,} Rn, Rm Signed Subtract 8 - STM Rn{!}, reglist Store Multiple registers, increment after - STMDB, STMEA Rn{!}, reglist Store Multiple registers, decrement before - STMFD, STMIA Rn{!}, reglist Store Multiple registers, increment after - STR Rt, [Rn, #offset] Store Register word - STRB, STRBT Rt, [Rn, #offset] Store Register byte - STRD Rt, Rt2, [Rn, #offset] Store Register two words - STREX Rd, Rt, [Rn, #offset] Store Register Exclusive - STREXB Rd, Rt, [Rn] Store Register Exclusive byte - STREXH Rd, Rt, [Rn] Store Register Exclusive halfword - STRH, STRHT Rt, [Rn, #offset] Store Register halfword - STRT Rt, [Rn, #offset] Store Register word - SUB, SUBS {Rd,} Rn, Op2 Subtract N,Z,C,V SUB, SUBW {Rd,} Rn, #imm12 Subtract N,Z,C,V SVC #imm Supervisor Call - SXTAB {Rd,} Rn, Rm,{,ROR #} Extend 8 bits to 32 and add - SXTAB16 {Rd,} Rn, Rm,{,ROR #} Dual extend 8 bits to 16 and add - SXTAH {Rd,} Rn, Rm,{,ROR #} Extend 16 bits to 32 and add - SXTB16 {Rd,} Rm {,ROR #n} Signed Extend Byte 16 - SXTB {Rd,} Rm {,ROR #n} Sign extend a byte - SXTH {Rd,} Rm {,ROR #n} Sign extend a halfword - TBB [Rn, Rm] Table Branch Byte - TBH [Rn, Rm, LSL #1] Table Branch Halfword - TEQ Rn, Op2 Test Equivalence N,Z,C TST Rn, Op2 Test N,Z,C UADD16 {Rd,} Rn, Rm Unsigned Add 16 GE UADD8 {Rd,} Rn, Rm Unsigned Add 8 GE USAX {Rd,} Rn, Rm Unsigned Subtract and Add with Exchange GE SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 77 Table 11-13. Cortex-M4 Instructions (Continued) Mnemonic Operands Description Flags UHADD16 {Rd,} Rn, Rm Unsigned Halving Add 16 - UHADD8 {Rd,} Rn, Rm Unsigned Halving Add 8 - UHASX {Rd,} Rn, Rm Unsigned Halving Add and Subtract with Exchange - UHSAX {Rd,} Rn, Rm Unsigned Halving Subtract and Add with Exchange - UHSUB16 {Rd,} Rn, Rm Unsigned Halving Subtract 16 - UHSUB8 {Rd,} Rn, Rm Unsigned Halving Subtract 8 - UBFX Rd, Rn, #lsb, #width Unsigned Bit Field Extract - UDIV {Rd,} Rn, Rm Unsigned Divide - UMAAL RdLo, RdHi, Rn, Rm Unsigned Multiply Accumulate Accumulate Long (32 x 32 + 32 +32), 64-bit result - UMLAL RdLo, RdHi, Rn, Rm Unsigned Multiply with Accumulate (32 x 32 + 64), 64-bit result - UMULL RdLo, RdHi, Rn, Rm Unsigned Multiply (32 x 32), 64-bit result - UQADD16 {Rd,} Rn, Rm Unsigned Saturating Add 16 - UQADD8 {Rd,} Rn, Rm Unsigned Saturating Add 8 - UQASX {Rd,} Rn, Rm Unsigned Saturating Add and Subtract with Exchange - UQSAX {Rd,} Rn, Rm Unsigned Saturating Subtract and Add with Exchange - UQSUB16 {Rd,} Rn, Rm Unsigned Saturating Subtract 16 - UQSUB8 {Rd,} Rn, Rm Unsigned Saturating Subtract 8 - USAD8 {Rd,} Rn, Rm Unsigned Sum of Absolute Differences - USADA8 {Rd,} Rn, Rm, Ra Unsigned Sum of Absolute Differences and Accumulate - USAT Rd, #n, Rm {,shift #s} Unsigned Saturate Q USAT16 Rd, #n, Rm Unsigned Saturate 16 Q UASX {Rd,} Rn, Rm Unsigned Add and Subtract with Exchange GE USUB16 {Rd,} Rn, Rm Unsigned Subtract 16 GE USUB8 {Rd,} Rn, Rm Unsigned Subtract 8 GE UXTAB {Rd,} Rn, Rm,{,ROR #} Rotate, extend 8 bits to 32 and Add - UXTAB16 {Rd,} Rn, Rm,{,ROR #} Rotate, dual extend 8 bits to 16 and Add - UXTAH {Rd,} Rn, Rm,{,ROR #} Rotate, unsigned extend and Add Halfword - UXTB {Rd,} Rm {,ROR #n} Zero extend a byte - UXTB16 {Rd,} Rm {,ROR #n} Unsigned Extend Byte 16 - UXTH {Rd,} Rm {,ROR #n} Zero extend a halfword - VABS.F32 Sd, Sm Floating-point Absolute - VADD.F32 {Sd,} Sn, Sm Floating-point Add - VCMP.F32 Sd, <Sm | #0.0> Compare two floating-point registers, or one floating-point register and zero FPSCR VCMPE.F32 Sd, <Sm | #0.0> Compare two floating-point registers, or one floating-point register and zero with Invalid Operation check FPSCR 78 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Table 11-13. Cortex-M4 Instructions (Continued) Mnemonic Operands Description Flags VCVT.S32.F32 Sd, Sm Convert between floating-point and integer - VCVT.S16.F32 Sd, Sd, #fbits Convert between floating-point and fixed point - VCVTR.S32.F32 Sd, Sm Convert between floating-point and integer with rounding - VCVT<B|H>.F32.F16 Sd, Sm Converts half-precision value to single-precision - VCVTT<B|T>.F32.F16 Sd, Sm Converts single-precision register to half-precision - VDIV.F32 {Sd,} Sn, Sm Floating-point Divide - VFMA.F32 {Sd,} Sn, Sm Floating-point Fused Multiply Accumulate - VFNMA.F32 {Sd,} Sn, Sm Floating-point Fused Negate Multiply Accumulate - VFMS.F32 {Sd,} Sn, Sm Floating-point Fused Multiply Subtract - VFNMS.F32 {Sd,} Sn, Sm Floating-point Fused Negate Multiply Subtract - VLDM.F<32|64> Rn{!}, list Load Multiple extension registers - VLDR.F<32|64> <Dd|Sd>, [Rn] Load an extension register from memory - VLMA.F32 {Sd,} Sn, Sm Floating-point Multiply Accumulate - VLMS.F32 {Sd,} Sn, Sm Floating-point Multiply Subtract - VMOV.F32 Sd, #imm Floating-point Move immediate - VMOV Sd, Sm Floating-point Move register - VMOV Sn, Rt Copy ARM core register to single precision - VMOV Sm, Sm1, Rt, Rt2 Copy 2 ARM core registers to 2 single precision - VMOV Dd[x], Rt Copy ARM core register to scalar - VMOV Rt, Dn[x] Copy scalar to ARM core register - VMRS Rt, FPSCR Move FPSCR to ARM core register or APSR N,Z,C,V VMSR FPSCR, Rt Move to FPSCR from ARM Core register FPSCR VMUL.F32 {Sd,} Sn, Sm Floating-point Multiply - VNEG.F32 Sd, Sm Floating-point Negate - VNMLA.F32 Sd, Sn, Sm Floating-point Multiply and Add - VNMLS.F32 Sd, Sn, Sm Floating-point Multiply and Subtract - VNMUL {Sd,} Sn, Sm Floating-point Multiply - VPOP list Pop extension registers - VPUSH list Push extension registers - VSQRT.F32 Sd, Sm Calculates floating-point Square Root - VSTM Rn{!}, list Floating-point register Store Multiple - VSTR.F<32|64> Sd, [Rn] Stores an extension register to memory - VSUB.F<32|64> {Sd,} Sn, Sm Floating-point Subtract - WFI - Wait For Interrupt - SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 79 11.6.2 CMSIS Functions ISO/IEC cannot directly access some Cortex-M4 instructions. This section describes intrinsic functions that can generate these instructions, provided by the CMIS and that might be provided by a C compiler. If a C compiler does not support an appropriate intrinsic function, the user might have to use inline assembler to access some instructions. The CMSIS provides the following intrinsic functions to generate instructions that ISO/IEC C code cannot directly access: Table 11-14. CMSIS Functions to Generate some Cortex-M4 Instructions Instruction CMSIS Function CPSIE I void __enable_irq(void) CPSID I void __disable_irq(void) CPSIE F void __enable_fault_irq(void) CPSID F void __disable_fault_irq(void) ISB void __ISB(void) DSB void __DSB(void) DMB void __DMB(void) REV uint32_t __REV(uint32_t int value) REV16 uint32_t __REV16(uint32_t int value) REVSH uint32_t __REVSH(uint32_t int value) RBIT uint32_t __RBIT(uint32_t int value) SEV void __SEV(void) WFI void __WFI(void) The CMSIS also provides a number of functions for accessing the special registers using MRS and MSR instructions: Table 11-15. CMSIS Intrinsic Functions to Access the Special Registers Special Register Access CMSIS Function Read uint32_t __get_PRIMASK (void) Write void __set_PRIMASK (uint32_t value) Read uint32_t __get_FAULTMASK (void) Write void __set_FAULTMASK (uint32_t value) Read uint32_t __get_BASEPRI (void) Write void __set_BASEPRI (uint32_t value) Read uint32_t __get_CONTROL (void) Write void __set_CONTROL (uint32_t value) Read uint32_t __get_MSP (void) Write void __set_MSP (uint32_t TopOfMainStack) Read uint32_t __get_PSP (void) Write void __set_PSP (uint32_t TopOfProcStack) PRIMASK FAULTMASK BASEPRI CONTROL MSP PSP 80 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.6.3 Instruction Descriptions 11.6.3.1 Operands An instruction operand can be an ARM register, a constant, or another instruction-specific parameter. Instructions act on the operands and often store the result in a destination register. When there is a destination register in the instruction, it is usually specified before the operands. Operands in some instructions are flexible, can either be a register or a constant. See “Flexible Second Operand” . 11.6.3.2 Restrictions when Using PC or SP Many instructions have restrictions on whether the Program Counter (PC) or Stack Pointer (SP) for the operands or destination register can be used. See instruction descriptions for more information. Note: Bit[0] of any address written to the PC with a BX, BLX, LDM, LDR, or POP instruction must be 1 for correct execution, because this bit indicates the required instruction set, and the Cortex-M4 processor only supports Thumb instructions. 11.6.3.3 Flexible Second Operand Many general data processing instructions have a flexible second operand. This is shown as Operand2 in the descriptions of the syntax of each instruction. Operand2 can be a: “Constant” “Register with Optional Shift” Constant Specify an Operand2 constant in the form: #constant where constant can be: Any constant that can be produced by shifting an 8-bit value left by any number of bits within a 32-bit word Any constant of the form 0x00XY00XY Any constant of the form 0xXY00XY00 Any constant of the form 0xXYXYXYXY. Note: In the constants shown above, X and Y are hexadecimal digits. In addition, in a small number of instructions, constant can take a wider range of values. These are described in the individual instruction descriptions. When an Operand2 constant is used with the instructions MOVS, MVNS, ANDS, ORRS, ORNS, EORS, BICS, TEQ or TST, the carry flag is updated to bit[31] of the constant, if the constant is greater than 255 and can be produced by shifting an 8-bit value. These instructions do not affect the carry flag if Operand2 is any other constant. Instruction Substitution The assembler might be able to produce an equivalent instruction in cases where the user specifies a constant that is not permitted. For example, an assembler might assemble the instruction CMP Rd, #0xFFFFFFFE as the equivalent instruction CMN Rd, #0x2. Register with Optional Shift Specify an Operand2 register in the form: Rm {, shift} where: Rm is the register holding the data for the second operand. shift is an optional shift to be applied to Rm. It can be one of: SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 81 ASR #n arithmetic shift right n bits, 1 ≤ n ≤ 32. LSL #n logical shift left n bits, 1 ≤ n ≤ 31. LSR #n logical shift right n bits, 1 ≤ n ≤ 32. ROR #n rotate right n bits, 1 ≤ n ≤ 31. RRX rotate right one bit, with extend. - if omitted, no shift occurs, equivalent to LSL #0. If the user omits the shift, or specifies LSL #0, the instruction uses the value in Rm. If the user specifies a shift, the shift is applied to the value in Rm, and the resulting 32-bit value is used by the instruction. However, the contents in the register Rm remains unchanged. Specifying a register with shift also updates the carry flag when used with certain instructions. For information on the shift operations and how they affect the carry flag, see “Flexible Second Operand” 11.6.3.4 Shift Operations Register shift operations move the bits in a register left or right by a specified number of bits, the shift length. Register shift can be performed: Directly by the instructions ASR, LSR, LSL, ROR, and RRX, and the result is written to a destination register During the calculation of Operand2 by the instructions that specify the second operand as a register with shift. See “Flexible Second Operand” . The result is used by the instruction. The permitted shift lengths depend on the shift type and the instruction. If the shift length is 0, no shift occurs. Register shift operations update the carry flag except when the specified shift length is 0. The following subsections describe the various shift operations and how they affect the carry flag. In these descriptions, Rm is the register containing the value to be shifted, and n is the shift length. ASR Arithmetic shift right by n bits moves the left-hand 32-n bits of the register, Rm, to the right by n places, into the right-hand 32-n bits of the result. And it copies the original bit[31] of the register into the left-hand n bits of the result. See Figure 11-9. The ASR #n operation can be used to divide the value in the register Rm by 2n, with the result being rounded towards negative-infinity. When the instruction is ASRS or when ASR #n is used in Operand2 with the instructions MOVS, MVNS, ANDS, ORRS, ORNS, EORS, BICS, TEQ or TST, the carry flag is updated to the last bit shifted out, bit[n-1], of the register Rm. If n is 32 or more, then all the bits in the result are set to the value of bit[31] of Rm. If n is 32 or more and the carry flag is updated, it is updated to the value of bit[31] of Rm. Figure 11-9. ASR #3 &DUU\ )ODJ LSR Logical shift right by n bits moves the left-hand 32-n bits of the register Rm, to the right by n places, into the righthand 32-n bits of the result. And it sets the left-hand n bits of the result to 0. See Figure 11-10. 82 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 The LSR #n operation can be used to divide the value in the register Rm by 2n, if the value is regarded as an unsigned integer. When the instruction is LSRS or when LSR #n is used in Operand2 with the instructions MOVS, MVNS, ANDS, ORRS, ORNS, EORS, BICS, TEQ or TST, the carry flag is updated to the last bit shifted out, bit[n-1], of the register Rm. If n is 32 or more, then all the bits in the result are cleared to 0. If n is 33 or more and the carry flag is updated, it is updated to 0. Figure 11-10. LSR #3 &DUU\ )ODJ LSL Logical shift left by n bits moves the right-hand 32-n bits of the register Rm, to the left by n places, into the left-hand 32-n bits of the result; and it sets the right-hand n bits of the result to 0. See Figure 11-11. The LSL #n operation can be used to multiply the value in the register Rm by 2n, if the value is regarded as an unsigned integer or a two’s complement signed integer. Overflow can occur without warning. When the instruction is LSLS or when LSL #n, with non-zero n, is used in Operand2 with the instructions MOVS, MVNS, ANDS, ORRS, ORNS, EORS, BICS, TEQ or TST, the carry flag is updated to the last bit shifted out, bit[32n], of the register Rm. These instructions do not affect the carry flag when used with LSL #0. If n is 32 or more, then all the bits in the result are cleared to 0. If n is 33 or more and the carry flag is updated, it is updated to 0. Figure 11-11. LSL #3 &DUU\ )ODJ ROR Rotate right by n bits moves the left-hand 32-n bits of the register Rm, to the right by n places, into the right-hand 32-n bits of the result; and it moves the right-hand n bits of the register into the left-hand n bits of the result. See Figure 11-12. When the instruction is RORS or when ROR #n is used in Operand2 with the instructions MOVS, MVNS, ANDS, ORRS, ORNS, EORS, BICS, TEQ or TST, the carry flag is updated to the last bit rotation, bit[n-1], of the register Rm. If n is 32, then the value of the result is same as the value in Rm, and if the carry flag is updated, it is updated to bit[31] of Rm. ROR with shift length, n, more than 32 is the same as ROR with shift length n-32. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 83 Figure 11-12. ROR #3 &DUU\ )ODJ RRX Rotate right with extend moves the bits of the register Rm to the right by one bit; and it copies the carry flag into bit[31] of the result. See Figure 11-13. When the instruction is RRXS or when RRX is used in Operand2 with the instructions MOVS, MVNS, ANDS, ORRS, ORNS, EORS, BICS, TEQ or TST, the carry flag is updated to bit[0] of the register Rm. Figure 11-13. RRX &DUU\ )ODJ 11.6.3.5 Address Alignment An aligned access is an operation where a word-aligned address is used for a word, dual word, or multiple word access, or where a halfword-aligned address is used for a halfword access. Byte accesses are always aligned. The Cortex-M4 processor supports unaligned access only for the following instructions: LDR, LDRT LDRH, LDRHT LDRSH, LDRSHT STR, STRT STRH, STRHT All other load and store instructions generate a usage fault exception if they perform an unaligned access, and therefore their accesses must be address-aligned. For more information about usage faults, see “Fault Handling” . Unaligned accesses are usually slower than aligned accesses. In addition, some memory regions might not support unaligned accesses. Therefore, ARM recommends that programmers ensure that accesses are aligned. To avoid accidental generation of unaligned accesses, use the UNALIGN_TRP bit in the Configuration and Control Register to trap all unaligned accesses, see “Configuration and Control Register” . 11.6.3.6 PC-relative Expressions A PC-relative expression or label is a symbol that represents the address of an instruction or literal data. It is represented in the instruction as the PC value plus or minus a numeric offset. The assembler calculates the required offset from the label and the address of the current instruction. If the offset is too big, the assembler produces an error. 84 For B, BL, CBNZ, and CBZ instructions, the value of the PC is the address of the current instruction plus 4 bytes. For all other instructions that use labels, the value of the PC is the address of the current instruction plus 4 bytes, with bit[1] of the result cleared to 0 to make it word-aligned. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Your assembler might permit other syntaxes for PC-relative expressions, such as a label plus or minus a number, or an expression of the form [PC, #number]. 11.6.3.7 Conditional Execution Most data processing instructions can optionally update the condition flags in the Application Program Status Register (APSR) according to the result of the operation, see “Application Program Status Register” . Some instructions update all flags, and some only update a subset. If a flag is not updated, the original value is preserved. See the instruction descriptions for the flags they affect. An instruction can be executed conditionally, based on the condition flags set in another instruction, either: Immediately after the instruction that updated the flags After any number of intervening instructions that have not updated the flags. Conditional execution is available by using conditional branches or by adding condition code suffixes to instructions. See Table 11-16 for a list of the suffixes to add to instructions to make them conditional instructions. The condition code suffix enables the processor to test a condition based on the flags. If the condition test of a conditional instruction fails, the instruction: Does not execute Does not write any value to its destination register Does not affect any of the flags Does not generate any exception. Conditional instructions, except for conditional branches, must be inside an If-Then instruction block. See “IT” for more information and restrictions when using the IT instruction. Depending on the vendor, the assembler might automatically insert an IT instruction if there are conditional instructions outside the IT block. The CBZ and CBNZ instructions are used to compare the value of a register against zero and branch on the result. This section describes: “Condition Flags” “Condition Code Suffixes” . Condition Flags The APSR contains the following condition flags: N Set to 1 when the result of the operation was negative, cleared to 0 otherwise. Z Set to 1 when the result of the operation was zero, cleared to 0 otherwise. C Set to 1 when the operation resulted in a carry, cleared to 0 otherwise. V Set to 1 when the operation caused overflow, cleared to 0 otherwise. For more information about the APSR, see “Program Status Register” . A carry occurs: If the result of an addition is greater than or equal to 232 If the result of a subtraction is positive or zero As the result of an inline barrel shifter operation in a move or logical instruction. An overflow occurs when the sign of the result, in bit[31], does not match the sign of the result, had the operation been performed at infinite precision, for example: If adding two negative values results in a positive value If adding two positive values results in a negative value If subtracting a positive value from a negative value generates a positive value If subtracting a negative value from a positive value generates a negative value. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 85 The Compare operations are identical to subtracting, for CMP, or adding, for CMN, except that the result is discarded. See the instruction descriptions for more information. Note: Most instructions update the status flags only if the S suffix is specified. See the instruction descriptions for more information. Condition Code Suffixes The instructions that can be conditional have an optional condition code, shown in syntax descriptions as {cond}. Conditional execution requires a preceding IT instruction. An instruction with a condition code is only executed if the condition code flags in the APSR meet the specified condition. Table 11-16 shows the condition codes to use. A conditional execution can be used with the IT instruction to reduce the number of branch instructions in code. Table 11-16 also shows the relationship between condition code suffixes and the N, Z, C, and V flags. Table 11-16. Condition Code Suffixes Suffix Flags Meaning EQ Z=1 Equal NE Z=0 Not equal CS or HS C=1 Higher or same, unsigned ≥ CC or LO C=0 Lower, unsigned < MI N=1 Negative PL N=0 Positive or zero VS V=1 Overflow VC V=0 No overflow HI C = 1 and Z = 0 Higher, unsigned > LS C = 0 or Z = 1 Lower or same, unsigned ≤ GE N=V Greater than or equal, signed ≥ LT N != V Less than, signed < GT Z = 0 and N = V Greater than, signed > LE Z = 1 and N != V Less than or equal, signed ≤ AL Can have any value Always. This is the default when no suffix is specified. Absolute Value The example below shows the use of a conditional instruction to find the absolute value of a number. R0 = ABS(R1). MOVS R0, R1 ; R0 = R1, setting flags IT MI ; IT instruction for the negative condition RSBMI R0, R1, #0 ; If negative, R0 = -R1 Compare and Update Value The example below shows the use of conditional instructions to update the value of R4 if the signed values R0 is greater than R1 and R2 is greater than R3. CMP R0, R1 ; Compare R0 and R1, setting flags ITT GT ; IT instruction for the two GT conditions CMPGT R2, R3 ; If 'greater than', compare R2 and R3, setting flags MOVGT R4, R5 ; If still 'greater than', do R4 = R5 86 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.6.3.8 Instruction Width Selection There are many instructions that can generate either a 16-bit encoding or a 32-bit encoding depending on the operands and destination register specified. For some of these instructions, the user can force a specific instruction size by using an instruction width suffix. The .W suffix forces a 32-bit instruction encoding. The .N suffix forces a 16-bit instruction encoding. If the user specifies an instruction width suffix and the assembler cannot generate an instruction encoding of the requested width, it generates an error. Note: In some cases, it might be necessary to specify the .W suffix, for example if the operand is the label of an instruction or literal data, as in the case of branch instructions. This is because the assembler might not automatically generate the right size encoding. To use an instruction width suffix, place it immediately after the instruction mnemonic and condition code, if any. The example below shows instructions with the instruction width suffix. BCS.W label ; creates a 32-bit instruction even for a short ; branch ADDS.W R0, R0, R1 ; creates a 32-bit instruction even though the same ; operation can be done by a 16-bit instruction SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 87 11.6.4 Memory Access Instructions The table below shows the memory access instructions: Table 11-17. 88 Memory Access Instructions Mnemonic Description ADR Load PC-relative address CLREX Clear Exclusive LDM{mode} Load Multiple registers LDR{type} Load Register using immediate offset LDR{type} Load Register using register offset LDR{type}T Load Register with unprivileged access LDR Load Register using PC-relative address LDRD Load Register Dual LDREX{type} Load Register Exclusive POP Pop registers from stack PUSH Push registers onto stack STM{mode} Store Multiple registers STR{type} Store Register using immediate offset STR{type} Store Register using register offset STR{type}T Store Register with unprivileged access STREX{type} Store Register Exclusive SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.6.4.1 ADR Load PC-relative address. Syntax ADR{cond} Rd, label where: cond is an optional condition code, see “Conditional Execution” . Rd is the destination register. label is a PC-relative expression. See “PC-relative Expressions” . Operation ADR determines the address by adding an immediate value to the PC, and writes the result to the destination register. ADR produces position-independent code, because the address is PC-relative. If ADR is used to generate a target address for a BX or BLX instruction, ensure that bit[0] of the address generated is set to 1 for correct execution. Values of label must be within the range of −4095 to +4095 from the address in the PC. Note: The user might have to use the .W suffix to get the maximum offset range or to generate addresses that are not wordaligned. See “Instruction Width Selection” . Restrictions Rd must not be SP and must not be PC. Condition Flags This instruction does not change the flags. Examples ADR R1, TextMessage ; Write address value of a location labelled as ; TextMessage to R1 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 89 11.6.4.2 LDR and STR, Immediate Offset Load and Store with immediate offset, pre-indexed immediate offset, or post-indexed immediate offset. Syntax op{type}{cond} Rt, op{type}{cond} Rt, op{type}{cond} Rt, opD{cond} Rt, Rt2, opD{cond} Rt, Rt2, opD{cond} Rt, Rt2, [Rn {, #offset}] [Rn, #offset]! [Rn], #offset [Rn {, #offset}] [Rn, #offset]! [Rn], #offset ; ; ; ; ; ; immediate offset pre-indexed post-indexed immediate offset, two words pre-indexed, two words post-indexed, two words where: op is one of: LDR Load Register. STR Store Register. type is one of: B unsigned byte, zero extend to 32 bits on loads. SB signed byte, sign extend to 32 bits (LDR only). H unsigned halfword, zero extend to 32 bits on loads. SH signed halfword, sign extend to 32 bits (LDR only). - omit, for word. cond is an optional condition code, see “Conditional Execution” . Rt is the register to load or store. Rn is the register on which the memory address is based. offset is an offset from Rn. If offset is omitted, the address is the contents of Rn. Rt2 is the additional register to load or store for two-word operations. Operation LDR instructions load one or two registers with a value from memory. STR instructions store one or two register values to memory. Load and store instructions with immediate offset can use the following addressing modes: Offset Addressing The offset value is added to or subtracted from the address obtained from the register Rn. The result is used as the address for the memory access. The register Rn is unaltered. The assembly language syntax for this mode is: [Rn, #offset] Pre-indexed Addressing The offset value is added to or subtracted from the address obtained from the register Rn. The result is used as the address for the memory access and written back into the register Rn. The assembly language syntax for this mode is: [Rn, #offset]! Post-indexed Addressing The address obtained from the register Rn is used as the address for the memory access. The offset value is added to or subtracted from the address, and written back into the register Rn. The assembly language syntax for this mode is: [Rn], #offset 90 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 The value to load or store can be a byte, halfword, word, or two words. Bytes and halfwords can either be signed or unsigned. See “Address Alignment” . The table below shows the ranges of offset for immediate, pre-indexed and post-indexed forms. Table 11-18. Offset Ranges Instruction Type Immediate Offset Pre-indexed Post-indexed Word, halfword, signed halfword, byte, or signed byte -255 to 4095 -255 to 255 -255 to 255 Two words multiple of 4 in the range -1020 to 1020 multiple of 4 in the range -1020 to 1020 multiple of 4 in the range -1020 to 1020 Restrictions For load instructions: Rt can be SP or PC for word loads only Rt must be different from Rt2 for two-word loads Rn must be different from Rt and Rt2 in the pre-indexed or post-indexed forms. When Rt is PC in a word load instruction: Bit[0] of the loaded value must be 1 for correct execution A branch occurs to the address created by changing bit[0] of the loaded value to 0 If the instruction is conditional, it must be the last instruction in the IT block. For store instructions: Rt can be SP for word stores only Rt must not be PC Rn must not be PC Rn must be different from Rt and Rt2 in the pre-indexed or post-indexed forms. Condition Flags These instructions do not change the flags. Examples LDR LDRNE R8, [R10] R2, [R5, #960]! STR R2, [R9,#const-struc] STRH R3, [R4], #4 LDRD R8, R9, [R3, #0x20] STRD R0, R1, [R8], #-16 ; ; ; ; ; ; ; ; ; ; ; ; ; ; Loads R8 from the address in R10. Loads (conditionally) R2 from a word 960 bytes above the address in R5, and increments R5 by 960. const-struc is an expression evaluating to a constant in the range 0-4095. Store R3 as halfword data into address in R4, then increment R4 by 4 Load R8 from a word 32 bytes above the address in R3, and load R9 from a word 36 bytes above the address in R3 Store R0 to address in R8, and store R1 to a word 4 bytes above the address in R8, and then decrement R8 by 16. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 91 11.6.4.3 LDR and STR, Register Offset Load and Store with register offset. Syntax op{type}{cond} Rt, [Rn, Rm {, LSL #n}] where: op is one of: LDR Load Register. STR Store Register. type is one of: B unsigned byte, zero extend to 32 bits on loads. SB signed byte, sign extend to 32 bits (LDR only). H unsigned halfword, zero extend to 32 bits on loads. SH signed halfword, sign extend to 32 bits (LDR only). - omit, for word. cond is an optional condition code, see “Conditional Execution” . Rt is the register to load or store. Rn is the register on which the memory address is based. Rm is a register containing a value to be used as the offset. LSL #n is an optional shift, with n in the range 0 to 3. Operation LDR instructions load a register with a value from memory. STR instructions store a register value into memory. The memory address to load from or store to is at an offset from the register Rn. The offset is specified by the register Rm and can be shifted left by up to 3 bits using LSL. The value to load or store can be a byte, halfword, or word. For load instructions, bytes and halfwords can either be signed or unsigned. See “Address Alignment” . Restrictions In these instructions: Rn must not be PC Rm must not be SP and must not be PC Rt can be SP only for word loads and word stores Rt can be PC only for word loads. When Rt is PC in a word load instruction: Bit[0] of the loaded value must be 1 for correct execution, and a branch occurs to this halfword-aligned address If the instruction is conditional, it must be the last instruction in the IT block. Condition Flags These instructions do not change the flags. Examples STR LDRSB 92 R0, [R5, R1] ; Store value of R0 into an address equal to ; sum of R5 and R1 R0, [R5, R1, LSL #1] ; Read byte value from an address equal to SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 STR ; ; R0, [R1, R2, LSL #2] ; ; sum of R5 and two times R1, sign extended it to a word value and put it in R0 Stores R0 to an address equal to sum of R1 and four times R2 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 93 11.6.4.4 LDR and STR, Unprivileged Load and Store with unprivileged access. Syntax op{type}T{cond} Rt, [Rn {, #offset}] ; immediate offset where: op is one of: LDR Load Register. STR Store Register. type is one of: B unsigned byte, zero extend to 32 bits on loads. SB signed byte, sign extend to 32 bits (LDR only). H unsigned halfword, zero extend to 32 bits on loads. SH signed halfword, sign extend to 32 bits (LDR only). - omit, for word. cond is an optional condition code, see “Conditional Execution” . Rt is the register to load or store. Rn is the register on which the memory address is based. offset is an offset from Rn and can be 0 to 255. If offset is omitted, the address is the value in Rn. Operation These load and store instructions perform the same function as the memory access instructions with immediate offset, see “LDR and STR, Immediate Offset” . The difference is that these instructions have only unprivileged access even when used in privileged software. When used in unprivileged software, these instructions behave in exactly the same way as normal memory access instructions with immediate offset. Restrictions In these instructions: Rn must not be PC Rt must not be SP and must not be PC. Condition Flags These instructions do not change the flags. Examples 94 STRBTEQ R4, [R7] LDRHT R2, [R2, #8] ; ; ; ; Conditionally store least significant byte in R4 to an address in R7, with unprivileged access Load halfword value from an address equal to sum of R2 and 8 into R2, with unprivileged access SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.6.4.5 LDR, PC-relative Load register from memory. Syntax LDR{type}{cond} Rt, label LDRD{cond} Rt, Rt2, label ; Load two words where: type is one of: B unsigned byte, zero extend to 32 bits. SB signed byte, sign extend to 32 bits. H unsigned halfword, zero extend to 32 bits. SH signed halfword, sign extend to 32 bits. - omit, for word. cond is an optional condition code, see “Conditional Execution” . Rt is the register to load or store. Rt2 is the second register to load or store. label is a PC-relative expression. See “PC-relative Expressions” . Operation LDR loads a register with a value from a PC-relative memory address. The memory address is specified by a label or by an offset from the PC. The value to load or store can be a byte, halfword, or word. For load instructions, bytes and halfwords can either be signed or unsigned. See “Address Alignment” . label must be within a limited range of the current instruction. The table below shows the possible offsets between label and the PC. Table 11-19. Offset Ranges Instruction Type Offset Range Word, halfword, signed halfword, byte, signed byte -4095 to 4095 Two words -1020 to 1020 The user might have to use the .W suffix to get the maximum offset range. See “Instruction Width Selection” . Restrictions In these instructions: Rt can be SP or PC only for word loads Rt2 must not be SP and must not be PC Rt must be different from Rt2. When Rt is PC in a word load instruction: Bit[0] of the loaded value must be 1 for correct execution, and a branch occurs to this halfword-aligned address If the instruction is conditional, it must be the last instruction in the IT block. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 95 Condition Flags These instructions do not change the flags. Examples 96 LDR R0, LookUpTable LDRSB R7, localdata ; ; ; ; ; Load R0 with a word of data from an address labelled as LookUpTable Load a byte value from an address labelled as localdata, sign extend it to a word value, and put it in R7 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.6.4.6 LDM and STM Load and Store Multiple registers. Syntax op{addr_mode}{cond} Rn{!}, reglist where: op is one of: LDM Load Multiple registers. STM Store Multiple registers. addr_mode is any one of the following: IA Increment address After each access. This is the default. DB Decrement address Before each access. cond is an optional condition code, see “Conditional Execution” . Rn is the register on which the memory addresses are based. ! is an optional writeback suffix. If ! is present, the final address, that is loaded from or stored to, is written back into Rn. reglist is a list of one or more registers to be loaded or stored, enclosed in braces. It can contain register ranges. It must be comma separated if it contains more than one register or register range, see “Examples” . LDM and LDMFD are synonyms for LDMIA. LDMFD refers to its use for popping data from Full Descending stacks. LDMEA is a synonym for LDMDB, and refers to its use for popping data from Empty Ascending stacks. STM and STMEA are synonyms for STMIA. STMEA refers to its use for pushing data onto Empty Ascending stacks. STMFD is s synonym for STMDB, and refers to its use for pushing data onto Full Descending stacks Operation LDM instructions load the registers in reglist with word values from memory addresses based on Rn. STM instructions store the word values in the registers in reglist to memory addresses based on Rn. For LDM, LDMIA, LDMFD, STM, STMIA, and STMEA the memory addresses used for the accesses are at 4-byte intervals ranging from Rn to Rn + 4 * (n-1), where n is the number of registers in reglist. The accesses happens in order of increasing register numbers, with the lowest numbered register using the lowest memory address and the highest number register using the highest memory address. If the writeback suffix is specified, the value of Rn + 4 * (n-1) is written back to Rn. For LDMDB, LDMEA, STMDB, and STMFD the memory addresses used for the accesses are at 4-byte intervals ranging from Rn to Rn - 4 * (n-1), where n is the number of registers in reglist. The accesses happen in order of decreasing register numbers, with the highest numbered register using the highest memory address and the lowest number register using the lowest memory address. If the writeback suffix is specified, the value of Rn - 4 * (n-1) is written back to Rn. The PUSH and POP instructions can be expressed in this form. See “PUSH and POP” for details. Restrictions In these instructions: Rn must not be PC reglist must not contain SP In any STM instruction, reglist must not contain PC SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 97 In any LDM instruction, reglist must not contain PC if it contains LR reglist must not contain Rn if the writeback suffix is specified. When PC is in reglist in an LDM instruction: Bit[0] of the value loaded to the PC must be 1 for correct execution, and a branch occurs to this halfwordaligned address If the instruction is conditional, it must be the last instruction in the IT block. Condition Flags These instructions do not change the flags. Examples LDM STMDB R8,{R0,R2,R9} ; LDMIA is a synonym for LDM R1!,{R3-R6,R11,R12} Incorrect Examples STM LDM 98 R5!,{R5,R4,R9} ; Value stored for R5 is unpredictable R2, {} ; There must be at least one register in the list SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.6.4.7 PUSH and POP Push registers onto, and pop registers off a full-descending stack. Syntax PUSH{cond} reglist POP{cond} reglist where: cond is an optional condition code, see “Conditional Execution” . reglist is a non-empty list of registers, enclosed in braces. It can contain register ranges. It must be comma separated if it contains more than one register or register range. PUSH and POP are synonyms for STMDB and LDM (or LDMIA) with the memory addresses for the access based on SP, and with the final address for the access written back to the SP. PUSH and POP are the preferred mnemonics in these cases. Operation PUSH stores registers on the stack in order of decreasing the register numbers, with the highest numbered register using the highest memory address and the lowest numbered register using the lowest memory address. POP loads registers from the stack in order of increasing register numbers, with the lowest numbered register using the lowest memory address and the highest numbered register using the highest memory address. See “LDM and STM” for more information. Restrictions In these instructions: reglist must not contain SP For the PUSH instruction, reglist must not contain PC For the POP instruction, reglist must not contain PC if it contains LR. When PC is in reglist in a POP instruction: Bit[0] of the value loaded to the PC must be 1 for correct execution, and a branch occurs to this halfwordaligned address If the instruction is conditional, it must be the last instruction in the IT block. Condition Flags These instructions do not change the flags. Examples PUSH PUSH POP {R0,R4-R7} {R2,LR} {R0,R10,PC} SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 99 11.6.4.8 LDREX and STREX Load and Store Register Exclusive. Syntax LDREX{cond} Rt, [Rn {, #offset}] STREX{cond} Rd, Rt, [Rn {, #offset}] LDREXB{cond} Rt, [Rn] STREXB{cond} Rd, Rt, [Rn] LDREXH{cond} Rt, [Rn] STREXH{cond} Rd, Rt, [Rn] where: cond is an optional condition code, see “Conditional Execution” . Rd is the destination register for the returned status. Rt is the register to load or store. Rn is the register on which the memory address is based. offset is an optional offset applied to the value in Rn. If offset is omitted, the address is the value in Rn. Operation LDREX, LDREXB, and LDREXH load a word, byte, and halfword respectively from a memory address. STREX, STREXB, and STREXH attempt to store a word, byte, and halfword respectively to a memory address. The address used in any Store-Exclusive instruction must be the same as the address in the most recently executed Load-exclusive instruction. The value stored by the Store-Exclusive instruction must also have the same data size as the value loaded by the preceding Load-exclusive instruction. This means software must always use a Load-exclusive instruction and a matching Store-Exclusive instruction to perform a synchronization operation, see “Synchronization Primitives” . If an Store-Exclusive instruction performs the store, it writes 0 to its destination register. If it does not perform the store, it writes 1 to its destination register. If the Store-Exclusive instruction writes 0 to the destination register, it is guaranteed that no other process in the system has accessed the memory location between the Load-exclusive and Store-Exclusive instructions. For reasons of performance, keep the number of instructions between corresponding Load-Exclusive and StoreExclusive instruction to a minimum. The result of executing a Store-Exclusive instruction to an address that is different from that used in the preceding Load-Exclusive instruction is unpredictable. Restrictions In these instructions: Do not use PC Do not use SP for Rd and Rt For STREX, Rd must be different from both Rt and Rn The value of offset must be a multiple of four in the range 0-1020. Condition Flags These instructions do not change the flags. Examples MOV LDREX CMP 100 R1, #0x1 R0, [LockAddr] R0, #0 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 ; Initialize the ‘lock taken’ value try ; Load the lock value ; Is the lock free? ITT STREXEQ CMPEQ BNE .... EQ R0, R1, [LockAddr] R0, #0 try ; ; ; ; ; IT instruction for STREXEQ and CMPEQ Try and claim the lock Did this succeed? No – try again Yes – we have the lock SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 101 11.6.4.9 CLREX Clear Exclusive. Syntax CLREX{cond} where: cond is an optional condition code, see “Conditional Execution” . Operation Use CLREX to make the next STREX, STREXB, or STREXH instruction write 1 to its destination register and fail to perform the store. It is useful in exception handler code to force the failure of the store exclusive if the exception occurs between a load exclusive instruction and the matching store exclusive instruction in a synchronization operation. See “Synchronization Primitives” for more information. Condition Flags These instructions do not change the flags. Examples CLREX 102 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.6.5 General Data Processing Instructions The table below shows the data processing instructions: Table 11-20. Data Processing Instructions Mnemonic Description ADC Add with Carry ADD Add ADDW Add AND Logical AND ASR Arithmetic Shift Right BIC Bit Clear CLZ Count leading zeros CMN Compare Negative CMP Compare EOR Exclusive OR LSL Logical Shift Left LSR Logical Shift Right MOV Move MOVT Move Top MOVW Move 16-bit constant MVN Move NOT ORN Logical OR NOT ORR Logical OR RBIT Reverse Bits REV Reverse byte order in a word REV16 Reverse byte order in each halfword REVSH Reverse byte order in bottom halfword and sign extend ROR Rotate Right RRX Rotate Right with Extend RSB Reverse Subtract SADD16 Signed Add 16 SADD8 Signed Add 8 SASX Signed Add and Subtract with Exchange SSAX Signed Subtract and Add with Exchange SBC Subtract with Carry SHADD16 Signed Halving Add 16 SHADD8 Signed Halving Add 8 SHASX Signed Halving Add and Subtract with Exchange SHSAX Signed Halving Subtract and Add with Exchange SHSUB16 Signed Halving Subtract 16 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 103 Table 11-20. 104 Data Processing Instructions (Continued) Mnemonic Description SHSUB8 Signed Halving Subtract 8 SSUB16 Signed Subtract 16 SSUB8 Signed Subtract 8 SUB Subtract SUBW Subtract TEQ Test Equivalence TST Test UADD16 Unsigned Add 16 UADD8 Unsigned Add 8 UASX Unsigned Add and Subtract with Exchange USAX Unsigned Subtract and Add with Exchange UHADD16 Unsigned Halving Add 16 UHADD8 Unsigned Halving Add 8 UHASX Unsigned Halving Add and Subtract with Exchange UHSAX Unsigned Halving Subtract and Add with Exchange UHSUB16 Unsigned Halving Subtract 16 UHSUB8 Unsigned Halving Subtract 8 USAD8 Unsigned Sum of Absolute Differences USADA8 Unsigned Sum of Absolute Differences and Accumulate USUB16 Unsigned Subtract 16 USUB8 Unsigned Subtract 8 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.6.5.1 ADD, ADC, SUB, SBC, and RSB Add, Add with carry, Subtract, Subtract with carry, and Reverse Subtract. Syntax op{S}{cond} {Rd,} Rn, Operand2 op{cond} {Rd,} Rn, #imm12 ; ADD and SUB only where: op is one of: ADD Add. ADC Add with Carry. SUB Subtract. SBC Subtract with Carry. RSB Reverse Subtract. S is an optional suffix. If S is specified, the condition code flags are updated on the result operation, see “Conditional Execution” . cond is an optional condition code, see “Conditional Execution” . Rd is the destination register. If Rd is omitted, the destination register is Rn. Rn is the register holding the first operand. Operand2 is a flexible second operand. See “Flexible Second Operand” for details of the options. imm12 is any value in the range 0-4095. of the Operation The ADD instruction adds the value of Operand2 or imm12 to the value in Rn. The ADC instruction adds the values in Rn and Operand2, together with the carry flag. The SUB instruction subtracts the value of Operand2 or imm12 from the value in Rn. The SBC instruction subtracts the value of Operand2 from the value in Rn. If the carry flag is clear, the result is reduced by one. The RSB instruction subtracts the value in Rn from the value of Operand2. This is useful because of the wide range of options for Operand2. Use ADC and SBC to synthesize multiword arithmetic, see Multiword arithmetic examples on. See also “ADR” . Note: ADDW is equivalent to the ADD syntax that uses the imm12 operand. SUBW is equivalent to the SUB syntax that uses the imm12 operand. Restrictions In these instructions: Operand2 must not be SP and must not be PC Rd can be SP only in ADD and SUB, and only with the additional restrictions: ̶ Rn must also be SP ̶ Any shift in Operand2 must be limited to a maximum of 3 bits using LSL Rn can be SP only in ADD and SUB Rd can be PC only in the ADD{cond} PC, PC, Rm instruction where: ̶ The user must not specify the S suffix ̶ Rm must not be PC and must not be SP SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 105 ̶ If the instruction is conditional, it must be the last instruction in the IT block With the exception of the ADD{cond} PC, PC, Rm instruction, Rn can be PC only in ADD and SUB, and only with the additional restrictions: ̶ The user must not specify the S suffix ̶ The second operand must be a constant in the range 0 to 4095. ̶ Note: When using the PC for an addition or a subtraction, bits[1:0] of the PC are rounded to 0b00 before performing the calculation, making the base address for the calculation word-aligned. ̶ Note: To generate the address of an instruction, the constant based on the value of the PC must be adjusted. ARM recommends to use the ADR instruction instead of ADD or SUB with Rn equal to the PC, because the assembler automatically calculates the correct constant for the ADR instruction. When Rd is PC in the ADD{cond} PC, PC, Rm instruction: Bit[0] of the value written to the PC is ignored A branch occurs to the address created by forcing bit[0] of that value to 0. Condition Flags If S is specified, these instructions update the N, Z, C and V flags according to the result. Examples ADD SUBS RSB ADCHI R2, R1, R3 R8, R6, #240 R4, R4, #1280 R11, R0, R3 ; ; ; ; Sets the flags on the result Subtracts contents of R4 from 1280 Only executed if C flag set and Z flag clear. Multiword Arithmetic Examples The example below shows two instructions that add a 64-bit integer contained in R2 and R3 to another 64-bit integer contained in R0 and R1, and place the result in R4 and R5. 64-bit Addition Example ADDS R4, R0, R2 ADC R5, R1, R3 ; add the least significant words ; add the most significant words with carry Multiword values do not have to use consecutive registers. The example below shows instructions that subtract a 96-bit integer contained in R9, R1, and R11 from another contained in R6, R2, and R8. The example stores the result in R6, R9, and R2. 96-bit Subtraction Example SUBS R6, R6, R9 SBCS R9, R2, R1 SBC R2, R8, R11 106 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 ; subtract the least significant words ; subtract the middle words with carry ; subtract the most significant words with carry 11.6.5.2 AND, ORR, EOR, BIC, and ORN Logical AND, OR, Exclusive OR, Bit Clear, and OR NOT. Syntax op{S}{cond} {Rd,} Rn, Operand2 where: op is one of: AND logical AND. ORR logical OR, or bit set. EOR logical Exclusive OR. BIC logical AND NOT, or bit clear. ORN logical OR NOT. S is an optional suffix. If S is specified, the condition code flags are updated on the result operation, see “Conditional Execution” . cond is an optional condition code, see “Conditional Execution” . Rd is the destination register. Rn is the register holding the first operand. Operand2 is a flexible second operand. See “Flexible Second Operand” for details of the options of the Operation The AND, EOR, and ORR instructions perform bitwise AND, Exclusive OR, and OR operations on the values in Rn and Operand2. The BIC instruction performs an AND operation on the bits in Rn with the complements of the corresponding bits in the value of Operand2. The ORN instruction performs an OR operation on the bits in Rn with the complements of the corresponding bits in the value of Operand2. Restrictions Do not use SP and do not use PC. Condition Flags If S is specified, these instructions: Update the N and Z flags according to the result Can update the C flag during the calculation of Operand2, see “Flexible Second Operand” Do not affect the V flag. Examples AND ORREQ ANDS EORS BIC ORN ORNS R9, R2, #0xFF00 R2, R0, R5 R9, R8, #0x19 R7, R11, #0x18181818 R0, R1, #0xab R7, R11, R14, ROR #4 R7, R11, R14, ASR #32 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 107 11.6.5.3 ASR, LSL, LSR, ROR, and RRX Arithmetic Shift Right, Logical Shift Left, Logical Shift Right, Rotate Right, and Rotate Right with Extend. Syntax op{S}{cond} Rd, Rm, Rs op{S}{cond} Rd, Rm, #n RRX{S}{cond} Rd, Rm where: op is one of: ASR Arithmetic Shift Right. LSL Logical Shift Left. LSR Logical Shift Right. ROR Rotate Right. S is an optional suffix. If S is specified, the condition code flags are updated on the result operation, see “Conditional Execution” . Rd is the destination register. Rm is the register holding the value to be shifted. Rs is the register holding the shift length to apply to the value in Rm. Only the least of the significant byte is used and can be in the range 0 to 255. n is the shift length. The range of shift length depends on the instruction: ASR shift length from 1 to 32 LSL shift length from 0 to 31 LSR shift length from 1 to 32 ROR shift length from 0 to 31 MOVS Rd, Rm is the preferred syntax for LSLS Rd, Rm, #0. Operation ASR, LSL, LSR, and ROR move the bits in the register Rm to the left or right by the number of places specified by constant n or register Rs. RRX moves the bits in register Rm to the right by 1. In all these instructions, the result is written to Rd, but the value in register Rm remains unchanged. For details on what result is generated by the different instructions, see “Shift Operations” . Restrictions Do not use SP and do not use PC. Condition Flags If S is specified: These instructions update the N and Z flags according to the result The C flag is updated to the last bit shifted out, except when the shift length is 0, see “Shift Operations” . Examples ASR SLS LSR ROR RRX 108 R7, R1, R4, R4, R4, R8, R2, R5, R5, R5 #9 #3 #6 R6 ; ; ; ; ; Arithmetic shift right by 9 bits Logical shift left by 3 bits with flag update Logical shift right by 6 bits Rotate right by the value in the bottom byte of R6 Rotate right with extend. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.6.5.4 CLZ Count Leading Zeros. Syntax CLZ{cond} Rd, Rm where: cond is an optional condition code, see “Conditional Execution” . Rd is the destination register. Rm is the operand register. Operation The CLZ instruction counts the number of leading zeros in the value in Rm and returns the result in Rd. The result value is 32 if no bits are set and zero if bit[31] is set. Restrictions Do not use SP and do not use PC. Condition Flags This instruction does not change the flags. Examples CLZ CLZNE R4,R9 R2,R3 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 109 11.6.5.5 CMP and CMN Compare and Compare Negative. Syntax CMP{cond} Rn, Operand2 CMN{cond} Rn, Operand2 where: cond is an optional condition code, see “Conditional Execution” . Rn is the register holding the first operand. Operand2 is a flexible second operand. See “Flexible Second Operand” for details of the options Operation These instructions compare the value in a register with Operand2. They update the condition flags on the result, but do not write the result to a register. The CMP instruction subtracts the value of Operand2 from the value in Rn. This is the same as a SUBS instruction, except that the result is discarded. The CMN instruction adds the value of Operand2 to the value in Rn. This is the same as an ADDS instruction, except that the result is discarded. Restrictions In these instructions: Do not use PC Operand2 must not be SP. Condition Flags These instructions update the N, Z, C and V flags according to the result. Examples CMP CMN CMPGT 110 R2, R9 R0, #6400 SP, R7, LSL #2 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.6.5.6 MOV and MVN Move and Move NOT. Syntax MOV{S}{cond} Rd, Operand2 MOV{cond} Rd, #imm16 MVN{S}{cond} Rd, Operand2 where: S is an optional suffix. If S is specified, the condition code flags are updated on the result operation, see “Conditional Execution” . cond is an optional condition code, see “Conditional Execution” . Rd is the destination register. Operand2 is a flexible second operand. See “Flexible Second Operand” for details of the options imm16 is any value in the range 0-65535. of the Operation The MOV instruction copies the value of Operand2 into Rd. When Operand2 in a MOV instruction is a register with a shift other than LSL #0, the preferred syntax is the corresponding shift instruction: ASR{S}{cond} Rd, Rm, #n is the preferred syntax for MOV{S}{cond} Rd, Rm, ASR #n LSL{S}{cond} Rd, Rm, #n is the preferred syntax for MOV{S}{cond} Rd, Rm, LSL #n if n != 0 LSR{S}{cond} Rd, Rm, #n is the preferred syntax for MOV{S}{cond} Rd, Rm, LSR #n ROR{S}{cond} Rd, Rm, #n is the preferred syntax for MOV{S}{cond} Rd, Rm, ROR #n RRX{S}{cond} Rd, Rm is the preferred syntax for MOV{S}{cond} Rd, Rm, RRX. Also, the MOV instruction permits additional forms of Operand2 as synonyms for shift instructions: MOV{S}{cond} Rd, Rm, ASR Rs is a synonym for ASR{S}{cond} Rd, Rm, Rs MOV{S}{cond} Rd, Rm, LSL Rs is a synonym for LSL{S}{cond} Rd, Rm, Rs MOV{S}{cond} Rd, Rm, LSR Rs is a synonym for LSR{S}{cond} Rd, Rm, Rs MOV{S}{cond} Rd, Rm, ROR Rs is a synonym for ROR{S}{cond} Rd, Rm, Rs See “ASR, LSL, LSR, ROR, and RRX” . The MVN instruction takes the value of Operand2, performs a bitwise logical NOT operation on the value, and places the result into Rd. The MOVW instruction provides the same function as MOV, but is restricted to using the imm16 operand. Restrictions SP and PC only can be used in the MOV instruction, with the following restrictions: The second operand must be a register without shift The S suffix must not be specified. When Rd is PC in a MOV instruction: Bit[0] of the value written to the PC is ignored A branch occurs to the address created by forcing bit[0] of that value to 0. Though it is possible to use MOV as a branch instruction, ARM strongly recommends the use of a BX or BLX instruction to branch for software portability to the ARM instruction set. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 111 Condition Flags If S is specified, these instructions: Update the N and Z flags according to the result Can update the C flag during the calculation of Operand2, see “Flexible Second Operand” Do not affect the V flag. Examples MOVS R11, #0x000B ; Write value of 0x000B to R11, flags get updated MOV R1, #0xFA05 ; Write value of 0xFA05 to R1, flags are not updated MOVS R10, R12 ; Write value in R12 to R10, flags get updated MOV R3, #23 ; Write value of 23 to R3 MOV R8, SP ; Write value of stack pointer to R8 MVNS R2, #0xF ; Write value of 0xFFFFFFF0 (bitwise inverse of 0xF) ; to the R2 and update flags. 112 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.6.5.7 MOVT Move Top. Syntax MOVT{cond} Rd, #imm16 where: cond is an optional condition code, see “Conditional Execution” . Rd is the destination register. imm16 is a 16-bit immediate constant. Operation MOVT writes a 16-bit immediate value, imm16, to the top halfword, Rd[31:16], of its destination register. The write does not affect Rd[15:0]. The MOV, MOVT instruction pair enables to generate any 32-bit constant. Restrictions Rd must not be SP and must not be PC. Condition Flags This instruction does not change the flags. Examples MOVT R3, #0xF123 ; Write 0xF123 to upper halfword of R3, lower halfword ; and APSR are unchanged. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 113 11.6.5.8 REV, REV16, REVSH, and RBIT Reverse bytes and Reverse bits. Syntax op{cond} Rd, Rn where: op is any of: REV Reverse byte order in a word. REV16 Reverse byte order in each halfword independently. REVSH Reverse byte order in the bottom halfword, and sign extend to 32 bits. RBIT Reverse the bit order in a 32-bit word. cond is an optional condition code, see “Conditional Execution” . Rd is the destination register. Rn is the register holding the operand. Operation Use these instructions to change endianness of data: REV converts either: 32-bit big-endian data into little-endian data 32-bit little-endian data into big-endian data. REV16 converts either: 16-bit big-endian data into little-endian data 16-bit little-endian data into big-endian data. REVSH converts either: 16-bit signed big-endian data into 32-bit signed little-endian data 16-bit signed little-endian data into 32-bit signed big-endian data. Restrictions Do not use SP and do not use PC. Condition Flags These instructions do not change the flags. Examples REV REV16 REVSH REVHS RBIT 114 R3, R0, R0, R3, R7, R7; R0; R5; R7; R8; Reverse Reverse Reverse Reverse Reverse byte order of value in R7 and write it to R3 byte order of each 16-bit halfword in R0 Signed Halfword with Higher or Same condition bit order of value in R8 and write the result to R7. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.6.5.9 SADD16 and SADD8 Signed Add 16 and Signed Add 8 Syntax op{cond}{Rd,} Rn, Rm where: op is any of: SADD16 Performs two 16-bit signed integer additions. SADD8 Performs four 8-bit signed integer additions. cond is an optional condition code, see “Conditional Execution” . Rd is the destination register. Rn is the first register holding the operand. Rm is the second register holding the operand. Operation Use these instructions to perform a halfword or byte add in parallel: The SADD16 instruction: 1. Adds each halfword from the first operand to the corresponding halfword of the second operand. 2. Writes the result in the corresponding halfwords of the destination register. The SADD8 instruction: 1. Adds each byte of the first operand to the corresponding byte of the second operand. Writes the result in the corresponding bytes of the destination register. Restrictions Do not use SP and do not use PC. Condition Flags These instructions do not change the flags. Examples SADD16 R1, R0 SADD8 ; ; ; R4, R0, R5 ; ; Adds the halfwords in R0 to the corresponding halfwords of R1 and writes to corresponding halfword of R1. Adds bytes of R0 to the corresponding byte in R5 and writes to the corresponding byte in R4. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 115 11.6.5.10 SHADD16 and SHADD8 Signed Halving Add 16 and Signed Halving Add 8 Syntax op{cond}{Rd,} Rn, Rm where: op is any of: SHADD16 Signed Halving Add 16. SHADD8 Signed Halving Add 8. cond is an optional condition code, see “Conditional Execution” . Rd is the destination register. Rn is the first operand register. Rm is the second operand register. Operation Use these instructions to add 16-bit and 8-bit data and then to halve the result before writing the result to the destination register: The SHADD16 instruction: 1. Adds each halfword from the first operand to the corresponding halfword of the second operand. 2. Shuffles the result by one bit to the right, halving the data. 3. Writes the halfword results in the destination register. The SHADDB8 instruction: 1. Adds each byte of the first operand to the corresponding byte of the second operand. 2. Shuffles the result by one bit to the right, halving the data. 3. Writes the byte results in the destination register. Restrictions Do not use SP and do not use PC. Condition Flags These instructions do not change the flags. Examples SHADD16 R1, R0 SHADD8 116 ; ; ; R4, R0, R5 ; ; Adds halfwords in R0 to corresponding halfword of R1 and writes halved result to corresponding halfword in R1 Adds bytes of R0 to corresponding byte in R5 and writes halved result to corresponding byte in R4. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.6.5.11 SHASX and SHSAX Signed Halving Add and Subtract with Exchange and Signed Halving Subtract and Add with Exchange. Syntax op{cond} {Rd}, Rn, Rm where: op is any of: SHASX Add and Subtract with Exchange and Halving. SHSAX Subtract and Add with Exchange and Halving. cond is an optional condition code, see “Conditional Execution” . Rd is the destination register. Rn, Rm are registers holding the first and second operands. Operation The SHASX instruction: 1. Adds the top halfword of the first operand with the bottom halfword of the second operand. 2. Writes the halfword result of the addition to the top halfword of the destination register, shifted by one bit to the right causing a divide by two, or halving. 3. Subtracts the top halfword of the second operand from the bottom highword of the first operand. 4. Writes the halfword result of the division in the bottom halfword of the destination register, shifted by one bit to the right causing a divide by two, or halving. The SHSAX instruction: 1. Subtracts the bottom halfword of the second operand from the top highword of the first operand. 2. Writes the halfword result of the addition to the bottom halfword of the destination register, shifted by one bit to the right causing a divide by two, or halving. 3. Adds the bottom halfword of the first operand with the top halfword of the second operand. 4. Writes the halfword result of the division in the top halfword of the destination register, shifted by one bit to the right causing a divide by two, or halving. Restrictions Do not use SP and do not use PC. Condition Flags These instructions do not affect the condition code flags. Examples SHASX R7, R4, R2 SHSAX R0, R3, R5 ; ; ; ; ; ; ; ; Adds top halfword of R4 to bottom halfword of R2 and writes halved result to top halfword of R7 Subtracts top halfword of R2 from bottom halfword of R4 and writes halved result to bottom halfword of R7 Subtracts bottom halfword of R5 from top halfword of R3 and writes halved result to top halfword of R0 Adds top halfword of R5 to bottom halfword of R3 and writes halved result to bottom halfword of R0. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 117 11.6.5.12 SHSUB16 and SHSUB8 Signed Halving Subtract 16 and Signed Halving Subtract 8 Syntax op{cond}{Rd,} Rn, Rm where: op is any of: SHSUB16 Signed Halving Subtract 16. SHSUB8 Signed Halving Subtract 8. cond is an optional condition code, see “Conditional Execution” . Rd is the destination register. Rn is the first operand register. Rm is the second operand register. Operation Use these instructions to add 16-bit and 8-bit data and then to halve the result before writing the result to the destination register: The SHSUB16 instruction: 1. Subtracts each halfword of the second operand from the corresponding halfwords of the first operand. 2. Shuffles the result by one bit to the right, halving the data. 3. Writes the halved halfword results in the destination register. The SHSUBB8 instruction: 1. Subtracts each byte of the second operand from the corresponding byte of the first operand, 2. Shuffles the result by one bit to the right, halving the data, 3. Writes the corresponding signed byte results in the destination register. Restrictions Do not use SP and do not use PC. Condition Flags These instructions do not change the flags. Examples SHSUB16 R1, R0 SHSUB8 118 ; ; R4, R0, R5 ; ; Subtracts halfwords in R0 from corresponding halfword of R1 and writes to corresponding halfword of R1 Subtracts bytes of R0 from corresponding byte in R5, and writes to corresponding byte in R4. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.6.5.13 SSUB16 and SSUB8 Signed Subtract 16 and Signed Subtract 8 Syntax op{cond}{Rd,} Rn, Rm where: op is any of: SSUB16 Performs two 16-bit signed integer subtractions. SSUB8 Performs four 8-bit signed integer subtractions. cond is an optional condition code, see “Conditional Execution” . Rd is the destination register. Rn is the first operand register. Rm is the second operand register. Operation Use these instructions to change endianness of data: The SSUB16 instruction: 1. Subtracts each halfword from the second operand from the corresponding halfword of the first operand 2. Writes the difference result of two signed halfwords in the corresponding halfword of the destination register. The SSUB8 instruction: 1. Subtracts each byte of the second operand from the corresponding byte of the first operand 2. Writes the difference result of four signed bytes in the corresponding byte of the destination register. Restrictions Do not use SP and do not use PC. Condition Flags These instructions do not change the flags. Examples SSUB16 R1, R0 SSUB8 ; ; R4, R0, R5 ; ; Subtracts halfwords in R0 from corresponding halfword of R1 and writes to corresponding halfword of R1 Subtracts bytes of R5 from corresponding byte in R0, and writes to corresponding byte of R4. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 119 11.6.5.14 SASX and SSAX Signed Add and Subtract with Exchange and Signed Subtract and Add with Exchange. Syntax op{cond} {Rd}, Rm, Rn where: op is any of: SASX Signed Add and Subtract with Exchange. SSAX Signed Subtract and Add with Exchange. cond is an optional condition code, see “Conditional Execution” . Rd is the destination register. Rn, Rm are registers holding the first and second operands. Operation The SASX instruction: 1. Adds the signed top halfword of the first operand with the signed bottom halfword of the second operand. 2. Writes the signed result of the addition to the top halfword of the destination register. 3. Subtracts the signed bottom halfword of the second operand from the top signed highword of the first operand. 4. Writes the signed result of the subtraction to the bottom halfword of the destination register. The SSAX instruction: 1. Subtracts the signed bottom halfword of the second operand from the top signed highword of the first operand. 2. Writes the signed result of the addition to the bottom halfword of the destination register. 3. Adds the signed top halfword of the first operand with the signed bottom halfword of the second operand. 4. Writes the signed result of the subtraction to the top halfword of the destination register. Restrictions Do not use SP and do not use PC. Condition Flags These instructions do not affect the condition code flags. Examples SASX SSAX 120 R0, R4, R5 ; ; ; ; R7, R3, R2 ; ; ; ; Adds top halfword of R4 to bottom halfword of R5 and writes to top halfword of R0 Subtracts bottom halfword of R5 from top halfword of R4 and writes to bottom halfword of R0 Subtracts top halfword of R2 from bottom halfword of R3 and writes to bottom halfword of R7 Adds top halfword of R3 with bottom halfword of R2 and writes to top halfword of R7. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.6.5.15 TST and TEQ Test bits and Test Equivalence. Syntax TST{cond} Rn, Operand2 TEQ{cond} Rn, Operand2 where cond is an optional condition code, see “Conditional Execution” . Rn is the register holding the first operand. Operand2 is a flexible second operand. See “Flexible Second Operand” for details of the options Operation These instructions test the value in a register against Operand2. They update the condition flags based on the result, but do not write the result to a register. The TST instruction performs a bitwise AND operation on the value in Rn and the value of Operand2. This is the same as the ANDS instruction, except that it discards the result. To test whether a bit of Rn is 0 or 1, use the TST instruction with an Operand2 constant that has that bit set to 1 and all other bits cleared to 0. The TEQ instruction performs a bitwise Exclusive OR operation on the value in Rn and the value of Operand2. This is the same as the EORS instruction, except that it discards the result. Use the TEQ instruction to test if two values are equal without affecting the V or C flags. TEQ is also useful for testing the sign of a value. After the comparison, the N flag is the logical Exclusive OR of the sign bits of the two operands. Restrictions Do not use SP and do not use PC. Condition Flags These instructions: Update the N and Z flags according to the result Can update the C flag during the calculation of Operand2, see “Flexible Second Operand” Do not affect the V flag. Examples TST TEQEQ R0, #0x3F8 ; ; R10, R9 ; ; Perform bitwise AND of R0 value to 0x3F8, APSR is updated but result is discarded Conditionally test if value in R10 is equal to value in R9, APSR is updated but result is discarded. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 121 11.6.5.16 UADD16 and UADD8 Unsigned Add 16 and Unsigned Add 8 Syntax op{cond}{Rd,} Rn, Rm where: op is any of: UADD16 Performs two 16-bit unsigned integer additions. UADD8 Performs four 8-bit unsigned integer additions. cond is an optional condition code, see “Conditional Execution” . Rd is the destination register. Rn is the first register holding the operand. Rm is the second register holding the operand. Operation Use these instructions to add 16- and 8-bit unsigned data: The UADD16 instruction: 1. Adds each halfword from the first operand to the corresponding halfword of the second operand. 2. Writes the unsigned result in the corresponding halfwords of the destination register. The UADD16 instruction: 1. Adds each byte of the first operand to the corresponding byte of the second operand. 2. Writes the unsigned result in the corresponding byte of the destination register. Restrictions Do not use SP and do not use PC. Condition Flags These instructions do not change the flags. Examples UADD16 R1, R0 UADD8 122 R4, R0, R5 ; ; ; ; Adds halfwords in R0 to corresponding halfword of R1, writes to corresponding halfword of R1 Adds bytes of R0 to corresponding byte in R5 and writes to corresponding byte in R4. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.6.5.17 UASX and USAX Add and Subtract with Exchange and Subtract and Add with Exchange. Syntax op{cond} {Rd}, Rn, Rm where: op is one of: UASX Add and Subtract with Exchange. USAX Subtract and Add with Exchange. cond is an optional condition code, see “Conditional Execution” . Rd is the destination register. Rn, Rm are registers holding the first and second operands. Operation The UASX instruction: 1. Subtracts the top halfword of the second operand from the bottom halfword of the first operand. 2. Writes the unsigned result from the subtraction to the bottom halfword of the destination register. 3. Adds the top halfword of the first operand with the bottom halfword of the second operand. 4. Writes the unsigned result of the addition to the top halfword of the destination register. The USAX instruction: 1. Adds the bottom halfword of the first operand with the top halfword of the second operand. 2. Writes the unsigned result of the addition to the bottom halfword of the destination register. 3. Subtracts the bottom halfword of the second operand from the top halfword of the first operand. 4. Writes the unsigned result from the subtraction to the top halfword of the destination register. Restrictions Do not use SP and do not use PC. Condition Flags These instructions do not affect the condition code flags. Examples UASX USAX R0, R4, R5 ; ; ; ; R7, R3, R2 ; ; ; ; Adds top halfword of R4 to bottom halfword of R5 and writes to top halfword of R0 Subtracts bottom halfword of R5 from top halfword of R0 and writes to bottom halfword of R0 Subtracts top halfword of R2 from bottom halfword of R3 and writes to bottom halfword of R7 Adds top halfword of R3 to bottom halfword of R2 and writes to top halfword of R7. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 123 11.6.5.18 UHADD16 and UHADD8 Unsigned Halving Add 16 and Unsigned Halving Add 8 Syntax op{cond}{Rd,} Rn, Rm where: op is any of: UHADD16 Unsigned Halving Add 16. UHADD8 Unsigned Halving Add 8. cond is an optional condition code, see “Conditional Execution” . Rd is the destination register. Rn is the register holding the first operand. Rm is the register holding the second operand. Operation Use these instructions to add 16- and 8-bit data and then to halve the result before writing the result to the destination register: The UHADD16 instruction: 1. Adds each halfword from the first operand to the corresponding halfword of the second operand. 2. Shuffles the halfword result by one bit to the right, halving the data. 3. Writes the unsigned results to the corresponding halfword in the destination register. The UHADD8 instruction: 1. Adds each byte of the first operand to the corresponding byte of the second operand. 2. Shuffles the byte result by one bit to the right, halving the data. 3. Writes the unsigned results in the corresponding byte in the destination register. Restrictions Do not use SP and do not use PC. Condition Flags These instructions do not change the flags. Examples UHADD16 R7, R3 UHADD8 124 R4, R0, R5 ; ; ; ; ; Adds halfwords in R7 to corresponding halfword of R3 and writes halved result to corresponding halfword in R7 Adds bytes of R0 to corresponding byte in R5 and writes halved result to corresponding byte in R4. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.6.5.19 UHASX and UHSAX Unsigned Halving Add and Subtract with Exchange and Unsigned Halving Subtract and Add with Exchange. Syntax op{cond} {Rd}, Rn, Rm where: op is one of: UHASX Add and Subtract with Exchange and Halving. UHSAX Subtract and Add with Exchange and Halving. cond is an optional condition code, see “Conditional Execution” . Rd is the destination register. Rn, Rm are registers holding the first and second operands. Operation The UHASX instruction: 1. Adds the top halfword of the first operand with the bottom halfword of the second operand. 2. Shifts the result by one bit to the right causing a divide by two, or halving. 3. Writes the halfword result of the addition to the top halfword of the destination register. 4. Subtracts the top halfword of the second operand from the bottom highword of the first operand. 5. Shifts the result by one bit to the right causing a divide by two, or halving. 6. Writes the halfword result of the division in the bottom halfword of the destination register. The UHSAX instruction: 1. Subtracts the bottom halfword of the second operand from the top highword of the first operand. 2. Shifts the result by one bit to the right causing a divide by two, or halving. 3. Writes the halfword result of the subtraction in the top halfword of the destination register. 4. Adds the bottom halfword of the first operand with the top halfword of the second operand. 5. Shifts the result by one bit to the right causing a divide by two, or halving. 6. Writes the halfword result of the addition to the bottom halfword of the destination register. Restrictions Do not use SP and do not use PC. Condition Flags These instructions do not affect the condition code flags. Examples UHASX UHSAX R7, R4, R2 ; ; ; ; R0, R3, R5 ; ; ; ; Adds top halfword of R4 with bottom halfword of R2 and writes halved result to top halfword of R7 Subtracts top halfword of R2 from bottom halfword of R7 and writes halved result to bottom halfword of R7 Subtracts bottom halfword of R5 from top halfword of R3 and writes halved result to top halfword of R0 Adds top halfword of R5 to bottom halfword of R3 and writes halved result to bottom halfword of R0. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 125 11.6.5.20 UHSUB16 and UHSUB8 Unsigned Halving Subtract 16 and Unsigned Halving Subtract 8 Syntax op{cond}{Rd,} Rn, Rm where: op is any of: UHSUB16 Performs two unsigned 16-bit integer additions, halves the results, and writes the results to the destination register. UHSUB8 Performs four unsigned 8-bit integer additions, halves the results, and writes the results to the destination register. cond is an optional condition code, see “Conditional Execution” . Rd is the destination register. Rn is the first register holding the operand. Rm is the second register holding the operand. Operation Use these instructions to add 16-bit and 8-bit data and then to halve the result before writing the result to the destination register: The UHSUB16 instruction: 1. Subtracts each halfword of the second operand from the corresponding halfword of the first operand. 2. Shuffles each halfword result to the right by one bit, halving the data. 3. Writes each unsigned halfword result to the corresponding halfwords in the destination register. The UHSUB8 instruction: 1. Subtracts each byte of second operand from the corresponding byte of the first operand. 2. Shuffles each byte result by one bit to the right, halving the data. 3. Writes the unsigned byte results to the corresponding byte of the destination register. Restrictions Do not use SP and do not use PC. Condition Flags These instructions do not change the flags. Examples UHSUB16 R1, R0 UHSUB8 126 R4, R0, R5 ; ; ; ; Subtracts halfwords in R0 from corresponding halfword of R1 and writes halved result to corresponding halfword in R1 Subtracts bytes of R5 from corresponding byte in R0 and writes halved result to corresponding byte in R4. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.6.5.21 SEL Select Bytes. Selects each byte of its result from either its first operand or its second operand, according to the values of the GE flags. Syntax SEL{<c>}{<q>} {<Rd>,} <Rn>, <Rm> where: c, q are standard assembler syntax fields. Rd is the destination register. Rn is the first register holding the operand. Rm is the second register holding the operand. Operation The SEL instruction: 1. Reads the value of each bit of APSR.GE. 2. Depending on the value of APSR.GE, assigns the destination register the value of either the first or second operand register. Restrictions None. Condition Flags These instructions do not change the flags. Examples SADD16 R0, R1, R2 SEL R0, R0, R3 ; Set GE bits based on result ; Select bytes from R0 or R3, based on GE. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 127 11.6.5.22 USAD8 Unsigned Sum of Absolute Differences Syntax USAD8{cond}{Rd,} Rn, Rm where: cond is an optional condition code, see “Conditional Execution” . Rd is the destination register. Rn is the first operand register. Rm is the second operand register. Operation The USAD8 instruction: 1. Subtracts each byte of the second operand register from the corresponding byte of the first operand register. 2. Adds the absolute values of the differences together. 3. Writes the result to the destination register. Restrictions Do not use SP and do not use PC. Condition Flags These instructions do not change the flags. Examples USAD8 R1, R4, R0 ; ; USAD8 R0, R5 ; ; 128 Subtracts each byte in R0 from corresponding byte of R4 adds the differences and writes to R1 Subtracts bytes of R5 from corresponding byte in R0, adds the differences and writes to R0. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.6.5.23 USADA8 Unsigned Sum of Absolute Differences and Accumulate Syntax USADA8{cond}{Rd,} Rn, Rm, Ra where: cond is an optional condition code, see “Conditional Execution” . Rd is the destination register. Rn is the first operand register. Rm is the second operand register. Ra is the register that contains the accumulation value. Operation The USADA8 instruction: 1. Subtracts each byte of the second operand register from the corresponding byte of the first operand register. 2. Adds the unsigned absolute differences together. 3. Adds the accumulation value to the sum of the absolute differences. 4. Writes the result to the destination register. Restrictions Do not use SP and do not use PC. Condition Flags These instructions do not change the flags. Examples USADA8 R1, R0, R6 USADA8 R4, R0, R5, R2 ; ; ; ; Subtracts bytes in R0 from corresponding halfword of R1 adds differences, adds value of R6, writes to R1 Subtracts bytes of R5 from corresponding byte in R0 adds differences, adds value of R2 writes to R4. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 129 11.6.5.24 USUB16 and USUB8 Unsigned Subtract 16 and Unsigned Subtract 8 Syntax op{cond}{Rd,} Rn, Rm where op is any of: USUB16 Unsigned Subtract 16. USUB8 Unsigned Subtract 8. cond is an optional condition code, see “Conditional Execution” . Rd is the destination register. Rn is the first operand register. Rm is the second operand register. Operation Use these instructions to subtract 16-bit and 8-bit data before writing the result to the destination register: The USUB16 instruction: 1. Subtracts each halfword from the second operand register from the corresponding halfword of the first operand register. 2. Writes the unsigned result in the corresponding halfwords of the destination register. The USUB8 instruction: 1. Subtracts each byte of the second operand register from the corresponding byte of the first operand register. 2. Writes the unsigned byte result in the corresponding byte of the destination register. Restrictions Do not use SP and do not use PC. Condition Flags These instructions do not change the flags. Examples USUB16 R1, R0 130 ; ; ; ; Subtracts halfwords in R0 from corresponding halfword of R1 and writes to corresponding halfword in R1USUB8 R4, R0, R5 Subtracts bytes of R5 from corresponding byte in R0 and writes to the corresponding byte in R4. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.6.6 Multiply and Divide Instructions The table below shows the multiply and divide instructions: Table 11-21. Multiply and Divide Instructions Mnemonic Description MLA Multiply with Accumulate, 32-bit result MLS Multiply and Subtract, 32-bit result MUL Multiply, 32-bit result SDIV Signed Divide SMLA[B,T] Signed Multiply Accumulate (halfwords) SMLAD, SMLADX Signed Multiply Accumulate Dual SMLAL Signed Multiply with Accumulate (32x32+64), 64-bit result SMLAL[B,T] Signed Multiply Accumulate Long (halfwords) SMLALD, SMLALDX Signed Multiply Accumulate Long Dual SMLAW[B|T] Signed Multiply Accumulate (word by halfword) SMLSD Signed Multiply Subtract Dual SMLSLD Signed Multiply Subtract Long Dual SMMLA Signed Most Significant Word Multiply Accumulate SMMLS, SMMLSR Signed Most Significant Word Multiply Subtract SMUAD, SMUADX Signed Dual Multiply Add SMUL[B,T] Signed Multiply (word by halfword) SMMUL, SMMULR Signed Most Significant Word Multiply SMULL Signed Multiply (32x32), 64-bit result SMULWB, SMULWT Signed Multiply (word by halfword) SMUSD, SMUSDX Signed Dual Multiply Subtract UDIV Unsigned Divide UMAAL Unsigned Multiply Accumulate Accumulate Long (32x32+32+32), 64-bit result UMLAL Unsigned Multiply with Accumulate (32x32+64), 64-bit result UMULL Unsigned Multiply (32x32), 64-bit result SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 131 11.6.6.1 MUL, MLA, and MLS Multiply, Multiply with Accumulate, and Multiply with Subtract, using 32-bit operands, and producing a 32-bit result. Syntax MUL{S}{cond} {Rd,} Rn, Rm ; Multiply MLA{cond} Rd, Rn, Rm, Ra ; Multiply with accumulate MLS{cond} Rd, Rn, Rm, Ra ; Multiply with subtract where: cond is an optional condition code, see “Conditional Execution” . S is an optional suffix. If S is specified, the condition code flags are updated on the result operation, see “Conditional Execution” . Rd is the destination register. If Rd is omitted, the destination register is Rn. Rn, Rm are registers holding the values to be multiplied. Ra is a register holding the value to be added or subtracted from. of the Operation The MUL instruction multiplies the values from Rn and Rm, and places the least significant 32 bits of the result in Rd. The MLA instruction multiplies the values from Rn and Rm, adds the value from Ra, and places the least significant 32 bits of the result in Rd. The MLS instruction multiplies the values from Rn and Rm, subtracts the product from the value from Ra, and places the least significant 32 bits of the result in Rd. The results of these instructions do not depend on whether the operands are signed or unsigned. Restrictions In these instructions, do not use SP and do not use PC. If the S suffix is used with the MUL instruction: Rd, Rn, and Rm must all be in the range R0 to R7 Rd must be the same as Rm The cond suffix must not be used. Condition Flags If S is specified, the MUL instruction: Updates the N and Z flags according to the result Does not affect the C and V flags. Examples MUL MLA MULS MULLT MLS 132 R10, R2, R5 R10, R2, R1, R5 R0, R2, R2 R2, R3, R2 R4, R5, R6, R7 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 ; ; ; ; ; Multiply, R10 Multiply with Multiply with Conditionally Multiply with = R2 x R5 accumulate, R10 = flag update, R0 = multiply, R2 = R3 subtract, R4 = R7 (R2 x R1) + R5 R2 x R2 x R2 - (R5 x R6) 11.6.6.2 UMULL, UMAAL, UMLAL Unsigned Long Multiply, with optional Accumulate, using 32-bit operands and producing a 64-bit result. Syntax op{cond} RdLo, RdHi, Rn, Rm where: op is one of: UMULL Unsigned Long Multiply. UMAAL Unsigned Long Multiply with Accumulate Accumulate. UMLAL Unsigned Long Multiply, with Accumulate. cond is an optional condition code, see “Conditional Execution” . RdHi, RdLo are the destination registers. For UMAAL, UMLAL and UMLAL they also hold the accumulating value. Rn, Rm are registers holding the first and second operands. Operation These instructions interpret the values from Rn and Rm as unsigned 32-bit integers. The UMULL instruction: Multiplies the two unsigned integers in the first and second operands. Writes the least significant 32 bits of the result in RdLo. Writes the most significant 32 bits of the result in RdHi. The UMAAL instruction: Multiplies the two unsigned 32-bit integers in the first and second operands. Adds the unsigned 32-bit integer in RdHi to the 64-bit result of the multiplication. Adds the unsigned 32-bit integer in RdLo to the 64-bit result of the addition. Writes the top 32-bits of the result to RdHi. Writes the lower 32-bits of the result to RdLo. The UMLAL instruction: Multiplies the two unsigned integers in the first and second operands. Adds the 64-bit result to the 64-bit unsigned integer contained in RdHi and RdLo. Writes the result back to RdHi and RdLo. Restrictions In these instructions: Do not use SP and do not use PC. RdHi and RdLo must be different registers. Condition Flags These instructions do not affect the condition code flags. Examples UMULL R0, R4, R5, R6 UMAAL R3, R6, R2, R7 UMLAL R2, R1, R3, R5 ; ; ; ; ; Multiplies R5 and R6, writes the top 32 bits to R4 and the bottom 32 bits to R0 Multiplies R2 and R7, adds R6, adds R3, writes the top 32 bits to R6, and the bottom 32 bits to R3 Multiplies R5 and R3, adds R1:R2, writes to R1:R2. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 133 11.6.6.3 SMLA and SMLAW Signed Multiply Accumulate (halfwords). Syntax op{XY}{cond} Rd, Rn, Rm op{Y}{cond} Rd, Rn, Rm, Ra where: op is one of: SMLA Signed Multiply Accumulate Long (halfwords). X and Y specifies which half of the source registers Rn and Rm are used as the first and second multiply operand. If X is B, then the bottom halfword, bits [15:0], of Rn is used. If X is T, then the top halfword, bits [31:16], of Rn is used. If Y is B, then the bottom halfword, bits [15:0], of Rm is used. If Y is T, then the top halfword, bits [31:16], of Rm is used SMLAW Signed Multiply Accumulate (word by halfword). Y specifies which half of the source register Rm is used as the second multiply operand. If Y is T, then the top halfword, bits [31:16] of Rm is used. If Y is B, then the bottom halfword, bits [15:0] of Rm is used. cond is an optional condition code, see “Conditional Execution” . Rd is the destination register. If Rd is omitted, the destination register is Rn. Rn, Rm are registers holding the values to be multiplied. Ra is a register holding the value to be added or subtracted from. Operation The SMALBB, SMLABT, SMLATB, SMLATT instructions: Multiplies the specified signed halfword, top or bottom, values from Rn and Rm. Adds the value in Ra to the resulting 32-bit product. Writes the result of the multiplication and addition in Rd. The non-specified halfwords of the source registers are ignored. The SMLAWB and SMLAWT instructions: Multiply the 32-bit signed values in Rn with: ̶ ̶ The top signed halfword of Rm, T instruction suffix. The bottom signed halfword of Rm, B instruction suffix. Add the 32-bit signed value in Ra to the top 32 bits of the 48-bit product Writes the result of the multiplication and addition in Rd. The bottom 16 bits of the 48-bit product are ignored. If overflow occurs during the addition of the accumulate value, the instruction sets the Q flag in the APSR. No overflow can occur during the multiplication. Restrictions In these instructions, do not use SP and do not use PC. Condition Flags If an overflow is detected, the Q flag is set. 134 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Examples SMLABB SMLATB SMLATT SMLABT SMLABT SMLAWB SMLAWT R5, R6, R4, R1 ; ; R5, R6, R4, R1 ; ; R5, R6, R4, R1 ; ; R5, R6, R4, R1 ; ; R4, R3, R2 ; ; R10, R2, R5, R3 ; ; R10, R2, R1, R5 ; ; Multiplies bottom halfwords of R6 and R4, adds R1 and writes to R5 Multiplies top halfword of R6 with bottom halfword of R4, adds R1 and writes to R5 Multiplies top halfwords of R6 and R4, adds R1 and writes the sum to R5 Multiplies bottom halfword of R6 with top halfword of R4, adds R1 and writes to R5 Multiplies bottom halfword of R4 with top halfword of R3, adds R2 and writes to R4 Multiplies R2 with bottom halfword of R5, adds R3 to the result and writes top 32-bits to R10 Multiplies R2 with top halfword of R1, adds R5 and writes top 32-bits to R10. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 135 11.6.6.4 SMLAD Signed Multiply Accumulate Long Dual Syntax op{X}{cond} Rd, Rn, Rm, Ra ; where: op is one of: SMLAD Signed Multiply Accumulate Dual. SMLADX Signed Multiply Accumulate Dual Reverse. X specifies which halfword of the source register Rn is used as the multiply operand. If X is omitted, the multiplications are bottom × bottom and top × top. If X is present, the multiplications are bottom × top and top × bottom. cond is an optional condition code, see “Conditional Execution” . Rd is the destination register. Rn is the first operand register holding the values to be multiplied. Rm the second operand register. Ra is the accumulate value. Operation The SMLAD and SMLADX instructions regard the two operands as four halfword 16-bit values. The SMLAD and SMLADX instructions: If X is not present, multiply the top signed halfword value in Rn with the top signed halfword of Rm and the bottom signed halfword values in Rn with the bottom signed halfword of Rm. Or if X is present, multiply the top signed halfword value in Rn with the bottom signed halfword of Rm and the bottom signed halfword values in Rn with the top signed halfword of Rm. Add both multiplication results to the signed 32-bit value in Ra. Writes the 32-bit signed result of the multiplication and addition to Rd. Restrictions Do not use SP and do not use PC. Condition Flags These instructions do not change the flags. Examples SMLAD R10, R2, R1, R5 ; ; ; SMLALDX R0, R2, R4, R6 ; ; ; ; 136 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Multiplies two halfword values in R2 with corresponding halfwords in R1, adds R5 and writes to R10 Multiplies top halfword of R2 with bottom halfword of R4, multiplies bottom halfword of R2 with top halfword of R4, adds R6 and writes to R0. 11.6.6.5 SMLAL and SMLALD Signed Multiply Accumulate Long, Signed Multiply Accumulate Long (halfwords) and Signed Multiply Accumulate Long Dual. Syntax op{cond} RdLo, RdHi, Rn, Rm op{XY}{cond} RdLo, RdHi, Rn, Rm op{X}{cond} RdLo, RdHi, Rn, Rm where: op is one of: MLAL Signed Multiply Accumulate Long. SMLAL Signed Multiply Accumulate Long (halfwords, X and Y). X and Y specify which halfword of the source registers Rn and Rm are used as the first and second multiply operand: If X is B, then the bottom halfword, bits [15:0], of Rn is used. If X is T, then the top halfword, bits [31:16], of Rn is used. If Y is B, then the bottom halfword, bits [15:0], of Rm is used. If Y is T, then the top halfword, bits [31:16], of Rm is used. SMLALD Signed Multiply Accumulate Long Dual. SMLALDX Signed Multiply Accumulate Long Dual Reversed. If the X is omitted, the multiplications are bottom × bottom and top × top. If X is present, the multiplications are bottom × top and top × bottom. cond is an optional condition code, see “Conditional Execution” . RdHi, RdLo are the destination registers. RdLo is the lower 32 bits and RdHi is the upper 32 bits of the 64-bit integer. For SMLAL, SMLALBB, SMLALBT, SMLALTB, SMLALTT, SMLALD and SMLA LDX, they also hold the accumulating value. Rn, Rm are registers holding the first and second operands. Operation The SMLAL instruction: Multiplies the two’s complement signed word values from Rn and Rm. Adds the 64-bit value in RdLo and RdHi to the resulting 64-bit product. Writes the 64-bit result of the multiplication and addition in RdLo and RdHi. The SMLALBB, SMLALBT, SMLALTB and SMLALTT instructions: Multiplies the specified signed halfword, Top or Bottom, values from Rn and Rm. Adds the resulting sign-extended 32-bit product to the 64-bit value in RdLo and RdHi. Writes the 64-bit result of the multiplication and addition in RdLo and RdHi. The non-specified halfwords of the source registers are ignored. The SMLALD and SMLALDX instructions interpret the values from Rn and Rm as four halfword two’s complement signed 16-bit integers. These instructions: If X is not present, multiply the top signed halfword value of Rn with the top signed halfword of Rm and the bottom signed halfword values of Rn with the bottom signed halfword of Rm. Or if X is present, multiply the top signed halfword value of Rn with the bottom signed halfword of Rm and the bottom signed halfword values of Rn with the top signed halfword of Rm. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 137 Add the two multiplication results to the signed 64-bit value in RdLo and RdHi to create the resulting 64-bit product. Write the 64-bit product in RdLo and RdHi. Restrictions In these instructions: Do not use SP and do not use PC. RdHi and RdLo must be different registers. Condition Flags These instructions do not affect the condition code flags. Examples SMLAL R4, R5, R3, R8 SMLALBT R2, R1, R6, R7 SMLALTB R2, R1, R6, R7 SMLALD R6, R8, R5, R1 SMLALDX R6, R8, R5, R1 138 ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; Multiplies R3 and R8, adds R5:R4 and writes to R5:R4 Multiplies bottom halfword of R6 with top halfword of R7, sign extends to 32-bit, adds R1:R2 and writes to R1:R2 Multiplies top halfword of R6 with bottom halfword of R7,sign extends to 32-bit, adds R1:R2 and writes to R1:R2 Multiplies top halfwords in R5 and R1 and bottom halfwords of R5 and R1, adds R8:R6 and writes to R8:R6 Multiplies top halfword in R5 with bottom halfword of R1, and bottom halfword of R5 with top halfword of R1, adds R8:R6 and writes to R8:R6. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.6.6.6 SMLSD and SMLSLD Signed Multiply Subtract Dual and Signed Multiply Subtract Long Dual Syntax op{X}{cond} Rd, Rn, Rm, Ra where: op is one of: SMLSD Signed Multiply Subtract Dual. SMLSDX Signed Multiply Subtract Dual Reversed. SMLSLD Signed Multiply Subtract Long Dual. SMLSLDX Signed Multiply Subtract Long Dual Reversed. SMLAW Signed Multiply Accumulate (word by halfword). If X is present, the multiplications are bottom × top and top × bottom. If the X is omitted, the multiplications are bottom × bottom and top × top. cond is an optional condition code, see “Conditional Execution” . Rd is the destination register. Rn, Rm are registers holding the first and second operands. Ra is the register holding the accumulate value. Operation The SMLSD instruction interprets the values from the first and second operands as four signed halfwords. This instruction: Optionally rotates the halfwords of the second operand. Performs two signed 16 × 16-bit halfword multiplications. Subtracts the result of the upper halfword multiplication from the result of the lower halfword multiplication. Adds the signed accumulate value to the result of the subtraction. Writes the result of the addition to the destination register. The SMLSLD instruction interprets the values from Rn and Rm as four signed halfwords. This instruction: Optionally rotates the halfwords of the second operand. Performs two signed 16 × 16-bit halfword multiplications. Subtracts the result of the upper halfword multiplication from the result of the lower halfword multiplication. Adds the 64-bit value in RdHi and RdLo to the result of the subtraction. Writes the 64-bit result of the addition to the RdHi and RdLo. Restrictions In these instructions: Do not use SP and do not use PC. Condition Flags This instruction sets the Q flag if the accumulate operation overflows. Overflow cannot occur during the multiplications or subtraction. For the Thumb instruction set, these instructions do not affect the condition code flags. Examples SMLSD R0, R4, R5, R6 ; Multiplies bottom halfword of R4 with bottom ; halfword of R5, multiplies top halfword of R4 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 139 ; ; SMLSDX R1, R3, R2, R0 ; ; ; ; SMLSLD R3, R6, R2, R7 ; ; ; ; SMLSLDX R3, R6, R2, R7 ; ; ; ; 140 with top halfword of R5, subtracts second from first, adds R6, writes to R0 Multiplies bottom halfword of R3 with top halfword of R2, multiplies top halfword of R3 with bottom halfword of R2, subtracts second from first, adds R0, writes to R1 Multiplies bottom halfword of R6 with bottom halfword of R2, multiplies top halfword of R6 with top halfword of R2, subtracts second from first, adds R6:R3, writes to R6:R3 Multiplies bottom halfword of R6 with top halfword of R2, multiplies top halfword of R6 with bottom halfword of R2, subtracts second from first, adds R6:R3, writes to R6:R3. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.6.6.7 SMMLA and SMMLS Signed Most Significant Word Multiply Accumulate and Signed Most Significant Word Multiply Subtract Syntax op{R}{cond} Rd, Rn, Rm, Ra where: op is one of: SMMLA Signed Most Significant Word Multiply Accumulate. SMMLS Signed Most Significant Word Multiply Subtract. If the X is omitted, the multiplications are bottom × bottom and top × top. R is a rounding error flag. If R is specified, the result is rounded instead of being truncated. In this case the constant 0x80000000 is added to the product before the high word is extracted. cond is an optional condition code, see “Conditional Execution” . Rd is the destination register. Rn, Rm are registers holding the first and second multiply operands. Ra is the register holding the accumulate value. Operation The SMMLA instruction interprets the values from Rn and Rm as signed 32-bit words. The SMMLA instruction: Multiplies the values in Rn and Rm. Optionally rounds the result by adding 0x80000000. Extracts the most significant 32 bits of the result. Adds the value of Ra to the signed extracted value. Writes the result of the addition in Rd. The SMMLS instruction interprets the values from Rn and Rm as signed 32-bit words. The SMMLS instruction: Multiplies the values in Rn and Rm. Optionally rounds the result by adding 0x80000000. Extracts the most significant 32 bits of the result. Subtracts the extracted value of the result from the value in Ra. Writes the result of the subtraction in Rd. Restrictions In these instructions: Do not use SP and do not use PC. Condition Flags These instructions do not affect the condition code flags. Examples SMMLA R0, R4, R5, R6 SMMLAR R6, R2, R1, R4 ; ; ; ; Multiplies R4 and R5, extracts top 32 bits, adds R6, truncates and writes to R0 Multiplies R2 and R1, extracts top 32 bits, adds R4, rounds and writes to R6 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 141 SMMLSR R3, R6, R2, R7 SMMLS 142 R4, R5, R3, R8 ; ; ; ; Multiplies R6 subtracts R7, Multiplies R5 subtracts R8, SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 and R2, extracts top rounds and writes to and R3, extracts top truncates and writes 32 bits, R3 32 bits, to R4. 11.6.6.8 SMMUL Signed Most Significant Word Multiply Syntax op{R}{cond} Rd, Rn, Rm where: op is one of: SMMUL Signed Most Significant Word Multiply. R is a rounding error flag. If R is specified, the result is rounded instead of being truncated. In this case the constant 0x80000000 is added to the product before the high word is extracted. cond is an optional condition code, see “Conditional Execution” . Rd is the destination register. Rn, Rm are registers holding the first and second operands. Operation The SMMUL instruction interprets the values from Rn and Rm as two’s complement 32-bit signed integers. The SMMUL instruction: Multiplies the values from Rn and Rm. Optionally rounds the result, otherwise truncates the result. Writes the most significant signed 32 bits of the result in Rd. Restrictions In this instruction: do not use SP and do not use PC. Condition Flags This instruction does not affect the condition code flags. Examples SMULL SMULLR R0, R4, R5 R6, R2 ; ; ; ; Multiplies and writes Multiplies and writes R4 to R6 to and R5, truncates top 32 bits R0 and R2, rounds the top 32 bits R6. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 143 11.6.6.9 SMUAD and SMUSD Signed Dual Multiply Add and Signed Dual Multiply Subtract Syntax op{X}{cond} Rd, Rn, Rm where: op is one of: SMUAD Signed Dual Multiply Add. SMUADX Signed Dual Multiply Add Reversed. SMUSD Signed Dual Multiply Subtract. SMUSDX Signed Dual Multiply Subtract Reversed. If X is present, the multiplications are bottom × top and top × bottom. If the X is omitted, the multiplications are bottom × bottom and top × top. cond is an optional condition code, see “Conditional Execution” . Rd is the destination register. Rn, Rm are registers holding the first and second operands. Operation The SMUAD instruction interprets the values from the first and second operands as two signed halfwords in each operand. This instruction: Optionally rotates the halfwords of the second operand. Performs two signed 16 × 16-bit multiplications. Adds the two multiplication results together. Writes the result of the addition to the destination register. The SMUSD instruction interprets the values from the first and second operands as two’s complement signed integers. This instruction: Optionally rotates the halfwords of the second operand. Performs two signed 16 × 16-bit multiplications. Subtracts the result of the top halfword multiplication from the result of the bottom halfword multiplication. Writes the result of the subtraction to the destination register. Restrictions In these instructions: Do not use SP and do not use PC. Condition Flags Sets the Q flag if the addition overflows. The multiplications cannot overflow. Examples SMUAD R0, R4, R5 SMUADX R3, R7, R4 SMUSD R3, R6, R2 SMUSDX R4, R5, R3 144 ; ; ; ; ; ; ; ; ; ; Multiplies bottom halfword of R4 with the bottom halfword of R5, adds multiplication of top halfword of R4 with top halfword of R5, writes to R0 Multiplies bottom halfword of R7 with top halfword of R4, adds multiplication of top halfword of R7 with bottom halfword of R4, writes to R3 Multiplies bottom halfword of R4 with bottom halfword of R6, subtracts multiplication of top halfword of R6 with top halfword of R3, writes to R3 Multiplies bottom halfword of R5 with top halfword of SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 ; R3, subtracts multiplication of top halfword of R5 ; with bottom halfword of R3, writes to R4. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 145 11.6.6.10 SMUL and SMULW Signed Multiply (halfwords) and Signed Multiply (word by halfword) Syntax op{XY}{cond} Rd,Rn, Rm op{Y}{cond} Rd. Rn, Rm For SMULXY only: op is one of: SMUL{XY} Signed Multiply (halfwords). X and Y specify which halfword of the source registers Rn and Rm is used as the first and second multiply operand. If X is B, then the bottom halfword, bits [15:0] of Rn is used. If X is T, then the top halfword, bits [31:16] of Rn is used.If Y is B, then the bot tom halfword, bits [15:0], of Rm is used. If Y is T, then the top halfword, bits [31:16], of Rm is used. SMULW{Y} Signed Multiply (word by halfword). Y specifies which halfword of the source register Rm is used as the second mul tiply operand. If Y is B, then the bottom halfword (bits [15:0]) of Rm is used. If Y is T, then the top halfword (bits [31:16]) of Rm is used. cond is an optional condition code, see “Conditional Execution” . Rd is the destination register. Rn, Rm are registers holding the first and second operands. Operation The SMULBB, SMULTB, SMULBT and SMULTT instructions interprets the values from Rn and Rm as four signed 16-bit integers. These instructions: Multiplies the specified signed halfword, Top or Bottom, values from Rn and Rm. Writes the 32-bit result of the multiplication in Rd. The SMULWT and SMULWB instructions interprets the values from Rn as a 32-bit signed integer and Rm as two halfword 16-bit signed integers. These instructions: Multiplies the first operand and the top, T suffix, or the bottom, B suffix, halfword of the second operand. Writes the signed most significant 32 bits of the 48-bit result in the destination register. Restrictions In these instructions: 146 Do not use SP and do not use PC. RdHi and RdLo must be different registers. Examples SMULBT R0, R4, R5 SMULBB R0, R4, R5 SMULTT R0, R4, R5 SMULTB R0, R4, R5 ; ; ; ; ; ; ; ; ; ; SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Multiplies the bottom halfword of R4 with the top halfword of R5, multiplies results and writes to R0 Multiplies the bottom halfword of R4 with the bottom halfword of R5, multiplies results and writes to R0 Multiplies the top halfword of R4 with the top halfword of R5, multiplies results and writes to R0 Multiplies the top halfword of R4 with the SMULWT R4, R5, R3 SMULWB R4, R5, R3 ; ; ; ; ; ; bottom halfword of R5, multiplies results and and writes to R0 Multiplies R5 with the top halfword of R3, extracts top 32 bits and writes to R4 Multiplies R5 with the bottom halfword of R3, extracts top 32 bits and writes to R4. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 147 11.6.6.11 UMULL, UMLAL, SMULL, and SMLAL Signed and Unsigned Long Multiply, with optional Accumulate, using 32-bit operands and producing a 64-bit result. Syntax op{cond} RdLo, RdHi, Rn, Rm where: op is one of: UMULL Unsigned Long Multiply. UMLAL Unsigned Long Multiply, with Accumulate. SMULL Signed Long Multiply. SMLAL Signed Long Multiply, with Accumulate. cond is an optional condition code, see “Conditional Execution” . RdHi, RdLo are the destination registers. For UMLAL and SMLAL they also hold the accu mulating value. Rn, Rm are registers holding the operands. Operation The UMULL instruction interprets the values from Rn and Rm as unsigned integers. It multiplies these integers and places the least significant 32 bits of the result in RdLo, and the most significant 32 bits of the result in RdHi. The UMLAL instruction interprets the values from Rn and Rm as unsigned integers. It multiplies these integers, adds the 64-bit result to the 64-bit unsigned integer contained in RdHi and RdLo, and writes the result back to RdHi and RdLo. The SMULL instruction interprets the values from Rn and Rm as two’s complement signed integers. It multiplies these integers and places the least significant 32 bits of the result in RdLo, and the most significant 32 bits of the result in RdHi. The SMLAL instruction interprets the values from Rn and Rm as two’s complement signed integers. It multiplies these integers, adds the 64-bit result to the 64-bit signed integer contained in RdHi and RdLo, and writes the result back to RdHi and RdLo. Restrictions In these instructions: Do not use SP and do not use PC RdHi and RdLo must be different registers. Condition Flags These instructions do not affect the condition code flags. Examples UMULL SMLAL 148 R0, R4, R5, R6 R4, R5, R3, R8 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 ; Unsigned (R4,R0) = R5 x R6 ; Signed (R5,R4) = (R5,R4) + R3 x R8 11.6.6.12 SDIV and UDIV Signed Divide and Unsigned Divide. Syntax SDIV{cond} {Rd,} Rn, Rm UDIV{cond} {Rd,} Rn, Rm where: cond is an optional condition code, see “Conditional Execution” . Rd is the destination register. If Rd is omitted, the destination register is Rn. Rn is the register holding the value to be divided. Rm is a register holding the divisor. Operation SDIV performs a signed integer division of the value in Rn by the value in Rm. UDIV performs an unsigned integer division of the value in Rn by the value in Rm. For both instructions, if the value in Rn is not divisible by the value in Rm, the result is rounded towards zero. Restrictions Do not use SP and do not use PC. Condition Flags These instructions do not change the flags. Examples SDIV UDIV R0, R2, R4 R8, R8, R1 ; Signed divide, R0 = R2/R4 ; Unsigned divide, R8 = R8/R1 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 149 11.6.7 Saturating Instructions The table below shows the saturating instructions: Table 11-22. Saturating Instructions Mnemonic Description SSAT Signed Saturate SSAT16 Signed Saturate Halfword USAT Unsigned Saturate USAT16 Unsigned Saturate Halfword QADD Saturating Add QSUB Saturating Subtract QSUB16 Saturating Subtract 16 QASX Saturating Add and Subtract with Exchange QSAX Saturating Subtract and Add with Exchange QDADD Saturating Double and Add QDSUB Saturating Double and Subtract UQADD16 Unsigned Saturating Add 16 UQADD8 Unsigned Saturating Add 8 UQASX Unsigned Saturating Add and Subtract with Exchange UQSAX Unsigned Saturating Subtract and Add with Exchange UQSUB16 Unsigned Saturating Subtract 16 UQSUB8 Unsigned Saturating Subtract 8 For signed n-bit saturation, this means that: If the value to be saturated is less than -2n-1, the result returned is -2n-1 If the value to be saturated is greater than 2n-1-1, the result returned is 2n-1-1 Otherwise, the result returned is the same as the value to be saturated. For unsigned n-bit saturation, this means that: If the value to be saturated is less than 0, the result returned is 0 If the value to be saturated is greater than 2n-1, the result returned is 2n-1 Otherwise, the result returned is the same as the value to be saturated. If the returned result is different from the value to be saturated, it is called saturation. If saturation occurs, the instruction sets the Q flag to 1 in the APSR. Otherwise, it leaves the Q flag unchanged. To clear the Q flag to 0, the MSR instruction must be used; see “MSR” . To read the state of the Q flag, the MRS instruction must be used; see “MRS” . 150 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.6.7.1 SSAT and USAT Signed Saturate and Unsigned Saturate to any bit position, with optional shift before saturating. Syntax op{cond} Rd, #n, Rm {, shift #s} where: op is one of: SSAT Saturates a signed value to a signed range. USAT Saturates a signed value to an unsigned range. cond is an optional condition code, see “Conditional Execution” . Rd is the destination register. n specifies the bit position to saturate to: n ranges from 1 n ranges from 0 to 31 for USAT. to 32 for SSAT Rm is the register containing the value to saturate. shift #s is an optional shift applied to Rm before saturating. It must be one of the following: ASR #s where s is in the range 1 to 31. LSL #s where s is in the range 0 to 31. Operation These instructions saturate to a signed or unsigned n-bit value. The SSAT instruction applies the specified shift, then saturates to the signed range -2n–1 £ x £ 2n–1-1. The USAT instruction applies the specified shift, then saturates to the unsigned range 0 £ x £ 2n-1. Restrictions Do not use SP and do not use PC. Condition Flags These instructions do not affect the condition code flags. If saturation occurs, these instructions set the Q flag to 1. Examples SSAT R7, #16, R7, LSL #4 USATNE R0, #7, R5 ; ; ; ; ; Logical shift left value in R7 by 4, then saturate it as a signed 16-bit value and write it back to R7 Conditionally saturate value in R5 as an unsigned 7 bit value and write it to R0. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 151 11.6.7.2 SSAT16 and USAT16 Signed Saturate and Unsigned Saturate to any bit position for two halfwords. Syntax op{cond} Rd, #n, Rm where: op is one of: SSAT16 Saturates a signed halfword value to a signed range. USAT16 Saturates a signed halfword value to an unsigned range. cond is an optional condition code, see “Conditional Execution” . Rd is the destination register. n specifies the bit position to saturate to: n ranges from 1 n ranges from 0 to 15 for USAT. to 16 for SSAT Rm is the register containing the value to saturate. Operation The SSAT16 instruction: Saturates two signed 16-bit halfword values of the register with the value to saturate from selected by the bit position in n. Writes the results as two signed 16-bit halfwords to the destination register. The USAT16 instruction: Saturates two unsigned 16-bit halfword values of the register with the value to saturate from selected by the bit position in n. Writes the results as two unsigned halfwords in the destination register. Restrictions Do not use SP and do not use PC. Condition Flags These instructions do not affect the condition code flags. If saturation occurs, these instructions set the Q flag to 1. Examples SSAT16 USAT16NE 152 R7, #9, R2 R0, #13, R5 ; ; ; ; ; ; Saturates the top and bottom highwords of R2 as 9-bit values, writes to corresponding halfword of R7 Conditionally saturates the top and bottom halfwords of R5 as 13-bit values, writes to corresponding halfword of R0. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.6.7.3 QADD and QSUB Saturating Add and Saturating Subtract, signed. Syntax op{cond} {Rd}, Rn, Rm op{cond} {Rd}, Rn, Rm where: op is one of: QADD Saturating 32-bit add. QADD8 Saturating four 8-bit integer additions. QADD16 Saturating two 16-bit integer additions. QSUB Saturating 32-bit subtraction. QSUB8 Saturating four 8-bit integer subtraction. QSUB16 Saturating two 16-bit integer subtraction. cond is an optional condition code, see “Conditional Execution” . Rd is the destination register. Rn, Rm are registers holding the first and second operands. Operation These instructions add or subtract two, four or eight values from the first and second operands and then writes a signed saturated value in the destination register. The QADD and QSUB instructions apply the specified add or subtract, and then saturate the result to the signed range -2n–1 £ x £ 2n–1-1, where x is given by the number of bits applied in the instruction, 32, 16 or 8. If the returned result is different from the value to be saturated, it is called saturation. If saturation occurs, the QADD and QSUB instructions set the Q flag to 1 in the APSR. Otherwise, it leaves the Q flag unchanged. The 8-bit and 16-bit QADD and QSUB instructions always leave the Q flag unchanged. To clear the Q flag to 0, the MSR instruction must be used; see “MSR” . To read the state of the Q flag, the MRS instruction must be used; see “MRS” . Restrictions Do not use SP and do not use PC. Condition Flags These instructions do not affect the condition code flags. If saturation occurs, these instructions set the Q flag to 1. Examples QADD16 R7, R4, R2 QADD8 R3, R1, R6 QSUB16 R4, R2, R3 QSUB8 R4, R2, R5 ; ; ; ; ; ; ; ; ; ; ; ; Adds halfwords of R4 with corresponding halfword of R2, saturates to 16 bits and writes to corresponding halfword of R7 Adds bytes of R1 to the corresponding bytes of R6, saturates to 8 bits and writes to corresponding byte of R3 Subtracts halfwords of R3 from corresponding halfword of R2, saturates to 16 bits, writes to corresponding halfword of R4 Subtracts bytes of R5 from the corresponding byte in R2, saturates to 8 bits, writes to corresponding byte of R4. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 153 11.6.7.4 QASX and QSAX Saturating Add and Subtract with Exchange and Saturating Subtract and Add with Exchange, signed. Syntax op{cond} {Rd}, Rm, Rn where: op is one of: QASX Add and Subtract with Exchange and Saturate. QSAX Subtract and Add with Exchange and Saturate. cond is an optional condition code, see “Conditional Execution” . Rd is the destination register. Rn, Rm are registers holding the first and second operands. Operation The QASX instruction: 1. Adds the top halfword of the source operand with the bottom halfword of the second operand. 2. Subtracts the top halfword of the second operand from the bottom highword of the first operand. 3. Saturates the result of the subtraction and writes a 16-bit signed integer in the range –215 ≤ x ≤ 215 – 1, where x equals 16, to the bottom halfword of the destination register. 4. Saturates the results of the sum and writes a 16-bit signed integer in the range –215 ≤ x ≤ 215 – 1, where x equals 16, to the top halfword of the destination register. The QSAX instruction: 1. Subtracts the bottom halfword of the second operand from the top highword of the first operand. 2. Adds the bottom halfword of the source operand with the top halfword of the second operand. 3. Saturates the results of the sum and writes a 16-bit signed integer in the range –215 ≤ x ≤ 215 – 1, where x equals 16, to the bottom halfword of the destination register. 4. Saturates the result of the subtraction and writes a 16-bit signed integer in the range –215 ≤ x ≤ 215 – 1, where x equals 16, to the top halfword of the destination register. Restrictions Do not use SP and do not use PC. Condition Flags These instructions do not affect the condition code flags. Examples QASX QSAX 154 R7, R4, R2 ; ; ; ; ; R0, R3, R5 ; ; ; ; Adds top halfword of R4 to bottom halfword of R2, saturates to 16 bits, writes to top halfword of R7 Subtracts top highword of R2 from bottom halfword of R4, saturates to 16 bits and writes to bottom halfword of R7 Subtracts bottom halfword of R5 from top halfword of R3, saturates to 16 bits, writes to top halfword of R0 Adds bottom halfword of R3 to top halfword of R5, saturates to 16 bits, writes to bottom halfword of R0. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.6.7.5 QDADD and QDSUB Saturating Double and Add and Saturating Double and Subtract, signed. Syntax op{cond} {Rd}, Rm, Rn where: op is one of: QDADD Saturating Double and Add. QDSUB Saturating Double and Subtract. cond is an optional condition code, see “Conditional Execution” . Rd is the destination register. Rm, Rn are registers holding the first and second operands. Operation The QDADD instruction: Doubles the second operand value. Adds the result of the doubling to the signed saturated value in the first operand. Writes the result to the destination register. The QDSUB instruction: Doubles the second operand value. Subtracts the doubled value from the signed saturated value in the first operand. Writes the result to the destination register. Both the doubling and the addition or subtraction have their results saturated to the 32-bit signed integer range – 231 ≤ x ≤ 231– 1. If saturation occurs in either operation, it sets the Q flag in the APSR. Restrictions Do not use SP and do not use PC. Condition Flags If saturation occurs, these instructions set the Q flag to 1. Examples QDADD R7, R4, R2 QDSUB R0, R3, R5 ; ; ; ; Doubles and saturates R4 to 32 bits, adds R2, saturates to 32 bits, writes to R7 Subtracts R3 doubled and saturated to 32 bits from R5, saturates to 32 bits, writes to R0. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 155 11.6.7.6 UQASX and UQSAX Saturating Add and Subtract with Exchange and Saturating Subtract and Add with Exchange, unsigned. Syntax op{cond} {Rd}, Rm, Rn where: type is one of: UQASX Add and Subtract with Exchange and Saturate. UQSAX Subtract and Add with Exchange and Saturate. cond is an optional condition code, see “Conditional Execution” . Rd is the destination register. Rn, Rm are registers holding the first and second operands. Operation The UQASX instruction: 1. Adds the bottom halfword of the source operand with the top halfword of the second operand. 2. Subtracts the bottom halfword of the second operand from the top highword of the first operand. 3. Saturates the results of the sum and writes a 16-bit unsigned integer in the range 0 ≤ x ≤ 216 – 1, where x equals 16, to the top halfword of the destination register. 4. Saturates the result of the subtraction and writes a 16-bit unsigned integer in the range 0 ≤ x ≤ 216 – 1, where x equals 16, to the bottom halfword of the destination register. The UQSAX instruction: 1. Subtracts the bottom halfword of the second operand from the top highword of the first operand. 2. Adds the bottom halfword of the first operand with the top halfword of the second operand. 3. Saturates the result of the subtraction and writes a 16-bit unsigned integer in the range 0 ≤ x ≤ 216 – 1, where x equals 16, to the top halfword of the destination register. 4. Saturates the results of the addition and writes a 16-bit unsigned integer in the range 0 ≤ x ≤ 216 – 1, where x equals 16, to the bottom halfword of the destination register. Restrictions Do not use SP and do not use PC. Condition Flags These instructions do not affect the condition code flags. Examples UQASX R7, R4, R2 UQSAX R0, R3, R5 156 ; ; ; ; ; ; ; ; Adds top halfword of R4 with bottom halfword of R2, saturates to 16 bits, writes to top halfword of R7 Subtracts top halfword of R2 from bottom halfword of R4, saturates to 16 bits, writes to bottom halfword of R7 Subtracts bottom halfword of R5 from top halfword of R3, saturates to 16 bits, writes to top halfword of R0 Adds bottom halfword of R4 to top halfword of R5 saturates to 16 bits, writes to bottom halfword of R0. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.6.7.7 UQADD and UQSUB Saturating Add and Saturating Subtract Unsigned. Syntax op{cond} {Rd}, Rn, Rm op{cond} {Rd}, Rn, Rm where: op is one of: UQADD8 Saturating four unsigned 8-bit integer additions. UQADD16 Saturating two unsigned 16-bit integer additions. UDSUB8 Saturating four unsigned 8-bit integer subtractions. UQSUB16 Saturating two unsigned 16-bit integer subtractions. cond is an optional condition code, see “Conditional Execution” . Rd is the destination register. Rn, Rm are registers holding the first and second operands. Operation These instructions add or subtract two or four values and then writes an unsigned saturated value in the destination register. The UQADD16 instruction: Adds the respective top and bottom halfwords of the first and second operands. Saturates the result of the additions for each halfword in the destination register to the unsigned range 0 £ x £ 216-1, where x is 16. The UQADD8 instruction: Adds each respective byte of the first and second operands. Saturates the result of the addition for each byte in the destination register to the unsigned range 0 £ x £ 281, where x is 8. The UQSUB16 instruction: Subtracts both halfwords of the second operand from the respective halfwords of the first operand. Saturates the result of the differences in the destination register to the unsigned range 0 £ x £ 216-1, where x is 16. The UQSUB8 instructions: Subtracts the respective bytes of the second operand from the respective bytes of the first operand. Saturates the results of the differences for each byte in the destination register to the unsigned range 0 £ x £ 28-1, where x is 8. Restrictions Do not use SP and do not use PC. Condition Flags These instructions do not affect the condition code flags. Examples UQADD16 R7, R4, R2 UQADD8 R4, R2, R5 UQSUB16 R6, R3, R0 ; ; ; ; ; ; Adds halfwords in R4 to corresponding halfword in R2, saturates to 16 bits, writes to corresponding halfword of R7 Adds bytes of R2 to corresponding byte of R5, saturates to 8 bits, writes to corresponding bytes of R4 Subtracts halfwords in R0 from corresponding halfword in R3, saturates to 16 bits, writes to corresponding SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 157 UQSUB8 158 R1, R5, R6 ; halfword in R6 ; Subtracts bytes in R6 from corresponding byte of R5, ; saturates to 8 bits, writes to corresponding byte of R1. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.6.8 Packing and Unpacking Instructions The table below shows the instructions that operate on packing and unpacking data: Table 11-23. Packing and Unpacking Instructions Mnemonic Description PKH Pack Halfword SXTAB Extend 8 bits to 32 and add SXTAB16 Dual extend 8 bits to 16 and add SXTAH Extend 16 bits to 32 and add SXTB Sign extend a byte SXTB16 Dual extend 8 bits to 16 and add SXTH Sign extend a halfword UXTAB Extend 8 bits to 32 and add UXTAB16 Dual extend 8 bits to 16 and add UXTAH Extend 16 bits to 32 and add UXTB Zero extend a byte UXTB16 Dual zero extend 8 bits to 16 and add UXTH Zero extend a halfword SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 159 11.6.8.1 PKHBT and PKHTB Pack Halfword Syntax op{cond} {Rd}, Rn, Rm {, LSL #imm} op{cond} {Rd}, Rn, Rm {, ASR #imm} where: op is one of: PKHBT Pack Halfword, bottom and top with shift. PKHTB Pack Halfword, top and bottom with shift. cond is an optional condition code, see “Conditional Execution” . Rd is the destination register. Rn is the first operand register Rm is the second operand register holding the value to be optionally shifted. imm is the shift length. The type of shift length depends on the instruction: For PKHBT LSL a left shift with a shift length from 1 to 31, 0 means no shift. For PKHTB ASR an arithmetic shift right with a shift length from 1 to 32, a shift of 32-bits is encoded as 0b00000. Operation The PKHBT instruction: 1. Writes the value of the bottom halfword of the first operand to the bottom halfword of the destination register. 2. If shifted, the shifted value of the second operand is written to the top halfword of the destination register. The PKHTB instruction: 1. Writes the value of the top halfword of the first operand to the top halfword of the destination register. 2. If shifted, the shifted value of the second operand is written to the bottom halfword of the destination register. Restrictions Rd must not be SP and must not be PC. Condition Flags This instruction does not change the flags. Examples PKHBT R3, R4, R5 LSL #0 PKHTB R4, R0, R2 ASR #1 160 ; ; ; ; ; ; Writes bottom halfword of R4 to bottom halfword of R3, writes top halfword of R5, unshifted, to top halfword of R3 Writes R2 shifted right by 1 bit to bottom halfword of R4, and writes top halfword of R0 to top halfword of R4. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.6.8.2 SXT and UXT Sign extend and Zero extend. Syntax op{cond} {Rd,} Rm {, ROR #n} op{cond} {Rd}, Rm {, ROR #n} where: op is one of: SXTB Sign extends an 8-bit value to a 32-bit value. SXTH Sign extends a 16-bit value to a 32-bit value. SXTB16 Sign extends two 8-bit values to two 16-bit values. UXTB Zero extends an 8-bit value to a 32-bit value. UXTH Zero extends a 16-bit value to a 32-bit value. UXTB16 Zero extends two 8-bit values to two 16-bit values. cond is an optional condition code, see “Conditional Execution” . Rd is the destination register. Rm is the register holding the value to extend. ROR #n is one of: ROR #8 Value from Rm is rotated right 8 bits. Operation These instructions do the following: 1. Rotate the value from Rm right by 0, 8, 16 or 24 bits. 2. Extract bits from the resulting value: ̶ SXTB extracts bits[7:0] and sign extends to 32 bits. ̶ UXTB extracts bits[7:0] and zero extends to 32 bits. ̶ SXTH extracts bits[15:0] and sign extends to 32 bits. ̶ UXTH extracts bits[15:0] and zero extends to 32 bits. ̶ SXTB16 extracts bits[7:0] and sign extends to 16 bits, and extracts bits [23:16] and sign extends to 16 bits. ̶ UXTB16 extracts bits[7:0] and zero extends to 16 bits, and extracts bits [23:16] and zero extends to 16 bits. Restrictions Do not use SP and do not use PC. Condition Flags These instructions do not affect the flags. Examples SXTH R4, R6, ROR #16 UXTB R3, R10 ; ; ; ; Rotates R6 right by 16 bits, obtains bottom halfword of of result, sign extends to 32 bits and writes to R4 Extracts lowest byte of value in R10, zero extends, and writes to R3. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 161 11.6.8.3 SXTA and UXTA Signed and Unsigned Extend and Add Syntax op{cond} {Rd,} Rn, Rm {, ROR #n} op{cond} {Rd,} Rn, Rm {, ROR #n} where: op is one of: SXTAB Sign extends an 8-bit value to a 32-bit value and add. SXTAH Sign extends a 16-bit value to a 32-bit value and add. SXTAB16 Sign extends two 8-bit values to two 16-bit values and add. UXTAB Zero extends an 8-bit value to a 32-bit value and add. UXTAH Zero extends a 16-bit value to a 32-bit value and add. UXTAB16 Zero extends two 8-bit values to two 16-bit values and add. cond is an optional condition code, see “Conditional Execution” . Rd is the destination register. Rn is the first operand register. Rm is the register holding the value to rotate and extend. ROR #n is one of: ROR #8 Value from Rm is rotated right 8 bits. ROR #16 Value from Rm is rotated right 16 bits. ROR #24 Value from Rm is rotated right 24 bits. If ROR #n is omitted, no rotation is performed. Operation These instructions do the following: 1. Rotate the value from Rm right by 0, 8, 16 or 24 bits. 2. Extract bits from the resulting value: ̶ SXTAB extracts bits[7:0] from Rm and sign extends to 32 bits. ̶ ̶ ̶ ̶ ̶ 3. UXTAB extracts bits[7:0] from Rm and zero extends to 32 bits. SXTAH extracts bits[15:0] from Rm and sign extends to 32 bits. UXTAH extracts bits[15:0] from Rm and zero extends to 32 bits. SXTAB16 extracts bits[7:0] from Rm and sign extends to 16 bits, and extracts bits [23:16] from Rm and sign extends to 16 bits. UXTAB16 extracts bits[7:0] from Rm and zero extends to 16 bits, and extracts bits [23:16] from Rm and zero extends to 16 bits. Adds the signed or zero extended value to the word or corresponding halfword of Rn and writes the result in Rd. Restrictions Do not use SP and do not use PC. Condition Flags These instructions do not affect the flags. Examples 162 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 SXTAH UXTAB R4, R8, R6, ROR #16 ; ; ; R3, R4, R10 ; ; Rotates R6 right by 16 bits, obtains bottom halfword, sign extends to 32 bits, adds R8,and writes to R4 Extracts bottom byte of R10 and zero extends to 32 bits, adds R4, and writes to R3. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 163 11.6.9 Bitfield Instructions The table below shows the instructions that operate on adjacent sets of bits in registers or bitfields: Table 11-24. 164 Packing and Unpacking Instructions Mnemonic Description BFC Bit Field Clear BFI Bit Field Insert SBFX Signed Bit Field Extract SXTB Sign extend a byte SXTH Sign extend a halfword UBFX Unsigned Bit Field Extract UXTB Zero extend a byte UXTH Zero extend a halfword SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.6.9.1 BFC and BFI Bit Field Clear and Bit Field Insert. Syntax BFC{cond} Rd, #lsb, #width BFI{cond} Rd, Rn, #lsb, #width where: cond is an optional condition code, see “Conditional Execution” . Rd is the destination register. Rn is the source register. lsb is the position of the least significant bit of the bitfield. lsb must be in the range 0 to 31. width is the width of the bitfield and must be in the range 1 to 32-lsb. Operation BFC clears a bitfield in a register. It clears width bits in Rd, starting at the low bit position lsb. Other bits in Rd are unchanged. BFI copies a bitfield into one register from another register. It replaces width bits in Rd starting at the low bit position lsb, with width bits from Rn starting at bit[0]. Other bits in Rd are unchanged. Restrictions Do not use SP and do not use PC. Condition Flags These instructions do not affect the flags. Examples BFC BFI R4, #8, #12 R9, R2, #8, #12 ; Clear bit 8 to bit 19 (12 bits) of R4 to 0 ; Replace bit 8 to bit 19 (12 bits) of R9 with ; bit 0 to bit 11 from R2. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 165 11.6.9.2 SBFX and UBFX Signed Bit Field Extract and Unsigned Bit Field Extract. Syntax SBFX{cond} Rd, Rn, #lsb, #width UBFX{cond} Rd, Rn, #lsb, #width where: cond is an optional condition code, see “Conditional Execution” . Rd is the destination register. Rn is the source register. lsb is the position of the least significant bit of the bitfield. lsb must be in the range 0 to 31. width is the width of the bitfield and must be in the range 1 to 32-lsb. Operation SBFX extracts a bitfield from one register, sign extends it to 32 bits, and writes the result to the destination register. UBFX extracts a bitfield from one register, zero extends it to 32 bits, and writes the result to the destination register. Restrictions Do not use SP and do not use PC. Condition Flags These instructions do not affect the flags. Examples SBFX UBFX 166 R0, R1, #20, #4 ; ; R8, R11, #9, #10 ; ; Extract bit 20 to bit 23 (4 bits) from R1 and sign extend to 32 bits and then write the result to R0. Extract bit 9 to bit 18 (10 bits) from R11 and zero extend to 32 bits and then write the result to R8. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.6.9.3 SXT and UXT Sign extend and Zero extend. Syntax SXTextend{cond} {Rd,} Rm {, ROR #n} UXTextend{cond} {Rd}, Rm {, ROR #n} where: extend is one of: B Extends an 8-bit value to a 32-bit value. H Extends a 16-bit value to a 32-bit value. cond is an optional condition code, see “Conditional Execution” . Rd is the destination register. Rm is the register holding the value to extend. ROR #n is one of: ROR #8 Value from Rm is rotated right 8 bits. ROR #16 Value from Rm is rotated right 16 bits. ROR #24 Value from Rm is rotated right 24 bits. If ROR #n is omitted, no rotation is performed. Operation These instructions do the following: 1. Rotate the value from Rm right by 0, 8, 16 or 24 bits. 2. Extract bits from the resulting value: ̶ SXTB extracts bits[7:0] and sign extends to 32 bits. ̶ UXTB extracts bits[7:0] and zero extends to 32 bits. ̶ SXTH extracts bits[15:0] and sign extends to 32 bits. ̶ UXTH extracts bits[15:0] and zero extends to 32 bits. Restrictions Do not use SP and do not use PC. Condition Flags These instructions do not affect the flags. Examples SXTH R4, R6, ROR #16 UXTB R3, R10 ; ; ; ; ; Rotate R6 right by 16 bits, then obtain the lower halfword of the result and then sign extend to 32 bits and write the result to R4. Extract lowest byte of the value in R10 and zero extend it, and write the result to R3. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 167 11.6.10 Branch and Control Instructions The table below shows the branch and control instructions: Table 11-25. 168 Branch and Control Instructions Mnemonic Description B Branch BL Branch with Link BLX Branch indirect with Link BX Branch indirect CBNZ Compare and Branch if Non Zero CBZ Compare and Branch if Zero IT If-Then TBB Table Branch Byte TBH Table Branch Halfword SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.6.10.1 B, BL, BX, and BLX Branch instructions. Syntax B{cond} label BL{cond} label BX{cond} Rm BLX{cond} Rm where: B is branch (immediate). BL is branch with link (immediate). BX is branch indirect (register). BLX is branch indirect with link (register). cond is an optional condition code, see “Conditional Execution” . label is a PC-relative expression. See “PC-relative Expressions” . Rm is a register that indicates an address to branch to. Bit[0] of the value in Rm must be 1, but the address to branch to is created by changing bit[0] to 0. Operation All these instructions cause a branch to label, or to the address indicated in Rm. In addition: The BL and BLX instructions write the address of the next instruction to LR (the link register, R14). The BX and BLX instructions result in a UsageFault exception if bit[0] of Rm is 0. Bcond label is the only conditional instruction that can be either inside or outside an IT block. All other branch instructions must be conditional inside an IT block, and must be unconditional outside the IT block, see “IT” . The table below shows the ranges for the various branch instructions. Table 11-26. Branch Ranges Instruction Branch Range B label −16 MB to +16 MB Bcond label (outside IT block) −1 MB to +1 MB Bcond label (inside IT block) −16 MB to +16 MB BL{cond} label −16 MB to +16 MB BX{cond} Rm Any value in register BLX{cond} Rm Any value in register The .W suffix might be used to get the maximum branch range. See “Instruction Width Selection” . Restrictions The restrictions are: Do not use PC in the BLX instruction For BX and BLX, bit[0] of Rm must be 1 for correct execution but a branch occurs to the target address created by changing bit[0] to 0 When any of these instructions is inside an IT block, it must be the last instruction of the IT block. Bcond is the only conditional instruction that is not required to be inside an IT block. However, it has a longer branch range when it is inside an IT block. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 169 Condition Flags These instructions do not change the flags. Examples 170 B BLE B.W BEQ BEQ.W BL loopA ng target target target funC BX BXNE BLX LR R0 R0 ; ; ; ; ; ; ; ; ; ; Branch to loopA Conditionally branch to label ng Branch to target within 16MB range Conditionally branch to target Conditionally branch to target within 1MB Branch with link (Call) to function funC, return address stored in LR Return from function call Conditionally branch to address stored in R0 Branch with link and exchange (Call) to a address stored in R0. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.6.10.2 CBZ and CBNZ Compare and Branch on Zero, Compare and Branch on Non-Zero. Syntax CBZ Rn, label CBNZ Rn, label where: Rn is the register holding the operand. label is the branch destination. Operation Use the CBZ or CBNZ instructions to avoid changing the condition code flags and to reduce the number of instructions. CBZ Rn, label does not change condition flags but is otherwise equivalent to: CMP Rn, #0 BEQ label CBNZ Rn, label does not change condition flags but is otherwise equivalent to: CMP Rn, #0 BNE label Restrictions The restrictions are: Rn must be in the range of R0 to R7 The branch destination must be within 4 to 130 bytes after the instruction These instructions must not be used inside an IT block. Condition Flags These instructions do not change the flags. Examples CBZ CBNZ R5, target R0, target ; Forward branch if R5 is zero ; Forward branch if R0 is not zero SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 171 11.6.10.3 IT If-Then condition instruction. Syntax IT{x{y{z}}} cond where: x specifies the condition switch for the second instruction in the IT block. y specifies the condition switch for the third instruction in the IT block. z specifies the condition switch for the fourth instruction in the IT block. cond specifies the condition for the first instruction in the IT block. The condition switch for the second, third and fourth instruction in the IT block can be either: T Then. Applies the condition cond to the instruction. E Else. Applies the inverse condition of cond to the instruction. It is possible to use AL (the always condition) for cond in an IT instruction. If this is done, all of the instructions in the IT block must be unconditional, and each of x, y, and z must be T or omitted but not E. Operation The IT instruction makes up to four following instructions conditional. The conditions can be all the same, or some of them can be the logical inverse of the others. The conditional instructions following the IT instruction form the IT block. The instructions in the IT block, including any branches, must specify the condition in the {cond} part of their syntax. The assembler might be able to generate the required IT instructions for conditional instructions automatically, so that the user does not have to write them. See the assembler documentation for details. A BKPT instruction in an IT block is always executed, even if its condition fails. Exceptions can be taken between an IT instruction and the corresponding IT block, or within an IT block. Such an exception results in entry to the appropriate exception handler, with suitable return information in LR and stacked PSR. Instructions designed for use for exception returns can be used as normal to return from the exception, and execution of the IT block resumes correctly. This is the only way that a PC-modifying instruction is permitted to branch to an instruction in an IT block. Restrictions The following instructions are not permitted in an IT block: IT CBZ and CBNZ CPSID and CPSIE. Other restrictions when using an IT block are: 172 A branch or any instruction that modifies the PC must either be outside an IT block or must be the last instruction inside the IT block. These are: ̶ ADD PC, PC, Rm ̶ MOV PC, Rm ̶ B, BL, BX, BLX ̶ Any LDM, LDR, or POP instruction that writes to the PC ̶ TBB and TBH Do not branch to any instruction inside an IT block, except when returning from an exception handler SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 All conditional instructions except Bcond must be inside an IT block. Bcond can be either outside or inside an IT block but has a larger branch range if it is inside one Each instruction inside the IT block must specify a condition code suffix that is either the same or logical inverse as for the other instructions in the block. Your assembler might place extra restrictions on the use of IT blocks, such as prohibiting the use of assembler directives within them. Condition Flags This instruction does not change the flags. Example ITTE ANDNE ADDSNE MOVEQ NE R0, R0, R1 R2, R2, #1 R2, R3 ; ; ; ; Next 3 instructions are conditional ANDNE does not update condition flags ADDSNE updates condition flags Conditional move CMP R0, #9 ITE ADDGT ADDLE GT R1, R0, #55 R1, R0, #48 ; ; ; ; ; Convert R0 hex value (0 to 15) into ASCII ('0'-'9', 'A'-'F') Next 2 instructions are conditional Convert 0xA -> 'A' Convert 0x0 -> '0' IT ADDGT GT R1, R1, #1 ; IT block with only one conditional instruction ; Increment R1 conditionally ITTEE MOVEQ ADDEQ ANDNE BNE.W EQ R0, R1 R2, R2, #10 R3, R3, #1 dloop ; ; ; ; ; ; IT ADD NE R0, R0, R1 ; Next instruction is conditional ; Syntax error: no condition code used in IT block Next 4 instructions are conditional Conditional move Conditional add Conditional AND Branch instruction can only be used in the last instruction of an IT block SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 173 11.6.10.4 TBB and TBH Table Branch Byte and Table Branch Halfword. Syntax TBB [Rn, Rm] TBH [Rn, Rm, LSL #1] where: Rn is the register containing the address of the table of branch lengths. If Rn is PC, then the address of the table is the address of the byte immediately following the TBB or TBH instruction. Rm is the index register. This contains an index into the table. For halfword tables, LSL #1 doubles the value in Rm to form the right offset into the table. Operation These instructions cause a PC-relative forward branch using a table of single byte offsets for TBB, or halfword offsets for TBH. Rn provides a pointer to the table, and Rm supplies an index into the table. For TBB the branch offset is twice the unsigned value of the byte returned from the table. and for TBH the branch offset is twice the unsigned value of the halfword returned from the table. The branch occurs to the address at that offset from the address of the byte immediately after the TBB or TBH instruction. Restrictions The restrictions are: Rn must not be SP Rm must not be SP and must not be PC When any of these instructions is used inside an IT block, it must be the last instruction of the IT block. Condition Flags These instructions do not change the flags. Examples ADR.W TBB R0, BranchTable_Byte [R0, R1] ; R1 is the index, R0 is the base address of the ; branch table Case1 ; an instruction sequence follows Case2 ; an instruction sequence follows Case3 ; an instruction sequence follows BranchTable_Byte DCB 0 ; Case1 offset calculation DCB ((Case2-Case1)/2) ; Case2 offset calculation DCB ((Case3-Case1)/2) ; Case3 offset calculation TBH [PC, R1, LSL #1] ; R1 is the index, PC is used as base of the ; branch table BranchTable_H DCI ((CaseA - BranchTable_H)/2) DCI ((CaseB - BranchTable_H)/2) DCI ((CaseC - BranchTable_H)/2) CaseA 174 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 ; CaseA offset calculation ; CaseB offset calculation ; CaseC offset calculation ; an instruction sequence follows CaseB ; an instruction sequence follows CaseC ; an instruction sequence follows SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 175 11.6.11 Miscellaneous Instructions The table below shows the remaining Cortex-M4 instructions: Table 11-27. 176 Miscellaneous Instructions Mnemonic Description BKPT Breakpoint CPSID Change Processor State, Disable Interrupts CPSIE Change Processor State, Enable Interrupts DMB Data Memory Barrier DSB Data Synchronization Barrier ISB Instruction Synchronization Barrier MRS Move from special register to register MSR Move from register to special register NOP No Operation SEV Send Event SVC Supervisor Call WFI Wait For Interrupt SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.6.11.1 BKPT Breakpoint. Syntax BKPT #imm where: imm is an expression evaluating to an integer in the range 0-255 (8-bit value). Operation The BKPT instruction causes the processor to enter Debug state. Debug tools can use this to investigate system state when the instruction at a particular address is reached. imm is ignored by the processor. If required, a debugger can use it to store additional information about the breakpoint. The BKPT instruction can be placed inside an IT block, but it executes unconditionally, unaffected by the condition specified by the IT instruction. Condition Flags This instruction does not change the flags. Examples BKPT 0xAB Note: ; Breakpoint with immediate value set to 0xAB (debugger can ; extract the immediate value by locating it using the PC) ARM does not recommend the use of the BKPT instruction with an immediate value set to 0xAB for any purpose other than Semi-hosting. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 177 11.6.11.2 CPS Change Processor State. Syntax CPSeffect iflags where: effect is one of: IE Clears the special purpose register. ID Sets the special purpose register. iflags is a sequence of one or more flags: i Set or clear PRIMASK. f Set or clear FAULTMASK. Operation CPS changes the PRIMASK and FAULTMASK special register values. See “Exception Mask Registers” for more information about these registers. Restrictions The restrictions are: Use CPS only from privileged software, it has no effect if used in unprivileged software CPS cannot be conditional and so must not be used inside an IT block. Condition Flags This instruction does not change the condition flags. Examples CPSID CPSID CPSIE CPSIE 178 i f i f ; ; ; ; Disable interrupts and configurable fault handlers (set PRIMASK) Disable interrupts and all fault handlers (set FAULTMASK) Enable interrupts and configurable fault handlers (clear PRIMASK) Enable interrupts and fault handlers (clear FAULTMASK) SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.6.11.3 DMB Data Memory Barrier. Syntax DMB{cond} where: cond is an optional condition code, see “Conditional Execution” . Operation DMB acts as a data memory barrier. It ensures that all explicit memory accesses that appear, in program order, before the DMB instruction are completed before any explicit memory accesses that appear, in program order, after the DMB instruction. DMB does not affect the ordering or execution of instructions that do not access memory. Condition Flags This instruction does not change the flags. Examples DMB ; Data Memory Barrier SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 179 11.6.11.4 DSB Data Synchronization Barrier. Syntax DSB{cond} where: cond is an optional condition code, see “Conditional Execution” . Operation DSB acts as a special data synchronization memory barrier. Instructions that come after the DSB, in program order, do not execute until the DSB instruction completes. The DSB instruction completes when all explicit memory accesses before it complete. Condition Flags This instruction does not change the flags. Examples DSB ; Data Synchronisation Barrier 180 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.6.11.5 ISB Instruction Synchronization Barrier. Syntax ISB{cond} where: cond is an optional condition code, see “Conditional Execution” . Operation ISB acts as an instruction synchronization barrier. It flushes the pipeline of the processor, so that all instructions following the ISB are fetched from memory again, after the ISB instruction has been completed. Condition Flags This instruction does not change the flags. Examples ISB ; Instruction Synchronisation Barrier SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 181 11.6.11.6 MRS Move the contents of a special register to a general-purpose register. Syntax MRS{cond} Rd, spec_reg where: cond is an optional condition code, see “Conditional Execution” . Rd is the destination register. spec_reg can be any of: APSR, IPSR, EPSR, IEPSR, IAPSR, EAPSR, PSR, MSP, PSP, PRIMASK, BASEPRI, BASEPRI_MAX, FAULTMASK, or CONTROL. Operation Use MRS in combination with MSR as part of a read-modify-write sequence for updating a PSR, for example to clear the Q flag. In process swap code, the programmers model state of the process being swapped out must be saved, including relevant PSR contents. Similarly, the state of the process being swapped in must also be restored. These operations use MRS in the state-saving instruction sequence and MSR in the state-restoring instruction sequence. Note: BASEPRI_MAX is an alias of BASEPRI when used with the MRS instruction. See “MSR” . Restrictions Rd must not be SP and must not be PC. Condition Flags This instruction does not change the flags. Examples MRS 182 R0, PRIMASK ; Read PRIMASK value and write it to R0 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.6.11.7 MSR Move the contents of a general-purpose register into the specified special register. Syntax MSR{cond} spec_reg, Rn where: cond is an optional condition code, see “Conditional Execution” . Rn is the source register. spec_reg can be any of: APSR, IPSR, EPSR, IEPSR, IAPSR, EAPSR, PSR, MSP, PSP, PRIMASK, BASEPRI, BASEPRI_MAX, FAULTMASK, or CONTROL. Operation The register access operation in MSR depends on the privilege level. Unprivileged software can only access the APSR. See “Application Program Status Register” . Privileged software can access all special registers. In unprivileged software writes to unallocated or execution state bits in the PSR are ignored. Note: When the user writes to BASEPRI_MAX, the instruction writes to BASEPRI only if either: Rn is non-zero and the current BASEPRI value is 0 Rn is non-zero and less than the current BASEPRI value. See “MRS” . Restrictions Rn must not be SP and must not be PC. Condition Flags This instruction updates the flags explicitly based on the value in Rn. Examples MSR CONTROL, R1 ; Read R1 value and write it to the CONTROL register SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 183 11.6.11.8 NOP No Operation. Syntax NOP{cond} where: cond is an optional condition code, see “Conditional Execution” . Operation NOP does nothing. NOP is not necessarily a time-consuming NOP. The processor might remove it from the pipeline before it reaches the execution stage. Use NOP for padding, for example to place the following instruction on a 64-bit boundary. Condition Flags This instruction does not change the flags. Examples NOP 184 ; No operation SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.6.11.9 SEV Send Event. Syntax SEV{cond} where: cond is an optional condition code, see “Conditional Execution” . Operation SEV is a hint instruction that causes an event to be signaled to all processors within a multiprocessor system. It also sets the local event register to 1, see “Power Management” . Condition Flags This instruction does not change the flags. Examples SEV ; Send Event SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 185 11.6.11.10 SVC Supervisor Call. Syntax SVC{cond} #imm where: cond is an optional condition code, see “Conditional Execution” . imm is an expression evaluating to an integer in the range 0-255 (8-bit value). Operation The SVC instruction causes the SVC exception. imm is ignored by the processor. If required, it can be retrieved by the exception handler to determine what service is being requested. Condition Flags This instruction does not change the flags. Examples SVC 186 0x32 ; Supervisor Call (SVC handler can extract the immediate value ; by locating it via the stacked PC) SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.6.11.11 WFI Wait for Interrupt. Syntax WFI{cond} where: cond is an optional condition code, see “Conditional Execution” . Operation WFI is a hint instruction that suspends execution until one of the following events occurs: An exception A Debug Entry request, regardless of whether Debug is enabled. Condition Flags This instruction does not change the flags. Examples WFI ; Wait for interrupt SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 187 11.7 Cortex-M4 Core Peripherals 11.7.1 Peripherals Nested Vectored Interrupt Controller (NVIC) The Nested Vectored Interrupt Controller (NVIC) is an embedded interrupt controller that supports low latency interrupt processing. See Section 11.8 “Nested Vectored Interrupt Controller (NVIC)” System Control Block (SCB) The System Control Block (SCB) is the programmers model interface to the processor. It provides system implementation information and system control, including configuration, control, and reporting of system exceptions. See Section 11.9 “System Control Block (SCB)” System Timer (SysTick) The System Timer, SysTick, is a 24-bit count-down timer. Use this as a Real Time Operating System (RTOS) tick timer or as a simple counter. See Section 11.10 “System Timer (SysTick)” Memory Protection Unit (MPU) The Memory Protection Unit (MPU) improves system reliability by defining the memory attributes for different memory regions. It provides up to eight different regions, and an optional predefined background region. See Section 11.11 “Memory Protection Unit (MPU)” 11.7.2 Address Map The address map of the Private peripheral bus (PPB) is: Table 11-28. Core Peripheral Register Regions Address Core Peripheral 0xE000E008-0xE000E00F System Control Block 0xE000E010-0xE000E01F System Timer 0xE000E100-0xE000E4EF Nested Vectored Interrupt Controller 0xE000ED00-0xE000ED3F System control block 0xE000ED90-0xE000EDB8 Memory Protection Unit 0xE000EF00-0xE000EF03 Nested Vectored Interrupt Controller In register descriptions: 188 The required privilege gives the privilege level required to access the register, as follows: ̶ Privileged: Only privileged software can access the register. ̶ Unprivileged: Both unprivileged and privileged software can access the register. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.8 Nested Vectored Interrupt Controller (NVIC) This section describes the NVIC and the registers it uses. The NVIC supports: 1 to 30 interrupts. A programmable priority level of 0-15 for each interrupt. A higher level corresponds to a lower priority, so level 0 is the highest interrupt priority. Level detection of interrupt signals. Dynamic reprioritization of interrupts. Grouping of priority values into group priority and subpriority fields. Interrupt tail-chaining. An external Non-maskable interrupt (NMI) The processor automatically stacks its state on exception entry and unstacks this state on exception exit, with no instruction overhead. This provides low latency exception handling. 11.8.1 Level-sensitive Interrupts The processor supports level-sensitive interrupts. A level-sensitive interrupt is held asserted until the peripheral deasserts the interrupt signal. Typically, this happens because the ISR accesses the peripheral, causing it to clear the interrupt request. When the processor enters the ISR, it automatically removes the pending state from the interrupt (see “Hardware and Software Control of Interrupts” ). For a level-sensitive interrupt, if the signal is not deasserted before the processor returns from the ISR, the interrupt becomes pending again, and the processor must execute its ISR again. This means that the peripheral can hold the interrupt signal asserted until it no longer requires servicing. 11.8.1.1 Hardware and Software Control of Interrupts The Cortex-M4 latches all interrupts. A peripheral interrupt becomes pending for one of the following reasons: The NVIC detects that the interrupt signal is HIGH and the interrupt is not active The NVIC detects a rising edge on the interrupt signal A software writes to the corresponding interrupt set-pending register bit, see “Interrupt Set-pending Registers” , or to the NVIC_STIR register to make an interrupt pending, see “Software Trigger Interrupt Register” . A pending interrupt remains pending until one of the following: The processor enters the ISR for the interrupt. This changes the state of the interrupt from pending to active. Then: ̶ For a level-sensitive interrupt, when the processor returns from the ISR, the NVIC samples the interrupt signal. If the signal is asserted, the state of the interrupt changes to pending, which might cause the processor to immediately re-enter the ISR. Otherwise, the state of the interrupt changes to inactive. Software writes to the corresponding interrupt clear-pending register bit. For a level-sensitive interrupt, if the interrupt signal is still asserted, the state of the interrupt does not change. Otherwise, the state of the interrupt changes to inactive. 11.8.2 NVIC Design Hints and Tips Ensure that the software uses correctly aligned register accesses. The processor does not support unaligned accesses to NVIC registers. See the individual register descriptions for the supported access sizes. A interrupt can enter a pending state even if it is disabled. Disabling an interrupt only prevents the processor from taking that interrupt. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 189 Before programming SCB_VTOR to relocate the vector table, ensure that the vector table entries of the new vector table are set up for fault handlers, NMI and all enabled exception like interrupts. For more information, see the “Vector Table Offset Register” . 11.8.2.1 NVIC Programming Hints The software uses the CPSIE I and CPSID I instructions to enable and disable the interrupts. The CMSIS provides the following intrinsic functions for these instructions: void __disable_irq(void) // Disable Interrupts void __enable_irq(void) // Enable Interrupts In addition, the CMSIS provides a number of functions for NVIC control, including: Table 11-29. CMSIS Functions for NVIC Control CMSIS Interrupt Control Function Description void NVIC_SetPriorityGrouping(uint32_t priority_grouping) Set the priority grouping void NVIC_EnableIRQ(IRQn_t IRQn) Enable IRQn void NVIC_DisableIRQ(IRQn_t IRQn) Disable IRQn uint32_t NVIC_GetPendingIRQ (IRQn_t IRQn) Return true (IRQ-Number) if IRQn is pending void NVIC_SetPendingIRQ (IRQn_t IRQn) Set IRQn pending void NVIC_ClearPendingIRQ (IRQn_t IRQn) Clear IRQn pending status uint32_t NVIC_GetActive (IRQn_t IRQn) Return the IRQ number of the active interrupt void NVIC_SetPriority (IRQn_t IRQn, uint32_t priority) Set priority for IRQn uint32_t NVIC_GetPriority (IRQn_t IRQn) Read priority of IRQn void NVIC_SystemReset (void) Reset the system The input parameter IRQn is the IRQ number. For more information about these functions, see the CMSIS documentation. To improve software efficiency, the CMSIS simplifies the NVIC register presentation. In the CMSIS: The Set-enable, Clear-enable, Set-pending, Clear-pending and Active Bit registers map to arrays of 32-bit integers, so that: ̶ The array ISER[0] corresponds to the registers ISER0 ̶ The array ICER[0] corresponds to the registers ICER0 ̶ The array ISPR[0] corresponds to the registers ISPR0 ̶ The array ICPR[0]corresponds to the registers ICPR0 ̶ The array IABR[0]corresponds to the registers IABR0 The 4-bit fields of the Interrupt Priority Registers map to an array of 4-bit integers, so that the array IP[0] to IP[29] corresponds to the registers IPR0-IPR7, and the array entry IP[n] holds the interrupt priority for interrupt n. The CMSIS provides thread-safe code that gives atomic access to the Interrupt Priority Registers. Table 11-30 shows how the interrupts, or IRQ numbers, map onto the interrupt registers and corresponding CMSIS variables that have one bit per interrupt. Table 11-30. Mapping of Interrupts to the Interrupt Variables CMSIS Array Elements (1) Interrupts 0-29 Notes: 190 Set-enable Clear-enable Set-pending Clear-pending Active Bit ISER[0] ICER[0] ISPR[0] ICPR[0] IABR[0] 1. Each array element corresponds to a single NVIC register, for example the ICER[0] element corresponds to the ICER0 register. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.8.3 Nested Vectored Interrupt Controller (NVIC) User Interface Table 11-31. Nested Vectored Interrupt Controller (NVIC) Register Mapping Offset Register Name Access Reset 0xE000E100 Interrupt Set-enable Register 0 NVIC_ISER0 Read-write 0x00000000 ... ... ... ... ... 0xE000E11C Interrupt Set-enable Register 7 NVIC_ISER7 Read-write 0x00000000 0XE000E180 Interrupt Clear-enable Register0 NVIC_ICER0 Read-write 0x00000000 ... ... ... ... ... 0xE000E19C Interrupt Clear-enable Register 7 NVIC_ICER7 Read-write 0x00000000 0XE000E200 Interrupt Set-pending Register 0 NVIC_ISPR0 Read-write 0x00000000 ... ... ... ... ... 0xE000E21C Interrupt Set-pending Register 7 NVIC_ISPR7 Read-write 0x00000000 0XE000E280 Interrupt Clear-pending Register 0 NVIC_ICPR0 Read-write 0x00000000 ... ... ... ... ... 0xE000E29C Interrupt Clear-pending Register 7 NVIC_ICPR7 Read-write 0x00000000 0xE000E300 Interrupt Active Bit Register 0 NVIC_IABR0 Read-write 0x00000000 ... ... ... ... ... 0xE000E31C Interrupt Active Bit Register 7 NVIC_IABR7 Read-write 0x00000000 0xE000E400 Interrupt Priority Register 0 NVIC_IPR0 Read-write 0x00000000 ... ... ... ... ... 0xE000E41C Interrupt Priority Register 7 NVIC_IPR7 Read-write 0x00000000 0xE000EF00 Software Trigger Interrupt Register NVIC_STIR Write-only 0x00000000 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 191 11.8.3.1 Interrupt Set-enable Registers Name: NVIC_ISERx [x=0..7] Access: Read-write Reset: 0x000000000 31 30 29 28 27 26 25 24 19 18 17 16 11 10 9 8 3 2 1 0 SETENA 23 22 21 20 SETENA 15 14 13 12 SETENA 7 6 5 4 SETENA These registers enable interrupts and show which interrupts are enabled. • SETENA: Interrupt Set-enable Write: 0: No effect. 1: Enables the interrupt. Read: 0: Interrupt disabled. 1: Interrupt enabled. Notes: 192 1. If a pending interrupt is enabled, the NVIC activates the interrupt based on its priority. 2. If an interrupt is not enabled, asserting its interrupt signal changes the interrupt state to pending, the NVIC never activates the interrupt, regardless of its priority. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.8.3.2 Interrupt Clear-enable Registers Name: NVIC_ICERx [x=0..7] Access: Read-write Reset: 0x000000000 31 30 29 28 27 26 25 24 19 18 17 16 11 10 9 8 3 2 1 0 CLRENA 23 22 21 20 CLRENA 15 14 13 12 CLRENA 7 6 5 4 CLRENA These registers disable interrupts, and show which interrupts are enabled. • CLRENA: Interrupt Clear-enable Write: 0: No effect. 1: Disables the interrupt. Read: 0: Interrupt disabled. 1: Interrupt enabled. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 193 11.8.3.3 Interrupt Set-pending Registers Name: NVIC_ISPRx [x=0..7] Access: Read-write Reset: 0x000000000 31 30 29 28 27 26 25 24 19 18 17 16 11 10 9 8 3 2 1 0 SETPEND 23 22 21 20 SETPEND 15 14 13 12 SETPEND 7 6 5 4 SETPEND These registers force interrupts into the pending state, and show which interrupts are pending. • SETPEND: Interrupt Set-pending Write: 0: No effect. 1: Changes the interrupt state to pending. Read: 0: Interrupt is not pending. 1: Interrupt is pending. Notes: 194 1. Writing 1 to an ISPR bit corresponding to an interrupt that is pending has no effect. 2. Writing 1 to an ISPR bit corresponding to a disabled interrupt sets the state of that interrupt to pending. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.8.3.4 Interrupt Clear-pending Registers Name: NVIC_ICPRx [x=0..7] Access: Read-write Reset: 0x000000000 31 30 29 28 27 26 25 24 19 18 17 16 11 10 9 8 3 2 1 0 CLRPEND 23 22 21 20 CLRPEND 15 14 13 12 CLRPEND 7 6 5 4 CLRPEND These registers remove the pending state from interrupts, and show which interrupts are pending. • CLRPEND: Interrupt Clear-pending Write: 0: No effect. 1: Removes the pending state from an interrupt. Read: 0: Interrupt is not pending. 1: Interrupt is pending. Note: Writing 1 to an ICPR bit does not affect the active state of the corresponding interrupt. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 195 11.8.3.5 Interrupt Active Bit Registers Name: NVIC_IABRx [x=0..7] Access: Read-write Reset: 0x000000000 31 30 29 28 27 26 25 24 19 18 17 16 11 10 9 8 3 2 1 0 ACTIVE 23 22 21 20 ACTIVE 15 14 13 12 ACTIVE 7 6 5 4 ACTIVE These registers indicate which interrupts are active. • ACTIVE: Interrupt Active Flags 0: Interrupt is not active. 1: Interrupt is active. Note: A bit reads as one if the status of the corresponding interrupt is active, or active and pending. 196 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.8.3.6 Interrupt Priority Registers Name: NVIC_IPRx [x=0..7] Access: Read-write Reset: 0x000000000 31 30 29 28 27 26 25 24 19 18 17 16 11 10 9 8 3 2 1 0 PRI3 23 22 21 20 PRI2 15 14 13 12 PRI1 7 6 5 4 PRI0 The NVIC_IPR0-NVIC_IPR7 registers provide a 4-bit priority field for each interrupt. These registers are byte-accessible. Each register holds four priority fields, that map up to four elements in the CMSIS interrupt priority array IP[0] to IP[29] • PRI3: Priority (4m+3) Priority, Byte Offset 3, refers to register bits [31:24]. • PRI2: Priority (4m+2) Priority, Byte Offset 2, refers to register bits [23:16]. • PRI1: Priority (4m+1) Priority, Byte Offset 1, refers to register bits [15:8]. • PRI0: Priority (4m) Priority, Byte Offset 0, refers to register bits [7:0]. Notes: 1. Each priority field holds a priority value, 0-15. The lower the value, the greater the priority of the corresponding interrupt. The processor implements only bits[7:4] of each field; bits[3:0] read as zero and ignore writes. 2. for more information about the IP[0] to IP[29] interrupt priority array, that provides the software view of the interrupt priorities, see Table 11-29, “CMSIS Functions for NVIC Control” . 3. The corresponding IPR number n is given by n = m DIV 4. 4. The byte offset of the required Priority field in this register is m MOD 4. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 197 11.8.3.7 Software Trigger Interrupt Register Name: NVIC_STIR Access: Write-only Reset: 0x000000000 31 – 30 – 29 – 28 – 27 – 26 – 25 – 24 – 23 – 22 – 21 – 20 – 19 – 18 – 17 – 16 – 15 – 14 – 13 – 12 – 11 – 10 – 9 – 8 INTID 7 6 5 4 3 2 1 0 INTID Write to this register to generate an interrupt from the software. • INTID: Interrupt ID Interrupt ID of the interrupt to trigger, in the range 0-239. For example, a value of 0x03 specifies interrupt IRQ3. 198 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.9 System Control Block (SCB) The System Control Block (SCB) provides system implementation information, and system control. This includes configuration, control, and reporting of the system exceptions. Ensure that the software uses aligned accesses of the correct size to access the system control block registers: Except for the SCB_CFSR and SCB_SHPR1-SCB_SHPR3 registers, it must use aligned word accesses For the SCB_CFSR and SCB_SHPR1-SCB_SHPR3 registers, it can use byte or aligned halfword or word accesses. The processor does not support unaligned accesses to system control block registers. In a fault handler, to determine the true faulting address: 1. Read and save the MMFAR or SCB_BFAR value. 2. Read the MMARVALID bit in the MMFSR subregister, or the BFARVALID bit in the BFSR subregister. The SCB_MMFAR or SCB_BFAR address is valid only if this bit is 1. The software must follow this sequence because another higher priority exception might change the SCB_MMFAR or SCB_BFAR value. For example, if a higher priority handler preempts the current fault handler, the other fault might change the SCB_MMFAR or SCB_BFAR value. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 199 11.9.1 System Control Block (SCB) User Interface Table 11-32. System Control Block (SCB) Register Mapping Offset Register Name Access Reset 0xE000E008 Auxiliary Control Register SCB_ACTLR Read-write 0x00000000 0xE000ED00 CPUID Base Register SCB_CPUID Read-only 0x410FC240 (1) 0x00000000 0xE000ED04 Interrupt Control and State Register SCB_ICSR Read-write 0xE000ED08 Vector Table Offset Register SCB_VTOR Read-write 0x00000000 0xE000ED0C Application Interrupt and Reset Control Register SCB_AIRCR Read-write 0xFA050000 0xE000ED10 System Control Register SCB_SCR Read-write 0x00000000 0xE000ED14 Configuration and Control Register SCB_CCR Read-write 0x00000200 0xE000ED18 System Handler Priority Register 1 SCB_SHPR1 Read-write 0x00000000 0xE000ED1C System Handler Priority Register 2 SCB_SHPR2 Read-write 0x00000000 0xE000ED20 System Handler Priority Register 3 SCB_SHPR3 Read-write 0x00000000 0xE000ED24 System Handler Control and State Register SCB_SHCSR Read-write 0x00000000 (2) Read-write 0x00000000 0xE000ED28 Configurable Fault Status Register SCB_CFSR 0xE000ED2C HardFault Status Register SCB_HFSR Read-write 0x00000000 0xE000ED34 MemManage Fault Address Register SCB_MMFAR Read-write Unknown 0xE000ED38 BusFault Address Register SCB_BFAR Read-write Unknown 0xE000ED3C Auxiliary Fault Status Register SCB_AFSR Read-write 0x00000000 Notes: 1. See the register description for more information. 2. This register contains the subregisters: “MMFSR: Memory Management Fault Status Subregister” (0xE000ED28 - 8 bits), “BFSR: Bus Fault Status Subregister” (0xE000ED29 - 8 bits), “UFSR: Usage Fault Status Subregister” (0xE000ED2A - 16 bits). 200 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.9.1.1 Auxiliary Control Register Name: SCB_ACTLR Access: Read-write Reset: 0x000000000 31 30 29 28 27 26 25 24 19 18 17 16 12 11 10 9 DISOOFP 8 DISFPCA 4 3 2 1 0 DISFOLD DISDEFWBUF DISMCYCINT – 23 22 21 20 – 15 14 13 – 7 6 5 – The SCB_ACTLR register provides disable bits for the following processor functions: IT folding Write buffer use for accesses to the default memory map Interruption of multi-cycle instructions. By default, this register is set to provide optimum performance from the Cortex-M4 processor, and does not normally require modification. • DISOOFP: Disable Out Of Order Floating Point Disables floating point instructions that complete out of order with respect to integer instructions. • DISFPCA: Disable FPCA Disables an automatic update of CONTROL.FPCA. • DISFOLD: Disable Folding When set to 1, disables the IT folding. Note: In some situations, the processor can start executing the first instruction in an IT block while it is still executing the IT instruction. This behavior is called IT folding, and it improves the performance. However, IT folding can cause jitter in looping. If a task must avoid jitter, set the DISFOLD bit to 1 before executing the task, to disable the IT folding. • DISDEFWBUF: Disable Default Write Buffer When set to 1, it disables the write buffer use during default memory map accesses. This causes BusFault to be precise but decreases the performance, as any store to memory must complete before the processor can execute the next instruction. This bit only affects write buffers implemented in the Cortex-M4 processor. • DISMCYCINT: Disable Multiple Cycle Interruption When set to 1, it disables the interruption of load multiple and store multiple instructions. This increases the interrupt latency of the processor, as any LDM or STM must complete before the processor can stack the current state and enter the interrupt handler. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 201 11.9.1.2 CPUID Base Register Name: SCB_CPUID Access: Read-write Reset: 0x000000000 31 30 29 28 27 26 19 18 25 24 17 16 Implementer 23 22 21 20 Variant 15 14 Constant 13 12 11 10 9 8 3 2 1 0 PartNo 7 6 5 4 PartNo Revision The SCB_CPUID register contains the processor part number, version, and implementation information. • Implementer: Implementer Code 0x41: ARM. • Variant: Variant Number It is the r value in the rnpn product revision identifier: 0x0: Revision 0. • Constant Reads as 0xF. • PartNo: Part Number of the Processor 0xC24 = Cortex-M4. • Revision: Revision Number It is the p value in the rnpn product revision identifier: 0x0: Patch 0. 202 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.9.1.3 Interrupt Control and State Register Name: SCB_ICSR Access: Read-write Reset: 0x000000000 31 NMIPENDSET 30 23 – 22 ISRPENDING 15 7 29 28 PENDSVSET 21 20 14 13 VECTPENDING 12 6 4 – 5 27 PENDSVCLR 26 PENDSTSET 19 18 VECTPENDING 11 RETTOBASE 10 3 2 25 PENDSTCLR 24 – 17 16 9 8 VECTACTIVE 1 0 – VECTACTIVE The SCB_ICSR register provides a set-pending bit for the Non-Maskable Interrupt (NMI) exception, and set-pending and clear-pending bits for the PendSV and SysTick exceptions. It indicates: The exception number of the exception being processed, and whether there are preempted active exceptions, The exception number of the highest priority pending exception, and whether any interrupts are pending. • NMIPENDSET: NMI Set-pending Write: PendSV set-pending bit. Write: 0: No effect. 1: Changes NMI exception state to pending. Read: 0: NMI exception is not pending. 1: NMI exception is pending. As NMI is the highest-priority exception, the processor normally enters the NMI exception handler as soon as it registers a write of 1 to this bit. Entering the handler clears this bit to 0. A read of this bit by the NMI exception handler returns 1 only if the NMI signal is reasserted while the processor is executing that handler. • PENDSVSET: PendSV Set-pending Write: 0: No effect. 1: Changes PendSV exception state to pending. Read: 0: PendSV exception is not pending. 1: PendSV exception is pending. Writing 1 to this bit is the only way to set the PendSV exception state to pending. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 203 • PENDSVCLR: PendSV Clear-pending Write: 0: No effect. 1: Removes the pending state from the PendSV exception. • PENDSTSET: SysTick Exception Set-pending Write: 0: No effect. 1: Changes SysTick exception state to pending. Read: 0: SysTick exception is not pending. 1: SysTick exception is pending. • PENDSTCLR: SysTick Exception Clear-pending Write: 0: No effect. 1: Removes the pending state from the SysTick exception. This bit is Write-only. On a register read, its value is Unknown. • ISRPENDING: Interrupt Pending Flag (Excluding NMI and Faults) 0: Interrupt not pending. 1: Interrupt pending. • VECTPENDING: Exception Number of the Highest Priority Pending Enabled Exception 0: No pending exceptions. Nonzero: The exception number of the highest priority pending enabled exception. The value indicated by this field includes the effect of the BASEPRI and FAULTMASK registers, but not any effect of the PRIMASK register. • RETTOBASE: Preempted Active Exceptions Present or Not 0: There are preempted active exceptions to execute. 1: There are no active exceptions, or the currently-executing exception is the only active exception. • VECTACTIVE: Active Exception Number Contained 0: Thread mode. Nonzero: The exception number of the currently active exception. The value is the same as IPSR bits [8:0]. See “Interrupt Program Status Register” . Subtract 16 from this value to obtain the IRQ number required to index into the Interrupt Clear-Enable, Set-Enable, ClearPending, Set-Pending, or Priority Registers, see “Interrupt Program Status Register” . Note: When the user writes to the SCB_ICSR register, the effect is unpredictable if: - Writing 1 to the PENDSVSET bit and writing 1 to the PENDSVCLR bit - Writing 1 to the PENDSTSET bit and writing 1 to the PENDSTCLR bit. 204 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.9.1.4 Vector Table Offset Register Name: SCB_VTOR Access: Read-write Reset: 0x000000000 31 30 29 28 27 26 25 24 19 18 17 16 11 10 9 8 3 – 2 1 0 TBLOFF 23 22 21 20 TBLOFF 15 14 13 12 TBLOFF 7 TBLOFF 6 5 4 The SCB_VTOR register indicates the offset of the vector table base address from memory address 0x00000000. • TBLOFF: Vector Table Base Offset It contains bits [29:7] of the offset of the table base from the bottom of the memory map. Bit [29] determines whether the vector table is in the code or SRAM memory region: 0: Code. 1: SRAM. It is sometimes called the TBLBASE bit. Note: When setting TBLOFF, the offset must be aligned to the number of exception entries in the vector table. Configure the next statement to give the information required for your implementation; the statement reminds the user of how to determine the alignment requirement. The minimum alignment is 32 words, enough for up to 16 interrupts. For more interrupts, adjust the alignment by rounding up to the next power of two. For example, if 21 interrupts are required, the alignment must be on a 64-word boundary because the required table size is 37 words, and the next power of two is 64. Table alignment requirements mean that bits[6:0] of the table offset are always zero. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 205 11.9.1.5 Application Interrupt and Reset Control Register Name: SCB_AIRCR Access: Read-write Reset: 0x000000000 31 30 29 28 27 VECTKEYSTAT/VECTKEY 26 25 24 23 22 21 20 19 VECTKEYSTAT/VECTKEY 18 17 16 15 ENDIANNESS 14 13 9 PRIGROUP 8 7 6 12 11 10 4 3 2 – 5 – 1 VECTCLRACTI SYSRESETREQ VE 0 VECTRESET The SCB_AIRCR register provides priority grouping control for the exception model, endian status for data accesses, and reset control of the system. To write to this register, write 0x5FA to the VECTKEY field, otherwise the processor ignores the write. • VECTKEYSTAT: Register Key Read: Reads as 0xFA05. • VECTKEY: Register Key Write: Writes 0x5FA to VECTKEY, otherwise the write is ignored. • ENDIANNESS: Data Endianness 0: Little-endian. 1: Big-endian. 206 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 • PRIGROUP: Interrupt Priority Grouping This field determines the split of group priority from subpriority. It shows the position of the binary point that splits the PRI_n fields in the Interrupt Priority Registers into separate group priority and subpriority fields. The table below shows how the PRIGROUP value controls this split: Interrupt Priority Level Value, PRI_N[7:0] PRIGROUP Binary Point 0b000 (1) Number of Group Priority Bits Subpriority Bits Group Priorities Subpriorities bxxxxxxx.y [7:1] None 128 2 0b001 bxxxxxx.yy [7:2] [4:0] 64 4 0b010 bxxxxx.yyy [7:3] [4:0] 32 8 0b011 bxxxx.yyyy [7:4] [4:0] 16 16 0b100 bxxx.yyyyy [7:5] [4:0] 8 32 0b101 bxx.yyyyyy [7:6] [5:0] 4 64 0b110 bx.yyyyyyy [7] [6:0] 2 128 0b111 b.yyyyyyy None [7:0] 1 256 Note: 1. PRI_n[7:0] field showing the binary point. x denotes a group priority field bit, and y denotes a subpriority field bit. Determining preemption of an exception uses only the group priority field. • SYSRESETREQ: System Reset Request 0: No system reset request. 1: Asserts a signal to the outer system that requests a reset. This is intended to force a large system reset of all major components except for debug. This bit reads as 0. • VECTCLRACTIVE Reserved for Debug use. This bit reads as 0. When writing to the register, write 0 to this bit, otherwise the behavior is unpredictable. • VECTRESET Reserved for Debug use. This bit reads as 0. When writing to the register, write 0 to this bit, otherwise the behavior is unpredictable. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 207 11.9.1.6 System Control Register Name: SCB_SCR Access: Read-write Reset: 0x000000000 31 30 29 28 27 26 25 24 19 18 17 16 11 10 9 8 3 – 2 SLEEPDEEP 1 SLEEPONEXIT 0 – – 23 22 21 20 – 15 14 13 12 – 7 6 – 5 4 SEVONPEND • SEVONPEND: Send Event on Pending Bit 0: Only enabled interrupts or events can wake up the processor; disabled interrupts are excluded. 1: Enabled events and all interrupts, including disabled interrupts, can wake up the processor. The processor also wakes up on execution of an SEV instruction or an external event. • SLEEPDEEP: Sleep or Deep Sleep Controls whether the processor uses sleep or deep sleep as its low power mode: 0: Sleep. 1: Deep sleep. • SLEEPONEXIT: Sleep-on-exit Indicates sleep-on-exit when returning from the Handler mode to the Thread mode: 0: Do not sleep when returning to Thread mode. 1: Enter sleep, or deep sleep, on return from an ISR. Setting this bit to 1 enables an interrupt-driven application to avoid returning to an empty main application. 208 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.9.1.7 Configuration and Control Register Name: SCB_CCR Access: Read-write Reset: 0x000000000 31 30 29 28 27 26 25 24 19 18 17 16 12 11 10 9 STKALIGN 8 BFHFNMIGN 4 3 2 DIV_0_TRP UNALIGN_TRP – – 23 22 21 20 – 15 14 13 – 7 6 5 – 1 0 USERSETMPE NONBASETHR ND DENA The SCB_CCR register controls the entry to the Thread mode and enables the handlers for NMI, hard fault and faults escalated by FAULTMASK to ignore BusFaults. It also enables the division by zero and unaligned access trapping, and the access to the NVIC_STIR register by unprivileged software (see “Software Trigger Interrupt Register” ). • STKALIGN: Stack Alignment Indicates the stack alignment on exception entry: 0: 4-byte aligned. 1: 8-byte aligned. On exception entry, the processor uses bit [9] of the stacked PSR to indicate the stack alignment. On return from the exception, it uses this stacked bit to restore the correct stack alignment. • BFHFNMIGN: Bus Faults Ignored Enables handlers with priority -1 or -2 to ignore data bus faults caused by load and store instructions. This applies to the hard fault and FAULTMASK escalated handlers: 0: Data bus faults caused by load and store instructions cause a lock-up. 1: Handlers running at priority -1 and -2 ignore data bus faults caused by load and store instructions. Set this bit to 1 only when the handler and its data are in absolutely safe memory. The normal use of this bit is to probe system devices and bridges to detect control path problems and fix them. • DIV_0_TRP: Division by Zero Trap Enables faulting or halting when the processor executes an SDIV or UDIV instruction with a divisor of 0: 0: Do not trap divide by 0. 1: Trap divide by 0. When this bit is set to 0, a divide by zero returns a quotient of 0. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 209 • UNALIGN_TRP: Unaligned Access Trap Enables unaligned access traps: 0: Do not trap unaligned halfword and word accesses. 1: Trap unaligned halfword and word accesses. If this bit is set to 1, an unaligned access generates a usage fault. Unaligned LDM, STM, LDRD, and STRD instructions always fault irrespective of whether UNALIGN_TRP is set to 1. • USERSETMPEND Enables unprivileged software access to the NVIC_STIR register, see “Software Trigger Interrupt Register” : 0: Disable. 1: Enable. • NONEBASETHRDENA: Thread Mode Enable Indicates how the processor enters Thread mode: 0: The processor can enter the Thread mode only when no exception is active. 1: The processor can enter the Thread mode from any level under the control of an EXC_RETURN value, see “Exception Return” . 210 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.9.1.8 System Handler Priority Registers The SCB_SHPR1-SCB_SHPR3 registers set the priority level, 0 to 15 of the exception handlers that have configurable priority. They are byte-accessible. The system fault handlers and the priority field and register for each handler are: Table 11-33. System Fault Handler Priority Fields Handler Field Memory management fault (MemManage) PRI_4 Bus fault (BusFault) PRI_5 Usage fault (UsageFault) PRI_6 SVCall PRI_11 PendSV PRI_14 SysTick PRI_15 Register Description “System Handler Priority Register 1” “System Handler Priority Register 2” “System Handler Priority Register 3” Each PRI_N field is 8 bits wide, but the processor implements only bits [7:4] of each field, and bits [3:0] read as zero and ignore writes. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 211 11.9.1.9 System Handler Priority Register 1 Name: SCB_SHPR1 Access: Read-write Reset: 0x000000000 31 30 29 28 27 26 25 24 19 18 17 16 11 10 9 8 3 2 1 0 – 23 22 21 20 PRI_6 15 14 13 12 PRI_5 7 6 5 4 PRI_4 • PRI_6: Priority Priority of system handler 6, UsageFault. • PRI_5: Priority Priority of system handler 5, BusFault. • PRI_4: Priority Priority of system handler 4, MemManage. 212 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.9.1.10 System Handler Priority Register 2 Name: SCB_SHPR2 Access: Read-write Reset: 0x000000000 31 30 29 28 27 26 25 24 19 18 17 16 11 10 9 8 3 2 1 0 PRI_11 23 22 21 20 – 15 14 13 12 – 7 6 5 4 – • PRI_11: Priority Priority of system handler 11, SVCall. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 213 11.9.1.11 System Handler Priority Register 3 Name: SCB_SHPR3 Access: Read-write Reset: 0x000000000 31 30 29 28 27 26 25 24 19 18 17 16 11 10 9 8 3 2 1 0 PRI_15 23 22 21 20 PRI_14 15 14 13 12 – 7 6 5 4 – • PRI_15: Priority Priority of system handler 15, SysTick exception. • PRI_14: Priority Priority of system handler 14, PendSV. 214 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.9.1.12 System Handler Control and State Register Name: SCB_SHCSR Access: Read-write Reset: 0x000000000 31 30 29 28 27 26 25 24 – 23 22 21 – 20 19 18 17 16 USGFAULTENA BUSFAULTENA MEMFAULTENA 15 14 13 12 11 SVCALLPENDE BUSFAULTPEN MEMFAULTPEN USGFAULTPEN SYSTICKACT D DED DED DED 7 SVCALLAVCT 6 5 – 4 3 USGFAULTACT 10 9 8 PENDSVACT – MONITORACT 2 – 1 0 BUSFAULTACT MEMFAULTACT The SHCSR register enables the system handlers, and indicates the pending status of the bus fault, memory management fault, and SVC exceptions; it also indicates the active status of the system handlers. • USGFAULTENA: Usage Fault Enable 0: Disables the exception. 1: Enables the exception. • BUSFAULTENA: Bus Fault Enable 0: Disables the exception. 1: Enables the exception. • MEMFAULTENA: Memory Management Fault Enable 0: Disables the exception. 1: Enables the exception. • SVCALLPENDED: SVC Call Pending Read: 0: The exception is not pending. 1: The exception is pending. Note: The user can write to these bits to change the pending status of the exceptions. • BUSFAULTPENDED: Bus Fault Exception Pending Read: 0: The exception is not pending. 1: The exception is pending. Note: The user can write to these bits to change the pending status of the exceptions. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 215 • MEMFAULTPENDED: Memory Management Fault Exception Pending Read: 0: The exception is not pending. 1: The exception is pending. Note: The user can write to these bits to change the pending status of the exceptions. • USGFAULTPENDED: Usage Fault Exception Pending Read: 0: The exception is not pending. 1: The exception is pending. Note: The user can write to these bits to change the pending status of the exceptions. • SYSTICKACT: SysTick Exception Active Read: 0: The exception is not active. 1: The exception is active. Note: The user can write to these bits to change the active status of the exceptions. - Caution: A software that changes the value of an active bit in this register without a correct adjustment to the stacked content can cause the processor to generate a fault exception. Ensure that the software writing to this register retains and subsequently restores the current active status. - Caution: After enabling the system handlers, to change the value of a bit in this register, the user must use a read-modify-write procedure to ensure that only the required bit is changed. • PENDSVACT: PendSV Exception Active 0: The exception is not active. 1: The exception is active. • MONITORACT: Debug Monitor Active 0: Debug monitor is not active. 1: Debug monitor is active. • SVCALLACT: SVC Call Active 0: SVC call is not active. 1: SVC call is active. • USGFAULTACT: Usage Fault Exception Active 0: Usage fault exception is not active. 1: Usage fault exception is active. • BUSFAULTACT: Bus Fault Exception Active 0: Bus fault exception is not active. 1: Bus fault exception is active. • MEMFAULTACT: Memory Management Fault Exception Active 0: Memory management fault exception is not active. 1: Memory management fault exception is active. 216 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 If the user disables a system handler and the corresponding fault occurs, the processor treats the fault as a hard fault. The user can write to this register to change the pending or active status of system exceptions. An OS kernel can write to the active bits to perform a context switch that changes the current exception type. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 217 11.9.1.13 Configurable Fault Status Register Name: SCB_CFSR Access: Read-write Reset: 0x000000000 31 30 29 28 27 26 25 DIVBYZERO 24 UNALIGNED 21 20 19 NOCP 18 INVPC 17 INVSTATE 16 UNDEFINSTR 13 12 STKERR 11 UNSTKERR 10 IMPRECISERR 9 PRECISERR 8 IBUSERR 5 MLSPERR 4 MSTKERR 3 MUNSTKERR 2 – 1 DACCVIOL 0 IACCVIOL – 23 22 – 15 BFRVALID 14 7 MMARVALID 6 – – • IACCVIOL: Instruction Access Violation Flag This is part of “MMFSR: Memory Management Fault Status Subregister” . 0: No instruction access violation fault. 1: The processor attempted an instruction fetch from a location that does not permit execution. This fault occurs on any access to an XN region, even when the MPU is disabled or not present. When this bit is 1, the PC value stacked for the exception return points to the faulting instruction. The processor has not written a fault address to the SCB_MMFAR register. • DACCVIOL: Data Access Violation Flag This is part of “MMFSR: Memory Management Fault Status Subregister” . 0: No data access violation fault. 1: The processor attempted a load or store at a location that does not permit the operation. When this bit is 1, the PC value stacked for the exception return points to the faulting instruction. The processor has loaded the SCB_MMFAR register with the address of the attempted access. • MUNSTKERR: Memory Manager Fault on Unstacking for a Return From Exception This is part of “MMFSR: Memory Management Fault Status Subregister” . 0: No unstacking fault. 1: Unstack for an exception return has caused one or more access violations. This fault is chained to the handler. This means that when this bit is 1, the original return stack is still present. The processor has not adjusted the SP from the failing return, and has not performed a new save. The processor has not written a fault address to the SCB_MMFAR register. • MSTKERR: Memory Manager Fault on Stacking for Exception Entry This is part of “MMFSR: Memory Management Fault Status Subregister” . 0: No stacking fault. 1: Stacking for an exception entry has caused one or more access violations. When this bit is 1, the SP is still adjusted but the values in the context area on the stack might be incorrect. The processor has not written a fault address to SCB_MMFAR register. 218 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 • MLSPERR: MemManage during Lazy State Preservation This is part of “MMFSR: Memory Management Fault Status Subregister” . 0: No MemManage fault occurred during the floating-point lazy state preservation. 1: A MemManage fault occurred during the floating-point lazy state preservation. • MMARVALID: Memory Management Fault Address Register (SCB_MMFAR) Valid Flag This is part of “MMFSR: Memory Management Fault Status Subregister” . 0: The value in SCB_MMFAR is not a valid fault address. 1: SCB_MMFAR register holds a valid fault address. If a memory management fault occurs and is escalated to a hard fault because of priority, the hard fault handler must set this bit to 0. This prevents problems on return to a stacked active memory management fault handler whose SCB_MMFAR value has been overwritten. • IBUSERR: Instruction Bus Error This is part of “BFSR: Bus Fault Status Subregister” . 0: No instruction bus error. 1: Instruction bus error. The processor detects the instruction bus error on prefetching an instruction, but it sets the IBUSERR flag to 1 only if it attempts to issue the faulting instruction. When the processor sets this bit to 1, it does not write a fault address to the BFAR register. • PRECISERR: Precise Data Bus Error This is part of “BFSR: Bus Fault Status Subregister” . 0: No precise data bus error. 1: A data bus error has occurred, and the PC value stacked for the exception return points to the instruction that caused the fault. When the processor sets this bit to 1, it writes the faulting address to the SCB_BFAR register. • IMPRECISERR: Imprecise Data Bus Error This is part of “BFSR: Bus Fault Status Subregister” . 0: No imprecise data bus error. 1: A data bus error has occurred, but the return address in the stack frame is not related to the instruction that caused the error. When the processor sets this bit to 1, it does not write a fault address to the SCB_BFAR register. This is an asynchronous fault. Therefore, if it is detected when the priority of the current process is higher than the bus fault priority, the bus fault becomes pending and becomes active only when the processor returns from all higher priority processes. If a precise fault occurs before the processor enters the handler for the imprecise bus fault, the handler detects that both this bit and one of the precise fault status bits are set to 1. • UNSTKERR: Bus Fault on Unstacking for a Return From Exception This is part of “BFSR: Bus Fault Status Subregister” . 0: No unstacking fault. 1: Unstack for an exception return has caused one or more bus faults. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 219 This fault is chained to the handler. This means that when the processor sets this bit to 1, the original return stack is still present. The processor does not adjust the SP from the failing return, does not performed a new save, and does not write a fault address to the BFAR. • STKERR: Bus Fault on Stacking for Exception Entry This is part of “BFSR: Bus Fault Status Subregister” . 0: No stacking fault. 1: Stacking for an exception entry has caused one or more bus faults. When the processor sets this bit to 1, the SP is still adjusted but the values in the context area on the stack might be incorrect. The processor does not write a fault address to the SCB_BFAR register. • BFARVALID: Bus Fault Address Register (BFAR) Valid flag This is part of “BFSR: Bus Fault Status Subregister” . 0: The value in SCB_BFAR is not a valid fault address. 1: SCB_BFAR holds a valid fault address. The processor sets this bit to 1 after a bus fault where the address is known. Other faults can set this bit to 0, such as a memory management fault occurring later. If a bus fault occurs and is escalated to a hard fault because of priority, the hard fault handler must set this bit to 0. This prevents problems if returning to a stacked active bus fault handler whose SCB_BFAR value has been overwritten. • UNDEFINSTR: Undefined Instruction Usage Fault This is part of “UFSR: Usage Fault Status Subregister” . 0: No undefined instruction usage fault. 1: The processor has attempted to execute an undefined instruction. When this bit is set to 1, the PC value stacked for the exception return points to the undefined instruction. An undefined instruction is an instruction that the processor cannot decode. • INVSTATE: Invalid State Usage Fault This is part of “UFSR: Usage Fault Status Subregister” . 0: No invalid state usage fault. 1: The processor has attempted to execute an instruction that makes illegal use of the EPSR. When this bit is set to 1, the PC value stacked for the exception return points to the instruction that attempted the illegal use of the EPSR. This bit is not set to 1 if an undefined instruction uses the EPSR. • INVPC: Invalid PC Load Usage Fault This is part of “UFSR: Usage Fault Status Subregister” . It is caused by an invalid PC load by EXC_RETURN: 0: No invalid PC load usage fault. 1: The processor has attempted an illegal load of EXC_RETURN to the PC, as a result of an invalid context, or an invalid EXC_RETURN value. When this bit is set to 1, the PC value stacked for the exception return points to the instruction that tried to perform the illegal load of the PC. 220 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 • NOCP: No Coprocessor Usage Fault This is part of “UFSR: Usage Fault Status Subregister” . The processor does not support coprocessor instructions: 0: No usage fault caused by attempting to access a coprocessor. 1: The processor has attempted to access a coprocessor. • UNALIGNED: Unaligned Access Usage Fault This is part of “UFSR: Usage Fault Status Subregister” . 0: No unaligned access fault, or unaligned access trapping not enabled. 1: The processor has made an unaligned memory access. Enable trapping of unaligned accesses by setting the UNALIGN_TRP bit in the SCB_CCR register to 1. See “Configuration and Control Register” . Unaligned LDM, STM, LDRD, and STRD instructions always fault irrespective of the setting of UNALIGN_TRP. • DIVBYZERO: Divide by Zero Usage Fault This is part of “UFSR: Usage Fault Status Subregister” . 0: No divide by zero fault, or divide by zero trapping not enabled. 1: The processor has executed an SDIV or UDIV instruction with a divisor of 0. When the processor sets this bit to 1, the PC value stacked for the exception return points to the instruction that performed the divide by zero. Enable trapping of divide by zero by setting the DIV_0_TRP bit in the SCB_CCR register to 1. See “Configuration and Control Register” . SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 221 11.9.1.14 Configurable Fault Status Register (Byte Access) Name: SCB_CFSR (BYTE) Access: Read-write Reset: 0x000000000 31 30 29 28 27 26 25 24 19 18 17 16 11 10 9 8 3 2 1 0 UFSR 23 22 21 20 UFSR 15 14 13 12 BFSR 7 6 5 4 MMFSR • MMFSR: Memory Management Fault Status Subregister The flags in the MMFSR subregister indicate the cause of memory access faults. See bitfield [7..0] description in Section 11.9.1.13. • BFSR: Bus Fault Status Subregister The flags in the BFSR subregister indicate the cause of a bus access fault. See bitfield [14..8] description in Section 11.9.1.13. • UFSR: Usage Fault Status Subregister The flags in the UFSR subregister indicate the cause of a usage fault. See bitfield [31..15] description in Section 11.9.1.13. Note: The UFSR bits are sticky. This means that as one or more fault occurs, the associated bits are set to 1. A bit that is set to 1 is cleared to 0 only by writing 1 to that bit, or by a reset. The SCB_CFSR register indicates the cause of a memory management fault, bus fault, or usage fault. It is byte accessible. The user can access the SCB_CFSR register or its subregisters as follows: 222 Access complete SCB_CFSR with a word access to 0xE000ED28 Access MMFSR with a byte access to 0xE000ED28 Access MMFSR and BFSR with a halfword access to 0xE000ED28 Access BFSR with a byte access to 0xE000ED29 Access UFSR with a halfword access to 0xE000ED2A. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.9.1.15 Hard Fault Status Register Name: SCB_HFSR Access: Read-write Reset: 0x000000000 31 DEBUGEVT 30 FORCED 29 23 22 21 28 27 26 25 24 19 18 17 16 11 10 9 8 3 2 1 VECTTBL 0 – – 20 – 15 14 13 12 – 7 6 5 4 – The HFSR register gives information about events that activate the hard fault handler. This register is read, write to clear. This means that bits in the register read normally, but writing 1 to any bit clears that bit to 0. • DEBUGEVT: Reserved for Debug Use When writing to the register, write 0 to this bit, otherwise the behavior is unpredictable. • FORCED: Forced Hard Fault It indicates a forced hard fault, generated by escalation of a fault with configurable priority that cannot be handles, either because of priority or because it is disabled: 0: No forced hard fault. 1: Forced hard fault. When this bit is set to 1, the hard fault handler must read the other fault status registers to find the cause of the fault. • VECTTBL: Bus Fault on a Vector Table It indicates a bus fault on a vector table read during an exception processing: 0: No bus fault on vector table read. 1: Bus fault on vector table read. This error is always handled by the hard fault handler. When this bit is set to 1, the PC value stacked for the exception return points to the instruction that was preempted by the exception. Note: The HFSR bits are sticky. This means that, as one or more fault occurs, the associated bits are set to 1. A bit that is set to 1 is cleared to 0 only by writing 1 to that bit, or by a reset. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 223 11.9.1.16 MemManage Fault Address Register Name: SCB_MMFAR Access: Read-write Reset: 0x000000000 31 30 29 28 27 26 25 24 19 18 17 16 11 10 9 8 3 2 1 0 ADDRESS 23 22 21 20 ADDRESS 15 14 13 12 ADDRESS 7 6 5 4 ADDRESS The MMFAR register contains the address of the location that generated a memory management fault. • ADDRESS When the MMARVALID bit of the MMFSR subregister is set to 1, this field holds the address of the location that generated the memory management fault. Notes: 224 1. When an unaligned access faults, the address is the actual address that faulted. Because a single read or write instruction can be split into multiple aligned accesses, the fault address can be any address in the range of the requested access size. 2. Flags in the MMFSR subregister indicate the cause of the fault, and whether the value in the SCB_MMFAR register is valid. See “MMFSR: Memory Management Fault Status Subregister” . SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.9.1.17 Bus Fault Address Register Name: SCB_BFAR Access: Read-write Reset: 0x000000000 31 30 29 28 27 26 25 24 19 18 17 16 11 10 9 8 3 2 1 0 ADDRESS 23 22 21 20 ADDRESS 15 14 13 12 ADDRESS 7 6 5 4 ADDRESS The BFAR register contains the address of the location that generated a bus fault. • ADDRESS When the BFARVALID bit of the BFSR subregister is set to 1, this field holds the address of the location that generated the bus fault. Notes: 1. When an unaligned access faults, the address in the SCB_BFAR register is the one requested by the instruction, even if it is not the address of the fault. 2. Flags in the BFSR indicate the cause of the fault, and whether the value in the SCB_BFAR register is valid. See “BFSR: Bus Fault Status Subregister” . SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 225 11.10 System Timer (SysTick) The processor has a 24-bit system timer, SysTick, that counts down from the reload value to zero, reloads (wraps to) the value in the SYST_RVR register on the next clock edge, then counts down on subsequent clocks. When the processor is halted for debugging, the counter does not decrement. The SysTick counter runs on the processor clock. If this clock signal is stopped for low power mode, the SysTick counter stops. Ensure that the software uses aligned word accesses to access the SysTick registers. The SysTick counter reload and current value are undefined at reset; the correct initialization sequence for the SysTick counter is: 1. Program the reload value. 2. Clear the current value. 3. Program the Control and Status register. 11.10.1 System Timer (SysTick) User Interface Table 11-34. System Timer (SYST) Register Mapping Offset Register Name Access Reset 0xE000E010 SysTick Control and Status Register SYST_CSR Read-write 0x00000004 0xE000E014 SysTick Reload Value Register SYST_RVR Read-write Unknown 0xE000E018 SysTick Current Value Register SYST_CVR Read-write Unknown 0xE000E01C SysTick Calibration Value Register SYST_CALIB Read-only 0xC0000000 226 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.10.1.1 SysTick Control and Status Name: SYST_CSR Access: Read-write Reset: 0x000000000 31 30 29 28 27 26 25 24 19 18 17 16 COUNTFLAG 11 10 9 8 3 2 CLKSOURCE 1 TICKINT 0 ENABLE – 23 22 21 20 – 15 14 13 12 – 7 6 5 4 The SysTick SYST_CSR register enables the SysTick features. • COUNTFLAG: Count Flag Returns 1 if the timer counted to 0 since the last time this was read. • CLKSOURCE: Clock Source Indicates the clock source: 0: External Clock. 1: Processor Clock. • TICKINT Enables a SysTick exception request: 0: Counting down to zero does not assert the SysTick exception request. 1: Counting down to zero asserts the SysTick exception request. The software can use COUNTFLAG to determine if SysTick has ever counted to zero. • ENABLE Enables the counter: 0: Counter disabled. 1: Counter enabled. When ENABLE is set to 1, the counter loads the RELOAD value from the SYST_RVR register and then counts down. On reaching 0, it sets the COUNTFLAG to 1 and optionally asserts the SysTick depending on the value of TICKINT. It then loads the RELOAD value again, and begins counting. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 227 11.10.1.2 SysTick Reload Value Registers Name: SYST_RVR Access: Read-write Reset: 0x000000000 31 30 29 28 27 26 25 24 19 18 17 16 11 10 9 8 3 2 1 0 – 23 22 21 20 RELOAD 15 14 13 12 RELOAD 7 6 5 4 RELOAD The SYST_RVR register specifies the start value to load into the SYST_CVR register. • RELOAD Value to load into the SYST_CVR register when the counter is enabled and when it reaches 0. The RELOAD value can be any value in the range 0x00000001-0x00FFFFFF. A start value of 0 is possible, but has no effect because the SysTick exception request and COUNTFLAG are activated when counting from 1 to 0. The RELOAD value is calculated according to its use: For example, to generate a multi-shot timer with a period of N processor clock cycles, use a RELOAD value of N-1. If the SysTick interrupt is required every 100 clock pulses, set RELOAD to 99. 228 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.10.1.3 SysTick Current Value Register Name: SYST_CVR Access: Read-write Reset: 0x000000000 31 30 29 28 27 26 25 24 19 18 17 16 11 10 9 8 3 2 1 0 – 23 22 21 20 CURRENT 15 14 13 12 CURRENT 7 6 5 4 CURRENT The SysTick SYST_CVR register contains the current value of the SysTick counter. • CURRENT Reads return the current value of the SysTick counter. A write of any value clears the field to 0, and also clears the SYST_CSR.COUNTFLAG bit to 0. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 229 11.10.1.4 SysTick Calibration Value Register Name: SYST_CALIB Access: Read-write Reset: 0x000000000 31 NOREF 30 SKEW 29 23 22 21 28 27 26 25 24 19 18 17 16 11 10 9 8 3 2 1 0 – 20 TENMS 15 14 13 12 TENMS 7 6 5 4 TENMS The SysTick SYST_CSR register indicates the SysTick calibration properties. • NOREF: No Reference Clock It indicates whether the device provides a reference clock to the processor: 0: Reference clock provided. 1: No reference clock provided. If your device does not provide a reference clock, the SYST_CSR.CLKSOURCE bit reads-as-one and ignores writes. • SKEW It indicates whether the TENMS value is exact: 0: TENMS value is exact. 1: TENMS value is inexact, or not given. An inexact TENMS value can affect the suitability of SysTick as a software real time clock. • TENMS: Ten Milliseconds The reload value for 10 ms (100 Hz) timing is subject to system clock skew errors. If the value reads as zero, the calibration value is not known. Read as 0x000030D4. The SysTick calibration value is fixed at 0x000030D4 (12500), which allows the generation of a time base of 1 ms with SysTick clock at 12.5 MHz (100/8 = 12.5 MHz). 230 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.11 Memory Protection Unit (MPU) The MPU divides the memory map into a number of regions, and defines the location, size, access permissions, and memory attributes of each region. It supports: Independent attribute settings for each region Overlapping regions Export of memory attributes to the system. The memory attributes affect the behavior of memory accesses to the region. The Cortex-M4 MPU defines: Eight separate memory regions, 0-7 A background region. When memory regions overlap, a memory access is affected by the attributes of the region with the highest number. For example, the attributes for region 7 take precedence over the attributes of any region that overlaps region 7. The background region has the same memory access attributes as the default memory map, but is accessible from privileged software only. The Cortex-M4 MPU memory map is unified. This means that instruction accesses and data accesses have the same region settings. If a program accesses a memory location that is prohibited by the MPU, the processor generates a memory management fault. This causes a fault exception, and might cause the termination of the process in an OS environment. In an OS environment, the kernel can update the MPU region setting dynamically based on the process to be executed. Typically, an embedded OS uses the MPU for memory protection. The configuration of MPU regions is based on memory types (see “Memory Regions, Types and Attributes” ). Table 11-35 shows the possible MPU region attributes. These include Share ability and cache behavior attributes that are not relevant to most microcontroller implementations. See “MPU Configuration for a Microcontroller” for guidelines for programming such an implementation. Table 11-35. Memory Attributes Summary Memory Type Shareability Other Attributes Description Strongly- ordered - - All accesses to Strongly-ordered memory occur in program order. All Strongly-ordered regions are assumed to be shared. Shared - Memory-mapped peripherals that several processors share. Non-shared - Memory-mapped peripherals that only a single processor uses. Device Shared Normal memory that is shared between several processors. Non-shared Normal memory that only a single processor uses. Normal SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 231 11.11.1 MPU Access Permission Attributes This section describes the MPU access permission attributes. The access permission bits (TEX, C, B, S, AP, and XN) of the MPU_RASR control the access to the corresponding memory region. If an access is made to an area of memory without the required permissions, then the MPU generates a permission fault. The table below shows the encodings for the TEX, C, B, and S access permission bits. Table 11-36. TEX TEX, C, B, and S Encoding C B S Memory Type Shareability Other Attributes 0 0 x (1) Stronglyordered Shareable - 1 x (1) Device Shareable - Normal Not shareable 0 0 b000 1 Outer and inner write-through. No write allocate. Shareable 1 0 1 0 Normal 1 Shareable 0 Not shareable 0 Normal 1 x 0 x (1) 1 Reserved encoding - Implementation defined attributes. - 0 1 Normal 1 1 b1B B 1. Not shareable x (1) Device 1 x (1) Reserved encoding - (1) Reserved encoding - x (1) x A Normal 1 Note: Outer and inner write-back. Write and read allocate. 0 0 A Not shareable Shareable 0 b010 Outer and inner write-back. No write allocate. Shareable (1) 1 b001 Not shareable Nonshared Device. Not shareable Shareable The MPU ignores the value of this bit. Table 11-37 shows the cache policy for memory attribute encodings with a TEX value is in the range 4-7. Table 11-37. 232 Cache Policy for Memory Attribute Encoding Encoding, AA or BB Corresponding Cache Policy 00 Non-cacheable 01 Write back, write and read allocate 10 Write through, no write allocate 11 Write back, no write allocate SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Table 11-38 shows the AP encodings that define the access permissions for privileged and unprivileged software. Table 11-38. AP Encoding AP[2:0] Privileged Permissions Unprivileged Permissions Description 000 No access No access All accesses generate a permission fault 001 RW No access Access from privileged software only 010 RW RO Writes by unprivileged software generate a permission fault 011 RW RW Full access 100 Unpredictable Unpredictable Reserved 101 RO No access Reads by privileged software only 110 RO RO Read only, by privileged or unprivileged software 111 RO RO Read only, by privileged or unprivileged software 11.11.1.1 MPU Mismatch When an access violates the MPU permissions, the processor generates a memory management fault, see “Exceptions and Interrupts” . The MMFSR indicates the cause of the fault. See “MMFSR: Memory Management Fault Status Subregister” for more information. 11.11.1.2 Updating an MPU Region To update the attributes for an MPU region, update the MPU_RNR, MPU_RBAR and MPU_RASR registers. Each register can be programed separately, or a multiple-word write can be used to program all of these registers. MPU_RBAR and MPU_RASR aliases can be used to program up to four regions simultaneously using an STM instruction. 11.11.1.3 Updating an MPU Region Using Separate Words Simple code to configure one region: ; R1 = region number ; R2 = size/enable ; R3 = attributes ; R4 = address LDR R0,=MPU_RNR STR R1, [R0, #0x0] STR R4, [R0, #0x4] STRH R2, [R0, #0x8] STRH R3, [R0, #0xA] ; ; ; ; ; 0xE000ED98, MPU region number register Region Number Region Base Address Region Size and Enable Region Attribute Disable a region before writing new region settings to the MPU, if the region being changed was previously enabled. For example: ; R1 = region number ; R2 = size/enable ; R3 = attributes ; R4 = address LDR R0,=MPU_RNR ; 0xE000ED98, MPU region number register STR R1, [R0, #0x0] ; Region Number BIC R2, R2, #1 ; Disable STRH R2, [R0, #0x8] ; Region Size and Enable STR R4, [R0, #0x4] ; Region Base Address STRH R3, [R0, #0xA] ; Region Attribute ORR R2, #1 ; Enable STRH R2, [R0, #0x8] ; Region Size and Enable SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 233 The software must use memory barrier instructions: Before the MPU setup, if there might be outstanding memory transfers, such as buffered writes, that might be affected by the change in MPU settings After the MPU setup, if it includes memory transfers that must use the new MPU settings. However, memory barrier instructions are not required if the MPU setup process starts by entering an exception handler, or is followed by an exception return, because the exception entry and exception return mechanisms cause memory barrier behavior. The software does not need any memory barrier instructions during an MPU setup, because it accesses the MPU through the PPB, which is a Strongly-Ordered memory region. For example, if the user wants all of the memory access behavior to take effect immediately after the programming sequence, a DSB instruction and an ISB instruction must be used. A DSB is required after changing MPU settings, such as at the end of a context switch. An ISB is required if the code that programs the MPU region or regions is entered using a branch or call. If the programming sequence is entered using a return from exception, or by taking an exception, then an ISB is not required. 11.11.1.4 Updating an MPU Region Using Multi-word Writes The user can program directly using multi-word writes, depending on how the information is divided. Consider the following reprogramming: ; R1 = region number ; R2 = address ; R3 = size, attributes in one LDR R0, =MPU_RNR ; 0xE000ED98, MPU region number register STR R1, [R0, #0x0] ; Region Number STR R2, [R0, #0x4] ; Region Base Address STR R3, [R0, #0x8] ; Region Attribute, Size and Enable Use an STM instruction to optimize this: ; R1 = region number ; R2 = address ; R3 = size, attributes in one LDR R0, =MPU_RNR ; 0xE000ED98, MPU region number register STM R0, {R1-R3} ; Region Number, address, attribute, size and enable This can be done in two words for pre-packed information. This means that the MPU_RBAR contains the required region number and had the VALID bit set to 1. See “MPU Region Base Address Register” . Use this when the data is statically packed, for example in a boot loader: ; R1 = address and region number in one ; R2 = size and attributes in one LDR R0, =MPU_RBAR ; 0xE000ED9C, MPU Region Base register STR R1, [R0, #0x0] ; Region base address and ; region number combined with VALID (bit 4) set to 1 STR R2, [R0, #0x4] ; Region Attribute, Size and Enable Use an STM instruction to optimize this: ; R1 = address and region number in one ; R2 = size and attributes in one LDR R0,=MPU_RBAR ; 0xE000ED9C, MPU Region Base register STM R0, {R1-R2} ; Region base address, region number and VALID bit, ; and Region Attribute, Size and Enable 11.11.1.5 Subregions Regions of 256 bytes or more are divided into eight equal-sized subregions. Set the corresponding bit in the SRD field of the MPU_RASR field to disable a subregion. See “MPU Region Attribute and Size Register” . The least significant bit of SRD controls the first subregion, and the most significant bit controls the last subregion. Disabling 234 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 a subregion means another region overlapping the disabled range matches instead. If no other enabled region overlaps the disabled subregion, the MPU issues a fault. Regions of 32, 64, and 128 bytes do not support subregions. With regions of these sizes, the SRD field must be set to 0x00, otherwise the MPU behavior is unpredictable. 11.11.1.6 Example of SRD Use Two regions with the same base address overlap. Region 1 is 128 KB, and region 2 is 512 KB. To ensure the attributes from region 1 apply to the first 128 KB region, set the SRD field for region 2 to b00000011 to disable the first two subregions, as in Figure 11-14 below: Figure 11-14. SRD Use Region 2, with subregions Region 1 Base address of both regions Offset from base address 512KB 448KB 384KB 320KB 256KB 192KB 128KB Disabled subregion 64KB Disabled subregion 0 11.11.1.7 MPU Design Hints And Tips To avoid unexpected behavior, disable the interrupts before updating the attributes of a region that the interrupt handlers might access. Ensure the software uses aligned accesses of the correct size to access MPU registers: Except for the MPU_RASR register, it must use aligned word accesses For the MPU_RASR register, it can use byte or aligned halfword or word accesses. The processor does not support unaligned accesses to MPU registers. When setting up the MPU, and if the MPU has previously been programmed, disable unused regions to prevent any previous region settings from affecting the new MPU setup. MPU Configuration for a Microcontroller Usually, a microcontroller system has only a single processor and no caches. In such a system, program the MPU as follows: Table 11-39. Memory Region Attributes for a Microcontroller Memory Region TEX C B S Memory Type and Attributes Flash memory b000 1 0 0 Normal memory, non-shareable, write-through Internal SRAM b000 1 0 1 Normal memory, shareable, write-through External SRAM b000 1 1 1 Normal memory, shareable, write-back, write-allocate Peripherals b000 0 1 1 Device memory, shareable In most microcontroller implementations, the shareability and cache policy attributes do not affect the system behavior. However, using these settings for the MPU regions can make the application code more portable. The values given are for typical situations. In special systems, such as multiprocessor designs or designs with a separate DMA engine, the shareability attribute might be important. In these cases, refer to the recommendations of the memory device manufacturer. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 235 11.11.2 Memory Protection Unit (MPU) User Interface Table 11-40. Memory Protection Unit (MPU) Register Mapping Offset Register Name Access Reset 0xE000ED90 MPU Type Register MPU_TYPE Read-only 0x00000800 0xE000ED94 MPU Control Register MPU_CTRL Read-write 0x00000000 0xE000ED98 MPU Region Number Register MPU_RNR Read-write 0x00000000 0xE000ED9C MPU Region Base Address Register MPU_RBAR Read-write 0x00000000 0xE000EDA0 MPU Region Attribute and Size Register MPU_RASR Read-write 0x00000000 0xE000EDA4 Alias of RBAR, see MPU Region Base Address Register MPU_RBAR_A1 Read-write 0x00000000 0xE000EDA8 Alias of RASR, see MPU Region Attribute and Size Register MPU_RASR_A1 Read-write 0x00000000 0xE000EDAC Alias of RBAR, see MPU Region Base Address Register MPU_RBAR_A2 Read-write 0x00000000 0xE000EDB0 Alias of RASR, see MPU Region Attribute and Size Register MPU_RASR_A2 Read-write 0x00000000 0xE000EDB4 Alias of RBAR, see MPU Region Base Address Register MPU_RBAR_A3 Read-write 0x00000000 0xE000EDB8 Alias of RASR, see MPU Region Attribute and Size Register MPU_RASR_A3 Read-write 0x00000000 236 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.11.2.1 MPU Type Register Name: MPU_TYPE Access: Read-write Reset: 0x00000800 31 30 29 28 27 26 25 24 19 18 17 16 11 10 9 8 3 2 1 0 SEPARATE – 23 22 21 20 IREGION 15 14 13 12 DREGION 7 6 5 4 – The MPU_TYPE register indicates whether the MPU is present, and if so, how many regions it supports. • IREGION: Instruction Region Indicates the number of supported MPU instruction regions. Always contains 0x00. The MPU memory map is unified and is described by the DREGION field. • DREGION: Data Region Indicates the number of supported MPU data regions: 0x08 = Eight MPU regions. • SEPARATE: Separate Instruction Indicates support for unified or separate instruction and date memory maps: 0: Unified. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 237 11.11.2.2 MPU Control Register Name: MPU_CTRL Access: Read-write Reset: 0x00000800 31 30 29 28 27 26 25 24 19 18 17 16 11 10 9 8 3 2 PRIVDEFENA 1 HFNMIENA 0 ENABLE – 23 22 21 20 – 15 14 13 12 – 7 6 5 – 4 The MPU CTRL register enables the MPU, enables the default memory map background region, and enables the use of the MPU when in the hard fault, Non-maskable Interrupt (NMI), and FAULTMASK escalated handlers. • PRIVDEFENA: Privileged Default Memory Map Enabled Enables privileged software access to the default memory map: 0: If the MPU is enabled, disables the use of the default memory map. Any memory access to a location not covered by any enabled region causes a fault. 1: If the MPU is enabled, enables the use of the default memory map as a background region for privileged software accesses. When enabled, the background region acts as a region number -1. Any region that is defined and enabled has priority over this default map. If the MPU is disabled, the processor ignores this bit. • HFNMIENA: Hard Fault and NMI Enabled Enables the operation of MPU during hard fault, NMI, and FAULTMASK handlers. When the MPU is enabled: 0: MPU is disabled during hard fault, NMI, and FAULTMASK handlers, regardless of the value of the ENABLE bit. 1: The MPU is enabled during hard fault, NMI, and FAULTMASK handlers. When the MPU is disabled, if this bit is set to 1, the behavior is unpredictable. • ENABLE Enables the MPU: 0: MPU disabled. 1: MPU enabled. When ENABLE and PRIVDEFENA are both set to 1: • For privileged accesses, the default memory map is as described in “Memory Model” . Any access by privileged software that does not address an enabled memory region behaves as defined by the default memory map. • Any access by unprivileged software that does not address an enabled memory region causes a memory management fault. 238 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 XN and Strongly-ordered rules always apply to the System Control Space regardless of the value of the ENABLE bit. When the ENABLE bit is set to 1, at least one region of the memory map must be enabled for the system to function unless the PRIVDEFENA bit is set to 1. If the PRIVDEFENA bit is set to 1 and no regions are enabled, then only privileged software can operate. When the ENABLE bit is set to 0, the system uses the default memory map. This has the same memory attributes as if the MPU is not implemented. The default memory map applies to accesses from both privileged and unprivileged software. When the MPU is enabled, accesses to the System Control Space and vector table are always permitted. Other areas are accessible based on regions and whether PRIVDEFENA is set to 1. Unless HFNMIENA is set to 1, the MPU is not enabled when the processor is executing the handler for an exception with priority –1 or –2. These priorities are only possible when handling a hard fault or NMI exception, or when FAULTMASK is enabled. Setting the HFNMIENA bit to 1 enables the MPU when operating with these two priorities. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 239 11.11.2.3 MPU Region Number Register Name: MPU_RNR Access: Read-write Reset: 0x00000800 31 30 29 28 27 26 25 24 19 18 17 16 11 10 9 8 3 2 1 0 – 23 22 21 20 – 15 14 13 12 – 7 6 5 4 REGION The MPU_RNR selects which memory region is referenced by the MPU_RBAR and MPU_RASR registers. • REGION Indicates the MPU region referenced by the MPU_RBAR and MPU_RASR registers. The MPU supports 8 memory regions, so the permitted values of this field are 0-7. Normally, the required region number is written to this register before accessing the MPU_RBAR or MPU_RASR. However, the region number can be changed by writing to the MPU_RBAR with the VALID bit set to 1; see “MPU Region Base Address Register” . This write updates the value of the REGION field. 240 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 11.11.2.4 MPU Region Base Address Register Name: MPU_RBAR Access: Read-write Reset: 0x00000000 31 30 29 28 27 26 25 24 19 18 17 16 11 10 9 N 3 2 1 0 ADDR 23 22 21 20 ADDR 15 14 13 12 ADDR N-1 6 – 5 4 VALID REGION Note: If the region size is 32B, the ADDR field is bits [31:5] and there is no Reserved field. The MPU_RBAR defines the base address of the MPU region selected by the MPU_RNR, and can update the value of the MPU_RNR. Write MPU_RBAR with the VALID bit set to 1 to change the current region number and update the MPU_RNR. • ADDR: Region Base Address The value of N depends on the region size. The ADDR field is bits[31:N] of the MPU_RBAR. The region size, as specified by the SIZE field in the MPU_RASR, defines the value of N: N = Log2(Region size in bytes), If the region size is configured to 4 GB, in the MPU_RASR, there is no valid ADDR field. In this case, the region occupies the complete memory map, and the base address is 0x00000000. The base address is aligned to the size of the region. For example, a 64 KB region must be aligned on a multiple of 64 KB, for example, at 0x00010000 or 0x00020000. • VALID: MPU Region Number Valid Write: 0: MPU_RNR not changed, and the processor updates the base address for the region specified in the MPU_RNR, and ignores the value of the REGION field. 1: The processor updates the value of the MPU_RNR to the value of the REGION field, and updates the base address for the region specified in the REGION field. Always reads as zero. • REGION: MPU Region For the behavior on writes, see the description of the VALID field. On reads, returns the current region number, as specified by the MPU_RNR. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 241 11.11.2.5 MPU Region Attribute and Size Register Name: MPU_RASR Access: Read-write Reset: 0x00000000 31 23 30 – 29 28 XN 27 – 26 25 AP 24 22 21 20 TEX 19 18 S 17 C 16 B 14 13 12 11 10 9 8 3 SIZE 2 1 0 ENABLE – 15 SRD 7 6 5 4 – The MPU_RASR defines the region size and memory attributes of the MPU region specified by the MPU_RNR, and enables that region and any subregions. MPU_RASR is accessible using word or halfword accesses: The most significant halfword holds the region attributes. The least significant halfword holds the region size, and the region and subregion enable bits. • XN: Instruction Access Disable 0: Instruction fetches enabled. 1: Instruction fetches disabled. • AP: Access Permission See Table 11-38. • TEX, C, B: Memory Access Attributes See Table 11-36. • S: Shareable See Table 11-36. • SRD: Subregion Disable For each bit in this field: 0: Corresponding sub-region is enabled. 1: Corresponding sub-region is disabled. See “Subregions” for more information. Region sizes of 128 bytes and less do not support subregions. When writing the attributes for such a region, write the SRD field as 0x00. 242 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 • SIZE: Size of the MPU Protection Region The minimum permitted value is 3 (b00010). The SIZE field defines the size of the MPU memory region specified by the MPU_RNR. as follows: (Region size in bytes) = 2(SIZE+1) The smallest permitted region size is 32B, corresponding to a SIZE value of 4. The table below gives an example of SIZE values, with the corresponding region size and value of N in the MPU_RBAR. SIZE Value Region Size Value of N (1) Note b00100 (4) 32 B 5 Minimum permitted size b01001 (9) 1 KB 10 - b10011 (19) 1 MB 20 - b11101 (29) 1 GB 30 - b11111 (31) 4 GB b01100 Maximum possible size Note: 1. In the MPU_RBAR, see “MPU Region Base Address Register” • ENABLE: Region Enable Note: For information about access permission, see “MPU Access Permission Attributes” . SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 243 11.12 Glossary This glossary describes some of the terms used in technical documents from ARM. Abort A mechanism that indicates to a processor that the value associated with a memory access is invalid. An abort can be caused by the external or internal memory system as a result of attempting to access invalid instruction or data memory. Aligned A data item stored at an address that is divisible by the number of bytes that defines the data size is said to be aligned. Aligned words and halfwords have addresses that are divisible by four and two respectively. The terms word-aligned and halfword-aligned therefore stipulate addresses that are divisible by four and two respectively. Banked register Base register A register that has multiple physical copies, where the state of the processor determines which copy is used. The Stack Pointer, SP (R13) is a banked register. In instruction descriptions, a register specified by a load or store instruction that is used to hold the base value for the instruction’s address calculation. Depending on the instruction and its addressing mode, an offset can be added to or subtracted from the base register value to form the address that is sent to memory. See also “Index register” Big-endian (BE) Byte ordering scheme in which bytes of decreasing significance in a data word are stored at increasing addresses in memory. See also “Byte-invariant” , “Endianness” , “Little-endian (LE)” . Big-endian memory Memory in which: a byte or halfword at a word-aligned address is the most significant byte or halfword within the word at that address, a byte at a halfword-aligned address is the most significant byte within the halfword at that address. See also “Little-endian memory” . Breakpoint A breakpoint is a mechanism provided by debuggers to identify an instruction at which program execution is to be halted. Breakpoints are inserted by the programmer to enable inspection of register contents, memory locations, variable values at fixed points in the program execution to test that the program is operating correctly. Breakpoints are removed after the program is successfully tested. 244 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Byte-invariant In a byte-invariant system, the address of each byte of memory remains unchanged when switching between little-endian and big-endian operation. When a data item larger than a byte is loaded from or stored to memory, the bytes making up that data item are arranged into the correct order depending on the endianness of the memory access. An ARM byte-invariant implementation also supports unaligned halfword and word memory accesses. It expects multi-word accesses to be word-aligned. Condition field A four-bit field in an instruction that specifies a condition under which the instruction can execute. Conditional execution If the condition code flags indicate that the corresponding condition is true when the instruction starts executing, it executes normally. Otherwise, the instruction does nothing. Context The environment that each process operates in for a multitasking operating system. In ARM processors, this is limited to mean the physical address range that it can access in memory and the associated memory access permissions. Coprocessor A processor that supplements the main processor. Cortex-M4 does not support any coprocessors. Debugger A debugging system that includes a program, used to detect, locate, and correct software faults, together with custom hardware that supports software debugging. Direct Memory Access (DMA) An operation that accesses main memory directly, without the processor performing any accesses to the data concerned. Doubleword A 64-bit data item. The contents are taken as being an unsigned integer unless otherwise stated. Doubleword-aligned A data item having a memory address that is divisible by eight. Endianness Byte ordering. The scheme that determines the order that successive bytes of a data word are stored in memory. An aspect of the system’s memory mapping. See also “Little-endian (LE)” and “Big-endian (BE)” Exception An event that interrupts program execution. When an exception occurs, the processor suspends the normal program flow and starts execution at the address indicated by the corresponding exception vector. The indicated address contains the first instruction of the handler for the exception. An exception can be an interrupt request, a fault, or a software-generated system exception. Faults include attempting an invalid memory access, attempting to execute an instruction in an invalid processor state, and attempting to execute an undefined instruction. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 245 Exception service routine See “Interrupt handler” . Exception vector See “Interrupt vector” . Flat address mapping A system of organizing memory in which each physical address in the memory space is the same as the corresponding virtual address. Halfword A 16-bit data item. Illegal instruction An instruction that is architecturally Undefined. Implementation-defined The behavior is not architecturally defined, but is defined and documented by individual implementations. Implementation-specific The behavior is not architecturally defined, and does not have to be documented by individual implementations. Used when there are a number of implementation options available and the option chosen does not affect software compatibility. Index register In some load and store instruction descriptions, the value of this register is used as an offset to be added to or subtracted from the base register value to form the address that is sent to memory. Some addressing modes optionally enable the index register value to be shifted prior to the addition or subtraction. See also “Base register” . Instruction cycle count The number of cycles that an instruction occupies the Execute stage of the pipeline. Interrupt handler A program that control of the processor is passed to when an interrupt occurs. Interrupt vector One of a number of fixed addresses in low memory, or in high memory if high vectors are configured, that contains the first instruction of the corresponding interrupt handler. Little-endian (LE) Byte ordering scheme in which bytes of increasing significance in a data word are stored at increasing addresses in memory. See also “Big-endian (BE)” , “Byte-invariant” , “Endianness” . 246 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Little-endian memory Memory in which: a byte or halfword at a word-aligned address is the least significant byte or halfword within the word at that address, a byte at a halfword-aligned address is the least significant byte within the halfword at that address. See also “Big-endian memory” . Load/store architecture A processor architecture where data-processing operations only operate on register contents, not directly on memory contents. Memory Protection Unit (MPU) Hardware that controls access permissions to blocks of memory. An MPU does not perform any address translation. Prefetching In pipelined processors, the process of fetching instructions from memory to fill up the pipeline before the preceding instructions have finished executing. Prefetching an instruction does not mean that the instruction has to be executed. Preserved Preserved by writing the same value back that has been previously read from the same field on the same processor. Read Reads are defined as memory operations that have the semantics of a load. Reads include the Thumb instructions LDM, LDR, LDRSH, LDRH, LDRSB, LDRB, and POP. Region A partition of memory space. Reserved A field in a control register or instruction format is reserved if the field is to be defined by the implementation, or produces Unpredictable results if the contents of the field are not zero. These fields are reserved for use in future extensions of the architecture or are implementation-specific. All reserved bits not used by the implementation must be written as 0 and read as 0. Thread-safe In a multi-tasking environment, thread-safe functions use safeguard mechanisms when accessing shared resources, to ensure correct operation without the risk of shared access conflicts. Thumb instruction One or two halfwords that specify an operation for a processor to perform. Thumb instructions must be halfword-aligned. Unaligned A data item stored at an address that is not divisible by the number of bytes that defines the data size is said to be unaligned. For example, a word stored at an address that is not divisible by four. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 247 Undefined Indicates an instruction that generates an Undefined instruction exception. Unpredictable One cannot rely on the behavior. Unpredictable behavior must not represent security holes. Unpredictable behavior must not halt or hang the processor, or any parts of the system. Warm reset Also known as a core reset. Initializes the majority of the processor excluding the debug controller and debug logic. This type of reset is useful if debugging features of a processor. Word A 32-bit data item. Write Writes are defined as operations that have the semantics of a store. Writes include the Thumb instructions STM, STR, STRH, STRB, and PUSH. 248 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 12. Debug and Test Features 12.1 Description The SAM4N Series microcontrollers feature a number of complementary debug and test capabilities. The Serial Wire/JTAG Debug Port (SWJ-DP) combining a Serial Wire Debug Port (SW-DP) and JTAG Debug Port (JTAGDP) is used for standard debugging functions, such as downloading code and single-stepping through programs. It also embeds a serial wire trace. 12.2 Embedded Characteristics Debug access to all memories and registers in the system, including Cortex-M4 register bank when the core is running, halted, or held in reset Serial Wire Debug Port (SW-DP) and Serial Wire JTAG Debug Port (SWJ-DP) debug access Flash Patch and Breakpoint (FPB) unit for implementing breakpoints and code patches Data Watchpoint and Trace (DWT) unit for implementing watchpoints, data tracing, and system profiling Instrumentation Trace Macrocell (ITM) for support of printf style debugging IEEE1149.1 JTAG Boundary-scan on all digital pins Figure 12-1. Debug and Test Block Diagram TMS TCK/SWCLK TDI Boundary TAP JTAGSEL SWJ-DP TDO/TRACESWO Reset and Test POR TST SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 249 12.3 Application Examples 12.3.1 Debug Environment Figure 12-2 shows a complete debug environment example. The SWJ-DP interface is used for standard debugging functions, such as downloading code and single-stepping through the program, and viewing core and peripheral registers. Figure 12-2. Application Debug Environment Example Host Debugger PC SWJ-DP Emulator/Probe SWJ-DP Connector SAM4 SAM4-based Application Board 12.3.2 Test Environment Figure 12-3 shows a test environment example (JTAG boundary scan). Test vectors are sent and interpreted by the tester. In this example, the “board in test” is designed using a number of JTAG-compliant devices. These devices can be connected to form a single scan chain. 250 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Figure 12-3. Application Test Environment Example Test Adaptor Tester JTAG Probe JTAG Connector Chip n SAM4 Chip 2 Chip 1 SAM4-based Application Board In Test 12.4 Debug and Test Pin Description Table 12-1. Debug and Test Signal List Signal Name Function Type Active Level Input/Output Low Reset/Test NRST Microcontroller Reset TST Test Select Input SWD/JTAG TCK/SWCLK Test Clock/Serial Wire Clock Input TDI Test Data In Input TDO/TRACESWO Test Data Out/Trace Asynchronous Data Out TMS/SWDIO Test Mode Select/Serial Wire Input/Output Input JTAGSEL JTAG Selection Input Note: 1. Output (1) High TDO pin is set in input mode when the Cortex-M4 Core is not in debug mode. Thus the internal pull-up corresponding to this PIO line must be enabled to avoid current consumption due to floating input. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 251 12.5 Functional Description 12.5.1 Test Pin One dedicated pin, TST, is used to define the device operating mode. When this pin is at low level during powerup, the device is in normal operating mode. When at high level, the device is in test mode or FFPI mode. The TST pin integrates a permanent pull-down resistor of about 15 kΩ, so that it can be left unconnected for normal operation. Note that when setting the TST pin to low or high level at power up, it must remain in the same state during the duration of the whole operation. 12.5.2 Debug Architecture Figure 12-4 shows the Debug Architecture used in the SAM4. The Cortex-M4 embeds five functional units for debug: SWJ-DP (Serial Wire/JTAG Debug Port) FPB (Flash Patch Breakpoint DWT (Data Watchpoint and Trace) ITM (Instrumentation Trace Macrocell) TPIU (Trace Port Interface Unit) The debug architecture information that follows is mainly dedicated to developers of SWJ-DP emulators/probes and debugging tool vendors for Cortex M4-based microcontrollers. For further details on SWJ-DP see the Cortex M4 technical reference manual. Figure 12-4. Debug Architecture DWT 4 watchpoints FPB SWJ-DP PC sampler 6 breakpoints data address sampler SWD/JTAG data sampler ITM software trace 32 channels interrupt trace time stamping CPU statistics 252 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 SWO trace TPIU 12.5.3 Serial Wire/JTAG Debug Port (SWJ-DP) The Cortex-M4 embeds a SWJ-DP debug port which is the standard CoreSight™ debug port. It combines Serial Wire Debug Port (SW-DP), from 2 to 3 pins and JTAG Debug Port(JTAG-DP), 5 pins. By default, the JTAG Debug Port is active. If the host debugger wants to switch to the Serial Wire Debug Port, it must provide a dedicated JTAG sequence on TMS/SWDIO and TCK/SWCLK which disables JTAG-DP and enables SW-DP. When the Serial Wire Debug Port is active, TDO/TRACESWO can be used for trace. The asynchronous TRACE output (TRACESWO) is multiplexed with TDO. The asynchronous trace can only be used with SW-DP, not JTAGDP. Table 12-2. SWJ-DP Pin List Pin Name JTAG Port Serial Wire Debug Port TMS/SWDIO TMS SWDIO TCK/SWCLK TCK SWCLK TDI TDI – TDO/TRACESWO TDO TRACESWO (optional: trace) SW-DP or JTAG-DP mode is selected when JTAGSEL is low. It is not possible to switch directly between SWJ-DP and JTAG boundary scan operations. A chip reset must be performed after JTAGSEL is changed. 12.5.3.1 SW-DP and JTAG-DP Selection Mechanism Debug port selection mechanism is done by sending specific SWDIOTMS sequence. The JTAG-DP is selected by default after reset. Switch from JTAG-DP to SW-DP. The sequence is: ̶ Send more than 50 SWCLKTCK cycles with SWDIOTMS = 1 ̶ Send the 16-bit sequence on SWDIOTMS = 0111100111100111 (0x79E7 MSB first) ̶ Send more than 50 SWCLKTCK cycles with SWDIOTMS = 1 Switch from SWD to JTAG. The sequence is: ̶ Send more than 50 SWCLKTCK cycles with SWDIOTMS = 1 ̶ Send the 16-bit sequence on SWDIOTMS = 0011110011100111 (0x3CE7 MSB first) ̶ Send more than 50 SWCLKTCK cycles with SWDIOTMS = 1 12.5.4 FPB (Flash Patch Breakpoint) The FPB: Implements hardware breakpoints. Patches code and data from code space to system space. The FPB unit contains: Two literal comparators for matching against literal loads from code space, and remapping to a corresponding area in system space. Six instruction comparators for matching against instruction fetches from code space and remapping to a corresponding area in system space. Alternatively, comparators can also be configured to generate a breakpoint instruction to the processor core on a match. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 253 12.5.5 DWT (Data Watchpoint and Trace) The DWT contains four comparators which can be configured to generate the following: PC sampling packets at set intervals PC or data watchpoint packets Watchpoint event to halt core The DWT contains counters for the items that follow: Clock cycle (CYCCNT) Folded instructions Load Store Unit (LSU) operations Sleep cycles CPI (all instruction cycles except for the first cycle) Interrupt overhead 12.5.6 ITM (Instrumentation Trace Macrocell) The ITM is an application driven trace source that supports printf style debugging to trace Operating System (OS) and application events, and emits diagnostic system information. The ITM emits trace information as packets which can be generated by three different sources with several priority levels: Software trace: Software can write directly to ITM stimulus registers. This can be done using the printf function. For more information, refer to Section 12.5.6.1 “How to Configure the ITM”. Hardware trace: The ITM emits packets generated by the DWT. Time stamping: Timestamps are emitted relative to packets. The ITM contains a 21-bit counter to generate the timestamp. 12.5.6.1 How to Configure the ITM The following example describes how to output trace data in asynchronous trace mode. Configure the TPIU for asynchronous trace mode (refer to Section 12.5.6.3 “How to Configure the TPIU”). Enable the write accesses into the ITM registers by writing “0xC5ACCE55” into the Lock Access Register (address: 0xE0000FB0). Write 0x00010015 into the Trace Control Register: ̶ Enable ITM. ̶ Enable synchronization packets. ̶ Enable SWO behavior. ̶ Fix the ATB ID to 1. Write 0x1 into the Trace Enable Register: ̶ Enable the stimulus port 0. Write 0x1 into the Trace Privilege Register: ̶ Write into the Stimulus Port 0 Register: TPIU (Trace Port Interface Unit). ̶ ̶ 254 Stimulus port 0 only accessed in privileged mode (clearing a bit in this register will result in the corresponding stimulus port being accessible in user mode). The TPIU acts as a bridge between the on-chip trace data and the Instruction Trace Macrocell (ITM). The TPIU formats and transmits trace data off-chip at frequencies asynchronous to the core. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 12.5.6.2 Asynchronous Mode The TPIU is configured in asynchronous mode, trace data are output using the single TRACESWO pin. The TRACESWO signal is multiplexed with the TDO signal of the JTAG Debug Port. As a consequence, asynchronous trace mode is only available when the serial wire debug mode is selected since TDO signal is used in JTAG debug mode. Two encoding formats are available for the single pin output: Manchester encoded stream. This is the reset value. NRZ-based UART byte structure 12.5.6.3 How to Configure the TPIU This example only concerns the asynchronous trace mode. Set the TRCENA bit to 1 into the Debug Exception and Monitor Register (0xE000EDFC) to enable the use of trace and debug blocks. Write 0x2 into the Selected Pin Protocol Register. ̶ Select the Serial Wire Output – NRZ. Write 0x100 into the Formatter and Flush Control Register. Set the suitable clock prescaler value into the Async Clock Prescaler Register to scale the baud rate of the asynchronous output (this can be done automatically by the debugging tool). 12.5.7 IEEE 1149.1 JTAG Boundary Scan IEEE 1149.1 JTAG Boundary Scan allows pin-level access independent of the device packaging technology. IEEE 1149.1 JTAG Boundary Scan is enabled when TST is tied to low, while JTAGSEL is high during power-up and must be kept in this state during the whole boundary scan operation. The SAMPLE, EXTEST and BYPASS functions are implemented. In SWD/JTAG debug mode, the ARM processor responds with a non-JTAG chip ID that identifies the processor. This is not IEEE 1149.1 JTAG-compliant. It is not possible to switch directly between JTAG Boundary Scan and SWJ Debug Port operations. A chip reset must be performed after JTAGSEL is changed. A Boundary-scan Descriptor Language (BSDL) file to set up the test is provided on www.atmel.com. 12.5.7.1 JTAG Boundary-scan Register The Boundary-scan Register (BSR) contains a number of bits which corresponds to active pins and associated control signals. Each SAM4 input/output pin corresponds to a 3-bit register in the BSR. The OUTPUT bit contains data that can be forced on the pad. The INPUT bit facilitates the observability of data applied to the pad. The CONTROL bit selects the direction of the pad. For more information, please refer to BSDL files available for the SAM4 Series. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 255 12.5.8 ID Code Register Access: Read-only 31 30 29 28 27 21 20 19 PART NUMBER VERSION 23 22 15 14 13 PART NUMBER 7 6 5 12 11 4 3 MANUFACTURER IDENTITY 26 25 PART NUMBER 24 18 16 17 10 9 MANUFACTURER IDENTITY 2 1 • VERSION[31:28]: Product Version Number Set to 0x0. • PART NUMBER[27:12]: Product Part Number Chip Name Chip ID SAM4N 0x05B2E • MANUFACTURER IDENTITY[11:1] Set to 0x01F. • Bit[0] Required by IEEE Std. 1149.1 Set to 0x1. Chip Name SAM4N 256 JTAG ID Code 0x05B3_603F SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 8 0 1 13. Reset Controller (RSTC) 13.1 Description The Reset Controller (RSTC), based on power-on reset cells, handles all the resets of the system without any external components. It reports which reset occurred last. The Reset Controller also drives independently or simultaneously the external reset and the peripheral and processor resets. 13.2 Embedded Characteristics Manages all Resets of the System, Including ̶ Processor Reset ̶ Peripheral Set Reset Based on Embedded Power-on Cell Reset Source Status 13.3 External Devices through the NRST Pin ̶ ̶ Status of the Last Reset ̶ Either Software Reset, User Reset, Watchdog Reset External Reset Signal Shaping Block Diagram Figure 13-1. Reset Controller Block Diagram Reset Controller core_backup_reset rstc_irq vddcore_nreset user_reset NRST nrst_out NRST Manager Reset State Manager proc_nreset periph_nreset exter_nreset WDRPROC wd_fault SLCK SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 257 13.4 Functional Description 13.4.1 Reset Controller Overview The Reset Controller is made up of an NRST Manager and a Reset State Manager. It runs at Slow Clock and generates the following reset signals: proc_nreset: Processor reset line. It also resets the Watchdog Timer periph_nreset: Affects the whole set of embedded peripherals nrst_out: Drives the NRST pin These reset signals are asserted by the Reset Controller, either on external events or on software action. The Reset State Manager controls the generation of reset signals and provides a signal to the NRST Manager when an assertion of the NRST pin is required. The NRST Manager shapes the NRST assertion during a programmable time, thus controlling external device resets. The Reset Controller Mode Register (RSTC_MR), allowing the configuration of the Reset Controller, is powered with VDDIO, so that its configuration is saved as long as VDDIO is on. 13.4.2 NRST Manager After power-up, NRST is an output during the ERSTL time period defined in the RSTC_MR. When ERSTL has elapsed, the pin behaves as an input and all the system is held in reset if NRST is tied to GND by an external signal. The NRST Manager samples the NRST input pin and drives this pin low when required by the Reset State Manager. Figure 13-2 shows the block diagram of the NRST Manager. Figure 13-2. NRST Manager RSTC_MR URSTIEN RSTC_SR URSTS NRSTL rstc_irq RSTC_MR URSTEN Other interrupt sources user_reset NRST RSTC_MR ERSTL nrst_out External Reset Timer exter_nreset 13.4.2.1 NRST Signal or Interrupt The NRST Manager samples the NRST pin at Slow Clock speed. When the line is detected low, a User Reset is reported to the Reset State Manager. However, the NRST Manager can be programmed to not trigger a reset when an assertion of NRST occurs. Writing the bit URSTEN at 0 in RSTC_MR disables the User Reset trigger. The level of the pin NRST can be read at any time in the bit NRSTL (NRST level) in RSTC_SR. As soon as the pin NRST is asserted, the bit URSTS in RSTC_SR is set. This bit clears only when RSTC_SR is read. The Reset Controller can also be programmed to generate an interrupt instead of generating a reset. To do so, the bit URSTIEN in RSTC_MR must be written at 1. 258 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 13.4.2.2 NRST External Reset Control The Reset State Manager asserts the signal ext_nreset to assert the NRST pin. When this occurs, the “nrst_out” signal is driven low by the NRST Manager for a time programmed by the field ERSTL in RSTC_MR. This assertion duration, named EXTERNAL_RESET_LENGTH, lasts 2(ERSTL+1) Slow Clock cycles. This gives the approximate duration of an assertion between 60 µs and 2 seconds. Note that ERSTL at 0 defines a two-cycle duration for the NRST pulse. This feature allows the Reset Controller to shape the NRST pin level, and thus to guarantee that the NRST line is driven low for a time compliant with potential external devices connected on the system reset. As the ERSTL field is within RSTC_MR register, which is backed-up, it can be used to shape the system power-up reset for devices requiring a longer startup time than the Slow Clock Oscillator. 13.4.3 Brownout Manager The Brownout manager is embedded within the Supply Controller, please refer to the product Supply Controller section for a detailed description. 13.4.4 Reset States The Reset State Manager handles the different reset sources and generates the internal reset signals. It reports the reset status in the field RSTTYP of the Status Register (RSTC_SR). The update of the field RSTTYP is performed when the processor reset is released. 13.4.4.1 General Reset A general reset occurs when a Power-on-reset is detected, a Brownout or a Voltage regulation loss is detected by the Supply controller. The vddcore_nreset signal is asserted by the Supply Controller when a general reset occurs. All the reset signals are released and the field RSTTYP in RSTC_SR reports a General Reset. As the RSTC_MR is reset, the NRST line rises 2 cycles after the vddcore_nreset, as ERSTL defaults at value 0x0. Figure 13-3 shows how the General Reset affects the reset signals. Figure 13-3. General Reset State SLCK Any Freq. MCK backup_nreset Processor Startup = 2 cycles proc_nreset RSTTYP XXX 0x0 = General Reset XXX periph_nreset NRST (nrst_out) EXTERNAL RESET LENGTH = 2 cycles SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 259 13.4.4.2 Backup Reset A Backup reset occurs when the chip returns from Backup Mode. The core_backup_reset signal is asserted by the Supply Controller when a Backup reset occurs. The field RSTTYP in RSTC_SR is updated to report a Backup Reset. 13.4.4.3 User Reset The User Reset is entered when a low level is detected on the NRST pin and the bit URSTEN in RSTC_MR is at 1. The NRST input signal is resynchronized with SLCK to insure proper behavior of the system. The User Reset is entered as soon as a low level is detected on NRST. The Processor Reset and the Peripheral Reset are asserted. The User Reset is left when NRST rises, after a two-cycle resynchronization time and a 3-cycle processor startup. The processor clock is re-enabled as soon as NRST is confirmed high. When the processor reset signal is released, the RSTTYP field of the Status Register (RSTC_SR) is loaded with the value 0x4, indicating a User Reset. The NRST Manager guarantees that the NRST line is asserted for EXTERNAL_RESET_LENGTH Slow Clock cycles, as programmed in the field ERSTL. However, if NRST does not rise after EXTERNAL_RESET_LENGTH because it is driven low externally, the internal reset lines remain asserted until NRST actually rises. Figure 13-4. User Reset State SLCK MCK Any Freq. NRST Resynch. 2 cycles Resynch. 2 cycles Processor Startup = 2 cycles proc_nreset RSTTYP Any XXX periph_nreset NRST (nrst_out) >= EXTERNAL RESET LENGTH 260 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 0x4 = User Reset 13.4.4.4 Software Reset The Reset Controller offers several commands used to assert the different reset signals. These commands are performed by writing the Control Register (RSTC_CR) with the following bits at 1: PROCRST: Writing PROCRST at 1 resets the processor and the watchdog timer PERRST: Writing PERRST at 1 resets all the embedded peripherals including the memory system, and, in particular, the Remap Command. The Peripheral Reset is generally used for debug purposes. Except for debug purposes, PERRST must always be used in conjunction with PROCRST (PERRST and PROCRST set both at 1 simultaneously). EXTRST: Writing EXTRST at 1 asserts low the NRST pin during a time defined by the field ERSTL in the Mode Register (RSTC_MR). The software reset is entered if at least one of these bits is set by the software. All these commands can be performed independently or simultaneously. The software reset lasts 3 Slow Clock cycles. The internal reset signals are asserted as soon as the register write is performed. This is detected on the Master Clock (MCK). They are released when the software reset is left, i.e.; synchronously to SLCK. If EXTRST is set, the nrst_out signal is asserted depending on the programming of the field ERSTL. However, the resulting falling edge on NRST does not lead to a User Reset. If and only if the PROCRST bit is set, the Reset Controller reports the software status in the field RSTTYP of the Status Register (RSTC_SR). Other Software Resets are not reported in RSTTYP. As soon as a software operation is detected, the bit SRCMP (Software Reset Command in Progress) is set in the Status Register (RSTC_SR). It is cleared as soon as the software reset is left. No other software reset can be performed while the SRCMP bit is set, and writing any value in RSTC_CR has no effect. Figure 13-5. Software Reset SLCK MCK Any Freq. Write RSTC_CR Resynch. Processor Startup 1 cycle = 2 cycles proc_nreset if PROCRST=1 RSTTYP Any XXX 0x3 = Software Reset periph_nreset if PERRST=1 NRST (nrst_out) if EXTRST=1 EXTERNAL RESET LENGTH 8 cycles (ERSTL=2) SRCMP in RSTC_SR SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 261 13.4.4.5 Watchdog Reset The Watchdog Reset is entered when a watchdog fault occurs. This state lasts 3 Slow Clock cycles. When in Watchdog Reset, assertion of the reset signals depends on the WDRPROC bit in WDT_MR: If WDRPROC is 0, the Processor Reset and the Peripheral Reset are asserted. The NRST line is also asserted, depending on the programming of the field ERSTL. However, the resulting low level on NRST does not result in a User Reset state. If WDRPROC = 1, only the processor reset is asserted. The Watchdog Timer is reset by the proc_nreset signal. As the watchdog fault always causes a processor reset if WDRSTEN is set, the Watchdog Timer is always reset after a Watchdog Reset, and the Watchdog is enabled by default and with a period set to a maximum. When the WDRSTEN in WDT_MR bit is reset, the watchdog fault has no impact on the reset controller. Figure 13-6. Watchdog Reset SLCK MCK Any Freq. wd_fault Processor Startup = 2 cycles proc_nreset RSTTYP Any XXX 0x2 = Watchdog Reset periph_nreset Only if WDRPROC = 0 NRST (nrst_out) EXTERNAL RESET LENGTH 8 cycles (ERSTL=2) 262 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 13.4.5 Reset State Priorities The Reset State Manager manages the following priorities between the different reset sources, given in descending order: General Reset Backup Reset Watchdog Reset Software Reset User Reset Particular cases are listed below: When in User Reset: ̶ ̶ A watchdog event is impossible because the Watchdog Timer is being reset by the proc_nreset signal. A software reset is impossible, since the processor reset is being activated. When in Software Reset: ̶ A watchdog event has priority over the current state. ̶ The NRST has no effect. When in Watchdog Reset: ̶ The processor reset is active and so a Software Reset cannot be programmed. ̶ A User Reset cannot be entered. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 263 13.4.6 Reset Controller Status Register The Reset Controller status register (RSTC_SR) provides several status fields: RSTTYP field: This field gives the type of the last reset, as explained in previous sections. SRCMP bit: This field indicates that a Software Reset Command is in progress and that no further software reset should be performed until the end of the current one. This bit is automatically cleared at the end of the current software reset. NRSTL bit: The NRSTL bit of the Status Register gives the level of the NRST pin sampled on each MCK rising edge. URSTS bit: A high-to-low transition of the NRST pin sets the URSTS bit of the RSTC_SR register. This transition is also detected on the Master Clock (MCK) rising edge (see Figure 13-7). If the User Reset is disabled (URSTEN = 0) and if the interruption is enabled by the URSTIEN bit in the RSTC_MR register, the URSTS bit triggers an interrupt. Reading the RSTC_SR status register resets the URSTS bit and clears the interrupt. Figure 13-7. Reset Controller Status and Interrupt MCK read RSTC_SR Peripheral Access 2 cycle resynchronization NRST NRSTL URSTS rstc_irq if (URSTEN = 0) and (URSTIEN = 1) 264 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 2 cycle resynchronization 13.5 Reset Controller (RSTC) User Interface Table 13-1. Register Mapping Offset Register Name Access Reset 0x00 Control Register RSTC_CR Write-only - 0x04 Status Register RSTC_SR Read-only 0x0000_0000 0x08 Mode Register RSTC_MR Read-write 0x0000 0001 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 265 13.5.1 Reset Controller Control Register Name: RSTC_CR Address: 0x400E1400 Access: Write-only 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 – 7 – 6 – 5 – 4 – 3 EXTRST 2 PERRST 1 – 0 PROCRST • PROCRST: Processor Reset 0 = No effect. 1 = If KEY is correct, resets the processor. • PERRST: Peripheral Reset 0 = No effect. 1 = If KEY is correct, resets the peripherals. • EXTRST: External Reset 0 = No effect. 1 = If KEY is correct, asserts the NRST pin and resets the processor and the peripherals. • KEY: System Reset Key 266 Value Name Description 0xA5 PASSWD Writing any other value in this field aborts the write operation. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 13.5.2 Reset Controller Status Register Name: RSTC_SR Address: 0x400E1404 Access: Read-only 31 – 30 – 29 – 28 – 27 – 26 – 25 – 24 – 23 – 22 – 21 – 20 – 19 – 18 – 17 SRCMP 16 NRSTL 15 – 14 – 13 – 12 – 11 – 10 9 RSTTYP 8 7 – 6 – 5 – 4 – 3 – 2 – 1 – 0 URSTS • URSTS: User Reset Status 0 = No high-to-low edge on NRST happened since the last read of RSTC_SR. 1 = At least one high-to-low transition of NRST has been detected since the last read of RSTC_SR. • RSTTYP: Reset Type Value Name Description 0 General Reset First power-up Reset 1 Backup Reset Return from Backup Mode 2 Watchdog Reset Watchdog fault occurred 3 Software Reset Processor reset required by the software 4 User Reset NRST pin detected low Reports the cause of the last processor reset. Reading this RSTC_SR does not reset this field. • NRSTL: NRST Pin Level Registers the NRST Pin Level at Master Clock (MCK). • SRCMP: Software Reset Command in Progress 0 = No software command is being performed by the reset controller. The reset controller is ready for a software command. 1 = A software reset command is being performed by the reset controller. The reset controller is busy. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 267 13.5.3 Reset Controller Mode Register Name: RSTC_MR Address: 0x400E1408 Access: Read-write 31 30 29 28 27 26 25 24 17 – 16 – 9 8 1 – 0 URSTEN KEY 23 – 22 – 21 – 20 – 19 – 18 – 15 – 14 – 13 – 12 – 11 10 7 – 6 – 5 4 URSTIEN 3 – ERSTL 2 – • URSTEN: User Reset Enable 0 = The detection of a low level on the pin NRST does not generate a User Reset. 1 = The detection of a low level on the pin NRST triggers a User Reset. • URSTIEN: User Reset Interrupt Enable 0 = USRTS bit in RSTC_SR at 1 has no effect on rstc_irq. 1 = USRTS bit in RSTC_SR at 1 asserts rstc_irq if URSTEN = 0. • ERSTL: External Reset Length This field defines the external reset length. The external reset is asserted during a time of 2(ERSTL+1) Slow Clock cycles. This allows assertion duration to be programmed between 60 µs and 2 seconds. • KEY: Write Access Password 268 Value Name 0xA5 PASSWD Description Writing any other value in this field aborts the write operation. Always reads as 0. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 14. Real-time Timer (RTT) 14.1 Description The Real-time Timer is built around a 32-bit counter used to count roll-over events of the programmable 16-bit prescaler which enables counting elapsed seconds from a 32 kHz slow clock source. It generates a periodic interrupt and/or triggers an alarm on a programmed value. It can be configured to be driven by the 1 Hz signal generated by the RTC, thus taking advantage of a calibrated 1 Hz clock. The slow clock source can be fully disabled to reduce power consumption when RTT is not required. 14.2 14.3 Embedded Characteristics 32-bit Free-running Counter on prescaled slow clock or RTC calibrated 1 Hz clock 16-bit Configurable Prescaler Interrupt on Alarm Block Diagram Figure 14-1. RTT_MR RTTDIS Real-time Timer RTT_MR RTT_MR RTTRST RTPRES RTT_MR reload 16-bit Divider SLCK RTTINCIEN set 0 RTT_MR RTC 1Hz RTTRST RTT_MR RTC1HZ 1 RTTINC RTT_SR 1 reset 0 rtt_int 0 32-bit Counter read RTT_SR RTT_MR ALMIEN RTT_VR reset CRTV RTT_SR ALMS set rtt_alarm = RTT_AR ALMV SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 269 14.4 Functional Description The Real-time Timer can be used to count elapsed seconds. It is built around a 32-bit counter fed by Slow Clock divided by a programmable 16-bit value. The value can be programmed in the field RTPRES of the Real-time Mode Register (RTT_MR). Programming RTPRES at 0x00008000 corresponds to feeding the real-time counter with a 1 Hz signal (if the Slow Clock is 32.768 kHz). The 32-bit counter can count up to 232 seconds, corresponding to more than 136 years, then roll over to 0. The real-time 32-bit counter can also be supplied by the RTC 1 Hz clock. This mode is interesting when the RTC 1Hz is calibrated (CORRECTION field of RTC_MR register differs from 0) in order to guaranty the synchronism between RTC and RTT counters. Setting the RTC 1HZ clock to 1 in RTT_MR register allows to drive the 32-bit RTT counter with the RTC 1Hz clock. In this mode, RTPRES field has no effect on 32-bit counter but RTTINC is still triggered by RTPRES. The Real-time Timer can also be used as a free-running timer with a lower time-base. The best accuracy is achieved by writing RTPRES to 3. Programming RTPRES to 1 or 2 is possible, but may result in losing status events because the status register is cleared two Slow Clock cycles after read. Thus if the RTT is configured to trigger an interrupt, the interrupt occurs during 2 Slow Clock cycles after reading RTT_SR. To prevent several executions of the interrupt handler, the interrupt must be disabled in the interrupt handler and re-enabled when the status register is clear. The Real-time Timer value (CRTV) can be read at any time in the register RTT_VR (Real-time Value Register). As this value can be updated asynchronously from the Master Clock, it is advisable to read this register twice at the same value to improve accuracy of the returned value. The current value of the counter is compared with the value written in the alarm register RTT_AR (Real-time Alarm Register). If the counter value matches the alarm, the bit ALMS in RTT_SR is set. The alarm register is set to its maximum value, corresponding to 0xFFFF_FFFF, after a reset. The alarm interrupt must be disabled (ALMIEN must be cleared in RTT_MR register) when writing a new ALMV value in Real-time Alarm Register. The bit RTTINC in RTT_SR is set each time there is a prescaler roll-over, so each time the Real-time Timer counter is incremented if RTC1HZ=0 else if RTC1HZ=1 the RTTINC bit can be triggered according to RTPRES value, in a fully independent way from the 32-bit counter increment. This bit can be used to start a periodic interrupt, the period being one second when the RTPRES is programmed with 0x8000 and Slow Clock equal to 32.768 Hz. The RTTINCIEN field must be cleared prior to write a new RTPRES value in RTT_MR register. Reading the RTT_SR status register resets the RTTINC and ALMS fields. Writing the bit RTTRST in RTT_MR immediately reloads and restarts the clock divider with the new programmed value. This also resets the 32-bit counter. When not used, the Real-time Timer can be disabled in order to suppress dynamic power consumption in this module. This can be achieved by setting the RTTDIS field to 1 in RTT_MR register. 270 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Figure 14-2. RTT Counting APB cycle APB cycle SCLK RTPRES - 1 Prescaler 0 RTT 0 ... ALMV-1 ALMV ALMV+1 ALMV+2 ALMV+3 RTTINC (RTT_SR) ALMS (RTT_SR) APB Interface read RTT_SR SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 271 14.5 Real-time Timer (RTT) User Interface Table 14-1. Register Mapping Offset Register Name Access Reset 0x00 Mode Register RTT_MR Read-write 0x0000_8000 0x04 Alarm Register RTT_AR Read-write 0xFFFF_FFFF 0x08 Value Register RTT_VR Read-only 0x0000_0000 0x0C Status Register RTT_SR Read-only 0x0000_0000 272 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 14.5.1 Real-time Timer Mode Register Name: RTT_MR Address: 0x400E1430 Access: Read-write 31 – 30 – 29 – 28 – 27 – 26 – 25 – 24 RTC1HZ 23 – 22 – 21 – 20 RTTDIS 19 – 18 RTTRST 17 RTTINCIEN 16 ALMIEN 15 14 13 12 11 10 9 8 3 2 1 0 RTPRES 7 6 5 4 RTPRES • RTPRES: Real-time Timer Prescaler Value Defines the number of SLCK periods required to increment the Real-time timer. RTPRES is defined as follows: RTPRES = 0: The prescaler period is equal to 216 * SCLK period. RTPRES ≠ 0: The prescaler period is equal to RTPRES * SCLK period. Note: The RTTINCIEN field must be cleared prior to write a new RTPRES value. • ALMIEN: Alarm Interrupt Enable 0 = The bit ALMS in RTT_SR has no effect on interrupt. 1 = The bit ALMS in RTT_SR asserts interrupt. • RTTINCIEN: Real-time Timer Increment Interrupt Enable 0 = The bit RTTINC in RTT_SR has no effect on interrupt. 1 = The bit RTTINC in RTT_SR asserts interrupt. • RTTRST: Real-time Timer Restart 0 = No effect. 1 = Reloads and restarts the clock divider with the new programmed value. This also resets the 32-bit counter. • RTTDIS: Real-time Timer Disable 0 = The real-time timer is enabled. 1 = The real-time timer is disabled (no dynamic power consumption). • RTC1HZ: Real-Time Clock 1Hz Clock Selection 0 = The RTT 32-bit counter is driven by the 16-bit prescaler roll-over events. 1 = The RTT 32-bit counter is driven by the RTC 1 Hz clock. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 273 14.5.2 Real-time Timer Alarm Register Name: RTT_AR Address: 0x400E1434 Access: Read-write 31 30 29 28 27 26 25 24 19 18 17 16 11 10 9 8 3 2 1 0 ALMV 23 22 21 20 ALMV 15 14 13 12 ALMV 7 6 5 4 ALMV • ALMV: Alarm Value Defines the alarm value (ALMV+1) compared with the Real-time Timer. Note: The alarm interrupt must be disabled (ALMIEN must be cleared in RTT_MR register) when writing a new ALMV value. 274 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 14.5.3 Real-time Timer Value Register Name: RTT_VR Address: 0x400E1438 Access: Read-only 31 30 29 28 27 26 25 24 19 18 17 16 11 10 9 8 3 2 1 0 CRTV 23 22 21 20 CRTV 15 14 13 12 CRTV 7 6 5 4 CRTV • CRTV: Current Real-time Value Returns the current value of the Real-time Timer. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 275 14.5.4 Real-time Timer Status Register Name: RTT_SR Address: 0x400E143C Access: Read-only 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 – 6 – 5 – 4 – 3 – 2 – 1 RTTINC 0 ALMS • ALMS: Real-time Alarm Status 0 = The Real-time Alarm has not occurred since the last read of RTT_SR. 1 = The Real-time Alarm occurred since the last read of RTT_SR. • RTTINC: Real-time Timer Increment 0 = The Real-time Timer has not been incremented since the last read of the RTT_SR. 1 = The Real-time Timer has been incremented since the last read of the RTT_SR. 276 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 15. Real-time Clock (RTC) 15.1 Description The Real-time Clock (RTC) peripheral is designed for very low power consumption. It combines a complete time-of-day clock with alarm and a two-hundred-year Gregorian or Persian calendar, complemented by a programmable periodic interrupt. The alarm and calendar registers are accessed by a 32-bit data bus. The time and calendar values are coded in binary-coded decimal (BCD) format. The time format can be 24-hour mode or 12-hour mode with an AM/PM indicator. Updating time and calendar fields and configuring the alarm fields are performed by a parallel capture on the 32-bit data bus. An entry control is performed to avoid loading registers with incompatible BCD format data or with an incompatible date according to the current month/year/century. A clock divider calibration circuitry enables to compensate crystal oscillator frequency inaccuracy. 15.2 Embedded Characteristics Ultra Low Power Consumption Full Asynchronous Design Gregorian Calendar up to 2099 or Persian Calendar Programmable Periodic Interrupt Safety/security features: ̶ Valid Time and Date Programmation Check ̶ On-The-Fly Time and Date Validity Check Crystal Oscillator Clock Calibration SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 277 15.3 Block Diagram Figure 15-1. RTC Block Diagram Slow Clock: SLCK 32768 Divider Time Date Clock Calibration APB 15.4 User Interface Entry Control Alarm Interrupt Control RTC Interrupt Product Dependencies 15.4.1 Power Management The Real-time Clock is continuously clocked at 32768 Hz. The Power Management Controller has no effect on RTC behavior. 15.4.2 Interrupt RTC interrupt line is connected on one of the internal sources of the interrupt controller. RTC interrupt requires the interrupt controller to be programmed first. 278 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 15.5 Functional Description The RTC provides a full binary-coded decimal (BCD) clock that includes century (19/20), year (with leap years), month, date, day, hours, minutes and seconds. The valid year range is 1900 to 2099 in Gregorian mode, a two-hundred-year calendar(or 1300 to 1499 in Persian mode). The RTC can operate in 24-hour mode or in 12-hour mode with an AM/PM indicator. Corrections for leap years are included (all years divisible by 4 being leap years). This is correct up to the year 2099. 15.5.1 Reference Clock The reference clock is Slow Clock (SLCK). It can be driven internally or by an external 32.768 kHz crystal. During low power modes of the processor, the oscillator runs and power consumption is critical. The crystal selection has to take into account the current consumption for power saving and the frequency drift due to temperature effect on the circuit for time accuracy. 15.5.2 Timing The RTC is updated in real time at one-second intervals in normal mode for the counters of seconds, at oneminute intervals for the counter of minutes and so on. Due to the asynchronous operation of the RTC with respect to the rest of the chip, to be certain that the value read in the RTC registers (century, year, month, date, day, hours, minutes, seconds) are valid and stable, it is necessary to read these registers twice. If the data is the same both times, then it is valid. Therefore, a minimum of two and a maximum of three accesses are required. 15.5.3 Alarm The RTC has five programmable fields: month, date, hours, minutes and seconds. Each of these fields can be enabled or disabled to match the alarm condition: If all the fields are enabled, an alarm flag is generated (the corresponding flag is asserted and an interrupt generated if enabled) at a given month, date, hour/minute/second. If only the “seconds” field is enabled, then an alarm is generated every minute. Depending on the combination of fields enabled, a large number of possibilities are available to the user ranging from minutes to 365/366 days. Hour, minute and second matching alarm (SECEN, MINEN, HOUREN) can be enabled independently of SEC, MIN, HOUR fields. Note: To change one of the SEC, MIN, HOUR, DATE, MONTH fields, it is recommended to disable the field before changing the value and re-enable it after the value has been changed. This requires up to 3 accesses to the RTC_TIMALR or RTC_CALALR registers. First access to only clear the enable corresponding to the field to change (SECEN, MINEN, HOUREN, DATEEN, MTHEN), this access is not required if the field is already cleared. The second access performs the change of the value (SEC, MIN, HOUR, DATE, MONTH). The third access is required to re-enable the field by writing 1 in SECEN, MINEN, HOUREN, DATEEN, MTHEN fields. 15.5.4 Error Checking when Programming Verification on user interface data is performed when accessing the century, year, month, date, day, hours, minutes, seconds and alarms. A check is performed on illegal BCD entries such as illegal date of the month with regard to the year and century configured. If one of the time fields is not correct, the data is not loaded into the register/counter and a flag is set in the validity register. The user can not reset this flag. It is reset as soon as an acceptable value is programmed. This avoids any further side effects in the hardware. The same procedure is done for the alarm. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 279 The following checks are performed: 1. Century (check if it is in range 19 - 20 or 13-14 in Persian mode) 2. Year (BCD entry check) 3. Date (check range 01 - 31) 4. Month (check if it is in BCD range 01 - 12, check validity regarding “date”) 5. Day (check range 1 - 7) 6. Hour (BCD checks: in 24-hour mode, check range 00 - 23 and check that AM/PM flag is not set if RTC is set in 24-hour mode; in 12-hour mode check range 01 - 12) 7. Minute (check BCD and range 00 - 59) 8. Second (check BCD and range 00 - 59) Note: If the 12-hour mode is selected by means of the RTC_MR register, a 12-hour value can be programmed and the returned value on RTC_TIMR will be the corresponding 24-hour value. The entry control checks the value of the AM/PM indicator (bit 22 of RTC_TIMR register) to determine the range to be checked. 15.5.5 RTC Internal Free Running Counter Error Checking To improve the reliability and security of the RTC, a permanent check is performed on the internal free running counters to report non-BCD or invalid date/time values. An error is reported by TDERR bit in the status register (RTC_SR) if an incorrect value has been detected. The flag can be cleared by programming the TDERRCLR in the RTC status clear control register (RTC_SCCR). Anyway the TDERR error flag will be set again if the source of the error has not been cleared before clearing the TDERR flag. The clearing of the source of such error can be done either by reprogramming a correct value on RTC_CALR and/or RTC_TIMR registers. The RTC internal free running counters may automatically clear the source of TDERR due to their roll-over (i.e. every 10 seconds for SECONDS[3:0] bitfield in RTC_TIMR register). In this case the TDERR is held high until a clear command is asserted by TDERRCLR bit in RTC_SCCR register. 15.5.6 Updating Time/Calendar To update any of the time/calendar fields, the user must first stop the RTC by setting the corresponding field in the Control Register. Bit UPDTIM must be set to update time fields (hour, minute, second) and bit UPDCAL must be set to update calendar fields (century, year, month, date, day). Then the user must poll or wait for the interrupt (if enabled) of bit ACKUPD in the Status Register. Once the bit reads 1, it is mandatory to clear this flag by writing the corresponding bit in RTC_SCCR. The user can now write to the appropriate Time and Calendar register. Once the update is finished, the user must reset (0) UPDTIM and/or UPDCAL in the Control When entering programming mode of the calendar fields, the time fields remain enabled. When entering the programming mode of the time fields, both time and calendar fields are stopped. This is due to the location of the calendar logic circuity (downstream for low-power considerations). It is highly recommended to prepare all the fields to be updated before entering programming mode. In successive update operations, the user must wait at least one second after resetting the UPDTIM/UPDCAL bit in the RTC_CR (Control Register) before setting these bits again. This is done by waiting for the SEC flag in the Status Register before setting UPDTIM/UPDCAL bit. After resetting UPDTIM/UPDCAL, the SEC flag must also be cleared. 280 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Figure 15-2. Update Sequence Begin Prepare TIme or Calendar Fields Set UPDTIM and/or UPDCAL bit(s) in RTC_CR Read RTC_SR Polling or IRQ (if enabled) ACKUPD =1? No Yes Clear ACKUPD bit in RTC_SCCR Update Time and/or Calendar values in RTC_TIMR/RTC_CALR Clear UPDTIM and/or UPDCAL bit in RTC_CR End SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 281 15.5.7 RTC Accurate Clock Calibration The crystal oscillator that drives the RTC may not be as accurate as expected mainly due to temperature variation. The RTC is equipped with circuitry able to correct slow clock crystal drift. To compensate for possible temperature variations over time, this accurate clock calibration circuitry can be programmed on-the-fly and also programmed during application manufacturing, in order to correct the crystal frequency accuracy at room temperature (20-25°C). The typical clock drift range at room temperature is ±20 ppm. In a temperature range of -40°C to +85°C, the 32.768 kHz crystal oscillator clock inaccuracy can be up to -200 ppm. The RTC clock calibration circuitry allows positive or negative correction in a range of 1.5 ppm to 1950 ppm. After correction, the remaining crystal drift is as follows: Below 1 ppm, for an initial crystal drift between 1.5 ppm up to 90 ppm Below 2 ppm, for an initial crystal drift between 90 ppm up to 130 ppm Below 5 ppm, for an initial crystal drift between 130 ppm up to 200 ppm The calibration circuitry acts by slightly modifying the 1 Hz clock period from time to time. When the period is modified, depending on the sign of the correction, the 1 Hz clock period increases or reduces by around 4 ms. The period interval between 2 correction events is programmable in order to cover the possible crystal oscillator clock variations. The inaccuracy of a crystal oscillator at typical room temperature (±20 ppm at 20-25 degrees Celsius) can be compensated if a reference clock/signal is used to measure such inaccuracy. This kind of calibration operation can be set up during the final product manufacturing by means of measurement equipment embedding such a reference clock. The correction of value must be programmed into the RTC Mode Register (RTC_MR), and this value is kept as long as the circuitry is powered (backup area). Removing the backup power supply cancels this calibration. This room temperature calibration can be further processed by means of the networking capability of the target application. In any event, this adjustment does not take into account the temperature variation. The frequency drift (up to -200 ppm) due to temperature variation can be compensated using a reference time if the application can access such a reference. If a reference time cannot be used, a temperature sensor can be placed close to the crystal oscillator in order to get the operating temperature of the crystal oscillator. Once obtained, the temperature may be converted using a lookup table (describing the accuracy/temperature curve of the crystal oscillator used) and RTC_MR configured accordingly. The calibration can be performed on-the-fly. This adjustment method is not based on a measurement of the crystal frequency/drift and therefore can be improved by means of the networking capability of the target application. If no crystal frequency adjustment has been done during manufacturing, it is still possible to do it. In the case where a reference time of the day can be obtained through LAN/WAN network, it is possible to calculate the drift of the application crystal oscillator by comparing the values read on RTC Time Register (RTC_TIMR) and programming the HIGHPPM and CORRECTION bitfields on RTC_MR according to the difference measured between the reference time and those of RTC_TIMR. 282 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 15.6 Real-time Clock (RTC) User Interface Table 15-1. Offset Register Mapping Register Name Access Reset 0x00 Control Register RTC_CR Read-write 0x0 0x04 Mode Register RTC_MR Read-write 0x0 0x08 Time Register RTC_TIMR Read-write 0x0 0x0C Calendar Register RTC_CALR Read-write 0x01A11020 0x10 Time Alarm Register RTC_TIMALR Read-write 0x0 0x14 Calendar Alarm Register RTC_CALALR Read-write 0x01010000 0x18 Status Register RTC_SR Read-only 0x0 0x1C Status Clear Command Register RTC_SCCR Write-only – 0x20 Interrupt Enable Register RTC_IER Write-only – 0x24 Interrupt Disable Register RTC_IDR Write-only – 0x28 Interrupt Mask Register RTC_IMR Read-only 0x0 0x2C Valid Entry Register RTC_VER Read-only 0x0 0x30–0xC4 Reserved Register – – – 0xC8–0xF8 Reserved Register – – – 0xFC Reserved Register – – – Note: If an offset is not listed in the table it must be considered as reserved. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 283 15.6.1 RTC Control Register Name: RTC_CR Address: 0x400E1460 Access: Read-write 31 30 29 28 27 26 25 24 – – – – – – – – 23 22 21 20 19 18 17 – – – – – – 15 14 13 12 11 10 – – – – – – 16 CALEVSEL 9 8 TIMEVSEL 7 6 5 4 3 2 1 0 – – – – – – UPDCAL UPDTIM • UPDTIM: Update Request Time Register 0 = No effect. 1 = Stops the RTC time counting. Time counting consists of second, minute and hour counters. Time counters can be programmed once this bit is set and acknowledged by the bit ACKUPD of the Status Register. • UPDCAL: Update Request Calendar Register 0 = No effect. 1 = Stops the RTC calendar counting. Calendar counting consists of day, date, month, year and century counters. Calendar counters can be programmed once this bit is set. • TIMEVSEL: Time Event Selection The event that generates the flag TIMEV in RTC_SR (Status Register) depends on the value of TIMEVSEL. Value Name Description 0 MINUTE Minute change 1 HOUR Hour change 2 MIDNIGHT Every day at midnight 3 NOON Every day at noon • CALEVSEL: Calendar Event Selection The event that generates the flag CALEV in RTC_SR depends on the value of CALEVSEL Value Name Description 0 WEEK Week change (every Monday at time 00:00:00) 1 MONTH Month change (every 01 of each month at time 00:00:00) 2 YEAR Year change (every January 1 at time 00:00:00) 284 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 15.6.2 RTC Mode Register Name: RTC_MR Address: 0x400E1464 Access: Read-write 31 30 29 28 27 26 25 24 – – – – – – – – 23 22 21 20 19 18 17 16 – – – – – – – – 15 14 13 12 11 10 9 8 HIGHPPM CORRECTION 7 6 5 4 3 2 1 0 – – – NEGPPM – – PERSIAN HRMOD • HRMOD: 12-/24-hour Mode 0 = 24-hour mode is selected. 1 = 12-hour mode is selected. • PERSIAN: PERSIAN Calendar 0 = Gregorian Calendar. 1 = Persian Calendar. • NEGPPM: NEGative PPM Correction 0 = positive correction (the divider will be slightly lower than 32768). 1 = negative correction (the divider will be slightly higher than 32768). Refer to CORRECTION and HIGHPPM field descriptions. • CORRECTION: Slow Clock Correction 0 = No correction 1..127 = The slow clock will be corrected according to the formula given below in HIGHPPM description. • HIGHPPM: HIGH PPM Correction 0 = lower range ppm correction with accurate correction. 1 = higher range ppm correction with accurate correction. If the absolute value of the correction to be applied is lower than 30ppm, it is recommended to clear HIGHPPM. HIGHPPM set to 1 is recommended for 30 ppm correction and above. Formula: If HIGHPPM = 0, then the clock frequency correction range is from 1.5 ppm up to 98 ppm. The RTC accuracy is less than 1 ppm for a range correction from 1.5 ppm up to 30 ppm.. The correction field must be programmed according to the required correction in ppm, the formula is as follows: 3906 CORRECTION = ----------------------- – 1 20 × ppm SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 285 The value obtained must be rounded to the nearest integer prior to being programmed into CORRECTION field. If HIGHPPM = 1, then the clock frequency correction range is from 30.5 ppm up to 1950 ppm. The RTC accuracy is less than 1 ppm for a range correction from 30.5 ppm up to 90 ppm. The correction field must be programmed according to the required correction in ppm, the formula is as follows: 3906 CORRECTION = ------------ – 1 ppm The value obtained must be rounded to the nearest integer prior to be programmed into CORRECTION field. If NEGPPM is set to 1, the ppm correction is negative. 286 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 15.6.3 RTC Time Register Name: RTC_TIMR Address: 0x400E1468 Access: Read-write 31 30 29 28 27 26 25 24 – – – – – – – – 23 22 21 20 19 18 17 16 – AMPM 15 14 10 9 8 2 1 0 HOUR 13 12 – 7 11 MIN 6 5 – 4 3 SEC • SEC: Current Second The range that can be set is 0 - 59 (BCD). The lowest four bits encode the units. The higher bits encode the tens. • MIN: Current Minute The range that can be set is 0 - 59 (BCD). The lowest four bits encode the units. The higher bits encode the tens. • HOUR: Current Hour The range that can be set is 1 - 12 (BCD) in 12-hour mode or 0 - 23 (BCD) in 24-hour mode. • AMPM: Ante Meridiem Post Meridiem Indicator This bit is the AM/PM indicator in 12-hour mode. 0 = AM. 1 = PM. All non-significant bits read zero. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 287 15.6.4 RTC Calendar Register Name: RTC_CALR Address: 0x400E146C Access: Read-write 31 30 – – 23 22 29 28 27 21 20 19 DAY 15 14 26 25 24 18 17 16 DATE MONTH 13 12 11 10 9 8 3 2 1 0 YEAR 7 6 5 – 4 CENT • CENT: Current Century The range that can be set is 19 - 20 (gregorian) or 13-14 (persian) (BCD). The lowest four bits encode the units. The higher bits encode the tens. • YEAR: Current Year The range that can be set is 00 - 99 (BCD). The lowest four bits encode the units. The higher bits encode the tens. • MONTH: Current Month The range that can be set is 01 - 12 (BCD). The lowest four bits encode the units. The higher bits encode the tens. • DAY: Current Day in Current Week The range that can be set is 1 - 7 (BCD). The coding of the number (which number represents which day) is user-defined as it has no effect on the date counter. • DATE: Current Day in Current Month The range that can be set is 01 - 31 (BCD). The lowest four bits encode the units. The higher bits encode the tens. All non-significant bits read zero. 288 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 15.6.5 RTC Time Alarm Register Name: RTC_TIMALR Address: 0x400E1470 Access: Read-write 31 30 29 28 27 26 25 24 – – – – – – – – 21 20 19 18 17 16 10 9 8 2 1 0 23 22 HOUREN AMPM 15 14 HOUR 13 12 MINEN 7 11 MIN 6 5 SECEN 4 3 SEC Note: To change one of the SEC, MIN, HOUR fields, it is recommended to disable the field before changing the value and re-enable it after the value has been changed. This requires up to 3 accesses to the RTC_TIMALR register. First access to only clear the enable corresponding to the field to change (SECEN, MINEN, HOUREN), this access is not required if the field is already cleared. The second access performs the change of the value (SEC, MIN, HOUR). The third access is required to re-enable the field by writing 1 in SECEN, MINEN, HOUREN fields. • SEC: Second Alarm This field is the alarm field corresponding to the BCD-coded second counter. • SECEN: Second Alarm Enable 0 = The second-matching alarm is disabled. 1 = The second-matching alarm is enabled. • MIN: Minute Alarm This field is the alarm field corresponding to the BCD-coded minute counter. • MINEN: Minute Alarm Enable 0 = The minute-matching alarm is disabled. 1 = The minute-matching alarm is enabled. • HOUR: Hour Alarm This field is the alarm field corresponding to the BCD-coded hour counter. • AMPM: AM/PM Indicator This field is the alarm field corresponding to the BCD-coded hour counter. • HOUREN: Hour Alarm Enable 0 = The hour-matching alarm is disabled. 1 = The hour-matching alarm is enabled. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 289 15.6.6 RTC Calendar Alarm Register Name: RTC_CALALR Address: 0x400E1474 Access: Read-write 31 30 DATEEN – 29 28 27 26 25 24 18 17 16 DATE 23 22 21 MTHEN – – 20 19 15 14 13 12 11 10 9 8 – – – – – – – – MONTH 7 6 5 4 3 2 1 0 – – – – – – – – Note: To change one of the DATE, MONTH fields, it is recommended to disable the field before changing the value and re-enable it after the value has been changed. This requires up to 3 accesses to the RTC_CALALR register. First access to only clear the enable corresponding to the field to change (DATEEN, MTHEN), this access is not required if the field is already cleared. The second access performs the change of the value (DATE, MONTH). The third access is required to re-enable the field by writing 1 in DATEEN, MTHEN fields. • MONTH: Month Alarm This field is the alarm field corresponding to the BCD-coded month counter. • MTHEN: Month Alarm Enable 0 = The month-matching alarm is disabled. 1 = The month-matching alarm is enabled. • DATE: Date Alarm This field is the alarm field corresponding to the BCD-coded date counter. • DATEEN: Date Alarm Enable 0 = The date-matching alarm is disabled. 1 = The date-matching alarm is enabled. 290 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 15.6.7 RTC Status Register Name: RTC_SR Address: 0x400E1478 Access: Read-only 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 6 5 4 3 2 1 0 – – TDERR CALEV TIMEV SEC ALARM ACKUPD • ACKUPD: Acknowledge for Update 0 (FREERUN) = Time and calendar registers cannot be updated. 1 (UPDATE) = Time and calendar registers can be updated. • ALARM: Alarm Flag 0 (NO_ALARMEVENT) = No alarm matching condition occurred. 1 (ALARMEVENT) = An alarm matching condition has occurred. • SEC: Second Event 0 (NO_SECEVENT) = No second event has occurred since the last clear. 1 (SECEVENT) = At least one second event has occurred since the last clear. • TIMEV: Time Event 0 (NO_TIMEVENT) = No time event has occurred since the last clear. 1 (TIMEVENT) = At least one time event has occurred since the last clear. The time event is selected in the TIMEVSEL field in RTC_CR (Control Register) and can be any one of the following events: minute change, hour change, noon, midnight (day change). • CALEV: Calendar Event 0 (NO_CALEVENT) = No calendar event has occurred since the last clear. 1 (CALEVENT) = At least one calendar event has occurred since the last clear. The calendar event is selected in the CALEVSEL field in RTC_CR and can be any one of the following events: week change, month change and year change. • TDERR: Time and/or Date Free Running Error 0 (CORRECT) = The internal free running counters are carrying valid values since the last read of RTC_SR. 1 (ERR_TIMEDATE) = The internal free running counters have been corrupted (invalid date or time, non-BCD values) since the last read and/or they are still invalid. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 291 15.6.8 RTC Status Clear Command Register Name: RTC_SCCR Address: 0x400E147C Access: Write-only 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 6 5 4 3 2 1 0 – – TDERRCLR CALCLR TIMCLR SECCLR ALRCLR ACKCLR • ACKCLR: Acknowledge Clear 0 = No effect. 1 = Clears corresponding status flag in the Status Register (RTC_SR). • ALRCLR: Alarm Clear 0 = No effect. 1 = Clears corresponding status flag in the Status Register (RTC_SR). • SECCLR: Second Clear 0 = No effect. 1 = Clears corresponding status flag in the Status Register (RTC_SR). • TIMCLR: Time Clear 0 = No effect. 1 = Clears corresponding status flag in the Status Register (RTC_SR). • CALCLR: Calendar Clear 0 = No effect. 1 = Clears corresponding status flag in the Status Register (RTC_SR). • TDERRCLR: Time and/or Date Free Running Error Clear 0 = No effect. 1 = Clears corresponding status flag in the Status Register (RTC_SR). 292 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 15.6.9 RTC Interrupt Enable Register Name: RTC_IER Address: 0x400E1480 Access: Write-only 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 6 5 4 3 2 1 0 – – TDERREN CALEN TIMEN SECEN ALREN ACKEN • ACKEN: Acknowledge Update Interrupt Enable 0 = No effect. 1 = The acknowledge for update interrupt is enabled. • ALREN: Alarm Interrupt Enable 0 = No effect. 1 = The alarm interrupt is enabled. • SECEN: Second Event Interrupt Enable 0 = No effect. 1 = The second periodic interrupt is enabled. • TIMEN: Time Event Interrupt Enable 0 = No effect. 1 = The selected time event interrupt is enabled. • CALEN: Calendar Event Interrupt Enable 0 = No effect. 1 = The selected calendar event interrupt is enabled. • TDERREN: Time and/or Date Error Interrupt Enable 0 = No effect. 1 = The time and date error interrupt is enabled. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 293 15.6.10 RTC Interrupt Disable Register Name: RTC_IDR Address: 0x400E1484 Access: Write-only 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 6 5 4 3 2 1 0 – – TDERRDIS CALDIS TIMDIS SECDIS ALRDIS ACKDIS • ACKDIS: Acknowledge Update Interrupt Disable 0 = No effect. 1 = The acknowledge for update interrupt is disabled. • ALRDIS: Alarm Interrupt Disable 0 = No effect. 1 = The alarm interrupt is disabled. • SECDIS: Second Event Interrupt Disable 0 = No effect. 1 = The second periodic interrupt is disabled. • TIMDIS: Time Event Interrupt Disable 0 = No effect. 1 = The selected time event interrupt is disabled. • CALDIS: Calendar Event Interrupt Disable 0 = No effect. 1 = The selected calendar event interrupt is disabled. • TDERRDIS: Time and/or Date Error Interrupt Disable 0 = No effect. • 1 = The time and date error interrupt is disabled. 294 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 15.6.11 RTC Interrupt Mask Register Name: RTC_IMR Address: 0x400E1488 Access: Read-only 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 6 5 4 3 2 1 0 – – – CAL TIM SEC ALR ACK • ACK: Acknowledge Update Interrupt Mask 0 = The acknowledge for update interrupt is disabled. 1 = The acknowledge for update interrupt is enabled. • ALR: Alarm Interrupt Mask 0 = The alarm interrupt is disabled. 1 = The alarm interrupt is enabled. • SEC: Second Event Interrupt Mask 0 = The second periodic interrupt is disabled. 1 = The second periodic interrupt is enabled. • TIM: Time Event Interrupt Mask 0 = The selected time event interrupt is disabled. 1 = The selected time event interrupt is enabled. • CAL: Calendar Event Interrupt Mask 0 = The selected calendar event interrupt is disabled. 1 = The selected calendar event interrupt is enabled. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 295 15.6.12 RTC Valid Entry Register Name: RTC_VER Address: 0x400E148C Access: Read-only 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 6 5 4 3 2 1 0 – – – – NVCALALR NVTIMALR NVCAL NVTIM • NVTIM: Non-valid Time 0 = No invalid data has been detected in RTC_TIMR (Time Register). 1 = RTC_TIMR has contained invalid data since it was last programmed. • NVCAL: Non-valid Calendar 0 = No invalid data has been detected in RTC_CALR (Calendar Register). 1 = RTC_CALR has contained invalid data since it was last programmed. • NVTIMALR: Non-valid Time Alarm 0 = No invalid data has been detected in RTC_TIMALR (Time Alarm Register). 1 = RTC_TIMALR has contained invalid data since it was last programmed. • NVCALALR: Non-valid Calendar Alarm 0 = No invalid data has been detected in RTC_CALALR (Calendar Alarm Register). 1 = RTC_CALALR has contained invalid data since it was last programmed. 296 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 16. Watchdog Timer (WDT) 16.1 Description The Watchdog Timer (WDT) can be used to prevent system lock-up if the software becomes trapped in a deadlock. It features a 12-bit down counter that allows a watchdog period of up to 16 seconds (slow clock around 32 kHz). It can generate a general reset or a processor reset only. In addition, it can be stopped while the processor is in debug mode or idle mode. 16.2 16.3 Embedded Characteristics 12-bit key-protected programmable counter Watchdog Clock is independent from Processor Clock Provides reset or interrupt signals to the system Counter may be stopped while the processor is in debug state or in idle mode Block Diagram Figure 16-1. Watchdog Timer Block Diagram write WDT_MR WDT_MR WDV WDT_CR WDRSTT reload 1 0 12-bit Down Counter WDT_MR reload WDD Current Value 1/128 SLCK <= WDD WDT_MR WDRSTEN = 0 wdt_fault (to Reset Controller) set set read WDT_SR or reset WDERR reset WDUNF reset wdt_int WDFIEN WDT_MR SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 297 16.4 Functional Description The Watchdog Timer can be used to prevent system lock-up if the software becomes trapped in a deadlock. It is supplied with VDDCORE. It restarts with initial values on processor reset. The Watchdog is built around a 12-bit down counter, which is loaded with the value defined in the field WDV of the Mode Register (WDT_MR). The Watchdog Timer uses the Slow Clock divided by 128 to establish the maximum Watchdog period to be 16 seconds (with a typical Slow Clock of 32.768 kHz). After a Processor Reset, the value of WDV is 0xFFF, corresponding to the maximum value of the counter with the external reset generation enabled (field WDRSTEN at 1 after a Backup Reset). This means that a default Watchdog is running at reset, i.e., at power-up. The user must either disable it (by setting the WDDIS bit in WDT_MR) if he does not expect to use it or must reprogram it to meet the maximum Watchdog period the application requires. If the watchdog is restarted by writing into the WDT_CR register, the WDT_MR register must not be programmed during a period of time of 3 slow clock periods following the WDT_CR write access. In any case, programming a new value in the WDT_MR register automatically initiates a restart instruction. The Watchdog Mode Register (WDT_MR) can be written only once . Only a processor reset resets it. Writing the WDT_MR register reloads the timer with the newly programmed mode parameters. In normal operation, the user reloads the Watchdog at regular intervals before the timer underflow occurs, by writing the Control Register (WDT_CR) with the bit WDRSTT to 1. The Watchdog counter is then immediately reloaded from WDT_MR and restarted, and the Slow Clock 128 divider is reset and restarted. The WDT_CR register is write-protected. As a result, writing WDT_CR without the correct hard-coded key has no effect. If an underflow does occur, the “wdt_fault” signal to the Reset Controller is asserted if the bit WDRSTEN is set in the Mode Register (WDT_MR). Moreover, the bit WDUNF is set in the Watchdog Status Register (WDT_SR). To prevent a software deadlock that continuously triggers the Watchdog, the reload of the Watchdog must occur while the Watchdog counter is within a window between 0 and WDD, WDD is defined in the WatchDog Mode Register WDT_MR. Any attempt to restart the Watchdog while the Watchdog counter is between WDV and WDD results in a Watchdog error, even if the Watchdog is disabled. The bit WDERR is updated in the WDT_SR and the “wdt_fault” signal to the Reset Controller is asserted. Note that this feature can be disabled by programming a WDD value greater than or equal to the WDV value. In such a configuration, restarting the Watchdog Timer is permitted in the whole range [0; WDV] and does not generate an error. This is the default configuration on reset (the WDD and WDV values are equal). The status bits WDUNF (Watchdog Underflow) and WDERR (Watchdog Error) trigger an interrupt, provided the bit WDFIEN is set in the mode register. The signal “wdt_fault” to the reset controller causes a Watchdog reset if the WDRSTEN bit is set as already explained in the reset controller programmer Datasheet. In that case, the processor and the Watchdog Timer are reset, and the WDERR and WDUNF flags are reset. If a reset is generated or if WDT_SR is read, the status bits are reset, the interrupt is cleared, and the “wdt_fault” signal to the reset controller is deasserted. Writing the WDT_MR reloads and restarts the down counter. While the processor is in debug state or in idle mode, the counter may be stopped depending on the value programmed for the bits WDIDLEHLT and WDDBGHLT in the WDT_MR. 298 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Figure 16-2. Watchdog Behavior Watchdog Error Watchdog Underflow if WDRSTEN is 1 FFF if WDRSTEN is 0 Normal behavior WDV Forbidden Window WDD Permitted Window 0 Watchdog Fault WDT_CR = WDRSTT SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 299 16.5 Watchdog Timer (WDT) User Interface Table 16-1. Register Mapping Offset Register Name 0x00 Control Register 0x04 0x08 300 Access Reset WDT_CR Write-only – Mode Register WDT_MR Read-write Once 0x3FFF_2FFF Status Register WDT_SR Read-only 0x0000_0000 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 16.5.1 Watchdog Timer Control Register Name: WDT_CR Address: 0x400E1450 Access: Write-only 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 – 7 – 6 – 5 – 4 – 3 – 2 – 1 – 0 WDRSTT • WDRSTT: Watchdog Restart 0: No effect. 1: Restarts the Watchdog if KEY is written to 0xA5. • KEY: Password. Value 0xA5 Name Description PASSWD Writing any other value in this field aborts the write operation. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 301 16.5.2 Watchdog Timer Mode Register Name: WDT_MR Address: 0x400E1454 Access: Read-write Once 31 30 23 29 WDIDLEHLT 28 WDDBGHLT 27 21 20 19 11 22 26 25 24 18 17 16 10 9 8 1 0 WDD WDD 15 WDDIS 14 13 12 WDRPROC WDRSTEN WDFIEN 7 6 5 4 WDV 3 2 WDV Note: The first write access prevents any further modification of the value of this register, read accesses remain possible. Note: The WDD and WDV values must not be modified within a period of time of 3 slow clock periods following a restart of the watchdog performed by means of a write access in the WDT_CR register, else the watchdog may trigger an end of period earlier than expected. • WDV: Watchdog Counter Value Defines the value loaded in the 12-bit Watchdog Counter. • WDFIEN: Watchdog Fault Interrupt Enable 0: A Watchdog fault (underflow or error) has no effect on interrupt. 1: A Watchdog fault (underflow or error) asserts interrupt. • WDRSTEN: Watchdog Reset Enable 0: A Watchdog fault (underflow or error) has no effect on the resets. 1: A Watchdog fault (underflow or error) triggers a Watchdog reset. • WDRPROC: Watchdog Reset Processor 0: If WDRSTEN is 1, a Watchdog fault (underflow or error) activates all resets. 1: If WDRSTEN is 1, a Watchdog fault (underflow or error) activates the processor reset. • WDD: Watchdog Delta Value Defines the permitted range for reloading the Watchdog Timer. If the Watchdog Timer value is less than or equal to WDD, writing WDT_CR with WDRSTT = 1 restarts the timer. If the Watchdog Timer value is greater than WDD, writing WDT_CR with WDRSTT = 1 causes a Watchdog error. • WDDBGHLT: Watchdog Debug Halt 0: The Watchdog runs when the processor is in debug state. 1: The Watchdog stops when the processor is in debug state. 302 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 • WDIDLEHLT: Watchdog Idle Halt 0: The Watchdog runs when the system is in idle mode. 1: The Watchdog stops when the system is in idle state. • WDDIS: Watchdog Disable 0: Enables the Watchdog Timer. 1: Disables the Watchdog Timer. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 303 16.5.3 Watchdog Timer Status Register Name: WDT_SR Address: 0x400E1458 Access Read-only 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 – 6 – 5 – 4 – 3 – 2 – 1 WDERR 0 WDUNF • WDUNF: Watchdog Underflow 0: No Watchdog underflow occurred since the last read of WDT_SR. 1: At least one Watchdog underflow occurred since the last read of WDT_SR. • WDERR: Watchdog Error 0: No Watchdog error occurred since the last read of WDT_SR. 1: At least one Watchdog error occurred since the last read of WDT_SR. 304 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 17. Supply Controller (SUPC) 17.1 Description The Supply Controller (SUPC) controls the supply voltages of the system and manages the Backup Low Power Mode. In this mode, the current consumption is reduced to a few microamps for Backup power retention. Exit from this mode is possible on multiple wake-up sources. The SUPC also generates the Slow Clock by selecting either the Low Power RC oscillator or the Low Power Crystal oscillator. 17.2 Embedded Characteristics Manages the Core Power Supply VDDCORE and the Backup Low Power Mode by Controlling the Embedded Voltage Regulator A Supply Monitor Detection on VDDIO or a Brownout Detection on VDDCORE can Trigger a Core Reset Generates the Slow Clock SLCK, by Selecting Either the 22-42 kHz Low Power RC Oscillator or the 32 kHz Low Power Crystal Oscillator Supports Multiple Wake-up Sources, for Exit from Backup Low Power Mode ̶ 16 Wake-up Inputs (including Tamper inputs), with Programmable Debouncing ̶ Real Time Clock Alarm ̶ Real Time Timer Alarm ̶ Supply Monitor Detection on VDDIO, with Programmable Scan Period and Voltage Threshold SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 305 17.3 Block Diagram Figure 17-1. Supply Controller Block Diagram VDDIO VDDOUT vr_on = VROFF / ONREG controlled Software Controlled Voltage Regulator VDDIN Supply Controller Zero-Power Power-on Reset VDDIO Supply Monitor (Backup) sm_on = SMSMPL control PIOA/B/C PIOx ADC ADx sm_out WKUP0 - WKUP15 General Purpose Backup Registers ADVREF rtc_nreset SLCK RTC SLCK RTT DAC rtc_alarm DAC0x rtt_nreset rtt_alarm on = XTALSEL core_nreset XIN32 XOUT32 XTALSEL Xtal 32 kHz Oscillator Embedded 32 kHz RC Oscillator Slow Clock SLCK on = !BODDIS core_brown_out Brownout Detector (Core) on = !XTALSEL SRAM Backup Power Supply core_nreset Peripherals proc_nreset periph_nreset ice_nreset Reset Controller NRST Peripheral Bridge Cortex-M Processor FSTT0 - FSTT15 (Note 1) Embedded 12/8/4 MHz RC Oscillator XIN XOUT VDDCORE Matrix SLCK Flash Main Clock MAINCK Xtal Oscillator Master Clock MCK Power Management Controller PLL SLCK Watchdog Timer Core Power Supply Note1: FSTT0 - FSTT15 are possible Fast Startup Sources, generated by WKUP0-WKUP15 Pins but are not physical 306 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 17.4 Supply Controller Functional Description 17.4.1 Supply Controller Overview The device can be divided into two power supply areas: The Backup VDDIO Power Supply: including the Supply Controller, a part of the Reset Controller, the Slow Clock switch, the General Purpose Backup Registers, the Supply Monitor and the Clock which includes the Real Time Timer and the Real Time Clock The Core Power Supply: including the other part of the Reset Controller, the Brownout Detector, the Processor, the SRAM memory, the FLASH memory and the Peripherals The Supply Controller (SUPC) controls the supply voltage of the core power supply. The SUPC intervenes when the VDDIO power supply rises (when the system is starting) or when the Backup Low Power Mode is entered. The SUPC also integrates the Slow Clock generator which is based on a 32 kHz crystal oscillator and an embedded 32 kHz RC oscillator. The Slow Clock defaults to the RC oscillator, but the software can enable the crystal oscillator and select it as the Slow Clock source. The Supply Controller and the VDDIO power supply have a reset circuitry based on a zero-power power-on reset cell. The zero-power power-on reset allows the SUPC to start properly as soon as the VDDIO voltage becomes valid. At start-up of the system, once the backup voltage VDDIO is valid and the embedded 32 kHz RC oscillator is stabilized, the SUPC starts up the core by sequentially enabling the internal Voltage Regulator, waiting that the core voltage VDDCORE is valid, then releasing the reset signal of the core “vddcore_nreset” signal. Once the system has started, the user can program a supply monitor and/or a brownout detector. If the supply monitor detects a voltage on VDDIO that is too low, the SUPC can assert the reset signal of the core “vddcore_nreset” signal until VDDIO is valid. Likewise, if the brownout detector detects a core voltage VDDCORE that is too low, the SUPC can assert the reset signal “vddcore_nreset” until VDDCORE is valid. When the Backup Low Power Mode is entered, the SUPC sequentially asserts the reset signal of the core power supply “vddcore_nreset” and disables the voltage regulator, in order to supply only the VDDIO power supply. In this mode the current consumption is reduced to a few microamps for Backup part retention. Exit from this mode is possible on multiple wake-up sources including an event on WKUP pins, or a Clock alarm. To exit this mode, the SUPC operates in the same way as system start-up. 17.4.2 Slow Clock Generator The Supply Controller embeds a slow clock generator that is supplied with the VDDIO power supply. As soon as the VDDIO is supplied, both the crystal oscillator and the embedded RC oscillator are powered up, but only the embedded RC oscillator is enabled. This allows the slow clock to be valid in a short time (about 100 µs). The user can select the crystal oscillator to be the source of the slow clock, as it provides a more accurate frequency. The command is made by writing the Supply Controller Control Register (SUPC_CR) with the XTALSEL bit at 1.This results in a sequence which first configures the PIO lines multiplexed with XIN32 and XOUT32 to be driven by the oscillator, then enables the crystal oscillator, then counts a number of slow RC oscillator clock periods to cover the start-up time of the crystal oscillator (refer to electrical characteristics for details of 32KHz crystal oscillator start-up time), then switches the slow clock on the output of the crystal oscillator and then disables the RC oscillator to save power. The switching time may vary according to the slow RC oscillator clock frequency range. The switch of the slow clock source is glitch free. The OSCSEL bit of the Supply Controller Status Register (SUPC_SR) allows knowing when the switch sequence is done. Coming back on the RC oscillator is only possible by shutting down the VDDIO power supply. If the user does not need the crystal oscillator, the XIN32 and XOUT32 pins should be left unconnected. The user can also set the crystal oscillator in bypass mode instead of connecting a crystal. In this case, the user has to provide the external clock signal on XIN32. The input characteristics of the XIN32 pin are given in the SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 307 product electrical characteristics section. In order to set the bypass mode, the OSCBYPASS bit of the Supply Controller Mode Register (SUPC_MR) needs to be set at 1. 17.4.3 Core Voltage Regulator Control/Backup Low Power Mode The Supply Controller can be used to control the embedded voltage regulator. The voltage regulator automatically adapts its quiescent current depending on the required load current. Please refer to the electrical characteristics section. The programmer can switch off the voltage regulator, and thus put the device in Backup mode, by writing the Supply Controller Control Register (SUPC_CR) with the VROFF bit at 1. This asserts the vddcore_nreset signal after the write resynchronization time which lasts, in the worse case, two slow clock cycles. Once the vddcore_nreset signal is asserted, the processor and the peripherals are stopped one slow clock cycle before the core power supply shuts off. When the user does not use the internal voltage regulator and wants to supply VDDCORE by an external supply, it is possible to disable the voltage regulator. This is done through ONREG bit in SUPC_MR. 17.4.4 Supply Monitor The Supply Controller embeds a supply monitor which is located in the VDDIO Power Supply and which monitors VDDIO power supply. The supply monitor can be used to prevent the processor from falling into an unpredictable state if the Main power supply drops below a certain level. The threshold of the supply monitor is programmable. It can be selected from 1.9V to 3.4V by steps of 100 mV. This threshold is programmed in the SMTH field of the Supply Controller Supply Monitor Mode Register (SUPC_SMMR). The supply monitor can also be enabled during one slow clock period on every one of either 32, 256 or 2048 slow clock periods, according to the choice of the user. This can be configured by programming the SMSMPL field in SUPC_SMMR. Enabling the supply monitor for such reduced times allows to divide the typical supply monitor power consumption respectively by factors of 32, 256 or 2048, if the user does not need a continuous monitoring of the VDDIO power supply. A supply monitor detection can either generate a reset of the core power supply or a wake-up of the core power supply. Generating a core reset when a supply monitor detection occurs is enabled by writing the SMRSTEN bit to 1 in SUPC_SMMR. Waking up the core power supply when a supply monitor detection occurs can be enabled by programming the SMEN bit to 1 in the Supply Controller Wake-up Mode Register (SUPC_WUMR). The Supply Controller provides two status bits in the Supply Controller Status Register for the supply monitor which allows to determine whether the last wake-up was due to the supply monitor: The SMOS bit provides real time information, which is updated at each measurement cycle or updated at each Slow Clock cycle, if the measurement is continuous. The SMS bit provides saved information and shows a supply monitor detection has occurred since the last read of SUPC_SR. The SMS bit can generate an interrupt if the SMIEN bit is set to 1 in the Supply Controller Supply Monitor Mode Register (SUPC_SMMR). 308 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Figure 17-2. Supply Monitor Status Bit and Associated Interrupt Continuous Sampling (SMSMPL = 1) Periodic Sampling Supply Monitor ON 3.3 V Threshold 0V Read SUPC_SR SMS and SUPC interrupt 17.4.5 Backup Power Supply Reset 17.4.5.1 Raising the Backup Power Supply As soon as the backup voltage VDDIO rises, the RC oscillator is powered up and the zero-power power-on reset cell maintains its output low as long as VDDIO has not reached its target voltage. During this time, the Supply Controller is entirely reset. When the VDDIO voltage becomes valid and zero-power power-on reset signal is released, a counter is started for 5 slow clock cycles. This is the time it takes for the 32 kHz RC oscillator to stabilize. After this time,the voltage regulator is enabled. The core power supply rises and the brownout detector provides the bodcore_in signal as soon as the core voltage VDDCORE is valid. This results in releasing the vddcore_nreset signal to the Reset Controller after the bodcore_in signal has been confirmed as being valid for at least one slow clock cycle. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 309 Figure 17-3. Raising the VDDIO Power Supply 7 x Slow Clock Cycles (5 for startup slow RC + 2 for synchro.) TON Voltage Regulator 3 x Slow Clock Cycles 2 x Slow Clock Cycles 6.5 x Slow Clock Cycles Zero-Power POR Backup Power Supply Zero-Power Power-On Reset Cell output 22 - 42 kHz RC Oscillator output vr_on Core Power Supply Fast RC Oscillator output bodcore_in vddcore_nreset RSTC.ERSTL default = 2 NRST (no ext. drive assumed) periph_nreset proc_nreset Note: After “proc_nreset” rising, the core starts fetching instructions from Flash at 4 MHz. 17.4.6 Core Reset The Supply Controller manages the vddcore_nreset signal to the Reset Controller, as described previously in Section 17.4.5 “Backup Power Supply Reset”. The vddcore_nreset signal is normally asserted before shutting down the core power supply and released as soon as the core power supply is correctly regulated. There are two additional sources which can be programmed to activate vddcore_nreset: a supply monitor detection a brownout detection 17.4.6.1 Supply Monitor Reset The supply monitor is capable of generating a reset of the system. This can be enabled by setting the SMRSTEN bit in the Supply Controller Supply Monitor Mode Register (SUPC_SMMR). If SMRSTEN is set and if a supply monitor detection occurs, the vddcore_nreset signal is immediately activated for a minimum of 1 slow clock cycle. 310 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 17.4.6.2 Brownout Detector Reset The brownout detector provides the bodcore_in signal to the SUPC which indicates that the voltage regulation is operating as programmed. If this signal is lost for longer than 1 slow clock period while the voltage regulator is enabled, the Supply Controller can assert vddcore_nreset. This feature is enabled by writing the bit, BODRSTEN (Brownout Detector Reset Enable) to 1 in the Supply Controller Mode Register (SUPC_MR). If BODRSTEN is set and the voltage regulation is lost (output voltage of the regulator too low), the vddcore_nreset signal is asserted for a minimum of 1 slow clock cycle and then released if bodcore_in has been reactivated. The BODRSTS bit is set in the Supply Controller Status Register (SUPC_SR) so that the user can know the source of the last reset. Until bodcore_in is deactivated, the vddcore_nreset signal remains active. 17.4.7 Wake-up Sources The wake-up events allow the device to exit backup mode. When a wake-up event is detected, the Supply Controller performs a sequence which automatically reenables the core power supply. Figure 17-4. Wake-up Sources SMEN sm_out RTCEN rtc_alarm RTTEN rtt_alarm LPDBC WKUPT1 RTCOUT0 LPDBCS1 LPDBCEN1 Low/High Level Detect Debouncer WKUPT0 LPDBC RTCOUT0 LPDBCEN0 LPDBCS0 Low/High Level Detect WKUPT0 WKUP0 WKUPEN0 Debouncer WKUPIS0 Low/High Level Detect WKUPDBC SLCK WKUPT1 Core Supply Restart WKUPEN1 WKUPS WKUPIS1 Debouncer WKUP1 Low/High Level Detect WKUPT15 WKUP15 WKUPEN15 WKUPIS15 Low/High Level Detect 17.4.7.1 Wake-up Inputs The wake-up inputs, WKUP0 to WKUP15, can be programmed to perform a wake-up of the core power supply. Each input can be enabled by writing to 1 the corresponding bit, WKUPEN0 to WKUPEN 15, in the Wake-up Inputs Register (SUPC_WUIR). The wake-up level can be selected with the corresponding polarity bit, WKUPPL0 to WKUPPL15, also located in SUPC_WUIR. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 311 All the resulting signals are wired-ORed to trigger a debounce counter, which can be programmed with the WKUPDBC field in the Supply Controller Wake-up Mode Register (SUPC_WUMR). The WKUPDBC field can select a debouncing period of 3, 32, 512, 4,096 or 32,768 slow clock cycles. This corresponds respectively to about 100 µs, about 1 ms, about 16 ms, about 128 ms and about 1 second (for a typical slow clock frequency of 32 kHz). Programming WKUPDBC to 0x0 selects an immediate wake-up, i.e., an enabled WKUP pin must be active according to its polarity during a minimum of one slow clock period to wake up the core power supply. If an enabled WKUP pin is asserted for a time longer than the debouncing period, a wake-up of the core power supply is started and the signals, WKUP0 to WKUP15 as shown in Figure 17-4, are latched in the Supply Controller Status Register (SUPC_SR). This allows the user to identify the source of the wake-up, however, if a new wake-up condition occurs, the primary information is lost. No new wake-up can be detected since the primary wake-up condition has disappeared. 17.4.7.2 Low-power Debouncer Inputs It is possible to generate a waveform (RTCOUT0) in all modes (including backup mode). It can be useful to control an external sensor and/or tampering function without waking up the processor. Please refer to the RTC section for waveform generation. Two separate debouncers are embedded for WKUP0 and WKUP1 inputs. The WKUP0 and/or WKUP1 inputs can be programmed to perform a wake-up of the core power supply with a debouncing done by RTCOUT0. These inputs can be also used when VDDCORE is powered to get tamper detection function with a low power debounce function. This can be enabled by setting LPDBC0 bit and/or LPDBC1 bit in SUPC_WUMR. In this mode of operation, WKUP0 and/or WKUP1 must not be configured to also act as debouncing source for the WKUPDBC counter (WKUPEN0 and/or WKUPEN1 must be cleared in SUPC_WUIR). Refer to Figure 17-4. This mode of operation requires the RTC Output (RTCOUT0) to be configured to generate a duty cycle programmable pulse (i.e. OUT0 = 0x7 in RTC_MR) in order to create the sampling points of both debouncers. The sampling point is the falling edge of the RTCOUT0 waveform. Figure 17-5 shows an example of an application where two tamper switches are used. RTCOUT0 powers the external pull-up used by the tampers. Figure 17-5. Low Power Debouncer (Push-to-Make switch, pull-up resistors) AT91SAM RTCOUT0 Pull-Up Resistor WKUP0 Pull-Up Resistor GND WKUP1 GND GND 312 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Figure 17-6. Low Power Debouncer (Push-to-Break switch, pull-down resistors) AT91SAM RTCOUT0 WKUP0 WKUP1 Pull-Down Resistors GND GND GND The debouncing parameters can be adjusted and are shared (except the wake-up input polarity) by both debouncers. The number of successive identical samples to wake up the core can be configured from 2 up to 8 in the LPDBC field of SUPC_WUMR. The period of time between 2 samples can be configured by programming the TPERIOD field in the RTC_MR register. Power parameters can be adjusted by modifying the period of time in the THIGH field in RTC_MR. The wake-up polarity of the inputs can be independently configured by writing WKUPT0 and WKUPT1 fields in SUPC_WUMR. In order to determine which wake-up pin triggers the core wake-up or simply which debouncer triggers an event (even if there is no wake-up, so when VDDCORE is powered on), a status flag is associated for each low power debouncer. These 2 flags can be read in the SUPC_SR. A debounce event can perform an immediate clear (0 delay) on first half the general purpose backup registers (GPBR). The LPDBCCLR bit must be set to 1 in SUPC_MR. Please note that it is not mandatory to use the RTCOUT pins when using the WKUP0/WKUP1 pins as tampering inputs (TMP0/TMP1) in backup mode or any other modes. Using RTCOUT0 pins provides a “sampling mode” to further reduce the power consumption in low power modes. However the RTC must be configured in the same manner as RTCOUT0 is used in order to create a sampling point for the debouncer logic. Figure 17-7 shows how to use WKUP0/WKUP1 without RTCOUT pins. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 313 Figure 17-7. Using WKUP0/WKUP1 without RTCOUT Pins VDD AT91SAM RTCOUT0 Pull-Up Resistor WKUP0 Pull-Up Resistor GND WKUP1 GND GND 17.4.7.3 Low-power Tamper Detection Inputs WKUP0 and WKUP1 can be used as tamper detect inputs. In Backup Mode they can be used also to wake up the core. If a tamper is detected, it performs an immediate clear (0 delay) on first half the general purpose backup registers (GPBR). Refer to “Wake-up Sources” on page 311 for more details. 17.4.7.4 Clock Alarms The RTC and the RTT alarms can generate a wake-up of the core power supply. This can be enabled by writing respectively, the bits RTCEN and RTTEN to 1 in the Supply Controller Wake-up Mode Register (SUPC_WUMR). The Supply Controller does not provide any status as the information is available in the User Interface of either the Real Time Timer or the Real Time Clock. 17.4.7.5 Supply Monitor Detection The supply monitor can generate a wake-up of the core power supply. See Section 17.4.4 “Supply Monitor”. 314 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 17.5 Supply Controller (SUPC) User Interface The User Interface of the Supply Controller is part of the System Controller User Interface. 17.5.1 System Controller (SYSC) User Interface Table 17-1. System Controller Registers Offset System Controller Peripheral Name 0x00-0x0c Reset Controller RSTC 0x10-0x2C Supply Controller SUPC 0x30-0x3C Real Time Timer RTT 0x50-0x5C Watchdog Timer WDT 0x60-0x8C Real Time Clock RTC 0x90-0xDC General Purpose Backup Register GPBR 0xE0 Reserved 0xE4 Write Protect Mode Register 0xE8-0xF8 Reserved SYSC_WPMR 17.5.2 Supply Controller (SUPC) User Interface Table 17-2. Register Mapping Offset Register Name Access Reset 0x00 Supply Controller Control Register SUPC_CR Write-only N/A 0x04 Supply Controller Supply Monitor Mode Register SUPC_SMMR Read-write 0x0000_0000 0x08 Supply Controller Mode Register SUPC_MR Read-write 0x0000_5A00 0x0C Supply Controller Wake-up Mode Register SUPC_WUMR Read-write 0x0000_0000 0x10 Supply Controller Wake-up Inputs Register SUPC_WUIR Read-write 0x0000_0000 0x14 Supply Controller Status Register SUPC_SR Read-only 0x0000_0000 0x18 Reserved SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 315 17.5.3 Supply Controller Control Register Name: SUPC_CR Address: 0x400E1410 Access: Write-only 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 – 7 – 6 – 5 – 4 – 3 XTALSEL 2 VROFF 1 – 0 – • VROFF: Voltage Regulator Off 0 (NO_EFFECT) = no effect. 1 (STOP_VREG) = if KEY is correct, asserts the vddcore_nreset and stops the voltage regulator. • XTALSEL: Crystal Oscillator Select 0 (NO_EFFECT) = no effect. 1 (CRYSTAL_SEL) = if KEY is correct, switches the slow clock on the crystal oscillator output. • KEY: Password 316 Value Name 0xA5 PASSWD Description Writing any other value in this field aborts the write operation. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 17.5.4 Supply Controller Supply Monitor Mode Register Name: SUPC_SMMR Address: 0x400E1414 Access: Read-write 31 – 30 – 29 – 28 – 27 – 26 – 25 – 24 – 23 – 22 – 21 – 20 – 19 – 18 – 17 – 16 – 15 – 14 – 13 SMIEN 12 SMRSTEN 11 – 10 9 SMSMPL 8 7 – 6 – 5 – 4 – 3 2 1 0 SMTH • SMTH: Supply Monitor Threshold Allows to select the threshold voltage of the supply monitor. Refer to electrical characteristics for voltage values. • SMSMPL: Supply Monitor Sampling Period Value Name Description 0x0 SMD Supply Monitor disabled 0x1 CSM Continuous Supply Monitor 0x2 32SLCK Supply Monitor enabled one SLCK period every 32 SLCK periods 0x3 256SLCK Supply Monitor enabled one SLCK period every 256 SLCK periods 0x4 2048SLCK Supply Monitor enabled one SLCK period every 2,048 SLCK periods • SMRSTEN: Supply Monitor Reset Enable 0 (NOT_ENABLE) = the core reset signal “vddcore_nreset” is not affected when a supply monitor detection occurs. 1 (ENABLE) = the core reset signal, vddcore_nreset is asserted when a supply monitor detection occurs. • SMIEN: Supply Monitor Interrupt Enable 0 (NOT_ENABLE) = the SUPC interrupt signal is not affected when a supply monitor detection occurs. 1 (ENABLE) = the SUPC interrupt signal is asserted when a supply monitor detection occurs. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 317 17.5.5 Supply Controller Mode Register Name: SUPC_MR Address: 0x400E1418 Access: Read-write 31 30 29 28 27 26 25 24 KEY 23 – 22 – 21 – 20 OSCBYPASS 19 – 18 – 17 – 16 – 15 14 ONREG 13 BODDIS 12 BODRSTEN 11 – 10 – 9 – 8 – 7 – 6 – 5 – 4 – 3 – 2 – 1 – 0 – • BODRSTEN: Brownout Detector Reset Enable 0 (NOT_ENABLE) = the core reset signal “vddcore_nreset” is not affected when a brownout detection occurs. 1 (ENABLE) = the core reset signal, vddcore_nreset is asserted when a brownout detection occurs. • BODDIS: Brownout Detector Disable 0 (ENABLE) = the core brownout detector is enabled. 1 (DISABLE) = the core brownout detector is disabled. • ONREG: Voltage Regulator enable 0 (ONREG_UNUSED) = Internal voltage regulator is not used (external power supply is used) 1 (ONREG_USED) = internal voltage regulator is used • OSCBYPASS: Oscillator Bypass 0 (NO_EFFECT) = no effect. Clock selection depends on XTALSEL value. 1 (BYPASS) = the 32-KHz XTAL oscillator is selected and is put in bypass mode. • KEY: Password Key 318 Value Name 0xA5 PASSWD Description Writing any other value in this field aborts the write operation. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 17.5.6 Supply Controller Wake-up Mode Register Name: SUPC_WUMR Address: 0x400E141C Access: Read-write 31 – 30 – 29 – 28 – 27 – 26 – 25 – 24 – 23 – 22 – 21 – 20 – 19 – 18 17 LPDBC 16 15 – 14 13 WKUPDBC 12 11 – 10 – 9 – 8 – 7 LPDBCCLR 6 LPDBCEN1 5 LPDBCEN0 4 – 3 RTCEN 2 RTTEN 1 SMEN 0 – • SMEN: Supply Monitor Wake-up Enable 0 (NOT_ENABLE) = the supply monitor detection has no wake-up effect. 1 (ENABLE) = the supply monitor detection forces the wake-up of the core power supply. • RTTEN: Real Time Timer Wake-up Enable 0 (NOT_ENABLE) = the RTT alarm signal has no wake-up effect. 1 (ENABLE) = the RTT alarm signal forces the wake-up of the core power supply. • RTCEN: Real Time Clock Wake-up Enable 0 (NOT_ENABLE) = the RTC alarm signal has no wake-up effect. 1 (ENABLE) = the RTC alarm signal forces the wake-up of the core power supply. • LPDBCEN0: Low power Debouncer ENable WKUP0 0 (NOT_ENABLE) = the WKUP0 input pin is not connected with low power debouncer. 1 (ENABLE) = the WKUP0 input pin is connected with low power debouncer and can force a core wake-up. • LPDBCEN1: Low power Debouncer ENable WKUP1 0 (NOT_ENABLE) = the WKUP1input pin is not connected with low power debouncer. 1 (ENABLE) = the WKUP1 input pin is connected with low power debouncer and can force a core wake-up. • LPDBCCLR: Low power Debouncer Clear 0 (NOT_ENABLE) = a low power debounce event does not create an immediate clear on first half GPBR registers. 1 (ENABLE) = a low power debounce event on WKUP0 or WKUP1 generates an immediate clear on first half GPBR registers. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 319 • WKUPDBC: Wake-up Inputs Debouncer Period Value Name Description 0 IMMEDIATE 1 3_SCLK WKUPx shall be in its active state for at least 3 SLCK periods 2 32_SCLK WKUPx shall be in its active state for at least 32 SLCK periods 3 512_SCLK WKUPx shall be in its active state for at least 512 SLCK periods 4 4096_SCLK WKUPx shall be in its active state for at least 4,096 SLCK periods 5 32768_SCLK WKUPx shall be in its active state for at least 32,768 SLCK periods 6 Reserved Reserved 7 Reserved Reserved Immediate, no debouncing, detected active at least on one Slow Clock edge. • LPDBC: Low Power DeBounCer Period 320 Value Name Description 0 DISABLE 1 2_RTCOUT0 WKUP0/1 in its active state for at least 2 RTCOUT0 periods 2 3_RTCOUT0 WKUP0/1 in its active state for at least 3 RTCOUT0 periods 3 4_RTCOUT0 WKUP0/1 in its active state for at least 4 RTCOUT0 periods 4 5_RTCOUT0 WKUP0/1 in its active state for at least 5 RTCOUT0 periods 5 6_RTCOUT0 WKUP0/1 in its active state for at least 6 RTCOUT0 periods 6 7_RTCOUT0 WKUP0/1 in its active state for at least 7 RTCOUT0 periods 7 8_RTCOUT0 WKUP0/1 in its active state for at least 8 RTCOUT0 periods Disable the low power debouncer. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 17.5.7 System Controller Wake-up Inputs Register Name: SUPC_WUIR Address: 0x400E1420 Access: Read-write 31 WKUPT15 30 WKUPT14 29 WKUPT13 28 WKUPT12 27 WKUPT11 26 WKUPT10 25 WKUPT9 24 WKUPT8 23 WKUPT7 22 WKUPT6 21 WKUPT5 20 WKUPT4 19 WKUPT3 18 WKUPT2 17 WKUPT1 16 WKUPT0 15 WKUPEN15 14 WKUPEN14 13 WKUPEN13 12 WKUPEN12 11 WKUPEN11 10 WKUPEN10 9 WKUPEN9 8 WKUPEN8 7 WKUPEN7 6 WKUPEN6 5 WKUPEN5 4 WKUPEN4 3 WKUPEN3 2 WKUPEN2 1 WKUPEN1 0 WKUPEN0 • WKUPEN0 - WKUPEN15: Wake-up Input Enable 0 to 15 0 (DISABLE) = the corresponding wake-up input has no wake-up effect. 1 (ENABLE) = the corresponding wake-up input forces the wake-up of the core power supply. • WKUPT0 - WKUPT15: Wake-up Input Type 0 to 15 0 (LOW) = a low level for a period defined by WKUPDBC on the corresponding wake-up input forces the wake-up of the core power supply. 1 (HIGH) = a high level for a period defined by WKUPDBC on the corresponding wake-up input forces the wake-up of the core power supply. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 321 17.5.8 Supply Controller Status Register Name: SUPC_SR Address: 0x400E1424 Access: Read-only 31 WKUPIS15 30 WKUPIS14 29 WKUPIS13 28 WKUPIS12 27 WKUPIS11 26 WKUPIS10 25 WKUPIS9 24 WKUPIS8 23 WKUPIS7 22 WKUPIS6 21 WKUPIS5 20 WKUPIS4 19 WKUPIS3 18 WKUPIS2 17 WKUPIS1 16 WKUPIS0 15 – 14 LPDBCS1 13 LPDBCS0 12 – 11 – 10 – 9 – 8 – 7 OSCSEL 6 SMOS 5 SMS 4 SMRSTS 3 BODRSTS 2 SMWS 1 WKUPS 0 – Note: Because of the asynchronism between the Slow Clock (SCLK) and the System Clock (MCK), the status register flag reset is taken into account only 2 slow clock cycles after the read of the SUPC_SR. • WKUPS: WKUP Wake-up Status 0 (NO) = no wake-up due to the assertion of the WKUP pins has occurred since the last read of SUPC_SR. 1 (PRESENT) = at least one wake-up due to the assertion of the WKUP pins has occurred since the last read of SUPC_SR. • SMWS: Supply Monitor Detection Wake-up Status 0 (NO) = no wake-up due to a supply monitor detection has occurred since the last read of SUPC_SR. 1 (PRESENT) = at least one wake-up due to a supply monitor detection has occurred since the last read of SUPC_SR. • BODRSTS: Brownout Detector Reset Status 0 (NO) = no core brownout rising edge event has been detected since the last read of the SUPC_SR. 1 (PRESENT) = at least one brownout output rising edge event has been detected since the last read of the SUPC_SR. When the voltage remains below the defined threshold, there is no rising edge event at the output of the brownout detection cell. The rising edge event occurs only when there is a voltage transition below the threshold. • SMRSTS: Supply Monitor Reset Status 0 (NO) = no supply monitor detection has generated a core reset since the last read of the SUPC_SR. 1 (PRESENT) = at least one supply monitor detection has generated a core reset since the last read of the SUPC_SR. • SMS: Supply Monitor Status 0 (NO) = no supply monitor detection since the last read of SUPC_SR. 1 (PRESENT) = at least one supply monitor detection since the last read of SUPC_SR. • SMOS: Supply Monitor Output Status 0 (HIGH) = the supply monitor detected VDDIO higher than its threshold at its last measurement. 1 (LOW) = the supply monitor detected VDDIO lower than its threshold at its last measurement. 322 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 • OSCSEL: 32-kHz Oscillator Selection Status 0 (RC) = the slow clock, SLCK is generated by the embedded 32-kHz RC oscillator. 1 (CRYST) = the slow clock, SLCK is generated by the 32-kHz crystal oscillator. • LPDBCS0: Low Power Debouncer Wake-up Status on WKUP0 0 (NO) = no wake-up due to the assertion of the WKUP0 pin has occurred since the last read of SUPC_SR. 1 (PRESENT) = at least one wake-up due to the assertion of the WKUP0 pin has occurred since the last read of SUPC_SR. • LPDBCS1: Low Power Debouncer Wake-up Status on WKUP1 0 (NO) = no wake-up due to the assertion of the WKUP1 pin has occurred since the last read of SUPC_SR. 1 (PRESENT) = at least one wake-up due to the assertion of the WKUP1 pin has occurred since the last read of SUPC_SR. • WKUPIS0-WKUPIS15: WKUP Input Status 0 to 15 0 (DIS) = the corresponding wake-up input is disabled, or was inactive at the time the debouncer triggered a wake-up event. 1 (EN) = the corresponding wake-up input was active at the time the debouncer triggered a wake-up event. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 323 17.5.9 System Controller Write Protect Mode Register Name: SYSC_WPMR Access: Read-write 31 30 29 28 27 26 25 24 19 18 17 16 11 10 9 8 3 – 2 – 1 – 0 WPEN WPKEY 23 22 21 20 WPKEY 15 14 13 12 WPKEY 7 – 6 – 5 – 4 – • WPEN: 0: The Write Protection is disabled. 1: The Write Protection is enabled. LList of the write-protected registers: RSTC Mode Register RTT Mode Register RTT Alarm Register RTC Control Register RTC Mode Register RTC Time Alarm Register RTC Calendar Alarm Register General Purpose Backup Registers SUPC Control Register SUPC Supply Monitor Mode Register SUPC Mode Register SUPC Wake-up Mode Register SUPC Wake-up Input Mode Register • WPKEY:. Value Name 0x525443 PASSWD 324 Description Writing any other value in this field aborts the write operation of the WPEN bit. Always reads as 0. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 18. General Purpose Backup Registers (GPBR) 18.1 Description The System Controller embeds Eight general-purpose backup registers. It is possible to generate an immediate clear of the content of general-purpose backup registers 0 to 3 (first half), if a low power debounce event is detected on a wakeup pin, WKUP0 or WKUP1. The content of the other generalpurpose backup registers (second half) remains unchanged. To enter this mode of operation, the supply controller module must be programmed accordingly. In supply controller SUPC_WUMR register, LPDBCCLR, LPDBCEN0 and/or LPDBCEN1 bit must be configured to 1 and LPDBC must be other than 0. If a tamper event has been detected, it is not possible to write into general-purpose backup registers while the LPDBCS0 or LPDBCS1 flags are not cleared in supply controller status register SUPC_SR. 18.2 Embedded Characteristics Eight 32-bit General Purpose Backup Registers SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 325 18.3 General Purpose Backup Registers (GPBR) User Interface Table 18-1. Offset 0x0 ... 0x1C 326 Register Mapping Register Name General Purpose Backup Register 0 SYS_GPBR0 ... ... General Purpose Backup Register 7 SYS_GPBR7 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Access Reset Read-write – ... ... Read-write – 18.3.1 General Purpose Backup Register x Name: SYS_GPBRx Address: 0x400E1490 [0] .. 0x400E14AC [7] Access: Read-write 31 30 29 28 27 26 25 24 18 17 16 10 9 8 2 1 0 GPBR_VALUE 23 22 21 20 19 GPBR_VALUE 15 14 13 12 11 GPBR_VALUE 7 6 5 4 3 GPBR_VALUE • GPBR_VALUE: Value of GPBR x If a tamper event has been detected, it is not possible to write GPBR_VALUE while the LPDBCS0 or LPDBCS1 flags are not cleared in supply controller status register SUPC_SR. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 327 19. Embedded Flash Controller (EFC) 19.1 Description The Enhanced Embedded Flash Controller (EEFC) ensures the interface of the Flash block with the 32-bit internal bus. Its 128-bit or 64-bit wide memory interface increases performance. It also manages the programming, erasing, locking and unlocking sequences of the Flash using a full set of commands. One of the commands returns the embedded Flash descriptor definition that informs the system about the Flash organization, thus making the software generic. 19.2 19.3 Embedded Characteristics Interface of the Flash Block with the 32-bit Internal Bus Increases Performance in Thumb2 Mode with 128-bit or -64 bit Wide Memory Interface up to 80 MHz Code loops optimization 128 Lock Bits, Each Protecting a Lock Region GPNVMx General-purpose GPNVM Bits One-by-one Lock Bit Programming Commands Protected by a Keyword Erases the Entire Flash Erases by Plane Erase by Sector Erase by Pages Possibility of Erasing before Programming Locking and Unlocking Operations Possibility to read the Calibration Bits Product Dependencies 19.3.1 Power Management The Enhanced Embedded Flash Controller (EEFC) is continuously clocked. The Power Management Controller has no effect on its behavior. 19.3.2 Interrupt Sources The Enhanced Embedded Flash Controller (EEFC) interrupt line is connected to the Nested Vectored Interrupt Controller (NVIC). Using the Enhanced Embedded Flash Controller (EEFC) interrupt requires the NVIC to be programmed first. The EEFC interrupt is generated only on FRDY bit rising. Table 19-1. 328 Peripheral IDs Instance ID EFC 6 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 19.4 Functional Description 19.4.1 Embedded Flash Organization The embedded Flash interfaces directly with the 32-bit internal bus. The embedded Flash is composed of: One memory plane organized in several pages of the same size. Two 128-bit or 64-bit read buffers used for code read optimization. One 128-bit or 64-bit read buffer used for data read optimization. One write buffer that manages page programming. The write buffer size is equal to the page size. This buffer is write-only and accessible all along the 1 MByte address space, so that each word can be written to its final address. Several lock bits used to protect write/erase operation on several pages (lock region). A lock bit is associated with a lock region composed of several pages in the memory plane. Several bits that may be set and cleared through the Enhanced Embedded Flash Controller (EEFC) interface, called General Purpose Non Volatile Memory bits (GPNVM bits). The embedded Flash size, the page size, the lock regions organization and GPNVM bits definition are specific to the product. The Enhanced Embedded Flash Controller (EEFC) returns a descriptor of the Flash controlled after a get descriptor command issued by the application (see “Getting Embedded Flash Descriptor” on page 335). Figure 19-1. Embedded Flash Organization Memory Plane Start Address Page 0 Lock Region 0 Lock Bit 0 Lock Region 1 Lock Bit 1 Lock Region (n-1) Lock Bit (n-1) Page (m-1) Start Address + Flash size -1 Page (n*m-1) 19.4.2 Read Operations An optimized controller manages embedded Flash reads, thus increasing performance when the processor is running in Thumb2 mode by means of the 128- or 64- bit wide memory interface. The Flash memory is accessible through 8-, 16- and 32-bit reads. As the Flash block size is smaller than the address space reserved for the internal memory area, the embedded Flash wraps around the address space and appears to be repeated within it. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 329 The read operations can be performed with or without wait states. Wait states must be programmed in the field FWS (Flash Read Wait State) in the Flash Mode Register (EEFC_FMR). Defining FWS to be 0 enables the singlecycle access of the embedded Flash. Refer to the Electrical Characteristics for more details. 19.4.2.1 128-bit or 64-bit Access Mode By default the read accesses of the Flash are performed through a 128-bit wide memory interface. It enables better system performance especially when 2 or 3 wait state needed. For systems requiring only 1 wait state, or to privilege current consumption rather than performance, the user can select a 64-bit wide memory access via the FAM bit in the Flash Mode Register (EEFC_FMR) Please refer to the electrical characteristics section of the product datasheet for more details. 19.4.2.2 Code Read Optimization This feature is enabled if the EEFC_FMR register bit SCOD is cleared. A system of 2 x 128-bit or 2 x 64-bit buffers is added in order to optimize sequential Code Fetch. Note: Immediate consecutive code read accesses are not mandatory to benefit from this optimization. The sequential code read optimization is enabled by default. If the bit SCOD in Flash Mode Register (EEFC_FMR) is set to 1, these buffers are disabled and the sequential code read is not optimized anymore. Another system of 2 x 128-bit or 2 x 64-bit buffers is added in order to optimize loop code fetch (see “Code Loops Optimization” on page 331). Figure 19-2. Code Read Optimization for FWS = 0 Master Clock ARM Request (32-bit) @Byte 0 Flash Access Buffer 0 (128bits) Buffer 1 (128bits) Data To ARM XXX @Byte 4 @Byte 8 Bytes 0-15 Bytes 16-31 XXX @Byte 12 @Byte 16 @Byte 20 @Byte 32 Bytes 32-47 Bytes 0-15 XXX Bytes 0-3 @Byte 28 Bytes 32-47 Bytes 16-31 Bytes 4-7 Bytes 8-11 Bytes 12-15 Bytes 16-19 Note: When FWS is equal to 0, all the accesses are performed in a single-cycle access. 330 @Byte 24 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Bytes 20-23 Bytes 24-27 Bytes 28-31 Figure 19-3. Code Read Optimization for FWS = 3 Master Clock ARM Request (32-bit) @Byte 0 @4 Flash Access @8 Bytes 0-15 @12 @16 @24 @28 @32 Bytes 16-31 XXX Buffer 0 (128bits) @20 @36 @40 Bytes 32-47 Bytes 32-47 XXX XXX Data To ARM @48 @52 Bytes 48-63 Bytes 0-15 Buffer 1 (128bits) @44 Bytes 16-31 0-3 4-7 8-11 12-15 16-19 20-23 24-27 28-31 32-35 36-39 40-43 44-47 48-51 Note: When FWS is included between 1 and 3, in case of sequential reads, the first access takes (FWS+1) cycles, the other ones only 1 cycle. 19.4.2.3 Code Loops Optimization The Code Loops optimization is enabled when the CLOE bit of the EEFC_FMR register is set at 1. When a backward jump is inserted in the code, the pipeline of the sequential optimization is broken, and it becomes inefficient. In this case the loop code read optimization takes over from the sequential code read optimization to avoid insertion of wait states. The loop code read optimization is enabled by default. If in Flash Mode Register (EEFC_FMR), the bit CLOE is reset to 0 or the bit SCOD is set to 1, these buffers are disabled and the loop code read is not optimized anymore. When this feature is enabled, if inner loop body instructions L0 to Ln lay from the 128-bit flash memory cell Mb0 to the memory cell Mp1, after recognition of a first backward branch, the two first flash memory cells M b0 and Mb1 targeted by this branch are cached for fast access from the processor at the next loop iterations. Afterwards, combining the sequential prefetch (described in Section 19.4.2.2 “Code Read Optimization”) through the loop body with the fast read access to the loop entry cache, the whole loop can be iterated with no wait-state. Figure 19-4 below illustrates the Code Loops optimization. Figure 19-4. Code Loops Optimization Backward address jump Flash Memory 128-bit words Mb0 B0 B1 Mb1 Mp0 Mp1 L0 L1 L2 L3 L4 L5 Ln-5 Ln-4 Ln-3 Ln-2 Ln-1 Ln B2 B3 B4 B5 B6 B7 P0 P1 P2 P3 P4 P5 2x128-bit loop entry cache P6 P7 2x128-bit prefetch buffer Mb0 Branch Cache 0 L0 Loop Entry instruction Mp0 Prefetch Buffer 0 Mb1 Branch Cache 1 Ln Loop End instruction Mp1 Prefetch Buffer 1 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 331 19.4.2.4 Data Read Optimization The organization of the Flash in 128 bits (or 64 bits) is associated with two 128-bit (or 64-bit) prefetch buffers and one 128-bit (or 64-bit) data read buffer, thus providing maximum system performance. This buffer is added in order to store the requested data plus all the data contained in the 128-bit (64-bit) aligned data. This speeds up sequential data reads if, for example, FWS is equal to 1 (see Figure 19-5). The data read optimization is enabled by default. If the bit SCOD in Flash Mode Register (EEFC_FMR) is set to 1, this buffer is disabled and the data read is not optimized anymore. Note: Figure 19-5. No consecutive data read accesses are mandatory to benefit from this optimization. Data Read Optimization for FWS = 1 Master Clock ARM Request (32-bit) @Byte 0 @4 Flash Access XXX Buffer (128bits) Data To ARM 332 @8 @ 12 @ 16 Bytes 0-15 @ 24 @ 28 4-7 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 8-11 12-15 @ 36 Bytes 32-47 Bytes 0-15 Bytes 0-3 @ 32 Bytes 16-31 XXX XXX @ 20 Bytes 16-31 16-19 20-23 24-27 28-31 32-35 19.4.3 Flash Commands The Enhanced Embedded Flash Controller (EEFC) offers a set of commands such as programming the memory Flash, locking and unlocking lock regions, consecutive programming and locking and full Flash erasing, etc. Table 19-2. Set of Commands Command Value Mnemonic Get Flash Descriptor 0x00 GETD Write page 0x01 WP Write page and lock 0x02 WPL Erase page and write page 0x03 EWP Erase page and write page then lock 0x04 EWPL Erase all 0x05 EA Erase Pages 0x07 EPA Set Lock Bit 0x08 SLB Clear Lock Bit 0x09 CLB Get Lock Bit 0x0A GLB Set GPNVM Bit 0x0B SGPB Clear GPNVM Bit 0x0C CGPB Get GPNVM Bit 0x0D GGPB Start Read Unique Identifier 0x0E STUI Stop Read Unique Identifier 0x0F SPUI Get CALIB Bit 0x10 GCALB Erase Sector 0x11 ES Write User Signature 0x12 WUS Erase User Signature 0x13 EUS Start Read User Signature 0x14 STUS Stop Read User Signature 0x15 SPUS In order to perform one of these commands, the Flash Command Register (EEFC_FCR) has to be written with the correct command using the FCMD field. As soon as the EEFC_FCR register is written, the FRDY flag and the FVALUE field in the EEFC_FRR register are automatically cleared. Once the current command is achieved, then the FRDY flag is automatically set. If an interrupt has been enabled by setting the FRDY bit in EEFC_FMR, the corresponding interrupt line of the NVIC is activated. (Note that this is true for all commands except for the STUI Command. The FRDY flag is not set when the STUI command is achieved.) All the commands are protected by the same keyword, which has to be written in the 8 highest bits of the EEFC_FCR register. Writing EEFC_FCR with data that does not contain the correct key and/or with an invalid command has no effect on the whole memory plane, but the FCMDE flag is set in the EEFC_FSR register. This flag is automatically cleared by a read access to the EEFC_FSR register. When the current command writes or erases a page in a locked region, the command has no effect on the whole memory plane, but the FLOCKE flag is set in the EEFC_FSR register. This flag is automatically cleared by a read access to the EEFC_FSR register. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 333 Figure 19-6. Command State Chart Read Status: MC_FSR No Check if FRDY flag Set Yes Write FCMD and PAGENB in Flash Command Register Read Status: MC_FSR No Check if FRDY flag Set Yes Check if FLOCKE flag Set Yes Locking region violation No Check if FCMDE flag Set No Command Successfull 334 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Yes Bad keyword violation 19.4.3.1 Getting Embedded Flash Descriptor This command allows the system to learn about the Flash organization. The system can take full advantage of this information. For instance, a device could be replaced by one with more Flash capacity, and so the software is able to adapt itself to the new configuration. To get the embedded Flash descriptor, the application writes the GETD command in the EEFC_FCR register. The first word of the descriptor can be read by the software application in the EEFC_FRR register as soon as the FRDY flag in the EEFC_FSR register rises. The next reads of the EEFC_FRR register provide the following word of the descriptor. If extra read operations to the EEFC_FRR register are done after the last word of the descriptor has been returned, then the EEFC_FRR register value is 0 until the next valid command. Table 19-3. Flash Descriptor Definition Symbol Word Index Description FL_ID 0 Flash Interface Description FL_SIZE 1 Flash size in bytes FL_PAGE_SIZE 2 Page size in bytes FL_NB_PLANE 3 Number of planes. FL_PLANE[0] 4 Number of bytes in the first plane. 4 + FL_NB_PLANE - 1 Number of bytes in the last plane. FL_NB_LOCK 4 + FL_NB_PLANE Number of lock bits. A bit is associated with a lock region. A lock bit is used to prevent write or erase operations in the lock region. FL_LOCK[0] 4 + FL_NB_PLANE + 1 Number of bytes in the first lock region. ... FL_PLANE[FL_NB_PLANE-1] ... SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 335 19.4.3.2 Write Commands Several commands can be used to program the Flash. Flash technology requires that an erase be done before programming. The full memory plane can be erased at the same time, or several pages can be erased at the same time (refer to Figure 19-7, "Example of Partial Page Programming", and the paragraph below the figure.). Also, a page erase can be automatically done before a page write using EWP or EWPL commands. After programming, the page (the whole lock region) can be locked to prevent miscellaneous write or erase sequences. The lock bit can be automatically set after page programming using WPL or EWPL commands. Data to be written are stored in an internal latch buffer. The size of the latch buffer corresponds to the page size. The latch buffer wraps around within the internal memory area address space and is repeated as many times as the number of pages within this address space. Note: Writing of 8-bit and 16-bit data is not allowed and may lead to unpredictable data corruption. Write operations are performed in a number of wait states equal to the number of wait states for read operations. Data are written to the latch buffer before the programming command is written to the Flash Command Register EEFC_FCR. The sequence is as follows: Write the full page, at any page address, within the internal memory area address space. Programming starts as soon as the page number and the programming command are written to the Flash Command Register. The FRDY bit in the Flash Programming Status Register (EEFC_FSR) is automatically cleared. When programming is completed, the FRDY bit in the Flash Programming Status Register (EEFC_FSR) rises. If an interrupt has been enabled by setting the bit FRDY in EEFC_FMR, the corresponding interrupt line of the NVIC is activated. Two errors can be detected in the EEFC_FSR register after a programming sequence: Command Error: a bad keyword has been written in the EEFC_FCR register. Lock Error: the page to be programmed belongs to a locked region. A command must be previously run to unlock the corresponding region. Flash Error: at the end of the programming, the WriteVerify test of the Flash memory has failed. By using the WP command, a page can be programmed in several steps if it has been erased before (see Figure 19-7 below). This mode is called Partial Programming. The Partial Programming mode works only with 32-bit (or higher) boundaries. It cannot be used with boundaries lower than 32 bits (8 or 16-bit for example). To write a single byte or a 16-bit halfword, the remaining byte of the 32bit word must be filled with 0xFF, then the 32-bit word must be written to Flash buffer. Note: If several 32-bit words need to be programmed, they must be written in ascending order to Flash buffer before executing the write page command. If a write page command is executed after writing each single 32-bit word, the write order of the word sequence does not matter. After any power-on sequence, the Flash memory internal latch buffer is not initialized. Thus the latch buffer must be initialized by writing the part-select to be programmed with user data and the remaining of the buffer must be written with logical 1. This action is not required for the next partial programming sequence because the latch buffer is automatically cleared after programming the page. 336 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Figure 19-7. Example of Partial Page Programming 32-bit wide X words X words FF FF FF FF FF FF FF FF FF FF X words FF FF FF X words FF FF 32-bit wide FF FF FF FF FF FF FF FF FF FF FF FF FF FF ... FF FF FF FF FF CA FE FF FF CA FE CA FE FF FF ... FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF ... FF FF FF FF FF FF FF FF FF FF FF FF FF ... Step 1. Erase All Flash So Page Y erased ... ... ... ... 32-bit wide FF FF FF FF FF ... FF FF FF FF FF FF FF FF FF FF CA FE CA FE CA CA FE FE CA FE CA FE FF FF DE CA FF FF FF FF DE CA DE CA FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF CA FE CA CA FE FE ... Step 2. Programming of the second part of Page Y ... DE CA DE CA DE CA ... FF FF FF FF FF FF Step 3. Programming of the third part of Page Y SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 337 19.4.3.3 Erase Commands Erase commands are allowed only on unlocked regions. Depending on the Flash memory, several commands can be used to erase the Flash: Erase all memory (EA): all memory is erased. The processor must not fetch code from the Flash memory. Erase pages (EPA): 4, 8, 16 or 32 pages are erased in the memory plane. The first page to be erased is specified in the FARG[15:2] field of the MC_FCR register. The first page number must be modulo 4, 8,16 or 32 according to the number of pages to erase at the same time. The processor must not fetch code from the Flash memory. Erase Sector (ES): A full memory sector is erased. Sector size depends on the Flash memory. FARG must be set with a page number that is in the sector to be erased. The processor must not fetch code from the Flash memory. The erase sequence is: Erase starts as soon as one of the erase commands and the FARG field are written in the Flash Command Register. ̶ For the EPA command, the 2 lowest bits of the FARG field define the number of pages to be erased (FARG[1:0]): Table 19-4. FARG[1:0] FARG Field for EPA command: Number of pages to be erased with EPA command 0 4 pages 1 8 pages 2 16 pages 3 32 pages When the programming completes, the FRDY bit in the Flash Programming Status Register (EEFC_FSR) rises. If an interrupt has been enabled by setting the FRDY bit in EEFC_FMR, the interrupt line of the NVIC is activated. Two errors can be detected in the EEFC_FSR register after a programming sequence: Command Error: a bad keyword has been written in the EEFC_FCR register. Lock Error: at least one page to be erased belongs to a locked region. The erase command has been refused, no page has been erased. A command must be run previously to unlock the corresponding region. Flash Error: at the end of the programming, the EraseVerify test of the Flash memory has failed. 19.4.3.4 Lock Bit Protection Lock bits are associated with several pages in the embedded Flash memory plane. This defines lock regions in the embedded Flash memory plane. They prevent writing/erasing protected pages. The lock sequence is: The Set Lock command (SLB) and a page number to be protected are written in the Flash Command Register. When the locking completes, the FRDY bit in the Flash Programming Status Register (EEFC_FSR) rises. If an interrupt has been enabled by setting the FRDY bit in EEFC_FMR, the interrupt line of the NVIC is activated. The result of the SLB command can be checked running a GLB (Get Lock Bit) command. Note: The value of the FARG argument passed together with SLB command must not exceed the higher lock bit index available in the product. One error can be detected in the EEFC_FSR register after a programming sequence: 338 Command Error: a bad keyword has been written in the EEFC_FCR register. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Flash Error: at the end of the programming, the EraseVerify or WriteVerify test of the Flash memory has failed. It is possible to clear lock bits previously set. Then the locked region can be erased or programmed. The unlock sequence is: The Clear Lock command (CLB) and a page number to be unprotected are written in the Flash Command Register. When the unlock completes, the FRDY bit in the Flash Programming Status Register (EEFC_FSR) rises. If an interrupt has been enabled by setting the FRDY bit in EEFC_FMR, the interrupt line of the NVIC is activated. Note: The value of the FARG argument passed together with CLB command must not exceed the higher lock bit index available in the product. One error can be detected in the EEFC_FSR register after a programming sequence: Command Error: a bad keyword has been written in the EEFC_FCR register. Flash Error: at the end of the programming, the EraseVerify or WriteVerify test of the Flash memory has failed. The status of lock bits can be returned by the Enhanced Embedded Flash Controller (EEFC). The Get Lock Bit status sequence is: The Get Lock Bit command (GLB) is written in the Flash Command Register, FARG field is meaningless. Lock bits can be read by the software application in the EEFC_FRR register. The first word read corresponds to the 32 first lock bits, next reads providing the next 32 lock bits as long as it is meaningful. Extra reads to the EEFC_FRR register return 0. For example, if the third bit of the first word read in the EEFC_FRR is set, then the third lock region is locked. One error can be detected in the EEFC_FSR register after a programming sequence: Command Error: a bad keyword has been written in the EEFC_FCR register. Flash Error: at the end of the programming, the EraseVerify or WriteVerify test of the Flash memory has failed. Note: Access to the Flash in read is permitted when a set, clear or get lock bit command is performed. 19.4.3.5 GPNVM Bit GPNVM bits do not interfere with the embedded Flash memory plane. Refer to specific product details for information on GPNVM bit action. The set GPNVM bit sequence is: Start the Set GPNVM Bit command (SGPB) by writing the Flash Command Register with the SGPB command and the number of the GPNVM bit to be set. When the GPNVM bit is set, the bit FRDY in the Flash Programming Status Register (EEFC_FSR) rises. If an interrupt was enabled by setting the FRDY bit in EEFC_FMR, the interrupt line of the NVIC is activated. The result of the SGPB command can be checked by running a GGPB (Get GPNVM Bit) command. Note: The value of the FARG argument passed together with SGPB command must not exceed the higher GPNVM index available in the product. Flash Data Content is not altered if FARG exceeds the limit. Command Error is detected only if FARG is greater than 8. One error can be detected in the EEFC_FSR register after a programming sequence: Command Error: a bad keyword has been written in the EEFC_FCR register. Flash Error: at the end of the programming, the EraseVerify or WriteVerify test of the Flash memory has failed. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 339 It is possible to clear GPNVM bits previously set. The clear GPNVM bit sequence is: Start the Clear GPNVM Bit command (CGPB) by writing the Flash Command Register with CGPB and the number of the GPNVM bit to be cleared. When the clear completes, the FRDY bit in the Flash Programming Status Register (EEFC_FSR) rises. If an interrupt has been enabled by setting the FRDY bit in EEFC_FMR, the interrupt line of the NVIC is activated. Note: The value of the FARG argument passed together with CGPB command must not exceed the higher GPNVM index available in the product. Flash Data Content is not altered if FARG exceeds the limit. Command Error is detected only if FARG is greater than 8. One error can be detected in the EEFC_FSR register after a programming sequence: Command Error: a bad keyword has been written in the EEFC_FCR register. Flash Error: at the end of the programming, the EraseVerify or WriteVerify test of the Flash memory has failed. The status of GPNVM bits can be returned by the Enhanced Embedded Flash Controller (EEFC). The sequence is: Start the Get GPNVM bit command by writing the Flash Command Register with GGPB. The FARG field is meaningless. GPNVM bits can be read by the software application in the EEFC_FRR register. The first word read corresponds to the 32 first GPNVM bits, following reads provide the next 32 GPNVM bits as long as it is meaningful. Extra reads to the EEFC_FRR register return 0. For example, if the third bit of the first word read in the EEFC_FRR is set, then the third GPNVM bit is active. One error can be detected in the EEFC_FSR register after a programming sequence: Note: Command Error: a bad keyword has been written in the EEFC_FCR register. Access to the Flash in read is permitted when a set, clear or get GPNVM bit command is performed. 19.4.3.6 Calibration Bit Calibration bits do not interfere with the embedded Flash memory plane. It is impossible to modify the calibration bits. The status of calibration bits can be returned by the Enhanced Embedded Flash Controller (EEFC). The sequence is: Issue the Get CALIB Bit command by writing the Flash Command Register with GCALB (see Table 19-2). The FARG field is meaningless. Calibration bits can be read by the software application in the EEFC_FRR register. The first word read corresponds to the 32 first calibration bits, following reads provide the next 32 calibration bits as long as it is meaningful. Extra reads to the EEFC_FRR register return 0. The 12/8/4 MHz Fast RC oscillator is calibrated in production. This calibration can be read through the Get CALIB Bit command. The table below shows the bit implementation for each frequency: Table 19-5. Calibration Bit Indexes RC Calibration Frequency EEFC_FRR Bits 8 MHz output [28 - 22] 4 MHz output [38 - 32] The RC calibration for the 12 MHz is set to ‘1000000’. 340 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 19.4.3.7 Security Bit Protection When the security is enabled, access to the Flash, either through the JTAG/SWD interface or through the Fast Flash Programming Interface, is forbidden. This ensures the confidentiality of the code programmed in the Flash. The security bit is GPNVM0. Disabling the security bit can only be achieved by asserting the ERASE pin at 1, and after a full Flash erase is performed. When the security bit is deactivated, all accesses to the Flash are permitted. 19.4.3.8 Unique Identifier Each part is programmed with a 2*512-bytes Unique Identifier. It can be used to generate keys for example. To read the Unique Identifier the sequence is: Send the Start Read unique Identifier command (STUI) by writing the Flash Command Register with the STUI command. When the Unique Identifier is ready to be read, the FRDY bit in the Flash Programming Status Register (EEFC_FSR) falls. The Unique Identifier is located in the first 128 bits of the Flash memory mapping, thus, at the address 0x00400000-0x004003FF. To stop the Unique Identifier mode, the user needs to send the Stop Read unique Identifier command (SPUI) by writing the Flash Command Register with the SPUI command. When the Stop read Unique Identifier command (SPUI) has been performed, the FRDY bit in the Flash Programming Status Register (EEFC_FSR) rises. If an interrupt was enabled by setting the FRDY bit in EEFC_FMR, the interrupt line of the NVIC is activated. Note that during the sequence, the software can not run out of Flash (or the second plane in case of dual plane). 19.4.3.9 User Signature Each part contains a User Signature of 512-bytes. It can be used by the user for storage. Read, write and erase of this area is allowed. To read the User Signature, the sequence is as follows: Send the Start Read User Signature command (STUS) by writing the Flash Command Register with the STUS command. When the User Signature is ready to be read, the FRDY bit in the Flash Programming Status Register (EEFC_FSR) falls. The User Signature is located in the first 512 bytes of the Flash memory mapping, thus, at the address 0x00400000-0x004001FF. To stop the User Signature mode, the user needs to send the Stop Read User Signature command (SPUS) by writing the Flash Command Register with the SPUS command. When the Stop Read User Signature command (SPUI) has been performed, the FRDY bit in the Flash Programming Status Register (EEFC_FSR) rises. If an interrupt was enabled by setting the FRDY bit in EEFC_FMR, the interrupt line of the NVIC is activated. Note that during the sequence, the software can not run out of Flash (or the second plane, in case of dual plane). One error can be detected in the EEFC_FSR register after this sequence: Command Error: a bad keyword has been written in the EEFC_FCR register. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 341 To write the User Signature, the sequence is: Write the full page, at any page address, within the internal memory area address space. Send the Write User Signature command (WUS) by writing the Flash Command Register with the WUS command. When programming is completed, the FRDY bit in the Flash Programming Status Register (EEFC_FSR) rises. If an interrupt has been enabled by setting the FRDY bit in EEFC_FMR, the corresponding interrupt line of the NVIC is activated. Two errors can be detected in the EEFC_FSR register after this sequence: Command Error: a bad keyword has been written in the EEFC_FCR register. Flash Error: at the end of the programming, the WriteVerify test of the Flash memory has failed. To erase the User Signature, the sequence is: Send the Erase User Signature command (EUS) by writing the Flash Command Register with the EUS command. When programming is completed, the FRDY bit in the Flash Programming Status Register (EEFC_FSR) rises. If an interrupt has been enabled by setting the FRDY bit in EEFC_FMR, the corresponding interrupt line of the NVIC is activated. Two errors can be detected in the EEFC_FSR register after this sequence: 342 Command Error: a bad keyword has been written in the EEFC_FCR register. Flash Error: at the end of the programming, the EraseVerify test of the Flash memory has failed. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 19.5 Enhanced Embedded Flash Controller (EEFC) User Interface The User Interface of the Enhanced Embedded Flash Controller (EEFC) is integrated within the System Controller with base address 0x400E0800. Table 19-6. Register Mapping Offset Register Name Access Reset State 0x00 EEFC Flash Mode Register EEFC_FMR Read-write 0x0400_0000 0x04 EEFC Flash Command Register EEFC_FCR Write-only – 0x08 EEFC Flash Status Register EEFC_FSR Read-only 0x00000001 0x0C EEFC Flash Result Register EEFC_FRR Read-only 0x0 0x10 Reserved – – – SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 343 19.5.1 EEFC Flash Mode Register Name: EEFC_FMR Address: 0x400E0A00 Access: Read-write Offset: 0x00 31 30 29 28 27 26 25 24 – – – – – CLOE – FAM 23 22 21 20 19 18 17 16 – – – – – – – SCOD 15 14 13 12 11 10 9 8 – – – – 7 6 5 4 3 2 1 0 – – – – – – – FRDY FWS • FRDY: Ready Interrupt Enable 0: Flash Ready does not generate an interrupt. 1: Flash Ready (to accept a new command) generates an interrupt. • FWS: Flash Wait State This field defines the number of wait states for read and write operations: Number of cycles for Read/Write operations = FWS+1 • SCOD: Sequential Code Optimization Disable 0: The sequential code optimization is enabled. 1: The sequential code optimization is disabled. No Flash read should be done during change of this register. • FAM: Flash Access Mode 0: 128-bit access in read Mode only, to enhance access speed. 1: 64-bit access in read Mode only, to enhance power consumption. No Flash read should be done during change of this register. • CLOE: Code Loops Optimization Enable 0: The opcode loops optimization is disabled. 1: The opcode loops optimization is enabled. No Flash read should be done during change of this register. 344 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 19.5.2 EEFC Flash Command Register Name: EEFC_FCR Address: 0x400E0A04 Access: Write-only Offset: 0x04 31 30 29 28 27 26 25 24 19 18 17 16 11 10 9 8 3 2 1 0 FKEY 23 22 21 20 FARG 15 14 13 12 FARG 7 6 5 4 FCMD • FCMD: Flash Command Value Name Description 0x00 GETD Get Flash Descriptor 0x01 WP Write page 0x02 WPL Write page and lock 0x03 EWP Erase page and write page 0x04 EWPL Erase page and write page then lock 0x05 EA Erase all 0x07 EPA Erase Pages 0x08 SLB Set Lock Bit 0x09 CLB Clear Lock Bit 0x0A GLB Get Lock Bit 0x0B SGPB Set GPNVM Bit 0x0C CGPB Clear GPNVM Bit 0x0D GGPB Get GPNVM Bit 0x0E STUI Start Read Unique Identifier 0x0F SPUI Stop Read Unique Identifier 0x10 GCALB Get CALIB Bit 0x11 ES Erase Sector 0x12 WUS Write User Signature 0x13 EUS Erase User Signature 0x14 STUS Start Read User Signature 0x15 SPUS Stop Read User Signature SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 345 • FARG: Flash Command Argument Erase all command Field is meaningless. Erase sector command FARG must be set with a page number that is in the sector to be erased. FARG[1:0] defines the number of pages to be erased. The page number from which the erase will start is defined as follows: FARG[1:0]=0, start page = 4*FARG[15:2] Erase pages command FARG[1:0]=1, start page = 8*FARG[15:3], FARG[2] undefined FARG[1:0]=2, start page = 16*FARG[15:4], FARG[3:2] undefined FARG[1:0]=3, start page = 32*FARG[15:5], FARG[4:2] undefined Note: undefined bit must be written to 0. Refer to Table 19-4 on page 338 Programming command FARG defines the page number to be programmed. Lock command FARG defines the page number to be locked. GPNVM command FARG defines the GPNVM number. • FKEY: Flash Writing Protection Key Value Name 0x5A PASSWD 346 Description The 0x5A value enables 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. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 19.5.3 EEFC Flash Status Register Name: EEFC_FSR Address: 0x400E0A08 Access: Read-only Offset: 0x08 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 6 5 4 3 2 1 0 – – – – FLERR FLOCKE FCMDE FRDY • FRDY: Flash Ready Status 0: The Enhanced Embedded Flash Controller (EEFC) is busy. 1: The Enhanced Embedded Flash Controller (EEFC) is ready to start a new command. When it is set, this flags triggers an interrupt if the FRDY flag is set in the EEFC_FMR register. This flag is automatically cleared when the Enhanced Embedded Flash Controller (EEFC) is busy. • FCMDE: Flash Command Error Status 0: No invalid commands and no bad keywords were written in the Flash Mode Register EEFC_FMR. 1: An invalid command and/or a bad keyword was/were written in the Flash Mode Register EEFC_FMR. This flag is automatically cleared when EEFC_FSR is read or EEFC_FCR is written. • FLOCKE: Flash Lock Error Status 0: No programming/erase of at least one locked region has happened since the last read of EEFC_FSR. 1: Programming/erase of at least one locked region has happened since the last read of EEFC_FSR. This flag is automatically cleared when EEFC_FSR is read or EEFC_FCR is written. • FLERR: Flash Error Status 0: No Flash Memory error occurred at the end of programming (EraseVerify or WriteVerify test has passed). 1: A Flash Memory error occurred at the end of programming (EraseVerify or WriteVerify test has failed). SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 347 19.5.4 EEFC Flash Result Register Name: EEFC_FRR Address: 0x400E0A0C Access: Read-only Offset: 0x0C 31 30 29 28 27 26 25 24 19 18 17 16 11 10 9 8 3 2 1 0 FVALUE 23 22 21 20 FVALUE 15 14 13 12 FVALUE 7 6 5 4 FVALUE • FVALUE: Flash Result Value The result of a Flash command is returned in this register. If the size of the result is greater than 32 bits, then the next resulting value is accessible at the next register read. 348 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 20. Fast Flash Programming Interface (FFPI) 20.1 Description The Fast Flash Programming Interface (FFPI) provides parallel high-volume programming using a standard gang programmer. The parallel interface is fully handshaked and the device is considered to be a standard EEPROM. Additionally, the parallel protocol offers an optimized access to all the embedded Flash functionalities. Although the Fast Flash Programming Mode is a dedicated mode for high volume programming, this mode is not designed for in-situ programming. 20.2 Embedded Characteristics 20.3 Programming Mode for High-volume Flash Programming Using Gang Programmer ̶ Offers Read and Write Access to the Flash Memory Plane ̶ Enables Control of Lock Bits and General-purpose NVM Bits ̶ Enables Security Bit Activation ̶ Disabled Once Security Bit is Set Parallel Fast Flash Programming Interface ̶ Provides an 16-bit Parallel Interface to Program the Embedded Flash ̶ Full Handshake Protocol Parallel Fast Flash Programming 20.3.1 Device Configuration In Fast Flash Programming Mode, the device is in a specific test mode. Only a certain set of pins is significant. The rest of the PIOs are used as inputs with a pull-up. The crystal oscillator is in bypass mode. Other pins must be left unconnected. Figure 20-1. SAM4NxB/C Parallel Programming Interface VDDIO VDDIO VDDIO TST PGMEN0 PGMEN1 VDDCORE NCMD RDY PGMNCMD PGMRDY NOE PGMNOE NVALID VDDIO VDDPLL GND PGMNVALID MODE[3:0] PGMM[3:0] DATA[15:0] PGMD[15:0] 0 - 50MHz XIN SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 349 Table 20-1. Signal Description List Signal Name Function Type Active Level Comments Power VDDIO I/O Lines Power Supply Power VDDCORE Core Power Supply Power VDDPLL PLL Power Supply Power GND Ground Ground Clocks Main Clock Input. This input can be tied to GND. In this case, the device is clocked by the internal RC oscillator. XIN Input 32 KHz to 50 MHz Test TST Test Mode Select Input High Must be connected to VDDIO PGMEN0 Test Mode Select Input High Must be connected to VDDIO PGMEN1 Test Mode Select Input High Must be connected to VDDIO PGMEN2 Test Mode Select Input Low Must be connected to GND Input Low Pulled-up input at reset Output High Pulled-up input at reset Input Low Pulled-up input at reset Output Low Pulled-up input at reset PIO PGMNCMD Valid command available 0: Device is busy PGMRDY 1: Device is ready for a new command PGMNOE Output Enable (active high) 0: DATA[15:0] is in input mode PGMNVALID 1: DATA[15:0] is in output mode PGMM[3:0] Specifies DATA type (see Table 20-2) PGMD[15:0] Bi-directional data bus Input Pulled-up input at reset Input/Output Pulled-up input at reset 20.3.2 Signal Names Depending on the MODE settings, DATA is latched in different internal registers. Table 20-2. Mode Coding MODE[3:0] Symbol Data 0000 CMDE Command Register 0001 ADDR0 Address Register LSBs 0010 ADDR1 0101 DATA Data Register Default IDLE No register When MODE is equal to CMDE, then a new command (strobed on DATA[15:0] signals) is stored in the command register. 350 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Table 20-3. Command Bit Coding DATA[15:0] Symbol Command Executed 0x0011 READ Read Flash 0x0012 WP Write Page Flash 0x0022 WPL Write Page and Lock Flash 0x0032 EWP Erase Page and Write Page 0x0042 EWPL Erase Page and Write Page then Lock 0x0013 EA Erase All 0x0014 SLB Set Lock Bit 0x0024 CLB Clear Lock Bit 0x0015 GLB Get Lock Bit 0x0034 SGPB Set General Purpose NVM bit 0x0044 CGPB Clear General Purpose NVM bit 0x0025 GGPB Get General Purpose NVM bit 0x0054 SSE Set Security Bit 0x0035 GSE Get Security Bit 0x001F WRAM Write Memory 0x001E GVE Get Version 20.3.3 Entering Programming Mode The following algorithm puts the device in Parallel Programming Mode: Apply the supplies as described in Table 20-1. Apply XIN clock within TPOR_RESET if an external clock is available. Wait for TPOR_RESET Start a read or write handshaking. Note: After reset, the device is clocked by the internal RC oscillator. Before clearing RDY signal, if an external clock ( > 32 kHz) is connected to XIN, then the device switches on the external clock. Else, XIN input is not considered. A higher frequency on XIN speeds up the programmer handshake. 20.3.4 Programmer Handshaking An handshake is defined for read and write operations. When the device is ready to start a new operation (RDY signal set), the programmer starts the handshake by clearing the NCMD signal. The handshaking is achieved once NCMD signal is high and RDY is high. 20.3.4.1 Write Handshaking For details on the write handshaking sequence, refer to Figure 20-2 and Table 20-4. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 351 Figure 20-2. Parallel Programming Timing, Write Sequence NCMD 2 4 3 RDY 5 NOE NVALID DATA[15:0] 1 MODE[3:0] Table 20-4. Write Handshake Step Programmer Action Device Action Data I/O 1 Sets MODE and DATA signals Waits for NCMD low Input 2 Clears NCMD signal Latches MODE and DATA Input 3 Waits for RDY low Clears RDY signal Input 4 Releases MODE and DATA signals Executes command and polls NCMD high Input 5 Sets NCMD signal Executes command and polls NCMD high Input 6 Waits for RDY high Sets RDY Input 20.3.4.2 Read Handshaking For details on the read handshaking sequence, refer to Figure 20-3 and Table 20-5. Figure 20-3. Parallel Programming Timing, Read Sequence NCMD 12 2 3 RDY 13 NOE 9 5 NVALID 6 4 Adress IN DATA[15:0] 1 MODE[3:0] 352 11 7 ADDR SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Z 8 Data OUT 10 X IN Table 20-5. Read Handshake Step Programmer Action Device Action DATA I/O 1 Sets MODE and DATA signals Waits for NCMD low Input 2 Clears NCMD signal Latch MODE and DATA Input 3 Waits for RDY low Clears RDY signal Input 4 Sets DATA signal in tristate Waits for NOE Low Input 5 Clears NOE signal 6 Waits for NVALID low Tristate 7 Sets DATA bus in output mode and outputs the flash contents. Output Clears NVALID signal Output Waits for NOE high Output 8 Reads value on DATA Bus 9 Sets NOE signal 10 Waits for NVALID high Sets DATA bus in input mode X 11 Sets DATA in output mode Sets NVALID signal Input 12 Sets NCMD signal Waits for NCMD high Input 13 Waits for RDY high Sets RDY signal Input Output 20.3.5 Device Operations Several commands on the Flash memory are available. These commands are summarized in Table 20-3 on page 351. Each command is driven by the programmer through the parallel interface running several read/write handshaking sequences. When a new command is executed, the previous one is automatically achieved. Thus, chaining a read command after a write automatically flushes the load buffer in the Flash. 20.3.5.1 Flash Read Command This command is used to read the contents of the Flash memory. The read command can start at any valid address in the memory plane and is optimized for consecutive reads. Read handshaking can be chained; an internal address buffer is automatically increased. Table 20-6. Read Command Step Handshake Sequence MODE[3:0] DATA[15:0] 1 Write handshaking CMDE READ 2 Write handshaking ADDR0 Memory Address LSB 3 Write handshaking ADDR1 Memory Address 4 Read handshaking DATA *Memory Address++ 5 Read handshaking DATA *Memory Address++ ... ... ... ... n Write handshaking ADDR0 Memory Address LSB n+1 Write handshaking ADDR1 Memory Address n+2 Read handshaking DATA *Memory Address++ n+3 Read handshaking DATA *Memory Address++ ... ... ... ... SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 353 20.3.5.2 Flash Write Command This command is used to write the Flash contents. The Flash memory plane is organized into several pages. Data to be written are stored in a load buffer that corresponds to a Flash memory page. The load buffer is automatically flushed to the Flash: before access to any page other than the current one when a new command is validated (MODE = CMDE) The Write Page command (WP) is optimized for consecutive writes. Write handshaking can be chained; an internal address buffer is automatically increased. Table 20-7. Write Command Step Handshake Sequence MODE[3:0] DATA[15:0] 1 Write handshaking CMDE WP or WPL or EWP or EWPL 2 Write handshaking ADDR0 Memory Address LSB 3 Write handshaking ADDR1 Memory Address 4 Write handshaking DATA *Memory Address++ 5 Write handshaking DATA *Memory Address++ ... ... ... ... n Write handshaking ADDR0 Memory Address LSB n+1 Write handshaking ADDR1 Memory Address n+2 Write handshaking DATA *Memory Address++ n+3 Write handshaking DATA *Memory Address++ ... ... ... ... The Flash command Write Page and Lock (WPL) is equivalent to the Flash Write Command. However, the lock bit is automatically set at the end of the Flash write operation. As a lock region is composed of several pages, the programmer writes to the first pages of the lock region using Flash write commands and writes to the last page of the lock region using a Flash write and lock command. The Flash command Erase Page and Write (EWP) is equivalent to the Flash Write Command. However, before programming the load buffer, the page is erased. The Flash command Erase Page and Write the Lock (EWPL) combines EWP and WPL commands. 20.3.5.3 Flash Full Erase Command This command is used to erase the Flash memory planes. All lock regions must be unlocked before the Full Erase command by using the CLB command. Otherwise, the erase command is aborted and no page is erased. Table 20-8. 354 Full Erase Command Step Handshake Sequence MODE[3:0] DATA[15:0] 1 Write handshaking CMDE EA 2 Write handshaking DATA 0 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 20.3.5.4 Flash Lock Commands Lock bits can be set using WPL or EWPL commands. They can also be set by using the Set Lock command (SLB). With this command, several lock bits can be activated. A Bit Mask is provided as argument to the command. When bit 0 of the bit mask is set, then the first lock bit is activated. In the same way, the Clear Lock command (CLB) is used to clear lock bits. Table 20-9. Set and Clear Lock Bit Command Step Handshake Sequence MODE[3:0] DATA[15:0] 1 Write handshaking CMDE SLB or CLB 2 Write handshaking DATA Bit Mask Lock bits can be read using Get Lock Bit command (GLB). The nth lock bit is active when the bit n of the bit mask is set.. Table 20-10. Get Lock Bit Command Step Handshake Sequence MODE[3:0] DATA[15:0] 1 Write handshaking CMDE GLB Lock Bit Mask Status 2 Read handshaking DATA 0 = Lock bit is cleared 1 = Lock bit is set 20.3.5.5 Flash General-purpose NVM Commands General-purpose NVM bits (GP NVM bits) can be set using the Set GPNVM command (SGPB). This command also activates GP NVM bits. A bit mask is provided as argument to the command. When bit 0 of the bit mask is set, then the first GP NVM bit is activated. In the same way, the Clear GPNVM command (CGPB) is used to clear general-purpose NVM bits. The generalpurpose NVM bit is deactivated when the corresponding bit in the pattern value is set to 1. Table 20-11. Set/Clear GP NVM Command Step Handshake Sequence MODE[3:0] DATA[15:0] 1 Write handshaking CMDE SGPB or CGPB 2 Write handshaking DATA GP NVM bit pattern value General-purpose NVM bits can be read using the Get GPNVM Bit command (GGPB). The nth GP NVM bit is active when bit n of the bit mask is set.. Table 20-12. Get GP NVM Bit Command Step Handshake Sequence MODE[3:0] DATA[15:0] 1 Write handshaking CMDE GGPB GP NVM Bit Mask Status 2 Read handshaking DATA 0 = GP NVM bit is cleared 1 = GP NVM bit is set 20.3.5.6 Flash Security Bit Command A security bit can be set using the Set Security Bit command (SSE). Once the security bit is active, the Fast Flash programming is disabled. No other command can be run. An event on the Erase pin can erase the security bit once the contents of the Flash have been erased. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 355 Table 20-13. Set Security Bit Command Step Handshake Sequence MODE[3:0] DATA[15:0] 1 Write handshaking CMDE SSE 2 Write handshaking DATA 0 Once the security bit is set, it is not possible to access FFPI. The only way to erase the security bit is to erase the Flash. In order to erase the Flash, the user must perform the following: Power-off the chip Power-on the chip with TST = 0 Assert Erase during a period of more than 220 ms Power-off the chip Then it is possible to return to FFPI mode and check that Flash is erased. 20.3.5.7 Memory Write Command This command is used to perform a write access to any memory location. The Memory Write command (WRAM) is optimized for consecutive writes. Write handshaking can be chained; an internal address buffer is automatically increased. Table 20-14. Write Command Step Handshake Sequence MODE[3:0] DATA[15:0] 1 Write handshaking CMDE WRAM 2 Write handshaking ADDR0 Memory Address LSB 3 Write handshaking ADDR1 Memory Address 4 Write handshaking DATA *Memory Address++ 5 Write handshaking DATA *Memory Address++ ... ... ... ... n Write handshaking ADDR0 Memory Address LSB n+1 Write handshaking ADDR1 Memory Address n+2 Write handshaking DATA *Memory Address++ n+3 Write handshaking DATA *Memory Address++ ... ... ... ... 20.3.5.8 Get Version Command The Get Version (GVE) command retrieves the version of the FFPI interface. Table 20-15. 356 Get Version Command Step Handshake Sequence MODE[3:0] DATA[15:0] 1 Write handshaking CMDE GVE 2 Read handshaking DATA Version SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Figure 20-4. Serial Programing VDDIO VDDIO VDDIO TST PGMEN0 PGMEN1 VDDCORE VDDIO TDI TDO VDDPLL TMS VDDFLASH TCK GND 0-50MHz XIN SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 357 21. SAM-BA Boot Program 21.1 Description The SAM-BA Boot Program integrates an array of programs permitting download and/or upload into the different memories of the product. 21.2 Hardware and Software Constraints SAM-BA Boot uses the first 2048 bytes of the SRAM for variables and stacks. The remaining available size can be used for user's code. UART0 requirements: None. Table 21-1. 21.3 Pins Driven during Boot Program Execution Peripheral Pin PIO Line UART0 URXD0 PA9 UART0 UTXD0 PA10 Flow Diagram The Boot Program implements the algorithm illustrated in Figure 21-1. Figure 21-1. Boot Program Algorithm Flow Diagram No Device Setup Character # received from UART0? Yes Run SAM-BA Monitor The SAM-BA Boot Program uses the internal 12 MHz RC oscillator as source clock for PLL. The MCK runs from PLL divided by 2. The core runs at 48 MHz. 21.4 Device Initialization The initialization sequence is the following: 1. 358 Stack setup 2. Set up the Embedded Flash Controller 3. Switch on internal 12 MHz RC oscillator 4. Configure PLL to run at 96 MHz 5. Switch MCK to run on PLL divided by 2 6. Configure UART0 7. Disable Watchdog 8. Wait for a character on UART0 9. Jump to SAM-BA monitor (see Section 21.5 “SAM-BA Monitor”) SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 21.5 SAM-BA Monitor Once the communication interface is identified, the monitor runs in an infinite loop waiting for different commands as shown in Table 21-2. Table 21-2. Commands Available through the SAM-BA Boot Command Action Argument(s) Example N Set Normal mode No argument N# T Set Terminal mode No argument T# O Write a byte Address, Value# O200001,CA# o Read a byte Address,# o200001,# H Write a half-word Address, Value# H200002,CAFE# h Read a half-word Address,# h200002,# W Write a word Address, Value# W200000,CAFEDECA# w Read a word Address,# w200000,# S Send a file Address,# S200000,# R Receive a file Address, NbOfBytes# R200000,1234# G Go Address# G200200# V Display version No argument V# Mode commands: ̶ Normal mode configures SAM-BA Monitor to send/receive data in binary format ̶ Terminal mode configures SAM-BA Monitor to send/receive data in ASCII format Write commands: Write a byte (O), a half-word (H) or a word (W) to the target ̶ Address: Address in hexadecimal ̶ Value: Byte, half-word or word to write in hexadecimal ̶ Read commands: Read a byte (o), a half-word (h) or a word (w) from the target ̶ Output: The byte, half-word or word read in hexadecimal following by ‘>’ Address: Address in hexadecimal ̶ Output: ‘>’ There is a time-out on this command which is reached when the prompt ‘>’ appears before the end of the command execution. Receive a file (R): Receive data into a file from a specified address ̶ ̶ Address: Address in hexadecimal ̶ ̶ ̶ Send a file (S): Send a file to a specified address Note: Output: ‘>’ Address: Address in hexadecimal NbOfBytes: Number of bytes in hexadecimal to receive Output: ‘>’ Go (G): Jump to a specified address and execute the code ̶ Address: Address to jump in hexadecimal ̶ Output: ‘>’ Get Version (V): Return the SAM-BA boot version ̶ Output: ‘>’ SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 359 21.5.1 UART0 Serial Port Communication is performed through the UART0 initialized to 115200 Baud, 8, n, 1. The Send and Receive File commands use the Xmodem protocol to communicate. Any terminal performing this protocol can be used to send the application file to the target. The size of the binary file to send depends on the SRAM size embedded in the product. In all cases, the size of the binary file must be lower than the SRAM size because the Xmodem protocol requires some SRAM memory to work. See Section 21.2 “Hardware and Software Constraints”. 21.5.2 Xmodem Protocol The Xmodem protocol supported is the 128-byte length block. This protocol uses a two-character CRC-16 to guarantee detection of a maximum bit error. Xmodem protocol with CRC is accurate provided both sender and receiver report successful transmission. Each block of the transfer looks like: <SOH><blk #><255-blk #><--128 data bytes--><checksum> in which: ̶ <SOH> = 01 hex ̶ <blk #> = binary number, starts at 01, increments by 1, and wraps 0FFH to 00H (not to 01) ̶ <255-blk #> = 1’s complement of the blk#. ̶ <checksum> = 2 bytes CRC16 Figure 21-2 shows a transmission using this protocol. Figure 21-2. Xmodem Transfer Example Host Device C SOH 01 FE Data[128] CRC CRC ACK SOH 02 FD Data[128] CRC CRC ACK SOH 03 FC Data[100] CRC CRC ACK EOT ACK 360 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 21.5.3 In Application Programming (IAP) Feature The IAP feature is a function located in ROM that can be called by any software application. When called, this function sends the desired FLASH command to the EEFC and waits for the Flash to be ready (looping while the FRDY bit is not set in the EEFC_FSR). Since this function is executed from ROM, this allows Flash programming (such as sector write) to be done by code running in Flash. The IAP function entry point is retrieved by reading the NMI vector in ROM (0x00800008). This function takes one argument in parameter: the command to be sent to the EEFC. This function returns the value of the EEFC_FSR. IAP software code example: (unsigned int) (*IAP_Function)(unsigned long); void main (void){ unsigned unsigned unsigned unsigned long long long long FlashSectorNum = 200; // flash_cmd = 0; flash_status = 0; EFCIndex = 0; // 0:EEFC0, 1: EEFC1 /* Initialize the function pointer (retrieve function address from NMI vector) */ IAP_Function = ((unsigned long) (*)(unsigned long)) 0x00800008; /* Send your data to the sector here */ /* build the command to send to EEFC */ flash_cmd = (0x5A << 24) | (FlashSectorNum << 8) | AT91C_MC_FCMD_EWP; /* Call the IAP function with appropriate command */ flash_status = IAP_Function (EFCIndex, flash_cmd); } SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 361 22. Bus Matrix (MATRIX) 22.1 Description The Bus Matrix implements a multi-layer AHB that enables parallel access paths between multiple AHB masters and slaves in a system, which increases the overall bandwidth. Bus Matrix interconnects 3 AHB Masters to 4 AHB 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 user interface also provides a Chip Configuration User Interface with Registers that allow to support application specific features. 22.2 Embedded Characteristics 22.2.1 Matrix Masters The Bus Matrix of the SAM4N product manages 3 masters, which means that each master can perform an access concurrently with others, to an available slave. Each master has its own decoder, which is defined specifically for each master. In order to simplify the addressing, all the masters have the same decodings. Table 22-1. List of Bus Matrix Masters Master 0 Cortex-M4 Instruction/Data Master 1 Cortex-M4 System Master 2 Peripheral DMA Controller (PDC) 22.2.2 Matrix Slaves The Bus Matrix of the SAM4N product manages 4 slaves. Each slave has its own arbiter, allowing a different arbitration per slave. 362 Table 22-2. List of Bus Matrix Slaves Slave 0 Internal SRAM Slave 1 Internal ROM Slave 2 Internal Flash Slave 3 Peripheral Bridge SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 22.2.3 Master to Slave Access All the Masters can normally access all the Slaves. However, some paths do not make sense, for example allowing access from the Cortex-M4 S Bus to the Internal ROM. Thus, these paths are forbidden or simply not wired and shown as “-” in the following table. Table 22-3. SAM4N Master to Slave Access Masters Slaves 22.3 0 1 2 Cortex-M4 I/D Bus Cortex-M4 S Bus PDC 0 Internal SRAM - X X 1 Internal ROM X - X 2 Internal Flash X - - 3 Peripheral Bridge - X X Memory Mapping Bus Matrix provides one decoder for every AHB Master Interface. The decoder offers each AHB Master several memory mappings. In fact, depending on the product, each memory area may be assigned to several slaves. Booting at the same address while using different AHB slaves (i.e. internal ROM or internal Flash) becomes possible. 22.4 Special Bus Granting Techniques The Bus Matrix provides some speculative bus granting techniques in order to anticipate access requests from some masters. This mechanism allows to reduce latency at first accesses of a burst or single transfer. The bus granting mechanism allows to set a 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. 22.4.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. 22.4.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. 22.4.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 doesn’t change unless the user modifies it by a software action (field FIXED_DEFMSTR of the related MATRIX_SCFG). 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 allow to 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 allows to choose the default master type (no default, last access master, fixed default master) whereas the 4-bit FIXED_DEFMSTR field allows to choose a fixed default master provided that DEFMSTR_TYPE is set to fixed default master. Please refer to the Bus Matrix user interface description. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 363 22.5 Arbitration The Bus Matrix provides an arbitration mechanism that allows to reduce latency when conflict cases occur, basically when two or more masters try to access the same slave at the same time. One arbiter per AHB slave is provided, allowing to arbitrate each slave differently. The Bus Matrix provides to the user the possibility to choose between 2 arbitration types, and this for each slave: 1. Round-Robin Arbitration (the default) 2. Fixed Priority Arbitration This choice is given through the field ARBT of the Slave Configuration Registers (MATRIX_SCFG). Each algorithm may be complemented by selecting a default master configuration for each slave. When a re-arbitration has to be done, it is realized only under some specific conditions detailed in the following paragraph. 22.5.1 Arbitration Rules Each arbiter has the ability to arbitrate between two or more different master’s 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 (See Section 22.5.1.1 “Undefined Length Burst Arbitration” on page 364“). 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 (See Section 22.5.1.2 “Slot Cycle Limit Arbitration” on page 364). 22.5.1.1 Undefined Length Burst Arbitration In order to avoid too 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 for defined length burst transfer, which is selected between the following: 1. Infinite: no predicted end of burst is generated and therefore INCR burst transfer will never be broken. 2. Four beat bursts: predicted end of burst is generated at the end of each four beat boundary inside INCR transfer. 3. Eight beat bursts: predicted end of burst is generated at the end of each eight beat boundary inside INCR transfer. 4. 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 field ULBT of the Master Configuration Registers (MATRIX_MCFG). 22.5.1.2 Slot Cycle Limit Arbitration The Bus Matrix contains specific logic to break too 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 (MATRIX_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, half word or word transfer. 364 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 22.5.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’s 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 algorithm implemented: Round-Robin arbitration without default master Round-Robin arbitration with last access master Round-Robin arbitration with fixed default master 22.5.2.1 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. 22.5.2.2 Round-Robin arbitration with last access 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. In fact, at the end of the current transfer, if no other master request is pending, the slave remains connected to the last master that performs the access. Other non privileged masters will 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. 22.5.2.3 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. 22.5.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’s requests are active at the same time, the master with the highest priority number is serviced first. If two or more master’s 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 (MATRIX_PRAS and MATRIX_PRBS). SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 365 22.6 System I/O Configuration The System I/O Configuration register (CCFG_SYSIO) allows to configure some I/O lines in System I/O mode (such as JTAG, ERASE, etc...) or as general purpose I/O lines. Enabling or disabling the corresponding I/O lines in peripheral mode or in PIO mode (PIO_PER or PIO_PDR registers) in the PIO controller as no effect. However, the direction (input or output), pull-up, pull-down and other mode control is still managed by the PIO controller. 22.7 Write Protect Registers To prevent any single software error that may corrupt MATRIX behavior, the entire MATRIX address space from address offset 0x000 to 0x1FC can be write-protected by setting the WPEN bit in the MATRIX Write Protect Mode Register (MATRIX_WPMR). If a write access to anywhere in the MATRIX address space from address offset 0x000 to 0x1FC is detected, then the WPVS flag in the MATRIX Write Protect Status Register (MATRIX_WPSR) is set and the field WPVSRC indicates in which register the write access has been attempted. The WPVS flag is reset by writing the MATRIX Write Protect Mode Register (MATRIX_WPMR) with the appropriate access key WPKEY. 366 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 22.8 Bus Matrix (MATRIX) User Interface Table 22-4. Register Mapping Offset Register Name Access Reset 0x0000 Master Configuration Register 0 MATRIX_MCFG0 Read-write 0x00000000 0x0004 Master Configuration Register 1 MATRIX_MCFG1 Read-write 0x00000000 0x0008 Master Configuration Register 2 MATRIX_MCFG2 Read-write 0x00000000 – – – 0x000C - 0x003C Reserved 0x0040 Slave Configuration Register 0 MATRIX_SCFG0 Read-write 0x00010010 0x0044 Slave Configuration Register 1 MATRIX_SCFG1 Read-write 0x00050010 0x0048 Slave Configuration Register 2 MATRIX_SCFG2 Read-write 0x00000010 0x004C Slave Configuration Register 3 MATRIX_SCFG3 Read-write 0x00000010 – – – MATRIX_PRAS0 Read-write 0x00000000 – – – MATRIX_PRAS1 Read-write 0x00000000 – – – MATRIX_PRAS2 Read-write 0x00000000 – – – MATRIX_PRAS3 Read-write 0x00000000 – – – Read/Write 0x00000000 0x0050 - 0x007C Reserved 0x0080 Priority Register A for Slave 0 0x0084 Reserved 0x0088 Priority Register A for Slave 1 0x008C Reserved 0x0090 Priority Register A for Slave 2 0x0094 Reserved 0x0098 Priority Register A for Slave 3 0x009C - 0x0110 0x0114 Reserved System I/O Configuration register CCFG_SYSIO 0x0118- 0x011C Reserved – – – 0x0120 - 0x010C Reserved – – – 0x0110 - 0x01FC Reserved – – – SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 367 22.8.1 Bus Matrix Master Configuration Registers Name: MATRIX_MCFG0..MATRIX_MCFG2 Address: 0x400E0200 Access: Read-write 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 – 6 – 5 – 4 – 3 – 2 1 ULBT 0 • ULBT: Undefined Length Burst Type 0: Infinite Length Burst No predicted end of burst is generated and therefore INCR bursts coming from this master cannot be broken. 1: Single Access The undefined length burst is treated as a succession of single access allowing rearbitration at each beat of the INCR burst. 2: Four Beat Burst The undefined length burst is split into a 4-beat bursts allowing rearbitration at each 4-beat burst end. 3: Eight Beat Burst The undefined length burst is split into 8-beat bursts allowing rearbitration at each 8-beat burst end. 4: Sixteen Beat Burst The undefined length burst is split into 16-beat bursts allowing rearbitration at each 16-beat burst end. 368 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 22.8.2 Bus Matrix Slave Configuration Registers Name: MATRIX_SCFG0..MATRIX_SCFG3 Address: 0x400E0240 Access: Read-write 31 – 30 – 29 – 28 – 27 – 26 – 25 24 23 – 22 – 21 – 20 19 FIXED_DEFMSTR 18 17 16 DEFMSTR_TYPE 15 – 14 – 13 – 12 – 11 – 10 – 9 – 8 – 7 6 5 4 3 2 1 0 ARBT SLOT_CYCLE • SLOT_CYCLE: Maximum Number of Allowed Cycles for a Burst When the SLOT_CYCLE limit is reach for a burst it may be broken by another master trying to access this slave. This limit has been placed to avoid locking very slow slaves when very long bursts are used. This limit should not be very small though. An unreasonable small value will break every burst and the Bus Matrix will spend its time to arbitrate without performing any data transfer. 16 cycles is a reasonable value for SLOT_CYCLE. • DEFMSTR_TYPE: Default Master Type 0: No Default Master At the end of current slave access, if no other master request is pending, the slave is disconnected from all masters. This results in having 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 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 the one cycle latency when the last master re-tries access on 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 the one cycle latency when the fixed master re-tries access on the slave again. • 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. • ARBT: Arbitration Type 0: Round-Robin Arbitration 1: Fixed Priority Arbitration 2: Reserved 3: Reserved SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 369 22.8.3 Bus Matrix Priority Registers For Slaves Name: MATRIX_PRAS0..MATRIX_PRAS3 Address: 0x400E0280 [0], 0x400E0288 [1], 0x400E0290 [2], 0x400E0298 [3] Access: Read-write 31 – 30 – 29 – 28 – 27 – 26 – 25 – 24 – 23 – 22 – 21 – 20 – 19 – 18 – 17 – 16 – 15 – 14 – 13 12 11 – 10 – 9 7 – 6 – 5 3 – 2 – 1 M3PR 4 M1PR 8 M2PR 0 M0PR • MxPR: Master x Priority Fixed priority of Master x for accessing the selected slave. The higher the number, the higher the priority. 370 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 22.8.4 System I/O Configuration Register Name: CCFG_SYSIO Address: 0x400E0314 Access Read-write Reset: 0x0000_0000 31 – 30 – 29 – 28 – 27 – 26 – 25 – 24 – 23 – 22 – 21 – 20 – 19 – 18 – 17 – 16 – 15 – 14 – 13 – 12 SYSIO12 11 – 10 – 9 – 8 – 7 SYSIO7 6 SYSIO6 5 SYSIO5 4 SYSIO4 3 – 2 – 1 – 0 – • SYSIO4: PB4 or TDI Assignment 0 = TDI function selected. 1 = PB4 function selected. • SYSIO5: PB5 or TDO/TRACESWO Assignment 0 = TDO/TRACESWO function selected. 1 = PB5 function selected. • SYSIO6: PB6 or TMS/SWDIO Assignment 0 = TMS/SWDIO function selected. 1 = PB6 function selected. • SYSIO7: PB7 or TCK/SWCLK Assignment 0 = TCK/SWCLK function selected. 1 = PB7 function selected. • SYSIO12: PB12 or ERASE Assignment 0 = ERASE function selected. 1 = PB12 function selected. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 371 22.8.5 Write Protect Mode Register Name: MATRIX_WPMR Access: Read-write 31 30 29 28 27 26 25 24 19 18 17 16 11 10 9 8 3 – 2 – 1 – 0 WPEN WPKEY 23 22 21 20 WPKEY 15 14 13 12 WPKEY 7 – 6 – 5 – 4 – For more details on MATRIX_WPMR, refer to Section 22.7 “Write Protect Registers” on page 366. • WPEN: Write Protect ENable 0 = Disables the Write Protect if WPKEY corresponds to 0x4D4154 (“MAT” in ASCII). 1 = Enables the Write Protect if WPKEY corresponds to 0x4D4154 (“MAT” in ASCII). Protects the entire MATRIX address space from address offset 0x000 to 0x1FC. • WPKEY: Write Protect KEY (Write-only) Value 0x4D4154 372 Name Description PASSWD Writing any other value in this field aborts the write operation of the WPEN bit. Always reads as 0. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 22.8.6 Write Protect Status Register Name: MATRIX_WPSR Access: Read-only 31 – 30 – 29 – 28 – 23 22 21 20 27 – 26 – 25 – 24 – 19 18 17 16 11 10 9 8 WPVSRC 15 14 13 12 WPVSRC 7 6 5 4 3 2 1 0 – – – – – – – WPVS For more details on MATRIX_WPSR, refer to Section 22.7 “Write Protect Registers” on page 366. • WPVS: Write Protect Violation Status 0: No Write Protect Violation has occurred since the last write of MATRIX_WPMR. 1: At least one Write Protect Violation has occurred since the last write of MATRIX_WPMR. • WPVSRC: Write Protect Violation Source Should be written at value 0x4D4154 (“MAT” in ASCII). Writing any other value in this field aborts the write operation of the WPEN bit. Always reads as 0. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 373 23. Peripheral DMA Controller (PDC) 23.1 Description The Peripheral DMA Controller (PDC) transfers data between on-chip serial peripherals and the on- and/or off-chip memories. The link between the PDC and a serial peripheral is operated by the AHB to APB bridge. The user interface of each PDC channel is integrated into the user interface of the peripheral it serves. The user interface of mono directional channels (receive only or transmit only), contains two 32-bit memory pointers and two 16-bit counters, one set (pointer, counter) for current transfer and one set (pointer, counter) for next transfer. The bi-directional channel user interface contains four 32-bit memory pointers and four 16-bit counters. Each set (pointer, counter) is used by current transmit, next transmit, current receive and next receive. Using the PDC removes processor overhead by reducing its intervention during the transfer. This significantly reduces the number of clock cycles required for a data transfer, which improves microcontroller performance. To launch a transfer, the peripheral triggers its associated PDC channels by using transmit and receive signals. When the programmed data is transferred, an end of transfer interrupt is generated by the peripheral itself. 23.2 374 Embedded Characteristics Performs Transfers to/from APB Communication Serial Peripherals Supports Half-duplex and Full-duplex Peripherals SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 23.3 Block Diagram Figure 23-1. Block Diagram FULL DUPLEX PERIPHERAL PDC THR PDC Channel A RHR PDC Channel B Control Status & Control HALF DUPLEX PERIPHERAL Control THR PDC Channel C RHR Control Status & Control RECEIVE or TRANSMIT PERIPHERAL RHR or THR Control PDC Channel D Status & Control SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 375 23.4 Functional Description 23.4.1 Configuration The PDC channel user interface enables the user to configure and control data transfers for each channel. The user interface of each PDC channel is integrated into the associated peripheral user interface. The user interface of a serial peripheral, whether it is full or half duplex, contains four 32-bit pointers (RPR, RNPR, TPR, TNPR) and four 16-bit counter registers (RCR, RNCR, TCR, TNCR). However, the transmit and receive parts of each type are programmed differently: the transmit and receive parts of a full duplex peripheral can be programmed at the same time, whereas only one part (transmit or receive) of a half duplex peripheral can be programmed at a time. 32-bit pointers define the access location in memory for current and next transfer, whether it is for read (transmit) or write (receive). 16-bit counters define the size of current and next transfers. It is possible, at any moment, to read the number of transfers left for each channel. The PDC has dedicated status registers which indicate if the transfer is enabled or disabled for each channel. The status for each channel is located in the associated peripheral status register. Transfers can be enabled and/or disabled by setting TXTEN/TXTDIS and RXTEN/RXTDIS in the peripheral’s Transfer Control Register. At the end of a transfer, the PDC channel sends status flags to its associated peripheral. These flags are visible in the peripheral status register (ENDRX, ENDTX, RXBUFF, and TXBUFE). Refer to Section 23.4.3 and to the associated peripheral user interface. 23.4.2 Memory Pointers Each full duplex peripheral is connected to the PDC by a receive channel and a transmit channel. Both channels have 32-bit memory pointers that point respectively to a receive area and to a transmit area in on- and/or off-chip memory. Each half duplex peripheral is connected to the PDC by a bidirectional channel. This channel has two 32-bit memory pointers, one for current transfer and the other for next transfer. These pointers point to transmit or receive data depending on the operating mode of the peripheral. Depending on the type of transfer (byte, half-word or word), the memory pointer is incremented respectively by 1, 2 or 4 bytes. If a memory pointer address changes in the middle of a transfer, the PDC channel continues operating using the new address. 23.4.3 Transfer Counters Each channel has two 16-bit counters, one for current transfer and the other one for next transfer. These counters define the size of data to be transferred by the channel. The current transfer counter is decremented first as the data addressed by current memory pointer starts to be transferred. When the current transfer counter reaches zero, the channel checks its next transfer counter. If the value of next counter is zero, the channel stops transferring data and sets the appropriate flag. But if the next counter value is greater than zero, the values of the next pointer/next counter are copied into the current pointer/current counter and the channel resumes the transfer whereas next pointer/next counter get zero/zero as values.At the end of this transfer the PDC channel sets the appropriate flags in the Peripheral Status Register. 376 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 The following list gives an overview of how status register flags behave depending on the counters’ values: ENDRX flag is set when the PERIPH_RCR register reaches zero. RXBUFF flag is set when both PERIPH_RCR and PERIPH_RNCR reach zero. ENDTX flag is set when the PERIPH_TCR register reaches zero. TXBUFE flag is set when both PERIPH_TCR and PERIPH_TNCR reach zero. These status flags are described in the Peripheral Status Register. 23.4.4 Data Transfers The serial peripheral triggers its associated PDC channels’ transfers using transmit enable (TXEN) and receive enable (RXEN) flags in the transfer control register integrated in the peripheral’s user interface. When the peripheral receives an external data, it sends a Receive Ready signal to its PDC receive channel which then requests access to the Matrix. When access is granted, the PDC receive channel starts reading the peripheral Receive Holding Register (RHR). The read data are stored in an internal buffer and then written to memory. When the peripheral is about to send data, it sends a Transmit Ready to its PDC transmit channel which then requests access to the Matrix. When access is granted, the PDC transmit channel reads data from memory and puts them to Transmit Holding Register (THR) of its associated peripheral. The same peripheral sends data according to its mechanism. 23.4.5 PDC Flags and Peripheral Status Register Each peripheral connected to the PDC sends out receive ready and transmit ready flags and the PDC sends back flags to the peripheral. All these flags are only visible in the Peripheral Status Register. Depending on the type of peripheral, half or full duplex, the flags belong to either one single channel or two different channels. 23.4.5.1 Receive Transfer End This flag is set when PERIPH_RCR register reaches zero and the last data has been transferred to memory. It is reset by writing a non zero value in PERIPH_RCR or PERIPH_RNCR. 23.4.5.2 Transmit Transfer End This flag is set when PERIPH_TCR register reaches zero and the last data has been written into peripheral THR. It is reset by writing a non zero value in PERIPH_TCR or PERIPH_TNCR. 23.4.5.3 Receive Buffer Full This flag is set when PERIPH_RCR register reaches zero with PERIPH_RNCR also set to zero and the last data has been transferred to memory. It is reset by writing a non zero value in PERIPH_TCR or PERIPH_TNCR. 23.4.5.4 Transmit Buffer Empty This flag is set when PERIPH_TCR register reaches zero with PERIPH_TNCR also set to zero and the last data has been written into peripheral THR. It is reset by writing a non zero value in PERIPH_TCR or PERIPH_TNCR. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 377 23.5 Peripheral DMA Controller (PDC) User Interface Table 23-1. Register Mapping Offset Register Name Access Reset 0x00 Receive Pointer Register PERIPH(1)_RPR Read-write 0 0x04 Receive Counter Register PERIPH_RCR Read-write 0 0x08 Transmit Pointer Register PERIPH_TPR Read-write 0 0x0C Transmit Counter Register PERIPH_TCR Read-write 0 0x10 Receive Next Pointer Register PERIPH_RNPR Read-write 0 0x14 Receive Next Counter Register PERIPH_RNCR Read-write 0 0x18 Transmit Next Pointer Register PERIPH_TNPR Read-write 0 0x1C Transmit Next Counter Register PERIPH_TNCR Read-write 0 0x20 Transfer Control Register PERIPH_PTCR Write-only 0 0x24 Transfer Status Register PERIPH_PTSR Read-only 0 Note: 378 1. PERIPH: Ten registers are mapped in the peripheral memory space at the same offset. These can be defined by the user according to the function and the desired peripheral.) SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 23.5.1 Receive Pointer Register Name: PERIPH_RPR Access: Read-write 31 30 29 28 27 26 25 24 19 18 17 16 11 10 9 8 3 2 1 0 RXPTR 23 22 21 20 RXPTR 15 14 13 12 RXPTR 7 6 5 4 RXPTR • RXPTR: Receive Pointer Register RXPTR must be set to receive buffer address. When a half duplex peripheral is connected to the PDC, RXPTR = TXPTR. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 379 23.5.2 Receive Counter Register Name: PERIPH_RCR Access: Read-write 31 – 30 – 29 – 28 – 27 – 26 – 25 – 24 – 23 – 22 – 21 – 20 – 19 – 18 – 17 – 16 – 15 14 13 12 11 10 9 8 3 2 1 0 RXCTR 7 6 5 4 RXCTR • RXCTR: Receive Counter Register RXCTR must be set to receive buffer size. When a half duplex peripheral is connected to the PDC, RXCTR = TXCTR. 0 = Stops peripheral data transfer to the receiver 1 - 65535 = Starts peripheral data transfer if corresponding channel is active 380 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 23.5.3 Transmit Pointer Register Name: PERIPH_TPR Access: Read-write 31 30 29 28 27 26 25 24 19 18 17 16 11 10 9 8 3 2 1 0 TXPTR 23 22 21 20 TXPTR 15 14 13 12 TXPTR 7 6 5 4 TXPTR • TXPTR: Transmit Counter Register TXPTR must be set to transmit buffer address. When a half duplex peripheral is connected to the PDC, RXPTR = TXPTR. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 381 23.5.4 Transmit Counter Register Name: PERIPH_TCR Access: Read-write 31 – 30 – 29 – 28 – 27 – 26 – 25 – 24 – 23 – 22 – 21 – 20 – 19 – 18 – 17 – 16 – 15 14 13 12 11 10 9 8 3 2 1 0 TXCTR 7 6 5 4 TXCTR • TXCTR: Transmit Counter Register TXCTR must be set to transmit buffer size. When a half duplex peripheral is connected to the PDC, RXCTR = TXCTR. 0 = Stops peripheral data transfer to the transmitter 1- 65535 = Starts peripheral data transfer if corresponding channel is active 382 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 23.5.5 Receive Next Pointer Register Name: PERIPH_RNPR Access: Read-write 31 30 29 28 27 26 25 24 19 18 17 16 11 10 9 8 3 2 1 0 RXNPTR 23 22 21 20 RXNPTR 15 14 13 12 RXNPTR 7 6 5 4 RXNPTR • RXNPTR: Receive Next Pointer RXNPTR contains next receive buffer address. When a half duplex peripheral is connected to the PDC, RXNPTR = TXNPTR. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 383 23.5.6 Receive Next Counter Register Name: PERIPH_RNCR Access: Read-write 31 – 30 – 29 – 28 – 27 – 26 – 25 – 24 – 23 – 22 – 21 – 20 – 19 – 18 – 17 – 16 – 15 14 13 12 11 10 9 8 3 2 1 0 RXNCTR 7 6 5 4 RXNCTR • RXNCTR: Receive Next Counter RXNCTR contains next receive buffer size. When a half duplex peripheral is connected to the PDC, RXNCTR = TXNCTR. 384 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 23.5.7 Transmit Next Pointer Register Name: PERIPH_TNPR Access: Read-write 31 30 29 28 27 26 25 24 19 18 17 16 11 10 9 8 3 2 1 0 TXNPTR 23 22 21 20 TXNPTR 15 14 13 12 TXNPTR 7 6 5 4 TXNPTR • TXNPTR: Transmit Next Pointer TXNPTR contains next transmit buffer address. When a half duplex peripheral is connected to the PDC, RXNPTR = TXNPTR. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 385 23.5.8 Transmit Next Counter Register Name: PERIPH_TNCR Access: Read-write 31 – 30 – 29 – 28 – 27 – 26 – 25 – 24 – 23 – 22 – 21 – 20 – 19 – 18 – 17 – 16 – 15 14 13 12 11 10 9 8 3 2 1 0 TXNCTR 7 6 5 4 TXNCTR • TXNCTR: Transmit Counter Next TXNCTR contains next transmit buffer size. When a half duplex peripheral is connected to the PDC, RXNCTR = TXNCTR. 386 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 23.5.9 Transfer Control Register Name: PERIPH_PTCR Access: Write-only 31 – 30 – 29 – 28 – 27 – 26 – 25 – 24 – 23 – 22 – 21 – 20 – 19 – 18 – 17 – 16 – 15 – 14 – 13 – 12 – 11 – 10 – 9 TXTDIS 8 TXTEN 7 – 6 – 5 – 4 – 3 – 2 – 1 RXTDIS 0 RXTEN • RXTEN: Receiver Transfer Enable 0 = No effect. 1 = Enables PDC receiver channel requests if RXTDIS is not set. When a half duplex peripheral is connected to the PDC, enabling the receiver channel requests automatically disables the transmitter channel requests. It is forbidden to set both TXTEN and RXTEN for a half duplex peripheral. • RXTDIS: Receiver Transfer Disable 0 = No effect. 1 = Disables the PDC receiver channel requests. When a half duplex peripheral is connected to the PDC, disabling the receiver channel requests also disables the transmitter channel requests. • TXTEN: Transmitter Transfer Enable 0 = No effect. 1 = Enables the PDC transmitter channel requests. When a half duplex peripheral is connected to the PDC, it enables the transmitter channel requests only if RXTEN is not set. It is forbidden to set both TXTEN and RXTEN for a half duplex peripheral. • TXTDIS: Transmitter Transfer Disable 0 = No effect. 1 = Disables the PDC transmitter channel requests. When a half duplex peripheral is connected to the PDC, disabling the transmitter channel requests disables the receiver channel requests. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 387 23.5.10 Transfer Status Register Name: PERIPH_PTSR Access: Read-only 31 – 30 – 29 – 28 – 27 – 26 – 25 – 24 – 23 – 22 – 21 – 20 – 19 – 18 – 17 – 16 – 15 – 14 – 13 – 12 – 11 – 10 – 9 – 8 TXTEN 7 – 6 – 5 – 4 – 3 – 2 – 1 – 0 RXTEN • RXTEN: Receiver Transfer Enable 0 = PDC receiver channel requests are disabled. 1 = PDC receiver channel requests are enabled. • TXTEN: Transmitter Transfer Enable 0 = PDC transmitter channel requests are disabled. 1 = PDC transmitter channel requests are enabled. 388 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 24. Clock Generator 24.1 Description The Clock Generator User Interface is embedded within the Power Management Controller and is described in Section 25.16 “Power Management Controller (PMC) User Interface”. However, the Clock Generator registers are named CKGR_. 24.2 Embedded Characteristics The Clock Generator is made up of: A Low Power 32768 Hz Slow Clock Oscillator with bypass mode. A Low Power RC Oscillator A 3 to 20 MHz Crystal or Ceramic Resonator-based Oscillator, which can be bypassed. A factory programmed Fast RC Oscillator. 3 output frequencies can be selected: 12/8/4 MHz. By default 4 MHz is selected. A 80 to 240 MHz programmable PLL (input from 8 to 32 MHz), capable of providing the clock MCK to the processor and to the peripherals. Write Protected Registers It provides the following clocks: SLCK, the Slow Clock, which is the only permanent clock within the system. MAINCK is the output of the Main Clock Oscillator selection: either the Crystal or Ceramic Resonator-based Oscillator or 12/8/4 MHz Fast RC Oscillator. PLLACK is the output of the Divider and 80 to 240 MHz programmable PLL (PLLA). SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 389 24.3 Block Diagram Figure 24-1. Clock Generator Block Diagram Clock Generator XTALSEL (Supply Controller) Embedded 32 kHz RC Oscillator 0 Slow Clock SLCK XIN32 XOUT32 32768 Hz Crystal Oscillator 1 MOSCSEL Embedded 12/8/4 MHz Fast RC Oscillator 0 Main Clock MAINCK XIN XOUT 3-20 MHz Crystal Oscillator 1 PLLA and Divider Status PLLA Clock PLLACK Control Power Management Controller 24.4 Slow Clock The Supply Controller embeds a slow clock generator that is supplied with the VDDIO power supply. As soon as the VDDIO is supplied, both the crystal oscillator and the embedded RC oscillator are powered up, but only the embedded RC oscillator is enabled. This allows the slow clock to be valid in a short time (about 100 µs). The Slow Clock is generated either by the Slow Clock Crystal Oscillator or by the Slow Clock RC Oscillator. The selection between the RC or the crystal oscillator is made by writing the XTALSEL bit in the Supply Controller Control Register (SUPC_CR). 24.4.1 Slow Clock RC Oscillator By default, the Slow Clock RC Oscillator is enabled and selected. The user has to take into account the possible drifts of the RC Oscillator. More details are given in the section “DC Characteristics” of the product datasheet. It can be disabled via the XTALSEL bit in the Supply Controller Control Register (SUPC_CR). 390 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 24.4.2 Slow Clock Crystal Oscillator The Clock Generator integrates a 32768 Hz low-power oscillator. In order to use this oscillator, the XIN32 and XOUT32 pins must be connected to a 32768 Hz crystal. Two external capacitors must be wired as shown in Figure 24-2. More details are given in the section “DC Characteristics” of the product datasheet. Note that the user is not obliged to use the Slow Clock Crystal and can use the RC oscillator instead. Figure 24-2. Typical Slow Clock Crystal Oscillator Connection XIN32 XOUT32 GND 32768 Hz Crystal The user can select the crystal oscillator to be the source of the slow clock, as it provides a more accurate frequency. The command is made by writing the Supply Controller Control Register (SUPC_CR) with the XTALSEL bit at 1. This results in a sequence which first configures the PIO lines multiplexed with XIN32 and XOUT32 to be driven by the oscillator, then enables the crystal oscillator and then disables the RC oscillator to save power. The switch of the slow clock source is glitch free. The OSCSEL bit of the Supply Controller Status Register (SUPC_SR) tracks the oscillator frequency downstream. It must be read in order to be informed when the switch sequence, initiated when a new value is written in MOSCSEL bit of CKGR_MOR, is done. Coming back on the RC oscillator is only possible by shutting down the VDDIO power supply. If the user does not need the crystal oscillator, the XIN32 and XOUT32 pins can be left unconnected since by default the XIN32 and XOUT32 system I/O pins are in PIO input mode with pull-up after reset. The user can also set the crystal oscillator in bypass mode instead of connecting a crystal. In this case, the user has to provide the external clock signal on XIN32. The input characteristics of the XIN32 pin are given in the product electrical characteristics section. In order to set the bypass mode, the OSCBYPASS bit of the Supply Controller Mode Register (SUPC_MR) needs to be set at 1. The user can set the Slow Clock Crystal Oscillator in bypass mode instead of connecting a crystal. In this case, the user has to provide the external clock signal on XIN32. The input characteristics of the XIN32 pin under these conditions are given in the product electrical characteristics section. The programmer has to be sure to set the OSCBYPASS bit in the Supply Controller Mode Register (SUPC_MR) and XTALSEL bit in the Supply Controller Control Register (SUPC_CR). SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 391 24.5 Main Clock Figure 24-3 shows the Main Clock block diagram. Figure 24-3. Main Clock Block Diagram MOSCRCEN MOSCRCF MOSCRCS Fast RC Oscillator MOSCSELS MOSCSEL 0 MAINCK Main Clock MOSCXTEN 1 3-20 MHz Crystal or Ceramic Resonator Oscillator XIN XOUT MOSCXTCNT 3-20 MHz Oscillator Counter SLCK Slow Clock MOSCXTS MOSCRCEN MOSCXTEN RCMEAS MOSCSEL MAINCK Main Clock Ref. Main Clock Frequency Counter MAINF MAINRDY The Main Clock has two sources: 24.5.1 12/8/4 MHz Fast RC Oscillator which starts very quickly and is used at start-up. 3 to 20 MHz Crystal or Ceramic Resonator-based Oscillator which can be bypassed. Fast RC Oscillator After reset, the 12/8/4 MHz Fast RC Oscillator is enabled with the 4 MHz frequency selected and it is selected as the source of MAINCK. MAINCK is the default clock selected to start up the system. The Fast RC Oscillator frequencies are calibrated in production except the lowest frequency which is not calibrated. Please refer to the “DC Characteristics” section of the product datasheet. The software can disable or enable the 12/8/4 MHz Fast RC Oscillator with the MOSCRCEN bit in the Clock Generator Main Oscillator Register (CKGR_MOR). The user can also select the output frequency of the Fast RC Oscillator, either 12/8/4 MHz are available. It can be done through MOSCRCF bits in CKGR_MOR. When changing this frequency selection, the MOSCRCS bit in the Power Management Controller Status Register (PMC_SR) is automatically cleared and MAINCK is stopped until the oscillator is stabilized. Once the oscillator is stabilized, MAINCK restarts and MOSCRCS is set. 392 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 When disabling the Main Clock by clearing the MOSCRCEN bit in CKGR_MOR, the MOSCRCS bit in the Power Management Controller Status Register (PMC_SR) is automatically cleared, indicating the Main Clock is off. Setting the MOSCRCS bit in the Power Management Controller Interrupt Enable Register (PMC_IER) can trigger an interrupt to the processor. It is recommended to disable the Main Clock as soon as the processor no longer uses it and runs out of SLCK. The CAL4, CAL8 and CAL12 values in the PMC Oscillator Calibration Register (PMC_OCR) are the default values set by Atmel during production. These values are stored in a specific Flash memory area different from the main memory plane. These values cannot be modified by the user and cannot be erased by a Flash erase command or by the ERASE pin. Values written by the user's application in PMC_OCR are reset after each power up or peripheral reset. 24.5.2 Fast RC Oscillator Clock Frequency Adjustment It is possible for the user to adjust the main RC oscillator frequency through PMC_OCR. By default, SEL4/8/12 are low, so the RC oscillator will be driven with Flash calibration bits which are programmed during chip production. The user can adjust the trimming of the 12/8/4 MHz Fast RC Oscillator through this register in order to obtain more accurate frequency (to compensate derating factors such as temperature and voltage). In order to calibrate the oscillator lower frequency, SEL4 must be set to 1 and a good frequency value must be configured in CAL4. Likewise, SEL8/12 must be set to 1 and a trim value must be configured in CAL8/12 in order to adjust the other frequencies of the oscillator. It is possible to adjust the oscillator frequency while operating from this clock. For example, when running on lowest frequency it is possible to change the CAL4 value if SEL4 is set in PMC_OCR. It is possible to restart, at anytime, a measurement of the main frequency by means of the RCMEAS bit in Main Clock Frequency Register (CKGR_MCFR). Thus, when MAINFRDY flag reads 1, another read access on Main Clock Frequency Register (CKGR_MCFR) provides an image of the frequency of the main clock on MAINF field. The software can calculate the error with an expected frequency and correct the CAL4 (or CAL8/CAL12) field accordingly. This may be used to compensate frequency drift due to derating factors such as temperature and/or voltage. 24.5.3 3 to 20 MHz Crystal or Ceramic Resonator-based Oscillator After reset, the 3 to 20 MHz Crystal or Ceramic Resonator-based oscillator is disabled and it is not selected as the source of MAINCK. The user can select the 3 to 20 MHz Crystal or Ceramic Resonator-based oscillator to be the source of MAINCK, as it provides a more accurate frequency. The software enables or disables the main oscillator so as to reduce power consumption by clearing the MOSCXTEN bit in the Main Oscillator Register (CKGR_MOR). When disabling the main oscillator by clearing the MOSCXTEN bit in CKGR_MOR, the MOSCXTS bit in PMC_SR is automatically cleared, indicating the Main Clock is off. When enabling the main oscillator, the user must initiate the main oscillator counter with a value corresponding to the start-up time of the oscillator. This start-up time depends on the crystal frequency connected to the oscillator. When the MOSCXTEN bit and the MOSCXTCNT are written in CKGR_MOR to enable the main oscillator, the XIN and XOUT pins are automatically switched into oscillator mode and MOSCXTS bit in the Power Management Controller Status Register (PMC_SR) is cleared and the counter starts counting down on the slow clock divided by 8 from the MOSCXTCNT value. Since the MOSCXTCNT value is coded with 8 bits, the maximum start-up time is about 62 ms. When the counter reaches 0, the MOSCXTS bit is set, indicating that the main clock is valid. Setting the MOSCXTS bit in PMC_IMR can trigger an interrupt to the processor. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 393 24.5.4 Main Clock Oscillator Selection The user can select either the 12/8/4 MHz Fast RC Oscillator or the 3 to 20 MHz Crystal or Ceramic Resonatorbased oscillator to be the source of Main Clock. The advantage of the 12/8/4 MHz Fast RC Oscillator is that it provides fast start-up time, this is why it is selected by default (to start up the system) and when entering Wait Mode. The advantage of the 3 to 20 MHz Crystal or Ceramic Resonator-based oscillator is that it is very accurate. The selection is made by writing the MOSCSEL bit in the Main Oscillator Register (CKGR_MOR). The switch of the Main Clock source is glitch free, so there is no need to run out of SLCK, PLLACK in order to change the selection. The MOSCSELS bit of the Power Management Controller Status Register (PMC_SR) allows knowing when the switch sequence is done. Setting the MOSCSELS bit in PMC_IMR can trigger an interrupt to the processor. Enabling the Fast RC Oscillator (MOSCRCEN = 1) and changing the Fast RC Frequency (MOSCCRF) at the same time is not allowed. The Fast RC must be enabled first and its frequency changed in a second step. 24.5.5 Software Sequence to Detect the Presence of Fast Crystal The frequency meter carried on the CKGR_MCFR register is operating on the selected main clock and not on the fast crystal clock nor on the fast RC Oscillator clock. Therefore, to check for the presence of the fast crystal clock, it is necessary to have the main clock (MAINCK) driven by the fast crystal clock (MOSCSEL=1). The following software sequence order must be followed: ̶ MCK must select the slow clock (CSS=0 in the PLL_MCKR register). ̶ Wait for the MCKRDY flag in the PLL_SR register to be 1. ̶ The fast crystal must be enabled by programming 1 in the MOSCXTEN field in the CKGR_MOR register with the MOSCXTST field being programmed to the appropriate value (see the Electrical Characteristics chapter). ̶ Wait for the MOSCXTS flag to be 1 in the PLL_SR register to get the end of a start-up period of the fast crystal oscillator. ̶ Then, MOSCSEL must be programmed to 1 in the CKGR_MOR register to select fast main crystal oscillator for the main clock. ̶ MOSCSEL must be read until its value equals 1. ̶ Then the MOSCSELS status flag must be checked in the PLL_SR register. At this point, 2 cases may occur (either MOSCSELS = 0 or MOSCSELS = 1). ̶ ̶ 394 ̶ If MOSCSELS = 1, there is a valid crystal connected and its frequency can be determined by initiating a frequency measure by programming RCMEAS in the CKGR_MCFR register. ̶ If MOSCSELS = 0, there is no fast crystal clock (either no crystal connected or a crystal clock out of specification). A frequency measure can reinforce this status by initiating a frequency measure by programming RCMEAS in the CKGR_MCFR register. If MOSCSELS=0, the selection of the main clock must be programmed back to the main RC oscillator by writing MOSCSEL to 0 prior to disabling the fast crystal oscillator. If MOSCSELS=0, the crystal oscillator can be disabled (MOSCXTEN=0 in the CKGR_MOR register). SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 24.5.6 Main Clock Frequency Counter The device features a Main Clock frequency counter that provides the frequency of the Main Clock. The Main Clock frequency counter is reset and starts incrementing at the Main Clock speed after the next rising edge of the Slow Clock in the following cases: When the 12/8/4 MHz Fast RC Oscillator clock is selected as the source of Main Clock and when this oscillator becomes stable (i.e., when the MOSCRCS bit is set) When the 3 to 20 MHz Crystal or Ceramic Resonator-based Oscillator is selected as the source of Main Clock and when this oscillator becomes stable (i.e., when the MOSCXTS bit is set) When the Main Clock Oscillator selection is modified When the RCMEAS bit of CKGR_MFCR is written to 1. Then, at the 16th falling edge of Slow Clock, the MAINFRDY bit in the Clock Generator Main Clock Frequency Register (CKGR_MCFR) is set and the counter stops counting. Its value can be read in the MAINF field of CKGR_MCFR and gives the number of Main Clock cycles during 16 periods of Slow Clock, so that the frequency of the 12/8/4 MHz Fast RC Oscillator or 3 to 20 MHz Crystal or Ceramic Resonator-based Oscillator can be determined. 24.6 Divider and PLL Block The device features one Divider/PLL Block that permits a wide range of frequencies to be selected on either the master clock, the processor clock or the programmable clock outputs. Figure 24-4 shows the block diagram of the dividers and PLL blocks. Figure 24-4. Divider and PLL Block Diagram DIVA MAINCK Divider MULA OUTA PLLA PLLACK PLLACOUNT SLCK 24.6.1 PLLA Counter LOCKA Divider and Phase Lock Loop Programming The divider can be set between 1 and 255 in steps of 1. When a divider field (DIV) is set to 0, the output of the corresponding divider and the PLL output is a continuous signal at level 0. On reset, each DIV field is set to 0, thus the corresponding PLL input clock is set to 0. The PLL (PLLA) allows multiplication of the divider’s output. The PLL clock signal has a frequency that depends on the respective source signal frequency and on the parameters DIV (DIVA) and MUL (MULA). The factor applied to the source signal frequency is (MUL + 1)/DIV. When MUL is written to 0 and DIV=0, the PLL is disabled and its power consumption is saved. Re-enabling the PLL can be performed by writing a value higher than 0 in the MUL field. Whenever the PLL is re-enabled or one of its parameters is changed, the LOCK (LOCKA) bit in PMC_SR is automatically cleared. The values written in the PLLCOUNT field (PLLACOUNT) in CKGR_PLLR (CKGR_PLLAR) are loaded in the PLL counter. The PLL counter then decrements at the speed of the Slow Clock until it reaches 0. At this time, the LOCK bit is set in PMC_SR and can trigger an interrupt to the processor. The user has to load the number of Slow Clock cycles required to cover the PLL transient time into the PLLCOUNT field. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 395 The PLL clock can be divided by 2 by writing the PLLDIV2 (PLLADIV2) bit in PMC Master Clock Register (PMC_MCKR). It is forbidden to change 12/8/4 MHz Fast RC Oscillator, or main selection in CKGR_MOR register while Master Clock source is PLL and PLL reference clock is the Fast RC Oscillator. The user must: 396 Switch on the Main RC oscillator by writing 1 in CSS field of PMC_MCKR. Change the frequency (MOSCRCF) or oscillator selection (MOSCSEL) in CKGR_MOR. Wait for MOSCRCS (if frequency changes) or MOSCSELS (if oscillator selection changes) in PMC_IER. Disable and then enable the PLL (LOCK in PMC_IDR and PMC_IER). Wait for PLLRDY. Switch back to PLL. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 25. Power Management Controller (PMC) 25.1 Description The Power Management Controller (PMC) optimizes power consumption by controlling all system and user peripheral clocks. The PMC enables/disables the clock inputs to many of the peripherals and the Cortex-M4 Processor. The Supply Controller selects between the 32 kHz RC oscillator or the crystal oscillator. The unused oscillator is disabled automatically so that power consumption is optimized. By default, at start-up the chip runs out of the Master Clock using the Fast RC Oscillator running at 4 MHz. The user can trim the 8 and 12 MHz RC Oscillator frequencies by software. 25.2 Embedded Characteristics The Power Management Controller provides the following clocks: MCK, the Master Clock, programmable from a few hundred Hz to the maximum operating frequency of the device. It is available to the modules running permanently, such as the Enhanced Embedded Flash Controller. Processor Clock (HCLK) , must be switched off when entering the processor in Sleep Mode. Free running processor Clock (FCLK) The Cortex-M4 SysTick external clock Peripheral Clocks, typically MCK, provided to the embedded peripherals (USART, SPI, TWI, TC, HSMCI, etc.) and independently controllable. In order to reduce the number of clock names in a product, the Peripheral Clocks are named MCK in the product datasheet. Programmable Clock Outputs can be selected from the clocks provided by the clock generator and driven on the PCKx pins. Write Protected Registers The Power Management Controller also provides the following operations on clocks: A main crystal oscillator clock failure detector. A 32768 kHz crystal oscillator frequency monitor. A frequency counter on main clock and an on-the-fly adjustable main RC oscillator frequency. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 397 25.3 Block Diagram Figure 25-1. General Clock Block Diagram Clock Generator Processor Clock Controller XTALSEL (Supply Controller) Processor clock HCLK int Sleep Mode Embedded 32 kHz RC Oscillator 0 Divider /8 Slow Clock SLCK XIN32 XOUT32 32768 Hz Crystal Oscillator XOUT Master Clock Controller (PMC_MCKR) Free Running Clock FCLK MAINCK Prescaler /1,/2,/3,/4,/8, /16,/32,/64 MOSCSEL Embedded 4/8/12 MHz Fast RC Oscillator XIN SLCK 1 PLLACK Master Clock MCK Peripherals Clock Controller (PMC_PCERx) ON/OFF 0 CSS PRES Main Clock MAINCK 3-20 MHz Crystal or Ceramic Resonator Oscillator periph_clk[..] 1 Programmable Clock Controller (PMC_PCKx) SLCK MAINCK PLLA and Divider/2 PLLA Clock PLLACK PLLADIV2 Status SysTick Prescaler /1,/2,/4,/8, /16,/32,/64 PLLACK ON/OFF pck[..] MCK CSS PRES Control Power Management Controller 25.4 Master Clock Controller The Master Clock Controller provides selection and division of the Master Clock (MCK). MCK is the clock provided to all the peripherals. The Master Clock is selected from one of the clocks provided by the Clock Generator. Selecting the Slow Clock provides a Slow Clock signal to the whole device. Selecting the Main Clock saves power consumption of the PLL. The Master Clock Controller is made up of a clock selector and a prescaler. The Master Clock selection is made by writing the CSS field (Clock Source Selection) in PMC_MCKR (Master Clock Register). The prescaler supports the division by a power of 2 of the selected clock between 1 and 64, and the division by 3. The PRES field in PMC_MCKR programs the prescaler. Each time PMC_MCKR is written to define a new Master Clock, the MCKRDY bit is cleared in PMC_SR. It reads 0 until the Master Clock is established. Then, the MCKRDY bit is set and can trigger an interrupt to the processor. This feature is useful when switching from a high-speed clock to a lower one to inform the software when the change is actually done. 398 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Figure 25-2. Master Clock Controller PMC_MCKR CSS PMC_MCKR PRES SLCK MAINCK Master Clock Prescaler MCK PLLACK To the Processor Clock Controller (PCK) 25.5 Processor Clock Controller The PMC features a Processor Clock Controller (HCLK) that implements the Processor Sleep Mode. The Processor Clock can be disabled by executing the WFI (WaitForInterrupt) or the WFE (WaitForEvent) processor instruction while the LPM bit is at 0 in the PMC Fast Start-up Mode Register (PMC_FSMR). The Processor Clock HCLK is enabled after a reset and is automatically re-enabled by any enabled interrupt. The Processor Sleep Mode is achieved by disabling the Processor Clock, which is automatically re-enabled by any enabled fast or normal interrupt, or by the reset of the product. When Processor Sleep Mode is entered, the current instruction is finished before the clock is stopped, but this does not prevent data transfers from other masters of the system bus. 25.6 SysTick Clock The SysTick calibration value is fixed to 10000 which allows the generation of a time base of 1 ms with SysTick clock to the maximum frequency on MCK divided by 8. 25.7 Peripheral Clock Controller The Power Management Controller controls the clocks of each embedded peripheral by means of the Peripheral Clock Controller. The user can individually enable and disable the Clock on the peripherals. The user can also enable and disable these clocks by writing Peripheral Clock Enable 0 (PMC_PCER0), Peripheral Clock Disable 0 (PMC_PCDR0). The status of the peripheral clock activity can be read in the Peripheral Clock Status Register (PMC_PCSR0) . When a peripheral clock is disabled, the clock is immediately stopped. The peripheral clocks are automatically disabled after a reset. In order to stop a peripheral, it is recommended that the system software wait until the peripheral has executed its last programmed operation before disabling the clock. This is to avoid data corruption or erroneous behavior of the system. The bit number within the Peripheral Clock Control registers (PMC_PCER0, PMC_PCDR0, and PMC_PCSR0) is the Peripheral Identifier defined at the product level. The bit number corresponds to the interrupt source number assigned to the peripheral. 25.8 Free Running Processor Clock The Free Running Processor Clock (FCLK) used for sampling interrupts and clocking debug blocks ensures that interrupts can be sampled, and sleep events can be traced, while the processor is sleeping. It is connected to Master Clock (MCK). SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 399 25.9 Programmable Clock Output Controller The PMC controls 3 signals to be output on external pins, PCKx. Each signal can be independently programmed via the Programmable Clock Registers (PMC_PCKx). PCKx can be independently selected between the Slow Clock (SLCK), the Main Clock (MAINCK), the PLLA Clock (PLLACK),and the Master Clock (MCK) by writing the CSS field in PMC_PCKx. Each output signal can also be divided by a power of 2 between 1 and 64 by writing the PRES (Prescaler) field in PMC_PCKx. Each output signal can be enabled and disabled by writing 1 in the corresponding bit, PCKx of PMC_SCER and PMC_SCDR, respectively. Status of the active programmable output clocks are given in the PCKx bits of PMC_SCSR (System Clock Status Register). Moreover, like the PCK, a status bit in PMC_SR indicates that the Programmable Clock is actually what has been programmed in the Programmable Clock registers. As the Programmable Clock Controller does not manage with glitch prevention when switching clocks, it is strongly recommended to disable the Programmable Clock before any configuration change and to re-enable it after the change is actually performed. 25.10 Fast Start-up The device allows the processor to restart in less than 10 microseconds while the device is in Wait Mode. The system enters Wait Mode either by writing the WAITMODE bit at 1 in the PMC Clock Generator Main Oscillator Register (CKGR_MOR), or by executing the WaitForEvent (WFE) instruction of the processor while the LPM bit is at 1 in the PMC Fast Start-up Mode Register (PMC_FSMR). Waiting for the MOSCRCEN bit to be cleared is strongly recommended to ensure that the core will not execute undesired instructions. Important: Prior to instructing the system to enter the Wait Mode, the internal sources of wake-up must be cleared. It must be verified that none of the enabled external wake-up inputs (WKUP) hold an active polarity. A Fast Start-up is enabled upon the detection of a programmed level on one of the 16 wake-up inputs (WKUP) or upon an active alarm from the RTC, RTT. The polarity of the 16 wake-up inputs is programmable by writing the PMC Fast Start-up Polarity Register (PMC_FSPR). The Fast Restart circuitry, as shown in Figure 25-3, is fully asynchronous and provides a fast start-up signal to the Power Management Controller. As soon as the fast start-up signal is asserted, the embedded 12/8/4 MHz Fast RC Oscillator restarts automatically. When entering the Wait Mode, the embedded flash can be placed in low power mode depending on the configuration of the FLPM in PMC_FSMR register. This bitfield can be programmed anytime and will be taken into account at the next time the system enters Wait Mode. The power consumption reduction is optimal when configuring 1 (deep power down mode) in FLPM. If 0 is programmed (standby mode), the power consumption is slightly higher as compared to the deep power down mode. When programming 2 in FLPM, the Wait Mode flash power consumption is equivalent to the active mode when there is no read access on the flash. 400 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Figure 25-3. Fast Start-up Circuitry FSTT0 WKUP0 FSTP0 FSTT1 WKUP1 FSTP1 FSTT15 WKUP15 fast_restart FSTP15 RTTAL RTT Alarm RTCAL RTC Alarm Each wake-up input pin and alarm can be enabled to generate a Fast Start-up event by writing 1 to the corresponding bit in the Fast Start-up Mode Register (PMC_FSMR). The user interface does not provide any status for Fast Start-up, but the user can easily recover this information by reading the PIO Controller and the status registers of the RTC, RTT. 25.11 Main Crystal Clock Failure Detector The clock failure detector monitors the 3 to 20 MHz Crystal or Ceramic Resonator-based oscillator to identify an eventual defect of this oscillator (for example, if the crystal is unconnected). The clock failure detector can be enabled or disabled by means of the CFDEN bit in the PMC Clock Generator Main Oscillator Register (CKGR_MOR). After reset, the detector is disabled. However, if the 3 to 20 MHz Crystal or Ceramic Resonator-based Oscillator is disabled, the clock failure detector is disabled too. The slow RC oscillator must be enabled.The clock failure detection must be enabled only when system clock MCK selects the fast RC Oscillator. Then the status register must be read 2 slow clock cycles after enabling. A failure is detected by means of a counter incrementing on the 3 to 20 MHz Crystal oscillator or Ceramic Resonator-based oscillator clock edge and timing logic clocked on the slow clock RC oscillator controlling the counter. The counter is cleared when the slow clock RC oscillator signal is low and enabled when the slow clock RC oscillator is high. Thus the failure detection time is 1 slow clock RC oscillator clock period. If, during the high level period of the slow clock RC oscillator, less than 8 fast crystal oscillator clock periods have been counted, then a failure is declared. If a failure of the 3 to 20 MHz Crystal or Ceramic Resonator-based oscillator clock is detected, the CFDEV flag is set in the PMC Status Register (PMC_SR), and generates an interrupt if it is not masked. The interrupt remains active until a read operation in the PMC_SR register. The user can know the status of the clock failure detector at any time by reading the CFDS bit in the PMC_SR register. If the 3 to 20 MHz Crystal or Ceramic Resonator-based oscillator clock is selected as the source clock of MAINCK (MOSCSEL = 1), and if the Master Clock Source is PLLACK (CSS = 2), a clock failure detection automatically SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 401 forces MAINCK to be the source clock for the master clock (MCK).Then, regardless of the PMC configuration, a clock failure detection automatically forces the 12/8/4 MHz Fast RC Oscillator to be the source clock for MAINCK. If the Fast RC Oscillator is disabled when a clock failure detection occurs, it is automatically re-enabled by the clock failure detection mechanism. It takes 2 slow clock RC oscillator cycles to detect and switch from the 3 to 20 MHz Crystal, or Ceramic Resonatorbased Oscillator, to the 12/8/4 MHz Fast RC Oscillator if the Master Clock source is Main Clock, or 3 slow clock RC oscillator cycles if the Master Clock source is PLLACK . A clock failure detection activates a fault output that is connected to the Pulse Width Modulator (PWM) Controller. With this connection, the PWM controller is able to force its outputs and to protect the driven device, if a clock failure is detected. This fault output remains active until the defect is detected and until it is cleared by the bit FOCLR in the PMC Fault Output Clear Register (PMC_FOCR). The user can know the status of the fault output at any time by reading the FOS bit in the PMC_SR register. 25.12 Slow Crystal Clock Frequency Monitor The frequency of the slow clock crystal oscillator can be monitored by means of logic driven by the main RC oscillator known as a reliable clock source. This function is enabled by configuring the XT32KFME bit of the Main Oscillator Register (CKGR_MOR). An error flag (XT32KERR in PMC_SR) is asserted when the slow clock crystal oscillator frequency is out of the +/10% nominal frequency value (i.e. 32768 kHz). The error flag can be cleared only if the slow clock frequency monitoring is disabled. When the main RC oscillator frequency is 4 MHz, the accuracy of the measurement is +/-40% as this frequency is not trimmed during production. Therefore, +/-10% accuracy is obtained only if the RC oscillator frequency is configured for 8 or 12 MHz. The monitored clock frequency is declared invalid if at least 4 consecutive clock period measurement results are over the nominal period +/-10%. Due to the possible frequency variation of the embedded main RC oscillator acting as reference clock for the monitor logic, any slow clock crystal frequency deviation over +/-10% of the nominal frequency is systematically reported as an error by means of XT32KERR in PMC_SR. Between -1% and -10% and +1% and +10%, the error is not systematically reported. Thus only a crystal running at 32768 kHz frequency ensures that the error flag will not be asserted. The permitted drift of the crystal is 10000ppm (1%), which allows any standard crystal to be used. If the main RC frequency needs to be changed while the slow clock frequency monitor is operating, the monitoring must be stopped prior to change the main RC frequency. Then it can be re-enabled as soon as MOSCRCS is set in PMC_SR register. The error flag can be defined as an interrupt source of the PMC by setting the XT32KERR bit of PMC_IER. 25.13 Programming Sequence 1. Enabling the Main Oscillator: The main oscillator is enabled by setting the MOSCXTEN field in the Main Oscillator Register (CKGR_MOR). The user can define a start-up time. This can be achieved by writing a value in the MOSCXTST field in CKGR_MOR. Once this register has been correctly configured, the user must wait for MOSCXTS field in the PMC_SR register to be set. This can be done either by polling the status register, or by waiting the interrupt line to be raised if the associated interrupt to MOSCXTS has been enabled in the PMC_IER register. Start Up Time = 8 * MOSCXTST / SLCK = 56 Slow Clock Cycles. The main oscillator will be enabled (MOSCXTS bit set) after 56 Slow Clock Cycles. 402 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 2. Checking the Main Oscillator Frequency (Optional): In some situations the user may need an accurate measure of the main clock frequency. This measure can be accomplished via the Main Clock Frequency Register (CKGR_MCFR). Once the MAINFRDY field is set in CKGR_MCFR, the user may read the MAINF field in CKGR_MCFR by performing another CKGR_MCFR read access. This provides the number of main clock cycles within sixteen slow clock cycles. 3. Setting PLL and Divider: All parameters needed to configure PLLA and the divider are located in CKGR_PLLAR. The DIV field is used to control the divider itself. It must be set to 1 when PLL is used. By default, DIV parameter is set to 0 which means that the divider is turned off. The MUL field is the PLL multiplier factor. This parameter can be programmed between 0 and 62. If MUL is set to 0, PLL will be turned off, otherwise the PLL output frequency is PLL input frequency multiplied by (MUL + 1). The PLLCOUNT field specifies the number of slow clock cycles before the LOCK bit is set in PMC_SR, after CKGR_PLLAR has been written. Once the CKGR_PLL register has been written, the user must wait for the LOCK bit to be set in the PMC_SR. This can be done either by polling the status register or by waiting the interrupt line to be raised if the associated interrupt to LOCK has been enabled in PMC_IER. All parameters in CKGR_PLLAR can be programmed in a single write operation. If at some stage one of the following parameters, MUL or DIV is modified, the LOCK bit will go low to indicate that PLL is not ready yet. When PLL is locked, LOCK will be set again. The user is constrained to wait for LOCK bit to be set before using the PLL output clock. 4. Selection of Master Clock and Processor Clock The Master Clock and the Processor Clock are configurable via the Master Clock Register (PMC_MCKR). The CSS field is used to select the Master Clock divider source. By default, the selected clock source is main clock. The PRES field is used to control the Master Clock prescaler. The user can choose between different values (1, 2, 3, 4, 8, 16, 32, 64). Master Clock output is prescaler input divided by PRES parameter. By default, PRES parameter is set to 1 which means that master clock is equal to main clock. Once PMC_MCKR has been written, the user must wait for the MCKRDY bit to be set in PMC_SR. This can be done either by polling the status register or by waiting for the interrupt line to be raised if the associated interrupt to MCKRDY has been enabled in the PMC_IER register. The PMC_MCKR must not be programmed in a single write operation. The preferred programming sequence for PMC_MCKR is as follows: If a new value for CSS field corresponds to PLL Clock, ̶ Program the PRES field in PMC_MCKR. ̶ Wait for the MCKRDY bit to be set in PMC_SR. ̶ Program the CSS field in PMC_MCKR. ̶ Wait for the MCKRDY bit to be set in PMC_SR. If a new value for CSS field corresponds to Main Clock or Slow Clock, ̶ Program the CSS field in PMC_MCKR. ̶ Wait for the MCKRDY bit to be set in the PMC_SR. ̶ Program the PRES field in PMC_MCKR. ̶ Wait for the MCKRDY bit to be set in PMC_SR. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 403 If at some stage one of the following parameters, CSS or PRES is modified, the MCKRDY bit will go low to indicate that the Master Clock and the Processor Clock are not ready yet. The user must wait for MCKRDY bit to be set again before using the Master and Processor Clocks. Note: IF PLLx clock was selected as the Master Clock and the user decides to modify it by writing in CKGR_PLLR, the MCKRDY flag will go low while PLL is unlocked. Once PLL is locked again, LOCK goes high and MCKRDY is set. While PLL is unlocked, the Master Clock selection is automatically changed to Slow Clock. For further information, see Section 25.14.2 “Clock Switching Waveforms” on page 405. Code Example: write_register(PMC_MCKR,0x00000001) wait (MCKRDY=1) write_register(PMC_MCKR,0x00000011) wait (MCKRDY=1) The Master Clock is main clock divided by 2. The Processor Clock is the Master Clock. 5. Selection of Programmable Clocks Programmable clocks are controlled via registers, PMC_SCER, PMC_SCDR and PMC_SCSR. Programmable clocks can be enabled and/or disabled via PMC_SCER and PMC_SCDR. 3 Programmable clocks can be enabled or disabled. The PMC_SCSR provides a clear indication as to which Programmable clock is enabled. By default all Programmable clocks are disabled. Programmable Clock Registers (PMC_PCKx) are used to configure Programmable clocks. The CSS field is used to select the Programmable clock divider source. Four clock options are available: main clock, slow clock, PLLACK, . By default, the clock source selected is slow clock. The PRES field is used to control the Programmable clock prescaler. It is possible to choose between different values (1, 2, 4, 8, 16, 32, 64). Programmable clock output is prescaler input divided by PRES parameter. By default, the PRES parameter is set to 0 which means that master clock is equal to slow clock. Once PMC_PCKx has been programmed, The corresponding Programmable clock must be enabled and the user is constrained to wait for the PCKRDYx bit to be set in PMC_SR. This can be done either by polling the status register or by waiting the interrupt line to be raised, if the associated interrupt to PCKRDYx has been enabled in the PMC_IER register. All parameters in PMC_PCKx can be programmed in a single write operation. If the CSS and PRES parameters are to be modified, the corresponding Programmable clock must be disabled first. The parameters can then be modified. Once this has been done, the user must re-enable the Programmable clock and wait for the PCKRDYx bit to be set. 6. Enabling Peripheral Clocks Once all of the previous steps have been completed, the peripheral clocks can be enabled and/or disabled via registers PMC_PCER0, PMC_PCDR0. 404 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 25.14 Clock Switching Details 25.14.1 Master Clock Switching Timings Table 25-1 and give the worst case timings required for the Master Clock to switch from one selected clock to another one. This is in the event that the prescaler is de-activated. When the prescaler is activated, an additional time of 64 clock cycles of the newly selected clock has to be added. Table 25-1. Clock Switching Timings (Worst Case) From Main Clock SLCK PLL Clock Main Clock – 4 x SLCK + 2.5 x Main Clock SLCK 0.5 x Main Clock + 4.5 x SLCK – 3 x PLL Clock + 5 x SLCK 0.5 x Main Clock + 4 x SLCK + PLLCOUNT x SLCK + 2.5 x PLLx Clock 2.5 x PLL Clock + 5 x SLCK + PLLCOUNT x SLCK 2.5 x PLL Clock + 4 x SLCK + PLLCOUNT x SLCK To PLL Clock Notes: 1. 2. 3 x PLL Clock + 4 x SLCK + 1 x Main Clock PLL designates the PLLA . PLLCOUNT designates PLLACOUNT . 25.14.2 Clock Switching Waveforms Figure 25-4. Switch Master Clock from Slow Clock to PLLx Clock Slow Clock PLLx Clock LOCK MCKRDY Master Clock Write PMC_MCKR SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 405 Figure 25-5. Switch Master Clock from Main Clock to Slow Clock Slow Clock Main Clock MCKRDY Master Clock Write PMC_MCKR Figure 25-6. Change PLLx Programming Slow Clock PLLx Clock LOCKx MCKRDY Master Clock Slow Clock Write CKGR_PLLxR 406 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Figure 25-7. Programmable Clock Output Programming PLLx Clock PCKRDY PCKx Output Write PMC_PCKx PLL Clock is selected Write PMC_SCER Write PMC_SCDR PCKx is enabled PCKx is disabled 25.15 Write Protection Registers To prevent any single software error that may corrupt PMC behavior, certain address spaces can be write protected by setting the WPEN bit in the “PMC Write Protect Mode Register” (PMC_WPMR). If a write access to the protected registers is detected, then the WPVS flag in the PMC Write Protect Status Register (PMC_WPSR) is set and the field WPVSRC indicates in which register the write access has been attempted. The WPVS flag is reset by writing the PMC Write Protect Mode Register (PMC_WPMR) with the appropriate access key, WPKEY. The protected registers are: “PMC System Clock Enable Register” “PMC System Clock Disable Register” “PMC Peripheral Clock Enable Register 0” “PMC Peripheral Clock Disable Register 0” “PMC Clock Generator Main Oscillator Register” “PMC Clock Generator PLLA Register” “PMC Master Clock Register” “PMC Programmable Clock Register” “PMC Fast Start-up Mode Register” “PMC Fast Start-up Polarity Register” “PMC Oscillator Calibration Register” SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 407 25.16 Power Management Controller (PMC) User Interface Table 25-2. Register Mapping Offset Register Name Access Reset 0x0000 System Clock Enable Register PMC_SCER Write-only – 0x0004 System Clock Disable Register PMC_SCDR Write-only – 0x0008 System Clock Status Register PMC_SCSR Read-only 0x0000_0001 0x000C Reserved – – 0x0010 Peripheral Clock Enable Register 0 PMC_PCER0 Write-only – 0x0014 Peripheral Clock Disable Register 0 PMC_PCDR0 Write-only – 0x0018 Peripheral Clock Status Register 0 PMC_PCSR0 Read-only 0x0000_0000 0x001C Reserved – – 0x0020 Main Oscillator Register CKGR_MOR Read-write 0x0000_0008 0x0024 Main Clock Frequency Register CKGR_MCFR Read-write 0x0000_0000 0x0028 PLLA Register CKGR_PLLAR Read-write 0x0000_3F00 0x002C Reserved – – 0x0030 Master Clock Register Read-write 0x0000_0001 – – 0x0034 - 0x003C – – – PMC_MCKR Reserved – 0x0040 Programmable Clock 0 Register PMC_PCK0 Read-write 0x0000_0000 0x0044 Programmable Clock 1 Register PMC_PCK1 Read-write 0x0000_0000 0x0048 Programmable Clock 2 Register PMC_PCK2 Read-write 0x0000_0000 – – 0x004C - 0x005C Reserved – 0x0060 Interrupt Enable Register PMC_IER Write-only – 0x0064 Interrupt Disable Register PMC_IDR Write-only – 0x0068 Status Register PMC_SR Read-only 0x0001_0008 0x006C Interrupt Mask Register PMC_IMR Read-only 0x0000_0000 0x0070 Fast Start-up Mode Register PMC_FSMR Read-write 0x0000_0000 0x0074 Fast Start-up Polarity Register PMC_FSPR Read-write 0x0000_0000 0x0078 Fault Output Clear Register PMC_FOCR Write-only – – – 0x007C- 0x00E0 Reserved – 0x00E4 Write Protect Mode Register PMC_WPMR Read-write 0x0 0x00E8 Write Protect Status Register PMC_WPSR Read-only 0x0 0x00EC-0x00FC Reserved – – – 0x0100 - 0x0108 Reserved – – – 0x010C Reserved – – – 0x0110 Oscillator Calibration Register Read-write 0x0040_4040 PMC_OCR Note: If an offset is not listed in the table it must be considered as “reserved”. 408 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 25.16.1 PMC System Clock Enable Register Name: PMC_SCER Address: 0x400E0400 Access: Write-only 31 30 29 28 27 26 25 24 – – – – – – – – 23 22 21 20 19 18 17 16 – – – – – – – – 15 14 13 12 11 10 9 8 – – – – – PCK2 PCK1 PCK0 7 6 5 4 3 2 1 0 – – – – – – – – This register can only be written if the WPEN bit is cleared in “PMC Write Protect Mode Register” . • PCKx: Programmable Clock x Output Enable 0 = No effect. 1 = Enables the corresponding Programmable Clock output. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 409 25.16.2 PMC System Clock Disable Register Name: PMC_SCDR Address: 0x400E0404 Access: Write-only 31 30 29 28 27 26 25 24 – – – – – – – – 23 22 21 20 19 18 17 16 – – – – – – – – 15 14 13 12 11 10 9 8 – – – – – PCK2 PCK1 PCK0 7 6 5 4 3 2 1 0 – – – – – – – – This register can only be written if the WPEN bit is cleared in “PMC Write Protect Mode Register” . • PCKx: Programmable Clock x Output Disable 0 = No effect. 1 = Disables the corresponding Programmable Clock output. 410 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 25.16.3 PMC System Clock Status Register Name: PMC_SCSR Address: 0x400E0408 Access: Read-only 31 30 29 28 27 26 25 24 – – – – – – – – 23 22 21 20 19 18 17 16 – – – – – – – – 15 14 13 12 11 10 9 8 – – – – – PCK2 PCK1 PCK0 7 6 5 4 3 2 1 0 – – – – – – – – • PCKx: Programmable Clock x Output Status 0 = The corresponding Programmable Clock output is disabled. 1 = The corresponding Programmable Clock output is enabled. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 411 25.16.4 PMC Peripheral Clock Enable Register 0 Name: PMC_PCER0 Address: 0x400E0410 Access: Write-only 31 30 29 28 27 26 25 24 PID31 PID30 PID29 PID28 PID27 PID26 PID25 PID24 23 22 21 20 19 18 17 16 PID23 PID22 PID21 PID20 PID19 PID18 PID17 PID16 15 14 13 12 11 10 9 8 PID15 PID14 PID13 PID12 PID11 PID10 PID9 PID8 7 6 5 4 3 2 1 0 – – – – – – – – This register can only be written if the WPEN bit is cleared in “PMC Write Protect Mode Register” . • PIDx: Peripheral Clock x Enable 0 = No effect. 1 = Enables the corresponding peripheral clock. Note: To get PIDx, refer to identifiers as defined in the section “Peripheral Identifiers” in the product datasheet. Note: Programming the control bits of the Peripheral ID that are not implemented has no effect on the behavior of the PMC. 412 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 25.16.5 PMC Peripheral Clock Disable Register 0 Name: PMC_PCDR0 Address: 0x400E0414 Access: Write-only 31 30 29 28 27 26 25 24 PID31 PID30 PID29 PID28 PID27 PID26 PID25 PID24 23 22 21 20 19 18 17 16 PID23 PID22 PID21 PID20 PID19 PID18 PID17 PID16 15 14 13 12 11 10 9 8 PID15 PID14 PID13 PID12 PID11 PID10 PID9 PID8 7 6 5 4 3 2 1 0 – – – – – – – – This register can only be written if the WPEN bit is cleared in “PMC Write Protect Mode Register” . • PIDx: Peripheral Clock x Disable 0 = No effect. 1 = Disables the corresponding peripheral clock. Note: To get PIDx, refer to identifiers as defined in the section “Peripheral Identifiers” in the product datasheet. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 413 25.16.6 PMC Peripheral Clock Status Register 0 Name: PMC_PCSR0 Address: 0x400E0418 Access: Read-only 31 30 29 28 27 26 25 24 PID31 PID30 PID29 PID28 PID27 PID26 PID25 PID24 23 22 21 20 19 18 17 16 PID23 PID22 PID21 PID20 PID19 PID18 PID17 PID16 15 14 13 12 11 10 9 8 PID15 PID14 PID13 PID12 PID11 PID10 PID9 PID8 7 6 5 4 3 2 1 0 – – – – – – – – • PIDx: Peripheral Clock x Status 0 = The corresponding peripheral clock is disabled. 1 = The corresponding peripheral clock is enabled. Note: To get PIDx, refer to identifiers as defined in the section “Peripheral Identifiers” in the product datasheet. 414 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 25.16.7 PMC Clock Generator Main Oscillator Register Name: CKGR_MOR Address: 0x400E0420 Access: Read-write 31 – 30 – 29 – 28 – 27 – 26 XT32KFME 25 CFDEN 24 MOSCSEL 23 22 21 20 19 18 17 16 11 10 9 8 3 MOSCRCEN 2 WAITMODE 1 MOSCXTBY 0 MOSCXTEN KEY 15 14 13 12 MOSCXTST 7 – 6 5 MOSCRCF 4 This register can only be written if the WPEN bit is cleared in “PMC Write Protect Mode Register” . • KEY: Write Access Password Value Name 0x37 PASSWD Description Writing any other value in this field aborts the write operation. Always reads as 0. • MOSCXTEN: Main Crystal Oscillator Enable A crystal must be connected between XIN and XOUT. 0 = The Main Crystal Oscillator is disabled. 1 = The Main Crystal Oscillator is enabled. MOSCXTBY must be set to 0. When MOSCXTEN is set, the MOSCXTS flag is set once the Main Crystal Oscillator start-up time is achieved. • MOSCXTBY: Main Crystal Oscillator Bypass 0 = No effect. 1 = The Main Crystal Oscillator is bypassed. MOSCXTEN must be set to 0. An external clock must be connected on XIN. When MOSCXTBY is set, the MOSCXTS flag in PMC_SR is automatically set. Clearing MOSCXTEN and MOSCXTBY bits allows resetting the MOSCXTS flag. • WAITMODE: Wait Mode Command 0 = No effect. 1 = Enters the device in Wait Mode. Note: The WAITMODE bit is write-only. • MOSCRCEN: Main On-Chip RC Oscillator Enable 0 = The Main On-Chip RC Oscillator is disabled. 1 = The Main On-Chip RC Oscillator is enabled. When MOSCRCEN is set, the MOSCRCS flag is set once the Main On-Chip RC Oscillator start-up time is achieved. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 415 • MOSCRCF: Main On-Chip RC Oscillator Frequency Selection At start-up, the Main On-Chip RC Oscillator frequency is 4 MHz. Value Name Description 0x0 12_MHz The Fast RC Oscillator Frequency is at 12 MHz (default) 0x1 8_MHz The Fast RC Oscillator Frequency is at 8 MHz 0x2 4_MHz The Fast RC Oscillator Frequency is at 4 MHz Note: MOSCRCF must be changed only if MOSCRCS is set in the PMC_SR register. Therefore MOSCRCF and MOSCRCEN cannot be changed at the same time. • MOSCXTST: Main Crystal Oscillator Start-up Time Specifies the number of Slow Clock cycles multiplied by 8 for the Main Crystal Oscillator start-up time. • MOSCSEL: Main Oscillator Selection 0 = The Main On-Chip RC Oscillator is selected. 1 = The Main Crystal Oscillator is selected. • CFDEN: Clock Failure Detector Enable 0 = The Clock Failure Detector is disabled. 1 = The Clock Failure Detector is enabled. Note: 1. The slow RC oscillator must be enabled when the CFDEN is enabled. 2. The clock failure detection must be enabled only when system clock MCK selects the fast RC Oscillator. 3. Then the status register must be read 2 slow clock cycles after enabling. • XT32KFME: Slow Crystal Oscillator Frequency Monitoring Enable 0 = The 32768 Hz Crystal Oscillator Frequency Monitoring is disabled. 1 = The 32768 Hz Crystal Oscillator Frequency Monitoring is enabled. 416 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 25.16.8 PMC Clock Generator Main Clock Frequency Register Name: CKGR_MCFR Address: 0x400E0424 Access: Read-Write 31 – 30 – 29 – 28 – 27 – 26 – 25 – 24 – 23 – 22 – 21 – 20 RCMEAS 19 – 18 – 17 – 16 MAINFRDY 15 14 13 12 11 10 9 8 3 2 1 0 MAINF 7 6 5 4 MAINF This register can only be written if the WPEN bit is cleared in “PMC Write Protect Mode Register” . • MAINF: Main Clock Frequency Gives the number of Main Clock cycles within 16 Slow Clock periods. • MAINFRDY: Main Clock Ready 0 = MAINF value is not valid or the Main Oscillator is disabled or a measure has just been started by means of RCMEAS. 1 = The Main Oscillator has been enabled previously and MAINF value is available. Note: To ensure that a correct value is read on the MAINF bitfield, the MAINFRDY flag must be read at 1 then another read access must be performed on the register to get a stable value on the MAINF bitfield. • RCMEAS: RC Oscillator Frequency Measure (write-only) 0 = No effect. 1 = Restarts measuring of the main RC frequency. MAINF will carry the new frequency as soon as a low to high transition occurs on the MAINFRDY flag. The measure is performed on the main frequency (i.e. not limited to RC oscillator only), but if the main clock frequency source is the fast crystal oscillator, the restart of measuring is not needed because of the well known stability of crystal oscillators. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 417 25.16.9 PMC Clock Generator PLLA Register Name: CKGR_PLLAR Address: 0x400E0428 Access: Read-write 31 – 30 – 29 ONE 28 – 27 – 26 25 MULA 24 23 22 21 20 19 18 17 16 10 9 8 2 1 0 MULA 15 – 14 – 13 7 6 5 12 11 PLLACOUNT 4 3 DIVA Possible limitations on PLLA input frequencies and multiplier factors should be checked before using the PMC. Warning: Bit 29 must always be set to 1 when programming the CKGR_PLLAR register. This register can only be written if the WPEN bit is cleared in “PMC Write Protect Mode Register” . • DIVA: Divider 0 = Divider output is stuck at 0 and PLLA is disabled. 1 = Divider is bypassed (divide by 1) 2 up to 255 = clock is divided by DIVA • PLLACOUNT: PLLA Counter Specifies the number of Slow Clock cycles before the LOCKA bit is set in PMC_SR after CKGR_PLLAR is written. • MULA: PLLA Multiplier 0 = The PLLA is deactivated (PLLA also disabled if DIVA = 0). 1 up to 62 = The PLLA Clock frequency is the PLLA input frequency multiplied by MULA + 1. • ONE: Must Be Set to 1 Bit 29 must always be set to 1 when programming the CKGR_PLLAR register. 418 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 25.16.10 PMC Master Clock Register Name: PMC_MCKR Address: 0x400E0430 Access: Read-write 31 30 29 28 27 26 25 24 – – – – – – – – 23 22 21 20 19 18 17 16 – – – – – – – – 15 14 13 12 11 10 9 8 – – – PLLADIV2 – – – – 7 6 5 4 3 2 1 – – – PRES 0 CSS This register can only be written if the WPEN bit is cleared in “PMC Write Protect Mode Register” . • CSS: Master Clock Source Selection Value Name Description 0 SLOW_CLK Slow Clock is selected 1 MAIN_CLK Main Clock is selected 2 PLLA_CLK PLLA Clock is selected • PRES: Processor Clock Prescaler Value Name Description 0 CLK_1 Selected clock 1 CLK_2 Selected clock divided by 2 2 CLK_4 Selected clock divided by 4 3 CLK_8 Selected clock divided by 8 4 CLK_16 Selected clock divided by 16 5 CLK_32 Selected clock divided by 32 6 CLK_64 Selected clock divided by 64 7 CLK_3 Selected clock divided by 3 • PLLADIV2: PLLA Divisor by 2 PLLADIV2 PLLA Clock Division 0 PLLA clock frequency is divided by 1. 1 PLLA clock frequency is divided by 2. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 419 25.16.11 PMC Programmable Clock Register Name: PMC_PCKx Address: 0x400E0440 Access: Read-write 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 6 5 4 3 2 1 0 – PRES – CSS This register can only be written if the WPEN bit is cleared in “PMC Write Protect Mode Register” . • CSS: Master Clock Source Selection Value Name Description 0 SLOW_CLK Slow Clock is selected 1 MAIN_CLK Main Clock is selected 2 PLLA_CLK PLLA Clock is selected 4 MCK Master Clock is selected • PRES: Programmable Clock Prescaler 420 Value Name Description 0 CLK_1 Selected clock 1 CLK_2 Selected clock divided by 2 2 CLK_4 Selected clock divided by 4 3 CLK_8 Selected clock divided by 8 4 CLK_16 Selected clock divided by 16 5 CLK_32 Selected clock divided by 32 6 CLK_64 Selected clock divided by 64 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 25.16.12 PMC Interrupt Enable Register Name: PMC_IER Address: 0x400E0460 Access: Write-only 31 30 29 28 27 26 25 24 – – – – – – – – 23 22 21 20 19 18 17 16 – – XT32KERR – – CFDEV MOSCRCS MOSCSELS 15 14 13 12 11 10 9 8 – – – – – PCKRDY2 PCKRDY1 PCKRDY0 7 6 5 4 3 2 1 0 – – – – MCKRDY – LOCKA MOSCXTS • MOSCXTS: Main Crystal Oscillator Status Interrupt Enable • LOCKA: PLLA Lock Interrupt Enable • MCKRDY: Master Clock Ready Interrupt Enable • PCKRDYx: Programmable Clock Ready x Interrupt Enable • MOSCSELS: Main Oscillator Selection Status Interrupt Enable • MOSCRCS: Main On-Chip RC Status Interrupt Enable • CFDEV: Clock Failure Detector Event Interrupt Enable • XT32KERR: Slow Crystal Oscillator Error Interrupt Enable SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 421 25.16.13 PMC Interrupt Disable Register Name: PMC_IDR Address: 0x400E0464 Access: Write-only 31 30 29 28 27 26 25 24 – – – – – – – – 23 22 21 20 19 18 17 16 – – XT32KERR – – CFDEV MOSCRCS MOSCSELS 15 14 13 12 11 10 9 8 – – – – – PCKRDY2 PCKRDY1 PCKRDY0 7 6 5 4 3 2 1 0 – – – – MCKRDY – LOCKA MOSCXTS • MOSCXTS: Main Crystal Oscillator Status Interrupt Disable • LOCKA: PLLA Lock Interrupt Disable • MCKRDY: Master Clock Ready Interrupt Disable • PCKRDYx: Programmable Clock Ready x Interrupt Disable • MOSCSELS: Main Oscillator Selection Status Interrupt Disable • MOSCRCS: Main On-Chip RC Status Interrupt Disable • CFDEV: Clock Failure Detector Event Interrupt Disable • XT32KERR: Slow Crystal Oscillator Error Interrupt Disable 422 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 25.16.14 PMC Status Register Name: PMC_SR Address: 0x400E0468 Access: Read-only 31 30 29 28 27 26 25 24 – – – – – – – – 23 22 21 20 19 18 17 16 – – XT32KERR FOS CFDS CFDEV MOSCRCS MOSCSELS 15 14 13 12 11 10 9 8 – – – – – PCKRDY2 PCKRDY1 PCKRDY0 7 6 5 4 3 2 1 0 OSCSELS – – – MCKRDY – LOCKA MOSCXTS • MOSCXTS: Main XTAL Oscillator Status 0 = Main XTAL oscillator is not stabilized. 1 = Main XTAL oscillator is stabilized. • LOCKA: PLLA Lock Status 0 = PLLA is not locked 1 = PLLA is locked. • MCKRDY: Master Clock Status 0 = Master Clock is not ready. 1 = Master Clock is ready. • OSCSELS: Slow Clock Oscillator Selection 0 = Internal slow clock RC oscillator is selected. 1 = External slow clock 32 kHz oscillator is selected. • PCKRDYx: Programmable Clock Ready Status 0 = Programmable Clock x is not ready. 1 = Programmable Clock x is ready. • MOSCSELS: Main Oscillator Selection Status 0 = Selection is in progress. 1 = Selection is done. • MOSCRCS: Main On-Chip RC Oscillator Status 0 = Main on-chip RC oscillator is not stabilized. 1 = Main on-chip RC oscillator is stabilized. • CFDEV: Clock Failure Detector Event 0 = No clock failure detection of the main on-chip RC oscillator clock has occurred since the last read of PMC_SR. 1 = At least one clock failure detection of the main on-chip RC oscillator clock has occurred since the last read of PMC_SR. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 423 • CFDS: Clock Failure Detector Status 0 = A clock failure of the main on-chip RC oscillator clock is not detected. 1 = A clock failure of the main on-chip RC oscillator clock is detected. • FOS: Clock Failure Detector Fault Output Status 0 = The fault output of the clock failure detector is inactive. 1 = The fault output of the clock failure detector is active. • XT32KERR: Slow Crystal Oscillator Error 0 = The frequency of the slow crystal oscillator is correct (32768 Hz +/- 1%) or the monitoring is disabled. 1 = The frequency of the slow crystal oscillator is incorrect or has been incorrect for an elapsed period of time since the monitoring has been enabled. 424 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 25.16.15 PMC Interrupt Mask Register Name: PMC_IMR Address: 0x400E046C Access: Read-only 31 30 29 28 27 26 25 24 – – – – – – – – 23 22 21 20 19 18 17 16 – – XT32KERR – – CFDEV MOSCRCS MOSCSELS 15 14 13 12 11 10 9 8 – – – – – PCKRDY2 PCKRDY1 PCKRDY0 7 6 5 4 3 2 1 0 – – – – MCKRDY – LOCKA MOSCXTS • MOSCXTS: Main Crystal Oscillator Status Interrupt Mask • LOCKA: PLLA Lock Interrupt Mask • MCKRDY: Master Clock Ready Interrupt Mask • PCKRDYx: Programmable Clock Ready x Interrupt Mask • MOSCSELS: Main Oscillator Selection Status Interrupt Mask • MOSCRCS: Main On-Chip RC Status Interrupt Mask • CFDEV: Clock Failure Detector Event Interrupt Mask • XT32KERR: Slow Crystal Oscillator Error Interrupt Mask SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 425 25.16.16 PMC Fast Start-up Mode Register Name: PMC_FSMR Address: 0x400E0470 Access: Read-write 31 – 30 – 29 – 28 – 27 – 26 – 25 – 24 – 23 – 22 21 20 LPM 19 – 18 – 17 RTCAL 16 RTTAL 15 FSTT15 14 FSTT14 13 FSTT13 12 FSTT12 11 FSTT11 10 FSTT10 9 FSTT9 8 FSTT8 7 FSTT7 6 FSTT6 5 FSTT5 4 FSTT4 3 FSTT3 2 FSTT2 1 FSTT1 0 FSTT0 FLPM This register can only be written if the WPEN bit is cleared in “PMC Write Protect Mode Register” . • FSTT0 - FSTT15: Fast Start-up Input Enable 0 to 15 0 = The corresponding wake-up input has no effect on the Power Management Controller. 1 = The corresponding wake-up input enables a fast restart signal to the Power Management Controller. • RTTAL: RTT Alarm Enable 0 = The RTT alarm has no effect on the Power Management Controller. 1 = The RTT alarm enables a fast restart signal to the Power Management Controller. • RTCAL: RTC Alarm Enable 0 = The RTC alarm has no effect on the Power Management Controller. 1 = The RTC alarm enables a fast restart signal to the Power Management Controller. • LPM: Low Power Mode 0 = The WaitForInterrupt (WFI) or the WaitForEvent (WFE) instruction of the processor makes the processor enter Sleep Mode. 1 = The WaitForEvent (WFE) instruction of the processor makes the system to enter in Wait Mode. • FLPM: Flash Low Power Mode Value 426 Name Description 0 FLASH_STANDBY Flash is in Standby Mode when system enters Wait Mode 1 FLASH_DEEP_POWERDOWN Flash is in deep power down mode when system enters Wait Mode 2 FLASH_IDLE idle mode SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 25.16.17 PMC Fast Start-up Polarity Register Name: PMC_FSPR Address: 0x400E0474 Access: Read-write 31 – 30 – 29 – 28 – 27 – 26 – 25 – 24 – 23 – 22 – 21 – 20 – 19 – 18 – 17 – 16 – 15 FSTP15 14 FSTP14 13 FSTP13 12 FSTP12 11 FSTP11 10 FSTP10 9 FSTP9 8 FSTP8 7 FSTP7 6 FSTP6 5 FSTP5 4 FSTP4 3 FSTP3 2 FSTP2 1 FSTP1 0 FSTP0 This register can only be written if the WPEN bit is cleared in “PMC Write Protect Mode Register” . • FSTPx: Fast Start-up Input Polarityx Defines the active polarity of the corresponding wake-up input. If the corresponding wake-up input is enabled and at the FSTP level, it enables a fast restart signal. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 427 25.16.18 PMC Fault Output Clear Register Name: PMC_FOCR Address: 0x400E0478 Access: Write-only 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 – 6 – 5 – 4 – 3 – 2 – 1 – 0 FOCLR • FOCLR: Fault Output Clear Clears the clock failure detector fault output. 428 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 25.16.19 PMC Write Protect Mode Register Name: PMC_WPMR Address: 0x400E04E4 Access: Read-write Reset: See Table 25-2 31 30 29 28 27 26 25 24 19 18 17 16 11 10 9 8 WPKEY 23 22 21 20 WPKEY 15 14 13 12 WPKEY 7 6 5 4 3 2 1 0 – – – – – – – WPEN • WPEN: Write Protect Enable 0 = Disables the Write Protect if WPKEY corresponds to 0x504D43 (“PMC” in ASCII). 1 = Enables the Write Protect if WPKEY corresponds to 0x504D43 (“PMC” in ASCII). Protects the registers: “PMC System Clock Enable Register” “PMC System Clock Disable Register” “PMC Peripheral Clock Enable Register 0” “PMC Peripheral Clock Disable Register 0” “PMC Clock Generator Main Oscillator Register” “PMC Clock Generator PLLA Register” “PMC Master Clock Register” “PMC Programmable Clock Register” “PMC Fast Start-up Mode Register” “PMC Fast Start-up Polarity Register” “PMC Oscillator Calibration Register” • WPKEY: Write Protect KEY Value 0x504D43 Name Description PASSWD Writing any other value in this field aborts the write operation of the WPEN bit. Always reads as 0. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 429 25.16.20 PMC Write Protect Status Register Name: PMC_WPSR Address: 0x400E04E8 Access: Read-only Reset: See Table 25-2 31 30 29 28 27 26 25 24 – – – – – – – – 23 22 21 20 19 18 17 16 11 10 9 8 WPVSRC 15 14 13 12 WPVSRC 7 6 5 4 3 2 1 0 – – – – – – – WPVS • WPVS: Write Protect Violation Status 0 = No Write Protect Violation has occurred since the last read of the PMC_WPSR register. 1 = A Write Protect Violation has occurred since the last read of the PMC_WPSR register. If this violation is an unauthorized attempt to write a protected register, the associated violation is reported into field WPVSRC. • WPVSRC: Write Protect Violation Source When WPVS is active, this field indicates the write-protected register (through address offset or code) in which a write access has been attempted. Reading PMC_WPSR automatically clears all fields. 430 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 25.16.21 PMC Oscillator Calibration Register Name: PMC_OCR Address: 0x400E0510 Access: Read-write 31 – 30 – 29 – 28 – 27 – 26 – 25 – 24 – 23 SEL12 22 21 20 19 CAL12 18 17 16 15 SEL8 14 13 12 11 CAL8 10 9 8 7 SEL4 6 5 4 3 CAL4 2 1 0 This register can only be written if the WPEN bit is cleared in “PMC Write Protect Mode Register” . • CAL4: RC Oscillator Calibration bits for 4 MHz Calibration bits applied to the RC Oscillator when SEL4 is set. • SEL4: Selection of RC Oscillator Calibration bits for 4 MHz 0 = Default value stored in Flash memory. 1 = Value written by user in CAL4 field of this register. • CAL8: RC Oscillator Calibration bits for 8 MHz Calibration bits applied to the RC Oscillator when SEL8 is set. • SEL8: Selection of RC Oscillator Calibration bits for 8 MHz 0 = Factory determined value stored in Flash memory. 1 = Value written by user in CAL8 field of this register. • CAL12: RC Oscillator Calibration bits for 12 MHz Calibration bits applied to the RC Oscillator when SEL12 is set. • SEL12: Selection of RC Oscillator Calibration bits for 12 MHz 0 = Factory determined value stored in Flash memory. 1 = Value written by user in CAL12 field of this register. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 431 26. Chip Identifier (CHIPID) 26.1 Description Chip Identifier (CHIPID) registers permit recognition of the device and its revision. These registers provide the sizes and types of the on-chip memories, as well as the set of embedded peripherals. Two chip identifier registers are embedded: CHIPID_CIDR (Chip ID Register) and CHIPID_EXID (Extension ID). Both registers contain a hard-wired value that is read-only. The first register contains the following fields: EXT - shows the use of the extension identifier register NVPTYP and NVPSIZ - identifies the type of embedded non-volatile memory and its size ARCH - identifies the set of embedded peripherals SRAMSIZ - indicates the size of the embedded SRAM EPROC - indicates the embedded ARM processor VERSION - gives the revision of the silicon The second register is device-dependent and reads 0 if the bit EXT is 0. 26.2 Embedded Characteristics Chip ID Registers ̶ Identification of the Device Revision, Sizes of the Embedded Memories, Set of Peripherals, Embedded Processor Table 26-1. 432 SAM4N Chip IDs Registers Chip Name CHIPID_CIDR CHIPID_EXID SAM4N16B (Rev A) 0x2946_0CE0 0x0 SAM4N16C (Rev A) 0x2956_0CE0 0x0 SAM4N8A (Rev A) 0x293B_0AE0 0x0 SAM4N8B (Rev A) 0x294B_0AE0 0x0 SAM4N8C (Rev A) 0x295B_0AE0 0x0 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 26.3 Chip Identifier (CHIPID) User Interface Table 26-2. Offset Register Mapping Register Name Access Reset 0x0 Chip ID Register CHIPID_CIDR Read-only – 0x4 Chip ID Extension Register CHIPID_EXID Read-only – SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 433 26.3.1 Chip ID Register Name: CHIPID_CIDR Address: 0x400E0740 Access: Read-only 31 EXT 30 23 22 29 NVPTYP 28 21 20 27 26 19 18 ARCH 15 14 13 6 EPROC 12 5 4 Current version of the device. • EPROC: Embedded Processor Name Description 1 ARM946ES ARM946ES 2 ARM7TDMI ARM7TDMI 3 CM3 Cortex-M3 4 ARM920T ARM920T 5 ARM926EJS ARM926EJS 6 CA5 Cortex-A5 7 CM4 Cortex-M4 • NVPSIZ: Nonvolatile Program Memory Size 434 17 16 11 10 9 8 1 0 NVPSIZ • VERSION: Version of the Device Value 24 SRAMSIZ NVPSIZ2 7 25 ARCH Value Name Description 0 NONE None 1 8K 8 Kbytes 2 16K 16 Kbytes 3 32K 32 Kbytes 4 – Reserved 5 64K 64 Kbytes 6 – Reserved 7 128K 128 Kbytes 8 – Reserved 9 256K 256 Kbytes 10 512K 512 Kbytes 11 – Reserved SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 3 2 VERSION Value Name Description 12 1024K 1024 Kbytes 13 – Reserved 14 2048K 2048 Kbytes 15 – Reserved • NVPSIZ2: Second Nonvolatile Program Memory Size Value Name Description 0 NONE None 1 8K 8 Kbytes 2 16K 16 Kbytes 3 32K 32 Kbytes 4 – Reserved 5 64K 64 Kbytes 6 – Reserved 7 128K 128 Kbytes 8 – Reserved 9 256K 256 Kbytes 10 512K 512 Kbytes 11 – Reserved 12 1024K 1024 Kbytes 13 – Reserved 14 2048K 2048 Kbytes 15 – Reserved • SRAMSIZ: Internal SRAM Size Value Name Description 0 48K 48 Kbytes 1 192K 192 Kbytes 2 2K 2 Kbytes 3 6K 6 Kbytes 4 24K 24 Kbytes 5 4K 4 Kbytes 6 80K 80 Kbytes 7 160K 160 Kbytes 8 8K 8 Kbytes 9 16K 16 Kbytes 10 32K 32 Kbytes 11 64K 64 Kbytes 12 128K 128 Kbytes SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 435 Value Name Description 13 256K 256 Kbytes 14 96K 96 Kbytes 15 512K 512 Kbytes • ARCH: Architecture Identifier 436 Value Name Description 0x19 AT91SAM9xx AT91SAM9xx Series 0x29 AT91SAM9XExx AT91SAM9XExx Series 0x34 AT91x34 AT91x34 Series 0x37 CAP7 CAP7 Series 0x39 CAP9 CAP9 Series 0x3B CAP11 CAP11 Series 0x40 AT91x40 AT91x40 Series 0x42 AT91x42 AT91x42 Series 0x45 AT91SAM4SH2 AT91SAM4SH2 Series 0x55 AT91x55 AT91x55 Series 0x60 AT91SAM7Axx AT91SAM7Axx Series 0x61 AT91SAM7AQxx AT91SAM7AQxx Series 0x63 AT91x63 AT91x63 Series 0x64 SAM4CxxC SAM4CxC Series (100-pin version) 0x66 SAM4CxxE SAM4CxE Series (144-pin version) 0x70 AT91SAM7Sxx AT91SAM7Sxx Series 0x71 AT91SAM7XCxx AT91SAM7XCxx Series 0x72 AT91SAM7SExx AT91SAM7SExx Series 0x73 AT91SAM7Lxx AT91SAM7Lxx Series 0x75 AT91SAM7Xxx AT91SAM7Xxx Series 0x76 AT91SAM7SLxx AT91SAM7SLxx Series 0x80 SAM3UxC SAM3UxC Series (100-pin version) 0x81 SAM3UxE SAM3UxE Series (144-pin version) 0x83 SAM3AxC SAM3AxC Series (100-pin version) 0x84 SAM3XxC SAM3XxC Series (100-pin version) 0x85 SAM3XxE SAM3XxE Series (144-pin version) 0x86 SAM3XxG SAM3XxG Series (208/217-pin version) 0x92 AT91x92 AT91x92 Series 0x93 SAM4NxA SAM4NxA Series (48-pin version) 0x94 SAM4NxB SAM4NxB Series (64-pin version) 0x95 SAM4NxC SAM4NxC Series (100-pin version) 0x99 SAM3SDxB SAM3SDxB Series (64-pin version) SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Value Name Description 0x9A SAM3SDxC SAM3SDxC Series (100-pin version) 0xA5 SAM5A SAM5A 0xB0 SAM4LxA SAM4LxA Series (48-pin version) 0xB1 SAM4LxB SAM4LxB Series (64-pin version) 0xB2 SAM4LxC SAM4LxC Series (100-pin version) 0xF0 AT75Cxx AT75Cxx Series • NVPTYP: Nonvolatile Program Memory Type Value Name Description 0 ROM ROM 1 ROMLESS ROMless or on-chip Flash 4 SRAM SRAM emulating ROM 2 FLASH Embedded Flash Memory ROM and Embedded Flash Memory 3 ROM_FLASH NVPSIZ is ROM size NVPSIZ2 is Flash size • EXT: Extension Flag 0 = Chip ID has a single register definition without extension 1 = An extended Chip ID exists. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 437 26.3.2 Chip ID Extension Register Name: CHIPID_EXID Address: 0x400E0744 Access: Read-only 31 30 29 28 27 26 25 24 19 18 17 16 11 10 9 8 3 2 1 0 EXID 23 22 21 20 EXID 15 14 13 12 EXID 7 6 5 4 EXID • EXID: Chip ID Extension Reads 0 if the EXT bit in CHIPID_CIDR is 0. 438 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 27. Parallel Input/Output (PIO) Controller 27.1 Description The Parallel Input/Output Controller (PIO) manages up to 32 fully programmable input/output lines. Each I/O line may be dedicated as a general-purpose I/O or be assigned to a function of an embedded peripheral. This assures effective optimization of the pins of a product. Each I/O line is associated with a bit number in all of the 32-bit registers of the 32-bit wide User Interface. Each I/O line of the PIO Controller features: An input change interrupt enabling level change detection on any I/O line. Additional Interrupt modes enabling rising edge, falling edge, low level or high level detection on any I/O line. A glitch filter providing rejection of glitches lower than one-half of PIO clock cycle. A debouncing filter providing rejection of unwanted pulses from key or push button operations. Multi-drive capability similar to an open drain I/O line. Control of the pull-up and pull-down of the I/O line. Input visibility and output control. The PIO Controller also features a synchronous output providing up to 32 bits of data output in a single write operation. 27.2 Embedded Characteristics Up to 32 Programmable I/O Lines Fully Programmable through Set/Clear Registers Multiplexing of Four Peripheral Functions per I/O Line For each I/O Line (Whether Assigned to a Peripheral or Used as General Purpose I/O) ̶ Input Change Interrupt ̶ Programmable Glitch Filter ̶ Programmable Debouncing Filter ̶ Multi-drive Option Enables Driving in Open Drain ̶ Programmable Pull Up on Each I/O Line ̶ Pin Data Status Register, Supplies Visibility of the Level on the Pin at Any Time ̶ Additional Interrupt Modes on a Programmable Event: Rising Edge, Falling Edge, Low Level or High Level Synchronous Output, Provides Set and Clear of Several I/O lines in a Single Write Write Protect Registers Programmable Schmitt Trigger Inputs SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 439 27.3 Block Diagram Figure 27-1. Block Diagram PIO Controller Interrupt Controller PIO Interrupt PIO Clock PMC Data, Enable Up to 32 peripheral IOs Embedded Peripheral PIN 0 Data, Enable PIN 1 Up to 32 pins Up to 32 peripheral IOs Embedded Peripheral PIN 31 APB Figure 27-2. Application Block Diagram On-Chip Peripheral Drivers Keyboard Driver Control & Command Driver On-Chip Peripherals PIO Controller Keyboard Driver 440 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 General Purpose I/Os External Devices 27.4 Product Dependencies 27.4.1 Pin Multiplexing Each pin is configurable, according to product definition as either a general-purpose I/O line only, or as an I/O line multiplexed with one or two peripheral I/Os. As the multiplexing is hardware defined and thus product-dependent, the hardware designer and programmer must carefully determine the configuration of the PIO controllers required by their application. When an I/O line is general-purpose only, i.e. not multiplexed with any peripheral I/O, programming of the PIO Controller regarding the assignment to a peripheral has no effect and only the PIO Controller can control how the pin is driven by the product. 27.4.2 External Interrupt Lines The interrupt signals FIQ and IRQ0 to IRQn are most generally multiplexed through the PIO Controllers. However, it is not necessary to assign the I/O line to the interrupt function as the PIO Controller has no effect on inputs and the interrupt lines (FIQ or IRQs) are used only as inputs. 27.4.3 Power Management The Power Management Controller controls the PIO Controller clock in order to save power. Writing any of the registers of the user interface does not require the PIO Controller clock to be enabled. This means that the configuration of the I/O lines does not require the PIO Controller clock to be enabled. However, when the clock is disabled, not all of the features of the PIO Controller are available, including glitch filtering. Note that the Input Change Interrupt, Interrupt Modes on a programmable event and the read of the pin level require the clock to be validated. After a hardware reset, the PIO clock is disabled by default. The user must configure the Power Management Controller before any access to the input line information. 27.4.4 Interrupt Generation For interrupt handling, the PIO Controllers are considered as user peripherals. This means that the PIO Controller interrupt lines are connected among the interrupt sources. Refer to the PIO Controller peripheral identifier in the product description to identify the interrupt sources dedicated to the PIO Controllers. Using the PIO Controller requires the Interrupt Controller to be programmed first. The PIO Controller interrupt can be generated only if the PIO Controller clock is enabled. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 441 27.5 Functional Description The PIO Controller features up to 32 fully-programmable I/O lines. Most of the control logic associated to each I/O is represented in Figure 27-3. In this description each signal shown represents but one of up to 32 possible indexes. Figure 27-3. I/O Line Control Logic PIO_OER[0] VDD PIO_OSR[0] PIO_PUER[0] PIO_ODR[0] PIO_PUSR[0] PIO_PUDR[0] 1 Peripheral A Output Enable 00 01 10 11 Peripheral B Output Enable Peripheral C Output Enable Peripheral D Output Enable 0 0 PIO_PER[0] PIO_ABCDSR1[0] PIO_PDR[0] 00 01 10 11 Peripheral B Output Peripheral C Output Peripheral D Output 1 PIO_PSR[0] PIO_ABCDSR2[0] Peripheral A Output Integrated Pull-Up Resistor PIO_MDER[0] PIO_MDSR[0] 0 PIO_MDDR[0] 0 PIO_SODR[0] 1 PIO_ODSR[0] Pad PIO_CODR[0] 1 PIO_PPDER[0] Integrated Pull-Down Resistor PIO_PPDSR[0] PIO_PPDDR[0] GND Peripheral A Input Peripheral B Input Peripheral C Input Peripheral D Input PIO_PDSR[0] PIO_ISR[0] 0 D PIO Clock 0 Slow Clock PIO_SCDR Clock Divider 1 Programmable Glitch or Debouncing Filter Q DFF D Q DFF EVENT DETECTOR PIO Interrupt 1 Resynchronization Stage PIO_IER[0] PIO_IMR[0] PIO_IFER[0] PIO_IDR[0] PIO_IFSR[0] PIO_IFSCER[0] PIO_IFDR[0] PIO_IFSCSR[0] PIO_IFSCDR[0] PIO_ISR[31] PIO_IER[31] PIO_IMR[31] PIO_IDR[31] 442 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 (Up to 32 possible inputs) 27.5.1 Pull-up and Pull-down Resistor Control Each I/O line is designed with an embedded pull-up resistor and an embedded pull-down resistor. The pull-up resistor can be enabled or disabled by writing respectively PIO_PUER (Pull-up Enable Register) and PIO_PUDR (Pull-up Disable Resistor). Writing in these registers results in setting or clearing the corresponding bit in PIO_PUSR (Pull-up Status Register). Reading a 1 in PIO_PUSR means the pull-up is disabled and reading a 0 means the pull-up is enabled. The pull-down resistor can be enabled or disabled by writing respectively PIO_PPDER (Pull-down Enable Register) and PIO_PPDDR (Pull-down Disable Resistor). Writing in these registers results in setting or clearing the corresponding bit in PIO_PPDSR (Pull-down Status Register). Reading a 1 in PIO_PPDSR means the pull-up is disabled and reading a 0 means the pull-down is enabled. Enabling the pull-down resistor while the pull-up resistor is still enabled is not possible. In this case, the write of PIO_PPDER for the concerned I/O line is discarded. Likewise, enabling the pull-up resistor while the pull-down resistor is still enabled is not possible. In this case, the write of PIO_PUER for the concerned I/O line is discarded. Control of the pull-up resistor is possible regardless of the configuration of the I/O line. After reset, all of the pull-ups are enabled, i.e. PIO_PUSR resets at the value 0x0, and all the pull-downs are disabled, i.e. PIO_PPDSR resets at the value 0xFFFFFFFF. 27.5.2 I/O Line or Peripheral Function Selection When a pin is multiplexed with one or two peripheral functions, the selection is controlled with the registers PIO_PER (PIO Enable Register) and PIO_PDR (PIO Disable Register). The register PIO_PSR (PIO Status Register) is the result of the set and clear registers and indicates whether the pin is controlled by the corresponding peripheral or by the PIO Controller. A value of 0 indicates that the pin is controlled by the corresponding on-chip peripheral selected in the PIO_ABCDSR1 and PIO_ABCDSR2 (ABCD Select Registers). A value of 1 indicates the pin is controlled by the PIO controller. If a pin is used as a general purpose I/O line (not multiplexed with an on-chip peripheral), PIO_PER and PIO_PDR have no effect and PIO_PSR returns 1 for the corresponding bit. After reset, most generally, the I/O lines are controlled by the PIO controller, i.e. PIO_PSR resets at 1. However, in some events, it is important that PIO lines are controlled by the peripheral (as in the case of memory chip select lines that must be driven inactive after reset or for address lines that must be driven low for booting out of an external memory). Thus, the reset value of PIO_PSR is defined at the product level, depending on the multiplexing of the device. 27.5.3 Peripheral A or B or C or D Selection The PIO Controller provides multiplexing of up to four peripheral functions on a single pin. The selection is performed by writing PIO_ABCDSR1 and PIO_ABCDSR2 (ABCD Select Registers). For each pin: The corresponding bit at level 0 in PIO_ABCDSR1 and the corresponding bit at level 0 in PIO_ABCDSR2 means peripheral A is selected. The corresponding bit at level 1 in PIO_ABCDSR1 and the corresponding bit at level 0 in PIO_ABCDSR2 means peripheral B is selected. The corresponding bit at level 0 in PIO_ABCDSR1 and the corresponding bit at level 1 in PIO_ABCDSR2 means peripheral C is selected. The corresponding bit at level 1 in PIO_ABCDSR1 and the corresponding bit at level 1 in PIO_ABCDSR2 means peripheral D is selected. Note that multiplexing of peripheral lines A, B, C and D only affects the output line. The peripheral input lines are always connected to the pin input. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 443 Writing in PIO_ABCDSR1 and PIO_ABCDSR2 manages the multiplexing regardless of the configuration of the pin. However, assignment of a pin to a peripheral function requires a write in the peripheral selection registers (PIO_ABCDSR1 and PIO_ABCDSR2) in addition to a write in PIO_PDR. After reset, PIO_ABCDSR1 and PIO_ABCDSR2 are 0, thus indicating that all the PIO lines are configured on peripheral A. However, peripheral A generally does not drive the pin as the PIO Controller resets in I/O line mode. 27.5.4 Output Control When the I/0 line is assigned to a peripheral function, i.e. the corresponding bit in PIO_PSR is at 0, the drive of the I/O line is controlled by the peripheral. Peripheral A or B or C or D depending on the value in PIO_ABCDSR1 and PIO_ABCDSR2 (ABCD Select Registers) determines whether the pin is driven or not. When the I/O line is controlled by the PIO controller, the pin can be configured to be driven. This is done by writing PIO_OER (Output Enable Register) and PIO_ODR (Output Disable Register). The results of these write operations are detected in PIO_OSR (Output Status Register). When a bit in this register is at 0, the corresponding I/O line is used as an input only. When the bit is at 1, the corresponding I/O line is driven by the PIO controller. The level driven on an I/O line can be determined by writing in PIO_SODR (Set Output Data Register) and PIO_CODR (Clear Output Data Register). These write operations respectively set and clear PIO_ODSR (Output Data Status Register), which represents the data driven on the I/O lines. Writing in PIO_OER and PIO_ODR manages PIO_OSR whether the pin is configured to be controlled by the PIO controller or assigned to a peripheral function. This enables configuration of the I/O line prior to setting it to be managed by the PIO Controller. Similarly, writing in PIO_SODR and PIO_CODR effects PIO_ODSR. This is important as it defines the first level driven on the I/O line. 27.5.5 Synchronous Data Output Clearing one (or more) PIO line(s) and setting another one (or more) PIO line(s) synchronously cannot be done by using PIO_SODR and PIO_CODR registers. It requires two successive write operations into two different registers. To overcome this, the PIO Controller offers a direct control of PIO outputs by single write access to PIO_ODSR (Output Data Status Register).Only bits unmasked by PIO_OWSR (Output Write Status Register) are written. The mask bits in PIO_OWSR are set by writing to PIO_OWER (Output Write Enable Register) and cleared by writing to PIO_OWDR (Output Write Disable Register). After reset, the synchronous data output is disabled on all the I/O lines as PIO_OWSR resets at 0x0. 27.5.6 Multi Drive Control (Open Drain) Each I/O can be independently programmed in Open Drain by using the Multi Drive feature. This feature permits several drivers to be connected on the I/O line which is driven low only by each device. An external pull-up resistor (or enabling of the internal one) is generally required to guarantee a high level on the line. The Multi Drive feature is controlled by PIO_MDER (Multi-driver Enable Register) and PIO_MDDR (Multi-driver Disable Register). The Multi Drive can be selected whether the I/O line is controlled by the PIO controller or assigned to a peripheral function. PIO_MDSR (Multi-driver Status Register) indicates the pins that are configured to support external drivers. After reset, the Multi Drive feature is disabled on all pins, i.e. PIO_MDSR resets at value 0x0. 27.5.7 Output Line Timings Figure 27-4 shows how the outputs are driven either by writing PIO_SODR or PIO_CODR, or by directly writing PIO_ODSR. This last case is valid only if the corresponding bit in PIO_OWSR is set. Figure 27-4 also shows when the feedback in PIO_PDSR is available. 444 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Figure 27-4. Output Line Timings MCK Write PIO_SODR Write PIO_ODSR at 1 APB Access Write PIO_CODR Write PIO_ODSR at 0 APB Access PIO_ODSR 2 cycles 2 cycles PIO_PDSR 27.5.8 Inputs The level on each I/O line can be read through PIO_PDSR (Pin Data Status Register). This register indicates the level of the I/O lines regardless of their configuration, whether uniquely as an input or driven by the PIO controller or driven by a peripheral. Reading the I/O line levels requires the clock of the PIO controller to be enabled, otherwise PIO_PDSR reads the levels present on the I/O line at the time the clock was disabled. 27.5.9 Input Glitch and Debouncing Filters Optional input glitch and debouncing filters are independently programmable on each I/O line. The glitch filter can filter a glitch with a duration of less than 1/2 Master Clock (MCK) and the debouncing filter can filter a pulse of less than 1/2 Period of a Programmable Divided Slow Clock. The selection between glitch filtering or debounce filtering is done by writing in the registers PIO_IFSCDR (PIO Input Filter Slow Clock Disable Register) and PIO_IFSCER (PIO Input Filter Slow Clock Enable Register). Writing PIO_IFSCDR and PIO_IFSCER respectively, sets and clears bits in PIO_IFSCSR. The current selection status can be checked by reading the register PIO_IFSCSR (Input Filter Slow Clock Status Register). If PIO_IFSCSR[i] = 0: The glitch filter can filter a glitch with a duration of less than 1/2 Period of Master Clock. If PIO_IFSCSR[i] = 1: The debouncing filter can filter a pulse with a duration of less than 1/2 Period of the Programmable Divided Slow Clock. For the debouncing filter, the Period of the Divided Slow Clock is performed by writing in the DIV field of the PIO_SCDR (Slow Clock Divider Register) Tdiv_slclk = ((DIV+1)*2).Tslow_clock When the glitch or debouncing filter is enabled, a glitch or pulse with a duration of less than 1/2 Selected Clock Cycle (Selected Clock represents MCK or Divided Slow Clock depending on PIO_IFSCDR and PIO_IFSCER programming) is automatically rejected, while a pulse with a duration of 1 Selected Clock (MCK or Divided Slow Clock) cycle or more is accepted. For pulse durations between 1/2 Selected Clock cycle and 1 Selected Clock cycle the pulse may or may not be taken into account, depending on the precise timing of its occurrence. Thus for a pulse to be visible it must exceed 1 Selected Clock cycle, whereas for a glitch to be reliably filtered out, its duration must not exceed 1/2 Selected Clock cycle. The filters also introduce some latencies, this is illustrated in Figure 27-5 and Figure 27-6. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 445 The glitch filters are controlled by the register set: PIO_IFER (Input Filter Enable Register), PIO_IFDR (Input Filter Disable Register) and PIO_IFSR (Input Filter Status Register). Writing PIO_IFER and PIO_IFDR respectively sets and clears bits in PIO_IFSR. This last register enables the glitch filter on the I/O lines. When the glitch and/or debouncing filter is enabled, it does not modify the behavior of the inputs on the peripherals. It acts only on the value read in PIO_PDSR and on the input change interrupt detection. The glitch and debouncing filters require that the PIO Controller clock is enabled. Figure 27-5. Input Glitch Filter Timing PIO_IFCSR = 0 MCK up to 1.5 cycles Pin Level 1 cycle 1 cycle 1 cycle 1 cycle PIO_PDSR if PIO_IFSR = 0 2 cycles up to 2.5 cycles PIO_PDSR if PIO_IFSR = 1 Figure 27-6. 1 cycle up to 2 cycles Input Debouncing Filter Timing PIO_IFCSR = 1 Divided Slow Clock Pin Level up to 2 cycles Tmck up to 2 cycles Tmck PIO_PDSR if PIO_IFSR = 0 1 cycle Tdiv_slclk PIO_PDSR if PIO_IFSR = 1 1 cycle Tdiv_slclk up to 1.5 cycles Tdiv_slclk up to 1.5 cycles Tdiv_slclk up to 2 cycles Tmck up to 2 cycles Tmck 27.5.10 Input Edge/Level Interrupt The PIO Controller can be programmed to generate an interrupt when it detects an edge or a level on an I/O line. The Input Edge/Level Interrupt is controlled by writing PIO_IER (Interrupt Enable Register) and PIO_IDR (Interrupt Disable Register), which respectively enable and disable the input change interrupt by setting and clearing the corresponding bit in PIO_IMR (Interrupt Mask Register). As Input change detection is possible only by comparing two successive samplings of the input of the I/O line, the PIO Controller clock must be enabled. The Input Change Interrupt is available, regardless of the configuration of the I/O line, i.e. configured as an input only, controlled by the PIO Controller or assigned to a peripheral function. By default, the interrupt can be generated at any time an edge is detected on the input. Some additional Interrupt modes can be enabled/disabled by writing in the PIO_AIMER (Additional Interrupt Modes Enable Register) and PIO_AIMDR (Additional Interrupt Modes Disable Register). The current state of this selection can be read through the PIO_AIMMR (Additional Interrupt Modes Mask Register) 446 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 These Additional Modes are: Rising Edge Detection Falling Edge Detection Low Level Detection High Level Detection In order to select an Additional Interrupt Mode: The type of event detection (Edge or Level) must be selected by writing in the set of registers; PIO_ESR (Edge Select Register) and PIO_LSR (Level Select Register) which enable respectively, the Edge and Level Detection. The current status of this selection is accessible through the PIO_ELSR (Edge/Level Status Register). The Polarity of the event detection (Rising/Falling Edge or High/Low Level) must be selected by writing in the set of registers; PIO_FELLSR (Falling Edge /Low Level Select Register) and PIO_REHLSR (Rising Edge/High Level Select Register) which allow to select Falling or Rising Edge (if Edge is selected in the PIO_ELSR) Edge or High or Low Level Detection (if Level is selected in the PIO_ELSR). The current status of this selection is accessible through the PIO_FRLHSR (Fall/Rise - Low/High Status Register). When an input Edge or Level is detected on an I/O line, the corresponding bit in PIO_ISR (Interrupt Status Register) is set. If the corresponding bit in PIO_IMR is set, the PIO Controller interrupt line is asserted.The interrupt signals of the thirty-two channels are ORed-wired together to generate a single interrupt signal to the interrupt controller. When the software reads PIO_ISR, all the interrupts are automatically cleared. This signifies that all the interrupts that are pending when PIO_ISR is read must be handled. When an Interrupt is enabled on a “Level”, the interrupt is generated as long as the interrupt source is not cleared, even if some read accesses in PIO_ISR are performed. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 447 Figure 27-7. Event Detector on Input Lines (Figure represents line 0) Event Detector Rising Edge Detector 1 Falling Edge Detector 0 0 PIO_REHLSR[0] 1 PIO_FRLHSR[0] Resynchronized input on line 0 Event detection on line 0 1 PIO_FELLSR[0] 0 High Level Detector 1 Low Level Detector 0 PIO_LSR[0] PIO_ELSR[0] PIO_ESR[0] PIO_AIMER[0] PIO_AIMMR[0] PIO_AIMDR[0] Edge Detector 27.5.10.1Example If generating an interrupt is required on the following: Rising edge on PIO line 0 Falling edge on PIO line 1 Rising edge on PIO line 2 Low Level on PIO line 3 High Level on PIO line 4 High Level on PIO line 5 Falling edge on PIO line 6 Rising edge on PIO line 7 Any edge on the other lines The configuration required is described below. 27.5.10.2Interrupt Mode Configuration All the interrupt sources are enabled by writing 32’hFFFF_FFFF in PIO_IER. Then the Additional Interrupt Mode is enabled for line 0 to 7 by writing 32’h0000_00FF in PIO_AIMER. 27.5.10.3Edge or Level Detection Configuration Lines 3, 4 and 5 are configured in Level detection by writing 32’h0000_0038 in PIO_LSR. The other lines are configured in Edge detection by default, if they have not been previously configured. Otherwise, lines 0, 1, 2, 6 and 7 must be configured in Edge detection by writing 32’h0000_00C7 in PIO_ESR. 27.5.10.4Falling/Rising Edge or Low/High Level Detection Configuration. Lines 0, 2, 4, 5 and 7 are configured in Rising Edge or High Level detection by writing 32’h0000_00B5 in PIO_REHLSR. The other lines are configured in Falling Edge or Low Level detection by default, if they have not been previously configured. Otherwise, lines 1, 3 and 6 must be configured in Falling Edge/Low Level detection by writing 32’h0000_004A in PIO_FELLSR. 448 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Figure 27-8. Input Change Interrupt Timings if there are no Additional Interrupt Modes MCK Pin Level PIO_ISR Read PIO_ISR APB Access APB Access Figure 27-9. 27.5.11 Programmable Schmitt Trigger It is possible to configure each input for the Schmitt Trigger. By default the Schmitt trigger is active. Disabling the Schmitt Trigger is requested when using the QTouch™ Library. 27.5.12 Write Protection Registers To prevent any single software error that may corrupt PIO behavior, certain address spaces can be write-protected by setting the WPEN bit in the “PIO Write Protect Mode Register” (PIO_WPMR). If a write access to the protected registers is detected, then the WPVS flag in the PIO Write Protect Status Register (PIO_WPSR) is set and the field WPVSRC indicates in which register the write access has been attempted. The WPVS flag is reset by writing the PIO Write Protect Mode Register (PIO_WPMR) with the appropriate access key, WPKEY. The protected registers are: “PIO Enable Register” on page 454 “PIO Disable Register” on page 455 “PIO Output Enable Register” on page 457 “PIO Output Disable Register” on page 458 “PIO Input Filter Enable Register” on page 460 “PIO Input Filter Disable Register” on page 461 “PIO Multi-driver Enable Register” on page 471 “PIO Multi-driver Disable Register” on page 472 “PIO Pull Up Disable Register” on page 474 “PIO Pull Up Enable Register” on page 475 “PIO Peripheral ABCD Select Register 1” on page 477 “PIO Peripheral ABCD Select Register 2” on page 478 “PIO Output Write Enable Register” on page 486 “PIO Output Write Disable Register” on page 487 “PIO Pad Pull Down Disable Register” on page 483 “PIO Pad Pull Down Status Register” on page 485 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 449 27.6 I/O Lines Programming Example The programing example as shown in Table 27-1 below is used to obtain the following configuration. 4-bit output port on I/O lines 0 to 3, (should be written in a single write operation), open-drain, with pull-up resistor Four output signals on I/O lines 4 to 7 (to drive LEDs for example), driven high and low, no pull-up resistor, no pull-down resistor Four input signals on I/O lines 8 to 11 (to read push-button states for example), with pull-up resistors, glitch filters and input change interrupts Four input signals on I/O line 12 to 15 to read an external device status (polled, thus no input change interrupt), no pull-up resistor, no glitch filter I/O lines 16 to 19 assigned to peripheral A functions with pull-up resistor I/O lines 20 to 23 assigned to peripheral B functions with pull-down resistor I/O line 24 to 27 assigned to peripheral C with Input Change Interrupt, no pull-up resistor and no pull-down resistor I/O line 28 to 31 assigned to peripheral D, no pull-up resistor and no pull-down resistor Table 27-1. 450 Programming Example Register Value to be Written PIO_PER 0x0000_FFFF PIO_PDR 0xFFFF_0000 PIO_OER 0x0000_00FF PIO_ODR 0xFFFF_FF00 PIO_IFER 0x0000_0F00 PIO_IFDR 0xFFFF_F0FF PIO_SODR 0x0000_0000 PIO_CODR 0x0FFF_FFFF PIO_IER 0x0F00_0F00 PIO_IDR 0xF0FF_F0FF PIO_MDER 0x0000_000F PIO_MDDR 0xFFFF_FFF0 PIO_PUDR 0xFFF0_00F0 PIO_PUER 0x000F_FF0F PIO_PPDDR 0xFF0F_FFFF PIO_PPDER 0x00F0_0000 PIO_ABCDSR1 0xF0F0_0000 PIO_ABCDSR2 0xFF00_0000 PIO_OWER 0x0000_000F PIO_OWDR 0x0FFF_ FFF0 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 27.7 Parallel Input/Output Controller (PIO) User Interface Each I/O line controlled by the PIO Controller is associated with a bit in each of the PIO Controller User Interface registers. Each register is 32 bits wide. If a parallel I/O line is not defined, writing to the corresponding bits has no effect. Undefined bits read zero. If the I/O line is notmultiplexed with any peripheral, the I/O line is controlled by the PIO Controller and PIO_PSR returns 1 systematically. Table 27-2. Register Mapping Offset Register Name Access Reset 0x0000 PIO Enable Register PIO_PER Write-only – 0x0004 PIO Disable Register PIO_PDR Write-only – Read-only (1) – – 0x0008 PIO Status Register 0x000C Reserved PIO_PSR 0x0010 Output Enable Register PIO_OER Write-only – 0x0014 Output Disable Register PIO_ODR Write-only – 0x0018 Output Status Register PIO_OSR Read-only 0x0000 0000 0x001C Reserved – – 0x0020 Glitch Input Filter Enable Register PIO_IFER Write-only – 0x0024 Glitch Input Filter Disable Register PIO_IFDR Write-only – 0x0028 Glitch Input Filter Status Register PIO_IFSR Read-only 0x0000 0000 0x002C Reserved – – 0x0030 Set Output Data Register PIO_SODR Write-only – 0x0034 Clear Output Data Register PIO_CODR Write-only 0x0038 Output Data Status Register PIO_ODSR Read-only or(2) Read-write – 0x003C Pin Data Status Register PIO_PDSR Read-only (3) 0x0040 Interrupt Enable Register PIO_IER Write-only – 0x0044 Interrupt Disable Register PIO_IDR Write-only – 0x0048 Interrupt Mask Register PIO_IMR Read-only 0x00000000 PIO_ISR Read-only 0x00000000 – – – (4) 0x004C Interrupt Status Register 0x0050 Multi-driver Enable Register PIO_MDER Write-only – 0x0054 Multi-driver Disable Register PIO_MDDR Write-only – 0x0058 Multi-driver Status Register PIO_MDSR Read-only 0x00000000 0x005C Reserved – – 0x0060 Pull-up Disable Register PIO_PUDR Write-only – 0x0064 Pull-up Enable Register PIO_PUER Write-only – Read-only (1) – – 0x0068 Pad Pull-up Status Register 0x006C Reserved – PIO_PUSR – SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 451 Table 27-2. Register Mapping (Continued) Offset Register Name Access Reset 0x0070 Peripheral Select Register 1 PIO_ABCDSR1 Read-write 0x00000000 0x0074 Peripheral Select Register 2 PIO_ABCDSR2 Read-write 0x00000000 0x0078 to 0x007C Reserved – – – 0x0080 Input Filter Slow Clock Disable Register PIO_IFSCDR Write-only – 0x0084 Input Filter Slow Clock Enable Register PIO_IFSCER Write-only – 0x0088 Input Filter Slow Clock Status Register PIO_IFSCSR Read-only 0x00000000 0x008C Slow Clock Divider Debouncing Register PIO_SCDR Read-write 0x00000000 0x0090 Pad Pull-down Disable Register PIO_PPDDR Write-only – 0x0094 Pad Pull-down Enable Register PIO_PPDER Write-only – Read-only (1) – – 0x0098 Pad Pull-down Status Register PIO_PPDSR 0x009C Reserved 0x00A0 Output Write Enable PIO_OWER Write-only – 0x00A4 Output Write Disable PIO_OWDR Write-only – 0x00A8 Output Write Status Register PIO_OWSR Read-only 0x00000000 – 0x00AC Reserved – – 0x00B0 Additional Interrupt Modes Enable Register PIO_AIMER Write-only – 0x00B4 Additional Interrupt Modes Disables Register PIO_AIMDR Write-only – 0x00B8 Additional Interrupt Modes Mask Register PIO_AIMMR Read-only 0x00000000 0x00BC Reserved – – 0x00C0 Edge Select Register PIO_ESR Write-only – 0x00C4 Level Select Register PIO_LSR Write-only – 0x00C8 Edge/Level Status Register PIO_ELSR Read-only 0x00000000 0x00CC Reserved – – 0x00D0 Falling Edge/Low Level Select Register PIO_FELLSR Write-only – 0x00D4 Rising Edge/ High Level Select Register PIO_REHLSR Write-only – 0x00D8 Fall/Rise - Low/High Status Register PIO_FRLHSR Read-only 0x00000000 0x00DC Reserved – – – 0x00E0 Reserved – – – 0x00E4 Write Protect Mode Register PIO_WPMR Read-write 0x0 0x00E8 Write Protect Status Register PIO_WPSR Read-only 0x0 0x00EC to 0x00F8 Reserved – – – 0x0100 Schmitt Trigger Register PIO_SCHMITT Read-write 0x00000000 0x01040x010C Reserved – – – 452 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 – – – Table 27-2. Register Mapping (Continued) Offset Register 0x0110 Reserved 0x01140x011C Reserved Name Access Reset – – – – – – 0x0120 to Reserved – – – 0x014C Notes: 1. Reset value depends on the product implementation. 2. PIO_ODSR is Read-only or Read/Write depending on PIO_OWSR I/O lines. 3. Reset value of PIO_PDSR depends on the level of the I/O lines. Reading the I/O line levels requires the clock of the PIO Controller to be enabled, otherwise PIO_PDSR reads the levels present on the I/O line at the time the clock was disabled. 4. PIO_ISR is reset at 0x0. However, the first read of the register may read a different value as input changes may have occurred. Note: If an offset is not listed in the table it must be considered as reserved. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 453 27.7.1 PIO Enable Register Name: PIO_PER Address: 0x400E0E00 (PIOA), 0x400E1000 (PIOB), 0x400E1200 (PIOC) Access: Write-only 31 30 29 28 27 26 25 24 P31 P30 P29 P28 P27 P26 P25 P24 23 22 21 20 19 18 17 16 P23 P22 P21 P20 P19 P18 P17 P16 15 14 13 12 11 10 9 8 P15 P14 P13 P12 P11 P10 P9 P8 7 6 5 4 3 2 1 0 P7 P6 P5 P4 P3 P2 P1 P0 This register can only be written if the WPEN bit is cleared in “PIO Write Protect Mode Register” . • P0-P31: PIO Enable 0: No effect. 1: Enables the PIO to control the corresponding pin (disables peripheral control of the pin). 454 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 27.7.2 PIO Disable Register Name: PIO_PDR Address: 0x400E0E04 (PIOA), 0x400E1004 (PIOB), 0x400E1204 (PIOC) Access: Write-only 31 30 29 28 27 26 25 24 P31 P30 P29 P28 P27 P26 P25 P24 23 22 21 20 19 18 17 16 P23 P22 P21 P20 P19 P18 P17 P16 15 14 13 12 11 10 9 8 P15 P14 P13 P12 P11 P10 P9 P8 7 6 5 4 3 2 1 0 P7 P6 P5 P4 P3 P2 P1 P0 This register can only be written if the WPEN bit is cleared in “PIO Write Protect Mode Register” . • P0-P31: PIO Disable 0: No effect. 1: Disables the PIO from controlling the corresponding pin (enables peripheral control of the pin). SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 455 27.7.3 PIO Status Register Name: PIO_PSR Address: 0x400E0E08 (PIOA), 0x400E1008 (PIOB), 0x400E1208 (PIOC) Access: Read-only 31 30 29 28 27 26 25 24 P31 P30 P29 P28 P27 P26 P25 P24 23 22 21 20 19 18 17 16 P23 P22 P21 P20 P19 P18 P17 P16 15 14 13 12 11 10 9 8 P15 P14 P13 P12 P11 P10 P9 P8 7 6 5 4 3 2 1 0 P7 P6 P5 P4 P3 P2 P1 P0 • P0-P31: PIO Status 0: PIO is inactive on the corresponding I/O line (peripheral is active). 1: PIO is active on the corresponding I/O line (peripheral is inactive). 456 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 27.7.4 PIO Output Enable Register Name: PIO_OER Address: 0x400E0E10 (PIOA), 0x400E1010 (PIOB), 0x400E1210 (PIOC) Access: Write-only 31 30 29 28 27 26 25 24 P31 P30 P29 P28 P27 P26 P25 P24 23 22 21 20 19 18 17 16 P23 P22 P21 P20 P19 P18 P17 P16 15 14 13 12 11 10 9 8 P15 P14 P13 P12 P11 P10 P9 P8 7 6 5 4 3 2 1 0 P7 P6 P5 P4 P3 P2 P1 P0 This register can only be written if the WPEN bit is cleared in “PIO Write Protect Mode Register” . • P0-P31: Output Enable 0: No effect. 1: Enables the output on the I/O line. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 457 27.7.5 PIO Output Disable Register Name: PIO_ODR Address: 0x400E0E14 (PIOA), 0x400E1014 (PIOB), 0x400E1214 (PIOC) Access: Write-only 31 30 29 28 27 26 25 24 P31 P30 P29 P28 P27 P26 P25 P24 23 22 21 20 19 18 17 16 P23 P22 P21 P20 P19 P18 P17 P16 15 14 13 12 11 10 9 8 P15 P14 P13 P12 P11 P10 P9 P8 7 6 5 4 3 2 1 0 P7 P6 P5 P4 P3 P2 P1 P0 This register can only be written if the WPEN bit is cleared in “PIO Write Protect Mode Register” . • P0-P31: Output Disable 0: No effect. 1: Disables the output on the I/O line. 458 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 27.7.6 PIO Output Status Register Name: PIO_OSR Address: 0x400E0E18 (PIOA), 0x400E1018 (PIOB), 0x400E1218 (PIOC) Access: Read-only 31 30 29 28 27 26 25 24 P31 P30 P29 P28 P27 P26 P25 P24 23 22 21 20 19 18 17 16 P23 P22 P21 P20 P19 P18 P17 P16 15 14 13 12 11 10 9 8 P15 P14 P13 P12 P11 P10 P9 P8 7 6 5 4 3 2 1 0 P7 P6 P5 P4 P3 P2 P1 P0 • P0-P31: Output Status 0: The I/O line is a pure input. 1: The I/O line is enabled in output. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 459 27.7.7 PIO Input Filter Enable Register Name: PIO_IFER Address: 0x400E0E20 (PIOA), 0x400E1020 (PIOB), 0x400E1220 (PIOC) Access: Write-only 31 30 29 28 27 26 25 24 P31 P30 P29 P28 P27 P26 P25 P24 23 22 21 20 19 18 17 16 P23 P22 P21 P20 P19 P18 P17 P16 15 14 13 12 11 10 9 8 P15 P14 P13 P12 P11 P10 P9 P8 7 6 5 4 3 2 1 0 P7 P6 P5 P4 P3 P2 P1 P0 This register can only be written if the WPEN bit is cleared in “PIO Write Protect Mode Register” . • P0-P31: Input Filter Enable 0: No effect. 1: Enables the input glitch filter on the I/O line. 460 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 27.7.8 PIO Input Filter Disable Register Name: PIO_IFDR Address: 0x400E0E24 (PIOA), 0x400E1024 (PIOB), 0x400E1224 (PIOC) Access: Write-only 31 30 29 28 27 26 25 24 P31 P30 P29 P28 P27 P26 P25 P24 23 22 21 20 19 18 17 16 P23 P22 P21 P20 P19 P18 P17 P16 15 14 13 12 11 10 9 8 P15 P14 P13 P12 P11 P10 P9 P8 7 6 5 4 3 2 1 0 P7 P6 P5 P4 P3 P2 P1 P0 This register can only be written if the WPEN bit is cleared in “PIO Write Protect Mode Register” . • P0-P31: Input Filter Disable 0: No effect. 1: Disables the input glitch filter on the I/O line. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 461 27.7.9 PIO Input Filter Status Register Name: PIO_IFSR Address: 0x400E0E28 (PIOA), 0x400E1028 (PIOB), 0x400E1228 (PIOC) Access: Read-only 31 30 29 28 27 26 25 24 P31 P30 P29 P28 P27 P26 P25 P24 23 22 21 20 19 18 17 16 P23 P22 P21 P20 P19 P18 P17 P16 15 14 13 12 11 10 9 8 P15 P14 P13 P12 P11 P10 P9 P8 7 6 5 4 3 2 1 0 P7 P6 P5 P4 P3 P2 P1 P0 • P0-P31: Input Filer Status 0: The input glitch filter is disabled on the I/O line. 1: The input glitch filter is enabled on the I/O line. 462 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 27.7.10 PIO Set Output Data Register Name: PIO_SODR Address: 0x400E0E30 (PIOA), 0x400E1030 (PIOB), 0x400E1230 (PIOC) Access: Write-only 31 30 29 28 27 26 25 24 P31 P30 P29 P28 P27 P26 P25 P24 23 22 21 20 19 18 17 16 P23 P22 P21 P20 P19 P18 P17 P16 15 14 13 12 11 10 9 8 P15 P14 P13 P12 P11 P10 P9 P8 7 6 5 4 3 2 1 0 P7 P6 P5 P4 P3 P2 P1 P0 • P0-P31: Set Output Data 0: No effect. 1: Sets the data to be driven on the I/O line. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 463 27.7.11 PIO Clear Output Data Register Name: PIO_CODR Address: 0x400E0E34 (PIOA), 0x400E1034 (PIOB), 0x400E1234 (PIOC) Access: Write-only 31 30 29 28 27 26 25 24 P31 P30 P29 P28 P27 P26 P25 P24 23 22 21 20 19 18 17 16 P23 P22 P21 P20 P19 P18 P17 P16 15 14 13 12 11 10 9 8 P15 P14 P13 P12 P11 P10 P9 P8 7 6 5 4 3 2 1 0 P7 P6 P5 P4 P3 P2 P1 P0 • P0-P31: Clear Output Data 0: No effect. 1: Clears the data to be driven on the I/O line. 464 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 27.7.12 PIO Output Data Status Register Name: PIO_ODSR Address: 0x400E0E38 (PIOA), 0x400E1038 (PIOB), 0x400E1238 (PIOC) Access: Read-only or Read-write 31 30 29 28 27 26 25 24 P31 P30 P29 P28 P27 P26 P25 P24 23 22 21 20 19 18 17 16 P23 P22 P21 P20 P19 P18 P17 P16 15 14 13 12 11 10 9 8 P15 P14 P13 P12 P11 P10 P9 P8 7 6 5 4 3 2 1 0 P7 P6 P5 P4 P3 P2 P1 P0 • P0-P31: Output Data Status 0: The data to be driven on the I/O line is 0. 1: The data to be driven on the I/O line is 1. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 465 27.7.13 PIO Pin Data Status Register Name: PIO_PDSR Address: 0x400E0E3C (PIOA), 0x400E103C (PIOB), 0x400E123C (PIOC) Access: Read-only 31 30 29 28 27 26 25 24 P31 P30 P29 P28 P27 P26 P25 P24 23 22 21 20 19 18 17 16 P23 P22 P21 P20 P19 P18 P17 P16 15 14 13 12 11 10 9 8 P15 P14 P13 P12 P11 P10 P9 P8 7 6 5 4 3 2 1 0 P7 P6 P5 P4 P3 P2 P1 P0 • P0-P31: Output Data Status 0: The I/O line is at level 0. 1: The I/O line is at level 1. 466 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 27.7.14 PIO Interrupt Enable Register Name: PIO_IER Address: 0x400E0E40 (PIOA), 0x400E1040 (PIOB), 0x400E1240 (PIOC) Access: Write-only 31 30 29 28 27 26 25 24 P31 P30 P29 P28 P27 P26 P25 P24 23 22 21 20 19 18 17 16 P23 P22 P21 P20 P19 P18 P17 P16 15 14 13 12 11 10 9 8 P15 P14 P13 P12 P11 P10 P9 P8 7 6 5 4 3 2 1 0 P7 P6 P5 P4 P3 P2 P1 P0 • P0-P31: Input Change Interrupt Enable 0: No effect. 1: Enables the Input Change Interrupt on the I/O line. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 467 27.7.15 PIO Interrupt Disable Register Name: PIO_IDR Address: 0x400E0E44 (PIOA), 0x400E1044 (PIOB), 0x400E1244 (PIOC) Access: Write-only 31 30 29 28 27 26 25 24 P31 P30 P29 P28 P27 P26 P25 P24 23 22 21 20 19 18 17 16 P23 P22 P21 P20 P19 P18 P17 P16 15 14 13 12 11 10 9 8 P15 P14 P13 P12 P11 P10 P9 P8 7 6 5 4 3 2 1 0 P7 P6 P5 P4 P3 P2 P1 P0 • P0-P31: Input Change Interrupt Disable 0: No effect. 1: Disables the Input Change Interrupt on the I/O line. 468 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 27.7.16 PIO Interrupt Mask Register Name: PIO_IMR Address: 0x400E0E48 (PIOA), 0x400E1048 (PIOB), 0x400E1248 (PIOC) Access: Read-only 31 30 29 28 27 26 25 24 P31 P30 P29 P28 P27 P26 P25 P24 23 22 21 20 19 18 17 16 P23 P22 P21 P20 P19 P18 P17 P16 15 14 13 12 11 10 9 8 P15 P14 P13 P12 P11 P10 P9 P8 7 6 5 4 3 2 1 0 P7 P6 P5 P4 P3 P2 P1 P0 • P0-P31: Input Change Interrupt Mask 0: Input Change Interrupt is disabled on the I/O line. 1: Input Change Interrupt is enabled on the I/O line. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 469 27.7.17 PIO Interrupt Status Register Name: PIO_ISR Address: 0x400E0E4C (PIOA), 0x400E104C (PIOB), 0x400E124C (PIOC) Access: Read-only 31 30 29 28 27 26 25 24 P31 P30 P29 P28 P27 P26 P25 P24 23 22 21 20 19 18 17 16 P23 P22 P21 P20 P19 P18 P17 P16 15 14 13 12 11 10 9 8 P15 P14 P13 P12 P11 P10 P9 P8 7 6 5 4 3 2 1 0 P7 P6 P5 P4 P3 P2 P1 P0 • P0-P31: Input Change Interrupt Status 0: No Input Change has been detected on the I/O line since PIO_ISR was last read or since reset. 1: At least one Input Change has been detected on the I/O line since PIO_ISR was last read or since reset. 470 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 27.7.18 PIO Multi-driver Enable Register Name: PIO_MDER Address: 0x400E0E50 (PIOA), 0x400E1050 (PIOB), 0x400E1250 (PIOC) Access: Write-only 31 30 29 28 27 26 25 24 P31 P30 P29 P28 P27 P26 P25 P24 23 22 21 20 19 18 17 16 P23 P22 P21 P20 P19 P18 P17 P16 15 14 13 12 11 10 9 8 P15 P14 P13 P12 P11 P10 P9 P8 7 6 5 4 3 2 1 0 P7 P6 P5 P4 P3 P2 P1 P0 This register can only be written if the WPEN bit is cleared in “PIO Write Protect Mode Register” . • P0-P31: Multi Drive Enable 0: No effect. 1: Enables Multi Drive on the I/O line. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 471 27.7.19 PIO Multi-driver Disable Register Name: PIO_MDDR Address: 0x400E0E54 (PIOA), 0x400E1054 (PIOB), 0x400E1254 (PIOC) Access: Write-only 31 30 29 28 27 26 25 24 P31 P30 P29 P28 P27 P26 P25 P24 23 22 21 20 19 18 17 16 P23 P22 P21 P20 P19 P18 P17 P16 15 14 13 12 11 10 9 8 P15 P14 P13 P12 P11 P10 P9 P8 7 6 5 4 3 2 1 0 P7 P6 P5 P4 P3 P2 P1 P0 This register can only be written if the WPEN bit is cleared in “PIO Write Protect Mode Register” . • P0-P31: Multi Drive Disable. 0: No effect. 1: Disables Multi Drive on the I/O line. 472 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 27.7.20 PIO Multi-driver Status Register Name: PIO_MDSR Address: 0x400E0E58 (PIOA), 0x400E1058 (PIOB), 0x400E1258 (PIOC) Access: Read-only 31 30 29 28 27 26 25 24 P31 P30 P29 P28 P27 P26 P25 P24 23 22 21 20 19 18 17 16 P23 P22 P21 P20 P19 P18 P17 P16 15 14 13 12 11 10 9 8 P15 P14 P13 P12 P11 P10 P9 P8 7 6 5 4 3 2 1 0 P7 P6 P5 P4 P3 P2 P1 P0 • P0-P31: Multi Drive Status. 0: The Multi Drive is disabled on the I/O line. The pin is driven at high and low level. 1: The Multi Drive is enabled on the I/O line. The pin is driven at low level only. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 473 27.7.21 PIO Pull Up Disable Register Name: PIO_PUDR Address: 0x400E0E60 (PIOA), 0x400E1060 (PIOB), 0x400E1260 (PIOC) Access: Write-only 31 30 29 28 27 26 25 24 P31 P30 P29 P28 P27 P26 P25 P24 23 22 21 20 19 18 17 16 P23 P22 P21 P20 P19 P18 P17 P16 15 14 13 12 11 10 9 8 P15 P14 P13 P12 P11 P10 P9 P8 7 6 5 4 3 2 1 0 P7 P6 P5 P4 P3 P2 P1 P0 This register can only be written if the WPEN bit is cleared in “PIO Write Protect Mode Register” . • P0-P31: Pull Up Disable. 0: No effect. 1: Disables the pull up resistor on the I/O line. 474 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 27.7.22 PIO Pull Up Enable Register Name: PIO_PUER Address: 0x400E0E64 (PIOA), 0x400E1064 (PIOB), 0x400E1264 (PIOC) Access: Write-only 31 30 29 28 27 26 25 24 P31 P30 P29 P28 P27 P26 P25 P24 23 22 21 20 19 18 17 16 P23 P22 P21 P20 P19 P18 P17 P16 15 14 13 12 11 10 9 8 P15 P14 P13 P12 P11 P10 P9 P8 7 6 5 4 3 2 1 0 P7 P6 P5 P4 P3 P2 P1 P0 This register can only be written if the WPEN bit is cleared in “PIO Write Protect Mode Register” . • P0-P31: Pull Up Enable. 0: No effect. 1: Enables the pull up resistor on the I/O line. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 475 27.7.23 PIO Pull Up Status Register Name: PIO_PUSR Address: 0x400E0E68 (PIOA), 0x400E1068 (PIOB), 0x400E1268 (PIOC) Access: Read-only 31 30 29 28 27 26 25 24 P31 P30 P29 P28 P27 P26 P25 P24 23 22 21 20 19 18 17 16 P23 P22 P21 P20 P19 P18 P17 P16 15 14 13 12 11 10 9 8 P15 P14 P13 P12 P11 P10 P9 P8 7 6 5 4 3 2 1 0 P7 P6 P5 P4 P3 P2 P1 P0 • P0-P31: Pull Up Status. 0: Pull Up resistor is enabled on the I/O line. 1: Pull Up resistor is disabled on the I/O line. 476 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 27.7.24 PIO Peripheral ABCD Select Register 1 Name: PIO_ABCDSR1 Access: Read-write 31 30 29 28 27 26 25 24 P31 P30 P29 P28 P27 P26 P25 P24 23 22 21 20 19 18 17 16 P23 P22 P21 P20 P19 P18 P17 P16 15 14 13 12 11 10 9 8 P15 P14 P13 P12 P11 P10 P9 P8 7 6 5 4 3 2 1 0 P7 P6 P5 P4 P3 P2 P1 P0 This register can only be written if the WPEN bit is cleared in “PIO Write Protect Mode Register” . • P0-P31: Peripheral Select. If the same bit is set to 0 in PIO_ABCDSR2: 0: Assigns the I/O line to the Peripheral A function. 1: Assigns the I/O line to the Peripheral B function. If the same bit is set to 1 in PIO_ABCDSR2: 0: Assigns the I/O line to the Peripheral C function. 1: Assigns the I/O line to the Peripheral D function. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 477 27.7.25 PIO Peripheral ABCD Select Register 2 Name: PIO_ABCDSR2 Access: Read-write 31 30 29 28 27 26 25 24 P31 P30 P29 P28 P27 P26 P25 P24 23 22 21 20 19 18 17 16 P23 P22 P21 P20 P19 P18 P17 P16 15 14 13 12 11 10 9 8 P15 P14 P13 P12 P11 P10 P9 P8 7 6 5 4 3 2 1 0 P7 P6 P5 P4 P3 P2 P1 P0 This register can only be written if the WPEN bit is cleared in “PIO Write Protect Mode Register” . • P0-P31: Peripheral Select. If the same bit is set to 0 in PIO_ABCDSR1: 0: Assigns the I/O line to the Peripheral A function. 1: Assigns the I/O line to the Peripheral C function. If the same bit is set to 1 in PIO_ABCDSR1: 0: Assigns the I/O line to the Peripheral B function. 1: Assigns the I/O line to the Peripheral D function. 478 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 27.7.26 PIO Input Filter Slow Clock Disable Register Name: PIO_IFSCDR Address: 0x400E0E80 (PIOA), 0x400E1080 (PIOB), 0x400E1280 (PIOC) Access: Write-only 31 30 29 28 27 26 25 24 P31 P30 P29 P28 P27 P26 P25 P24 23 22 21 20 19 18 17 16 P23 P22 P21 P20 P19 P18 P17 P16 15 14 13 12 11 10 9 8 P15 P14 P13 P12 P11 P10 P9 P8 7 6 5 4 3 2 1 0 P7 P6 P5 P4 P3 P2 P1 P0 • P0-P31: PIO Clock Glitch Filtering Select. 0: No Effect. 1: The Glitch Filter is able to filter glitches with a duration < Tmck/2. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 479 27.7.27 PIO Input Filter Slow Clock Enable Register Name: PIO_IFSCER Address: 0x400E0E84 (PIOA), 0x400E1084 (PIOB), 0x400E1284 (PIOC) Access: Write-only 31 30 29 28 27 26 25 24 P31 P30 P29 P28 P27 P26 P25 P24 23 22 21 20 19 18 17 16 P23 P22 P21 P20 P19 P18 P17 P16 15 14 13 12 11 10 9 8 P15 P14 P13 P12 P11 P10 P9 P8 7 6 5 4 3 2 1 0 P7 P6 P5 P4 P3 P2 P1 P0 • P0-P31: Debouncing Filtering Select. 0: No Effect. 1: The Debouncing Filter is able to filter pulses with a duration < Tdiv_slclk/2. 480 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 27.7.28 PIO Input Filter Slow Clock Status Register Name: PIO_IFSCSR Address: 0x400E0E88 (PIOA), 0x400E1088 (PIOB), 0x400E1288 (PIOC) Access: Read-only 31 30 29 28 27 26 25 24 P31 P30 P29 P28 P27 P26 P25 P24 23 22 21 20 19 18 17 16 P23 P22 P21 P20 P19 P18 P17 P16 15 14 13 12 11 10 9 8 P15 P14 P13 P12 P11 P10 P9 P8 7 6 5 4 3 2 1 0 P7 P6 P5 P4 P3 P2 P1 P0 • P0-P31: Glitch or Debouncing Filter Selection Status 0: The Glitch Filter is able to filter glitches with a duration < Tmck2. 1: The Debouncing Filter is able to filter pulses with a duration < Tdiv_slclk/2. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 481 27.7.29 PIO Slow Clock Divider Debouncing Register Name: PIO_SCDR Address: 0x400E0E8C (PIOA), 0x400E108C (PIOB), 0x400E128C (PIOC) Access: Read-write 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 6 2 1 0 DIV 5 4 3 DIV • DIV: Slow Clock Divider Selection for Debouncing Tdiv_slclk = 2*(DIV+1)*Tslow_clock. 482 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 27.7.30 PIO Pad Pull Down Disable Register Name: PIO_PPDDR Address: 0x400E0E90 (PIOA), 0x400E1090 (PIOB), 0x400E1290 (PIOC) Access: Write-only 31 30 29 28 27 26 25 24 P31 P30 P29 P28 P27 P26 P25 P24 23 22 21 20 19 18 17 16 P23 P22 P21 P20 P19 P18 P17 P16 15 14 13 12 11 10 9 8 P15 P14 P13 P12 P11 P10 P9 P8 7 6 5 4 3 2 1 0 P7 P6 P5 P4 P3 P2 P1 P0 This register can only be written if the WPEN bit is cleared in “PIO Write Protect Mode Register” . • P0-P31: Pull Down Disable 0: No effect. 1: Disables the pull down resistor on the I/O line. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 483 27.7.31 PIO Pad Pull Down Enable Register Name: PIO_PPDER Address: 0x400E0E94 (PIOA), 0x400E1094 (PIOB), 0x400E1294 (PIOC) Access: Write-only 31 30 29 28 27 26 25 24 P31 P30 P29 P28 P27 P26 P25 P24 23 22 21 20 19 18 17 16 P23 P22 P21 P20 P19 P18 P17 P16 15 14 13 12 11 10 9 8 P15 P14 P13 P12 P11 P10 P9 P8 7 6 5 4 3 2 1 0 P7 P6 P5 P4 P3 P2 P1 P0 This register can only be written if the WPEN bit is cleared in “PIO Write Protect Mode Register” . • P0-P31: Pull Down Enable 0: No effect. 1: Enables the pull down resistor on the I/O line. 484 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 27.7.32 PIO Pad Pull Down Status Register Name: PIO_PPDSR Address: 0x400E0E98 (PIOA), 0x400E1098 (PIOB), 0x400E1298 (PIOC) Access: Read-only 31 30 29 28 27 26 25 24 P31 P30 P29 P28 P27 P26 P25 P24 23 22 21 20 19 18 17 16 P23 P22 P21 P20 P19 P18 P17 P16 15 14 13 12 11 10 9 8 P15 P14 P13 P12 P11 P10 P9 P8 7 6 5 4 3 2 1 0 P7 P6 P5 P4 P3 P2 P1 P0 This register can only be written if the WPEN bit is cleared in “PIO Write Protect Mode Register” . • P0-P31: Pull Down Status 0: Pull Down resistor is enabled on the I/O line. 1: Pull Down resistor is disabled on the I/O line. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 485 27.7.33 PIO Output Write Enable Register Name: PIO_OWER Address: 0x400E0EA0 (PIOA), 0x400E10A0 (PIOB), 0x400E12A0 (PIOC) Access: Write-only 31 30 29 28 27 26 25 24 P31 P30 P29 P28 P27 P26 P25 P24 23 22 21 20 19 18 17 16 P23 P22 P21 P20 P19 P18 P17 P16 15 14 13 12 11 10 9 8 P15 P14 P13 P12 P11 P10 P9 P8 7 6 5 4 3 2 1 0 P7 P6 P5 P4 P3 P2 P1 P0 This register can only be written if the WPEN bit is cleared in “PIO Write Protect Mode Register” . • P0-P31: Output Write Enable 0: No effect. 1: Enables writing PIO_ODSR for the I/O line. 486 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 27.7.34 PIO Output Write Disable Register Name: PIO_OWDR Address: 0x400E0EA4 (PIOA), 0x400E10A4 (PIOB), 0x400E12A4 (PIOC) Access: Write-only 31 30 29 28 27 26 25 24 P31 P30 P29 P28 P27 P26 P25 P24 23 22 21 20 19 18 17 16 P23 P22 P21 P20 P19 P18 P17 P16 15 14 13 12 11 10 9 8 P15 P14 P13 P12 P11 P10 P9 P8 7 6 5 4 3 2 1 0 P7 P6 P5 P4 P3 P2 P1 P0 This register can only be written if the WPEN bit is cleared in “PIO Write Protect Mode Register” . • P0-P31: Output Write Disable 0: No effect. 1: Disables writing PIO_ODSR for the I/O line. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 487 27.7.35 PIO Output Write Status Register Name: PIO_OWSR Address: 0x400E0EA8 (PIOA), 0x400E10A8 (PIOB), 0x400E12A8 (PIOC) Access: Read-only 31 30 29 28 27 26 25 24 P31 P30 P29 P28 P27 P26 P25 P24 23 22 21 20 19 18 17 16 P23 P22 P21 P20 P19 P18 P17 P16 15 14 13 12 11 10 9 8 P15 P14 P13 P12 P11 P10 P9 P8 7 6 5 4 3 2 1 0 P7 P6 P5 P4 P3 P2 P1 P0 • P0-P31: Output Write Status 0: Writing PIO_ODSR does not affect the I/O line. 1: Writing PIO_ODSR affects the I/O line. 488 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 27.7.36 PIO Additional Interrupt Modes Enable Register Name: PIO_AIMER Address: 0x400E0EB0 (PIOA), 0x400E10B0 (PIOB), 0x400E12B0 (PIOC) Access: Write-only 31 30 29 28 27 26 25 24 P31 P30 P29 P28 P27 P26 P25 P24 23 22 21 20 19 18 17 16 P23 P22 P21 P20 P19 P18 P17 P16 15 14 13 12 11 10 9 8 P15 P14 P13 P12 P11 P10 P9 P8 7 6 5 4 3 2 1 0 P7 P6 P5 P4 P3 P2 P1 P0 • P0-P31: Additional Interrupt Modes Enable 0: No effect. 1: The interrupt source is the event described in PIO_ELSR and PIO_FRLHSR. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 489 27.7.37 PIO Additional Interrupt Modes Disable Register Name: PIO_AIMDR Address: 0x400E0EB4 (PIOA), 0x400E10B4 (PIOB), 0x400E12B4 (PIOC) Access: Write-only 31 30 29 28 27 26 25 24 P31 P30 P29 P28 P27 P26 P25 P24 23 22 21 20 19 18 17 16 P23 P22 P21 P20 P19 P18 P17 P16 15 14 13 12 11 10 9 8 P15 P14 P13 P12 P11 P10 P9 P8 7 6 5 4 3 2 1 0 P7 P6 P5 P4 P3 P2 P1 P0 • P0-P31: Additional Interrupt Modes Disable 0: No effect. 1: The interrupt mode is set to the default interrupt mode (Both Edge detection). 490 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 27.7.38 PIO Additional Interrupt Modes Mask Register Name: PIO_AIMMR Address: 0x400E0EB8 (PIOA), 0x400E10B8 (PIOB), 0x400E12B8 (PIOC) Access: Read-only 31 30 29 28 27 26 25 24 P31 P30 P29 P28 P27 P26 P25 P24 23 22 21 20 19 18 17 16 P23 P22 P21 P20 P19 P18 P17 P16 15 14 13 12 11 10 9 8 P15 P14 P13 P12 P11 P10 P9 P8 7 6 5 4 3 2 1 0 P7 P6 P5 P4 P3 P2 P1 P0 • P0-P31: Peripheral CD Status 0: The interrupt source is a Both Edge detection event. 1: The interrupt source is described by the registers PIO_ELSR and PIO_FRLHSR. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 491 27.7.39 PIO Edge Select Register Name: PIO_ESR Address: 0x400E0EC0 (PIOA), 0x400E10C0 (PIOB), 0x400E12C0 (PIOC) Access: Write-only 31 30 29 28 27 26 25 24 P31 P30 P29 P28 P27 P26 P25 P24 23 22 21 20 19 18 17 16 P23 P22 P21 P20 P19 P18 P17 P16 15 14 13 12 11 10 9 8 P15 P14 P13 P12 P11 P10 P9 P8 7 6 5 4 3 2 1 0 P7 P6 P5 P4 P3 P2 P1 P0 • P0-P31: Edge Interrupt Selection 0: No effect. 1: The interrupt source is an Edge detection event. 492 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 27.7.40 PIO Level Select Register Name: PIO_LSR Address: 0x400E0EC4 (PIOA), 0x400E10C4 (PIOB), 0x400E12C4 (PIOC) Access: Write-only 31 30 29 28 27 26 25 24 P31 P30 P29 P28 P27 P26 P25 P24 23 22 21 20 19 18 17 16 P23 P22 P21 P20 P19 P18 P17 P16 15 14 13 12 11 10 9 8 P15 P14 P13 P12 P11 P10 P9 P8 7 6 5 4 3 2 1 0 P7 P6 P5 P4 P3 P2 P1 P0 • P0-P31: Level Interrupt Selection 0: No effect. 1: The interrupt source is a Level detection event. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 493 27.7.41 PIO Edge/Level Status Register Name: PIO_ELSR Address: 0x400E0EC8 (PIOA), 0x400E10C8 (PIOB), 0x400E12C8 (PIOC) Access: Read-only 31 30 29 28 27 26 25 24 P31 P30 P29 P28 P27 P26 P25 P24 23 22 21 20 19 18 17 16 P23 P22 P21 P20 P19 P18 P17 P16 15 14 13 12 11 10 9 8 P15 P14 P13 P12 P11 P10 P9 P8 7 6 5 4 3 2 1 0 P7 P6 P5 P4 P3 P2 P1 P0 • P0-P31: Edge/Level Interrupt Source Selection 0: The interrupt source is an Edge detection event. 1: The interrupt source is a Level detection event. 494 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 27.7.42 PIO Falling Edge/Low Level Select Register Name: PIO_FELLSR Address: 0x400E0ED0 (PIOA), 0x400E10D0 (PIOB), 0x400E12D0 (PIOC) Access: Write-only 31 30 29 28 27 26 25 24 P31 P30 P29 P28 P27 P26 P25 P24 23 22 21 20 19 18 17 16 P23 P22 P21 P20 P19 P18 P17 P16 15 14 13 12 11 10 9 8 P15 P14 P13 P12 P11 P10 P9 P8 7 6 5 4 3 2 1 0 P7 P6 P5 P4 P3 P2 P1 P0 • P0-P31: Falling Edge/Low Level Interrupt Selection 0: No effect. 1: The interrupt source is set to a Falling Edge detection or Low Level detection event, depending on PIO_ELSR. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 495 27.7.43 PIO Rising Edge/High Level Select Register Name: PIO_REHLSR Address: 0x400E0ED4 (PIOA), 0x400E10D4 (PIOB), 0x400E12D4 (PIOC) Access: Write-only 31 30 29 28 27 26 25 24 P31 P30 P29 P28 P27 P26 P25 P24 23 22 21 20 19 18 17 16 P23 P22 P21 P20 P19 P18 P17 P16 15 14 13 12 11 10 9 8 P15 P14 P13 P12 P11 P10 P9 P8 7 6 5 4 3 2 1 0 P7 P6 P5 P4 P3 P2 P1 P0 • P0-P31: Rising Edge /High Level Interrupt Selection 0: No effect. 1: The interrupt source is set to a Rising Edge detection or High Level detection event, depending on PIO_ELSR. 496 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 27.7.44 PIO Fall/Rise - Low/High Status Register Name: PIO_FRLHSR Address: 0x400E0ED8 (PIOA), 0x400E10D8 (PIOB), 0x400E12D8 (PIOC) Access: Read-only 31 30 29 28 27 26 25 24 P31 P30 P29 P28 P27 P26 P25 P24 23 22 21 20 19 18 17 16 P23 P22 P21 P20 P19 P18 P17 P16 15 14 13 12 11 10 9 8 P15 P14 P13 P12 P11 P10 P9 P8 7 6 5 4 3 2 1 0 P7 P6 P5 P4 P3 P2 P1 P0 • P0-P31: Edge /Level Interrupt Source Selection 0: The interrupt source is a Falling Edge detection (if PIO_ELSR = 0) or Low Level detection event (if PIO_ELSR = 1). 1: The interrupt source is a Rising Edge detection (if PIO_ELSR = 0) or High Level detection event (if PIO_ELSR = 1). SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 497 27.7.45 PIO Write Protect Mode Register Name: PIO_WPMR Address: 0x400E0EE4 (PIOA), 0x400E10E4 (PIOB), 0x400E12E4 (PIOC) Access: Read-write Reset: See Table 27-2 31 30 29 28 27 26 25 24 19 18 17 16 11 10 9 8 WPKEY 23 22 21 20 WPKEY 15 14 13 12 WPKEY 7 6 5 4 3 2 1 0 – – – – – – – WPEN For more information on Write Protection Registers, refer to Section 27.7 “Parallel Input/Output Controller (PIO) User Interface”. • WPEN: Write Protect Enable 0: Disables the Write Protect if WPKEY corresponds to 0x50494F (“PIO” in ASCII). 1: Enables the Write Protect if WPKEY corresponds to 0x50494F (“PIO” in ASCII). Protects the registers: “PIO Enable Register” on page 454 “PIO Disable Register” on page 455 “PIO Output Enable Register” on page 457 “PIO Output Disable Register” on page 458 “PIO Input Filter Enable Register” on page 460 “PIO Input Filter Disable Register” on page 461 “PIO Multi-driver Enable Register” on page 471 “PIO Multi-driver Disable Register” on page 472 “PIO Pull Up Disable Register” on page 474 “PIO Pull Up Enable Register” on page 475 “PIO Peripheral ABCD Select Register 1” on page 477 “PIO Peripheral ABCD Select Register 2” on page 478 “PIO Output Write Enable Register” on page 486 “PIO Output Write Disable Register” on page 487 “PIO Pad Pull Down Disable Register” on page 483 “PIO Pad Pull Down Status Register” on page 485 498 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 • WPKEY: Write Protect KEY. Value Name 0x50494F PASSWD Description Writing any other value in this field aborts the write operation of the WPEN bit. Always reads as 0. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 499 27.7.46 PIO Write Protect Status Register Name: PIO_WPSR Address: 0x400E0EE8 (PIOA), 0x400E10E8 (PIOB), 0x400E12E8 (PIOC) Access: Read-only Reset: See Table 27-2 31 30 29 28 27 26 25 24 – – – – – – – – 23 22 21 20 19 18 17 16 11 10 9 8 WPVSRC 15 14 13 12 WPVSRC 7 6 5 4 3 2 1 0 – – – – – – – WPVS • WPVS: Write Protect Violation Status 0: No Write Protect Violation has occurred since the last read of the PIO_WPSR register. 1: A Write Protect Violation has occurred since the last read of the PIO_WPSR register. If this violation is an unauthorized attempt to write a protected register, the associated violation is reported into field WPVSRC. • WPVSRC: Write Protect Violation Source When WPVS is active, this field indicates the write-protected register (through address offset or code) in which a write access has been attempted. Note: Reading PIO_WPSR automatically clears all fields. 500 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 27.7.47 PIO Schmitt Trigger Register Name: PIO_SCHMITT Address: 0x400E0F00 (PIOA), 0x400E1100 (PIOB), 0x400E1300 (PIOC) Access: Read-write Reset: See Table 27-2 31 30 29 28 27 26 25 24 SCHMITT31 SCHMITT30 SCHMITT29 SCHMITT28 SCHMITT27 SCHMITT26 SCHMITT25 SCHMITT24 23 22 21 20 19 18 17 16 SCHMITT23 SCHMITT22 SCHMITT21 SCHMITT20 SCHMITT19 SCHMITT18 SCHMITT17 SCHMITT16 15 14 13 12 11 10 9 8 SCHMITT15 SCHMITT14 SCHMITT13 SCHMITT12 SCHMITT11 SCHMITT10 SCHMITT9 SCHMITT8 7 6 5 4 3 2 1 0 SCHMITT7 SCHMITT6 SCHMITT5 SCHMITT4 SCHMITT3 SCHMITT2 SCHMITT1 SCHMITT0 • SCHMITTx [x=0..31]: Schmitt Trigger Control 0: Schmitt Trigger is enabled. 1: Schmitt Trigger is disabled. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 501 28. Serial Peripheral Interface (SPI) 28.1 Description 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: 28.2 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. Embedded Characteristics Supports Communication with Serial External Devices ̶ Master Mode can drive SPCK up to peripheral clock (bounded by maximum bus clock divided by 2) ̶ Slave Mode operates on SPCK, asynchronously to Core and Bus Clock ̶ Four Chip Selects with External Decoder Support Allow Communication with Up to 15 Peripherals ̶ ̶ Serial Memories, such as DataFlash and 3-wire EEPROMs ̶ Master or Slave Serial Peripheral Bus Interface ̶ 8-bit to 16-bit Programmable Data Length Per Chip Select ̶ Programmable Phase and Polarity Per Chip Select ̶ Programmable Transfer Delay Between Consecutive Transfers and Delay before SPI Clock per Chip Select ̶ Programmable Delay Between Chip Selects ̶ Selectable Mode Fault Detection Connection to PDC Channel Capabilities Optimizes Data Transfers ̶ 502 Serial Peripherals, such as ADCs, DACs, LCD Controllers, CAN Controllers and Sensors External Coprocessors One Channel for the Receiver, One Channel for the Transmitter SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 28.3 Block Diagram Figure 28-1. Block Diagram PDC APB SPCK MISO PMC MOSI MCK SPI Interface PIO NPCS0/NSS NPCS1 NPCS2 Interrupt Control NPCS3 SPI Interrupt 28.4 Application Block Diagram Figure 28-2. Application Block Diagram: Single Master/Multiple Slave Implementation SPI Master SPCK SPCK MISO MISO MOSI MOSI NPCS0 NSS Slave 0 SPCK NPCS1 NPCS2 NPCS3 NC MISO Slave 1 MOSI NSS SPCK MISO Slave 2 MOSI NSS SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 503 28.5 Signal Description Table 28-1. Signal Description Type Pin Name Pin Description 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 28.6 Product Dependencies 28.6.1 I/O Lines The pins used for interfacing the compliant external devices may be multiplexed with PIO lines. The programmer must first program the PIO controllers to assign the SPI pins to their peripheral functions. Table 28-2. I/O Lines Instance Signal I/O Line Peripheral SPI MISO PA12 A SPI MOSI PA13 A SPI NPCS0 PA11 A SPI NPCS1 PA9 B SPI NPCS1 PA31 A SPI NPCS1 PB14 A SPI NPCS1 PC4 B SPI NPCS2 PA10 B SPI NPCS2 PA30 B SPI NPCS2 PB2 B SPI NPCS2 PC7 B SPI NPCS3 PA3 B SPI NPCS3 PA5 B SPI NPCS3 PA22 B SPI SPCK PA14 A 28.6.2 Power Management The SPI may be clocked through the Power Management Controller (PMC), thus the programmer must first configure the PMC to enable the SPI clock. 504 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 28.6.3 Interrupt The SPI interface has an interrupt line connected to the Interrupt Controller. Handling the SPI interrupt requires programming the interrupt controller before configuring the SPI. Table 28-3. Peripheral IDs Instance ID SPI 21 28.6.4 Peripheral DMA Controller (PDC) The SPI interface can be used in conjunction with the PDC in order to reduce processor overhead. For a full description of the PDC, refer to the corresponding section in the full datasheet. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 505 28.7 Functional Description 28.7.1 Modes of Operation The SPI operates in Master Mode or in Slave Mode. Operation in Master Mode is programmed by writing at 1 the MSTR bit in the Mode Register. 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 MSTR bit is written at 0, 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. 28.7.2 Data Transfer Four combinations of polarity and phase are available for data transfers. The clock polarity is programmed with the CPOL bit in the Chip Select Register. The clock phase is programmed with the NCPHA bit. These two parameters determine the edges of the clock signal on which data is driven and sampled. Each of the two parameters 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 28-4 shows the four modes and corresponding parameter settings. Table 28-4. 506 SPI Bus Protocol Mode SPI Mode CPOL NCPHA Shift SPCK Edge Capture SPCK Edge SPCK Inactive Level 0 0 1 Falling Rising Low 1 0 0 Rising Falling Low 2 1 1 Rising Falling High 3 1 0 Falling Rising High SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Figure 28-3 and Figure 28-4 show examples of data transfers. Figure 28-3. SPI Transfer Format (NCPHA = 1, 8 bits per transfer) 1 SPCK cycle (for reference) 2 3 4 6 5 7 8 SPCK (CPOL = 0) SPCK (CPOL = 1) MOSI (from master) MSB MISO (from slave) MSB 6 5 4 3 2 1 LSB 6 5 4 3 2 1 LSB * NSS (to slave) * Not defined, but normally MSB of previous character received. Figure 28-4. SPI Transfer Format (NCPHA = 0, 8 bits per transfer) 1 SPCK cycle (for reference) 2 3 4 5 8 7 6 SPCK (CPOL = 0) SPCK (CPOL = 1) MOSI (from master) MISO (from slave) * MSB 6 5 4 3 2 1 MSB 6 5 4 3 2 1 LSB LSB NSS (to slave) * Not defined but normally LSB of previous character transmitted. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 507 28.7.3 Master Mode Operations When configured in Master Mode, the SPI operates on the clock generated by the internal programmable baud rate generator. 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 and the Receive Data Register, 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 SPI_TDR (Transmit Data 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. Receiving data cannot occur without transmitting data. If receiving mode is not needed, for example when communicating with a slave receiver only (such as an LCD), the receive status flags in the status register can be discarded. Before writing the TDR, the PCS field in the SPI_MR register must be set in order to select a slave. After enabling the SPI, a data transfer begins when the processor writes to the SPI_TDR (Transmit Data 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 the TDR, the PCS field must be set in order to select a slave. If new data is written in SPI_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 SPI_RDR, the data in SPI_TDR is loaded in the Shift Register and a new transfer starts. The transfer of a data written in SPI_TDR in the Shift Register is indicated by the TDRE bit (Transmit Data Register Empty) in the Status Register (SPI_SR). When new data is written in SPI_TDR, this bit is cleared. The TDRE bit is used to trigger the TransmitPDC channel. The end of transfer is indicated by the TXEMPTY flag in the SPI_SR register. If a transfer delay (DLYBCT) is greater than 0 for the last transfer, TXEMPTY is set after the completion of said delay. The master clock (MCK) can be switched off at this time. The transfer of received data from the Shift Register in SPI_RDR is indicated by the RDRF bit (Receive Data Register Full) in the Status Register (SPI_SR). When the received data is read, the RDRF bit is cleared. If the SPI_RDR (Receive Data Register) has not been read before new data is received, the Overrun Error bit (OVRES) in SPI_SR is set. As long as this flag is set, data is loaded in SPI_RDR. The user has to read the status register to clear the OVRES bit. Figure 28-5, shows a block diagram of the SPI when operating in Master Mode. Figure 28-6 on page 510 shows a flow chart describing how transfers are handled. 508 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 28.7.3.1 Master Mode Block Diagram Figure 28-5. Master Mode Block Diagram SPI_CSR0..3 SCBR Baud Rate Generator MCK SPCK SPI Clock SPI_CSR0..3 BITS NCPHA CPOL LSB MISO SPI_RDR RDRF OVRES RD MSB Shift Register MOSI SPI_TDR TDRE TD SPI_CSR0..3 SPI_RDR CSAAT PCS PS NPCS3 PCSDEC SPI_MR PCS 0 NPCS2 Current Peripheral NPCS1 SPI_TDR NPCS0 PCS 1 MSTR MODF NPCS0 MODFDIS SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 509 28.7.3.2 Master Mode Flow Diagram Figure 28-6. Master Mode Flow Diagram SPI Enable - 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. 1 TDRE ? 0 CSAAT ? PS ? 1 0 0 Fixed peripheral PS ? 1 Variable peripheral Variable peripheral SPI_TDR(PCS) = NPCS ? no NPCS = SPI_TDR(PCS) NPCS = SPI_MR(PCS) Delay DLYBS Serializer = SPI_TDR(TD) TDRE = 1 Data Transfer SPI_RDR(RD) = Serializer RDRF = 1 Delay DLYBCT 0 TDRE ? 1 1 CSAAT ? 0 NPCS = 0xF Delay DLYBCS 510 Fixed peripheral 0 1 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 yes SPI_MR(PCS) = NPCS ? no NPCS = 0xF NPCS = 0xF Delay DLYBCS Delay DLYBCS NPCS = SPI_TDR(PCS) NPCS = SPI_MR(PCS), SPI_TDR(PCS) Figure 28-7 shows Transmit Data Register Empty (TDRE), Receive Data Register (RDRF) and Transmission Register Empty (TXEMPTY) status flags behavior within the SPI_SR (Status Register) during an 8-bit data transfer in fixed mode and no Peripheral Data Controller involved. Figure 28-7. Status Register Flags Behavior 1 2 3 4 6 5 7 8 SPCK NPCS0 MOSI (from master) MSB 6 5 4 3 2 1 LSB TDRE RDR read Write in SPI_TDR RDRF MISO (from slave) MSB 6 5 4 3 2 1 LSB TXEMPTY shift register empty Figure 28-8 shows Transmission Register Empty (TXEMPTY), End of RX buffer (ENDRX), End of TX buffer (ENDTX), RX Buffer Full (RXBUFF) and TX Buffer Empty (TXBUFE) status flags behavior within the SPI_SR (Status Register) during an 8-bit data transfer in fixed mode with the Peripheral Data Controller involved. The PDC is programmed to transfer and receive three data. The next pointer and counter are not used. The RDRF and TDRE are not shown because these flags are managed by the PDC when using the PDC. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 511 Figure 28-8. PDC Status Register Flags Behavior 1 3 2 SPCK NPCS0 MOSI (from master) MISO (from slave) MSB MSB 6 5 4 3 2 1 LSB MSB 6 5 4 3 2 1 LSB MSB 6 5 4 3 2 1 LSB 6 5 4 3 2 1 LSB MSB 6 5 4 3 2 1 LSB MSB 6 5 4 3 2 1 LSB TDRE (not required if PDC is used) PDC loads first byte PDC loads 2nd byte (double buffer effect) PDC loads last byte ENDTX ENDRX TXBUFE RXBUFF TXEMPTY 28.7.3.3 Clock Generation The SPI Baud rate clock is generated by dividing the Master Clock (MCK), by a value between 1 and 255. This allows a maximum operating baud rate at up to Master Clock and a minimum operating baud rate of MCK divided by 255. Programming the SCBR field at 0 is forbidden. Triggering a transfer while SCBR is at 0 can lead to unpredictable results. At reset, SCBR is 0 and the user has to program 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 programmed in the SCBR field of the Chip Select Registers. This allows the SPI to automatically adapt the baud rate for each interfaced peripheral without reprogramming. 28.7.3.4 Transfer Delays Figure 28-9 shows a chip select transfer change and consecutive transfers on the same chip select. Three delays can be programmed to modify the transfer waveforms: The delay between chip selects, programmable only once for all the chip selects by writing the DLYBCS field in the Mode Register. 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 field 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 DLYBCT field. 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. 512 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Figure 28-9. Programmable Delays Chip Select 1 Chip Select 2 SPCK DLYBCS DLYBS DLYBCT DLYBCT 28.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. Fixed Peripheral Select: SPI exchanges data with only one peripheral Fixed Peripheral Select is activated by writing the PS bit to zero in SPI_MR (Mode Register). In this case, the current peripheral is defined by the PCS field in SPI_MR and the PCS field in the SPI_TDR has no effect. Variable Peripheral Select: Data can be exchanged with more than one peripheral without having to reprogram the NPCS field in the SPI_MR register. Variable Peripheral Select is activated by setting PS bit to one. The PCS field in SPI_TDR is used to select the current peripheral. This means that the peripheral selection can be defined for each new data. The value to write in the SPI_TDR register as the following format. [xxxxxxx(7-bit) + LASTXFER(1-bit)(1)+ xxxx(4-bit) + PCS (4-bit) + DATA (8 to 16-bit)] with PCS equals to the chip select to assert as defined in Section 28.8.4 (SPI Transmit Data Register) and LASTXFER bit at 0 or 1 depending on CSAAT bit. Note: 1. Optional. CSAAT, LASTXFER and CSNAAT bits are discussed in Section 28.7.3.9 “Peripheral Deselection with PDC”. If LASTXFER is used, the command must be issued before writing the last character. Instead of LASTXFER, the user can use the SPIDIS command. After the end of the PDC transfer, wait for the TXEMPTY flag, then write SPIDIS into the SPI_CR register (this will not change the configuration register values); the NPCS will be deactivated after the last character transfer. Then, another PDC transfer can be started if the SPIEN was previously written in the SPI_CR register. 28.7.3.6 SPI Peripheral DMA Controller (PDC) In both fixed and variable mode the Peripheral DMA Controller (PDC) can be used to reduce processor overhead. The Fixed Peripheral Selection allows buffer transfers with a single peripheral. Using the PDC is an optimal means, as the size of the data transfer between the memory and the SPI is either 8 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 Mode Register. Data written in SPI_TDR is 32 bits wide and defines the real data to be transmitted and the peripheral it is destined to. Using the PDC 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 chip select configuration 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. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 513 Transfer Size Depending on the data size to transmit, from 8 to 16 bits, the PDC manages automatically the type of pointer's size it has to point to. The PDC will perform the following transfer size depending on the mode and number of bits per data. Fixed Mode: 8-bit Data: Byte transfer, PDC Pointer Address = Address + 1 byte, PDC Counter = Counter - 1 8-bit to 16-bit Data: 2 bytes transfer. n-bit data transfer with don’t care data (MSB) filled with 0’s, PDC Pointer Address = Address + 2 bytes, PDC Counter = Counter - 1 Variable Mode: In variable Mode, PDC Pointer Address = Address +4 bytes and PDC Counter = Counter - 1 for 8 to 16-bit transfer size. When using the PDC, the TDRE and RDRF flags are handled by the PDC, thus the user’s application does not have to check those bits. Only End of RX Buffer (ENDRX), End of TX Buffer (ENDTX), Buffer Full (RXBUFF), TX Buffer Empty (TXBUFE) are significant. For further details about the Peripheral DMA Controller and user interface, refer to the PDC section of the product datasheet. 28.7.3.7 Peripheral Chip Select Decoding The user can program the SPI to operate with up to 15 peripherals by decoding the four Chip Select lines, NPCS0 to NPCS3 with 1 of up to 16 decoder/demultiplexer. This can be enabled by writing the PCSDEC bit at 1 in the Mode Register (SPI_MR). When operating without decoding, the SPI makes sure that in any case only one chip select line is activated, i.e., one NPCS line 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 on NPCS lines of either the Mode Register or the Transmit Data 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 1) 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, SPI_CRS0 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. Figure 28-10 below shows such an implementation. If the CSAAT bit is used, with or without the PDC, the Mode Fault detection for NPCS0 line must be disabled. This is not needed for all other chip select lines since Mode Fault Detection is only on NPCS0. 514 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Figure 28-10. Chip Select Decoding Application Block Diagram: Single Master/Multiple Slave Implementation SPCK MISO MOSI SPCK MISO MOSI SPCK MISO MOSI SPCK MISO MOSI Slave 0 Slave 1 Slave 14 NSS NSS SPI Master NSS NPCS0 NPCS1 NPCS2 NPCS3 1-of-n Decoder/Demultiplexer 28.7.3.8 Peripheral Deselection without PDC During a transfer of more than one data on a Chip Select without the PDC, the SPI_TDR is loaded by the processor, the flag TDRE rises as soon as the content of the SPI_TDR is transferred into the internal shift register. When this flag is detected high, the SPI_TDR can be reloaded. If this reload by the processor 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. But depending on the application software handling the SPI status register flags (by interrupt or polling method) or servicing other interrupts or other tasks, the processor may not reload the SPI_TDR in time to keep the chip select active (low). A null Delay Between Consecutive Transfer (DLYBCT) value in the SPI_CSR register, will give even less time for the processor to reload the SPI_TDR. With some SPI slave peripherals, requiring the chip select line to remain active (low) during a full set of transfers might lead to communication errors. To facilitate interfacing with such devices, the Chip Select Register [CSR0...CSR3] can be programmed with the CSAAT bit (Chip Select Active After Transfer) at 1. This allows the chip select lines to remain in their current state (low = active) until transfer to another chip select is required. Even if the SPI_TDR is not reloaded the chip select will remain active. To have the chip select line to raise at the end of the transfer the Last transfer Bit (LASTXFER) in the SPI_MR register must be set at 1 before writing the last data to transmit into the SPI_TDR. 28.7.3.9 Peripheral Deselection with PDC When the Peripheral DMA Controller is used, the chip select line will remain low during the whole transfer since the TDRE flag is managed by the PDC itself. The reloading of the SPI_TDR by the PDC is done as soon as TDRE flag is set to one. In this case the use of CSAAT bit might not be needed. However, it may happen that when other PDC channels connected to other peripherals are in use as well, the SPI PDC might be delayed by another (PDC with a higher priority on the bus). Having PDC buffers in slower memories like flash memory or SDRAM compared to fast internal SRAM, may lengthen the reload time of the SPI_TDR by the PDC as well. This means that the SPI_TDR might not be reloaded in time to keep the chip select line low. In this case the chip select line may toggle between data transfer and according to some SPI Slave devices, the communication might get lost. The use of the CSAAT bit might be needed. When the CSAAT bit is set at 0, the NPCS does not rise in all cases between two transfers on the same peripheral. During a transfer on a Chip Select, the flag TDRE rises as soon as the content of the SPI_TDR is transferred into the internal shifter. When this flag is detected the SPI_TDR can be reloaded. If this SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 515 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 Chip Select Register can be programmed with the CSNAAT bit (Chip Select Not Active After Transfer) at 1. This allows to de-assert systematically the chip select lines during a time DLYBCS. (The value of the CSNAAT bit is taken into account only if the CSAAT bit is set at 0 for the same Chip Select). Figure 28-11 shows different peripheral deselection cases and the effect of the CSAAT and CSNAAT bits. Figure 28-11. Peripheral Deselection CSAAT = 0 and CSNAAT = 0 TDRE NPCS[0..3] CSAAT = 1 and CSNAAT= 0 / 1 DLYBCT DLYBCT A A A A DLYBCS A DLYBCS PCS = A PCS = A Write SPI_TDR TDRE NPCS[0..3] DLYBCT DLYBCT A A A A DLYBCS A DLYBCS PCS=A PCS = A Write SPI_TDR TDRE NPCS[0..3] DLYBCT DLYBCT A B A B DLYBCS DLYBCS PCS = B PCS = B Write SPI_TDR CSAAT = 0 and CSNAAT = 0 CSAAT = 0 and CSNAAT = 1 DLYBCT DLYBCT TDRE NPCS[0..3] A A A A DLYBCS PCS = A Write SPI_TDR 516 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 PCS = A 28.7.3.10Mode Fault Detection A mode fault is detected when the SPI is programmed in Master Mode and a low level is driven by an external master on the NPCS0/NSS signal. In this case, multi-master configuration, NPCS0, MOSI, MISO and SPCK pins must be configured in open drain (through the PIO controller). When a mode fault is detected, the MODF bit in the SPI_SR is set until the SPI_SR is read and the SPI is automatically disabled until re-enabled by writing the SPIEN bit in the SPI_CR (Control Register) at 1. By default, the Mode Fault detection circuitry is enabled. The user can disable Mode Fault detection by setting the MODFDIS bit in the SPI Mode Register (SPI_MR). 28.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 field of the Chip Select Register 0 (SPI_CSR0). These bits are processed following a phase and a polarity defined respectively by the NCPHA and CPOL bits of the SPI_CSR0. Note that BITS, CPOL and NCPHA of the other Chip Select Registers have no effect when the SPI is programmed in Slave Mode. The bits are shifted out on the MISO line and sampled on the MOSI line. (For more information on BITS field, see also, the Register” on page 530.) (Note:) below the register table; Section 28.8.9 “SPI Chip Select When all the bits are processed, the received data is transferred in the Receive Data Register and the RDRF bit rises. If the SPI_RDR (Receive Data Register) has not been read before new data is received, the Overrun Error bit (OVRES) in SPI_SR is set. As long as this flag is set, data is loaded in SPI_RDR. The user has to read the status register to clear the 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 Transmit Data Register (SPI_TDR), 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 at 0. When a first data is written in SPI_TDR, it is transferred immediately in the Shift Register and the TDRE bit rises. If new data is written, it remains in SPI_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 SPI_TDR is transferred in the Shift Register and the 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 Transmit Data Register. In case no character is ready to be transmitted, i.e. no character has been written in SPI_TDR since the last load from SPI_TDR to the Shift Register, the SPI_TDR is retransmitted. In this case the Underrun Error Status Flag (UNDES) is set in the SPI_SR. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 517 Figure 28-12 shows a block diagram of the SPI when operating in Slave Mode. Figure 28-12. Slave Mode Functional Block Diagram SPCK NSS SPI Clock SPIEN SPIENS SPIDIS SPI_CSR0 BITS NCPHA CPOL MOSI LSB SPI_RDR RDRF OVRES RD MSB Shift Register MISO SPI_TDR TD TDRE 28.7.5 Write Protected Registers To prevent any single software error that may corrupt SPI behavior, the registers listed below can be writeprotected by setting the WPEN bit in the SPI Write Protection Mode Register (SPI_WPMR). If a write access in a write-protected register is detected, then the WPVS flag in the SPI Write Protection Status Register (SPI_WPSR) is set and the field WPVSRC indicates in which register the write access has been attempted. The WPVS flag is automatically reset after reading the SPI Write Protection Status Register (SPI_WPSR). List of the write-protected registers: Section 28.8.2 “SPI Mode Register” Section 28.8.9 “SPI Chip Select Register” 518 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 28.8 Serial Peripheral Interface (SPI) User Interface Table 28-5. Register Mapping Offset Register Name Access Reset 0x00 Control Register SPI_CR Write-only --- 0x04 Mode Register SPI_MR Read-write 0x0 0x08 Receive Data Register SPI_RDR Read-only 0x0 0x0C Transmit Data Register SPI_TDR Write-only --- 0x10 Status Register SPI_SR Read-only 0x000000F0 0x14 Interrupt Enable Register SPI_IER Write-only --- 0x18 Interrupt Disable Register SPI_IDR Write-only --- 0x1C Interrupt Mask Register SPI_IMR Read-only 0x0 0x20 - 0x2C Reserved 0x30 Chip Select Register 0 SPI_CSR0 Read-write 0x0 0x34 Chip Select Register 1 SPI_CSR1 Read-write 0x0 0x38 Chip Select Register 2 SPI_CSR2 Read-write 0x0 0x3C Chip Select Register 3 SPI_CSR3 Read-write 0x0 – – – 0x40 - 0xE0 Reserved 0xE4 Write Protection Control Register SPI_WPMR Read-write 0x0 0xE8 Write Protection Status Register SPI_WPSR Read-only 0x0 0x00EC - 0x00F8 Reserved – – – 0x00FC Reserved – – – Reserved for PDC Registers – – – 0x100 - 0x124 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 519 28.8.1 SPI Control Register Name: SPI_CR Address: 0x40008000 Access: Write-only 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 – – – – – – – – 7 6 5 4 3 2 1 0 SWRST – – – – – SPIDIS SPIEN • SPIEN: SPI Enable 0 = No effect. 1 = Enables the SPI to transfer and receive data. • SPIDIS: SPI Disable 0 = No effect. 1 = Disables the SPI. As soon as SPIDIS is set, 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 control register is written, the SPI is disabled. • SWRST: SPI Software Reset 0 = No effect. 1 = Reset the SPI. A software-triggered hardware reset of the SPI interface is performed. The SPI is in slave mode after software reset. PDC channels are not affected by software reset. • LASTXFER: Last Transfer 0 = No effect. 1 = The current NPCS will be deasserted after the character written in TD has been transferred. When CSAAT is set, this allows to close the communication with the current serial peripheral by raising the corresponding NPCS line as soon as TD transfer has completed. Refer to Section 28.7.3.5 “Peripheral Selection”for more details. 520 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 28.8.2 SPI Mode Register Name: SPI_MR Address: 0x40008004 Access: Read-write 31 30 29 28 27 26 19 18 25 24 17 16 DLYBCS 23 22 21 20 – – – – 15 14 13 12 11 10 9 8 – – – – – – – – PCS 7 6 5 4 3 2 1 0 LLB – WDRBT MODFDIS – PCSDEC PS MSTR This register can only be written if the WPEN bit is cleared in ”SPI Write Protection Mode Register”. • MSTR: Master/Slave Mode 0 = SPI is in Slave mode. 1 = SPI is in Master mode. • PS: Peripheral Select 0 = Fixed Peripheral Select. 1 = Variable Peripheral Select. • 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 Chip Select Registers define the characteristics of the 15 chip selects according to the following rules: SPI_CSR0 defines peripheral chip select signals 0 to 3. SPI_CSR1 defines peripheral chip select signals 4 to 7. SPI_CSR2 defines peripheral chip select signals 8 to 11. SPI_CSR3 defines peripheral chip select signals 12 to 14. • MODFDIS: Mode Fault Detection 0 = Mode fault detection is enabled. 1 = Mode fault detection is disabled. • WDRBT: Wait Data Read Before Transfer 0 = No Effect. In master mode, a transfer can be initiated whatever the state of the Receive Data Register is. 1 = In Master Mode, a transfer can start only if the Receive Data Register is empty, i.e. does not contain any unread data. This mode prevents overrun error in reception. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 521 • LLB: Local Loopback Enable 0 = Local loopback path disabled. 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.) • PCS: Peripheral Chip Select This field is only used if Fixed Peripheral Select is active (PS = 0). If PCSDEC = 0: PCS = xxx0 NPCS[3:0] = 1110 PCS = xx01 NPCS[3:0] = 1101 PCS = x011 NPCS[3:0] = 1011 PCS = 0111 NPCS[3:0] = 0111 PCS = 1111 forbidden (no peripheral is selected) (x = don’t care) If PCSDEC = 1: NPCS[3:0] output signals = PCS. • 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 MCK periods will be inserted by default. Otherwise, the following equation determines the delay: DLYBCS Delay Between Chip Selects = ----------------------MCK 522 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 28.8.3 SPI Receive Data Register Name: SPI_RDR Address: 0x40008008 Access: Read-only 31 30 29 28 27 26 25 24 – – – – – – – – 23 22 21 20 19 18 17 16 – – – – 15 14 13 12 PCS 11 10 9 8 3 2 1 0 RD 7 6 5 4 RD • RD: Receive Data Data received by the SPI Interface is stored in this register right-justified. Unused bits read zero. • PCS: Peripheral Chip Select In Master Mode only, these bits indicate the value on the NPCS pins at the end of a transfer. Otherwise, these bits read zero. Note: When using variable peripheral select mode (PS = 1 in SPI_MR) it is mandatory to also set the WDRBT field to 1 if the SPI_RDR PCS field is to be processed. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 523 28.8.4 SPI Transmit Data Register Name: SPI_TDR Address: 0x4000800C Access: Write-only 31 30 29 28 27 26 25 24 – – – – – – – LASTXFER 23 22 21 20 19 18 17 16 – – – – 15 14 13 12 PCS 11 10 9 8 3 2 1 0 TD 7 6 5 4 TD • 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 transmit data register in a right-justified format. • PCS: Peripheral Chip Select This field is only used if Variable Peripheral Select is active (PS = 1). If PCSDEC = 0: PCS = xxx0 NPCS[3:0] = 1110 PCS = xx01 NPCS[3:0] = 1101 PCS = x011 NPCS[3:0] = 1011 PCS = 0111 NPCS[3:0] = 0111 PCS = 1111 forbidden (no peripheral is selected) (x = don’t care) If PCSDEC = 1: NPCS[3:0] output signals = PCS • LASTXFER: Last Transfer 0 = No effect. 1 = The current NPCS will be deasserted after the character written in TD has been transferred. When CSAAT is set, this allows to close the communication with the current serial peripheral by raising the corresponding NPCS line as soon as TD transfer has completed. This field is only used if Variable Peripheral Select is active (PS = 1). 524 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 28.8.5 SPI Status Register Name: SPI_SR Address: 0x40008010 Access: Read-only 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 7 6 5 4 3 2 1 0 TXBUFE RXBUFF ENDTX ENDRX OVRES MODF TDRE RDRF • RDRF: Receive Data Register Full 0 = No data has been received since the last read of SPI_RDR 1 = Data has been received and the received data has been transferred from the serializer to SPI_RDR since the last read of SPI_RDR. • TDRE: Transmit Data Register Empty 0 = Data has been written to SPI_TDR and not yet transferred to the serializer. 1 = The last data written in the Transmit Data Register has been transferred to the serializer. TDRE equals zero when the SPI is disabled or at reset. The SPI enable command sets this bit to one. • MODF: Mode Fault Error 0 = No Mode Fault has been detected since the last read of SPI_SR. 1 = A Mode Fault occurred since the last read of the SPI_SR. • OVRES: Overrun Error Status 0 = No overrun has been detected since the last read of SPI_SR. 1 = An overrun has occurred since the last read of SPI_SR. An overrun occurs when SPI_RDR is loaded at least twice from the serializer since the last read of the SPI_RDR. • ENDRX: End of RX buffer 0 = The Receive Counter Register has not reached 0 since the last write in SPI_RCR(1) or SPI_RNCR(1). 1 = The Receive Counter Register has reached 0 since the last write in SPI_RCR(1) or SPI_RNCR(1). • ENDTX: End of TX buffer 0 = The Transmit Counter Register has not reached 0 since the last write in SPI_TCR(1) or SPI_TNCR(1). 1 = The Transmit Counter Register has reached 0 since the last write in SPI_TCR(1) or SPI_TNCR(1). • RXBUFF: RX Buffer Full 0 = SPI_RCR(1) or SPI_RNCR(1) has a value other than 0. 1 = Both SPI_RCR(1) and SPI_RNCR(1) have a value of 0. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 525 • TXBUFE: TX Buffer Empty 0 = SPI_TCR(1) or SPI_TNCR(1) has a value other than 0. 1 = Both SPI_TCR(1) and SPI_TNCR(1) have a value of 0. • NSSR: NSS Rising 0 = No rising edge detected on NSS pin since last read. 1 = A rising edge occurred on NSS pin since last read. • TXEMPTY: Transmission Registers Empty 0 = As soon as data is written in SPI_TDR. 1 = SPI_TDR and internal shifter are empty. If a transfer delay has been defined, TXEMPTY is set after the completion of such delay. • UNDES: Underrun Error Status (Slave Mode Only) 0 = No underrun has been detected since the last read of SPI_SR. 1 = A transfer begins whereas no data has been loaded in the Transmit Data Register. • SPIENS: SPI Enable Status 0 = SPI is disabled. 1 = SPI is enabled. Note: 526 1. SPI_RCR, SPI_RNCR, SPI_TCR, SPI_TNCR are physically located in the PDC. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 28.8.6 SPI Interrupt Enable Register Name: SPI_IER Address: 0x40008014 Access: Write-only 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 7 6 5 4 3 2 1 0 TXBUFE RXBUFF ENDTX ENDRX OVRES MODF TDRE RDRF 0 = No effect. 1 = Enables the corresponding interrupt. • RDRF: Receive Data Register Full Interrupt Enable • TDRE: SPI Transmit Data Register Empty Interrupt Enable • MODF: Mode Fault Error Interrupt Enable • OVRES: Overrun Error Interrupt Enable • ENDRX: End of Receive Buffer Interrupt Enable • ENDTX: End of Transmit Buffer Interrupt Enable • RXBUFF: Receive Buffer Full Interrupt Enable • TXBUFE: Transmit Buffer Empty Interrupt Enable • NSSR: NSS Rising Interrupt Enable • TXEMPTY: Transmission Registers Empty Enable • UNDES: Underrun Error Interrupt Enable SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 527 28.8.7 SPI Interrupt Disable Register Name: SPI_IDR Address: 0x40008018 Access: Write-only 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 7 6 5 4 3 2 1 0 TXBUFE RXBUFF ENDTX ENDRX OVRES MODF TDRE RDRF 0 = No effect. 1 = Disables the corresponding interrupt. • RDRF: Receive Data Register Full Interrupt Disable • TDRE: SPI Transmit Data Register Empty Interrupt Disable • MODF: Mode Fault Error Interrupt Disable • OVRES: Overrun Error Interrupt Disable • ENDRX: End of Receive Buffer Interrupt Disable • ENDTX: End of Transmit Buffer Interrupt Disable • RXBUFF: Receive Buffer Full Interrupt Disable • TXBUFE: Transmit Buffer Empty Interrupt Disable • NSSR: NSS Rising Interrupt Disable • TXEMPTY: Transmission Registers Empty Disable • UNDES: Underrun Error Interrupt Disable 528 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 28.8.8 SPI Interrupt Mask Register Name: SPI_IMR Address: 0x4000801C Access: Read-only 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 7 6 5 4 3 2 1 0 TXBUFE RXBUFF ENDTX ENDRX OVRES MODF TDRE RDRF 0 = The corresponding interrupt is not enabled. 1 = The corresponding interrupt is enabled. • RDRF: Receive Data Register Full Interrupt Mask • TDRE: SPI Transmit Data Register Empty Interrupt Mask • MODF: Mode Fault Error Interrupt Mask • OVRES: Overrun Error Interrupt Mask • ENDRX: End of Receive Buffer Interrupt Mask • ENDTX: End of Transmit Buffer Interrupt Mask • RXBUFF: Receive Buffer Full Interrupt Mask • TXBUFE: Transmit Buffer Empty Interrupt Mask • NSSR: NSS Rising Interrupt Mask • TXEMPTY: Transmission Registers Empty Mask • UNDES: Underrun Error Interrupt Mask SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 529 28.8.9 SPI Chip Select Register Name: SPI_CSRx[x=0..3] Address: 0x40008030 Access: Read/Write 31 30 29 28 27 26 25 24 19 18 17 16 11 10 9 8 DLYBCT 23 22 21 20 DLYBS 15 14 13 12 SCBR 7 6 5 4 BITS 3 2 1 0 CSAAT CSNAAT NCPHA CPOL This register can only be written if the WPEN bit is cleared in ”SPI Write Protection Mode Register”. Note: SPI_CSRx registers must be written even if the user wants to use the defaults. The BITS field will not be updated with the translated value unless the register is written. • CPOL: Clock Polarity 0 = The inactive state value of SPCK is logic level zero. 1 = The inactive state value of SPCK is logic level one. 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. • NCPHA: Clock Phase 0 = Data is changed on the leading edge of SPCK and captured on the following edge of SPCK. 1 = Data is captured on the leading edge of SPCK and changed on the following 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. • CSNAAT: Chip Select Not Active After Transfer (Ignored if CSAAT = 1) 0 = The Peripheral Chip Select does not rise between two transfers if the SPI_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 after each transfer performed on the same slave. It remains active after the end of transfer for a minimal duration of: DLYBCT – ----------------------- (if DLYBCT field is different from 0) MCK DLYBCT + 1 – --------------------------------- (if DLYBCT field equals 0) MCK • CSAAT: Chip Select Active After Transfer 0 = The Peripheral Chip Select Line rises as soon as the last transfer is achieved. 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. 530 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 • BITS: Bits Per Transfer (See the (Note:) below the register table; Section 28.8.9 “SPI Chip Select Register” on page 530.) The BITS field determines the number of data bits transferred. Reserved values should not be used. Value Name Description 0 8_BIT 8 bits for transfer 1 9_BIT 9 bits for transfer 2 10_BIT 10 bits for transfer 3 11_BIT 11 bits for transfer 4 12_BIT 12 bits for transfer 5 13_BIT 13 bits for transfer 6 14_BIT 14 bits for transfer 7 15_BIT 15 bits for transfer 8 16_BIT 16 bits for transfer 9 – Reserved 10 – Reserved 11 – Reserved 12 – Reserved 13 – Reserved 14 – Reserved 15 – Reserved • SCBR: Serial Clock Baud Rate In Master Mode, the SPI Interface uses a modulus counter to derive the SPCK baud rate from the Master Clock MCK. 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: MCK SPCK Baudrate = --------------SCBR Programming the SCBR field at 0 is forbidden. Triggering a transfer while SCBR is at 0 can lead to unpredictable results. At reset, SCBR is 0 and the user has to program it at a valid value before performing the first transfer. Note: If one of the SCBR fields inSPI_CSRx is set to 1, the other SCBR fields in SPI_CSRx must be set to 1 as well, if they are required to process transfers. If they are not used to transfer data, they can be set at any value. • 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: DLYBS Delay Before SPCK = ------------------MCK • 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. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 531 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: 32 × DLYBCT Delay Between Consecutive Transfers = -----------------------------------MCK 532 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 28.8.10 SPI Write Protection Mode Register Name: SPI_WPMR Address: 0x400080E4 Access: Read-write 31 30 29 28 27 26 25 24 19 18 17 16 11 10 9 8 WPKEY 23 22 21 20 WPKEY 15 14 13 12 WPKEY 7 6 5 4 3 2 1 0 – – – – – – – WPEN • WPEN: Write Protect Enable 0: Disables the Write Protect if WPKEY corresponds to 0x535049 (“SPI” in ASCII). 1: Enables the Write Protect if WPKEY corresponds to 0x535049 (“SPI” in ASCII). Protects the registers: • Section 28.8.2 “SPI Mode Register” • Section 28.8.9 “SPI Chip Select Register” • WPKEY: Write Protect Key Value 0x535049 Name PASSWD Description Writing any other value in this field aborts the write operation of the WPEN bit. Always reads as 0. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 533 28.8.11 SPI Write Protection Status Register Name: SPI_WPSR Address: 0x400080E8 Access: Read-only 31 30 29 28 27 26 25 24 – – – – – – – – 23 22 21 20 19 18 17 16 – – – – – – – – 15 14 13 12 11 10 9 8 WPVSRC 7 6 5 4 3 2 1 0 – – – – – – – WPVS • WPVS: Write Protection Violation Status 0 = No Write Protect Violation has occurred since the last read of the SPI_WPSR register. 1 = A Write Protect Violation has occurred since the last read of the SPI_WPSR register. If this violation is an unauthorized attempt to write a protected register, the associated violation is reported into field WPVSRC. • WPVSRC: Write Protection Violation Source This Field indicates the APB Offset of the register concerned by the violation (SPI_MR or SPI_CSRx) 534 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 29. Two-wire Interface (TWI) 29.1 Description The Atmel Two-wire Interface (TWI) interconnects components on a unique two-wire bus, made up of one clock line and one data line with speeds of up to 400 Kbits per second, 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 Real Time Clock (RTC), Dot Matrix/Graphic LCD Controllers and Temperature Sensor, to name but a few. The TWI is programmable as a master or a slave with sequential or single-byte access. Multiple master capability is supported. Arbitration of the bus is performed internally and puts the TWI in slave mode 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. Below, Table 29-1 lists the compatibility level of the Atmel Two-wire Interface in Master Mode and a full I 2C compatible device. Atmel TWI compatibility with I2C Standard Table 29-1. I2C Standard Atmel TWI Standard Mode Speed (100 KHz) Supported Fast Mode Speed (400 KHz) Supported 7 or 10 bits Slave Addressing Supported (1) START BYTE Not Supported Repeated Start (Sr) Condition Supported ACK and NACK Management Supported Slope control and input filtering (Fast mode) Not Supported Clock stretching Supported Multi Master Capability Supported Note: 29.2 1. START + b000000001 + Ack + Sr Embedded Characteristics 3 x TWI Compatible with Atmel Two-wire Interface Serial Memory and I²C Compatible Devices(1) One, Two or Three Bytes for Slave Address Sequential Read-write Operations Master, Multi-master and Slave Mode Operation Bit Rate: Up to 400 Kbits General Call Supported in Slave mode SMBUS Quick Command Supported in Master Mode Connection to Peripheral DMA Controller (PDC) Channel Capabilities Optimizes Data Transfers Note: ̶ One Channel for the Receiver, One Channel for the Transmitter 1. See Table 29-1 for details on compatibility with I²C Standard. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 535 29.3 List of Abbreviations Table 29-2. 29.4 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 Block Diagram Figure 29-1. Block Diagram APB Bridge TWCK PIO PMC MCK TWD Two-wire Interface TWI Interrupt 536 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Interrupt Controller 29.5 Application Block Diagram Figure 29-2. Application Block Diagram VDD Rp Host with TWI Interface Rp TWD TWCK Atmel TWI Serial EEPROM Slave 1 I²C RTC I²C LCD Controller I²C Temp. Sensor Slave 2 Slave 3 Slave 4 Rp: Pull up value as given by the I²C Standard 29.5.1 I/O Lines Description Table 29-3. I/O Lines Description Pin Name Pin Description TWD Two-wire Serial Data Input/Output TWCK Two-wire Serial Clock Input/Output 29.6 Type Product Dependencies 29.6.1 I/O Lines Both TWD and TWCK are bidirectional lines, connected to a positive supply voltage via a current source or pull-up resistor (see Figure 29-2 on page 537). 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. TWD and TWCK pins may be multiplexed with PIO lines. To enable the TWI, the programmer must perform the following step: Program the PIO controller to dedicate TWD and TWCK as peripheral lines. The user must not program TWD and TWCK as open-drain. It is already done by the hardware. Table 29-4. I/O Lines Instance Signal I/O Line Peripheral TWI0 TWCK0 PA4 A TWI0 TWD0 PA3 A TWI1 TWCK1 PB5 A TWI1 TWD1 PB4 A TWI2 TWCK2 PB1 B TWI2 TWD2 PB0 B SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 537 29.6.2 Power Management Enable the peripheral clock. The TWI interface may be clocked through the Power Management Controller (PMC), thus the programmer must first configure the PMC to enable the TWI clock. 29.6.3 Interrupt The TWI interface has an interrupt line connected to the Interrupt Controller. In order to handle interrupts, the Interrupt Controller must be programmed before configuring the TWI. Table 29-5. 538 Peripheral IDs Instance ID TWI0 19 TWI1 20 TWI2 22 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 29.7 Functional Description 29.7.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 29-4). Each transfer begins with a START condition and terminates with a STOP condition (see Figure 29-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 29-3. START and STOP Conditions TWD TWCK Start Figure 29-4. Stop Transfer Format TWD TWCK Start Address R/W Ack Data Ack Data Ack Stop 29.7.2 Modes of Operation The TWI has different modes of operations: Master transmitter mode Master receiver mode Multi-master transmitter mode Multi-master receiver mode Slave transmitter mode Slave receiver mode These modes are described in the following chapters. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 539 29.8 Master Mode 29.8.1 Definition The Master is the device that starts a transfer, generates a clock and stops it. 29.8.2 Application Block Diagram Figure 29-5. Master Mode Typical Application Block Diagram VDD Rp Host with TWI Interface Rp TWD TWCK Atmel TWI Serial EEPROM Slave 1 I²C RTC I²C LCD Controller I²C Temp. Sensor Slave 2 Slave 3 Slave 4 Rp: Pull up value as given by the I²C Standard 29.8.3 Programming Master Mode The following registers have to be programmed before entering Master mode: 1. DADR (+ IADRSZ + IADR if a 10 bit device is addressed): The device address is used to access slave devices in read or write mode. 2. CKDIV + CHDIV + CLDIV: Clock Waveform. 3. SVDIS: Disable the slave mode. 4. MSEN: Enable the master mode. 29.8.4 Master Transmitter Mode After the master initiates a Start condition when writing into the Transmit Holding Register, TWI_THR, it sends a 7bit slave address, configured in the Master Mode register (DADR in TWI_MMR), to notify the slave device. The bit following the slave address indicates the transfer direction, 0 in this case (MREAD = 0 in TWI_MMR). The TWI transfers require the slave to acknowledge each received 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 Not Acknowledge bit (NACK) in the status register if the slave does not acknowledge the byte. As with the other status bits, an interrupt can be generated if enabled in the interrupt enable register (TWI_IER). If the slave acknowledges the byte, the data written in the TWI_THR, is then shifted in the internal shifter and transferred. When an acknowledge is detected, the TXRDY bit is set until a new write in the TWI_THR. TXRDY is used as Transmit Ready for the PDC transmit channel. While no new data is written in the TWI_THR, the Serial Clock Line is tied low. When new data is written in the TWI_THR, the SCL is released and the data is sent. To generate a STOP event, the STOP command must be performed by writing in the STOP field of TWI_CR. 540 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 After a Master Write transfer, the Serial Clock line is stretched (tied low) while no new data is written in the TWI_THR or until a STOP command is performed. See Figure 29-6, Figure 29-7, and Figure 29-8. Figure 29-6. Master Write with One Data Byte STOP Command sent (write in TWI_CR) TWD S DADR W A DATA A P TXCOMP TXRDY Write THR (DATA) Figure 29-7. Master Write with Multiple Data Bytes STOP command performed (by writing in the TWI_CR) TWD S DADR W A DATA n A DATA n+1 A DATA n+2 A P TWCK TXCOMP TXRDY Write THR (Data n) Write THR (Data n+1) Write THR (Data n+2) Last data sent SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 541 Figure 29-8. Master Write with One Byte Internal Address and Multiple Data Bytes STOP command performed (by writing in the TWI_CR) TWD S DADR W A IADR A DATA n A DATA n+1 A DATA n+2 A P TWCK TXCOMP TXRDY Write THR (Data n) Write THR (Data n+1) Write THR (Data n+2) Last data sent 29.8.5 Master Receiver Mode The read sequence begins by setting the START bit. After the start condition has been sent, the master sends a 7bit slave address to notify the slave device. The bit following the slave address indicates the transfer direction, 1 in this case (MREAD = 1 in TWI_MMR). 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 NACK bit in the status register if the slave does not acknowledge the byte. If an acknowledge is received, the master is then ready to receive data from the slave. After data has been received, the master sends an acknowledge condition to notify the slave that the data has been received except for the last data, after the stop condition. See Figure 29-9. When the RXRDY bit is set in the status register, a character has been received in the receive-holding register (TWI_RHR). The RXRDY bit is reset when reading the TWI_RHR. When a single data byte read is performed, with or without internal address (IADR), the START and STOP bits must be set at the same time. See Figure 29-9. When a multiple data byte read is performed, with or without internal address (IADR), the STOP bit must be set after the next-to-last data received. See Figure 29-10. For Internal Address usage see Section 29.8.6. Figure 29-9. Master Read with One Data Byte TWD S DADR R A DATA NA P TXCOMP Write START & STOP Bit RXRDY Read RHR 542 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Figure 29-10. Master Read with Multiple Data Bytes TWD S DADR R A DATA n A DATA (n+1) A DATA (n+m)-1 A DATA (n+m) P NA TXCOMP Write START Bit RXRDY Read RHR DATA n Read RHR DATA (n+1) Read RHR DATA (n+m)-1 Read RHR DATA (n+m) Write STOP Bit after next-to-last data read RXRDY is used as Receive Ready for the PDC receive channel. 29.8.6 Internal Address The TWI interface can perform various transfer formats: Transfers with 7-bit slave address devices and 10-bit slave address devices. 29.8.6.1 7-bit Slave Addressing When Addressing 7-bit slave devices, the internal address bytes are used to perform random address (read or write) accesses to reach one or more data bytes, within a memory page location in a serial memory, for example. When performing read operations with an internal address, the TWI performs a write operation to set the internal address into the slave device, and then switch to Master Receiver mode. Note that the second start condition (after sending the IADR) is sometimes called “repeated start” (Sr) in I2C fully-compatible devices. See Figure 29-12. See Figure 29-11 and Figure 29-13 for Master Write operation with internal address. The three internal address bytes are configurable through the Master Mode register (TWI_MMR). If the slave device supports only a 7-bit address, i.e. no internal address, IADRSZ must be set to 0. In the figures below the following abbreviations are used: S Start Sr Repeated Start P Stop W Write R Read A Acknowledge NA Not Acknowledge DADR Device Address IADR Internal Address SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 543 Figure 29-11. Master Write with One, Two or Three Bytes Internal Address and One Data Byte Three bytes internal address TWD S DADR W A IADR(23:16) A IADR(15:8) A IADR(7:0) A W A IADR(15:8) A IADR(7:0) A DATA A W A IADR(7:0) A DATA A DATA A P Two bytes internal address TWD S DADR P One byte internal address TWD S DADR P Figure 29-12. Master Read with One, Two or Three Bytes Internal Address and One Data Byte Three bytes internal address TWD S DADR W A IADR(23:16) A A IADR(15:8) IADR(7:0) Sr A DADR R A DATA NA P Two bytes internal address TWD S DADR W A IADR(15:8) A IADR(7:0) A Sr W A IADR(7:0) A Sr R A DADR R A DATA NA P One byte internal address TWD S DADR DADR DATA NA P 29.8.6.2 10-bit Slave Addressing For a slave address higher than 7 bits, the user must configure the address size (IADRSZ) and set the other slave address bits in the internal address register (TWI_IADR). The two remaining Internal address bytes, IADR[15:8] and IADR[23:16] can be used the same as in 7-bit Slave Addressing. Example: Address a 10-bit device (10-bit device address is b1 b2 b3 b4 b5 b6 b7 b8 b9 b10) 1. Program IADRSZ = 1, 2. Program DADR with 1 1 1 1 0 b1 b2 (b1 is the MSB of the 10-bit address, b2, etc.) 3. Program TWI_IADR with b3 b4 b5 b6 b7 b8 b9 b10 (b10 is the LSB of the 10-bit address) Figure 29-13 below shows a byte write to an Atmel AT24LC512 EEPROM. This demonstrates the use of internal addresses to access the device. Figure 29-13. Internal Address Usage S T A R T Device Address W R I T E FIRST WORD ADDRESS SECOND WORD ADDRESS S T O P DATA 0 M S B LR A S / C BW K M S B A C K LA SC BK 29.8.7 Using the Peripheral DMA Controller (PDC) The use of the PDC significantly reduces the CPU load. To assure correct implementation, respect the following programming sequences: 544 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 A C K 29.8.7.1 Data Transmit with the PDC 1. 2. Initialize the transmit PDC (memory pointers, transfer size - 1). 3. Start the transfer by setting the PDC TXTEN bit. 4. Wait for the PDC ENDTX Flag either by using the polling method or ENDTX interrupt. Configure the master (DADR, CKDIV, etc.) or slave mode. 5. Disable the PDC by setting the PDC TXTDIS bit. 6. Wait for the TXRDY flag in TWI_SR register 7. Set the STOP command in TWI_CR. 8. Write the last character in TWI_THR 9. (Optional) Wait for the TXCOMP flag in TWI_SR register before disabling the peripheral clock if required 29.8.7.2 Data Receive with the PDC The PDC transfer size must be defined with the buffer size minus 2. The two remaining characters must be managed without PDC to ensure that the exact number of bytes are received whatever the system bus latency conditions encountered during the end of buffer transfer period. In slave mode, the number of characters to receive must be known in order to configure the PDC. 1. Initialize the receive PDC (memory pointers, transfer size - 2). 2. Configure the master (DADR, CKDIV, etc.) or slave mode. 3. Set the PDC RXTEN bit. 4. (Master Only) Write the START bit in the TWI_CR register to start the transfer 5. Wait for the PDC ENDRX Flag either by using polling method or ENDRX interrupt. 6. Disable the PDC by setting the PDC RXTDIS bit. 7. Wait for the RXRDY flag in TWI_SR register 8. Set the STOP command in TWI_CR 9. Read the penultimate character in TWI_RHR 10. Wait for the RXRDY flag in TWI_SR register 11. Read the last character in TWI_RHR 12. (Optional) Wait for the TXCOMP flag in TWI_SR register before disabling the peripheral clock if required 29.8.8 SMBUS Quick Command (Master Mode Only) The TWI interface can perform a Quick Command: 1. Configure the master mode (DADR, CKDIV, etc.). 2. Write the MREAD bit in the TWI_MMR register at the value of the one-bit command to be sent. 3. Start the transfer by setting the QUICK bit in the TWI_CR. Figure 29-14. SMBUS Quick Command TWD S DADR R/W A P TXCOMP TXRDY Write QUICK command in TWI_CR SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 545 29.8.9 Read-write Flowcharts The following flowcharts shown in Figure 29-16 on page 547, Figure 29-17 on page 548, Figure 29-18 on page 549, Figure 29-19 on page 550 and Figure 29-20 on page 551 give examples for read and write operations. A polling or interrupt method can be used to check the status bits. The interrupt method requires that the interrupt enable register (TWI_IER) be configured first. Figure 29-15. TWI Write Operation with Single Data Byte without Internal Address BEGIN Set TWI clock (CLDIV, CHDIV, CKDIV) in TWI_CWGR (Needed only once) Set the Control register: - Master enable TWI_CR = MSEN + SVDIS Set the Master Mode register: - Device slave address (DADR) - Transfer direction bit Write ==> bit MREAD = 0 Load Transmit register TWI_THR = Data to send Write STOP Command TWI_CR = STOP Read Status register No TXRDY = 1? Yes Read Status register No TXCOMP = 1? Yes Transfer finished 546 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Figure 29-16. TWI Write Operation with Single Data Byte and Internal Address BEGIN Set TWI clock (CLDIV, CHDIV, CKDIV) in TWI_CWGR (Needed only once) Set the Control register: - Master enable TWI_CR = MSEN + SVDIS Set the Master Mode register: - Device slave address (DADR) - Internal address size (IADRSZ) - Transfer direction bit Write ==> bit MREAD = 0 Set the internal address TWI_IADR = address Load transmit register TWI_THR = Data to send Write STOP command TWI_CR = STOP Read Status register No TXRDY = 1? Yes Read Status register TXCOMP = 1? No Yes Transfer finished SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 547 Figure 29-17. TWI Write Operation with Multiple Data Bytes with or without Internal Address BEGIN Set TWI clock (CLDIV, CHDIV, CKDIV) in TWI_CWGR (Needed only once) Set the Control register: - Master enable TWI_CR = MSEN + SVDIS Set the Master Mode register: - Device slave address - Internal address size (if IADR used) - Transfer direction bit Write ==> bit MREAD = 0 No Internal address size = 0? Set the internal address TWI_IADR = address Yes Load Transmit register TWI_THR = Data to send Read Status register TWI_THR = data to send No TXRDY = 1? Yes Data to send? Yes No Write STOP Command TWI_CR = STOP Read Status register No TXCOMP = 1? Yes END 548 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Figure 29-18. TWI Read Operation with Single Data Byte without Internal Address BEGIN Set TWI clock (CLDIV, CHDIV, CKDIV) in TWI_CWGR (Needed only once) Set the Control register: - Master enable TWI_CR = MSEN + SVDIS Set the Master Mode register: - Device slave address - Transfer direction bit Read ==> bit MREAD = 1 Start the transfer TWI_CR = START | STOP Read status register RXRDY = 1? No Yes Read Receive Holding Register Read Status register No TXCOMP = 1? Yes END SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 549 Figure 29-19. TWI Read Operation with Single Data Byte and Internal Address BEGIN Set TWI clock (CLDIV, CHDIV, CKDIV) in TWI_CWGR (Needed only once) Set the Control register: - Master enable TWI_CR = MSEN + SVDIS Set the Master Mode register: - Device slave address - Internal address size (IADRSZ) - Transfer direction bit Read ==> bit MREAD = 1 Set the internal address TWI_IADR = address Start the transfer TWI_CR = START | STOP Read Status register No RXRDY = 1? Yes Read Receive Holding register Read Status register No TXCOMP = 1? Yes END 550 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Figure 29-20. TWI Read Operation with Multiple Data Bytes with or without Internal Address BEGIN Set TWI clock (CLDIV, CHDIV, CKDIV) in TWI_CWGR (Needed only once) Set the Control register: - Master enable TWI_CR = MSEN + SVDIS Set the Master Mode register: - Device slave address - Internal address size (if IADR used) - Transfer direction bit Read ==> bit MREAD = 1 No Internal address size = 0? Set the internal address TWI_IADR = address Yes Start the transfer TWI_CR = START Read Status register RXRDY = 1? No Yes Read Receive Holding register (TWI_RHR) No Last data to read but one? Yes Stop the transfer TWI_CR = STOP Read Status register No RXRDY = 1? Yes Read Receive Holding register (TWI_RHR) Read status register TXCOMP = 1? No Yes END SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 551 29.9 Multi-master Mode 29.9.1 Definition More than one master may handle 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. When the stop is detected, the master who has lost arbitration may put its data on the bus by respecting arbitration. Arbitration is illustrated in Figure 29-22 on page 553. 29.9.2 Different Multi-master Modes Two multi-master modes may be distinguished: 1. TWI is considered as a Master only and will never be addressed. 2. TWI may be either a Master or a Slave and may be addressed. Note: In both Multi-master modes arbitration is supported. 29.9.2.1 TWI as Master Only In this mode, TWI is considered as a Master only (MSEN is always at one) and must be driven like a Master with the ARBLST (ARBitration Lost) flag in addition. If arbitration is lost (ARBLST = 1), the programmer must reinitiate the data transfer. If the user starts a transfer (ex.: DADR + START + W + Write in THR) and if the bus is busy, the TWI automatically waits for a STOP condition on the bus to initiate the transfer (see Figure 29-21 on page 553). Note: The state of the bus (busy or free) is not indicated in the user interface. 29.9.2.2 TWI as Master or Slave The automatic reversal from Master to Slave is not supported in case of a lost arbitration. Then, in the case where TWI may be either a Master or a Slave, the programmer must manage the pseudo Multimaster mode described in the steps below. 1. Program TWI in Slave mode (SADR + MSDIS + SVEN) and perform Slave Access (if TWI is addressed). 2. If TWI has to be set in Master mode, wait until TXCOMP flag is at 1. 3. Program Master mode (DADR + SVDIS + MSEN) and start the transfer (ex: START + Write in THR). 4. As soon as the Master mode is enabled, TWI scans the bus in order to detect if it is busy or free. When the bus is considered as free, TWI initiates the transfer. 5. As soon as the transfer is initiated and until a STOP condition is sent, the arbitration becomes relevant and the user must monitor the ARBLST flag. 6. If the arbitration is lost (ARBLST is set to 1), the user must program the TWI in Slave mode in the case where the Master that won the arbitration wanted to access the TWI. 7. If TWI has to be set in Slave mode, wait until TXCOMP flag is at 1 and then program the Slave mode. Note: 552 In the case where the arbitration is lost and TWI is addressed, TWI will not acknowledge even if it is programmed in Slave mode as soon as ARBLST is set to 1. Then, the Master must repeat SADR. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Figure 29-21. Programmer Sends Data While the Bus is Busy TWCK START sent by the TWI STOP sent by the master DATA sent by a master TWD DATA sent by the TWI Bus is busy Bus is free Transfer is kept TWI DATA transfer A transfer is programmed (DADR + W + START + Write THR) Bus is considered as free Transfer is initiated Figure 29-22. Arbitration Cases TWCK TWD TWCK Data from a Master S 1 0 0 1 1 Data from TWI S 1 0 1 TWD S 1 0 0 P Arbitration is lost TWI stops sending data 1 1 Data from the master P Arbitration is lost S 1 0 1 S 1 0 0 1 1 S 1 0 0 1 1 The master stops sending data Data from the TWI ARBLST Bus is busy Transfer is kept TWI DATA transfer A transfer is programmed (DADR + W + START + Write THR) Bus is free Transfer is stopped Transfer is programmed again (DADR + W + START + Write THR) Bus is considered as free Transfer is initiated The flowchart shown in Figure 29-23 on page 554 gives an example of read and write operations in Multi-master mode. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 553 Figure 29-23. Multi-master Flowchart START Programm the SLAVE mode: SADR + MSDIS + SVEN Read Status Register SVACC = 1 ? Yes GACC = 1 ? No No No No SVREAD = 1 ? EOSACC = 1 ? TXRDY= 1 ? Yes Yes Yes No Write in TWI_THR TXCOMP = 1 ? Yes No No RXRDY= 1 ? Yes Read TWI_RHR Need to perform a master access ? GENERAL CALL TREATMENT Yes Decoding of the programming sequence No Prog seq OK ? Change SADR Program the Master mode DADR + SVDIS + MSEN + CLK + R / W Read Status Register Yes No ARBLST = 1 ? Yes Yes No MREAD = 1 ? RXRDY= 0 ? TXRDY= 0 ? No No Read TWI_RHR Yes Data to read? Data to send ? No No Stop Transfer TWI_CR = STOP Read Status Register Yes 554 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Yes TXCOMP = 0 ? No Yes Write in TWI_THR No 29.10 Slave Mode 29.10.1 Definition The Slave Mode is defined as a mode where the device receives the clock and the address from another device called the master. In this mode, the device never initiates and never completes the transmission (START, REPEATED_START and STOP conditions are always provided by the master). 29.10.2 Application Block Diagram Figure 29-24. Slave Mode Typical Application Block Diagram VDD R Master Host with TWI Interface R TWD TWCK Host with TWI Interface Host with TWI Interface LCD Controller Slave 1 Slave 2 Slave 3 29.10.3 Programming Slave Mode The following fields must be programmed before entering Slave mode: 1. SADR (TWI_SMR): The slave device address is used in order to be accessed by master devices in read or write mode. 2. MSDIS (TWI_CR): Disable the master mode. 3. SVEN (TWI_CR): Enable the slave mode. As the device receives the clock, values written in TWI_CWGR are not taken into account. 29.10.4 Receiving Data After a Start or Repeated Start condition is detected and if the address sent by the Master matches with the Slave address programmed in the SADR (Slave ADdress) field, SVACC (Slave ACCess) flag is set and SVREAD (Slave READ) indicates the direction of the transfer. SVACC remains high until a STOP condition or a repeated START is detected. When such a condition is detected, EOSACC (End Of Slave ACCess) flag is set. 29.10.4.1Read Sequence In the case of a Read sequence (SVREAD is high), TWI transfers data written in the TWI_THR (TWI Transmit Holding Register) until a STOP condition or a REPEATED_START + an address different from SADR is detected. Note that at the end of the read sequence TXCOMP (Transmission Complete) flag is set and SVACC reset. As soon as data is written in the TWI_THR, TXRDY (Transmit Holding Register Ready) flag is reset, and it is set when the shift register is empty and the sent data acknowledged or not. If the data is not acknowledged, the NACK flag is set. Note that a STOP or a repeated START always follows a NACK. See Figure 29-25 on page 556. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 555 29.10.4.2Write Sequence In the case of a Write sequence (SVREAD is low), the RXRDY (Receive Holding Register Ready) flag is set as soon as a character has been received in the TWI_RHR (TWI Receive Holding Register). RXRDY is reset when reading the TWI_RHR. TWI continues receiving data until a STOP condition or a REPEATED_START + an address different from SADR is detected. Note that at the end of the write sequence TXCOMP flag is set and SVACC reset. See Figure 29-26 on page 557. 29.10.4.3Clock Synchronization Sequence In the case where TWI_THR or TWI_RHR is not written/read in time, TWI performs a clock synchronization. Clock stretching information is given by the SCLWS (Clock Wait state) bit. See Figure 29-28 on page 558 and Figure 29-29 on page 559. 29.10.4.4General Call In the case where a GENERAL CALL is performed, GACC (General Call ACCess) flag is set. After GACC is set, it is up to the programmer to interpret the meaning of the GENERAL CALL and to decode the new address programming sequence. See Figure 29-27 on page 557. 29.10.5 Data Transfer 29.10.5.1Read Operation The read mode is defined as a data requirement from the master. After a START or a REPEATED START condition is detected, the decoding of the address starts. If the slave address (SADR) is decoded, SVACC is set and SVREAD indicates the direction of the transfer. Until a STOP or REPEATED START condition is detected, TWI continues sending data loaded in the TWI_THR register. If a STOP condition or a REPEATED START + an address different from SADR is detected, SVACC is reset. Figure 29-25 on page 556 describes the write operation. Figure 29-25. Read Access Ordered by a MASTER SADR matches, TWI answers with an ACK SADR does not match, TWI answers with a NACK TWD S ADR R NA DATA NA P/S/Sr SADR R A DATA A ACK/NACK from the Master A DATA NA S/Sr TXRDY NACK Write THR Read RHR SVACC SVREAD SVREAD has to be taken into account only while SVACC is active EOSVACC Notes: 556 1. When SVACC is low, the state of SVREAD becomes irrelevant. 2. TXRDY is reset when data has been transmitted from TWI_THR to the shift register and set when this data has been acknowledged or non acknowledged. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 29.10.5.2Write Operation The write mode is defined as a data transmission from the master. After a START or a REPEATED START, the decoding of the address starts. If the slave address is decoded, SVACC is set and SVREAD indicates the direction of the transfer (SVREAD is low in this case). Until a STOP or REPEATED START condition is detected, TWI stores the received data in the TWI_RHR register. If a STOP condition or a REPEATED START + an address different from SADR is detected, SVACC is reset. Figure 29-26 on page 557 describes the Write operation. Figure 29-26. Write Access Ordered by a Master SADR does not match, TWI answers with a NACK S TWD ADR W NA DATA NA SADR matches, TWI answers with an ACK P/S/Sr SADR W A DATA Read RHR A A DATA NA S/Sr RXRDY SVACC SVREAD has to be taken into account only while SVACC is active SVREAD EOSVACC Notes: 1. When SVACC is low, the state of SVREAD becomes irrelevant. 2. RXRDY is set when data has been transmitted from the shift register to the TWI_RHR and reset when this data is read. 29.10.5.3General Call The general call is performed in order to change the address of the slave. If a GENERAL CALL is detected, GACC is set. After the detection of General Call, it is up to the programmer to decode the commands which come afterwards. In case of a WRITE command, the programmer has to decode the programming sequence and program a new SADR if the programming sequence matches. Figure 29-27 on page 557 describes the General Call access. Figure 29-27. Master Performs a General Call 0000000 + W TXD S GENERAL CALL RESET command = 00000110X WRITE command = 00000100X A Reset or write DADD A DATA1 A DATA2 A New SADR A P New SADR Programming sequence GCACC Reset after read SVACC Note: This method allows the user to create an own programming sequence by choosing the programming bytes and the number of them. The programming sequence has to be provided to the master. 29.10.5.4Clock Synchronization In both read and write modes, it may happen that TWI_THR/TWI_RHR buffer is not filled /emptied before the emission/reception of a new character. In this case, to avoid sending/receiving undesired data, a clock stretching mechanism is implemented. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 557 Clock Synchronization in Read Mode The clock is tied low if the shift register is empty and if a STOP or REPEATED START condition was not detected. It is tied low until the shift register is loaded. Figure 29-28 describes the clock synchronization in Read mode. Figure 29-28. Clock Synchronization in Read Mode TWI_THR S SADR R DATA1 1 DATA0 A DATA0 A DATA1 DATA2 A XXXXXXX DATA2 NA S 2 TWCK Write THR CLOCK is tied low by the TWI as long as THR is empty SCLWS TXRDY SVACC SVREAD As soon as a START is detected TXCOMP TWI_THR is transmitted to the shift register Notes: Ack or Nack from the master 1 The data is memorized in TWI_THR until a new value is written 2 The clock is stretched after the ACK, the state of TWD is undefined during clock stretching 1. TXRDY is reset when data has been written in the TWI_THR to the shift register and set when this data has been acknowledged or non acknowledged. 2. At the end of the read sequence, TXCOMP is set after a STOP or after a REPEATED_START + an address different from SADR. 3. SCLWS is automatically set when the clock synchronization mechanism is started. Clock Synchronization in Write Mode The clock is tied low if the shift register and the TWI_RHR is full. If a STOP or REPEATED_START condition was not detected, it is tied low until TWI_RHR is read. Figure 29-29 on page 559 describes the clock synchronization in Read mode. 558 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Figure 29-29. Clock Synchronization in Write Mode TWCK CLOCK is tied low by the TWI as long as RHR is full S TWD SADR W A DATA0 A DATA1 TWI_RHR A NA DATA2 DATA1 DATA0 is not read in the RHR S ADR DATA2 SCLWS SCL is stretched on the last bit of DATA1 RXRDY Rd DATA0 Rd DATA1 Rd DATA2 SVACC SVREAD As soon as a START is detected TXCOMP Notes: 1. At the end of the read sequence, TXCOMP is set after a STOP or after a REPEATED_START + an address different from SADR. 2. SCLWS is automatically set when the clock synchronization mechanism is started and automatically reset when the mechanism is finished. 29.10.5.5Reversal after a Repeated Start Reversal of Read to Write The master initiates the communication by a read command and finishes it by a write command. Figure 29-30 describes the repeated start + reversal from Read to Write mode. Figure 29-30. Repeated Start + Reversal from Read to Write Mode TWI_THR TWD DATA0 S SADR R A DATA0 DATA1 A DATA1 NA Sr SADR W A DATA2 TWI_RHR A DATA3 DATA2 A P DATA3 SVACC SVREAD TXRDY RXRDY EOSACC Cleared after read As soon as a START is detected TXCOMP Note: 1. TXCOMP is only set at the end of the transmission because after the repeated start, SADR is detected again. Reversal of Write to Read The master initiates the communication by a write command and finishes it by a read command. Figure 29-31 on page 560 describes the repeated start + reversal from Write to Read mode. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 559 Figure 29-31. Repeated Start + Reversal from Write to Read Mode DATA2 TWI_THR TWD S SADR W A DATA0 TWI_RHR A DATA1 DATA0 A Sr SADR R A DATA3 DATA2 A DATA3 NA P DATA1 SVACC SVREAD TXRDY RXRDY EOSACC TXCOMP Notes: Read TWI_RHR Cleared after read As soon as a START is detected 1. In this case, if TWI_THR has not been written at the end of the read command, the clock is automatically stretched before the ACK. 2. TXCOMP is only set at the end of the transmission because after the repeated start, SADR is detected again. 29.10.6 Read Write Flowcharts The flowchart shown in Figure 29-32 on page 561 gives an example of read and write operations in Slave mode. A polling or interrupt method can be used to check the status bits. The interrupt method requires that the interrupt enable register (TWI_IER) be configured first. 560 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Figure 29-32. Read Write Flowchart in Slave Mode Set the SLAVE mode: SADR + MSDIS + SVEN Read Status Register SVACC = 1 ? No No EOSACC = 1 ? GACC = 1 ? No SVREAD = 0 ? TXRDY= 1 ? No No Write in TWI_THR No TXCOMP = 1 ? RXRDY= 0 ? No END Read TWI_RHR GENERAL CALL TREATMENT Decoding of the programming sequence Prog seq OK ? No Change SADR SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 561 29.11 Two-wire Interface (TWI) User Interface Table 29-6. Register Mapping Offset Register Name Access Reset 0x00 Control Register TWI_CR Write-only N/A 0x04 Master Mode Register TWI_MMR Read-write 0x00000000 0x08 Slave Mode Register TWI_SMR Read-write 0x00000000 0x0C Internal Address Register TWI_IADR Read-write 0x00000000 0x10 Clock Waveform Generator Register TWI_CWGR Read-write 0x00000000 0x14 - 0x1C Reserved – – – 0x20 Status Register TWI_SR Read-only 0x0000F009 0x24 Interrupt Enable Register TWI_IER Write-only N/A 0x28 Interrupt Disable Register TWI_IDR Write-only N/A 0x2C Interrupt Mask Register TWI_IMR Read-only 0x00000000 0x30 Receive Holding Register TWI_RHR Read-only 0x00000000 0x34 Transmit Holding Register TWI_THR Write-only 0x00000000 0xEC - 0xFC(1) Reserved – – – 0x100 - 0x128 Reserved for PDC registers – – – Note: 562 1. All unlisted offset values are considered as “reserved”. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 29.11.1 TWI Control Register Name: TWI_CR Address: 0x40018000 (0), 0x4001C000 (1), 0x40040000 (2) Access: Write-only Reset: 0x00000000 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 SWRST 6 QUICK 5 SVDIS 4 SVEN 3 MSDIS 2 MSEN 1 STOP 0 START • START: Send a START Condition 0 = No effect. 1 = A frame beginning with a START bit is transmitted according to the features defined in the mode register. This action is necessary when the TWI peripheral wants to read data from a slave. When configured in Master Mode with a write operation, a frame is sent as soon as the user writes a character in the Transmit Holding Register (TWI_THR). • STOP: Send a STOP Condition 0 = No effect. 1 = STOP Condition is sent just after completing the current byte transmission in master read mode. – In single data byte master read, the START and STOP must both be set. – In multiple data bytes master read, the STOP must be set after the last data received but one. – In master read mode, if a NACK bit is received, the STOP is automatically performed. – In master data write operation, a STOP condition will be sent after the transmission of the current data is finished. • MSEN: TWI Master Mode Enabled 0 = No effect. 1 = If MSDIS = 0, the master mode is enabled. Note: Switching from Slave to Master mode is only permitted when TXCOMP = 1. • MSDIS: TWI Master Mode Disabled 0 = No effect. 1 = The master mode is disabled, all pending data is transmitted. The shifter and holding characters (if it contains data) are transmitted in case of write operation. In read operation, the character being transferred must be completely received before disabling. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 563 • SVEN: TWI Slave Mode Enabled 0 = No effect. 1 = If SVDIS = 0, the slave mode is enabled. Note: Switching from Master to Slave mode is only permitted when TXCOMP = 1. • SVDIS: TWI Slave Mode Disabled 0 = No effect. 1 = The slave mode is disabled. The shifter and holding characters (if it contains data) are transmitted in case of read operation. In write operation, the character being transferred must be completely received before disabling. • QUICK: SMBUS Quick Command 0 = No effect. 1 = If Master mode is enabled, a SMBUS Quick Command is sent. • SWRST: Software Reset 0 = No effect. 1 = Equivalent to a system reset. 564 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 29.11.2 TWI Master Mode Register Name: TWI_MMR Address: 0x40018004 (0), 0x4001C004 (1), 0x40040004 (2) Access: Read-write Reset: 0x00000000 31 – 30 – 29 – 28 – 27 – 26 – 25 – 24 – 23 – 22 21 20 19 DADR 18 17 16 15 – 14 – 13 – 12 MREAD 11 – 10 – 9 8 7 – 6 – 5 – 4 – 3 – 2 – 1 – IADRSZ 0 – • IADRSZ: Internal Device Address Size Value Name Description 0 NONE No internal device address 1 1_BYTE One-byte internal device address 2 2_BYTE Two-byte internal device address 3 3_BYTE Three-byte internal device address • MREAD: Master Read Direction 0 = Master write direction. 1 = Master read direction. • DADR: Device Address The device address is used to access slave devices in read or write mode. Those bits are only used in Master mode. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 565 29.11.3 TWI Slave Mode Register Name: TWI_SMR Address: 0x40018008 (0), 0x4001C008 (1), 0x40040008 (2) Access: Read-write Reset: 0x00000000 31 – 30 – 29 – 28 – 27 – 26 – 25 – 24 – 23 – 22 21 20 19 SADR 18 17 16 15 – 14 – 13 – 12 – 11 – 10 – 9 8 7 – 6 – 5 – 4 – 3 – 2 – 1 – 0 – • SADR: Slave Address The slave device address is used in Slave mode in order to be accessed by master devices in read or write mode. SADR must be programmed before enabling the Slave mode or after a general call. Writes at other times have no effect. 566 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 29.11.4 TWI Internal Address Register Name: TWI_IADR Address: 0x4001800C (0), 0x4001C00C (1), 0x4004000C (2) Access: Read-write Reset: 0x00000000 31 – 30 – 29 – 28 – 23 22 21 20 27 – 26 – 25 – 24 – 19 18 17 16 11 10 9 8 3 2 1 0 IADR 15 14 13 12 IADR 7 6 5 4 IADR • IADR: Internal Address 0, 1, 2 or 3 bytes depending on IADRSZ. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 567 29.11.5 TWI Clock Waveform Generator Register Name: TWI_CWGR Address: 0x40018010 (0), 0x4001C010 (1), 0x40040010 (2) Access: Read-write Reset: 0x00000000 31 – 30 – 29 – 28 – 27 – 26 – 25 – 24 – 23 – 22 – 21 – 20 – 19 – 18 17 CKDIV 16 15 14 13 12 11 10 9 8 3 2 1 0 CHDIV 7 6 5 4 CLDIV TWI_CWGR is only used in Master mode. • CLDIV: Clock Low Divider The SCL low period is defined as follows: T low = ( ( CLDIV × 2 CKDIV ) + 4 ) × T MCK • CHDIV: Clock High Divider The SCL high period is defined as follows: T high = ( ( CHDIV × 2 CKDIV ) + 4 ) × T MCK • CKDIV: Clock Divider The CKDIV is used to increase both SCL high and low periods. 568 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 29.11.6 TWI Status Register Name: TWI_SR Address: 0x40018020 (0), 0x4001C020 (1), 0x40040020 (2) Access: Read-only Reset: 0x0000F009 31 – 30 – 29 – 28 – 27 – 26 – 25 – 24 – 23 – 22 – 21 – 20 – 19 – 18 – 17 – 16 – 15 TXBUFE 14 RXBUFF 13 ENDTX 12 ENDRX 11 EOSACC 10 SCLWS 9 ARBLST 8 NACK 7 – 6 OVRE 5 GACC 4 SVACC 3 SVREAD 2 TXRDY 1 RXRDY 0 TXCOMP • TXCOMP: Transmission Completed (automatically set / reset) TXCOMP used in Master mode: 0 = During the length of the current frame. 1 = When both holding and shifter registers are empty and STOP condition has been sent. TXCOMP behavior in Master mode can be seen in Figure 29-8 on page 542 and in Figure 29-10 on page 543. TXCOMP used in Slave mode: 0 = As soon as a Start is detected. 1 = After a Stop or a Repeated Start + an address different from SADR is detected. TXCOMP behavior in Slave mode can be seen in Figure 29-28 on page 558, Figure 29-29 on page 559, Figure 29-30 on page 559 and Figure 29-31 on page 560. • RXRDY: Receive Holding Register Ready (automatically set / reset) 0 = No character has been received since the last TWI_RHR read operation. 1 = A byte has been received in the TWI_RHR since the last read. RXRDY behavior in Master mode can be seen in Figure 29-10 on page 543. RXRDY behavior in Slave mode can be seen in Figure 29-26 on page 557, Figure 29-29 on page 559, Figure 29-30 on page 559 and Figure 29-31 on page 560. • TXRDY: Transmit Holding Register Ready (automatically set / reset) TXRDY used in Master mode: 0 = The transmit holding register has not been transferred into shift register. Set to 0 when writing into TWI_THR register. 1 = As soon as a data byte is transferred from TWI_THR to internal shifter or if a NACK error is detected, TXRDY is set at the same time as TXCOMP and NACK. TXRDY is also set when MSEN is set (enable TWI). TXRDY behavior in Master mode can be seen in Figure 29.8.4 on page 540. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 569 TXRDY used in Slave mode: 0 = As soon as data is written in the TWI_THR, until this data has been transmitted and acknowledged (ACK or NACK). 1 = It indicates that the TWI_THR is empty and that data has been transmitted and acknowledged. If TXRDY is high and if a NACK has been detected, the transmission will be stopped. Thus when TRDY = NACK = 1, the programmer must not fill TWI_THR to avoid losing it. TXRDY behavior in Slave mode can be seen in Figure 29-25 on page 556, Figure 29-28 on page 558, Figure 29-30 on page 559 and Figure 29-31 on page 560. • SVREAD: Slave Read (automatically set / reset) This bit is only used in Slave mode. When SVACC is low (no Slave access has been detected) SVREAD is irrelevant. 0 = Indicates that a write access is performed by a Master. 1 = Indicates that a read access is performed by a Master. SVREAD behavior can be seen in Figure 29-25 on page 556, Figure 29-26 on page 557, Figure 29-30 on page 559 and Figure 29-31 on page 560. • SVACC: Slave Access (automatically set / reset) This bit is only used in Slave mode. 0 = TWI is not addressed. SVACC is automatically cleared after a NACK or a STOP condition is detected. 1 = Indicates that the address decoding sequence has matched (A Master has sent SADR). SVACC remains high until a NACK or a STOP condition is detected. SVACC behavior can be seen in Figure 29-25 on page 556, Figure 29-26 on page 557, Figure 29-30 on page 559 and Figure 29-31 on page 560. • GACC: General Call Access (clear on read) This bit is only used in Slave mode. 0 = No General Call has been detected. 1 = A General Call has been detected. After the detection of General Call, if need be, the programmer may acknowledge this access and decode the following bytes and respond according to the value of the bytes. GACC behavior can be seen in Figure 29-27 on page 557. • OVRE: Overrun Error (clear on read) This bit is only used in Master mode. 0 = TWI_RHR has not been loaded while RXRDY was set 1 = TWI_RHR has been loaded while RXRDY was set. Reset by read in TWI_SR when TXCOMP is set. • NACK: Not Acknowledged (clear on read) NACK used in Master mode: 0 = Each data byte has been correctly received by the far-end side TWI slave component. 1 = A data byte has not been acknowledged by the slave component. Set at the same time as TXCOMP. NACK used in Slave Read mode: 0 = Each data byte has been correctly received by the Master. 1 = In read mode, a data byte has not been acknowledged by the Master. When NACK is set the programmer must not fill TWI_THR even if TXRDY is set, because it means that the Master will stop the data transfer or re initiate it. Note that in Slave Write mode all data are acknowledged by the TWI. 570 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 • ARBLST: Arbitration Lost (clear on read) This bit is only used in Master mode. 0: Arbitration won. 1: Arbitration lost. Another master of the TWI bus has won the multi-master arbitration. TXCOMP is set at the same time. • SCLWS: Clock Wait State (automatically set / reset) This bit is only used in Slave mode. 0 = The clock is not stretched. 1 = The clock is stretched. TWI_THR / TWI_RHR buffer is not filled / emptied before the emission / reception of a new character. SCLWS behavior can be seen in Figure 29-28 on page 558 and Figure 29-29 on page 559. • EOSACC: End Of Slave Access (clear on read) This bit is only used in Slave mode. 0 = A slave access is being performing. 1 = The Slave Access is finished. End Of Slave Access is automatically set as soon as SVACC is reset. EOSACC behavior can be seen in Figure 29-30 on page 559 and Figure 29-31 on page 560 • ENDRX: End of RX buffer 0 = The Receive Counter Register has not reached 0 since the last write in TWI_RCR or TWI_RNCR. 1 = The Receive Counter Register has reached 0 since the last write in TWI_RCR or TWI_RNCR. • ENDTX: End of TX buffer 0 = The Transmit Counter Register has not reached 0 since the last write in TWI_TCR or TWI_TNCR. 1 = The Transmit Counter Register has reached 0 since the last write in TWI_TCR or TWI_TNCR. • RXBUFF: RX Buffer Full 0 = TWI_RCR or TWI_RNCR have a value other than 0. 1 = Both TWI_RCR and TWI_RNCR have a value of 0. • TXBUFE: TX Buffer Empty 0 = TWI_TCR or TWI_TNCR have a value other than 0. 1 = Both TWI_TCR and TWI_TNCR have a value of 0. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 571 29.11.7 TWI Interrupt Enable Register Name: TWI_IER Address: 0x40018024 (0), 0x4001C024 (1), 0x40040024 (2) Access: Write-only Reset: 0x00000000 31 – 30 – 29 – 28 – 27 – 26 – 25 – 24 – 23 – 22 – 21 – 20 – 19 – 18 – 17 – 16 – 15 TXBUFE 14 RXBUFF 13 ENDTX 12 ENDRX 11 EOSACC 10 SCL_WS 9 ARBLST 8 NACK 7 – 6 OVRE 5 GACC 4 SVACC 3 – 2 TXRDY 1 RXRDY 0 TXCOMP • TXCOMP: Transmission Completed Interrupt Enable • RXRDY: Receive Holding Register Ready Interrupt Enable • TXRDY: Transmit Holding Register Ready Interrupt Enable • SVACC: Slave Access Interrupt Enable • GACC: General Call Access Interrupt Enable • OVRE: Overrun Error Interrupt Enable • NACK: Not Acknowledge Interrupt Enable • ARBLST: Arbitration Lost Interrupt Enable • SCL_WS: Clock Wait State Interrupt Enable • EOSACC: End Of Slave Access Interrupt Enable • ENDRX: End of Receive Buffer Interrupt Enable • ENDTX: End of Transmit Buffer Interrupt Enable • RXBUFF: Receive Buffer Full Interrupt Enable • TXBUFE: Transmit Buffer Empty Interrupt Enable 0 = No effect. 1 = Enables the corresponding interrupt. 572 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 29.11.8 TWI Interrupt Disable Register Name: TWI_IDR Address: 0x40018028 (0), 0x4001C028 (1), 0x40040028 (2) Access: Write-only Reset: 0x00000000 31 – 30 – 29 – 28 – 27 – 26 – 25 – 24 – 23 – 22 – 21 – 20 – 19 – 18 – 17 – 16 – 15 TXBUFE 14 RXBUFF 13 ENDTX 12 ENDRX 11 EOSACC 10 SCL_WS 9 ARBLST 8 NACK 7 – 6 OVRE 5 GACC 4 SVACC 3 – 2 TXRDY 1 RXRDY 0 TXCOMP • TXCOMP: Transmission Completed Interrupt Disable • RXRDY: Receive Holding Register Ready Interrupt Disable • TXRDY: Transmit Holding Register Ready Interrupt Disable • SVACC: Slave Access Interrupt Disable • GACC: General Call Access Interrupt Disable • OVRE: Overrun Error Interrupt Disable • NACK: Not Acknowledge Interrupt Disable • ARBLST: Arbitration Lost Interrupt Disable • SCL_WS: Clock Wait State Interrupt Disable • EOSACC: End Of Slave Access Interrupt Disable • ENDRX: End of Receive Buffer Interrupt Disable • ENDTX: End of Transmit Buffer Interrupt Disable • RXBUFF: Receive Buffer Full Interrupt Disable • TXBUFE: Transmit Buffer Empty Interrupt Disable 0 = No effect. 1 = Disables the corresponding interrupt. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 573 29.11.9 TWI Interrupt Mask Register Name: TWI_IMR Address: 0x4001802C (0), 0x4001C02C (1), 0x4004002C (2) Access: Read-only Reset: 0x00000000 31 – 30 – 29 – 28 – 27 – 26 – 25 – 24 – 23 – 22 – 21 – 20 – 19 – 18 – 17 – 16 – 15 TXBUFE 14 RXBUFF 13 ENDTX 12 ENDRX 11 EOSACC 10 SCL_WS 9 ARBLST 8 NACK 7 – 6 OVRE 5 GACC 4 SVACC 3 – 2 TXRDY 1 RXRDY 0 TXCOMP • TXCOMP: Transmission Completed Interrupt Mask • RXRDY: Receive Holding Register Ready Interrupt Mask • TXRDY: Transmit Holding Register Ready Interrupt Mask • SVACC: Slave Access Interrupt Mask • GACC: General Call Access Interrupt Mask • OVRE: Overrun Error Interrupt Mask • NACK: Not Acknowledge Interrupt Mask • ARBLST: Arbitration Lost Interrupt Mask • SCL_WS: Clock Wait State Interrupt Mask • EOSACC: End Of Slave Access Interrupt Mask • ENDRX: End of Receive Buffer Interrupt Mask • ENDTX: End of Transmit Buffer Interrupt Mask • RXBUFF: Receive Buffer Full Interrupt Mask • TXBUFE: Transmit Buffer Empty Interrupt Mask 0 = The corresponding interrupt is disabled. 1 = The corresponding interrupt is enabled. 574 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 29.11.10TWI Receive Holding Register Name: TWI_RHR Address: 0x40018030 (0), 0x4001C030 (1), 0x40040030 (2) Access: Read-only Reset: 0x00000000 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 6 5 4 3 2 1 0 RXDATA • RXDATA: Master or Slave Receive Holding Data SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 575 29.11.11TWI Transmit Holding Register Name: TWI_THR Address: 0x40018034 (0), 0x4001C034 (1), 0x40040034 (2) Access: Read-write Reset: 0x00000000 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 6 5 4 3 2 1 0 TXDATA • TXDATA: Master or Slave Transmit Holding Data 576 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 30. Universal Asynchronous Receiver Transmitter (UART) 30.1 Description The Universal Asynchronous Receiver Transmitter features a two-pin UART that can be used for communication and trace purposes and offers an ideal medium for in-situ programming solutions. Moreover, the association with peripheral DMA controller (PDC) permits packet handling for these tasks with processor time reduced to a minimum. 30.2 Embedded Characteristics 30.3 Two-pin UART ̶ Independent Receiver and Transmitter with a Common Programmable Baud Rate Generator ̶ Even, Odd, Mark or Space Parity Generation ̶ Parity, Framing and Overrun Error Detection ̶ Automatic Echo, Local Loopback and Remote Loopback Channel Modes ̶ Interrupt Generation ̶ Support for Two PDC Channels with Connection to Receiver and Transmitter Block Diagram Figure 30-1. UART Functional Block Diagram Peripheral Bridge Peripheral DMA Controller APB UART UTXD Transmit Power Management Controller MCK Parallel Input/ Output Baud Rate Generator Receive URXD Interrupt Control Table 30-1. uart_irq UART Pin Description Pin Name Description Type URXD UART Receive Data Input UTXD UART Transmit Data Output SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 577 30.4 Product Dependencies 30.4.1 I/O Lines The UART pins are multiplexed with PIO lines. The programmer must first configure the corresponding PIO Controller to enable I/O line operations of the UART. Table 30-2. I/O Lines Instance Signal I/O Line Peripheral UART0 URXD0 PA9 A UART0 UTXD0 PA10 A UART1 URXD1 PB2 A UART1 UTXD1 PB3 A UART2 URXD2 PA16 A UART2 UTXD2 PA15 A UART3 URXD3 PB10 B UART3 UTXD3 PB11 B 30.4.2 Power Management The UART clock is controllable through the Power Management Controller. In this case, the programmer must first configure the PMC to enable the UART clock. Usually, the peripheral identifier used for this purpose is 1. 30.4.3 Interrupt Source The UART interrupt line is connected to one of the interrupt sources of the Interrupt Controller. Interrupt handling requires programming of the Interrupt Controller before configuring the UART. 578 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 30.5 UART Operations The UART operates in asynchronous mode only and supports only 8-bit character handling (with parity). It has no clock pin. The UART is made up of a receiver and a transmitter that operate independently, and a common baud rate generator. Receiver timeout and transmitter time guard are not implemented. However, all the implemented features are compatible with those of a standard USART. 30.5.1 Baud Rate Generator The baud rate generator provides the bit period clock named baud rate clock to both the receiver and the transmitter. The baud rate clock is the master clock divided by 16 times the value (CD) written in UART_BRGR (Baud Rate Generator Register). If UART_BRGR is set to 0, the baud rate clock is disabled and the UART remains inactive. The maximum allowable baud rate is Master Clock divided by 16. The minimum allowable baud rate is Master Clock divided by (16 x 65536). MCK Baud Rate = ---------------------16 × CD Figure 30-2. Baud Rate Generator CD CD MCK 16-bit Counter OUT >1 1 0 Divide by 16 Baud Rate Clock 0 Receiver Sampling Clock 30.5.2 Receiver 30.5.2.1 Receiver Reset, Enable and Disable After device reset, the UART receiver is disabled and must be enabled before being used. The receiver can be enabled by writing the control register UART_CR with the bit RXEN at 1. At this command, the receiver starts looking for a start bit. The programmer can disable the receiver by writing UART_CR with the bit RXDIS at 1. If the receiver is waiting for a start bit, it is immediately stopped. However, if the receiver has already detected a start bit and is receiving the data, it waits for the stop bit before actually stopping its operation. The programmer can also put the receiver in its reset state by writing UART_CR with the bit RSTRX at 1. In doing so, the receiver immediately stops its current operations and is disabled, whatever its current state. If RSTRX is applied when data is being processed, this data is lost. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 579 30.5.2.2 Start Detection and Data Sampling The UART only supports asynchronous operations, and this affects only its receiver. The UART receiver detects the start of a received character by sampling the URXD signal until it detects a valid start bit. A low level (space) on URXD is interpreted as a valid start bit if it is detected for more than 7 cycles of the sampling clock, which is 16 times the baud rate. Hence, a space that is longer than 7/16 of the bit period is detected as a valid start bit. A space which is 7/16 of a bit period or shorter is ignored and the receiver continues to wait for a valid start bit. When a valid start bit has been detected, the receiver samples the URXD at the theoretical midpoint of each bit. It is assumed that each bit lasts 16 cycles of the sampling clock (1-bit period) so the bit sampling point is eight cycles (0.5-bit period) after the start of the bit. The first sampling point is therefore 24 cycles (1.5-bit periods) after the falling edge of the start bit was detected. Each subsequent bit is sampled 16 cycles (1-bit period) after the previous one. Figure 30-3. Start Bit Detection Sampling Clock URXD True Start Detection D0 Baud Rate Clock Figure 30-4. Character Reception Example: 8-bit, parity enabled 1 stop 0.5 bit period 1 bit period URXD Sampling D0 D1 True Start Detection D2 D3 D4 D5 D6 Stop Bit D7 Parity Bit 30.5.2.3 Receiver Ready When a complete character is received, it is transferred to the UART_RHR and the RXRDY status bit in UART_SR (Status Register) is set. The bit RXRDY is automatically cleared when the receive holding register UART_RHR is read. Figure 30-5. URXD Receiver Ready S D0 D1 D2 D3 D4 D5 D6 D7 P S D0 D1 D2 RXRDY Read UART_RHR 580 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 D3 D4 D5 D6 D7 P 30.5.2.4 Receiver Overrun If UART_RHR has not been read by the software (or the Peripheral Data Controller or DMA Controller) since the last transfer, the RXRDY bit is still set and a new character is received, the OVRE status bit in UART_SR is set. OVRE is cleared when the software writes the control register UART_CR with the bit RSTSTA (Reset Status) at 1. Figure 30-6. Receiver Overrun S URXD D0 D1 D2 D3 D4 D5 D6 D7 P D0 S stop D1 D2 D3 D4 D5 D6 D7 P stop RXRDY OVRE RSTSTA 30.5.2.5 Parity Error Each time a character is received, the receiver calculates the parity of the received data bits, in accordance with the field PAR in UART_MR. It then compares the result with the received parity bit. If different, the parity error bit PARE in UART_SR is set at the same time the RXRDY is set. The parity bit is cleared when the control register UART_CR is written with the bit RSTSTA (Reset Status) at 1. If a new character is received before the reset status command is written, the PARE bit remains at 1. Figure 30-7. Parity Error S URXD D0 D1 D2 D3 D4 D5 D6 D7 P stop RXRDY PARE Wrong Parity Bit RSTSTA 30.5.2.6 Receiver Framing Error When a start bit is detected, it generates a character reception when all the data bits have been sampled. The stop bit is also sampled and when it is detected at 0, the FRAME (Framing Error) bit in UART_SR is set at the same time the RXRDY bit is set. The FRAME bit remains high until the control register UART_CR is written with the bit RSTSTA at 1. Figure 30-8. Receiver Framing Error URXD S D0 D1 D2 D3 D4 D5 D6 D7 P stop RXRDY FRAME Stop Bit Detected at 0 RSTSTA SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 581 30.5.3 Transmitter 30.5.3.1 Transmitter Reset, Enable and Disable After device reset, the UART transmitter is disabled and it must be enabled before being used. The transmitter is enabled by writing the control register UART_CR with the bit TXEN at 1. From this command, the transmitter waits for a character to be written in the Transmit Holding Register (UART_THR) before actually starting the transmission. The programmer can disable the transmitter by writing UART_CR with the bit TXDIS at 1. If the transmitter is not operating, it is immediately stopped. However, if a character is being processed into the Shift Register and/or a character has been written in the Transmit Holding Register, the characters are completed before the transmitter is actually stopped. The programmer can also put the transmitter in its reset state by writing the UART_CR with the bit RSTTX at 1. This immediately stops the transmitter, whether or not it is processing characters. 30.5.3.2 Transmit Format The UART transmitter drives the pin UTXD at the baud rate clock speed. The line is driven depending on the format defined in the Mode Register and the data stored in the Shift Register. One start bit at level 0, then the 8 data bits, from the lowest to the highest bit, one optional parity bit and one stop bit at 1 are consecutively shifted out as shown in the following figure. The field PARE in the mode register UART_MR defines whether or not a parity bit is shifted out. When a parity bit is enabled, it can be selected between an odd parity, an even parity, or a fixed space or mark bit. Figure 30-9. Character Transmission Example: Parity enabled Baud Rate Clock UTXD Start Bit D0 D1 D2 D3 D4 D5 D6 D7 Parity Bit Stop Bit 30.5.3.3 Transmitter Control When the transmitter is enabled, the bit TXRDY (Transmitter Ready) is set in the status register UART_SR. The transmission starts when the programmer writes in the Transmit Holding Register (UART_THR), and after the written character is transferred from UART_THR to the Shift Register. The TXRDY bit remains high until a second character is written in UART_THR. As soon as the first character is completed, the last character written in UART_THR is transferred into the shift register and TXRDY rises again, showing that the holding register is empty. When both the Shift Register and UART_THR are empty, i.e., all the characters written in UART_THR have been processed, the TXEMPTY bit rises after the last stop bit has been completed. 582 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Figure 30-10. Transmitter Control UART_THR Data 0 Data 1 Shift Register UTXD Data 0 S Data 0 Data 1 P stop S Data 1 P stop TXRDY TXEMPTY Write Data 0 in UART_THR Write Data 1 in UART_THR 30.5.4 Peripheral DMA Controller Both the receiver and the transmitter of the UART are connected to a Peripheral DMA Controller (PDC) channel. The peripheral data controller channels are programmed via registers that are mapped within the UART user interface from the offset 0x100. The status bits are reported in the UART status register (UART_SR) and can generate an interrupt. The RXRDY bit triggers the PDC channel data transfer of the receiver. This results in a read of the data in UART_RHR. The TXRDY bit triggers the PDC channel data transfer of the transmitter. This results in a write of data in UART_THR. 30.5.5 Test Modes The UART supports three test modes. These modes of operation are programmed by using the field CHMODE (Channel Mode) in the mode register (UART_MR). The Automatic Echo mode allows bit-by-bit retransmission. When a bit is received on the URXD line, it is sent to the UTXD line. The transmitter operates normally, but has no effect on the UTXD line. The Local Loopback mode allows the transmitted characters to be received. UTXD and URXD pins are not used and the output of the transmitter is internally connected to the input of the receiver. The URXD pin level has no effect and the UTXD line is held high, as in idle state. The Remote Loopback mode directly connects the URXD pin to the UTXD line. The transmitter and the receiver are disabled and have no effect. This mode allows a bit-by-bit retransmission. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 583 Figure 30-11. Test Modes Automatic Echo RXD Receiver Transmitter Disabled TXD Local Loopback Disabled Receiver RXD VDD Disabled Transmitter Remote Loopback TXD VDD Disabled RXD Receiver Disabled Transmitter 584 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 TXD 30.6 Universal Asynchronous Receiver Transmitter (UART) User Interface Table 30-3. Register Mapping Offset Register Name Access Reset 0x0000 Control Register UART_CR Write-only – 0x0004 Mode Register UART_MR Read-write 0x0 0x0008 Interrupt Enable Register UART_IER Write-only – 0x000C Interrupt Disable Register UART_IDR Write-only – 0x0010 Interrupt Mask Register UART_IMR Read-only 0x0 0x0014 Status Register UART_SR Read-only – 0x0018 Receive Holding Register UART_RHR Read-only 0x0 0x001C Transmit Holding Register UART_THR Write-only – 0x0020 Baud Rate Generator Register UART_BRGR Read-write 0x0 0x0024 - 0x003C Reserved – – – 0x004C - 0x00FC Reserved – – – 0x0100 - 0x0124 Reserved for PDC registers – – – SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 585 30.6.1 UART Control Register Name: UART_CR Address: 0x400E0600 (0), 0x400E0800 (1), 0x40044000 (2), 0x40048000 (3) Access: Write-only 31 30 29 28 27 26 25 24 – – – – – – – – 23 22 21 20 19 18 17 16 – – – – – – – – 15 14 13 12 11 10 9 8 – – – – – – – RSTSTA 7 6 5 4 3 2 1 0 TXDIS TXEN RXDIS RXEN RSTTX RSTRX – – • RSTRX: Reset Receiver 0 = No effect. 1 = The receiver logic is reset and disabled. If a character is being received, the reception is aborted. • RSTTX: Reset Transmitter 0 = No effect. 1 = The transmitter logic is reset and disabled. If a character is being transmitted, the transmission is aborted. • RXEN: Receiver Enable 0 = No effect. 1 = The receiver is enabled if RXDIS is 0. • RXDIS: Receiver Disable 0 = No effect. 1 = The receiver is disabled. If a character is being processed and RSTRX is not set, the character is completed before the receiver is stopped. • TXEN: Transmitter Enable 0 = No effect. 1 = The transmitter is enabled if TXDIS is 0. • TXDIS: Transmitter Disable 0 = No effect. 1 = The transmitter is disabled. If a character is being processed and a character has been written in the UART_THR and RSTTX is not set, both characters are completed before the transmitter is stopped. • RSTSTA: Reset Status Bits 0 = No effect. 1 = Resets the status bits PARE, FRAME and OVRE in the UART_SR. 586 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 30.6.2 UART Mode Register Name: UART_MR Address: 0x400E0604 (0), 0x400E0804 (1), 0x40044004 (2), 0x40048004 (3) Access: Read-write 31 30 29 28 27 26 25 24 – – – – – – – – 23 22 21 20 19 18 17 16 – – – – – – – – 15 14 13 12 11 10 9 8 – – CHMODE PAR – 7 6 5 4 3 2 1 0 – – – – – – – – • PAR: Parity Type Value Name Description 0 EVEN Even Parity 1 ODD Odd Parity 2 SPACE Space: parity forced to 0 3 MARK Mark: parity forced to 1 4 NO No Parity • CHMODE: Channel Mode Value Name Description 0 NORMAL Normal Mode 1 AUTOMATIC Automatic Echo 2 LOCAL_LOOPBACK Local Loopback 3 REMOTE_LOOPBACK Remote Loopback SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 587 30.6.3 UART Interrupt Enable Register Name: UART_IER Address: 0x400E0608 (0), 0x400E0808 (1), 0x40044008 (2), 0x40048008 (3) Access: Write-only 31 30 29 28 27 26 25 24 – – – – – – – – 23 22 21 20 19 18 17 16 – – – – – – – – 15 14 13 12 11 10 9 8 – – – RXBUFF TXBUFE – TXEMPTY – 7 6 5 4 3 2 1 0 PARE FRAME OVRE ENDTX ENDRX – TXRDY RXRDY • RXRDY: Enable RXRDY Interrupt • TXRDY: Enable TXRDY Interrupt • ENDRX: Enable End of Receive Transfer Interrupt • ENDTX: Enable End of Transmit Interrupt • OVRE: Enable Overrun Error Interrupt • FRAME: Enable Framing Error Interrupt • PARE: Enable Parity Error Interrupt • TXEMPTY: Enable TXEMPTY Interrupt • TXBUFE: Enable Buffer Empty Interrupt • RXBUFF: Enable Buffer Full Interrupt 0 = No effect. 1 = Enables the corresponding interrupt. 588 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 30.6.4 UART Interrupt Disable Register Name: UART_IDR Address: 0x400E060C (0), 0x400E080C (1), 0x4004400C (2), 0x4004800C (3) Access: Write-only 31 30 29 28 27 26 25 24 – – – – – – – – 23 22 21 20 19 18 17 16 – – – – – – – – 15 14 13 12 11 10 9 8 – – – RXBUFF TXBUFE – TXEMPTY – 7 6 5 4 3 2 1 0 PARE FRAME OVRE ENDTX ENDRX – TXRDY RXRDY • RXRDY: Disable RXRDY Interrupt • TXRDY: Disable TXRDY Interrupt • ENDRX: Disable End of Receive Transfer Interrupt • ENDTX: Disable End of Transmit Interrupt • OVRE: Disable Overrun Error Interrupt • FRAME: Disable Framing Error Interrupt • PARE: Disable Parity Error Interrupt • TXEMPTY: Disable TXEMPTY Interrupt • TXBUFE: Disable Buffer Empty Interrupt • RXBUFF: Disable Buffer Full Interrupt 0 = No effect. 1 = Disables the corresponding interrupt. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 589 30.6.5 UART Interrupt Mask Register Name: UART_IMR Address: 0x400E0610 (0), 0x400E0810 (1), 0x40044010 (2), 0x40048010 (3) Access: Read-only 31 30 29 28 27 26 25 24 – – – – – – – – 23 22 21 20 19 18 17 16 – – – – – – – – 15 14 13 12 11 10 9 8 – – – RXBUFF TXBUFE – TXEMPTY – 7 6 5 4 3 2 1 0 PARE FRAME OVRE ENDTX ENDRX – TXRDY RXRDY • RXRDY: Mask RXRDY Interrupt • TXRDY: Disable TXRDY Interrupt • ENDRX: Mask End of Receive Transfer Interrupt • ENDTX: Mask End of Transmit Interrupt • OVRE: Mask Overrun Error Interrupt • FRAME: Mask Framing Error Interrupt • PARE: Mask Parity Error Interrupt • TXEMPTY: Mask TXEMPTY Interrupt • TXBUFE: Mask TXBUFE Interrupt • RXBUFF: Mask RXBUFF Interrupt 0 = The corresponding interrupt is disabled. 1 = The corresponding interrupt is enabled. 590 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 30.6.6 UART Status Register Name: UART_SR Address: 0x400E0614 (0), 0x400E0814 (1), 0x40044014 (2), 0x40048014 (3) Access: Read-only 31 30 29 28 27 26 25 24 – – – – – – – – 23 22 21 20 19 18 17 16 – – – – – – – – 15 14 13 12 11 10 9 8 – – – RXBUFF TXBUFE – TXEMPTY – 7 6 5 4 3 2 1 0 PARE FRAME OVRE ENDTX ENDRX – TXRDY RXRDY • RXRDY: Receiver Ready 0 = No character has been received since the last read of the UART_RHR or the receiver is disabled. 1 = At least one complete character has been received, transferred to UART_RHR and not yet read. • TXRDY: Transmitter Ready 0 = A character has been written to UART_THR and not yet transferred to the Shift Register, or the transmitter is disabled. 1 = There is no character written to UART_THR not yet transferred to the Shift Register. • ENDRX: End of Receiver Transfer 0 = The End of Transfer signal from the receiver Peripheral Data Controller channel is inactive. 1 = The End of Transfer signal from the receiver Peripheral Data Controller channel is active. • ENDTX: End of Transmitter Transfer 0 = The End of Transfer signal from the transmitter Peripheral Data Controller channel is inactive. 1 = The End of Transfer signal from the transmitter Peripheral Data Controller channel is active. • 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. • FRAME: Framing Error 0 = No framing error has occurred since the last RSTSTA. 1 = At least one framing error has occurred since the last RSTSTA. • PARE: Parity Error 0 = No parity error has occurred since the last RSTSTA. 1 = At least one parity error has occurred since the last RSTSTA. • TXEMPTY: Transmitter Empty 0 = There are characters in UART_THR, or characters being processed by the transmitter, or the transmitter is disabled. 1 = There are no characters in UART_THR and there are no characters being processed by the transmitter. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 591 • TXBUFE: Transmission Buffer Empty 0 = The buffer empty signal from the transmitter PDC channel is inactive. 1 = The buffer empty signal from the transmitter PDC channel is active. • RXBUFF: Receive Buffer Full 0 = The buffer full signal from the receiver PDC channel is inactive. 1 = The buffer full signal from the receiver PDC channel is active. 592 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 30.6.7 UART Receiver Holding Register Name: UART_RHR Address: 0x400E0618 (0), 0x400E0818 (1), 0x40044018 (2), 0x40048018 (3) Access: Read-only 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 6 5 4 3 2 1 0 RXCHR • RXCHR: Received Character Last received character if RXRDY is set. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 593 30.6.8 UART Transmit Holding Register Name: UART_THR Address: 0x400E061C (0), 0x400E081C (1), 0x4004401C (2), 0x4004801C (3) Access: Write-only 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 6 5 4 3 2 1 0 TXCHR • TXCHR: Character to be Transmitted Next character to be transmitted after the current character if TXRDY is not set. 594 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 30.6.9 UART Baud Rate Generator Register Name: UART_BRGR Address: 0x400E0620 (0), 0x400E0820 (1), 0x40044020 (2), 0x40048020 (3) Access: Read-write 31 30 29 28 27 26 25 24 – – – – – – – – 23 22 21 20 19 18 17 16 – – – – – – – – 15 14 13 12 11 10 9 8 3 2 1 0 CD 7 6 5 4 CD • CD: Clock Divisor 0 = Baud Rate Clock is disabled 1 to 65,535 = MCK / (CD x 16) SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 595 31. Universal Synchronous Asynchronous Receiver Transmitter (USART) 31.1 Description The Universal Synchronous Asynchronous Receiver Transceiver (USART) provides one full duplex universal synchronous asynchronous serial link. Data frame format is widely programmable (data length, parity, number of stop bits) to support a maximum of standards. The receiver implements parity error, framing error and overrun error detection. The receiver time-out enables handling variable-length frames and the transmitter timeguard facilitates communications with slow remote devices. Multidrop communications are also supported through address bit handling in reception and transmission. The USART features three test modes: remote loopback, local loopback and automatic echo. The USART supports specific operating modes providing interfaces on RS485 and SPI buses, with ISO7816 T = 0 or T = 1 smart card slots and infrared transceivers. The hardware handshaking feature enables an out-of-band flow control by automatic management of the pins RTS and CTS. The USART supports the connection to the Peripheral DMA Controller, which enables data transfers to the transmitter and from the receiver. The PDC provides chained buffer management without any intervention of the processor. 31.2 Embedded Characteristics Programmable Baud Rate Generator 5- to 9-bit Full-duplex Synchronous or Asynchronous Serial Communications ̶ 1, 1.5 or 2 Stop Bits in Asynchronous Mode or 1 or 2 Stop Bits in Synchronous Mode ̶ Parity Generation and Error Detection ̶ Framing Error Detection, Overrun Error Detection ̶ MSB- or LSB-first ̶ Optional Break Generation and Detection ̶ By 8 or by 16 Over-sampling Receiver Frequency ̶ Optional Hardware Handshaking RTS-CTS ̶ Receiver Time-out and Transmitter Timeguard ̶ Optional Multidrop Mode with Address Generation and Detection RS485 with Driver Control Signal ISO7816, T = 0 or T = 1 Protocols for Interfacing with Smart Cards ̶ NACK Handling, Error Counter with Repetition and Iteration Limit IrDA Modulation and Demodulation ̶ Communication at up to 115.2 Kbps SPI Mode ̶ Master or Slave ̶ Serial Clock Programmable Phase and Polarity ̶ SPI Serial Clock (SCK) Frequency up to Internal Clock Frequency MCK/6 Test Modes ̶ Remote Loopback, Local Loopback, Automatic Echo Supports Connection of: ̶ 596 Two Peripheral DMA Controller Channels (PDC) Offers Buffer Transfer without Processor Intervention SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 31.3 Block Diagram Figure 31-1. USART Block Diagram (Peripheral) DMA Controller Channel Channel PIO Controller USART RXD Receiver RTS Interrupt Controller USART Interrupt TXD Transmitter CTS PMC MCK DIV Baud Rate Generator SCK MCK/DIV User Interface SLCK APB Table 31-1. SPI Operating Mode PIN USART SPI Slave SPI Master RXD RXD MOSI MISO TXD TXD MISO MOSI RTS RTS – CS CTS CTS CS – SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 597 31.4 Application Block Diagram Figure 31-2. Application Block Diagram IrLAP PPP Serial Driver Field Bus Driver EMV Driver IrDA Driver SPI Driver USART 31.5 RS232 Drivers RS485 Drivers Serial Port Differential Bus Smart Card Slot IrDA Transceivers SPI Bus I/O Lines Description Table 31-2. I/O Line Description Name Description Type SCK Serial Clock I/O Active Level Transmit Serial Data TXD or Master Out Slave In (MOSI) in SPI Master Mode I/O or Master In Slave Out (MISO) in SPI Slave Mode Receive Serial Data RXD or Master In Slave Out (MISO) in SPI Master Mode Input or Master Out Slave In (MOSI) in SPI Slave Mode CTS RTS 598 Clear to Send or Slave Select (NSS) in SPI Slave Mode Request to Send or Slave Select (NSS) in SPI Master Mode SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Input Low Output Low 31.6 Product Dependencies 31.6.1 I/O Lines The pins used for interfacing the USART may be multiplexed with the PIO lines. The programmer must first program the PIO controller to assign the desired USART pins to their peripheral function. If I/O lines of the USART are not used by the application, they can be used for other purposes by the PIO Controller. To prevent the TXD line from falling when the USART is disabled, the use of an internal pull up is mandatory. If the hardware handshaking feature is used, the internal pull up on TXD must also be enabled. Table 31-3. I/O Lines Instance Signal I/O Line Peripheral USART0 CTS0 PA8 A USART0 RTS0 PA7 A USART0 RXD0 PA5 A USART0 SCK0 PA2 B USART0 TXD0 PA6 A USART1 CTS1 PA25 A USART1 RTS1 PA24 A USART1 RXD1 PA21 A USART1 SCK1 PA23 A USART1 TXD1 PA22 A USART2 CTS2 PC17 A USART2 RTS2 PC16 A USART2 RXD2 PC9 A USART2 SCK2 PC14 A USART2 TXD2 PC10 A 31.6.2 Power Management The USART is not continuously clocked. The programmer must first enable the USART Clock in the Power Management Controller (PMC) before using the USART. However, if the application does not require USART operations, the USART clock can be stopped when not needed and be restarted later. In this case, the USART will resume its operations where it left off. Configuring the USART does not require the USART clock to be enabled. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 599 31.6.3 Interrupt The USART interrupt line is connected on one of the internal sources of the Interrupt Controller. Using the USART Table 31-4. Peripheral IDs Instance ID USART0 14 USART1 15 USART2 17 interrupt requires the Interrupt Controller to be programmed first. Note that it is not recommended to use the USART interrupt line in edge sensitive mode. 600 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 31.7 Functional Description The USART is capable of managing several types of serial synchronous or asynchronous communications. It supports the following communication modes: 5- to 9-bit full-duplex asynchronous serial communication ̶ MSB- or LSB-first ̶ 1, 1.5 or 2 stop bits ̶ Parity even, odd, marked, space or none ̶ By 8 or by 16 over-sampling receiver frequency ̶ Optional hardware handshaking ̶ Optional break management ̶ Optional multidrop serial communication High-speed 5- to 9-bit full-duplex synchronous serial communication ̶ MSB- or LSB-first ̶ 1 or 2 stop bits ̶ Parity even, odd, marked, space or none ̶ By 8 or by 16 over-sampling frequency ̶ Optional hardware handshaking ̶ Optional break management ̶ Optional multidrop serial communication RS485 with driver control signal ISO7816, T0 or T1 protocols for interfacing with smart cards ̶ NACK handling, error counter with repetition and iteration limit, inverted data. InfraRed IrDA Modulation and Demodulation SPI Mode ̶ Master or Slave ̶ Serial Clock Programmable Phase and Polarity ̶ SPI Serial Clock (SCK) Frequency up to Internal Clock Frequency MCK/6 Test modes ̶ Remote loopback, local loopback, automatic echo 31.7.1 Baud Rate Generator The Baud Rate Generator provides the bit period clock named the Baud Rate Clock to both the receiver and the transmitter. The Baud Rate Generator clock source can be selected by setting the USCLKS field in the Mode Register (US_MR) between: The Master Clock MCK A division of the Master Clock, the divider being product dependent, but generally set to 8 The external clock, available on the SCK pin The Baud Rate Generator is based upon a 16-bit divider, which is programmed with the CD field of the Baud Rate Generator Register (US_BRGR). If CD is programmed to 0, the Baud Rate Generator does not generate any clock. If CD is programmed to 1, the divider is bypassed and becomes inactive. If the external SCK clock is selected, the duration of the low and high levels of the signal provided on the SCK pin must be longer than a Master Clock (MCK) period. The frequency of the signal provided on SCK must be at least 3 times lower than MCK in USART mode, or 6 times lower in SPI mode. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 601 Figure 31-3. Baud Rate Generator USCLKS MCK MCK/DIV SCK Reserved CD CD SCK 0 1 2 16-bit Counter FIDI >1 3 1 0 0 0 SYNC OVER Sampling Divider 0 Baud Rate Clock 1 1 SYNC USCLKS = 3 Sampling Clock 31.7.1.1 Baud Rate in Asynchronous Mode If the USART is programmed to operate in asynchronous mode, the selected clock is first divided by CD, which is field programmed in the Baud Rate Generator Register (US_BRGR). The resulting clock is provided to the receiver as a sampling clock and then divided by 16 or 8, depending on the programming of the OVER bit in US_MR. If OVER is set to 1, the receiver sampling is 8 times higher than the baud rate clock. If OVER is cleared, the sampling is performed at 16 times the baud rate clock. The following formula performs the calculation of the Baud Rate. SelectedClock Baudrate = -------------------------------------------( 8 ( 2 – Over )CD ) This gives a maximum baud rate of MCK divided by 8, assuming that MCK is the highest possible clock and that OVER is programmed to 1. 602 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Baud Rate Calculation Example Table 31-5 shows calculations of CD to obtain a baud rate at 38400 bauds for different source clock frequencies. This table also shows the actual resulting baud rate and the error. Table 31-5. Baud Rate Example (OVER = 0) Source Clock Expected Baud Rate MHz Bit/s 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% Calculation Result CD Actual Baud Rate Error Bit/s The baud rate is calculated with the following formula: BaudRate = MCK ⁄ CD × 16 The baud rate error is calculated with the following formula. It is not recommended to work with an error higher than 5%. ExpectedBaudRate Error = 1 – --------------------------------------------------- ActualBaudRate SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 603 31.7.1.2 Fractional Baud Rate in Asynchronous Mode The Baud Rate generator previously defined is subject to the following limitation: the output frequency changes by only integer multiples of the reference frequency. An approach to this problem is to integrate a fractional N clock generator that has a high resolution. The generator architecture is modified to obtain Baud Rate changes by a fraction of the reference source clock. This fractional part is programmed with the FP field in the Baud Rate Generator Register (US_BRGR). If FP is not 0, the fractional part is activated. The resolution is one eighth of the clock divider. This feature is only available when using USART normal mode. The fractional Baud Rate is calculated using the following formula: SelectedClock Baudrate = --------------------------------------------------------------- 8 ( 2 – Over ) CD + FP ------- 8 The modified architecture is presented below: Figure 31-4. Fractional Baud Rate Generator FP USCLKS CD Modulus Control FP MCK MCK/DIV SCK Reserved CD SCK 0 1 2 16-bit Counter 3 Glitch-free Logic 1 0 FIDI >1 0 0 SYNC OVER Sampling Divider 0 Baud Rate Clock 1 1 SYNC USCLKS = 3 Sampling Clock 31.7.1.3 Baud Rate in Synchronous Mode or SPI Mode If the USART is programmed to operate in synchronous mode, the selected clock is simply divided by the field CD in US_BRGR. SelectedClock BaudRate = -------------------------------------CD In synchronous mode, if the external clock is selected (USCLKS = 3), the clock is provided directly by the signal on the USART SCK pin. No division is active. The value written in US_BRGR has no effect. The external clock frequency must be at least 3 times lower than the system clock. In synchronous mode master (USCLKS = 0 or 1, CLK0 set to 1), the receive part limits the SCK maximum frequency to MCK/3 in USART mode, or MCK/6 in SPI mode. When either the external clock SCK or the internal clock divided (MCK/DIV) is selected, the value programmed in CD must be even if the user has to ensure a 50:50 mark/space ratio on the SCK pin. If the internal clock MCK is selected, the Baud Rate Generator ensures a 50:50 duty cycle on the SCK pin, even if the value programmed in CD is odd. 604 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 31.7.1.4 Baud Rate in ISO 7816 Mode The ISO7816 specification defines the bit rate with the following formula: Di B = ------ × f Fi where: B is the bit rate Di is the bit-rate adjustment factor Fi is the clock frequency division factor f is the ISO7816 clock frequency (Hz) Di is a binary value encoded on a 4-bit field, named DI, as represented in Table 31-6. Table 31-6. Binary and Decimal Values for Di DI field 0001 0010 0011 0100 0101 0110 1000 1001 1 2 4 8 16 32 12 20 Di (decimal) Fi is a binary value encoded on a 4-bit field, named FI, as represented in Table 31-7. Table 31-7. Binary and Decimal Values for Fi FI field 0000 0001 0010 0011 0100 0101 0110 1001 1010 1011 1100 1101 Fi (decimal) 372 372 558 744 1116 1488 1860 512 768 1024 1536 2048 Table 31-8 shows the resulting Fi/Di Ratio, which is the ratio between the ISO7816 clock and the baud rate clock. Table 31-8. Possible Values for the Fi/Di Ratio Fi/Di 372 558 774 1116 1488 1806 512 768 1024 1536 2048 1 372 558 744 1116 1488 1860 512 768 1024 1536 2048 2 186 279 372 558 744 930 256 384 512 768 1024 4 93 139.5 186 279 372 465 128 192 256 384 512 8 46.5 69.75 93 139.5 186 232.5 64 96 128 192 256 16 23.25 34.87 46.5 69.75 93 116.2 32 48 64 96 128 32 11.62 17.43 23.25 34.87 46.5 58.13 16 24 32 48 64 12 31 46.5 62 93 124 155 42.66 64 85.33 128 170.6 20 18.6 27.9 37.2 55.8 74.4 93 25.6 38.4 51.2 76.8 102.4 If the USART is configured in ISO7816 Mode, the clock selected by the USCLKS field in the Mode Register (US_MR) is first divided by the value programmed in the field CD in the Baud Rate Generator Register (US_BRGR). The resulting clock can be provided to the SCK pin to feed the smart card clock inputs. This means that the CLKO bit can be set in US_MR. This clock is then divided by the value programmed in the FI_DI_RATIO field in the FI_DI_Ratio register (US_FIDI). This is performed by the Sampling Divider, which performs a division by up to 2047 in ISO7816 Mode. The non-integer values of the Fi/Di Ratio are not supported and the user must program the FI_DI_RATIO field to a value as close as possible to the expected value. The FI_DI_RATIO field resets to the value 0x174 (372 in decimal) and is the most common divider between the ISO7816 clock and the bit rate (Fi = 372, Di = 1). Figure 31-5 shows the relation between the Elementary Time Unit, corresponding to a bit time, and the ISO 7816 clock. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 605 Figure 31-5. Elementary Time Unit (ETU) FI_DI_RATIO ISO7816 Clock Cycles ISO7816 Clock on SCK ISO7816 I/O Line on TXD 1 ETU 31.7.2 Receiver and Transmitter Control After reset, the receiver is disabled. The user must enable the receiver by setting the RXEN bit in the Control Register (US_CR). However, the receiver registers can be programmed before the receiver clock is enabled. After reset, the transmitter is disabled. The user must enable it by setting the TXEN bit in the Control Register (US_CR). However, the transmitter registers can be programmed before being enabled. The Receiver and the Transmitter can be enabled together or independently. At any time, the software can perform a reset on the receiver or the transmitter of the USART by setting the corresponding bit, RSTRX and RSTTX respectively, in the Control Register (US_CR). The software resets clear the status flag and reset internal state machines but the user interface configuration registers hold the value configured prior to software reset. Regardless of what the receiver or the transmitter is performing, the communication is immediately stopped. The user can also independently disable the receiver or the transmitter by setting RXDIS and TXDIS respectively in US_CR. If the receiver is disabled during a character reception, the USART waits until the end of reception of the current character, then the reception is stopped. If the transmitter is disabled while it is operating, the USART waits the end of transmission of both the current character and character being stored in the Transmit Holding Register (US_THR). If a timeguard is programmed, it is handled normally. 31.7.3 Synchronous and Asynchronous Modes 31.7.3.1 Transmitter Operations The transmitter performs the same in both synchronous and asynchronous operating modes (SYNC = 0 or SYNC = 1). One start bit, up to 9 data bits, one optional parity bit and up to two stop bits are successively shifted out on the TXD pin at each falling edge of the programmed serial clock. The number of data bits is selected by the CHRL field and the MODE 9 bit in the Mode Register (US_MR). Nine bits are selected by setting the MODE 9 bit regardless of the CHRL field. The parity bit is set according to the PAR field in US_MR. The even, odd, space, marked or none parity bit can be configured. The MSBF field in US_MR configures which data bit is sent first. If written to 1, the most significant bit is sent first. If written to 0, the less significant bit is sent first. The number of stop bits is selected by the NBSTOP field in US_MR. The 1.5 stop bit is supported in asynchronous mode only. 606 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Figure 31-6. Character Transmit Example: 8-bit, Parity Enabled One Stop Baud Rate Clock TXD D0 Start Bit D1 D2 D3 D4 D5 D6 D7 Parity Bit Stop Bit The characters are sent by writing in the Transmit Holding Register (US_THR). The transmitter reports two status bits in the Channel Status Register (US_CSR): TXRDY (Transmitter Ready), which indicates that US_THR is empty and TXEMPTY, which indicates that all the characters written in US_THR have been processed. When the current character processing is completed, the last character written in US_THR is transferred into the Shift Register of the transmitter and US_THR becomes empty, thus TXRDY rises. Both TXRDY and TXEMPTY bits are low when the transmitter is disabled. Writing a character in US_THR while TXRDY is low has no effect and the written character is lost. Figure 31-7. Transmitter Status Baud Rate Clock TXD Start D0 Bit D1 D2 D3 D4 D5 D6 D7 Parity Stop Start D0 Bit Bit Bit D1 D2 D3 D4 D5 D6 D7 Parity Stop Bit Bit Write US_THR TXRDY TXEMPTY 31.7.3.2 Asynchronous Receiver If the USART is programmed in asynchronous operating mode (SYNC = 0), the receiver oversamples the RXD input line. The oversampling is either 16 or 8 times the Baud Rate clock, depending on the OVER bit in the Mode Register (US_MR). The receiver samples the RXD line. If the line is sampled during one half of a bit time to 0, a start bit is detected and data, parity and stop bits are successively sampled on the bit rate clock. If the oversampling is 16, (OVER to 0), a start is detected at the eighth sample to 0. Then, data bits, parity bit and stop bit are sampled on each 16 sampling clock cycle. If the oversampling is 8 (OVER to 1), a start bit is detected at the fourth sample to 0. Then, data bits, parity bit and stop bit are sampled on each 8 sampling clock cycle. The number of data bits, first bit sent and parity mode are selected by the same fields and bits as the transmitter, i.e. respectively CHRL, MODE9, MSBF and PAR. For the synchronization mechanism only, the number of stop bits has no effect on the receiver as it considers only one stop bit, regardless of the field NBSTOP, so that resynchronization between the receiver and the transmitter can occur. Moreover, as soon as the stop bit is sampled, the receiver starts looking for a new start bit so that resynchronization can also be accomplished when the transmitter is operating with one stop bit. Figure 31-8 and Figure 31-9 illustrate start detection and character reception when USART operates in asynchronous mode. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 607 Figure 31-8. Asynchronous Start Detection Baud Rate Clock Sampling Clock (x16) RXD Sampling 1 2 3 4 5 6 7 8 1 2 3 4 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 D0 Sampling Start Detection RXD Sampling 1 Figure 31-9. 2 3 4 5 6 7 0 1 Start Rejection Asynchronous Character Reception Example: 8-bit, Parity Enabled Baud Rate Clock RXD Start Detection 16 16 16 16 16 16 16 16 16 16 samples samples samples samples samples samples samples samples samples samples D0 D1 D2 D3 D4 D5 D6 D7 Parity Bit Stop Bit 31.7.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. All data bits, the parity bit and the stop bits are sampled and the receiver waits for the next start bit. Synchronous mode operations provide a high speed transfer capability. Configuration fields and bits are the same as in asynchronous mode. Figure 31-10 illustrates a character reception in synchronous mode. Figure 31-10. Synchronous Mode Character Reception Example: 8-bit, Parity Enabled 1 Stop Baud Rate Clock RXD Sampling Start D0 D1 D2 D3 D4 D5 D6 D7 Stop Bit Parity Bit 608 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 31.7.3.4 Receiver Operations When a character reception is completed, it is transferred to the Receive Holding Register (US_RHR) and the RXRDY bit in the Status Register (US_CSR) rises. If a character is completed while the RXRDY is set, the OVRE (Overrun Error) bit is set. The last character is transferred into US_RHR and overwrites the previous one. The OVRE bit is cleared by writing the Control Register (US_CR) with the RSTSTA (Reset Status) bit to 1. Figure 31-11. Receiver Status Baud Rate Clock RXD Start D0 Bit D1 D2 D3 D4 D5 D6 D7 Parity Stop Start D0 Bit Bit Bit D1 D2 D3 D4 D5 D6 D7 Parity Stop Bit Bit RSTSTA = 1 Write US_CR Read US_RHR RXRDY OVRE 31.7.3.5 Parity The USART supports five parity modes selected by programming the PAR field in the Mode Register (US_MR). The PAR field also enables the Multidrop mode, see “Multidrop Mode” on page 610. Even and odd parity bit generation and error detection are supported. If even parity is selected, the parity generator of the transmitter drives the parity bit to 0 if a number of 1s in the character data bit is even, and to 1 if the number of 1s is odd. Accordingly, the receiver parity checker counts the number of received 1s and reports a parity error if the sampled parity bit does not correspond. If odd parity is selected, the parity generator of the transmitter drives the parity bit to 1 if a number of 1s in the character data bit is even, and to 0 if the number of 1s is odd. Accordingly, the receiver parity checker counts the number of received 1s and reports a parity error if the sampled parity bit does not correspond. If the mark parity is used, the parity generator of the transmitter drives the parity bit to 1 for all characters. The receiver parity checker reports an error if the parity bit is sampled to 0. If the space parity is used, the parity generator of the transmitter drives the parity bit to 0 for all characters. The receiver parity checker reports an error if the parity bit is sampled to 1. If parity is disabled, the transmitter does not generate any parity bit and the receiver does not report any parity error. Table 31-9 shows an example of the parity bit for the character 0x41 (character ASCII “A”) depending on the configuration of the USART. Because there are two bits to 1, 1 bit is added when a parity is odd, or 0 is added when a parity is even. Table 31-9. Parity Bit Examples Character Hexa Binary Parity Bit Parity Mode A 0x41 0100 0001 1 Odd A 0x41 0100 0001 0 Even A 0x41 0100 0001 1 Mark A 0x41 0100 0001 0 Space A 0x41 0100 0001 None None SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 609 When the receiver detects a parity error, it sets the PARE (Parity Error) bit in the Channel Status Register (US_CSR). The PARE bit can be cleared by writing the Control Register (US_CR) with the RSTSTA bit to 1. Figure 31-12 illustrates the parity bit status setting and clearing. Figure 31-12. Parity Error Baud Rate Clock RXD Start D0 Bit D1 D2 D3 D4 D5 D6 D7 Bad Stop Parity Bit Bit RSTSTA = 1 Write US_CR PARE Parity Error Detect Time Flags Report Time RXRDY 31.7.3.6 Multidrop Mode If the PAR field in the Mode Register (US_MR) is programmed to the value 0x6 or 0x07, the USART runs in Multidrop Mode. This mode differentiates the data characters and the address characters. Data is transmitted with the parity bit to 0 and addresses are transmitted with the parity bit to 1. If the USART is configured in multidrop mode, the receiver sets the PARE parity error bit when the parity bit is high and the transmitter is able to send a character with the parity bit high when the Control Register is written with the SENDA bit to 1. To handle parity error, the PARE bit is cleared when the Control Register is written with the bit RSTSTA to 1. The transmitter sends an address byte (parity bit set) when SENDA is written to US_CR. In this case, the next byte written to US_THR is transmitted as an address. Any character written in US_THR without having written the command SENDA is transmitted normally with the parity to 0. 31.7.3.7 Transmitter Timeguard The timeguard feature enables the USART interface with slow remote devices. The timeguard function enables the transmitter to insert an idle state on the TXD line between two characters. This idle state actually acts as a long stop bit. The duration of the idle state is programmed in the TG field of the Transmitter Timeguard Register (US_TTGR). When this field is programmed to zero no timeguard is generated. Otherwise, the transmitter holds a high level on TXD after each transmitted byte during the number of bit periods programmed in TG in addition to the number of stop bits. As illustrated in Figure 31-13, the behavior of TXRDY and TXEMPTY status bits is modified by the programming of a timeguard. TXRDY rises only when the start bit of the next character is sent, and thus remains to 0 during the timeguard transmission if a character has been written in US_THR. TXEMPTY remains low until the timeguard transmission is completed as the timeguard is part of the current character being transmitted. 610 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Figure 31-13. Timeguard Operations TG = 4 TG = 4 Baud Rate Clock TXD Start D0 Bit D1 D2 D3 D4 D5 D6 D7 Parity Stop Bit Bit Start D0 Bit D1 D2 D3 D4 D5 D6 D7 Parity Stop Bit Bit Write US_THR TXRDY TXEMPTY Table 31-10 indicates the maximum length of a timeguard period that the transmitter can handle in relation to the function of the Baud Rate. Table 31-10. Maximum Timeguard Length Depending on Baud Rate Baud Rate Bit time Timeguard Bit/sec µs 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 38400 26 6.63 56000 17.9 4.55 57600 17.4 4.43 115200 8.7 2.21 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 611 31.7.3.8 Receiver Time-out The Receiver Time-out provides support in handling variable-length frames. This feature detects an idle condition on the RXD line. When a time-out is detected, the bit TIMEOUT in the Channel Status Register (US_CSR) rises and can generate an interrupt, thus indicating to the driver an end of frame. The time-out delay period (during which the receiver waits for a new character) is programmed in the TO field of the Receiver Time-out Register (US_RTOR). If the TO field is programmed to 0, the Receiver Time-out is disabled and no time-out is detected. The TIMEOUT bit in US_CSR remains to 0. Otherwise, the receiver loads a 16-bit counter with the value programmed in TO. This counter is decremented at each bit period and reloaded each time a new character is received. If the counter reaches 0, the TIMEOUT bit in the Status Register rises. Then, the user can either: Stop the counter clock until a new character is received. This is performed by writing the Control Register (US_CR) with the STTTO (Start Time-out) bit to 1. In this case, the idle state on RXD before a new character is received will not provide a time-out. This prevents having to handle an interrupt before a character is received and allows waiting for the next idle state on RXD after a frame is received. Obtain an interrupt while no character is received. This is performed by writing US_CR with the RETTO (Reload and Start Time-out) bit to 1. If RETTO is performed, the counter starts counting down immediately from the value TO. This enables generation of a periodic interrupt so that a user time-out can be handled, for example when no key is pressed on a keyboard. If STTTO is performed, the counter clock is stopped until a first character is received. The idle state on RXD before the start of the frame does not provide a time-out. This prevents having to obtain a periodic interrupt and enables a wait of the end of frame when the idle state on RXD is detected. If RETTO is performed, the counter starts counting down immediately from the value TO. This enables generation of a periodic interrupt so that a user time-out can be handled, for example when no key is pressed on a keyboard. Figure 31-14 shows the block diagram of the Receiver Time-out feature. Figure 31-14. Receiver Time-out Block Diagram TO Baud Rate Clock 1 D Q Clock 16-bit Time-out Counter 16-bit Value = STTTO Character Received Clear RETTO 612 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Load 0 TIMEOUT Table 31-11 gives the maximum time-out period for some standard baud rates. Table 31-11. Maximum Time-out Period Baud Rate Bit Time Time-out bit/sec µs ms 600 1 667 109 225 1 200 833 54 613 2 400 417 27 306 4 800 208 13 653 9 600 104 6 827 14400 69 4 551 19200 52 3 413 28800 35 2 276 38400 26 1 704 56000 18 1 170 57600 17 1 138 200000 5 328 31.7.3.9 Framing Error The receiver is capable of detecting framing errors. A framing error happens when the stop bit of a received character is detected at level 0. This can occur if the receiver and the transmitter are fully desynchronized. A framing error is reported on the FRAME bit of the Channel Status Register (US_CSR). The FRAME bit is asserted in the middle of the stop bit as soon as the framing error is detected. It is cleared by writing the Control Register (US_CR) with the RSTSTA bit to 1. Figure 31-15. Framing Error Status Baud Rate Clock RXD Start D0 Bit D1 D2 D3 D4 D5 D6 D7 Parity Stop Bit Bit RSTSTA = 1 Write US_CR FRAME RXRDY 31.7.3.10Transmit Break The user can request the transmitter to generate a break condition on the TXD line. A break condition drives the TXD line low during at least one complete character. It appears the same as a 0x00 character sent with the parity and the stop bits to 0. However, the transmitter holds the TXD line at least during one character until the user requests the break condition to be removed. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 613 A break is transmitted by writing the Control Register (US_CR) with the STTBRK bit to 1. This can be performed at any time, either while the transmitter is empty (no character in either the Shift Register or in US_THR) or when a character is being transmitted. If a break is requested while a character is being shifted out, the character is first completed before the TXD line is held low. Once STTBRK command is requested further STTBRK commands are ignored until the end of the break is completed. The break condition is removed by writing US_CR with the STPBRK bit to 1. If the STPBRK is requested before the end of the minimum break duration (one character, including start, data, parity and stop bits), the transmitter ensures that the break condition completes. The transmitter considers the break as though it is a character, i.e. the STTBRK and STPBRK commands are taken into account only if the TXRDY bit in US_CSR is to 1 and the start of the break condition clears the TXRDY and TXEMPTY bits as if a character is processed. Writing US_CR with both STTBRK and STPBRK bits to 1 can lead to an unpredictable result. All STPBRK commands requested without a previous STTBRK command are ignored. A byte written into the Transmit Holding Register while a break is pending, but not started, is ignored. After the break condition, the transmitter returns the TXD line to 1 for a minimum of 12 bit times. Thus, the transmitter ensures that the remote receiver detects correctly the end of break and the start of the next character. If the timeguard is programmed with a value higher than 12, the TXD line is held high for the timeguard period. After holding the TXD line for this period, the transmitter resumes normal operations. Figure 31-16 illustrates the effect of both the Start Break (STTBRK) and Stop Break (STPBRK) commands on the TXD line. Figure 31-16. Break Transmission Baud Rate Clock TXD Start D0 Bit D1 D2 D3 D4 D5 D6 D7 Parity Stop Bit Bit STTBRK = 1 Break Transmission End of Break STPBRK = 1 Write US_CR TXRDY TXEMPTY 31.7.3.11Receive Break The receiver detects a break condition when all data, parity and stop bits are low. This corresponds to detecting a framing error with data to 0x00, but FRAME remains low. When the low stop bit is detected, the receiver asserts the RXBRK bit in US_CSR. This bit may be cleared by writing the Control Register (US_CR) with the bit RSTSTA to 1. An end of receive break is detected by a high level for at least 2/16 of a bit period in asynchronous operating mode or one sample at high level in synchronous operating mode. The end of break detection also asserts the RXBRK bit. 614 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 31.7.3.12Hardware Handshaking The USART features a hardware handshaking out-of-band flow control. The RTS and CTS pins are used to connect with the remote device, as shown in Figure 31-17. Figure 31-17. Connection with a Remote Device for Hardware Handshaking USART Remote Device TXD RXD RXD TXD CTS RTS RTS CTS Setting the USART to operate with hardware handshaking is performed by writing the USART_MODE field in the Mode Register (US_MR) to the value 0x2. The USART behavior when hardware handshaking is enabled is the same as the behavior in standard synchronous or asynchronous mode, except that the receiver drives the RTS pin as described below and the level on the CTS pin modifies the behavior of the transmitter as described below. Using this mode requires using the PDC channel for reception. The transmitter can handle hardware handshaking in any case. Figure 31-18 shows how the receiver operates if hardware handshaking is enabled. The RTS pin is driven high if the receiver is disabled and if the status RXBUFF (Receive Buffer Full) coming from the PDC channel is high. Normally, the remote device does not start transmitting while its CTS pin (driven by RTS) is high. As soon as the Receiver is enabled, the RTS falls, indicating to the remote device that it can start transmitting. Defining a new buffer to the PDC clears the status bit RXBUFF and, as a result, asserts the pin RTS low. Figure 31-18. Receiver Behavior when Operating with Hardware Handshaking RXD RXEN = 1 RXDIS = 1 Write US_CR RTS RXBUFF Figure 31-19 shows how the transmitter operates if hardware handshaking is enabled. The CTS pin disables the transmitter. If a character is being processing, the transmitter is disabled only after the completion of the current character and transmission of the next character happens as soon as the pin CTS falls. Figure 31-19. Transmitter Behavior when Operating with Hardware Handshaking CTS TXD SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 615 31.7.4 ISO7816 Mode The USART features an ISO7816-compatible operating mode. This mode permits interfacing with smart cards and Security Access Modules (SAM) communicating through an ISO7816 link. Both T = 0 and T = 1 protocols defined by the ISO7816 specification are supported. Setting the USART in ISO7816 mode is performed by writing the USART_MODE field in the Mode Register (US_MR) to the value 0x4 for protocol T = 0 and to the value 0x5 for protocol T = 1. 31.7.4.1 ISO7816 Mode Overview The ISO7816 is a half duplex communication on only one bidirectional line. The baud rate is determined by a division of the clock provided to the remote device (see “Baud Rate Generator” on page 602). The USART connects to a smart card as shown in Figure 31-20. The TXD line becomes bidirectional and the Baud Rate Generator feeds the ISO7816 clock on the SCK pin. As the TXD pin becomes bidirectional, its output remains driven by the output of the transmitter but only when the transmitter is active while its input is directed to the input of the receiver. The USART is considered as the master of the communication as it generates the clock. Figure 31-20. Connection of a Smart Card to the USART USART SCK TXD CLK I/O Smart Card When operating in ISO7816, either in T = 0 or T = 1 modes, the character format is fixed. The configuration is 8 data bits, even parity and 1 or 2 stop bits, regardless of the values programmed in the CHRL, MODE9, PAR and CHMODE fields. MSBF can be used to transmit LSB or MSB first. Parity Bit (PAR) can be used to transmit in normal or inverse mode. Refer to “USART Mode Register” on page 633 and “PAR: Parity Type” on page 634. The USART cannot operate concurrently in both receiver and transmitter modes as the communication is unidirectional at a time. It has to be configured according to the required mode by enabling or disabling either the receiver or the transmitter as desired. Enabling both the receiver and the transmitter at the same time in ISO7816 mode may lead to unpredictable results. The ISO7816 specification defines an inverse transmission format. Data bits of the character must be transmitted on the I/O line at their negative value. 31.7.4.2 Protocol T = 0 In T = 0 protocol, a character is made up of one start bit, eight data bits, one parity bit and one guard time, which lasts two bit times. The transmitter shifts out the bits and does not drive the I/O line during the guard time. If no parity error is detected, the I/O line remains to 1 during the guard time and the transmitter can continue with the transmission of the next character, as shown in Figure 31-21. If a parity error is detected by the receiver, it drives the I/O line to 0 during the guard time, as shown in Figure 3122. This error bit is also named NACK, for Non Acknowledge. In this case, the character lasts 1 bit time more, as the guard time length is the same and is added to the error bit time which lasts 1 bit time. When the USART is the receiver and it detects an error, it does not load the erroneous character in the Receive Holding Register (US_RHR). It appropriately sets the PARE bit in the Status Register (US_SR) so that the software can handle the error. 616 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Figure 31-21. T = 0 Protocol without Parity Error Baud Rate Clock RXD Start Bit D0 D2 D1 D4 D3 D5 D6 D7 Parity Guard Guard Next Bit Time 1 Time 2 Start Bit Figure 31-22. T = 0 Protocol with Parity Error Baud Rate Clock Error I/O Start Bit D0 D1 D2 D3 D4 D5 D6 D7 Parity Guard Bit Time 1 D0 Guard Start Time 2 Bit D1 Repetition Receive Error Counter The USART receiver also records the total number of errors. This can be read in the Number of Error (US_NER) register. The NB_ERRORS field can record up to 255 errors. Reading US_NER automatically clears the NB_ERRORS field. Receive NACK Inhibit The USART can also be configured to inhibit an error. This can be achieved by setting the INACK bit in the Mode Register (US_MR). If INACK is to 1, no error signal is driven on the I/O line even if a parity bit is detected. Moreover, if INACK is set, the erroneous received character is stored in the Receive Holding Register, as if no error occurred and the RXRDY bit does rise. Transmit Character Repetition When the USART is transmitting a character and gets a NACK, it can automatically repeat the character before moving on to the next one. Repetition is enabled by writing the MAX_ITERATION field in the Mode Register (US_MR) at a value higher than 0. Each character can be transmitted up to eight times; the first transmission plus seven repetitions. If MAX_ITERATION does not equal zero, the USART repeats the character as many times as the value loaded in MAX_ITERATION. When the USART repetition number reaches MAX_ITERATION, the ITERATION bit is set in the Channel Status Register (US_CSR). If the repetition of the character is acknowledged by the receiver, the repetitions are stopped and the iteration counter is cleared. The ITERATION bit in US_CSR can be cleared by writing the Control Register with the RSIT bit to 1. Disable Successive Receive NACK The receiver can limit the number of successive NACKs sent back to the remote transmitter. This is programmed by setting the bit DSNACK in the Mode Register (US_MR). The maximum number of NACK transmitted is programmed in the MAX_ITERATION field. As soon as MAX_ITERATION is reached, the character is considered as correct, an acknowledge is sent on the line and the ITERATION bit in the Channel Status Register is set. 31.7.4.3 Protocol T = 1 When operating in ISO7816 protocol T = 1, the transmission is similar to an asynchronous format with only one stop bit. The parity is generated when transmitting and checked when receiving. Parity error detection sets the PARE bit in the Channel Status Register (US_CSR). SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 617 31.7.5 IrDA Mode The USART features an IrDA mode supplying half-duplex point-to-point wireless communication. It embeds the modulator and demodulator which allows a glueless connection to the infrared transceivers, as shown in Figure 31-23. The modulator and demodulator are compliant with the IrDA specification version 1.1 and support data transfer speeds ranging from 2.4 Kb/s to 115.2 Kb/s. The USART IrDA mode is enabled by setting the USART_MODE field in the Mode Register (US_MR) to the value 0x8. The IrDA Filter Register (US_IF) allows configuring the demodulator filter. The USART transmitter and receiver operate in a normal asynchronous mode and all parameters are accessible. Note that the modulator and the demodulator are activated. Figure 31-23. Connection to IrDA Transceivers USART IrDA Transceivers Receiver Demodulator Transmitter Modulator RXD RX TX TXD The receiver and the transmitter must be enabled or disabled according to the direction of the transmission to be managed. To receive IrDA signals, the following needs to be done: Disable TX and Enable RX Configure the TXD pin as PIO and set it as an output to 0 (to avoid LED emission). Disable the internal pullup (better for power consumption). Receive data 31.7.5.1 IrDA Modulation For baud rates up to and including 115.2 Kbits/sec, the RZI modulation scheme is used. “0” is represented by a light pulse of 3/16th of a bit time. Some examples of signal pulse duration are shown in Table 31-12. Table 31-12. IrDA Pulse Duration Baud Rate Pulse Duration (3/16) 2.4 Kb/s 78.13 µs 9.6 Kb/s 19.53 µs 19.2 Kb/s 9.77 µs 38.4 Kb/s 4.88 µs 57.6 Kb/s 3.26 µs 115.2 Kb/s 1.63 µs Figure 31-24 shows an example of character transmission. 618 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Figure 31-24. IrDA Modulation Start Bit Transmitter Output 0 Stop Bit Data Bits 0 1 1 0 1 0 1 0 1 TXD 3 16 Bit Period Bit Period 31.7.5.2 IrDA Baud Rate Table 31-13 gives some examples of CD values, baud rate error and pulse duration. Note that the requirement on the maximum acceptable error of ±1.87% must be met. Table 31-13. IrDA Baud Rate Error Peripheral Clock Baud Rate CD Baud Rate Error Pulse Time 3 686 400 115 200 2 0.00% 1.63 20 000 000 115 200 11 1.38% 1.63 32 768 000 115 200 18 1.25% 1.63 40 000 000 115 200 22 1.38% 1.63 3 686 400 57 600 4 0.00% 3.26 20 000 000 57 600 22 1.38% 3.26 32 768 000 57 600 36 1.25% 3.26 40 000 000 57 600 43 0.93% 3.26 3 686 400 38 400 6 0.00% 4.88 20 000 000 38 400 33 1.38% 4.88 32 768 000 38 400 53 0.63% 4.88 40 000 000 38 400 65 0.16% 4.88 3 686 400 19 200 12 0.00% 9.77 20 000 000 19 200 65 0.16% 9.77 32 768 000 19 200 107 0.31% 9.77 40 000 000 19 200 130 0.16% 9.77 3 686 400 9 600 24 0.00% 19.53 20 000 000 9 600 130 0.16% 19.53 32 768 000 9 600 213 0.16% 19.53 40 000 000 9 600 260 0.16% 19.53 3 686 400 2 400 96 0.00% 78.13 20 000 000 2 400 521 0.03% 78.13 32 768 000 2 400 853 0.04% 78.13 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 619 31.7.5.3 IrDA Demodulator The demodulator is based on the IrDA Receive filter comprised of an 8-bit down counter which is loaded with the value programmed in US_IF. When a falling edge is detected on the RXD pin, the Filter Counter starts counting down at the Master Clock (MCK) speed. If a rising edge is detected on the RXD pin, the counter stops and is reloaded with US_IF. If no rising edge is detected when the counter reaches 0, the input of the receiver is driven low during one bit time. Figure 31-25 illustrates the operations of the IrDA demodulator. Figure 31-25. IrDA Demodulator Operations MCK RXD Counter Value Receiver Input 6 5 4 3 Pulse Rejected 2 6 6 5 4 3 2 1 0 Pulse Accepted The programmed value in the US_IF register must always meet the following criteria: TMCK * (IRDA_FILTER + 3) < 1.41 us As the IrDA mode uses the same logic as the ISO7816, note that the FI_DI_RATIO field in US_FIDI must be set to a value higher than 0 in order to assure IrDA communications operate correctly. 620 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 31.7.6 RS485 Mode The USART features the RS485 mode to enable line driver control. While operating in RS485 mode, the USART behaves as though in asynchronous or synchronous mode and configuration of all the parameters is possible. The difference is that the RTS pin is driven high when the transmitter is operating. The behavior of the RTS pin is controlled by the TXEMPTY bit. A typical connection of the USART to a RS485 bus is shown in Figure 31-26. Figure 31-26. Typical Connection to a RS485 Bus USART RXD Differential Bus TXD RTS The USART is set in RS485 mode by programming the USART_MODE field in the Mode Register (US_MR) to the value 0x1. The RTS pin is at a level inverse to the TXEMPTY bit. Significantly, the RTS pin remains high when a timeguard is programmed so that the line can remain driven after the last character completion. Figure 31-27 gives an example of the RTS waveform during a character transmission when the timeguard is enabled. Figure 31-27. Example of RTS Drive with Timeguard TG = 4 Baud Rate Clock TXD Start D0 Bit D1 D2 D3 D4 D5 D6 D7 Parity Stop Bit Bit Write US_THR TXRDY TXEMPTY RTS SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 621 31.7.7 SPI Mode The Serial Peripheral Interface (SPI) Mode 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 turns being masters and one master may simultaneously shift data into multiple slaves. (Multiple Master Protocol is the opposite of Single Master Protocol, where one CPU is always the master while all of the others are always 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 its NSS signal is asserted by the master. The USART in SPI Master mode can address only one SPI Slave because it can generate only one NSS signal. 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 of the slave. Master In Slave Out (MISO): This data line supplies the output data from a slave to the input of the master. Serial Clock (SCK): 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 SCK line cycles once for each bit that is transmitted. Slave Select (NSS): This control line allows the master to select or deselect the slave. 31.7.7.1 Modes of Operation The USART can operate in SPI Master Mode or in SPI Slave Mode. Operation in SPI Master Mode is programmed by writing to 0xE the USART_MODE field in the Mode Register. In this case the SPI lines must be connected as described below: The MOSI line is driven by the output pin TXD The MISO line drives the input pin RXD The SCK line is driven by the output pin SCK The NSS line is driven by the output pin RTS Operation in SPI Slave Mode is programmed by writing to 0xF the USART_MODE field in the Mode Register. In this case the SPI lines must be connected as described below: The MOSI line drives the input pin RXD The MISO line is driven by the output pin TXD The SCK line drives the input pin SCK The NSS line drives the input pin CTS In order to avoid unpredicted behavior, any change of the SPI Mode must be followed by a software reset of the transmitter and of the receiver (except the initial configuration after a hardware reset). 622 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 31.7.7.2 Baud Rate In SPI Mode, the baudrate generator operates in the same way as in USART synchronous mode: See “Baud Rate in Synchronous Mode or SPI Mode” on page 604. However, there are some restrictions: In SPI Master Mode: The external clock SCK must not be selected (USCLKS ≠ 0x3), and the bit CLKO must be set to “1” in the Mode Register (US_MR), in order to generate correctly the serial clock on the SCK pin. To obtain correct behavior of the receiver and the transmitter, the value programmed in CD must be superior or equal to 6. If the internal clock divided (MCK/DIV) is selected, the value programmed in CD must be even to ensure a 50:50 mark/space ratio on the SCK pin, this value can be odd if the internal clock is selected (MCK). In SPI Slave Mode: The external clock (SCK) selection is forced regardless of the value of the USCLKS field in the Mode Register (US_MR). Likewise, the value written in US_BRGR has no effect, because the clock is provided directly by the signal on the USART SCK pin. To obtain correct behavior of the receiver and the transmitter, the external clock (SCK) frequency must be at least 6 times lower than the system clock. 31.7.7.3 Data Transfer Up to 9 data bits are successively shifted out on the TXD pin at each rising or falling edge (depending of CPOL and CPHA) of the programmed serial clock. There is no Start bit, no Parity bit and no Stop bit. The number of data bits is selected by the CHRL field and the MODE 9 bit in the Mode Register (US_MR). The 9 bits are selected by setting the MODE 9 bit regardless of the CHRL field. The MSB data bit is always sent first in SPI Mode (Master or Slave). Four combinations of polarity and phase are available for data transfers. The clock polarity is programmed with the CPOL bit in the Mode Register. The clock phase is programmed with the CPHA bit. These two parameters determine the edges of the clock signal upon which data is driven and sampled. Each of the two parameters 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 31-14. SPI Bus Protocol Mode SPI Bus Protocol Mode CPOL CPHA 0 0 1 1 0 0 2 1 1 3 1 0 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 623 Figure 31-28. SPI Transfer Format (CPHA=1, 8 bits per transfer) SCK cycle (for reference) 1 2 3 4 6 5 7 8 SCK (CPOL = 0) SCK (CPOL = 1) MOSI SPI Master ->TXD SPI Slave -> RXD MISO SPI Master ->RXD SPI Slave -> TXD MSB MSB 6 5 4 3 2 1 LSB 6 5 4 3 2 1 LSB NSS SPI Master -> RTS SPI Slave -> CTS Figure 31-29. SPI Transfer Format (CPHA=0, 8 bits per transfer) SCK cycle (for reference) 1 2 3 4 5 8 7 6 SCK (CPOL = 0) SCK (CPOL = 1) MOSI SPI Master -> TXD SPI Slave -> RXD MSB 6 5 4 3 2 1 LSB MISO SPI Master -> RXD SPI Slave -> TXD MSB 6 5 4 3 2 1 LSB NSS SPI Master -> RTS SPI Slave -> CTS 31.7.7.4 Receiver and Transmitter Control See “Receiver and Transmitter Control” on page 606. 624 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 31.7.7.5 Character Transmission The characters are sent by writing in the Transmit Holding Register (US_THR). An additional condition for transmitting a character can be added when the USART is configured in SPI master mode. In the USART_MR register, the value configured on INACK field can prevent any character transmission (even if US_THR has been written) while the receiver side is not ready (character not read). When WRDBT equals 0, the character is transmitted whatever the receiver status. If WRDBT is set to 1, the transmitter waits for the receiver holding register to be read before transmitting the character (RXRDY flag cleared), thus preventing any overflow (character loss) on the receiver side. The transmitter reports two status bits in the Channel Status Register (US_CSR): TXRDY (Transmitter Ready), which indicates that US_THR is empty and TXEMPTY, which indicates that all the characters written in US_THR have been processed. When the current character processing is completed, the last character written in US_THR is transferred into the Shift Register of the transmitter and US_THR becomes empty, thus TXRDY rises. Both TXRDY and TXEMPTY bits are low when the transmitter is disabled. Writing a character in US_THR while TXRDY is low has no effect and the written character is lost. If the USART is in SPI Slave Mode and if a character must be sent while the Transmit Holding Register (US_THR) is empty, the UNRE (Underrun Error) bit is set. The TXD transmission line stays at high level during all this time. The UNRE bit is cleared by writing the Control Register (US_CR) with the RSTSTA (Reset Status) bit to 1. In SPI Master Mode, the slave select line (NSS) is asserted at low level 1 Tbit (Time bit) before the transmission of the MSB bit and released at high level 1 Tbit after the transmission of the LSB bit. So, the slave select line (NSS) is always released between each character transmission and a minimum delay of 3 Tbits always inserted. However, in order to address slave devices supporting the CSAAT mode (Chip Select Active After Transfer), the slave select line (NSS) can be forced at low level by writing the Control Register (US_CR) with the RTSEN bit to 1. The slave select line (NSS) can be released at high level only by writing the Control Register (US_CR) with the RTSDIS bit to 1 (for example, when all data have been transferred to the slave device). In SPI Slave Mode, the transmitter does not require a falling edge of the slave select line (NSS) to initiate a character transmission but only a low level. However, this low level must be present on the slave select line (NSS) at least 1 Tbit before the first serial clock cycle corresponding to the MSB bit. 31.7.7.6 Character Reception When a character reception is completed, it is transferred to the Receive Holding Register (US_RHR) and the RXRDY bit in the Status Register (US_CSR) rises. If a character is completed while RXRDY is set, the OVRE (Overrun Error) bit is set. The last character is transferred into US_RHR and overwrites the previous one. The OVRE bit is cleared by writing the Control Register (US_CR) with the RSTSTA (Reset Status) bit to 1. To ensure correct behavior of the receiver in SPI Slave Mode, the master device sending the frame must ensure a minimum delay of 1 Tbit between each character transmission. The receiver does not require a falling edge of the slave select line (NSS) to initiate a character reception but only a low level. However, this low level must be present on the slave select line (NSS) at least 1 Tbit before the first serial clock cycle corresponding to the MSB bit. 31.7.7.7 Receiver Timeout Because the receiver baudrate clock is active only during data transfers in SPI Mode, a receiver timeout is impossible in this mode, whatever the Time-out value is (field TO) in the Time-out Register (US_RTOR). 31.7.8 Test Modes The USART can be programmed to operate in three different test modes. The internal loopback capability allows on-board diagnostics. In the loopback mode the USART interface pins are disconnected or not and reconfigured for loopback internally or externally. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 625 31.7.8.1 Normal Mode Normal mode connects the RXD pin on the receiver input and the transmitter output on the TXD pin. Figure 31-30. Normal Mode Configuration RXD Receiver TXD Transmitter 31.7.8.2 Automatic Echo Mode Automatic echo mode allows bit-by-bit retransmission. When a bit is received on the RXD pin, it is sent to the TXD pin, as shown in Figure 31-31. Programming the transmitter has no effect on the TXD pin. The RXD pin is still connected to the receiver input, thus the receiver remains active. Figure 31-31. Automatic Echo Mode Configuration RXD Receiver TXD Transmitter 31.7.8.3 Local Loopback Mode Local loopback mode connects the output of the transmitter directly to the input of the receiver, as shown in Figure 31-32. 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 31-32. Local Loopback Mode Configuration RXD Receiver 1 Transmitter TXD 31.7.8.4 Remote Loopback Mode Remote loopback mode directly connects the RXD pin to the TXD pin, as shown in Figure 31-33. The transmitter and the receiver are disabled and have no effect. This mode allows bit-by-bit retransmission. Figure 31-33. Remote Loopback Mode Configuration Receiver 1 RXD TXD Transmitter 626 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 31.7.9 Write Protection Registers To prevent any single software error that may corrupt USART behavior, certain address spaces can be writeprotected by setting the WPEN bit in the USART Write Protect Mode Register (US_WPMR). If a write access to the protected registers is detected, then the WPVS flag in the USART Write Protect Status Register (US_WPSR) is set and the field WPVSRC indicates in which register the write access has been attempted. The WPVS flag is automatically reset by reading the USART Write Protect Mode Register (US_WPMR) with the appropriate access key, WPKEY. The protected registers are: “USART Mode Register” “USART Baud Rate Generator Register” “USART Receiver Time-out Register” “USART Transmitter Timeguard Register” “USART FI DI RATIO Register” “USART IrDA FILTER Register” SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 627 31.8 Universal Synchronous Asynchronous Receiver Transmitter (USART) User Interface Table 31-15. Register Mapping Offset Register Name Access Reset 0x0000 Control Register US_CR Write-only – 0x0004 Mode Register US_MR Read-write – 0x0008 Interrupt Enable Register US_IER Write-only – 0x000C Interrupt Disable Register US_IDR Write-only – 0x0010 Interrupt Mask Register US_IMR Read-only 0x0 0x0014 Channel Status Register US_CSR Read-only – 0x0018 Receiver Holding Register US_RHR Read-only 0x0 0x001C Transmitter Holding Register US_THR Write-only – 0x0020 Baud Rate Generator Register US_BRGR Read-write 0x0 0x0024 Receiver Time-out Register US_RTOR Read-write 0x0 0x0028 Transmitter Timeguard Register US_TTGR Read-write 0x0 – – – 0x2C - 0x3C Reserved 0x0040 FI DI Ratio Register US_FIDI Read-write 0x174 0x0044 Number of Errors Register US_NER Read-only – 0x0048 Reserved – – – 0x004C IrDA Filter Register US_IF Read-write 0x0 0x0050 Reserved – – – 0x0054 - 0x005C Reserved – – – 0x0060-0x00E0 Reserved – – – 0x00E4 Write Protect Mode Register US_WPMR Read-write 0x0 0x00E8 Write Protect Status Register US_WPSR Read-only 0x0 Reserved – – – Reserved for PDC Registers – – – 0x00EC - 0x00FC 0x100 - 0x128 628 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 31.8.1 USART Control Register Name: US_CR Address: 0x40024000 (0), 0x40028000 (1), 0x4002C000 (2) Access: Write-only 31 – 30 – 29 – 28 – 27 – 26 – 25 – 24 – 23 – 22 – 21 – 20 – 19 RTSDIS 18 RTSEN 17 – 16 – 15 RETTO 14 RSTNACK 13 RSTIT 12 SENDA 11 STTTO 10 STPBRK 9 STTBRK 8 RSTSTA 7 TXDIS 6 TXEN 5 RXDIS 4 RXEN 3 RSTTX 2 RSTRX 1 – 0 – For SPI control, see “USART Control Register (SPI_MODE)” on page 631. • RSTRX: Reset Receiver 0: No effect. 1: Resets the receiver. • RSTTX: Reset Transmitter 0: No effect. 1: Resets the transmitter. • RXEN: Receiver Enable 0: No effect. 1: Enables the receiver, if RXDIS is 0. • RXDIS: Receiver Disable 0: No effect. 1: Disables the receiver. • TXEN: Transmitter Enable 0: No effect. 1: Enables the transmitter if TXDIS is 0. • TXDIS: Transmitter Disable 0: No effect. 1: Disables the transmitter. • RSTSTA: Reset Status Bits 0: No effect. 1: Resets the status bits PARE, FRAME, OVRE and RXBRK in US_CSR. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 629 • STTBRK: Start Break 0: No effect. 1: Starts transmission of a break after the characters present in US_THR and the Transmit Shift Register have been transmitted. No effect if a break is already being transmitted. • STPBRK: Stop Break 0: No effect. 1: Stops transmission of the break after a minimum of one character length and transmits a high level during 12-bit periods. No effect if no break is being transmitted. • STTTO: Start Time-out 0: No effect. 1: Starts waiting for a character before clocking the time-out counter. Resets the status bit TIMEOUT in US_CSR. • SENDA: Send Address 0: No effect. 1: In Multidrop Mode only, the next character written to the US_THR is sent with the address bit set. • RSTIT: Reset Iterations 0: No effect. 1: Resets ITERATION in US_CSR. No effect if the ISO7816 is not enabled. • RSTNACK: Reset Non Acknowledge 0: No effect 1: Resets NACK in US_CSR. • RETTO: Rearm Time-out 0: No effect 1: Restart Time-out • RTSEN: Request to Send Enable 0: No effect. 1: Drives the pin RTS to 0. • RTSDIS: Request to Send Disable 0: No effect. 1: Drives the pin RTS to 1. 630 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 31.8.2 USART Control Register (SPI_MODE) Name: US_CR (SPI_MODE) Address: 0x40024000 (0), 0x40028000 (1), 0x4002C000 (2) Access: Write-only 31 – 30 – 29 – 28 – 27 – 26 – 25 – 24 – 23 – 22 – 21 – 20 – 19 RCS 18 FCS 17 – 16 – 15 – 14 – 13 – 12 – 11 – 10 – 9 – 8 RSTSTA 7 TXDIS 6 TXEN 5 RXDIS 4 RXEN 3 RSTTX 2 RSTRX 1 – 0 – This configuration is relevant only if USART_MODE=0xE or 0xF in “USART Mode Register” on page 633. • RSTRX: Reset Receiver 0: No effect. 1: Resets the receiver. • RSTTX: Reset Transmitter 0: No effect. 1: Resets the transmitter. • RXEN: Receiver Enable 0: No effect. 1: Enables the receiver, if RXDIS is 0. • RXDIS: Receiver Disable 0: No effect. 1: Disables the receiver. • TXEN: Transmitter Enable 0: No effect. 1: Enables the transmitter if TXDIS is 0. • TXDIS: Transmitter Disable 0: No effect. 1: Disables the transmitter. • RSTSTA: Reset Status Bits 0: No effect. 1: Resets the status bits OVRE, UNRE in US_CSR. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 631 • FCS: Force SPI Chip Select – Applicable if USART operates in SPI Master Mode (USART_MODE = 0xE): FCS = 0: No effect. FCS = 1: Forces the Slave Select Line NSS (RTS pin) to 0, even if USART is no transmitting, in order to address SPI slave devices supporting the CSAAT Mode (Chip Select Active After Transfer). • RCS: Release SPI Chip Select – Applicable if USART operates in SPI Master Mode (USART_MODE = 0xE): RCS = 0: No effect. RCS = 1: Releases the Slave Select Line NSS (RTS pin). 632 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 31.8.3 USART Mode Register Name: US_MR Address: 0x40024004 (0), 0x40028004 (1), 0x4002C004 (2) Access: Read-write 31 – 30 – 29 – 28 FILTER 27 – 26 25 MAX_ITERATION 24 23 INVDATA 22 – 21 DSNACK 20 INACK 19 OVER 18 CLKO 17 MODE9 16 MSBF 15 14 13 12 11 10 PAR 9 8 SYNC 4 3 2 1 0 CHMODE 7 NBSTOP 6 5 CHRL USCLKS USART_MODE This register can only be written if the WPEN bit is cleared in “USART Write Protect Mode Register” on page 655. For SPI configuration, see “USART Mode Register (SPI_MODE)” on page 636. • USART_MODE: USART Mode of Operation Value Name Description 0x0 NORMAL Normal mode 0x1 RS485 0x2 HW_HANDSHAKING Hardware Handshaking 0x4 IS07816_T_0 IS07816 Protocol: T = 0 0x6 IS07816_T_1 IS07816 Protocol: T = 1 0x8 IRDA 0xE SPI_MASTER SPI Master 0xF SPI_SLAVE SPI Slave RS485 IrDA The PDC transfers are supported in all USART Mode of Operation. • USCLKS: Clock Selection Value Name Description 0 MCK Master Clock MCK is selected 1 DIV Internal Clock Divided MCK/DIV (DIV=8) is selected 3 SCK Serial Clock SLK is selected • CHRL: Character Length. Value Name Description 0 5_BIT Character length is 5 bits 1 6_BIT Character length is 6 bits 2 7_BIT Character length is 7 bits 3 8_BIT Character length is 8 bits SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 633 • SYNC: Synchronous Mode Select 0: USART operates in Asynchronous Mode. 1: USART operates in Synchronous Mode. • PAR: Parity Type Value Name Description 0 EVEN Even parity 1 ODD Odd parity 2 SPACE Parity forced to 0 (Space) 3 MARK Parity forced to 1 (Mark) 4 NO 6 MULTIDROP No parity Multidrop mode • NBSTOP: Number of Stop Bits Value Name Description 0 1_BIT 1 stop bit 1 1_5_BIT 2 2_BIT 1.5 stop bit (SYNC = 0) or reserved (SYNC = 1) 2 stop bits • CHMODE: Channel Mode Value Name Description 0 NORMAL Normal Mode 1 AUTOMATIC 2 LOCAL_LOOPBACK 3 REMOTE_LOOPBACK Automatic Echo. Receiver input is connected to the TXD pin. Local Loopback. Transmitter output is connected to the Receiver Input. Remote Loopback. RXD pin is internally connected to the TXD pin. • MSBF: Bit Order 0: Least Significant Bit is sent/received first. 1: Most Significant Bit is sent/received first. • MODE9: 9-bit Character Length 0: CHRL defines character length. 1: 9-bit character length. • CLKO: Clock Output Select 0: The USART does not drive the SCK pin. 1: The USART drives the SCK pin if USCLKS does not select the external clock SCK. • OVER: Oversampling Mode 0: 16x Oversampling. 1: 8x Oversampling. 634 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 • INACK: Inhibit Non Acknowledge 0: The NACK is generated. 1: The NACK is not generated. • DSNACK: Disable Successive NACK 0: NACK is sent on the ISO line as soon as a parity error occurs in the received character (unless INACK is set). 1: Successive parity errors are counted up to the value specified in the MAX_ITERATION field. These parity errors generate a NACK on the ISO line. As soon as this value is reached, no additional NACK is sent on the ISO line. The flag ITERATION is asserted. • INVDATA: Inverted Data 0: The data field transmitted on TXD line is the same as the one written in US_THR register or the content read in US_RHR is the same as RXD line. Normal mode of operation. 1: The data field transmitted on TXD line is inverted (voltage polarity only) compared to the value written on US_THR register or the content read in US_RHR is inverted compared to what is received on RXD line (or ISO7816 IO line). Inverted Mode of operation, useful for contactless card application. To be used with configuration bit MSBF. • MAX_ITERATION: Maximum Number of Automatic Iteration 0 - 7: Defines the maximum number of iterations in mode ISO7816, protocol T= 0. • FILTER: Infrared Receive Line Filter 0: The USART does not filter the receive line. 1: The USART filters the receive line using a three-sample filter (1/16-bit clock) (2 over 3 majority). SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 635 31.8.4 USART Mode Register (SPI_MODE) Name: US_MR (SPI_MODE) Address: 0x40024004 (0), 0x40028004 (1), 0x4002C004 (2) Access: Read-write 31 – 30 – 29 – 28 – 27 – 26 – 25 – 24 – 23 – 22 – 21 – 20 WRDBT 19 – 18 – 17 – 16 CPOL 15 – 14 – 13 – 12 – 11 – 10 – 9 – 8 CPHA 6 5 4 3 2 1 0 7 CHRL USCLKS USART_MODE This configuration is relevant only if USART_MODE=0xE or 0xF in “USART Mode Register” on page 633. This register can only be written if the WPEN bit is cleared in “USART Write Protect Mode Register” on page 655. • USART_MODE: USART Mode of Operation Value Name Description 0xE SPI_MASTER SPI Master 0xF SPI_SLAVE SPI Slave • USCLKS: Clock Selection Value Name Description 0 MCK Master Clock MCK is selected 1 DIV Internal Clock Divided MCK/DIV (DIV=8) is selected 3 SCK Serial Clock SLK is selected • CHRL: Character Length. Value Name Description 3 8_BIT Character length is 8 bits • CPHA: SPI Clock Phase – Applicable if USART operates in SPI Mode (USART_MODE = 0xE or 0xF): CPHA = 0: Data is changed on the leading edge of SPCK and captured on the following edge of SPCK. CPHA = 1: Data is captured on the leading edge of SPCK and changed on the following edge of SPCK. CPHA determines which edge of SPCK 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. 636 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 • CHMODE: Channel Mode Value Name Description 0 NORMAL Normal Mode 1 AUTOMATIC 2 LOCAL_LOOPBACK 3 REMOTE_LOOPBACK Automatic Echo. Receiver input is connected to the TXD pin. Local Loopback. Transmitter output is connected to the Receiver Input. Remote Loopback. RXD pin is internally connected to the TXD pin. • CPOL: SPI Clock Polarity – Applicable if USART operates in SPI Mode (Slave or Master, USART_MODE = 0xE or 0xF): CPOL = 0: The inactive state value of SPCK is logic level zero. CPOL = 1: The inactive state value of SPCK is logic level one. CPOL is used to determine the inactive state value of the serial clock (SPCK). It is used with CPHA to produce the required clock/data relationship between master and slave devices. • WRDBT: Wait Read Data Before Transfer 0: The character transmission starts as soon as a character is written into US_THR register (assuming TXRDY was set). 1: The character transmission starts when a character is written and only if RXRDY flag is cleared (Receiver Holding Register has been read). SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 637 31.8.5 USART Interrupt Enable Register Name: US_IER Address: 0x40024008 (0), 0x40028008 (1), 0x4002C008 (2) Access: Write-only 31 – 30 – 29 – 28 – 27 – 26 – 25 – 24 – 23 – 22 – 21 – 20 – 19 CTSIC 18 – 17 – 16 – 15 – 14 – 13 NACK 12 RXBUFF 11 TXBUFE 10 ITER 9 TXEMPTY 8 TIMEOUT 7 PARE 6 FRAME 5 OVRE 4 ENDTX 3 ENDRX 2 RXBRK 1 TXRDY 0 RXRDY For SPI specific configuration, see “USART Interrupt Enable Register (SPI_MODE)” on page 639. • RXRDY: RXRDY Interrupt Enable • TXRDY: TXRDY Interrupt Enable • RXBRK: Receiver Break Interrupt Enable • ENDRX: End of Receive Transfer Interrupt Enable (available in all USART modes of operation) • ENDTX: End of Transmit Interrupt Enable (available in all USART modes of operation) • OVRE: Overrun Error Interrupt Enable • FRAME: Framing Error Interrupt Enable • PARE: Parity Error Interrupt Enable • TIMEOUT: Time-out Interrupt Enable • TXEMPTY: TXEMPTY Interrupt Enable • ITER: Max number of Repetitions Reached Interrupt Enable • TXBUFE: Buffer Empty Interrupt Enable (available in all USART modes of operation) • RXBUFF: Buffer Full Interrupt Enable (available in all USART modes of operation) • NACK: Non AcknowledgeInterrupt Enable • CTSIC: Clear to Send Input Change Interrupt Enable 0: No effect 1: Enables the corresponding interrupt. 638 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 31.8.6 USART Interrupt Enable Register (SPI_MODE) Name: US_IER (SPI_MODE) Address: 0x40024008 (0), 0x40028008 (1), 0x4002C008 (2) Access: Write-only 31 – 30 – 29 – 28 – 27 – 26 – 25 – 24 – 23 – 22 – 21 – 20 – 19 – 18 – 17 – 16 – 15 – 14 – 13 – 12 RXBUFF 11 TXBUFE 10 UNRE 9 TXEMPTY 8 – 7 – 6 – 5 OVRE 4 ENDTX 3 ENDRX 2 – 1 TXRDY 0 RXRDY This configuration is relevant only if USART_MODE=0xE or 0xF in “USART Mode Register” on page 633. • RXRDY: RXRDY Interrupt Enable • TXRDY: TXRDY Interrupt Enable • OVRE: Overrun Error Interrupt Enable • TXEMPTY: TXEMPTY Interrupt Enable • UNRE: SPI Underrun Error Interrupt Enable 0: No effect 1: Enables the corresponding interrupt. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 639 31.8.7 USART Interrupt Disable Register Name: US_IDR Address: 0x4002400C (0), 0x4002800C (1), 0x4002C00C (2) Access: Write-only 31 – 30 – 29 – 28 – 27 – 26 – 25 – 24 – 23 – 22 – 21 – 20 – 19 CTSIC 18 – 17 – 16 – 15 – 14 – 13 NACK 12 RXBUFF 11 TXBUFE 10 ITER 9 TXEMPTY 8 TIMEOUT 7 PARE 6 FRAME 5 OVRE 4 ENDTX 3 ENDRX 2 RXBRK 1 TXRDY 0 RXRDY For SPI specific configuration, see “USART Interrupt Disable Register (SPI_MODE)” on page 641. • RXRDY: RXRDY Interrupt Disable • TXRDY: TXRDY Interrupt Disable • RXBRK: Receiver Break Interrupt Disable • ENDRX: End of Receive Transfer Interrupt Disable (available in all USART modes of operation) • ENDTX: End of Transmit Interrupt Disable (available in all USART modes of operation) • OVRE: Overrun Error Interrupt Enable • FRAME: Framing Error Interrupt Disable • PARE: Parity Error Interrupt Disable • TIMEOUT: Time-out Interrupt Disable • TXEMPTY: TXEMPTY Interrupt Disable • ITER: Max Number of Repetitions Reached Interrupt Disable • TXBUFE: Buffer Empty Interrupt Disable (available in all USART modes of operation) • RXBUFF: Buffer Full Interrupt Disable (available in all USART modes of operation) • NACK: Non AcknowledgeInterrupt Disable • CTSIC: Clear to Send Input Change Interrupt Disable 0: No effect 1: Disables the corresponding interrupt. 640 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 31.8.8 USART Interrupt Disable Register (SPI_MODE) Name: US_IDR (SPI_MODE) Address: 0x4002400C (0), 0x4002800C (1), 0x4002C00C (2) Access: Write-only 31 – 30 – 29 – 28 – 27 – 26 – 25 – 24 – 23 – 22 – 21 – 20 – 19 – 18 – 17 – 16 – 15 – 14 – 13 – 12 RXBUFF 11 TXBUFE 10 UNRE 9 TXEMPTY 8 – 7 – 6 – 5 OVRE 4 ENDTX 3 ENDRX 2 – 1 TXRDY 0 RXRDY This configuration is relevant only if USART_MODE=0xE or 0xF in “USART Mode Register” on page 633. • RXRDY: RXRDY Interrupt Disable • TXRDY: TXRDY Interrupt Disable • OVRE: Overrun Error Interrupt Disable • TXEMPTY: TXEMPTY Interrupt Disable • UNRE: SPI Underrun Error Interrupt Disable 0: No effect 1: Disables the corresponding interrupt. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 641 31.8.9 USART Interrupt Mask Register Name: US_IMR Address: 0x40024010 (0), 0x40028010 (1), 0x4002C010 (2) Access: Read-only 31 – 30 – 29 – 28 – 27 – 26 – 25 – 24 – 23 – 22 – 21 – 20 – 19 CTSIC 18 – 17 – 16 – 15 – 14 – 13 NACK 12 RXBUFF 11 TXBUFE 10 ITER 9 TXEMPTY 8 TIMEOUT 7 PARE 6 FRAME 5 OVRE 4 ENDTX 3 ENDRX 2 RXBRK 1 TXRDY 0 RXRDY For SPI specific configuration, see “USART Interrupt Mask Register (SPI_MODE)” on page 643. • RXRDY: RXRDY Interrupt Mask • TXRDY: TXRDY Interrupt Mask • RXBRK: Receiver Break Interrupt Mask • ENDRX: End of Receive Transfer Interrupt Mask (available in all USART modes of operation) • ENDTX: End of Transmit Interrupt Mask (available in all USART modes of operation) • OVRE: Overrun Error Interrupt Mask • FRAME: Framing Error Interrupt Mask • PARE: Parity Error Interrupt Mask • TIMEOUT: Time-out Interrupt Mask • TXEMPTY: TXEMPTY Interrupt Mask • ITER: Max Number of Repetitions Reached Interrupt Mask • TXBUFE: Buffer Empty Interrupt Mask (available in all USART modes of operation) • RXBUFF: Buffer Full Interrupt Mask (available in all USART modes of operation) • NACK: Non AcknowledgeInterrupt Mask • CTSIC: Clear to Send Input Change Interrupt Mask 0: The corresponding interrupt is not enabled. 1: The corresponding interrupt is enabled. 642 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 31.8.10 USART Interrupt Mask Register (SPI_MODE) Name: US_IMR (SPI_MODE) Address: 0x40024010 (0), 0x40028010 (1), 0x4002C010 (2) Access: Read-only 31 – 30 – 29 – 28 – 27 – 26 – 25 – 24 – 23 – 22 – 21 – 20 – 19 – 18 – 17 – 16 – 15 – 14 – 13 – 12 RXBUFF 11 TXBUFE 10 UNRE 9 TXEMPTY 8 – 7 – 6 – 5 OVRE 4 ENDTX 3 ENDRX 2 – 1 TXRDY 0 RXRDY This configuration is relevant only if USART_MODE=0xE or 0xF in “USART Mode Register” on page 633. • RXRDY: RXRDY Interrupt Mask • TXRDY: TXRDY Interrupt Mask • OVRE: Overrun Error Interrupt Mask • TXEMPTY: TXEMPTY Interrupt Mask • UNRE: SPI Underrun Error Interrupt Mask 0: The corresponding interrupt is not enabled. 1: The corresponding interrupt is enabled. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 643 31.8.11 USART Channel Status Register Name: US_CSR Address: 0x40024014 (0), 0x40028014 (1), 0x4002C014 (2) Access: Read-only 31 – 30 – 29 – 28 – 27 – 26 – 25 – 24 – 23 CTS 22 – 21 – 20 – 19 CTSIC 18 – 17 – 16 – 15 – 14 – 13 NACK 12 RXBUFF 11 TXBUFE 10 ITER 9 TXEMPTY 8 TIMEOUT 7 PARE 6 FRAME 5 OVRE 4 ENDTX 3 ENDRX 2 RXBRK 1 TXRDY 0 RXRDY For SPI specific configuration, see “USART Channel Status Register (SPI_MODE)” on page 646. • RXRDY: Receiver Ready 0: No complete character has been received since the last read of US_RHR or the receiver is disabled. 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 US_RHR has not yet been read. • TXRDY: Transmitter Ready 0: A character is in the US_THR waiting to be transferred to the Transmit Shift Register, or an STTBRK command has been requested, or the transmitter is disabled. As soon as the transmitter is enabled, TXRDY becomes 1. 1: There is no character in the US_THR. • 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. • ENDRX: End of Receiver Transfer 0: The End of Transfer signal from the Receive PDC channel is inactive. 1: The End of Transfer signal from the Receive PDC channel is active. • ENDTX: End of Transmitter Transfer 0: The End of Transfer signal from the Transmit PDC channel is inactive. 1: The End of Transfer signal from the Transmit PDC channel is active. • 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. 644 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 • FRAME: Framing Error 0: No stop bit has been detected low since the last RSTSTA. 1: At least one stop bit has been detected low since the last RSTSTA. • PARE: Parity Error 0: No parity error has been detected since the last RSTSTA. 1: At least one parity error has been detected since the last RSTSTA. • TIMEOUT: Receiver Time-out 0: There has not been a time-out since the last Start Time-out command (STTTO in US_CR) or the Time-out Register is 0. 1: There has been a time-out since the last Start Time-out command (STTTO in US_CR). • TXEMPTY: Transmitter Empty 0: There are characters in either US_THR or the Transmit Shift Register, or the transmitter is disabled. 1: There are no characters in US_THR, nor in the Transmit Shift Register. • ITER: Max Number of Repetitions Reached 0: Maximum number of repetitions has not been reached since the last RSTSTA. 1: Maximum number of repetitions has been reached since the last RSTSTA. • TXBUFE: Transmission Buffer Empty 0: The signal Buffer Empty from the Transmit PDC channel is inactive. 1: The signal Buffer Empty from the Transmit PDC channel is active. • RXBUFF: Reception Buffer Full 0: The signal Buffer Full from the Receive PDC channel is inactive. 1: The signal Buffer Full from the Receive PDC channel is active. • NACK: Non AcknowledgeInterrupt 0: Non Acknowledge has not been detected since the last RSTNACK. 1: At least one Non Acknowledge has been detected since the last RSTNACK. • CTSIC: Clear to Send Input Change Flag 0: No input change has been detected on the CTS pin since the last read of US_CSR. 1: At least one input change has been detected on the CTS pin since the last read of US_CSR. • CTS: Image of CTS Input 0: CTS is set to 0. 1: CTS is set to 1. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 645 31.8.12 USART Channel Status Register (SPI_MODE) Name: US_CSR (SPI_MODE) Address: 0x40024014 (0), 0x40028014 (1), 0x4002C014 (2) Access: Read-only 31 – 30 – 29 – 28 – 27 – 26 – 25 – 24 – 23 – 22 – 21 – 20 – 19 – 18 – 17 – 16 – 15 – 14 – 13 – 12 RXBUFF 11 TXBUFE 10 UNRE 9 TXEMPTY 8 – 7 – 6 – 5 OVRE 4 ENDTX 3 ENDRX 2 – 1 TXRDY 0 RXRDY This configuration is relevant only if USART_MODE=0xE or 0xF in “USART Mode Register” on page 633. • RXRDY: Receiver Ready 0: No complete character has been received since the last read of US_RHR or the receiver is disabled. 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 US_RHR has not yet been read. • TXRDY: Transmitter Ready 0: A character is in the US_THR waiting to be transferred to the Transmit Shift Register or the transmitter is disabled. As soon as the transmitter is enabled, TXRDY becomes 1. 1: There is no character in the US_THR. • 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. • TXEMPTY: Transmitter Empty 0: There are characters in either US_THR or the Transmit Shift Register, or the transmitter is disabled. 1: There are no characters in US_THR, nor in the Transmit Shift Register. • UNRE: Underrun Error 0: No SPI underrun error has occurred since the last RSTSTA. 1: At least one SPI underrun error has occurred since the last RSTSTA. 646 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 31.8.13 USART Receive Holding Register Name: US_RHR Address: 0x40024018 (0), 0x40028018 (1), 0x4002C018 (2) Access: Read-only 31 – 30 – 29 – 28 – 27 – 26 – 25 – 24 – 23 – 22 – 21 – 20 – 19 – 18 – 17 – 16 – 15 RXSYNH 14 – 13 – 12 – 11 – 10 – 9 – 8 RXCHR 7 6 5 4 3 2 1 0 RXCHR • RXCHR: Received Character Last character received if RXRDY is set. • RXSYNH: Received Sync 0: Last Character received is a Data. 1: Last Character received is a Command. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 647 31.8.14 USART Transmit Holding Register Name: US_THR Address: 0x4002401C (0), 0x4002801C (1), 0x4002C01C (2) Access: Write-only 31 – 30 – 29 – 28 – 27 – 26 – 25 – 24 – 23 – 22 – 21 – 20 – 19 – 18 – 17 – 16 – 15 TXSYNH 14 – 13 – 12 – 11 – 10 – 9 – 8 TXCHR 7 6 5 4 3 2 1 0 TXCHR • TXCHR: Character to be Transmitted Next character to be transmitted after the current character if TXRDY is not set. • TXSYNH: Sync Field to be Transmitted 0: The next character sent is encoded as a data. Start Frame Delimiter is DATA SYNC. 1: The next character sent is encoded as a command. Start Frame Delimiter is COMMAND SYNC. 648 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 31.8.15 USART Baud Rate Generator Register Name: US_BRGR Address: 0x40024020 (0), 0x40028020 (1), 0x4002C020 (2) Access: Read-write 31 – 30 – 29 – 28 – 27 – 26 – 25 – 24 – 23 – 22 – 21 – 20 – 19 – 18 17 FP 16 15 14 13 12 11 10 9 8 3 2 1 0 CD 7 6 5 4 CD This register can only be written if the WPEN bit is cleared in “USART Write Protect Mode Register” on page 655. • CD: Clock Divider USART_MODE ≠ ISO7816 SYNC = 1 or USART_MODE = SPI (Master or Slave) SYNC = 0 CD OVER = 0 OVER = 1 0 1 to 65535 USART_MODE = ISO7816 Baud Rate Clock Disabled Baud Rate = Baud Rate = Baud Rate = Selected Clock/(16*CD) Selected Clock/(8*CD) Selected Clock /CD Baud Rate = Selected Clock/(FI_DI_RATIO*CD) • FP: Fractional Part 0: Fractional divider is disabled. 1 - 7: Baud rate resolution, defined by FP x 1/8. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 649 31.8.16 USART Receiver Time-out Register Name: US_RTOR Address: 0x40024024 (0), 0x40028024 (1), 0x4002C024 (2) Access: Read-write 31 30 29 28 27 26 25 24 – – – – – – – – 23 – 22 – 21 – 20 – 19 – 18 – 17 – 16 – 15 14 13 12 11 10 9 8 3 2 1 0 TO 7 6 5 4 TO This register can only be written if the WPEN bit is cleared in “USART Write Protect Mode Register” on page 655. • TO: Time-out Value 0: The Receiver Time-out is disabled. 1 - 65535: The Receiver Time-out is enabled and the Time-out delay is TO x Bit Period. 650 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 31.8.17 USART Transmitter Timeguard Register Name: US_TTGR Address: 0x40024028 (0), 0x40028028 (1), 0x4002C028 (2) Access: Read-write 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 6 5 4 3 2 1 0 TG This register can only be written if the WPEN bit is cleared in “USART Write Protect Mode Register” on page 655. • 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. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 651 31.8.18 USART FI DI RATIO Register Name: US_FIDI Address: 0x40024040 (0), 0x40028040 (1), 0x4002C040 (2) Access: Read-write Reset Value: 0x174 31 – 30 – 29 – 28 – 27 – 26 – 25 – 24 – 23 – 22 – 21 – 20 – 19 – 18 – 17 – 16 – 15 14 13 12 11 10 9 8 3 2 1 0 FI_DI_RATIO 7 6 5 4 FI_DI_RATIO This register can only be written if the WPEN bit is cleared in “USART Write Protect Mode Register” on page 655. • FI_DI_RATIO: FI Over DI Ratio Value 0: If ISO7816 mode is selected, the Baud Rate Generator generates no signal. 1 - 2047: If ISO7816 mode is selected, the Baud Rate is the clock provided on SCK divided by FI_DI_RATIO. 652 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 31.8.19 USART Number of Errors Register Name: US_NER Address: 0x40024044 (0), 0x40028044 (1), 0x4002C044 (2) Access: Read-only 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 6 5 4 3 2 1 0 NB_ERRORS This register is relevant only if USART_MODE=0x4 or 0x6 in “USART Mode Register” on page 633. • NB_ERRORS: Number of Errors Total number of errors that occurred during an ISO7816 transfer. This register automatically clears when read. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 653 31.8.20 USART IrDA FILTER Register Name: US_IF Address: 0x4002404C (0), 0x4002804C (1), 0x4002C04C (2) Access: Read-write 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 6 5 4 3 2 1 0 IRDA_FILTER This register is relevant only if USART_MODE=0x8 in “USART Mode Register” on page 633. This register can only be written if the WPEN bit is cleared in “USART Write Protect Mode Register” on page 655. • IRDA_FILTER: IrDA Filter The IRDA_FILTER value must be defined to meet the following criteria: TMCK * (IRDA_FILTER + 3) < 1.41 us 654 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 31.8.21 USART Write Protect Mode Register Name: US_WPMR Address: 0x400240E4 (0), 0x400280E4 (1), 0x4002C0E4 (2) Access: Read-write Reset: See Table 31-15 31 30 29 28 27 26 25 24 19 18 17 16 11 10 9 8 WPKEY 23 22 21 20 WPKEY 15 14 13 12 WPKEY 7 6 5 4 3 2 1 0 — — — — — — — WPEN • WPEN: Write Protect Enable 0 = Disables the Write Protect if WPKEY corresponds to 0x555341 (“USA” in ASCII). 1 = Enables the Write Protect if WPKEY corresponds to 0x555341 (“USA” in ASCII). Protects the registers: “USART Mode Register” on page 633 “USART Baud Rate Generator Register” on page 649 “USART Receiver Time-out Register” on page 650 “USART Transmitter Timeguard Register” on page 651 “USART FI DI RATIO Register” on page 652 “USART IrDA FILTER Register” on page 654 • WPKEY: Write Protect KEY. Value Name 0x555341 PASSWD Description Writing any other value in this field aborts the write operation of the WPEN bit. Always reads as 0. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 655 31.8.22 USART Write Protect Status Register Name: US_WPSR Address: 0x400240E8 (0), 0x400280E8 (1), 0x4002C0E8 (2) Access: Read-only Reset: See Table 31-15 31 30 29 28 27 26 25 24 — — — — — — — — 23 22 21 20 19 18 17 16 11 10 9 8 WPVSRC 15 14 13 12 WPVSRC 7 6 5 4 3 2 1 0 — — — — — — — WPVS • WPVS: Write Protect Violation Status 0 = No Write Protect Violation has occurred since the last read of the US_WPSR register. 1 = A Write Protect Violation has occurred since the last read of the US_WPSR register. If this violation is an unauthorized attempt to write a protected register, the associated violation is reported into field WPVSRC. • WPVSRC: Write Protect Violation Source When WPVS is active, this field indicates the write-protected register (through address offset or code) in which a write access has been attempted. Note: Reading US_WPSR automatically clears all fields. 656 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 32. Timer Counter (TC) 32.1 Description A Timer Counter (TC) module includes three identical TC channels. The number of implemented TC modules is device-specific. Each TC 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 embeds a quadrature decoder (QDEC) connected in front of the timers and driven by TIOA0, TIOB0 and TIOB1 inputs. When enabled, the QDEC performs the input lines filtering, decoding of quadrature signals and connects to the timers/counters in order to read the position and speed of the motor through the user interface. The TC block has two global registers which act upon all TC channels: 32.2 Block Control Register (TC_BCR)—allows channels to be started simultaneously with the same instruction Block Mode Register (TC_BMR)—defines the external clock inputs for each channel, allowing them to be chained Embedded Characteristics Total number of TC channels: 6 TC channel size: 16-bit Wide range of functions including: ̶ Frequency measurement ̶ Event counting ̶ Interval measurement ̶ Pulse generation ̶ Delay timing ̶ Pulse Width Modulation ̶ Up/down capabilities ̶ Quadrature decoder ̶ 2-bit gray up/down count for stepper motor Each channel is user-configurable and contains: ̶ Three external clock inputs ̶ Five Internal clock inputs ̶ Two multi-purpose input/output signals acting as trigger event Internal interrupt signal Read of the Capture registers by the PDC Compare event fault generation for PWM Register Write Protection SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 657 32.3 Block Diagram Table 32-1. Timer Counter Clock Assignment Name Definition TIMER_CLOCK1 MCK/2 TIMER_CLOCK2 MCK/8 TIMER_CLOCK3 MCK/32 TIMER_CLOCK4 MCK/128 TIMER_CLOCK5 SLCK Note: Figure 32-1. 1. When SLCK is selected for Peripheral Clock (CSS = 0 in PMC Master Clock Register), SLCK input is equivalent to Peripheral Clock. Timer Counter Block Diagram Parallel I/O Controller TIMER_CLOCK1 TCLK0 TIMER_CLOCK2 TIOA1 TIOA2 TIMER_CLOCK3 XC0 TCLK1 TIMER_CLOCK4 Timer/Counter Channel 0 XC1 TIOA TIOA0 TIOB0 TIOA0 TIOB TCLK2 TIOB0 XC2 TIMER_CLOCK5 TC0XC0S SYNC TCLK0 TCLK1 TCLK2 INT0 TCLK0 TCLK1 XC0 TIOA0 XC1 TIOA2 XC2 Timer/Counter Channel 1 TIOA TIOA1 TIOB1 TIOA1 TIOB TCLK2 TIOB1 SYNC TC1XC1S TCLK0 XC0 TCLK1 XC1 Timer/Counter Channel 2 INT1 TIOA TIOA2 TIOB2 TIOA2 TIOB TCLK2 XC2 TIOB2 TIOA0 TIOA1 SYNC TC2XC2S INT2 FAULT Timer Counter PWM Note: The QDEC connections are detailed in Figure 32-16. 658 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Interrupt Controller Table 32-2. Signal Name Description Block/Channel Signal Name XC0, XC1, XC2 Channel Signal 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 SYNC 32.4 Description Interrupt Signal Output (internal signal) Synchronization Input Signal (from configuration register) Pin Name List Table 32-3. TC Pin List Pin Name Description Type TCLK0–TCLK2 External Clock Input Input TIOA0–TIOA2 I/O Line A I/O TIOB0–TIOB2 I/O Line B I/O SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 659 32.5 Product Dependencies 32.5.1 I/O Lines The pins used for interfacing the compliant external devices may be multiplexed with PIO lines. The programmer must first program the PIO controllers to assign the TC pins to their peripheral functions. Table 32-4. I/O Lines Instance Signal I/O Line Peripheral TC0 TCLK0 PA4 B TC0 TCLK1 PA28 B TC0 TCLK2 PA29 B TC0 TIOA0 PA0 B TC0 TIOA1 PA15 B TC0 TIOA2 PA26 B TC0 TIOB0 PA1 B TC0 TIOB1 PA16 B TC0 TIOB2 PA27 B TC1 TCLK3 PC25 B TC1 TCLK4 PC28 B TC1 TCLK5 PC31 B TC1 TIOA3 PC23 B TC1 TIOA4 PC26 B TC1 TIOA5 PC29 B TC1 TIOB3 PC24 B TC1 TIOB4 PC27 B TC1 TIOB5 PC30 B 32.5.2 Power Management The TC is clocked through the Power Management Controller (PMC), thus the programmer must first configure the PMC to enable the Timer Counter clock of each channel. 32.5.3 Interrupt Sources The TC has an interrupt line per channel connected to the interrupt controller. Handling the TC interrupt requires programming the interrupt controller before configuring the TC. Table 32-5. Peripheral IDs Instance ID TC0 23 TC1 24 32.5.4 Fault Output The TC has the FAULT output internally connected to the fault input of PWM. Refer to Section 32.6.17 “Fault Mode” and to the implementation of the Pulse Width Modulation (PWM) in this product. 660 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 32.6 Functional Description 32.6.1 Description All channels of the Timer Counter are independent and identical in operation except when the QDEC is enabled. The registers for channel programming are listed in Table 32-6, “Register Mapping,”. 32.6.2 16-bit Counter Each 16-bit 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 216-1 and passes to zero, an overflow occurs and the COVFS bit in the TC Status Register (TC_SR) is set. The current value of the counter is accessible in real time by reading the TC Counter Value Register (TC_CV). The counter can be reset by a trigger. In this case, the counter value passes to zero on the next valid edge of the selected clock. 32.6.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 internal I/O signals TIOA0, TIOA1 or TIOA2 for chaining by programming the TC Block Mode Register (TC_BMR). See Figure 32-2. Each channel can independently select an internal or external clock source for its counter: External clock signals(1): XC0, XC1 or XC2 Internal clock signals: MCK/2, MCK/8, MCK/32, MCK/128, SLCK This selection is made by the TCCLKS bits in the TC Channel Mode Register (TC_CMR). The selected clock can be inverted with the CLKI bit in the TC_CMR. 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 parameter in the TC_CMR defines this signal (none, XC0, XC1, XC2). See Figure 32-3. Note: 1. In all cases, if an external clock is used, the duration of each of its levels must be longer than the peripheral clock period. The external clock frequency must be at least 2.5 times lower than the peripheral clock. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 661 Figure 32-2. Clock Chaining Selection TC0XC0S Timer/Counter Channel 0 TCLK0 TIOA1 XC0 TIOA2 TIOA0 XC1 = TCLK1 XC2 = TCLK2 TIOB0 SYNC TC1XC1S Timer/Counter Channel 1 TCLK1 XC0 = TCLK0 TIOA0 TIOA1 XC1 TIOA2 XC2 = TCLK2 TIOB1 SYNC Timer/Counter Channel 2 TC2XC2S XC0 = TCLK0 TCLK2 TIOA2 XC1 = TCLK1 TIOA0 XC2 TIOB2 TIOA1 SYNC Figure 32-3. Clock Selection TCCLKS CLKI TIMER_CLOCK1 Synchronous Edge Detection TIMER_CLOCK2 TIMER_CLOCK3 Selected Clock TIMER_CLOCK4 TIMER_CLOCK5 XC0 XC1 XC2 Peripheral Clock BURST 1 662 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 32.6.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 32-4. The clock can be enabled or disabled by the user with the CLKEN and the CLKDIS commands in the TC Channel Control Register (TC_CCR). In Capture mode it can be disabled by an RB load event if LDBDIS is set to 1 in the TC_CMR. In Waveform mode, it can be disabled by an RC Compare event if CPCDIS is set to 1 in TC_CMR. When disabled, the start or the stop actions have no effect: only a CLKEN command in the TC_CCR can re-enable the clock. When the clock is enabled, the CLKSTA bit is set in the TC_SR. The clock can also be started or stopped: a trigger (software, synchro, external or compare) always starts the clock. The clock can be stopped by an RB load event in Capture mode (LDBSTOP = 1 in TC_CMR) or an RC compare event in Waveform mode (CPCSTOP = 1 in TC_CMR). The start and the stop commands are effective only if the clock is enabled. Figure 32-4. Clock Control Selected Clock Trigger CLKSTA CLKEN Q Q CLKDIS S R S R Stop Event Counter Clock Disable Event 32.6.5 Operating Modes Each channel can operate independently in two different modes: Capture mode provides measurement on signals. Waveform mode provides wave generation. The TC operating mode is programmed with the WAVE bit in the TC_CMR. In Capture mode, TIOA and TIOB are configured as inputs. 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. 32.6.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. 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. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 663 The following triggers are common to both modes: Software Trigger: Each channel has a software trigger, available by setting SWTRG in TC_CCR. 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 TC_BCR (Block Control) with SYNC set. Compare RC Trigger: RC is implemented in each channel and can provide a trigger when the counter value matches the RC value if CPCTRG is set in the TC_CMR. 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 on one of the following signals: TIOB, XC0, XC1 or XC2. This external event can then be programmed to perform a trigger by setting bit ENETRG in the TC_CMR. If an external trigger is used, the duration of the pulses must be longer than the peripheral clock period in order to be detected. 32.6.7 Capture Mode Capture mode is entered by clearing the WAVE bit in the TC_CMR. 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 32-6 shows the configuration of the TC channel when programmed in Capture mode. 32.6.8 Capture Registers A and B Registers A and B (RA and RB) are used as capture registers. They can be loaded with the counter value when a programmable event occurs on the signal TIOA. The LDRA field in the TC_CMR defines the TIOA selected edge for the loading of register A, and the LDRB field defines the TIOA selected edge for the loading of Register B. 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 Overrun Error Flag (LOVRS bit) in the TC_SR. In this case, the old value is overwritten. 32.6.9 Transfer with PDC The PDC can only perform access from timer to system memory. Figure 32-5 illustrates how TC_RA and TC_RB can be loaded in the system memory without CPU intervention. 664 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Figure 32-5. Example of Transfer with PDC ETRGEDG = 1, LDRA = 1, LDRB = 2, ABETRG = 0 TIOB TIOA RA RB Peripheral trigger Transfer to System Memory RA RB RA RB T1 T2 T3 T4 T1,T2,T3,T4 = System Bus load dependent (tmin = 8 peripheral clocks) ETRGEDG = 3, LDRA = 3, LDRB = 0, ABETRG = 0 TIOB TIOA RA Peripheral trigger Transfer to System Memory RA RA RA RA T1 T2 T3 T4 T1,T2,T3,T4 = System Bus load dependent (tmin = 8 peripheral clocks) 32.6.10 Trigger Conditions In addition to the SYNC signal, the software trigger and the RC compare trigger, an external trigger can be defined. The ABETRG bit in the TC_CMR selects TIOA or TIOB input signal as an external trigger . The External Trigger Edge Selection parameter (ETRGEDG field in TC_CMR) defines the edge (rising, falling, or both) detected to generate an external trigger. If ETRGEDG = 0 (none), the external trigger is disabled. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 665 666 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 MTIOA MTIOB 1 ABETRG CLKI If RA is not loaded or RB is Loaded Edge Detector ETRGEDG SWTRG Timer/Counter Channel BURST Peripheral Clock Synchronous Edge Detection S R OVF LDRB Edge Detector Edge Detector Capture Register A LDBSTOP R S CLKEN LDRA If RA is Loaded CPCTRG Counter RESET Trig CLK Q Q CLKSTA LDBDIS Capture Register B CLKDIS TC1_SR TIOA TIOB SYNC XC2 XC1 XC0 TIMER_CLOCK5 TIMER_CLOCK4 TIMER_CLOCK3 TIMER_CLOCK2 TIMER_CLOCK1 TCCLKS Compare RC = Register C COVFS LDRBS INT Figure 32-6. Capture Mode LOVRS CPCS ETRGS LDRAS TC1_IMR 32.6.11 Waveform Mode Waveform mode is entered by setting the TC_CMRx.WAVE bit. In Waveform mode, the TC channel generates one or two PWM signals with the same frequency and independently programmable duty cycles, or generates different types of one-shot 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 (EEVT parameter in TC_CMR). Figure 32-7 shows the configuration of the TC channel when programmed in Waveform operating mode. 32.6.12 Waveform Selection Depending on the WAVSEL parameter in TC_CMR, the behavior of TC_CV varies. With any selection, TC_RA, TC_RB and TC_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. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 667 668 1 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 EEVT BURST ENETRG CLKI Timer/Counter Channel Edge Detector EEVTEDG SWTRG Peripheral Clock Synchronous Edge Detection Trig CLK R S OVF WAVSEL RESET Counter WAVSEL Q Compare RA = Register A Q CLKSTA Compare RC = Compare RB = CPCSTOP CPCDIS Register C CLKDIS Register B R S CLKEN CPAS INT BSWTRG BEEVT BCPB BCPC ASWTRG AEEVT ACPA ACPC Output Controller TIOB SYNC XC2 XC1 XC0 TIMER_CLOCK5 TIMER_CLOCK4 TIMER_CLOCK3 TIMER_CLOCK2 TIMER_CLOCK1 TCCLKS TIOB MTIOB TIOA MTIOA Figure 32-7. Waveform Mode Output Controller CPCS CPBS COVFS TC1_SR ETRGS TC1_IMR 32.6.12.1 WAVSEL = 00 When WAVSEL = 00, the value of TC_CV is incremented from 0 to 216-1. Once 216-1 has been reached, the value of TC_CV is reset. Incrementation of TC_CV starts again and the cycle continues. See Figure 32-8. An external event trigger or a software trigger can reset the value of TC_CV. It is important to note that the trigger may occur at any time. See Figure 32-9. RC Compare cannot be programmed to generate a trigger in this configuration. At the same time, RC Compare can stop the counter clock (CPCSTOP = 1 in TC_CMR) and/or disable the counter clock (CPCDIS = 1 in TC_CMR). Figure 32-8. WAVSEL = 00 without trigger Counter Value Counter cleared by compare match with 0xFFFF 0xFFFF RC RB RA Time Waveform Examples TIOB TIOA Figure 32-9. WAVSEL = 00 with Trigger Counter Value Counter cleared by compare match with 0xFFFF 0xFFFF RC Counter cleared by trigger RB RA Waveform Examples Time TIOB TIOA SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 669 32.6.12.2 WAVSEL = 10 When WAVSEL = 10, the value of TC_CV is incremented from 0 to the value of RC, then automatically reset on a RC Compare. Once the value of TC_CV has been reset, it is then incremented and so on. See Figure 32-10. It is important to note that TC_CV can be reset at any time by an external event or a software trigger if both are programmed correctly. See Figure 32-11. In addition, RC Compare can stop the counter clock (CPCSTOP = 1 in TC_CMR) and/or disable the counter clock (CPCDIS = 1 in TC_CMR). Figure 32-10. WAVSEL = 10 without Trigger Counter Value 2n-1 (n = counter size) Counter cleared by compare match with RC RC RB RA Waveform Examples Time TIOB TIOA Figure 32-11. WAVSEL = 10 with Trigger Counter Value 2n-1 (n = counter size) Counter cleared by compare match with RC Counter cleared by trigger RC RB RA Waveform Examples TIOB TIOA 670 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Time 32.6.12.3 WAVSEL = 01 When WAVSEL = 01, the value of TC_CV is incremented from 0 to 216-1 . Once 216-1 is reached, the value of TC_CV is decremented to 0, then re-incremented to 216-1 and so on. See Figure 32-12. A trigger such as an external event or a software trigger can modify TC_CV at any time. If a trigger occurs while TC_CV is incrementing, TC_CV then decrements. If a trigger is received while TC_CV is decrementing, TC_CV then increments. See Figure 32-13. RC Compare cannot be programmed to generate a trigger in this configuration. At the same time, RC Compare can stop the counter clock (CPCSTOP = 1) and/or disable the counter clock (CPCDIS = 1). Figure 32-12. WAVSEL = 01 without Trigger Counter Value Counter decremented by compare match with 0xFFFF 0xFFFF RC RB RA Time Waveform Examples TIOB TIOA Figure 32-13. WAVSEL = 01 with Trigger Counter Value Counter decremented by compare match with 0xFFFF 0xFFFF Counter decremented by trigger RC RB Counter incremented by trigger RA Waveform Examples Time TIOB TIOA SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 671 32.6.12.4 WAVSEL = 11 When WAVSEL = 11, the value of TC_CV is incremented from 0 to RC. Once RC is reached, the value of TC_CV is decremented to 0, then re-incremented to RC and so on. See Figure 32-14. A trigger such as an external event or a software trigger can modify TC_CV at any time. If a trigger occurs while TC_CV is incrementing, TC_CV then decrements. If a trigger is received while TC_CV is decrementing, TC_CV then increments. See Figure 32-15. RC Compare can stop the counter clock (CPCSTOP = 1) and/or disable the counter clock (CPCDIS = 1). Figure 32-14. WAVSEL = 11 without Trigger Counter Value 2n-1 (n = counter size) Counter decremented by compare match with RC RC RB RA Time Waveform Examples TIOB TIOA Figure 32-15. WAVSEL = 11 with Trigger Counter Value 2n-1 (n = counter size) Counter decremented by compare match with RC RC RB Counter decremented by trigger Counter incremented by trigger RA Waveform Examples TIOB TIOA 672 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Time 32.6.13 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 EEVT parameter in TC_CMR selects the external trigger. The EEVTEDG parameter defines the trigger edge for each of the possible external triggers (rising, falling or both). If EEVTEDG is cleared (none), no external event is defined. If TIOB is defined as an external event signal (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 setting bit ENETRG in the TC_CMR. 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 parameter WAVSEL. 32.6.14 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 and 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 corresponding parameter in TC_CMR. 32.6.15 Quadrature Decoder 32.6.15.1 Description The quadrature decoder (QDEC) is driven by TIOA0, TIOB0, TIOB1 input pins and drives the timer/counter of channel 0 and 1. Channel 2 can be used as a time base in case of speed measurement requirements (refer to Figure 32-16). When writing a 0 to bit QDEN of the TC_BMR, the QDEC is bypassed and the IO pins are directly routed to the timer counter function. See TIOA0 and TIOB0 are to be driven by the two dedicated quadrature signals from a rotary sensor mounted on the shaft of the off-chip motor. A third signal from the rotary sensor can be processed through pin TIOB1 and is typically dedicated to be driven by an index signal if it is provided by the sensor. This signal is not required to decode the quadrature signals PHA, PHB. Field TCCLKS of TC_CMRx must be configured to select XC0 input (i.e., 0x101). Field TC0XC0S has no effect as soon as the QDEC is enabled. Either speed or position/revolution can be measured. Position channel 0 accumulates the edges of PHA, PHB input signals giving a high accuracy on motor position whereas channel 1 accumulates the index pulses of the sensor, therefore the number of rotations. Concatenation of both values provides a high level of precision on motion system position. In Speed mode, position cannot be measured but revolution can be measured. Inputs from the rotary sensor can be filtered prior to down-stream processing. Accommodation of input polarity, phase definition and other factors are configurable. Interruptions can be generated on different events. A compare function (using TC_RC) is available on channel 0 (speed/position) or channel 1 (rotation) and can generate an interrupt by means of the CPCS flag in the TC_SRx. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 673 Figure 32-16. Predefined Connection of the Quadrature Decoder with Timer Counters Reset pulse SPEEDEN Quadrature Decoder 1 1 (Filter + Edge Detect + QD) TIOA Timer/Counter Channel 0 TIOA0 QDEN PHEdges 1 TIOB 1 XC0 TIOB0 TIOA0 PHA TIOB0 PHB TIOB1 IDX XC0 Speed/Position QDEN Index 1 TIOB TIOB1 1 XC0 Timer/Counter Channel 1 XC0 Rotation Direction Timer/Counter Channel 2 Speed Time Base 32.6.15.2 Input Pre-processing Input pre-processing consists of capabilities to take into account rotary sensor factors such as polarities and phase definition followed by configurable digital filtering. Each input can be negated and swapping PHA, PHB is also configurable. The MAXFILT field in the TC_BMR is used to configure a minimum duration for which the pulse is stated as valid. When the filter is active, pulses with a duration lower than MAXFILT +1 × tperipheral clock ns are not passed to downstream logic. 674 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Figure 32-17. Input Stage Input Pre-Processing MAXFILT SWAP 1 PHA Filter TIOA0 MAXFILT > 0 1 PHedge Direction and Edge Detection INVA 1 PHB Filter TIOB0 1 DIR 1 IDX INVB 1 1 IDX Filter TIOB1 IDXPHB INVIDX Input filtering can efficiently remove spurious pulses that might be generated by the presence of particulate contamination on the optical or magnetic disk of the rotary sensor. Spurious pulses can also occur in environments with high levels of electro-magnetic interference. Or, simply if vibration occurs even when rotation is fully stopped and the shaft of the motor is in such a position that the beginning of one of the reflective or magnetic bars on the rotary sensor disk is aligned with the light or magnetic (Hall) receiver cell of the rotary sensor. Any vibration can make the PHA, PHB signals toggle for a short duration. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 675 Figure 32-18. Filtering Examples MAXFILT = 2 Peripheral Clock particulate contamination PHA,B Filter Out Optical/Magnetic disk strips PHA PHB motor shaft stopped in such a position that rotary sensor cell is aligned with an edge of the disk rotation stop PHA PHB Edge area due to system vibration PHB Resulting PHA, PHB electrical waveforms PHA stop mechanical shock on system PHB vibration PHA, PHB electrical waveforms after filtering PHA PHB 676 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 32.6.15.3 Direction Status and Change Detection After filtering, the quadrature signals are analyzed to extract the rotation direction and edges of the two quadrature signals detected in order to be counted by timer/counter logic downstream. The direction status can be directly read at anytime in the TC_QISR. The polarity of the direction flag status depends on the configuration written in TC_BMR. INVA, INVB, INVIDX, SWAP modify the polarity of DIR flag. Any change in rotation direction is reported in the TC_QISR and can generate an interrupt. The direction change condition is reported as soon as two consecutive edges on a phase signal have sampled the same value on the other phase signal and there is an edge on the other signal. The two consecutive edges of one phase signal sampling the same value on other phase signal is not sufficient to declare a direction change, for the reason that particulate contamination may mask one or more reflective bars on the optical or magnetic disk of the sensor. Refer to Figure 32-19 for waveforms. Figure 32-19. Rotation Change Detection Direction Change under normal conditions PHA change condition Report Time PHB DIR DIRCHG No direction change due to particulate contamination masking a reflective bar missing pulse PHA same phase PHB DIR spurious change condition (if detected in a simple way) DIRCHG The direction change detection is disabled when QDTRANS is set in the TC_BMR. In this case, the DIR flag report must not be used. A quadrature error is also reported by the QDEC via the QERR flag in the TC_QISR. This error is reported if the time difference between two edges on PHA, PHB is lower than a predefined value. This predefined value is SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 677 configurable and corresponds to (MAXFILT + 1) × tperipheral clock ns. After being filtered there is no reason to have two edges closer than (MAXFILT + 1) × tperipheral clock ns under normal mode of operation. Figure 32-20. Quadrature Error Detection MAXFILT = 2 Peripheral Clock Abnormally formatted optical disk strips (theoretical view) PHA PHB strip edge inaccurary due to disk etching/printing process PHA PHB resulting PHA, PHB electrical waveforms PHA Even with an abnorrmaly formatted disk, there is no occurence of PHA, PHB switching at the same time. PHB duration < MAXFILT QERR MAXFILT must be tuned according to several factors such as the peripheral clock frequency, type of rotary sensor and rotation speed to be achieved. 32.6.15.4 Position and Rotation Measurement When the POSEN bit is set in the TC_BMR, the motor axis position is processed on channel 0 (by means of the PHA, PHB edge detections) and the number of motor revolutions are recorded on channel 1 if the IDX signal is provided on the TIOB1 input. The position measurement can be read in the TC_CV0 register and the rotation measurement can be read in the TC_CV1 register. Channel 0 and 1 must be configured in Capture mode (TC_CMR0.WAVE = 0). ‘Rising edge’ must be selected as the External Trigger Edge (TC_CMR.ETRGEDG = 0x01) and ‘TIOA’ must be selected as the External Trigger (TC_CMR.ABETRG = 0x1). In parallel, the number of edges are accumulated on timer/counter channel 0 and can be read on the TC_CV0 register. Therefore, the accurate position can be read on both TC_CV registers and concatenated to form a 32-bit word. The timer/counter channel 0 is cleared for each increment of IDX count value. 678 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Depending on the quadrature signals, the direction is decoded and allows to count up or down in timer/counter channels 0 and 1. The direction status is reported on TC_QISR. 32.6.15.5 Speed Measurement When SPEEDEN is set in the TC_BMR, the speed measure is enabled on channel 0. A time base must be defined on channel 2 by writing the TC_RC2 period register. Channel 2 must be configured in Waveform mode (WAVE bit set) in TC_CMR2. The WAVSEL field must be defined with 0x10 to clear the counter by comparison and matching with TC_RC value. Field ACPC must be defined at 0x11 to toggle TIOA output. This time base is automatically fed back to TIOA of channel 0 when QDEN and SPEEDEN are set. Channel 0 must be configured in Capture mode (WAVE = 0 in TC_CMR0). The ABETRG bit of TC_CMR0 must be configured at 1 to select TIOA as a trigger for this channel. EDGTRG must be set to 0x01, to clear the counter on a rising edge of the TIOA signal and field LDRA must be set accordingly to 0x01, to load TC_RA0 at the same time as the counter is cleared (LDRB must be set to 0x01). As a consequence, at the end of each time base period the differentiation required for the speed calculation is performed. The process must be started by configuring bits CLKEN and SWTRG in the TC_CCR. The speed can be read on field RA in TC_RA0. Channel 1 can still be used to count the number of revolutions of the motor. 32.6.16 2-bit Gray Up/Down Counter for Stepper Motor Each channel can be independently configured to generate a 2-bit gray count waveform on corresponding TIOA, TIOB outputs by means of the GCEN bit in TC_SMMRx. Up or Down count can be defined by writing bit DOWN in TC_SMMRx. It is mandatory to configure the channel in Waveform mode in the TC_CMR. The period of the counters can be programmed in TC_RCx. Figure 32-21. 2-bit Gray Up/Down Counter WAVEx = GCENx =1 TIOAx TC_RCx TIOBx DOWNx 32.6.17 Fault Mode At any time, the TC_RCx registers can be used to perform a comparison on the respective current channel counter value (TC_CVx) with the value of TC_RCx register. The CPCSx flags can be set accordingly and an interrupt can be generated. This interrupt is processed but requires an unpredictable amount of time to be achieve the required action. It is possible to trigger the FAULT output of the TIMER1 with CPCS from TC_SR0 and/or CPCS from TC_SR1. Each source can be independently enabled/disabled in the TC_FMR. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 679 This can be useful to detect an overflow on speed and/or position when QDEC is processed and to act immediately by using the FAULT output. Figure 32-22. Fault Output Generation AND TC_SR0 flag CPCS OR TC_FMR / ENCF0 AND FAULT (to PWM input) TC_SR1 flag CPCS TC_FMR / ENCF1 32.6.18 Register Write Protection To prevent any single software error from corrupting TC behavior, certain registers in the address space can be write-protected by setting the WPEN bit in the TC Write Protection Mode Register (TC_WPMR). The Timer Counter clock of the first channel must be enabled to access TC_WPMR. The following registers can be write-protected: 680 TC Block Mode Register TC Channel Mode Register: Capture Mode TC Channel Mode Register: Waveform Mode TC Fault Mode Register TC Stepper Motor Mode Register TC Register A TC Register B TC Register C SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 32.7 Timer Counter (TC) User Interface Table 32-6. Register Mapping Offset(1) Register Name Access Reset 0x00 + channel * 0x40 + 0x00 Channel Control Register TC_CCR Write-only – 0x00 + channel * 0x40 + 0x04 Channel Mode Register TC_CMR Read/Write 0 0x00 + channel * 0x40 + 0x08 Stepper Motor Mode Register TC_SMMR Read/Write 0 0x00 + channel * 0x40 + 0x0C Reserved – – – 0x00 + channel * 0x40 + 0x10 Counter Value TC_CV 0x00 + channel * 0x40 + 0x14 Register A TC_RA Read-only Read/Write 0 (2) 0 (2) 0 0x00 + channel * 0x40 + 0x18 Register B TC_RB 0x00 + channel * 0x40 + 0x1C Register C TC_RC Read/Write 0 0x00 + channel * 0x40 + 0x20 Status Register TC_SR Read-only 0 0x00 + channel * 0x40 + 0x24 Interrupt Enable Register TC_IER Write-only – 0x00 + channel * 0x40 + 0x28 Interrupt Disable Register TC_IDR Write-only – 0x00 + channel * 0x40 + 0x2C Interrupt Mask Register TC_IMR Read-only 0 0xC0 Block Control Register TC_BCR Write-only – 0xC4 Block Mode Register TC_BMR Read/Write 0 0xC8 QDEC Interrupt Enable Register TC_QIER Write-only – 0xCC QDEC Interrupt Disable Register TC_QIDR Write-only – 0xD0 QDEC Interrupt Mask Register TC_QIMR Read-only 0 0xD4 QDEC Interrupt Status Register TC_QISR Read-only 0 0xD8 Fault Mode Register TC_FMR Read/Write 0 0xE4 Write Protection Mode Register TC_WPMR Read/Write 0 Reserved – – – Reserved for PDC Registers – – – 0xE8–0xFC 0x100–0x1A4 Notes: Read/Write 1. Channel index ranges from 0 to 2. 2. Read-only if TC_CMRx.WAVE = 0 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 681 32.7.1 TC Channel Control Register Name: TC_CCRx [x=0..2] Address: 0x40010000 (0)[0], 0x40010040 (0)[1], 0x40010080 (0)[2], 0x40014000 (1)[0], 0x40014040 (1)[1], 0x40014080 (1)[2] Access: Write-only 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 – 6 – 5 – 4 – 3 – 2 SWTRG 1 CLKDIS 0 CLKEN • CLKEN: Counter Clock Enable Command 0: No effect. 1: Enables the clock if CLKDIS is not 1. • CLKDIS: Counter Clock Disable Command 0: No effect. 1: Disables the clock. • SWTRG: Software Trigger Command 0: No effect. 1: A software trigger is performed: the counter is reset and the clock is started. 682 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 32.7.2 TC Channel Mode Register: Capture Mode Name: TC_CMRx [x=0..2] (CAPTURE_MODE) Address: 0x40010004 (0)[0], 0x40010044 (0)[1], 0x40010084 (0)[2], 0x40014004 (1)[0], 0x40014044 (1)[1], 0x40014084 (1)[2] Access: Read/Write 31 – 30 – 29 – 28 – 27 – 26 – 25 – 18 17 24 – 23 – 22 – 21 – 20 – 19 15 WAVE 14 CPCTRG 13 – 12 – 11 – 10 ABETRG 9 7 LDBDIS 6 LDBSTOP 5 4 3 CLKI 2 1 TCCLKS 16 LDRB BURST LDRA 8 ETRGEDG 0 This register can only be written if the WPEN bit is cleared in the TC Write Protection Mode Register. • TCCLKS: Clock Selection Value Name Description 0 TIMER_CLOCK1 Clock selected: internal MCK/2 clock signal (from PMC) 1 TIMER_CLOCK2 Clock selected: internal MCK/8 clock signal (from PMC) 2 TIMER_CLOCK3 Clock selected: internal MCK/32 clock signal (from PMC) 3 TIMER_CLOCK4 Clock selected: internal MCK/128 clock signal (from PMC) 4 TIMER_CLOCK5 Clock selected: internal SLCK clock signal (from PMC) 5 XC0 Clock selected: XC0 6 XC1 Clock selected: XC1 7 XC2 Clock selected: XC2 • CLKI: Clock Invert 0: Counter is incremented on rising edge of the clock. 1: Counter is incremented on falling edge of the clock. • BURST: Burst Signal Selection Value Name Description 0 NONE The clock is not gated by an external signal. 1 XC0 XC0 is ANDed with the selected clock. 2 XC1 XC1 is ANDed with the selected clock. 3 XC2 XC2 is ANDed with the selected clock. • LDBSTOP: Counter Clock Stopped with RB Loading 0: Counter clock is not stopped when RB loading occurs. 1: Counter clock is stopped when RB loading occurs. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 683 • LDBDIS: Counter Clock Disable with RB Loading 0: Counter clock is not disabled when RB loading occurs. 1: Counter clock is disabled when RB loading occurs. • ETRGEDG: External Trigger Edge Selection Value Name Description 0 NONE The clock is not gated by an external signal. 1 RISING Rising edge 2 FALLING Falling edge 3 EDGE Each edge • ABETRG: TIOA or TIOB External Trigger Selection 0: TIOB is used as an external trigger. 1: TIOA is used as an external trigger. • CPCTRG: RC Compare Trigger Enable 0: RC Compare has no effect on the counter and its clock. 1: RC Compare resets the counter and starts the counter clock. • WAVE: Waveform Mode 0: Capture mode is enabled. 1: Capture mode is disabled (Waveform mode is enabled). • LDRA: RA Loading Edge Selection Value Name Description 0 NONE None 1 RISING Rising edge of TIOA 2 FALLING Falling edge of TIOA 3 EDGE Each edge of TIOA • LDRB: RB Loading Edge Selection 684 Value Name Description 0 NONE None 1 RISING Rising edge of TIOA 2 FALLING Falling edge of TIOA 3 EDGE Each edge of TIOA SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 32.7.3 TC Channel Mode Register: Waveform Mode Name: TC_CMRx [x=0..2] (WAVEFORM_MODE) Access: Read/Write 31 30 29 BSWTRG 23 28 27 BEEVT 22 20 19 AEEVT 15 WAVE 14 13 7 CPCDIS 6 CPCSTOP WAVSEL 25 24 BCPC 21 ASWTRG 26 BCPB 18 17 16 ACPC 12 ENETRG 11 4 3 CLKI 5 BURST ACPA 10 9 EEVT 8 EEVTEDG 2 1 TCCLKS 0 This register can only be written if the WPEN bit is cleared in the TC Write Protection Mode Register. • TCCLKS: Clock Selection Value Name Description 0 TIMER_CLOCK1 Clock selected: internal MCK/2 clock signal (from PMC) 1 TIMER_CLOCK2 Clock selected: internal MCK/8 clock signal (from PMC) 2 TIMER_CLOCK3 Clock selected: internal MCK/32 clock signal (from PMC) 3 TIMER_CLOCK4 Clock selected: internal MCK/128 clock signal (from PMC) 4 TIMER_CLOCK5 Clock selected: internal SLCK clock signal (from PMC) 5 XC0 Clock selected: XC0 6 XC1 Clock selected: XC1 7 XC2 Clock selected: XC2 • CLKI: Clock Invert 0: Counter is incremented on rising edge of the clock. 1: Counter is incremented on falling edge of the clock. • BURST: Burst Signal Selection Value Name Description 0 NONE The clock is not gated by an external signal. 1 XC0 XC0 is ANDed with the selected clock. 2 XC1 XC1 is ANDed with the selected clock. 3 XC2 XC2 is ANDed with the selected clock. • CPCSTOP: Counter Clock Stopped with RC Compare 0: Counter clock is not stopped when counter reaches RC. 1: Counter clock is stopped when counter reaches RC. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 685 • CPCDIS: Counter Clock Disable with RC Compare 0: Counter clock is not disabled when counter reaches RC. 1: Counter clock is disabled when counter reaches RC. • EEVTEDG: External Event Edge Selection Value Name Description 0 NONE None 1 RISING Rising edge 2 FALLING Falling edge 3 EDGE Each edge • EEVT: External Event Selection Signal selected as external event. Value Note: Name Description 0 TIOB (1) TIOB Direction TIOB Input 1 XC0 XC0 Output 2 XC1 XC1 Output 3 XC2 XC2 Output 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. • ENETRG: External Event Trigger Enable 0: The external event has no effect on the counter and its clock. 1: The external event resets the counter and starts the counter clock. Note: Whatever the value programmed in ENETRG, the selected external event only controls the TIOA output and TIOB if not used as input (trigger event input or other input used). • WAVSEL: Waveform Selection Value Name Description 0 UP UP mode without automatic trigger on RC Compare 1 UPDOWN UPDOWN mode without automatic trigger on RC Compare 2 UP_RC UP mode with automatic trigger on RC Compare 3 UPDOWN_RC UPDOWN mode with automatic trigger on RC Compare • WAVE: Waveform Mode 0: Waveform mode is disabled (Capture mode is enabled). 1: Waveform mode is enabled. • ACPA: RA Compare Effect on TIOA 686 Value Name Description 0 NONE None 1 SET Set 2 CLEAR Clear 3 TOGGLE Toggle SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 • ACPC: RC Compare Effect on TIOA Value Name Description 0 NONE None 1 SET Set 2 CLEAR Clear 3 TOGGLE Toggle • AEEVT: External Event Effect on TIOA Value Name Description 0 NONE None 1 SET Set 2 CLEAR Clear 3 TOGGLE Toggle • ASWTRG: Software Trigger Effect on TIOA Value Name Description 0 NONE None 1 SET Set 2 CLEAR Clear 3 TOGGLE Toggle • BCPB: RB Compare Effect on TIOB Value Name Description 0 NONE None 1 SET Set 2 CLEAR Clear 3 TOGGLE Toggle • BCPC: RC Compare Effect on TIOB Value Name Description 0 NONE None 1 SET Set 2 CLEAR Clear 3 TOGGLE Toggle • BEEVT: External Event Effect on TIOB Value Name Description 0 NONE None 1 SET Set 2 CLEAR Clear 3 TOGGLE Toggle SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 687 • BSWTRG: Software Trigger Effect on TIOB 688 Value Name Description 0 NONE None 1 SET Set 2 CLEAR Clear 3 TOGGLE Toggle SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 32.7.4 TC Stepper Motor Mode Register Name: TC_SMMRx [x=0..2] Address: 0x40010008 (0)[0], 0x40010048 (0)[1], 0x40010088 (0)[2], 0x40014008 (1)[0], 0x40014048 (1)[1], 0x40014088 (1)[2] Access: Read/Write 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 – 6 – 5 – 4 – 3 – 2 – 1 DOWN 0 GCEN This register can only be written if the WPEN bit is cleared in the TC Write Protection Mode Register. • GCEN: Gray Count Enable 0: TIOAx [x=0..2] and TIOBx [x=0..2] are driven by internal counter of channel x. 1: TIOAx [x=0..2] and TIOBx [x=0..2] are driven by a 2-bit gray counter. • DOWN: Down Count 0: Up counter. 1: Down counter. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 689 32.7.5 TC Counter Value Register Name: TC_CVx [x=0..2] Address: 0x40010010 (0)[0], 0x40010050 (0)[1], 0x40010090 (0)[2], 0x40014010 (1)[0], 0x40014050 (1)[1], 0x40014090 (1)[2] Access: Read-only 31 30 29 28 27 26 25 24 19 18 17 16 11 10 9 8 3 2 1 0 CV 23 22 21 20 CV 15 14 13 12 CV 7 6 5 4 CV • CV: Counter Value CV contains the counter value in real time. IMPORTANT: For 16-bit channels, CV field size is limited to register bits 15:0. 690 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 32.7.6 TC Register A Name: TC_RAx [x=0..2] Address: 0x40010014 (0)[0], 0x40010054 (0)[1], 0x40010094 (0)[2], 0x40014014 (1)[0], 0x40014054 (1)[1], 0x40014094 (1)[2] Access: Read-only if TC_CMRx.WAVE = 0, Read/Write if TC_CMRx.WAVE = 1 31 30 29 28 27 26 25 24 19 18 17 16 11 10 9 8 3 2 1 0 RA 23 22 21 20 RA 15 14 13 12 RA 7 6 5 4 RA This register can only be written if the WPEN bit is cleared in the TC Write Protection Mode Register. • RA: Register A RA contains the Register A value in real time. IMPORTANT: For 16-bit channels, RA field size is limited to register bits 15:0. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 691 32.7.7 TC Register B Name: TC_RBx [x=0..2] Address: 0x40010018 (0)[0], 0x40010058 (0)[1], 0x40010098 (0)[2], 0x40014018 (1)[0], 0x40014058 (1)[1], 0x40014098 (1)[2] Access: Read-only if TC_CMRx.WAVE = 0, Read/Write if TC_CMRx.WAVE = 1 31 30 29 28 27 26 25 24 19 18 17 16 11 10 9 8 3 2 1 0 RB 23 22 21 20 RB 15 14 13 12 RB 7 6 5 4 RB This register can only be written if the WPEN bit is cleared in the TC Write Protection Mode Register. • RB: Register B RB contains the Register B value in real time. IMPORTANT: For 16-bit channels, RB field size is limited to register bits 15:0. 692 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 32.7.8 TC Register C Name: TC_RCx [x=0..2] Address: 0x4001001C (0)[0], 0x4001005C (0)[1], 0x4001009C (0)[2], 0x4001401C (1)[0], 0x4001405C (1)[1], 0x4001409C (1)[2] Access: Read/Write 31 30 29 28 27 26 25 24 19 18 17 16 11 10 9 8 3 2 1 0 RC 23 22 21 20 RC 15 14 13 12 RC 7 6 5 4 RC This register can only be written if the WPEN bit is cleared in the TC Write Protection Mode Register. • RC: Register C RC contains the Register C value in real time. IMPORTANT: For 16-bit channels, RC field size is limited to register bits 15:0. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 693 32.7.9 TC Status Register Name: TC_SRx [x=0..2] Address: 0x40010020 (0)[0], 0x40010060 (0)[1], 0x400100A0 (0)[2], 0x40014020 (1)[0], 0x40014060 (1)[1], 0x400140A0 (1)[2] Access: Read-only 31 – 30 – 29 – 28 – 27 – 26 – 25 – 24 – 23 – 22 – 21 – 20 – 19 – 18 MTIOB 17 MTIOA 16 CLKSTA 15 – 14 – 13 – 12 – 11 – 10 – 9 RXBUFF 8 ENDRX 7 ETRGS 6 LDRBS 5 LDRAS 4 CPCS 3 CPBS 2 CPAS 1 LOVRS 0 COVFS • COVFS: Counter Overflow Status (cleared on read) 0: No counter overflow has occurred since the last read of the Status Register. 1: A counter overflow has occurred since the last read of the Status Register. • LOVRS: Load Overrun Status (cleared on read) 0: Load overrun has not occurred since the last read of the Status Register or TC_CMRx.WAVE = 1. 1: RA or RB have been loaded at least twice without any read of the corresponding register since the last read of the Status Register, if TC_CMRx.WAVE = 0. • CPAS: RA Compare Status (cleared on read) 0: RA Compare has not occurred since the last read of the Status Register or TC_CMRx.WAVE = 0. 1: RA Compare has occurred since the last read of the Status Register, if TC_CMRx.WAVE = 1. • CPBS: RB Compare Status (cleared on read) 0: RB Compare has not occurred since the last read of the Status Register or TC_CMRx.WAVE = 0. 1: RB Compare has occurred since the last read of the Status Register, if TC_CMRx.WAVE = 1. • CPCS: RC Compare Status (cleared on read) 0: RC Compare has not occurred since the last read of the Status Register. 1: RC Compare has occurred since the last read of the Status Register. • LDRAS: RA Loading Status (cleared on read) 0: RA Load has not occurred since the last read of the Status Register or TC_CMRx.WAVE = 1. 1: RA Load has occurred since the last read of the Status Register, if TC_CMRx.WAVE = 0. • LDRBS: RB Loading Status (cleared on read) 0: RB Load has not occurred since the last read of the Status Register or TC_CMRx.WAVE = 1. 1: RB Load has occurred since the last read of the Status Register, if TC_CMRx.WAVE = 0. 694 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 • ETRGS: External Trigger Status (cleared on read) 0: External trigger has not occurred since the last read of the Status Register. 1: External trigger has occurred since the last read of the Status Register. • ENDRX: End of Receiver Transfer (cleared by writing TC_RCR or TC_RNCR) 0: The Receive Counter Register has not reached 0 since the last write in TC_RCR(1) or TC_RNCR(1). 1: The Receive Counter Register has reached 0 since the last write in TC_RCR or TC_RNCR. • RXBUFF: Reception Buffer Full (cleared by writing TC_RCR or TC_RNCR) 0: TC_RCR or TC_RNCR have a value other than 0. 1: Both TC_RCR and TC_RNCR have a value of 0. Note: 1. TC_RCR and TC_RNCR are PDC registers. • CLKSTA: Clock Enabling Status 0: Clock is disabled. 1: Clock is enabled. • MTIOA: TIOA Mirror 0: TIOA is low. If TC_CMRx.WAVE = 0, this means that TIOA pin is low. If TC_CMRx.WAVE = 1, this means that TIOA is driven low. 1: TIOA is high. If TC_CMRx.WAVE = 0, this means that TIOA pin is high. If TC_CMRx.WAVE = 1, this means that TIOA is driven high. • MTIOB: TIOB Mirror 0: TIOB is low. If TC_CMRx.WAVE = 0, this means that TIOB pin is low. If TC_CMRx.WAVE = 1, this means that TIOB is driven low. 1: TIOB is high. If TC_CMRx.WAVE = 0, this means that TIOB pin is high. If TC_CMRx.WAVE = 1, this means that TIOB is driven high. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 695 32.7.10 TC Interrupt Enable Register Name: TC_IERx [x=0..2] Address: 0x40010024 (0)[0], 0x40010064 (0)[1], 0x400100A4 (0)[2], 0x40014024 (1)[0], 0x40014064 (1)[1], 0x400140A4 (1)[2] Access: Write-only 31 – 30 – 29 – 28 – 27 – 26 – 25 – 24 – 23 – 22 – 21 – 20 – 19 – 18 – 17 – 16 – 15 – 14 – 13 – 12 – 11 – 10 – 9 RXBUFF 8 ENDRX 7 ETRGS 6 LDRBS 5 LDRAS 4 CPCS 3 CPBS 2 CPAS 1 LOVRS 0 COVFS • COVFS: Counter Overflow 0: No effect. 1: Enables the Counter Overflow Interrupt. • LOVRS: Load Overrun 0: No effect. 1: Enables the Load Overrun Interrupt. • CPAS: RA Compare 0: No effect. 1: Enables the RA Compare Interrupt. • CPBS: RB Compare 0: No effect. 1: Enables the RB Compare Interrupt. • CPCS: RC Compare 0: No effect. 1: Enables the RC Compare Interrupt. • LDRAS: RA Loading 0: No effect. 1: Enables the RA Load Interrupt. • LDRBS: RB Loading 0: No effect. 1: Enables the RB Load Interrupt. 696 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 • ETRGS: External Trigger 0: No effect. 1: Enables the External Trigger Interrupt. • ENDRX: End of Receiver Transfer 0: No effect. 1: Enables the PDC Receive End of Transfer Interrupt. • RXBUFF: Reception Buffer Full 0: No effect. 1: Enables the PDC Receive Buffer Full Interrupt. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 697 32.7.11 TC Interrupt Disable Register Name: TC_IDRx [x=0..2] Address: 0x40010028 (0)[0], 0x40010068 (0)[1], 0x400100A8 (0)[2], 0x40014028 (1)[0], 0x40014068 (1)[1], 0x400140A8 (1)[2] Access: Write-only 31 – 30 – 29 – 28 – 27 – 26 – 25 – 24 – 23 – 22 – 21 – 20 – 19 – 18 – 17 – 16 – 15 – 14 – 13 – 12 – 11 – 10 – 9 RXBUFF 8 ENDRX 7 ETRGS 6 LDRBS 5 LDRAS 4 CPCS 3 CPBS 2 CPAS 1 LOVRS 0 COVFS • COVFS: Counter Overflow 0: No effect. 1: Disables the Counter Overflow Interrupt. • LOVRS: Load Overrun 0: No effect. 1: Disables the Load Overrun Interrupt (if TC_CMRx.WAVE = 0). • CPAS: RA Compare 0: No effect. 1: Disables the RA Compare Interrupt (if TC_CMRx.WAVE = 1). • CPBS: RB Compare 0: No effect. 1: Disables the RB Compare Interrupt (if TC_CMRx.WAVE = 1). • CPCS: RC Compare 0: No effect. 1: Disables the RC Compare Interrupt. • LDRAS: RA Loading 0: No effect. 1: Disables the RA Load Interrupt (if TC_CMRx.WAVE = 0). • LDRBS: RB Loading 0: No effect. 1: Disables the RB Load Interrupt (if TC_CMRx.WAVE = 0). 698 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 • ETRGS: External Trigger 0: No effect. 1: Disables the External Trigger Interrupt. • ENDRX: End of Receiver Transfer 0: No effect. 1: Disables the PDC Receive End of Transfer Interrupt. • RXBUFF: Reception Buffer Full 0: No effect. 1: Disables the PDC Receive Buffer Full Interrupt. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 699 32.7.12 TC Interrupt Mask Register Name: TC_IMRx [x=0..2] Address: 0x4001002C (0)[0], 0x4001006C (0)[1], 0x400100AC (0)[2], 0x4001402C (1)[0], 0x4001406C (1)[1], 0x400140AC (1)[2] Access: Read-only 31 – 30 – 29 – 28 – 27 – 26 – 25 – 24 – 23 – 22 – 21 – 20 – 19 – 18 – 17 – 16 – 15 – 14 – 13 – 12 – 11 – 10 – 9 RXBUFF 8 ENDRX 7 ETRGS 6 LDRBS 5 LDRAS 4 CPCS 3 CPBS 2 CPAS 1 LOVRS 0 COVFS • COVFS: Counter Overflow 0: The Counter Overflow Interrupt is disabled. 1: The Counter Overflow Interrupt is enabled. • LOVRS: Load Overrun 0: The Load Overrun Interrupt is disabled. 1: The Load Overrun Interrupt is enabled. • CPAS: RA Compare 0: The RA Compare Interrupt is disabled. 1: The RA Compare Interrupt is enabled. • CPBS: RB Compare 0: The RB Compare Interrupt is disabled. 1: The RB Compare Interrupt is enabled. • CPCS: RC Compare 0: The RC Compare Interrupt is disabled. 1: The RC Compare Interrupt is enabled. • LDRAS: RA Loading 0: The Load RA Interrupt is disabled. 1: The Load RA Interrupt is enabled. • LDRBS: RB Loading 0: The Load RB Interrupt is disabled. 1: The Load RB Interrupt is enabled. 700 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 • ETRGS: External Trigger 0: The External Trigger Interrupt is disabled. 1: The External Trigger Interrupt is enabled. • ENDRX: End of Receiver Transfer 0: The PDC Receive End of Transfer Interrupt is disabled. 1: The PDC Receive End of Transfer Interrupt is enabled. • RXBUFF: Reception Buffer Full 0: The PDC Receive Buffer Full Interrupt is disabled. 1: The PDC Receive Buffer Full Interrupt is enabled. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 701 32.7.13 TC Block Control Register Name: TC_BCR Address: 0x400100C0 (0), 0x400140C0 (1) Access: Write-only 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 – 6 – 5 – 4 – 3 – 2 – 1 – 0 SYNC • SYNC: Synchro Command 0: No effect. 1: Asserts the SYNC signal which generates a software trigger simultaneously for each of the channels. 702 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 32.7.14 TC Block Mode Register Name: TC_BMR Address: 0x400100C4 (0), 0x400140C4 (1) Access: Read/Write 31 – 30 – 29 – 28 – 27 – 26 – 25 23 22 21 20 19 – 18 – 17 IDXPHB 16 SWAP 12 EDGPHA 11 QDTRANS 10 SPEEDEN 9 POSEN 8 QDEN 4 3 2 1 0 MAXFILT 15 INVIDX 14 INVB 13 INVA 7 – 6 – 5 TC2XC2S 24 MAXFILT TC1XC1S TC0XC0S This register can only be written if the WPEN bit is cleared in the TC Write Protection Mode Register. • TC0XC0S: External Clock Signal 0 Selection Value Name Description 0 TCLK0 Signal connected to XC0: TCLK0 1 – Reserved 2 TIOA1 Signal connected to XC0: TIOA1 3 TIOA2 Signal connected to XC0: TIOA2 • TC1XC1S: External Clock Signal 1 Selection Value Name Description 0 TCLK1 Signal connected to XC1: TCLK1 1 – Reserved 2 TIOA0 Signal connected to XC1: TIOA0 3 TIOA2 Signal connected to XC1: TIOA2 • TC2XC2S: External Clock Signal 2 Selection Value Name Description 0 TCLK2 Signal connected to XC2: TCLK2 1 – Reserved 2 TIOA0 Signal connected to XC2: TIOA0 3 TIOA1 Signal connected to XC2: TIOA1 • QDEN: Quadrature Decoder Enabled 0: Disabled. 1: Enables the QDEC (filter, edge detection and quadrature decoding). Quadrature decoding (direction change) can be disabled using QDTRANS bit. One of the POSEN or SPEEDEN bits must be also enabled. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 703 • POSEN: Position Enabled 0: Disable position. 1: Enables the position measure on channel 0 and 1. • SPEEDEN: Speed Enabled 0: Disabled. 1: Enables the speed measure on channel 0, the time base being provided by channel 2. • QDTRANS: Quadrature Decoding Transparent 0: Full quadrature decoding logic is active (direction change detected). 1: Quadrature decoding logic is inactive (direction change inactive) but input filtering and edge detection are performed. • EDGPHA: Edge on PHA Count Mode 0: Edges are detected on PHA only. 1: Edges are detected on both PHA and PHB. • INVA: Inverted PHA 0: PHA (TIOA0) is directly driving the QDEC. 1: PHA is inverted before driving the QDEC. • INVB: Inverted PHB 0: PHB (TIOB0) is directly driving the QDEC. 1: PHB is inverted before driving the QDEC. • INVIDX: Inverted Index 0: IDX (TIOA1) is directly driving the QDEC. 1: IDX is inverted before driving the QDEC. • SWAP: Swap PHA and PHB 0: No swap between PHA and PHB. 1: Swap PHA and PHB internally, prior to driving the QDEC. • IDXPHB: Index Pin is PHB Pin 0: IDX pin of the rotary sensor must drive TIOA1. 1: IDX pin of the rotary sensor must drive TIOB0. • MAXFILT: Maximum Filter 1–63: Defines the filtering capabilities. Pulses with a period shorter than MAXFILT+1 peripheral clock cycles are discarded. 704 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 32.7.15 TC QDEC Interrupt Enable Register Name: TC_QIER Address: 0x400100C8 (0), 0x400140C8 (1) Access: Write-only 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 – 6 – 5 – 4 – 3 – 2 QERR 1 DIRCHG 0 IDX • IDX: Index 0: No effect. 1: Enables the interrupt when a rising edge occurs on IDX input. • DIRCHG: Direction Change 0: No effect. 1: Enables the interrupt when a change on rotation direction is detected. • QERR: Quadrature Error 0: No effect. 1: Enables the interrupt when a quadrature error occurs on PHA, PHB. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 705 32.7.16 TC QDEC Interrupt Disable Register Name: TC_QIDR Address: 0x400100CC (0), 0x400140CC (1) Access: Write-only 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 – 6 – 5 – 4 – 3 – 2 QERR 1 DIRCHG 0 IDX • IDX: Index 0: No effect. 1: Disables the interrupt when a rising edge occurs on IDX input. • DIRCHG: Direction Change 0: No effect. 1: Disables the interrupt when a change on rotation direction is detected. • QERR: Quadrature Error 0: No effect. 1: Disables the interrupt when a quadrature error occurs on PHA, PHB. 706 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 32.7.17 TC QDEC Interrupt Mask Register Name: TC_QIMR Address: 0x400100D0 (0), 0x400140D0 (1) Access: Read-only 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 – 6 – 5 – 4 – 3 – 2 QERR 1 DIRCHG 0 IDX • IDX: Index 0: The interrupt on IDX input is disabled. 1: The interrupt on IDX input is enabled. • DIRCHG: Direction Change 0: The interrupt on rotation direction change is disabled. 1: The interrupt on rotation direction change is enabled. • QERR: Quadrature Error 0: The interrupt on quadrature error is disabled. 1: The interrupt on quadrature error is enabled. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 707 32.7.18 TC QDEC Interrupt Status Register Name: TC_QISR Address: 0x400100D4 (0), 0x400140D4 (1) Access: Read-only 31 – 30 – 29 – 28 – 27 – 26 – 25 – 24 – 23 – 22 – 21 – 20 – 19 – 18 – 17 – 16 – 15 – 14 – 13 – 12 – 11 – 10 – 9 – 8 DIR 7 – 6 – 5 – 4 – 3 – 2 QERR 1 DIRCHG 0 IDX • IDX: Index 0: No Index input change since the last read of TC_QISR. 1: The IDX input has changed since the last read of TC_QISR. • DIRCHG: Direction Change 0: No change on rotation direction since the last read of TC_QISR. 1: The rotation direction changed since the last read of TC_QISR. • QERR: Quadrature Error 0: No quadrature error since the last read of TC_QISR. 1: A quadrature error occurred since the last read of TC_QISR. • DIR: Direction Returns an image of the actual rotation direction. 708 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 32.7.19 TC Fault Mode Register Name: TC_FMR Address: 0x400100D8 (0), 0x400140D8 (1) Access: Read/Write 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 – 6 – 5 – 4 – 3 – 2 – 1 ENCF1 0 ENCF0 This register can only be written if the WPEN bit is cleared in the TC Write Protection Mode Register. • ENCF0: Enable Compare Fault Channel 0 0: Disables the FAULT output source (CPCS flag) from channel 0. 1: Enables the FAULT output source (CPCS flag) from channel 0. • ENCF1: Enable Compare Fault Channel 1 0: Disables the FAULT output source (CPCS flag) from channel 1. 1: Enables the FAULT output source (CPCS flag) from channel 1. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 709 32.7.20 TC Write Protection Mode Register Name: TC_WPMR Address: 0x400100E4 (0), 0x400140E4 (1) Access: Read/Write 31 30 29 28 27 26 25 24 19 18 17 16 11 10 9 8 3 – 2 – 1 – 0 WPEN WPKEY 23 22 21 20 WPKEY 15 14 13 12 WPKEY 7 – 6 – 5 – 4 – • WPEN: Write Protection Enable 0: Disables the write protection if WPKEY corresponds to 0x54494D (“TIM” in ASCII). 1: Enables the write protection if WPKEY corresponds to 0x54494D (“TIM” in ASCII). The Timer Counter clock of the first channel must be enabled to access this register. See Section 32.6.18 “Register Write Protection” for a list of registers that can be write-protected and Timer Counter clock conditions. • WPKEY: Write Protection Key Value 0x54494D 710 Name PASSWD Description Writing any other value in this field aborts the write operation of the WPEN bit. Always reads as 0. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 33. Pulse Width Modulation Controller (PWM) 33.1 Description The PWM macrocell controls several channels independently. Each channel controls one square output waveform. Characteristics of the output waveform such as period, duty-cycle and polarity are configurable through the user interface. Each channel selects and uses one of the clocks provided by the clock generator. The clock generator provides several clocks resulting from the division of the PWM macrocell master clock. All PWM macrocell accesses are made through APB mapped registers. Channels can be synchronized, to generate non overlapped waveforms. All channels integrate a double buffering system in order to prevent an unexpected output waveform while modifying the period or the duty-cycle. 33.2 Embedded characteristics 4 Channels One 16-bit Counter Per Channel Common Clock Generator Providing Thirteen Different Clocks ̶ A Modulo n Counter Providing Eleven Clocks ̶ Two Independent Linear Dividers Working on Modulo n Counter Outputs Independent Channels ̶ Independent Enable Disable Command for Each Channel ̶ Independent Clock Selection for Each Channel ̶ Independent Period and Duty Cycle for Each Channel ̶ Double Buffering of Period or Duty Cycle for Each Channel ̶ Programmable Selection of The Output Waveform Polarity for Each Channel ̶ Programmable Center or Left Aligned Output Waveform for Each Channel Block Diagram SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 711 33.3 Block Diagram Figure 33-1. Pulse Width Modulation Controller Block Diagram PWM Controller PWMx Period Channel PWMx Update Duty Cycle Clock Selector Comparator PWMx Counter PIO PWM0 Channel Period PWM0 Update Duty Cycle Clock Selector PMC MCK Clock Generator Comparator PWM0 Counter APB Interface Interrupt Generator APB 33.4 I/O Lines Description Each channel outputs one waveform on one external I/O line. Table 33-1. 712 I/O Line Description Name Description Type PWMx PWM Waveform Output for channel x Output SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 Interrupt Controller 33.5 Product Dependencies 33.5.1 I/O Lines The pins used for interfacing the PWM may be multiplexed with PIO lines. The programmer must first program the PIO controller to assign the desired PWM pins to their peripheral function. If I/O lines of the PWM are not used by the application, they can be used for other purposes by the PIO controller. All of the PWM outputs may or may not be enabled. If an application requires only four channels, then only four PIO lines will be assigned to PWM outputs. Table 33-2. I/O Lines Instance Signal I/O Line Peripheral PWM PWM0 PA0 A PWM PWM0 PA11 B PWM PWM0 PA23 B PWM PWM0 PB0 A PWM PWM0 PC8 B PWM PWM0 PC18 B PWM PWM0 PC22 B PWM PWM1 PA1 A PWM PWM1 PA12 B PWM PWM1 PA24 B PWM PWM1 PB1 A PWM PWM1 PC9 B PWM PWM1 PC19 B PWM PWM2 PA2 A PWM PWM2 PA13 B PWM PWM2 PA25 B PWM PWM2 PB4 B PWM PWM2 PC10 B PWM PWM2 PC20 B PWM PWM3 PA7 B PWM PWM3 PA14 B PWM PWM3 PB14 B PWM PWM3 PC11 B PWM PWM3 PC21 B 33.5.2 Power Management The PWM is not continuously clocked. The programmer must first enable the PWM clock in the Power Management Controller (PMC) before using the PWM. However, if the application does not require PWM operations, the PWM clock can be stopped when not needed and be restarted later. In this case, the PWM will resume its operations where it left off. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 713 All the PWM registers except PWM_CDTY and PWM_CPRD can be read without the PWM peripheral clock enabled. All the registers can be written without the peripheral clock enabled. 33.5.3 Interrupt Sources The PWM interrupt line is connected on one of the internal sources of the Interrupt Controller. Using the PWM interrupt requires the Interrupt Controller to be programmed first. Note that it is not recommended to use the PWM interrupt line in edge sensitive mode. Table 33-3. 714 Peripheral IDs Instance ID PWM 31 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 33.6 Functional Description The PWM macrocell is primarily composed of a clock generator module and 4 channels. ̶ Clocked by the system clock, MCK, the clock generator module provides 13 clocks. ̶ Each channel can independently choose one of the clock generator outputs. ̶ Each channel generates an output waveform with attributes that can be defined independently for each channel through the user interface registers. 33.6.1 PWM Clock Generator Figure 33-2. Functional View of the Clock Generator Block Diagram MCK modulo n counter MCK MCK/2 MCK/4 MCK/8 MCK/16 MCK/32 MCK/64 MCK/128 MCK/256 MCK/512 MCK/1024 Divider A PREA clkA DIVA PWM_MR Divider B PREB clkB DIVB PWM_MR Caution: Before using the PWM macrocell, the programmer must first enable the PWM clock in the Power Management Controller (PMC). The PWM macrocell master clock, MCK, is divided in the clock generator module to provide different clocks available for all channels. Each channel can independently select one of the divided clocks. The clock generator is divided in three blocks: ̶ ̶ a modulo n counter which provides 11 clocks: FMCK, FMCK/2, FMCK/4, FMCK/8, FMCK/16, FMCK/32, FMCK/64, FMCK/128, FMCK/256, FMCK/512, FMCK/1024 two linear dividers (1, 1/2, 1/3,... 1/255) that provide two separate clocks: clkA and clkB SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 715 Each linear divider can independently divide one of the clocks of the modulo n counter. The selection of the clock to be divided is made according to the PREA (PREB) field of the PWM Mode register (PWM_MR). The resulting clock clkA (clkB) is the clock selected divided by DIVA (DIVB) field value in the PWM Mode register (PWM_MR). After a reset of the PWM controller, DIVA (DIVB) and PREA (PREB) in the PWM Mode register are set to 0. This implies that after reset clkA (clkB) are turned off. At reset, all clocks provided by the modulo n counter are turned off except clock “clk”. This situation is also true when the PWM master clock is turned off through the Power Management Controller. 33.6.2 PWM Channel 33.6.2.1 Block Diagram Figure 33-3. Functional View of the Channel Block Diagram inputs from clock generator Channel Clock Selector Internal Counter Comparator PWMx output waveform inputs from APB bus Each of the 4 channels is composed of three blocks: A clock selector which selects one of the clocks provided by the clock generator described in Section 33.6.1 “PWM Clock Generator” on page 715. An internal counter clocked by the output of the clock selector. This internal counter is incremented or decremented according to the channel configuration and comparators events. The size of the internal counter is 16 bits. A comparator used to generate events according to the internal counter value. It also computes the PWMx output waveform according to the configuration. 33.6.2.2 Waveform Properties The different properties of output waveforms are: the internal clock selection. The internal channel counter is clocked by one of the clocks provided by the clock generator described in the previous section. This channel parameter is defined in the CPRE field of the PWM_CMRx register. This field is reset at 0. the waveform period. This channel parameter is defined in the CPRD field of the PWM_CPRDx register. - If the waveform is left aligned, then the output waveform period depends on the counter source clock and can be calculated: By using the Master Clock (MCK) divided by an X given prescaler value (with X being 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, or 1024), the resulting period formula will be: (-----------------------------X × CPRD )MCK By using a Master Clock divided by one of both DIVA or DIVB divider, the formula becomes, respectively: (---------------------------------------------X*CPRD*DIVA -) ( X*CPRD*DIVB ) or ----------------------------------------------MCK MCK If the waveform is center aligned then the output waveform period depends on the counter source clock and can be calculated: By using the Master Clock (MCK) divided by an X given prescaler value 716 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 (with X being 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, or 1024). The resulting period formula will be: (---------------------------------------2 × X × CPRD ) MCK By using a Master Clock divided by one of both DIVA or DIVB divider, the formula becomes, respectively: (----------------------------------------------------2*X*CPRD*DIVA -) ( 2*X*CPRD*DIVB ) or -----------------------------------------------------MCK MCK the waveform duty cycle. This channel parameter is defined in the CDTY field of the PWM_CDTYx register. If the waveform is left aligned then: ( period – 1 ⁄ fchannel_x_clock × CDTY ) duty cycle = ---------------------------------------------------------------------------------------------------period If the waveform is center aligned, then: ( ( period ⁄ 2 ) – 1 ⁄ fchannel_x_clock × CDTY ) ) duty cycle = ------------------------------------------------------------------------------------------------------------------( period ⁄ 2 ) the waveform polarity. At the beginning of the period, the signal can be at high or low level. This property is defined in the CPOL field of the PWM_CMRx register. By default the signal starts by a low level. the waveform alignment. The output waveform can be left or center aligned. Center aligned waveforms can be used to generate non overlapped waveforms. This property is defined in the CALG field of the PWM_CMRx register. The default mode is left aligned. Figure 33-4. Non Overlapped Center Aligned Waveforms No overlap PWM0 PWM1 Period Note: 1. See Figure 33-5 on page 718 for a detailed description of center aligned waveforms. When center aligned, the internal channel counter increases up to CPRD and.decreases down to 0. This ends the period. When left aligned, the internal channel counter increases up to CPRD and is reset. This ends the period. Thus, for the same CPRD value, the period for a center aligned channel is twice the period for a left aligned channel. Waveforms are fixed at 0 when: CDTY = CPRD and CPOL = 0 CDTY = 0 and CPOL = 1 Waveforms are fixed at 1 (once the channel is enabled) when: CDTY = 0 and CPOL = 0 CDTY = CPRD and CPOL = 1 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 717 The waveform polarity must be set before enabling the channel. This immediately affects the channel output level. Changes on channel polarity are not taken into account while the channel is enabled. Figure 33-5. Waveform Properties PWM_MCKx CHIDx(PWM_SR) CHIDx(PWM_ENA) CHIDx(PWM_DIS) Center Aligned CALG(PWM_CMRx) = 1 PWM_CCNTx CPRD(PWM_CPRDx) CDTY(PWM_CDTYx) Period Output Waveform PWMx CPOL(PWM_CMRx) = 0 Output Waveform PWMx CPOL(PWM_CMRx) = 1 CHIDx(PWM_ISR) Left Aligned CALG(PWM_CMRx) = 0 PWM_CCNTx CPRD(PWM_CPRDx) CDTY(PWM_CDTYx) Period Output Waveform PWMx CPOL(PWM_CMRx) = 0 Output Waveform PWMx CPOL(PWM_CMRx) = 1 CHIDx(PWM_ISR) 718 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 33.6.3 PWM Controller Operations 33.6.3.1 Initialization Before enabling the output channel, this channel must have been configured by the software application: Configuration of the clock generator if DIVA and DIVB are required Selection of the clock for each channel (CPRE field in the PWM_CMRx register) Configuration of the waveform alignment for each channel (CALG field in the PWM_CMRx register) Configuration of the period for each channel (CPRD in the PWM_CPRDx register). Writing in PWM_CPRDx Register is possible while the channel is disabled. After validation of the channel, the user must use PWM_CUPDx Register to update PWM_CPRDx as explained below. Configuration of the duty cycle for each channel (CDTY in the PWM_CDTYx register). Writing in PWM_CDTYx Register is possible while the channel is disabled. After validation of the channel, the user must use PWM_CUPDx Register to update PWM_CDTYx as explained below. Configuration of the output waveform polarity for each channel (CPOL in the PWM_CMRx register) Enable Interrupts (Writing CHIDx in the PWM_IER register) Enable the PWM channel (Writing CHIDx in the PWM_ENA register) It is possible to synchronize different channels by enabling them at the same time by means of writing simultaneously several CHIDx bits in the PWM_ENA register. In such a situation, all channels may have the same clock selector configuration and the same period specified. 33.6.3.2 Source Clock Selection Criteria The large number of source clocks can make selection difficult. The relationship between the value in the Period Register (PWM_CPRDx) and the Duty Cycle Register (PWM_CDTYx) can help the user in choosing. The event number written in the Period Register gives the PWM accuracy. The Duty Cycle quantum cannot be lower than 1/PWM_CPRDx value. The higher the value of PWM_CPRDx, the greater the PWM accuracy. For example, if the user sets 15 (in decimal) in PWM_CPRDx, the user is able to set a value between 1 up to 14 in PWM_CDTYx Register. The resulting duty cycle quantum cannot be lower than 1/15 of the PWM period. 33.6.3.3 Changing the Duty Cycle or the Period It is possible to modulate the output waveform duty cycle or period. To prevent unexpected output waveform, the user must use the update register (PWM_CUPDx) to change waveform parameters while the channel is still enabled. The user can write a new period value or duty cycle value in the update register (PWM_CUPDx). This register holds the new value until the end of the current cycle and updates the value for the next cycle. Depending on the CPD field in the PWM_CMRx register, PWM_CUPDx either updates PWM_CPRDx or PWM_CDTYx. Note that even if the update register is used, the period must not be smaller than the duty cycle. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 719 Figure 33-6. Synchronized Period or Duty Cycle Update User's Writing PWM_CUPDx Value 0 1 PWM_CPRDx PWM_CMRx. CPD PWM_CDTYx End of Cycle To prevent overwriting the PWM_CUPDx by software, the user can use status events in order to synchronize his software. Two methods are possible. In both, the user must enable the dedicated interrupt in PWM_IER at PWM Controller level. The first method (polling method) consists of reading the relevant status bit in PWM_ISR Register according to the enabled channel(s). See Figure 33-7. The second method uses an Interrupt Service Routine associated with the PWM channel. Note: Figure 33-7. Reading the PWM_ISR register automatically clears CHIDx flags. Polling Method PWM_ISR Read Acknowledgement and clear previous register state Writing in CPD field Update of the Period or Duty Cycle CHIDx = 1 YES Writing in PWM_CUPDx The last write has been taken into account Note: Polarity and alignment can be modified only when the channel is disabled. 720 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 33.6.3.4 Interrupts Depending on the interrupt mask in the PWM_IMR register, an interrupt is generated at the end of the corresponding channel period. The interrupt remains active until a read operation in the PWM_ISR register occurs. A channel interrupt is enabled by setting the corresponding bit in the PWM_IER register. A channel interrupt is disabled by setting the corresponding bit in the PWM_IDR register. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 721 33.7 Pulse Width Modulation Controller (PWM) User Interface Table 33-4. Register Mapping(1) Offset Register Name Access Reset 0x00 PWM Mode Register PWM_MR Read-write 0 0x04 PWM Enable Register PWM_ENA Write-only - 0x08 PWM Disable Register PWM_DIS Write-only - 0x0C PWM Status Register PWM_SR Read-only 0 0x10 PWM Interrupt Enable Register PWM_IER Write-only - 0x14 PWM Interrupt Disable Register PWM_IDR Write-only - 0x18 PWM Interrupt Mask Register PWM_IMR Read-only 0 0x1C PWM Interrupt Status Register PWM_ISR Read-only 0 0x20 - 0xFC Reserved – – 0x100 - 0x1FC Reserved 0x200 + ch_num * 0x20 + 0x00 PWM Channel Mode Register PWM_CMR Read-write 0x0 0x200 + ch_num * 0x20 + 0x04 PWM Channel Duty Cycle Register PWM_CDTY Read-write 0x0 0x200 + ch_num * 0x20 + 0x08 PWM Channel Period Register PWM_CPRD Read-write 0x0 0x200 + ch_num * 0x20 + 0x0C PWM Channel Counter Register PWM_CCNT Read-only 0x0 0x200 + ch_num * 0x20 + 0x10 PWM Channel Update Register PWM_CUPD Write-only - Note: 722 – 1. Some registers are indexed with “ch_num” index ranging from 0 to 3. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 33.7.1 PWM Mode Register Name: PWM_MR Address: 0x40020000 Access: Read/Write 31 – 30 – 29 – 28 – 23 22 21 20 27 26 25 24 17 16 9 8 1 0 PREB 19 18 11 10 DIVB 15 – 14 – 13 – 12 – 7 6 5 4 PREA 3 2 DIVA • DIVA, DIVB: CLKA, CLKB Divide Factor Value Name Description 0 CLK_OFF CLKA, CLKB clock is turned off 1 CLK_DIV1 CLKA, CLKB clock is clock selected by PREA, PREB 2-255 – CLKA, CLKB clock is clock selected by PREA, PREB divided by DIVA, DIVB factor. • PREA, PREB Value Name Description 0000 MCK Master Clock 0001 MCKDIV2 Master Clock divided by 2 0010 MCKDIV4 Master Clock divided by 4 0011 MCKDIV8 Master Clock divided by 8 0100 MCKDIV16 Master Clock divided by 16 0101 MCKDIV32 Master Clock divided by 32 0110 MCKDIV64 Master Clock divided by 64 0111 MCKDIV128 Master Clock divided by 128 1000 MCKDIV256 Master Clock divided by 256 1001 MCKDIV512 Master Clock divided by 512 1010 MCKDIV1024 Master Clock divided by 1024 Values which are not listed in the table must be considered as “reserved”. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 723 33.7.2 PWM Enable Register Name: PWM_ENA Address: 0x40020004 Access: Write-only 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 – 6 – 5 – 4 – 3 CHID3 2 CHID2 1 CHID1 0 CHID0 • CHIDx: Channel ID 0 = No effect. 1 = Enable PWM output for channel x. 724 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 33.7.3 PWM Disable Register Name: PWM_DIS Address: 0x40020008 Access: Write-only 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 – 6 – 5 – 4 – 3 CHID3 2 CHID2 1 CHID1 0 CHID0 • CHIDx: Channel ID 0 = No effect. 1 = Disable PWM output for channel x. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 725 33.7.4 PWM Status Register Name: PWM_SR Address: 0x4002000C Access: Read-only 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 – 6 – 5 – 4 – 3 CHID3 2 CHID2 1 CHID1 0 CHID0 • CHIDx: Channel ID 0 = PWM output for channel x is disabled. 1 = PWM output for channel x is enabled. 726 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 33.7.5 PWM Interrupt Enable Register Name: PWM_IER Address: 0x40020010 Access: Write-only 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 – 6 – 5 – 4 – 3 CHID3 2 CHID2 1 CHID1 0 CHID0 • CHIDx: Channel ID. 0 = No effect. 1 = Enable interrupt for PWM channel x. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 727 33.7.6 PWM Interrupt Disable Register Name: PWM_IDR Address: 0x40020014 Access: Write-only 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 – 6 – 5 – 4 – 3 CHID3 2 CHID2 1 CHID1 0 CHID0 • CHIDx: Channel ID. 0 = No effect. 1 = Disable interrupt for PWM channel x. 728 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 33.7.7 PWM Interrupt Mask Register Name: PWM_IMR Address: 0x40020018 Access: Read-only 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 – 6 – 5 – 4 – 3 CHID3 2 CHID2 1 CHID1 0 CHID0 • CHIDx: Channel ID. 0 = Interrupt for PWM channel x is disabled. 1 = Interrupt for PWM channel x is enabled. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 729 33.7.8 PWM Interrupt Status Register Name: PWM_ISR Address: 0x4002001C Access: Read-only 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 – 6 – 5 – 4 – 3 CHID3 2 CHID2 1 CHID1 0 CHID0 • CHIDx: Channel ID 0 = No new channel period has been achieved since the last read of the PWM_ISR register. 1 = At least one new channel period has been achieved since the last read of the PWM_ISR register. Note: Reading PWM_ISR automatically clears CHIDx flags. 730 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 33.7.9 PWM Channel Mode Register Name: PWM_CMR[0..3] Address: 0x40020200 [0], 0x40020220 [1], 0x40020240 [2], 0x40020260 [3] Access: Read/Write 31 – 30 – 29 – 28 – 27 – 26 – 25 – 24 – 23 – 22 – 21 – 20 – 19 – 18 – 17 – 16 – 15 – 14 – 13 – 12 – 11 – 10 CPD 9 CPOL 8 CALG 7 – 6 – 5 – 4 – 3 2 1 0 CPRE • CPRE: Channel Pre-scaler Value Name Description 0000 MCK Master Clock 0001 MCKDIV2 Master Clock divided by 2 0010 MCKDIV4 Master Clock divided by 4 0011 MCKDIV8 Master Clock divided by 8 0100 MCKDIV16 Master Clock divided by 16 0101 MCKDIV32 Master Clock divided by 32 0110 MCKDIV64 Master Clock divided by 64 0111 MCKDIV128 Master Clock divided by 128 1000 MCKDIV256 Master Clock divided by 256 1001 MCKDIV512 Master Clock divided by 512 1010 MCKDIV1024 Master Clock divided by 1024 1011 CLKA Clock A 1100 CLKB Clock B Values which are not listed in the table must be considered as “reserved”. • CALG: Channel Alignment 0 = The period is left aligned. 1 = The period is center aligned. • CPOL: Channel Polarity 0 = The output waveform starts at a low level. 1 = The output waveform starts at a high level. • CPD: Channel Update Period 0 = Writing to the PWM_CUPDx will modify the duty cycle at the next period start event. 1 = Writing to the PWM_CUPDx will modify the period at the next period start event. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 731 33.7.10 PWM Channel Duty Cycle Register Name: PWM_CDTY[0..3] Address: 0x40020204 [0], 0x40020224 [1], 0x40020244 [2], 0x40020264 [3] Access: Read/Write 31 30 29 28 27 26 25 24 19 18 17 16 11 10 9 8 3 2 1 0 CDTY 23 22 21 20 CDTY 15 14 13 12 CDTY 7 6 5 4 CDTY Only the first 16 bits (internal channel counter size) are significant. • CDTY: Channel Duty Cycle Defines the waveform duty cycle. This value must be defined between 0 and CPRD (PWM_CPRx). 732 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 33.7.11 PWM Channel Period Register Name: PWM_CPRD[0..3] Address: 0x40020208 [0], 0x40020228 [1], 0x40020248 [2], 0x40020268 [3] Access: Read/Write 31 30 29 28 27 26 25 24 19 18 17 16 11 10 9 8 3 2 1 0 CPRD 23 22 21 20 CPRD 15 14 13 12 CPRD 7 6 5 4 CPRD Only the first 16 bits (internal channel counter size) are significant. • CPRD: Channel Period If the waveform is left-aligned, then the output waveform period depends on the counter source clock and can be calculated: – By using the Master Clock (MCK) divided by an X given prescaler value (with X being 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, or 1024). The resulting period formula will be: (-----------------------------X × CPRD )MCK – By using a Master Clock divided by one of both DIVA or DIVB divider, the formula becomes, respectively: (----------------------------------------CRPD × DIVA )( CRPD × DIVAB ) or ---------------------------------------------MCK MCK If the waveform is center-aligned, then the output waveform period depends on the counter source clock and can be calculated: – By using the Master Clock (MCK) divided by an X given prescaler value (with X being 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, or 1024). The resulting period formula will be: (---------------------------------------2 × X × CPRD ) MCK – By using a Master Clock divided by one of both DIVA or DIVB divider, the formula becomes, respectively: (--------------------------------------------------2 × CPRD × DIVA ) ( 2 × CPRD × DIVB ) or --------------------------------------------------MCK MCK SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 733 33.7.12 PWM Channel Counter Register Name: PWM_CCNT[0..3] Address: 0x4002020C [0], 0x4002022C [1], 0x4002024C [2], 0x4002026C [3] Access: Read-only 31 30 29 28 27 26 25 24 19 18 17 16 11 10 9 8 3 2 1 0 CNT 23 22 21 20 CNT 15 14 13 12 CNT 7 6 5 4 CNT • CNT: Channel Counter Register Internal counter value. This register is reset when: 734 the channel is enabled (writing CHIDx in the PWM_ENA register). the counter reaches CPRD value defined in the PWM_CPRDx register if the waveform is left aligned. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 33.7.13 PWM Channel Update Register Name: PWM_CUPD[0..3] Address: 0x40020210 [0], 0x40020230 [1], 0x40020250 [2], 0x40020270 [3] Access: Write-only 31 30 29 28 27 26 25 24 19 18 17 16 11 10 9 8 3 2 1 0 CUPD 23 22 21 20 CUPD 15 14 13 12 CUPD 7 6 5 4 CUPD CUPD: Channel Update Register This register acts as a double buffer for the period or the duty cycle. This prevents an unexpected waveform when modifying the waveform period or duty-cycle. Only the first 16 bits (internal channel counter size) are significant. When CPD field of PWM_CMRx register = 0, the duty-cycle (CDTY of PWM_CDTYx register) is updated with the CUPD value at the beginning of the next period. When CPD field of PWM_CMRx register = 1, the period (CPRD of PWM_CPRDx register) is updated with the CUPD value at the beginning of the next period. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 735 34. Analog-to-Digital Converter (ADC) 34.1 Description The ADC is based on a 10-bit Analog-to-Digital Converter (ADC) managed by an ADC Controller. Refer to the Block Diagram: . It also integrates a 17-to-1 analog multiplexer, making possible the analog-to-digital conversions of 17 analog lines. The conversions extend from 0V to the voltage carried on pin ADVREF or the voltage provided by the internal reference voltage which can be programmed in ADC_ACR register. The selection of reference voltage source is defined by ONREF field in ADC_MR register. The ADC supports the 8-bit or 10-bit resolution mode. The 8-bit resolution mode prevents from using 16-bit Peripheral DMA transfer into memory when only 8-bit resolution is required by the application. Please note that using this low resolution mode does not increase the conversion rate. Conversion results are reported in a common register for all channels, as well as in a channel-dedicated register. 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 an effective sample rate of 1/16 of the actual sample frequency. This arrangement allows conversion speed to be traded for better accuracy. The last channel is internally connected by a temperature sensor. The processing of this channel can be fully configured for efficient downstream processing due to the slow frequency variation of the value carried on such a sensor. Software trigger, external trigger on rising edge of the ADTRG pin or internal triggers from Timer Counter output(s) are configurable. The main comparison circuitry allows automatic detection of values below a threshold, higher than a threshold, in a given range or outside the range, thresholds and ranges being fully configurable. The ADC also integrates a Sleep Mode and a conversion sequencer and connects with a PDC channel. These features reduce both power consumption and processor intervention. Finally, the user can configure ADC timings, such as Startup Time and Tracking Time. 736 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 34.2 Embedded Characteristics 10-bit Resolution with Enhanced Mode up to 12-bit 500 kHz Conversion Rate Digital Averaging Function providing Enhanced Resolution Mode up to 12-bit On-chip Temperature Sensor Management Wide Range Power Supply Operation Selectable External Voltage Reference or Programmable Internal Reference Integrated Multiplexer Offering Up to 17 Independent Analog Inputs Individual Enable and Disable of Each Channel Hardware or Software Trigger ̶ External Trigger Pin ̶ Timer Counter Outputs (Corresponding TIOA Trigger) PDC Support Possibility of ADC Timings Configuration Two Sleep Modes and Conversion Sequencer ̶ Automatic Wakeup on Trigger and Back to Sleep Mode after Conversions of all Enabled Channels ̶ Possibility of Customized Channel Sequence Standby Mode for Fast Wakeup Time Response ̶ Power Down Capability Automatic Window Comparison of Converted Values Write Protect Registers SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 737 34.3 Block Diagram Figure 34-1. Analog-to-Digital Converter Block Diagram Timer Counter Channels RTC 1Hz PMC MCK ADC Controller Trigger Selection ADTRG Control Logic FORCEREF Internal Voltage Reference System Bus VDDIN PIO APB ADCHx AD- GND 34.4 Signal Description Table 34-1. ADC Pin Description Pin Name Description ADVREF External Reference voltage (1) AD0 - AD16 Analog input channels ADTRG External trigger Note: 738 Peripheral Bridge Successive Approximation Register Analog-to-Digital Converter AD- Analog Inputs Multiplexed with I/O lines PDC User Interface Temp. Sensor Interrupt Controller ADC Cell ONREF ADVREF ADC Interrupt 1. AD16 is not an actual pin but is internally connected to a temperature sensor. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 34.5 Product Dependencies 34.5.1 Power Management The ADC Controller is not continuously clocked. The programmer must first enable the ADC Controller MCK in the Power Management Controller (PMC) before using the ADC Controller. However, if the application does not require ADC operations, the ADC Controller clock can be stopped when not needed and restarted when necessary. Configuring the ADC Controller does not require the ADC Controller clock to be enabled. 34.5.2 Interrupt Sources The ADC interrupt line is connected on one of the internal sources of the Interrupt Controller. Using the ADC interrupt requires the interrupt controller to be programmed first. Table 34-2. Peripheral IDs Instance ID ADC 29 34.5.3 Analog Inputs The analog input pins can be multiplexed with PIO lines. In this case, the assignment of the ADC input is automatically done as soon as the corresponding channel is enabled by writing the register ADC_CHER. By default, after reset, the PIO line is configured as input with its pull-up enabled and the ADC input is connected to the GND. 34.5.4 Temperature Sensor The temperature sensor is internally connected to channel index 16 of the ADC. The temperature sensor provides an output voltage VT that is proportional to the absolute temperature (PTAT). To activate the temperature sensor, TEMPON bit (ADC_TEMPMR)needs to be set. After being set, the startup time of the temperature sensor must be achieved prior to initiating any measure. SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 739 34.5.5 I/O Lines The pin ADTRG may be shared with other peripheral functions through the PIO Controller. In this case, the PIO Controller should be set accordingly to assign the pin ADTRG to the ADC function. Table 34-3. I/O Lines Instance Signal I/O Line Peripheral ADC ADTRG PA8 B ADC AD0 PA17 X1 ADC AD1 PA18 X1 ADC AD2/WKUP9 PA19 X1 ADC AD3/WKUP10 PA20 X1 ADC AD4 PB0 X1 ADC AD5 PB1 X1 ADC AD6/WKUP12 PB2 X1 ADC AD7 PB3 X1 ADC AD8 PA21 X1 ADC AD9 PA22 X1 ADC AD10 PC13 X1 ADC AD11 PC15 X1 ADC AD12 PC12 X1 ADC AD13 PC29 X1 ADC AD14 PC30 X1 ADC AD15 PC31 X1 34.5.6 Timer Triggers Timer Counters may or may not be used as hardware triggers depending on user requirements. Thus, some or all of the timer counters may be unconnected. 34.5.7 Conversion Performances For performance and electrical characteristics of the ADC, see the product DC Characteristics section. 740 SAM4N8/SAM4N16 [DATASHEET] Atmel-11158B-ATARM-SAM4N8-SAM4N16-Datasheet_23-Mar-15 34.6 Functional Description 34.6.1 Analog-to-digital Conversion The ADC uses the ADC Clock to perform conversions. Converting a single analog value to a 10-bit digital data requires Tracking Clock cycles as defined in the field TRACKTIM of the “ADC Mode Register” on page 755. The ADC Clock frequency is selected in the PRESCAL field of the Mode Register (ADC_MR). The tracking phase starts during the conversion of the previous channel. If the tracking time is longer than the conversion time, the