Presentation is loading. Please wait.

Presentation is loading. Please wait.

MCU bit Standard Peripherals and Programming using C30

Similar presentations


Presentation on theme: "MCU bit Standard Peripherals and Programming using C30"— Presentation transcript:

1 MCU3121 16-bit Standard Peripherals and Programming using C30

2 Objectives When you walk out of this class, you will understand the 16-Bit MCU: Architecture Interrupts Basic Peripherals Peripheral Configuration Programming in C using MPLAB C30

3 Agenda 16-Bit Architecture Basics & MPLAB C30
MCU Data Path & Registers Program & Data Memory ALU, Register Set, Clocking Scheme LAB 1: My First C30 Project Data Access From Program Memory LAB 2: PSV Configuration and Usage Stack and Frame pointer Interrupt and Trap Handling LAB 3: Interrupt Configuration and Usage

4 Agenda (Continued..) 16-Bit Peripherals I/O Ports ADC
LAB 4: ADC Configuration & usage Comparators & Voltage Reference generator Timers LAB 5: Configuration of 32-bit Timers Capture Compare & PWM UART LAB 6: UART Configuration and Usage of FIFO I2C™ SPI

5 Agenda (Continued..) Special features
Oscillators and Power Saving modes Resets WDT Summary References Appendix A MPLAB C30 C-Language Extensions

6 16-Bit Architecture Basics & MPLAB C30

7 Harvard Architecture 16-bit microcontroller 24-bit Instruction width
Data Transfer Mechanism between PM and DM 16 – bit window PIC 24 is 16-bit uC with modified Harvard Architecture. What is Harvard Architecture, the architecture where different busses are used to access program memory and data memory In PIC 24 a 24-bit bus to access PM and a 16bit bus to access DM PIC 24 also have a mechanism of transferring data between PM and DM thus it is called Modified Harvard Architecture. <click> The dsPIC line of digital signal controllers have the Multiple Accumulator (MAC) feature Program Memory (Up to 12MB) Data Memory (Up to 64KB) PIC24 RISC CPU MAC (dsPIC) 16 24

8 Architecture Block Diagram
Data Memory (RAM) 32K x 16 bit DSP: dual access MCU: single access Instruction Pre-fetch & Decode DSP Engine Access Cntrl TABLE Y AGU X AGU W Array 16 x 16 Program Memory 4M x 24 bit Linear Let us break this complicated block diagram down into parts and talk to it (Click for each bullet point below to highlight): The Program Counter is 23-bit wide which can address …<click> 8 Megs by 16 bits addresses however since we have a 24 bit wide program memory this translates to 4 Megs by 24 bits <Click> We have upto 32K by 16 bits of data memory which have single access in MCU mode (PIC24F/H) and dual access in DSP mode dsPIC30/33. <Click> Hence there are two address generators X and Y <Click> The DSP engine is integrated with the CORE <Click> The ALU/MCU can access RAM as well as any of the 16 working registers <Click> Finally Program memory can be accessed as data memory using the Program Space Visibility (PSV) and/or Table Access control 23-bit PC Control MCU ALU MCU & DSC DSC ONLY Address Path DSP Data Path MCU/DSP Data Path Program Data/Control Path

9 Program Memory Organization
23 Maximum 12MB 4MB x 24-bit 23-bit PC (PCH & PCL) PC increments in words (LSB always ‘0’) Reset Vector at 0 Interrupt Vector Table from 4h to FEh User Code space from 200h to 7FFFFEh (what ever is implemented) PC<22:1> Unimplemented Device ID Config Registers On Chip User Flash Memory Alternate Vector Table Flash Config Words Reset Vector Interrupt Vector Table 000000h User Space 000004h 000104h 000200h 16-bit PICs can have maximum of 12MB of program memory and 12MB of config space The reset vector resides at 0x000000, The Interrupt Vector Table (IVT) occupies from 0x to 0x0ff with an Alternate IVT (AIVT) from 0x104 to 0x1ff. User program memory starts at 0x200 and may go up to 0x7fffff. The last few locations at the end of the implemented program memory are used for storing the configuration words. The PC is 23 bit wide and using PC only 12MB of program memory can be accessed There are 2 other modes of accessing program memory, one is table operations which uses TABPAG as base pointer to access program memory. Table operations can be performed on both user and config space. The other mode is Program Space Visibility (PSV) which uses PSVPAG as the base pointer. Using this mode only user memory can be accessed. These 2 modes will be discussed in later sessions. The Device ID is stored in Configuration space from 0xff0000H to 0xffffff. Config Space 7FFFFEh Table Ops 23 PSV TABPAG Source reg Source reg PSVPAG FFFFFEh

10 Data Memory Organization
MS Byte Address 16-bits LS Byte Address MSB LSB 2 KB SFR Space 0x0001 0x0000 SFR Space Near Data Memory 8 KB 0x07FF 0x07FE 0x0801 0x0800 SRAM Space X Data Ram Y Data Ram 0x1FFE Dual Port RAM 2 KB Dual-Port DMA RAM 0x8001 0x8000 Unimplemented Optionally Mapped into Program Memory Using PSV <Click> for each animated item to appear. The data memory capability is 64Kbytes. The top 2KB are allocated for Special Function Registers. These are registers which are used to configure and access the peripherals. Just below that space is the User RAM which in the DSP devices is broken into X and Y data spaces for dual access. In non-DSP devices (MCU only devices) there is only one memory data space (single access). The first 8kBytes is known as Near Data Memory, please note this as we will refer to it, in the instruction set discussion. The bottom 32Kbytes of Data memory is unimplemented. This space can optionally be mapped into Program Memory using the Program Space Visibility (PSC) feature. This feature allows the user to access PM in 32Kb chunks just like Data Memory. Notice that the 16-bit architecture and instruction set allows byte mode operation on data memory so on the right side you will notice even number addresses while on the left side you will notice odd number addresses. Since the 16-bit wide word can be broken into two 8-bit bytes, using the specific odd/even number address can access each byte of the data memory. If in case we use an odd address to access a word, an address error trap will result. All word accesses have to be “word aligned” that is their address has to be an even number. 0xFFFF 0xFFFE

11 PSV - Program Space Visibility From Data Space
Ability to map 16KW (32KB) program memory segments into Data Memory 15 23 15 0x000000 0x0000 0x0000 0x001000 SFR Space 0x1234 0x1234 PAGE 1 0x008000 Data Memory 0x009000 0x5678 0x5678 PAGE 2 0x8000 0x010000 In most applications, users would like to access constant values like: tables, menus, configuration bytes, coefficients, etc quickly just like Data memory (RAM). However, saving these constant entities in RAM is a waste of limited RAM resources. These constants can alternately be saved in Program Memory. Program Space Visibility (PSV) allows easy “RAM like” access of data stores in Program memory. The user first has to set the PSV bit in the CORCON register and has to load the appropriate PSVpage value in the PSVPAG register to access the right 32Kb segment in PM being accessed. In this slide we see how different segments can be accessed. When PAGE 1 is being access the segment accessed is the one from hex 0 to hex 7FFF in PM. So accessing a location 9000 hex in data memory will physically access the location 1000 hex in PM hence a value of hex When PAGE 2 is accessed, the same access of data memory 9000 hex will access the location 9000 hex in program memory so a value of hex 5678 will result. Finally when PAGE 3 is accessed the same access will give a value of hex ABCD. The actual mechanism of how this accessing is done will be shown later followed with a hands on exercise to show how to utilize it. Notice, when using PSV, only the lower 16 bits of the 24 bit wide program memory is used. Byte access is possible using PSV. If the entire 24 bits of the Program memory needs to be used then the Table Read/write instructions have to be used, not PSV. 0x9000 0x011000 32 KB Program Space Visibility (PSV) 0xABCD 0xABCD PAGE 3 0x018000 Data Memory 0xFFFE Program Memory

12 MCU ALU & Datapath - Overview -
16-bit Family ALU is 16-bits Wide Operates on both 8 & 16-bit operands for better C support (char / int) Instruction set : (dsPIC) Single cycle bit manipulation (RMW) Operations: Add, Subtract, Logical, Single/Multi-bit shifts (1 cycle), 2’s complement

13 Datapath Example (c = a + b;)
CPU Registers Data Memory (Variables) w0 a (copy) a w1 addr(b) b w2 addr(c) c w3 temp i w5 …. …. w15 ALU ALU can operate directly or indirectly on variables stored in Data Memory add w0, [w1], [w2]

14 Datapath Example #2 (c = a + b;)
CPU Registers Data Memory (Variables) w0 a (copy) a w1 b (copy) b w2 c (copy) c w3 temp i w5 …. …. w15 ALU ALU can operate directly on variables stored in CPU Registers add w0, w1, w2

15 Multiply & Divide Support
Single-cycle, 17x17 multiplier Supports mixed mode multiplies (signed/unsigned) 32/16 and 16/16 signed/unsigned integer divider Implemented as an interruptible, single instruction iterative loop, i.e.  Execution time: 19 Tcy, Latency : 1 Tcy repeat #17 ;must be executed within repeat loop div.sd ;signed division (16/16)

16 Register Set 16 General Purpose Data Registers or Address Pointers
15 W0 W1 W2 W3 W4 W5 W6 W7 W8 W9 W10 W11 W12 W13 W14 W15 16 General Purpose Data Registers or Address Pointers MCU & DSC Frame Pointer Stack Pointer DSC ONLY SPLIM Stack Pointer Limit Considering the Programmers Model, the Arch has 16 General purpose 16-bit working registers. This is a big step up on the PIC16 and PIC18 which only have one 8 bit working register. There are no special address registers. However the working register themselves can be used as address pointer. We will see this when we discuss the addressing modes. There is no special stack pointer, so W15 is used as the stack pointer. This location has to be filled with an address which points to a RAM location as the start of the Stack. The Stack pointer limit allows the user to predetermine the size of the stack. The Frame Pointer is used by C function calls. The Status register can be broken into two parts the Low byte are MCU status bits and CPU interrupt priority and the high byte are DSP status bits. 7 Status Register Low IPL2 IPL1 IPL0 RA N Z OV C MCU Status Status Register High OA OB SA SB OAB DA SAB DC 15 8 DSP Status

17 Register Set (contd.) CORCON Core/DSP Control Register PSVPAG
15 Core/DSP Control Register PSVPAG 7 Prg. Space Visibility Page Address TBLPAG 7 Data Table Page Address There is a 16-bit CORCON register to control CORE and DSP operations. The PSVPAGe and TaBLePAGe registers allow users to access program memory as data memory. The DSP devices also have two 40-bit accumulators for DSP operations. These are useful for 16 by 16 bit multiplication, resulting in a 32-bit value such operations can be accumulated before an overflow would occur. ACCA ACCAL ACCAH ACCAU 15 31 39 Two DSP Accumulators ACCBL ACCBH ACCBU ACCB

18 Register Set (contd.) Do Loop Registers: Repeat Loop Counter RCOUNT
15 Repeat Loop Counter Program Counter 22 Program Counter Do Loop Registers: DCOUNT 15 Do Loop Counter There are also some special register in the core which allow for special operations to be done. We have a Repeat Instruction which allow us to repeat a instruction N times. This instruction has a RCOUNT register which is used for this purpose. We have the 23 bit wide program counter to access 4Mega words of instructions . dsPIC devices also have a DO instruction which allows a user to repeat a set of instructions (or code) N number of time. For this we have a DCOUNT register, and a start and end address register for the start and end addresses of the code. DOSTART 22 Do Loop Start Address DOEND 22 Do Loop End Address

19 Instruction Pipeline Allows overlap of execution and fetch
Makes single cycle execution Program branches (e.g. goto, rcall) take two cycles TCY0 TCY1 TCY TCY TCY4 1. mov W0, PORTB Fetch 1 Exec. 1 16-bit arch. Has a two level deep instruction pipeline. This allows parallel processing. While the first instruction is executed in Tcy1, the next instruction is fetched, in this case the second instruction is a branch instruction rcall sub_1. When “rcall sub_1” is executed in Tcy2, the next instruction is fetched into the pipeline. The execution of rcall, updates the Program Counter (PC) with the address of the branch location SUB_1. So in Tcy3, a NOP operation is force executed and the pipeline is now loaded with the instruction from sub_1 which is “bset porta,#ra3” On Tcy4 the bit set instruction is executed and the next instruction fetched into the pipeline. All instructions are single cycle instructions except for branch or program flow instructions which take two cycles. 2. rcall SUB_1 Fetch 2 Update PC . (Forced nop) Fetch 2+1 Forced NOP . 3. SUB_1: 4. bset PORTA, #RA3 Fetch SUB_1 Exec. SUB_1 . Fetch SUB_1+1 .

20 Clocking Scheme Instruction cycle = 2 Input Clocks PIC24F
A 32Mhz clk = 16MIPS or Tcy = 62.5 nS PIC24H/dsPIC33 A 80Mhz clk = 40 MIPS or Tcy = 25 nS dsPIC30F – Instruction cycle = 4 Input Clocks A 120Mhz clk = 30MIPS or Tcy = 33 nS 1 Instruction cycle (TCY) OSC1 Q2 Q1 Q3 Q4 FCY In the PIC24F, PIC24H and dsPIC33 family one instruction cycle is equal to 2 oscillator clock cycles or Tosc. Q1 to Q4 are four internal CPU clock cycles which are generated for internal MCU operations. Four Q clocks are used to execute one single cycle instruction or Tcy. As an example: on a PIC24F family, if we use an external xtal of 32Mhz, then the instruction execution speed would be 16Mhz for single cycle instructions or Tcy would equal 62.5 nano seconds. The dsPIC30 family operate much like other PIC families: that is 4 oscillator clock cycles are used to generate the four internal Q clocks. If we took the same example as above, a 32Mz xtal would give a single cycle instruction speed of 8Mhz or Tcy = 125 nano seconds

21 Lab 1 My First C30 Project

22 Hands-on Exercises All labs are in the following directory:
C:\RTC\MCU3121\LabX where X is the number of the lab Solution workspaces are supplied in the following directory: C:\RTC\MCU3121\LabX\Solution Directions for the labs are in the class handout which is also in the following directory: C:\RTC\MCU3121\Presentation & Handouts\MCU3121_Handout v1.0.pdf Supplementary materials are in the following directory: C:\RTC\MCU3121\User’s Guides and Data Sheets

23 Labcenter Proteus VSM Virtual prototyping for PICMicro’s.
Simulate complete embedded systems. Develop and debug your firmware on virtual hardware. Test and verify before ordering your prototype. Proteus VSM is a traditional mixed mode (analog & digital) SPICE circuit simulator with the added ability to simulate the interaction between software running on a microcontroller and any analog or digital electronics connected to it. The micro-controller model sits on the schematic along with the other elements of your product design. It simulates the execution of your firmware, just like a real chip. If the program code writes to a port, the logic levels in circuit change accordingly, and if the circuit changes the state of the processor's pins, this will be seen by your program code, just as in real life. The PICMicro models fully simulate I/O ports, interrupts, timers, ADC’s, comparators, USARTs and all other peripherals present on the processor. The interaction of the processor with the external circuit is fully modelled down to waveform level and the entire system is therefore simulated according to the schematic design. Over 250 PICMicro models from PIC10 through dsPIC33 (P10,P12,P16,P18,P24,P33). Integrates with MPLAB .. source level debugging. USD 479 for 8-bit family, USD 649 for 16-bit family. Schematic Simulation of PICDEM2+ Board.

24 Development Tools - Explorer 16 Board-
POT ICD2 connector RS232 connector Make sure to set the following: S2PIM J7PIC24 JP2Shorted PIMPIC24F LEDs Switches

25 Development Tools - MPLAB REAL-ICE -
Next-generation ICE platform Legacy (ICD2 RJ11) and high speed connectivity Full speed emulation High speed 480 Mb/S 2.0 USB workstation connection High speed target debug protocol Supports real-time watch, hardware stopwatch, and trace capture Microchip’s newer and faster product families are driving requirements for new emulation hardware (PIC32, dsPIC33F/PIC24F & J Series) Traditional emulation is limited by Memory speed Interconnection distances Availability of emulation devices Desire to reduce or eliminate the need to purchase processor modules and make emulation available as soon as possible Feature Set Summary: Real time watch Provides a non-intrusive view of data Gathered in real time Hardware Stopwatch Function Measures elapsed time between breakpoints Capture Trace Uses device to program execution points, tracing application execution and Logs small amounts of data Maximum transfer rate of ~10KB per second at 4MHz for 16-bit core Port Trace Hardware assisted tracing and logging Assigned to device communication port Similar transfer rates with less device overhead Trace information is stored on PC workstation Probe contains transfer buffers, not trace memory Traces program execution points by executing code on MCU or dsPIC Supported families : PIC16(*), PIC18/24/32, dsPIC3x (*check REAL ICE release notes for specific product support)

26 Connecting the MPLAB® REAL-ICE Debugger
MPLAB REAL-ICE (w. “Standard” Probe) Connect the ICD2 to the PICDEM2 + Demo board as show. The ICD2 is connected to the PC via the USB cable. 9V are applied to the PICDEM2+ using a power brick. The ICD2 is connected to the PICDEM2+ via the 6 pin RJ11, telephone cable and connectors. 9VDC Power Supply Explorer Demo Board

27 Lab 1: Working with C30 and MPLAB IDE
Goals: Learn the basics of C30 by working with a template project To Do: Follow along with the presenter Expected Result: Successfully build the project and program the device LED D3 should blink

28 Lab 1: C30 Project C Source File Linker Script (Optional) C30
Assembler Compiler And Linker Comment (Linker Scripts): Note that for MPLAB v8.x, a correct default linker script is automatically included in the build, so you do not have to explicitly add it to the project. Make sure to set the build to “Release”. The file temp_128GA010.c is provided as an example and template file for 16-bit PIC applications. It has some examples on how to declare variables and interrupt functions in C30. The file is intended to be used with the PIC24FJ128GA010 that is provided with the explorer 16. After opening the temp_128GA010.c file in MPLAB, you should create a new project. Set the project to use C30 tool suite, select the correct device, and add the p24fj128ga010.gld linker script to the project so that it will compile and link correctly.

29 Lab 1: Template File Include statements, Configuration macros, and Define statements Shown are some examples of code from the template file. The template includes examples on: using #include to add the device .h files so that C30 has SFR definitions Using configuration bit macros to set the device configuration Using #defines in C30 Variable definitions of various variable types, including arrays. Multiple types of attributes are used as well. Global variable declarations with and without attributes

30 Lab 1: Template File Continued
Templates for main function and interrupt service routines. Note the use of the various ISR attributes Shown are some examples of code from the template file. The template includes examples on: Template for the program’s main function Templates for various ISR definitions. Examples are shown on how to use different ISR attributes

31 Add this code to main function
Lab 1: Code Add this code to main function Create delay function In order to see the code work, add some simple code to blink an LED. First, you must set the pin as an output. Then, loop toggling the pin using the bit toggle built-in. This is the most efficient way to toggle a bit in C30. Add a delay to the loop to slow it down so the LED can be observed. In this case the delay is a simple for loop. Compile the project to ensure that you have no errors. Now Compile! (F10)

32 Lab 1: Program Memory View
Reset and Interrupt Vectors Initialization code inserted from crt0.s main() and delay() functions You can view important aspects of your project in MPLAB. Shown here is the program memory view. It displays in various formats the data in the device’s program memory. At the bottom addresses of program memory are the Reset and Interrupt vectors. Starting at address 0x200 is user code space. Here C30 has automatically included the initialization code from crt0.s to initialize the stack, psv, and data memory. The user code immediately follows the init code. Here we can see the main and delay functions, as well as the ISR routines defined in the template file. Interrupt Service Routines

33 Lab 1: Program Memory & Disassembly Listing
Program Memory Variables Disassembly Listing The assembly code that the compiler generates You can view important aspects of your project in MPLAB. At the end of the used program memory, C30 places constant variables and data initialization information (for RAM variables which do not initialize to 0). The last instruction is C30’s default interrupt routine. By default all interrupts vector here. The disassembly listing shows the assembly code that is generated by the compiler. It is useful to check this view during debugging to ensure that the code generated is as expected. Any time you have timing problems or unexpected operation, check the disassembly to ensure the code does what you think it should. Shown here is the disassembly for the LED blink code added to the template main function.

34 Data Memory Variable Locations Prog Mem Variable & Function Locations
Lab 1: Map File Locate memory sections in Map file Data Memory Variable Locations Prog Mem Variable & Function Locations Memory usage data By going to Project Build Options for the MPLAB Linker, you can select in the diagnostic category to output a MAP file of the project. The map file details information about the project such as: memory usage statistics Data memory variable locations Program memory variable and function locations Where sections in memory are mapped to, relating this information to the code in the linker script which causes it to be located there. This is a very useful debugging tool when editing linker scripts.

35 Lab 1: Watch Window Compare addresses to expected values. Do they make sense? Data memory on 32-byte boundary (lower 5 bits of address 0) Program Memory Variable – note longer address When debugging a project, the watch window provides an area to view the value of variables. Here we can see both data and program memory variables in the watch window. Note the variable addresses and compare them with the C declarations to verify that the attributes we added to them were correctly applied. Data memory variables

36 Main loop execution time Configure Oscillator Frequency
Lab 1: MPLAB SIM When we added code we put in a delay loop with an unknown delay. If we want to find out what the delay is in milliseconds, we can use the MPLAB simulator to run our code and give us the information. After configuring the simulator, you can use the stopwatch to find out how much time a section of code takes by running to the location and breaking. Here we time the main lop once by zeroing out the stopwatch and running again. Some of the other debuggers provide similar functionality, in addition to actually allowing us to debug the code within a device. Main loop execution time Configure Oscillator Frequency

37 Data Access From Program Memory
Table Read/Write & Program Space Visibility (PSV)

38 Constant Data Access from PM Using Table Instructions
24-bit Effective Address(EA) formation Configuration space is accessed by setting TBLPAG<7> (i.e. EA<23>) Only means of accessing configuration space 24-bit Instruction OP CODE p Source & Dest Regs TBLPAG Register 16-bit Source/Dest. Pointer TBLPAG<7:0> TBLPAG<7:0> w w Byte Select w 1) Only this method of access can be used to access Configuration Space. 2) This method can be used for both byte and word accesses (depending on the instruction). To access the PM the base address should be loaded into TBLPAG reg and the offset address in source register. When one of the table instruction is executed the 24 bit effective address is generated by concatenating 8 bit of TBLPAG with 15 bits from the Source register and the LS bit is generated by the opcode. If table op is done for higher word (TBLRDH/TBLWTH) then LSbit will be 1 and for lower word (TBLRDL/TBLWTL) it will be 0. When the table operations are done to access the 16-bit word the LSbit of source reg should be maintained ‘0’ If the operation is done to access the LSByte of the word then LSbit of source reg should be written ‘0’ and to access MSbyte it should be written 1 8-bits from TBLPAG Register 15-bits from Source/Dest. Pointer Word Select From Op Code Effective 24-bit PM Address

39 Constant Data Access from PM Using Table Instructions
Actual 24-bit Program Memory 23 Phantom Byte 8-bits 16-bits TBLRDH/TBLWTH TBLRDL/TBLWTL When TBLRDH/TBLRDL and TBLWTH/TBLWTL instructions are executed in word mode 16 bit data is read or written In case of TBLRDH operation the instruction attempts to access 16 bits. However, only 8 bits really exists it reads the higher 8 bits of PM with 00 as the MSB, referred as the Phantom Byte TBLRDH.B/TBLWTH.B TBLRDL.B/TBLWTL.B TBLRDL.B/TBLWTL.B Table Instruction View of Program Memory

40 Using Table Read/Write in C30
Must use assembly for special instructions and exact timing Add assembly file to project, or, Use C30 Built-ins: const unsigned int myVar = 0xFFFF; unsigned int varAddr; TBLPAG = __builtin_tblpage(&myVar); varAddr = __builtin_tbloffset(&myVar); __builtin_tblwtl(varAddr, 0xAAAA); //load data to write: //0xAAAA NVMCON = 0x4003; //NVM word write opcode __builtin_write_NVM(); //unlock & set WR bit You cannot perform table reads and writes using only C code. Table reads and writes require both special instructions to perform (tblrdl, tblrdh, tblwtl, tblwth) and require exact timing. In order to perform table operations to the NVM, you must use assembly language. This can be done in two ways, as discussed earlier: - Add an assembly file to the project - Use C30 built-in functions to perform the same operations using C Here is an example of writing new data to an NVM address. We are writing the data 0xAAAAAA to the location of a constant variable, myVar. To do this we need the address of myVar, which we can obtain by using the tblpage and tbloffset built-ins. Then you can perform table writes of the lower 16-bits and upper 8-bits independently using the tblwt built-ins. Finally, you must configure the NVM to perform a table write, and then execute the operation with the write_NVM built-in. Note: You should always erase a flash location before writing to it! You may corrupt the data if you write a location multiple times without erasing.

41 Constant Data Access from PM Using Program Space Visibility
32 KB segment of PM may be mapped into the data memory address space If PSV bit (CORCON<2>) is set and if SrcPointer (DM EA)<15> is ‘1’ then data is accessed from PM 24-bit Instruction OP CODE Source & Dest Regs PSVPAG Register 16-bit Source Pointer PSVPAG<7:0> PSVPAG<7:0> Select PSV 1 w w Byte Select 1) This method also can be used for both byte and word accesses (depending on the instruction). To access the PM the base address should be loaded into PSVPAG reg and the offset address in source register. When any of the instruction tries to access the memory region higher than 0x8000 and if PSV bit (CORCON<2>) is set it accesses Program Memory. The 24 bit effective address to PM is generated by concatenating 8 bit of PSVPAG with 14 bits from the Source register and the LS bit is always 0 as only even word can be accessed using PSV. When the operations are done to access the 16-bit word the LSbit of source reg should be maintained ‘0’ If the operation is done to access the LSByte of the word then LSbit of source reg should be written ‘0’ and to access MSbyte it should be written 1 8-bits from PSVPAG Register 14-bits from Source Pointer User Space Only User Space only Only even words can be accessed Effective 24-bit PM Address

42 PSV Addressing Example
23 0000H Data Space 000000H 000000H PC<22:1> 0800H 2000H SFRs Reset Vector 2FFEH Near Data Memory Interrupt Vector Table Far Data Memory 8000H Alternate Vector Table User Space 100000H On Chip User Flash Memory On Chip User Flash Memory 32KB 15 The addresses that are mapped using PSV to data space, actually map to the X-data space. Data Space EA<15:0> 7FFFFEH 1 CORCON<PSV> = 1 Flash Config Words PSVPAG = 0x20 ProgEA = 0x101000 DataEA = 0x9000 PSVPAG PSVPAG Source reg Source reg

43 Data Access from PM Using PSV
Actual 24-bit Program Memory 23 8-bits 16-bits WORD access instruction 0x00 or 0xFF Byte access instruction with odd address Byte access instruction with even address If the instructions are used in word mode, the instruction access the lower word and if instructions are used in byte mode individual byte of lower word is accessed. The Upper 8 bits cannot be accessed using PSV. Only reading of PM is possible and no writing into PM is possible while using PSV. So only source register to point to PM and not he destination register. Only lower 16-bits of PM location can be accessed via mapping Upper 8 bits should be programmed for a NOP

44 Using the PSV in C30 Three usage options Manual PSV Auto PSV
char data[256] __attribute__((space(psv))) Must manually point to the correct PSV when accessing the variable Auto PSV const char data[256]; or char data[256] __attribute__((space(auto_psv))) Maximum of 32 KB of constant data allowed Linker does not allow PSV space to cross a PSVPAG boundary and adjusts automatically Manual PSV: Manually place the variable in PSV space by using __attribute__ ((space(psv))) Whenever accessing the variable, user must manually ensure that the PSV page is set correctly. The PSVPAG built-in discussed earlier helps with this. Auto PSV: Declare variables using either the “const” keyword or using the attribute space(auto_psv). Compiler automatically ensures that the PSVPAG is set correctly when accessing the variable A maximum of 32 KB (one page) of PSV data is allowed. The linker automatically aligns the data so that PSV data does not cross a PSVPAG boundary (so all PSV variables will have same PSVPAG)

45 Using the PSV in C30 Compiler Managed PSV Only in C30 v3.00 and later
Allows use of more than 32 KB of constants Compiler automatically sets PSVPAG Must apply attribute space(psv) to variable & declare variable as managed with __psv__ qualifier __psv__ char data[256] __attribute__ ((space(psv))) Compiler Managed PSV New in C30 v.3.00 Allows more than 32 KB of PSV data to be used without requiring manual PSV control. NOTE: Individual variables are still limited to a maximum of 32 KB in size New type qualifiers are available: __psv__ tells the compiler that it is PSV data and that the object cannot cross a PSVPAG __prog__ tells the compiler it is constant data in program space but does not constrain it to be page aligned When the __psv__ qualifier is applied to an object, the compiler automatically sets the PSVPAG. Pointers to these objects musts also be declared with the __psv__ qualifier and are not considered the same thing as a normal pointer – they are different types!

46 Advantages of PSV PSV allows large tables of data to be stored and accessed quickly & easily PSV provides a bridge to a common data/program address space (Von Neumann) but only when needed Example: Strings for display, Sine table, lookup tables Note : If your application requires large data tables, access through TBLPAG should is preferred to optimize PM memory usage

47 Data Access Overhead Using PSV
PSV data fetch overhead: Outside a REPEAT loop: Data move ops, overhead = 1 cycle ALU based ops, overhead = 2 cycles Within a REPEAT loop: Data pipelined, so overhead for all ops = 0 cycles First & last iteration - data pipeline fill/flush Note: REPEAT loop refers to the REPEAT instruction, not a loop in C (while or for loops).

48 PSV Configuration and Usage
Lab 2 PSV Configuration and Usage

49 Lab 2: PSV Configuration and Usage
Goals: To initialize PSV To store a Hello World string in PSV space To read and transmit this string to LCD To Do: Look into the Hand out provided Expected Result: The text displayed on LCD should match the array defined

50 Software Stack

51 Software Stack in Data RAM
0x27FE Over Flow Error SPLIM Stack Grows Towards Higher Address Pushed Data Two levels used to save PC 0x00 PCH PCL SRL PCH Stack Pointer (W15 ) Top of the Stack PCL Under Flow Error The purpose of this slide is to let the customer know that the architecture implements a software stack (vs. hardware stack on the 8-bit PICs)…leave the detailed explanation to the later “software stack” section push Interrupt call 0x800

52 Indicates 4 bytes of Space required (always even no.)
Frame Pointer 0x27FE SPLIM Local Variable2 Offset = 2 Local Variable1 Frame Pointer 0x00 PCH Stack Pointer (W15) Top of the Stack PCL The C compiler uses the Stack to save local variables. It stores the variables at locations offsetting with a Base Pointer. As the Stack pointer can change within a function call it cannot be used as a Base pointer. So there is a need of another pointer, a Frame Pointer is provided, implemented in W14. <click> On calling a function as we have seen before PC is saved and Stack pointer increments by 4 Now Lnk instruction is executed with the literal value specifying number of bytes required to save the local variables. Now old Frame pointer is saved and Stack pointer increments by 2 and this stack pointer is moved to frame pointer. Now Frame pointer becomes the base pointer and the local variables are saved at offset 0 and offset 2 as in this case only 2 16 bit variables are to be saved, requiring 4 bytes as indicated by the literal value 4 when Lnk was executed. The stack pointer is incremented and will be pointing to new top of the stack. Lnk #4 Frame Pointer (W14) Call Indicates 4 bytes of Space required (always even no.) 0x800

53 Traps and Interrupts

54 Interrupt Architecture
Interrupt Controller CPU TRAPS 15 8 Static Priority CPU Interrupt 7 PRIORITY CPU Interrupts 7 Vector Address Address Natural Priority User Selectable Priority The 16-bit PIC interrupt controller module reduces the numerous peripheral interrupt request signals to a single interrupt request signal to the 16-bit CPU. Depending on the number of peripherals implemented, there can be up to 118 interrupts and up to 8 traps. Each interrupt and Trap is assigned to a particular address. So, for each interrupt, the program counter of the CPU jumps to a particular vector address. Interrupts are mask able. By default, there is a natural order of priority for the interrupt, starting from 0 to is the highest priority and 117 is the lowest. Additionally, each interrupt can have a software programmed priority from 0 to 7. Traps can be considered as non-mask able, nest able interrupts which adhere to a fixed priority structure. Levels 8 though 15 are assigned to individual traps and only one trap is assigned to a priority level, trap levels cannot be changed. The CPU can operate at one of eight priority levels, 0-7. An interrupt or trap source must have a priority level greater than the current CPU priority in order to initiate an exception process. Note that an interrupt source programmed to priority level 0 is effectively disabled, since it can never be greater than the CPU priority. Also note that traps cannot be ignored because the lowest trap is priority 8 and the highest CPU priority is 7. 117

55 IVT / AIVT Highest Priority 0x100 RESET Vector 0x00 0x102 0x02
Lowest Priority RESET Vector 0x100 0x00 0x02 Also used for RESET 0x102 0x104 0x04 Reserved 0x06 Osc. Fail Trap Vector 0x106 0x08 Adrs. Err. Trap Vector 0x108 0x0A Stack Err. Trap Vector 0x10A 0x0C Math Err. Trap Vector 0x10C 0x10E 0x0E Reserved 0x110 0x10 Reserved 0x12 Reserved 0x112 0x14 Interrupt 0 Vector 0x114 0x16 Interrupt 1 Vector 0x116 This is a section of the IVT/AIVT showing the natural order priority for various interrupt sources. Remember that the natural priority provided by the IVT can be overridden by assigning a source with low natural priority to a high user priority level or vice versa. The only time the fixed natural priority of the IVT would be a potential issue is when more than one interrupt source has the same user assigned priority level. . . . Interrupt 116 Vector 0x1FC 0xFC 0x1FE 0xFE Interrupt 117 Vector

56 Glow LED; Visual Indication
AIVT Advantage IF “condition1” is true goto “application” Else goto “debug” Debug_main Use AIVT ... ….. End ISR1 ; add. 0x104 Glow LED; Visual Indication Application_main Use IVT ... ….. End ISR1 ; add. 0x004 Process data The advantages of AIVT are that in case of debugging the code and if ISR should not be changed then on one condition it can vector to ISR and on other conditions it can vector to alternate location. This way it helps in debugging. The AIVT control bit is bit 15 of the INTCON2 register. The bit name is ALTIVT and will cause the controller to use the AIVT when it is set.

57 Interrupt Priority CPU has 16 priority levels
Level 0 is the default CPU level (main) Level for user interrupts Level reserved for traps (NMI) An interrupt source must have a user-assigned priority level greater than current CPU priority level (IPL<3:0>) to initiate an exception process. Level 4 is the default for all user interrupt sources Natural order priority (IVT order) is used to resolve conflicts between simultaneous, pending interrupt sources within a given user-assigned priority level Here is the default setting of interrupts on PIC24: On Reset: CPU IPL = 0, All User-assigned IPL = 4, Nesting enabled So, your main function can be interrupted by any of the (enabled) level 4 interrupt sources. Since they are all at user-assigned priority level 4, they will not be able to pre-empt each other. (i.e. if CPU is running a level 4 ISR, and another level 4 interrupt comes in, it will wait until the current ISR completes) Conflict among multiple pending level 4 interrupt sources is resolved via the IVT natural order (low IVT addresses get first shot) Since nesting is enabled, you can modify the user-assigned priority bits for all your interrupt sources to allow your highest priority interrupt sources to pre-empt lower ones, overriding the natural priority. Note, that lower priority interrupts can now have considerable latency. See next slide for an example of nesting. NOTE: It is not recommended to change the interrupt priority while an interrupt is enabled – this can cause conflicts if the priority is changed at the same time an interrupt occurs, causing interrupt to be missed or incorrect priority levels to be used. An interrupt should be disabled prior to changing its priority.

58 Interrupt Nesting Example
RETURN L7 L7 INT 5 Cycle Latency 7 Cycle Latency RETURN* L4 7 Cycle Latency 5 Cycle Latency RETURN L1 3 Cycle Latency L4 INT L1 INT main() L0 CPU EXECUTION TRACE Status Register 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 The IPL bits in Status Register and the CORCON Registers indicates the priority level of CPU. By default it is at Zero level, so CPU is running at Level 0 Say a Level 4 interrupt comes CPU starts executing the Level 4 interrupt, - If an interrupt occurs at or before the midpoint of a CPU instruction cycle, the ISR entry will begin on the next instruction. If it occurs after this point, and additional instruction will be executed before ISR entry begins. So, a maximum of 2 instructions can be run after an interrupt occurs. This makes interrupt latency between 4-5 cycles. Say while in Level ISR a Level 7 interrupt comes, then CPU preempts to Level 7 ISR, Say while in Level 7 ISR a Level 1 interrupt comes CPU ignores for time being and continues in Level & till it returns. On returning from level 7 it enters level 4 ISR and on returning from level 4 ISR only it enters Level 1 ISR. On returning from Level 1 ISR it comes back to Level 0. IPL<3:0> IPL 2 IPL 1 IPL 3 2 1 Core Control Register 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 IPL 3

59 Interrupt Latency 1 2 3 4 PC PC-2 PC PC+2 Vector # ISR ISR+2 Instruction Executed Fetch Vector INST(PC-4) INST(PC-2)* PC* NOP NOP ISR IFS bit CPU Priority 4 4 4 4 4 6 6 - If an interrupt occurs at or before the midpoint of a CPU instruction cycle, the ISR entry will begin on the next instruction. If it occurs after this point, and additional instruction will be executed before ISR entry begins. So, a maximum of 2 instructions can be run after an interrupt occurs. - When Hard Traps occur, to ensure data is not corrupted, the CPU will stall instruction execution after the cycle where the trap occurs completes. - After the interrupt occurs, the CPU requires 4 cycles to enter the ISR - 1st Cycle: Executes the current PC and sets the IFS flag - 2nd Cycle: CPU executes Forced Nop. Saves PC in temporary buffer - 3rd Cycle: CPU fetches ISR vector - 4th Cycle: CPU executes Forced Nop. Status bits and Wregs are saved on stack. Interrupt or Trap event occurs in this interval Push CPU status, and high 7 bits of PC onto stack Save PC in temporary buffer Push low 16- bits of PC onto stack *These instructions are executed as a NOP if the previous instruction causes a Hard Trap

60 Traps Soft Traps Hard Traps Priority levels 8 through 12
Treated as an NMI with fixed priority ‘Normal’ exception process is taken Example: Arithmetic error trap (priority level 11) Stack error trap (priority level 12) Hard Traps Priority levels 13 through 15 CPU execution flow is immediately suspended Execution cannot resume until trap is acknowledged Address error trap (level 13) Oscillator error trap (level 14) The traps can be broadly classified into soft and hard traps. Soft traps are those generated because of software errors like arithmetic error or stack error and hard traps are generated because of hardware errors like address error and oscillator fail error.

61 Error Traps What happens when a trap occurs?
Branches to address 0 by default Better to branch to a reset instruction Linker adds a reset instruction and vector Best to add your own error trap handler If a trap occurs and the trap vector is un-programmed, it will cause a “reset” of the device by branching to address 0. Since this is not a true reset, a better practice is to use the reset instruction, so that SFRs get reset as well. This, by default, is what C30 does. It creates the “_DefaultInterrupt” label which is associated with a reset instruction which is added to the end of every program. This way, all unimplemented traps (and interrupts) will cause a device reset. The optimal practice is to add your own trap handler, to deal with the cause of the trap and resume normal operation without a reset. 1 2

62 Configuring Interrupts
IPC0: Interrupt Priority Control Register 0 : Assign Priority 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 INT0IP 000: Disabled 001: Priority 1 Interrupt 010: Priority 2 Interrupt 011: Priority 3 Interrupt 100: Priority 4 Interrupt 101: Priority 5 Interrupt 110: Priority 6 Interrupt 111: Priority 7 Interrupt Changes to the interrupt priority level should not be made while an interrupt is enabled IEC0: Interrupt Enable Control Register 0 : Enable Interrupt 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 INT0IE To Enable any particular interrupts, IECx registers are to be used, by setting the corresponding bits the particular interrupt can be enabled. NOTE: It is not recommended to change the interrupt priority while an interrupt is enabled – this can cause conflicts if the priority is changed at the same time an interrupt occurs, causing interrupt to be missed or incorrect priority levels to be used. An interrupt should be disabled prior to changing its priority. To set the priority of any interrupt IPCx register should be used, to set the priority 3 bits are there priority 0 to 7 can be set. If priority 0 is set the interrupt is disabled. On occurrences of different events the interrupt flag will be set in IFSx register, user needs to clear them after attending the interrupt. IFS0: Interrupt Flag Control Register 0 : Clear Interrupt in the ISR 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 INT0IF

63 Interrupt Service Routines in C
Compiler saves / restores the ISR context Hardware saves return address and SR Fast ISR saves W0-W3 in one cycle (only 1 level deep) Uses push.s and pop.s (only 1 level deep) Globals used by the ISR must be volatile volatile unsigned global_flag; ISR must clear the Interrupt Flag IFS0bits.T1IF = 0; Making function calls not recommended Linker will populate the Vector Table Must use designated interrupt names The designated interrupt names can be found in the .gld file of that device, which can be found at c:\Program Files\Microchip\MPLAB C30\support\PIC24F\gld Compiler Context Saving: By default the compiler will save the context of the WREGs and SFRs used by the compiler on the stack before an ISR occurs. If you declare an ISR as a Fast ISR, it will instead use the push.s and pop.s instructions. PUSH.S stores the W0-W3 and the SR register in 1-level deep “shadow” registers, POP.S restores the shadowed values into the registers. Optionally, you can indicate extra registers or variables to save on the stack before an ISR is called. This is done as part of the ISR declaration. Note on globals: The purpose of the volatile flag is to tell the compiler that a variable may change outside of when C30 expects it to. As an example, all SFRs are labeled as volatile as they can be modified by the hardware outside of software execution. This flag prevents the compiler from compiling or optimizing in such a way that an unintended data value is used. It ensures that C30 knows that in between one instruction and the next, the value can change. This will ensure that C30 performs changes to the variable using atomic instructions: changes will be made in a single cycle when possible to ensure that the value does not get corrupted by an ISR call.

64 Function Attributes Declare an interrupt function
void __attribute__((interrupt)) _ADCInterrupt(void) void _ISR _IC1Interrupt(void) Make function use shadow registers void __attribute__((interrupt,shadow)) _ADCInterrupt(void) void _ISRFAST _IC1Interrupt(void) int __attribute__((shadow)) FastFunc(int Abc) Saves W0-W3 and SR bits with push.s and pop.s If an interrupt handler does not require any of the optional parameters to be saved instead of using the complex interrupt attribute, the simpler macro can be used. If optional parameters are to be saved in interrupt handler then attribute should be used. Eg. void __attribute__((__interrupt__(__save__(var1,var2)))) _ADCInterrupt (void)

65 Interrupt Configuration and Usage
Lab 3 Interrupt Configuration and Usage

66 Lab 3: Interrupt Configuration and Usage
Goal: Understand Interrupt configuration Understand Interrupt priority Writing Interrupt handler for a given Interrupt vector To Do: Look into the Hand out provided Expected Result:

67 16-Bit Peripherals

68 PIC24F Family Peripheral Pin Select Memory Bus 16 MIPS 16-bit Core
INTRC w/PLL WDT & Pwr Mgmt. 4 – 16 KB Data Memory Memory Bus 8 – 256 KB Flash Memory 500 Ksps 10b ADC (2) Comparators (5) 16/32 Timers Input Capture Control Interrupt 16 MIPS 16-bit Core Peripheral Pin Select Output Compare/PWM Interrupt Control 16 x 16b W Register Array 16b ALU (2 to 4) UART Peripheral Bus (2) SPI + (2) I2C 17b x 17b Multiply Address Generator Unit Real time clock+cal PIC24F family is lowest cost 16-bit family and is entry point into 16-bit architecture. It is specified for 16MIPS of operation. Currently PIC24F devices are available from 28 to 100 pin and 16KB to 128KB of reprogrammable Flash. As expected it is 16-bit machine so it has 16-bit data bus. PIC24F uses Howard RISC architecture so it has separate bus for program memory. It is 24-bit wide. Most instructions are single cycle instructions. It has 16 , 16bit working register array. It helps to generate C compiler optimized code. It has 17 x 17bit multiplier for signed multiplications. Let’s look at the PIC24F peripheral set. It has internal oscillator that can go from 32KHz to full speed of 32MHz (16MIPS), If you know PIC then you may have realized that this is a divide by two architecture, different than 8-bit PIC devices. It has multiple power management features (Sleep, Idle and Doze mode). The device has 500Ksps A/D. Current devices have maximum 16 analog channels. Lower pin –count devices have lesser channels. A/D has 16 level deep FIFO and many other advanced features. It has two analog comparators for analog features. Current devices has 5 16-bit timers. Four of them can be combined together to create 2 32-bit timers. Currently they have 5 input capture and 5 Output Compare/ PWM modules. IC module is useful to capture timer value on certain external event. OC module generates certain output on pin when timer matches certain set value. The PWM module can give upto 16-bit resolution. We have following serial communication modules. 1) UART, 2) SPI and 3) I2C. Two each UART module supports RS232, RS485, LIN and IrDA protocol. It has 4-level deep FIFO. SPI module supports many operating modes and has 8-level deep FIFO The I2c module can operate in Master or Slave mode. The slave mode supports full 7 or 10-bit address masking allowing module to respond to more than one address. The Cyclic Redundancy Check (CRC) module provides HW support to calculate CRC for program memory and communications applications The Real Time Clock and Calendar (RTCC) module provides time and 100 year calendar with leap year correction in HW. The Parallel Mast Port (PMP) makes it easier to interface with hardware modules. FYI The 28/44 pin PIC24F device and all future PIC24F devices has min endurance of 10,000 cycles. The 64/80/100 pin family is specified at 1000 typical CRC JTAG Interface Multi-bit Shifter PMP CTMU NEW pin Packages USB 2.0 OTG New devices with PPS (Peripheral Pin Select)  digital I/O pins can be freely connected to peripherals by SW !!

69 PIC24H Family Memory Bus 40 MIPS 16-bit Core 8 Channel Peripheral Bus
INTRC w/PLL 1 – 16 KB Data Memory Memory Bus 12 – 256 KB Flash Memory 8 Channel DMA (3-9) 16/32 Timers WDT & Pwr Mgmt. 1.1 Msps 10b ADC SW selectable 500 Ksps 12b ADC Control Interrupt Interrupt Control 40 MIPS 16-bit Core 16b ALU 16 x 16b W Register Array 17b x 17b Multiply Address Generator Unit Multi-bit Shifter JTAG Interface (1-2) UART w/LIN & IrDA® Peripheral Bus (1-2) I2C™ (1-2) SPI Input Capture Slide Key Objectives Basic High Level Block Diagram showing key CPU and peripheral features on PIC24H This foil was used in Spring 2006 Seminars so nothing new here Slide Key Points Scalable MIPS performance up to 40 Configurable ADC module for 10- and 12-bit operation 8 Channel DMA with a range of DMA enabled peripherals (not shown here) Comments Key Note: All future dsPIC33F and PIC24H device will support the Peripheral Pin Select feature. Output Compare/PWM (0-2) ECAN™ pin Packages New devices with PPS (Peripheral Pin Select)  digital I/O pins can be freely connected to peripherals by SW !!

70 dsPIC30F Family Memory Bus 30 MIPS 16-bit Core 0.5 - 8 KB 12 - 144 KB
INTRC w/PLL (2-5) 16/32 Timers KB Data Memory Memory Bus KB Flash Memory 1 - 4 KB EEPROM WDT & Pwr Mgmt. 1 Msps 10b ADC -or- 200 Ksps 12b ADC (1-2) UART w/LIN & IrDA® Control Interrupt 30 MIPS 16-bit Core 16b ALU 16 x 16b W Register Array 17b x 17b Multiply Dual AGU X & Y Barrel Shifter JTAG Interface DSP Engine Dual 40b Accumulators (1-2) I2C™ Peripheral Bus (1-2) SPI Input Capture Output Compare/PWM Slide Key Objectives Basic High Level Block Diagram showing key CPU and peripheral features on dsPIC30F This foil was used in Spring 2006 Seminars so nothing new here Slide Key Points Scalable MIPS performance up to 30 Configurable ADC module for 10- and 12-bit operation Comments Operates from 2.5 to 5.5Vdc. (0-2) CAN™ Codec I/F (I2S, AC97) MC PWM MC QEI pin Packages

71 dsPIC33F Family Memory Bus 40 MIPS 16-bit Core 8-channel
1 – 30 KB Data Memory Memory Bus 12 – 256 KB Flash Memory 8-channel DMA INTRC w/PLL (3-9) 16/32 Timers WDT & Pwr Mgmt. (1-2) 1.1Msps 10b ADC SW selectable Control Interrupt 40 MIPS 16-bit Core 16b ALU 16 x 16b W Register Array 17b x 17b Multiply Dual AGU X & Y Barrel Shifter JTAG Interface DSP Engine Dual 40b Accumulators (1-2) 500Ksps 12b ADC (1-2) UART w/LIN & IrDA® Peripheral Bus (1-2) I2C™ (1-2) SPI™ IC / OC / PWM (2) 16 bits Audio DAC Slide Key Objectives Basic High Level Block Diagram showing key CPU and peripheral features on dsPIC33F This foil was used in Spring 2006 Seminars so nothing new here Slide Key Points Scalable MIPS performance up to 40 Configurable ADC module for 10- and 12-bit operation 8 Channel DMA with a range of DMA enabled peripherals (not shown here) Integrated DSP engine into the Core for seamless operation Comments Key Note: All future dsPIC33F and PIC24H device will support the Peripheral Pin Select feature. (0-2) ECAN™ Codec I/F (I2S, AC97) (4-8) MC PWM pin Packages (0-2) MC QEI New devices with PPS (Peripheral Pin Select)  digital I/O pins can be freely connected to peripherals by SW !!

72 I/O Ports

73 I/O PORT TRISA PORTA Function PINs 1 I O O O 2 1 3 4 5 6 7 15
3 4 5 6 7 15 1 TRISA PORTA Function I O O O PINs But before we start let us understand how the I/O register work. Each port has upto 16 I/O lines associated with it. In this case let us use PORTA. Each PortA pin has an associated TRISA bit which controls the Function of the respective PORTA pin as an input or an output. On reset the TRISA register is loaded with ones so all PortA pins Function as inputs. One looks like I which stands for Input. If we want to make say PORTA bit 0 Function as an output, then we must write a zero into the corresponding TRISA bit location. (Click mouse). Zero looks like “O” which stands for Output. When we do this, the corresponding pin functions as an Output (as you see in the animation). Let us next make bits 3 function as an output and finally let us try to make bit 5 function as an Output also. Easy to remember “one(1)” looks like “I” which stands for Input. “Zero(0)” looks like “O” which stands for Output.

74 Digital I/O Ports In order to understand this, let us take a look at the Port structure. Each PORT has Latches allocated. When a write to a PORT is done, the write operation writes to the Latches. However when a read to the PORT is done, the PORT pins are read not the latches. In order to read the latches, the Read LAT instruction needs to be executes. The Bit SET or BitCLeaR Instructions are read-modify-write (RMW) instructions. So the whole PORT is read, the designated bit is modified and then the whole PORT is written back to the PORT. Le us assume that we execute the following instructions: BSET PORTA,#0 ; Turn PORTA bit 0 ON BSET PORTA,#1 ; Turn PORTA bit 1 ON At the end, we expect Two LEDs connected to Bit 0 and 1 should be ON right? Well here is what may happen Next slide ….

75 Why do we have LAT Reg? At Low Frequency or Low Capacitive Loading
BSET PORTA,PIN0 BSET PORTA,PIN1 Q4 Q1 Q2 Q3 Voltage VIL Qclks V on PORTA,PIN0 Port A Read in RMW Operation At High Frequency or High Capacitive Loading BSET PORTA,PIN0 BSET PORTA,PIN1 Let’s take a look at the Read modify write issue in relationship to the speed of the Q clock and the speed of the voltage transition which occurs on the I/O lines. <click> The vertical axis is the voltage and the horizontal axis is the Q clock cycles. We use a dotted line marked Vil to mark the voltage level below which a zero will be sensed and above which a one will be sensed. <click> When BSF PORTA,PIN0 is executed, the Q4 clock cycle end will indicate that the instruction has been completed. <click> we now execute the BSF PORTA,PIN1 instruction. This is a read-modify-write instruction in which the whole port A is read at the end of the Q1 cycle shown by the vertical blue line. Meanwhile our previous instruction has set PIN zero so let’s see how that voltage is doing. <click> The Red line shows the voltage transition of the I/O line. When it reaches the point where the Q1 end will sample the whole port A, the voltage at PIN zero will be read above the threshold voltage Vil, so PIN 0 will be read as a 1. So in Q4 when the whole port A is written back, PIN0 will be written back as a 1 as intended by the last instruction. <click>Now let us look at the same scenario when the Frequency is higher that is the Q clocks are closer to one another. <click> we are still tracking the Voltage and Q clocks and Vil. <click> When BSF PORTA,PIN0 is executed, it will be completed at Q4. <click> We then execute BSF PORTA,PIN1. In this instruction the whole port A will be read at the end of Q1, shown by the blue arrow. <click> The same voltage transition on PIN 0, shown by the red line, will now be read below the Vil line so it is read as a zero. It will not be modified and will be written back to the port A as a zero. Which was not the intention of the previous instruction. Q4 Q1 Q2 Q3 Q4 Voltage VIL V on PORTA,PIN0 Qclks Port A Read in RMW Operation

76 Why do we have LAT Reg? For Read-Modify-Write operations on port pins, use the LATch rather than PORTx: BSET LATA,#0 BSET LATA,#1 _LATA0 = 0 ; // = LATAbits.LATA0 _LATA1 = 1 ; // = LATAbits.LATA1 To solve this issue, never use the read-modify-write instruction on the PORT instead use it on the LATch by using the BSET LATA,#0 and BSET LATA,#1 instructions.

77 I/O PORT Open Drain Control
2 1 3 4 5 6 7 15 1 ODCx PORTx Function OD PINs Each I/O pin has I/O pin driver to sink and source current. All ‘J’ devices provide feature to convert all pins to open drain configuration. In open drain configuration the current source capability of pin is disabled. Drive Logic

78 Interfacing to 5V devices
5V tolerant input and Open drain configuration simplifies 5V interface On 16-bit ‘J’ devices digital function only pins are 5V tolerant. They can tolerate 5V input signal even if Vdd is 3V. This capability with open drain configuration can significantly simplify 5V interface. Let’s look at one example. In this case output of 5V peripheral is directly fed to 5V tolerant input. The MCU is running at 3.3V. However, with external pull up resistor to 5V and open drain feature we can generate 5V output. Question: What do you mean by digital only pin? Answer: If any pin has analog functionality (i.e. A/D channel, Comparator input etc) as one of the multiplexed option then that I/O pin is considered to have analog function pin. Any pin that do not have any of the analog function as one of the multiplexed option is considered digital only pin.

79 Interfacing to 5V devices
Interfacing to low impedence 5V load with open drain feature 5V 5V PIC24FJxxxx PIC24FJxxxx One may say that solution discussed in previous slide will not work for low impedance load like relay. Therefore one will not able to drive 5V low impedance load with these devices. However, its not true. This slide shows example of one such configuration. The drive strength of 16-bit devices. PIC24F – All I/O pins +/- 18mA PIC24H – All I/O pins +/- 4mA dsPIC30 – All I/O pins +/- 25mA dsPIC33 All I/O pins +/- 4mA. Check out device DS for details. Load on Logic high Logic low Load Off

80 Analog-to-Digital Converter
ADC Analog-to-Digital Converter

81 10 Bit ADC Features Successive Approximation (SAR) conversion
Conversion speeds of up to 500ksps Up to 16 analog input pins External Voltage reference pins Automatic Channel Scan mode Selectable conversion trigger source 16-word conversion result buffer Selectable Buffer Fill modes Four result alignment options Operation during CPU Sleep and Idle modes The slides in this presentation shows the general 10 bit ADC features, in some variants of some 16-bit family there are some extra features which are not covered. These are the features of A/D Read out.

82 PIC24F A/D VR Select Conversion Control Input Muxes A/D converter
AVDD VR Select AVSS VR+ VREF+ VR- Conversion Control VREF- Input Muxes AN0 AN1 CH0 A/D converter 8/16 Level Results Buffer Data Format S/H Bus Interface ADC peripherals on dsPIC30F DSCs are fixed 4S/H-10 bit, or 1S/H-12 bit, depending on family member (Sensor, General Purpose, Motor Control) ADC peripheral on PIC24F is fixed at 1S/H, 10 bit ADC peripheral on PIC24H/dsPIC33F are programmable: Either 4S/H-10 bit OR 1S/H-12 bit On PIC24H/dsPIC33F devices with 2ADC modules, it is possible to interleave ADC conversions together to achieve up to 2.2MSPS sample rate on a single input. Up to 32 analog input channels may be multiplexed into the S/H inputs This block diagram shows the 24F 10-bit ADC. The 12-bit ADC of other 16-bit controllers are similar to this. Module has a 16-word buffer Buffer will reset to ADRES0 after each interrupt At end of next conversion, ADRES0 overwritten Can software unload buffer quickly enough? If not, split buffer by setting BUFM = 1 Now module alternates two 8-word buffers BUFS shows buffer in use by A/D Converter BUFS = 1, read ADRES0 - ADRES7 BUFS = 0, read ADRES8 - ADRES15 8 samples per interrupt max when BUFM = 1 A/D Setup Setup analog pins, reference source Select output data format Select conversion clock, trigger source Enable auto-sample, if desired Set auto-sample time, if using auto-trigger Select A/D inputs and groups Enable ALTS, if using group A and group B Enable input scan, if desired Select S/H channels, SIMSAM if desired Select SMPI, buffer mode AN15 Sample Sequence Control

83 10-bit ADC - Block Diagram
AVDD AVSS VREF+ VREF- VR+ VR- VR Select AD1CON2<VCFG2:VCFG0> AVSS AVDD 1xx VREF- VREF+ 011 010 001 000 VR- VR+ VCFG2:VCFG0 First let us see reference voltages for adc. The reference voltages can be AVDD AVSS or VREF+AVSS or AVDD VREF- or VREF+VREF-. One of these can be selected by configuring VCFG2:VCFG0 bits in AD1CON2 register. AD1CON2 Register bit15 bit8 VCFG2 CSSL15=0 VCFG1 CSSL14=0 VCFG0 CSSL13=0 --- --- CSNA --- --- bit7 bit0 BUFS --- SMPI3 SMPI2 SMPI1 SMPI 0 BUFM ALTS

84 10-bit ADC - Block Diagram
AN0 AD1CHS<CH0SA3:CH0SA0> AN1 VINH Mux A (1) AN1 VINL (0) VR- AN15 AD1CHS<CH0NA> bit15 bit8 AD1CON2 Register VCFG2 VCFG1 CSSL14=0 CSSL13=0 VCFG0 --- --- CSNA --- --- bit7 bit0 BUFS --- SMPI3 SMPI2 SMPI1 SMPI 0 BUFM ALTS The ADC is differential ADC and so ADC has 2 inputs VINH and VINL VINH can be one of the 16 channels AN0 to AN15 and second input VINL can be either AN1 or VR- VINH can be selected using CH0SA3:CH0SA0 bits in AD1CHS reg And VINL can be selected using CH0NA bit in AD1CHS. The Analog channels AN0 to AN15 can be individually made analog or digital using AD1PCFG register. In 16-bit PICs VINH can be scanned. To enable scan mode set the bit CSCNA in AD1CON2. And the channels to be scanned are to be selected using AD1CSSL registers. The selected channels are automatically scanned and the result is stored in buffer. AD1CSSL Register bit15 CSSL13=0 CSSL14=0 CSSL1 bit0 CSSL0 CSSL2 CSSL15 CSSL14 CSSL13 ………… bit8 AD1CHS Register bit15 CH0SA1 bit0 CH0SA0 CH0SA2 CH0NA bit7 CH0SA3 CH0SB1 CH0SB0 CH0SB2 CH0NB CH0SB3 --- AD1PCFG Register bit15 CSSL10=0 CSSL13=0 CSSL14=0 CSSL8=0 PCFG1 bit0 PCFG0 PCFG2 PCFG15 PCFG14 PCFG13 …………

85 Channel Scanning INT AD1CSSL Register AD1CON2 Register ADCBUF Buffer
…. - B + AN14 AN5 CH 0 AN4 - AN3 +A AN2 - A AN1 AN0 AN1 VREF- Module has a 16-word buffer Buffer will reset to ADRES0 after each interrupt At end of next conversion, ADRES0 overwritten Can software unload buffer quickly enough? If not, split buffer by setting BUFM = 1 Now module alternates two 8-word buffers BUFS shows buffer in use by A/D Converter BUFS = 1, read ADRES0 - ADRES7 BUFS = 0, read ADRES8 - ADRES15 8 samples per interrupt max when BUFM = 1 A/D Setup Setup analog pins, reference source Select output data format Select conversion clock, trigger source Enable auto-sample, if desired Set auto-sample time, if using auto-trigger Select A/D inputs and groups Enable ALTS, if using group A and group B Enable input scan, if desired Select S/H channels, SIMSAM if desired Select SMPI, buffer mode bit15 bit0 AD1CSSL Register CSSL15 CSSL14=0 CSSL14 CSSL13=0 CSSL13 ………… CSSL2 CSSL1 CSSL0 bit8 AD1CON2 Register bit15 CSSL13=0 CSSL14=0 BUFM bit0 ALTS CSNA VCFG2 VCFG1 VCFG0 SMPI1 SMPI 0 SMPI3 SMPI2 BUFS bit7 ---

86 10-bit ADC - Block Diagram
Mux A VINH S/H VINL Mux B AD1CON1<ASAM> 1 Conversion complete Signal AD1CON1<SAMP> There is one more option in 16-bit PICs that the sample and hold can be alternated between MUX A and MUX B This is done by setting the bit ALTC in AD1CON2 reg If VINH of MUXA is one of the channel and the VINH of MUXB is some other channel then these 2 channel will be sampled alternatively. Module has a 16-word buffer Buffer will reset to ADRES0 after each interrupt At end of next conversion, ADRES0 overwritten Can software unload buffer quickly enough? If not, split buffer by setting BUFM = 1 Now module alternates two 8-word buffers BUFS shows buffer in use by A/D Converter BUFS = 1, read ADRES0 - ADRES7 BUFS = 0, read ADRES8 - ADRES15 8 samples per interrupt max when BUFM = 1 A/D Setup Setup analog pins, reference source Select output data format Select conversion clock, trigger source Enable auto-sample, if desired Set auto-sample time, if using auto-trigger Select A/D inputs and groups Enable ALTS, if using group A and group B Enable input scan, if desired Select S/H channels, SIMSAM if desired Select SMPI, buffer mode bit8 AD1CON2 Register bit15 CSSL13=0 BUFM bit0 ALTS CSNA VCFG2 VCFG1 VCFG0 SMPI1 SMPI 0 SMPI3 SMPI2 BUFS bit7 ---

87 10-bit ADC - Block Diagram
AD1CON3<SAMC4:SAMC0> (7) 0 TAD to 31 TAD AD1CON1 <SSRC2:SSRC0> Clearing AD1CON1<SAMP> (0) Active Transition on INT0 pin (1) Timer4 Compare ends (2) Avoid 0 TAD VR- VR+ VINH VR- VR+ S/H A/D converter VINL RESULT AD1CON1<ASAM> Conversion complete Signal ADC1BUF0 : ADC1BUF15 To start sampling there are 2 ways, One auto sample after each conversion and the other Sample on setting SAMPbit when to start conversion also can be selected. There are 4 options One auto conversion after laps of sampling time selected using SAMC4:SAMC0 of AD1CON3 reg The sampling time that can be selected are 0TAD to 31TAD, but avoid 0TAD Second on Timer4 compare ends Third active transition on INT0 pin Fourth after completion of sampling AD1CON1<SAMP> AD1CON1<DONE>

88 10-bit ADC - Block Diagram
AD1CON3<ADCS7:ADCS0> AD Clock Postscaler ÷ by 1 to 256 FCY = FOSC/2 TCY to 256*TCY TAD 1 RCAD The clock to adc can be selected using ADRC bit it can be either ADRC or derivative of system clock The system clock can be fed through the postscaler from 1:1 to 1:256 (PIC24H & dsPIC) In PIC24F devices, the postscaler is from 1:1 to 1:64 (Rev D datasheet shows 8-bits which is an error) Module has a 16-word buffer Buffer will reset to ADRES0 after each interrupt At end of next conversion, ADRES0 overwritten Can software unload buffer quickly enough? If not, split buffer by setting BUFM = 1 Now module alternates two 8-word buffers BUFS shows buffer in use by A/D Converter BUFS = 1, read ADRES0 - ADRES7 BUFS = 0, read ADRES8 - ADRES15 8 samples per interrupt max when BUFM = 1 A/D Setup Setup analog pins, reference source Select output data format Select conversion clock, trigger source Enable auto-sample, if desired Set auto-sample time, if using auto-trigger Select A/D inputs and groups Enable ALTS, if using group A and group B Enable input scan, if desired Select S/H channels, SIMSAM if desired Select SMPI, buffer mode AD1CON3<ADRC>

89 10-bit ADC - Block Diagram
dd dddd dddd ssss sssd dddd dddd dddd dddd dd sddd dddd dd RESULT FORMAT AD1CON2<SMPI3:SMPI0> AD1CON1<FORM1:FORM0> ADC1BUF0 : ADC1BUF7 ADC1BUF0 : : : ADC1BUF15 AD1CON2<BUFS> The result can be stored in 4 different formats They are unsigned integer, signed integer, unsigned fractional or signed fractional. Module has a 16-word buffer Buffer will reset to ADRES0 after each interrupt At end of next conversion, ADRES0 overwritten Can software unload buffer quickly enough? If not, split buffer by setting BUFM = 1 Now module alternates two 8-word buffers BUFS shows buffer in use by A/D Converter BUFS = 1, read ADRES0 - ADRES7 BUFS = 0, read ADRES8 - ADRES15 8 samples per interrupt max when BUFM = 1 The buffer is available only in PIC24F devices. In other 16-bit controllers ADC can be used with DMA and DMA buffer can be used, and all the ADC features are similar to this. ADC1BUF8 : ADC1BUF15 1 AD1CON2<BUFM> = ‘1’ AD1CON2<BUFM> = ‘0’

90 Acquisition/Conversion Timing
Analog Input TAD A/D Clock Start Acquisition Time End Conversion Acquisition Time Conversion Time A/D Sampling Time

91 12-bit A/D Converter Up to 500 K Samples / Sec Sampling Rate
Up to 32 input channels ( 2 x A/D ) 16 conversion results deep buffer (dsPIC30) DMA capable (PIC24H / dsPIC33) Analog Input Range: Vss to Vdd (or VREF- to VREF+) Multiple Trigger sources for Start of Conversion Software Trigger Motor Control PWM Timer 3 External Interrupt Automatic conversion on internal time out

92 PIC24H/30/33 A/D AVDD VR Select VR+ AVSS VREF+ VR- Conversion Control VREF- Input Muxes CH0 AN0 S/H AN1 A/D converter Results Buffer Data Format CH1 * S/H Bus Interface CH2 * S/H ADC peripherals on dsPIC30F DSCs are fixed 4S/H-10 bit, or 1S/H-12 bit, depending on family member (Sensor, General Purpose, Motor Control) ADC peripheral on PIC24F is fixed at 1S/H, 10 bit ADC peripheral on PIC24H/dsPIC33F are programmable: Either 4S/H-10 bit OR 1S/H-12 bit On PIC24H/dsPIC33F devices with 2ADC modules, it is possible to interleave ADC conversions together to achieve up to 2.2MSPS sample rate on a single input. Up to 32 analog input channels may be multiplexed into the S/H inputs CH3 * S/H AN31 Sample Sequence Control * S/H channels 1, 2 & 3 only available on 10- bit mode

93 ADC Configuration and Usage
Lab 4 ADC Configuration and Usage

94 Lab 4: ADC Configuration and Usage
Goal To configure ADC To configure I/O ports To read ADC and o/p on to LEDs To Do: Look into the Hand out provided Expected Result: The average pot value is displayed on LEDs

95 Analog Comparator Module

96 Analog Comparator Block Diagram CMCON<CxOUTEN>
CMCON<CxEN> CMCON<CxNEG> CMCON<CxINV> CMCON<CxOUT> CxIN+ VIN - _ CxIN- Comp CxOUT VIN + CxIN+ + CMCON<CxOUTEN> CVREF This is the block diagram of analog comparator of pic24 The negative input can be either CxIN+ or CxIN- which can be selected using CxNEG bit of CMCON The positive input of comparator can be either CxIN+ or CVREF. This can be selected using CxPOS bit of CMCON The o/p of comparator can be inverted using CxINV bit The o/p can be made to come o pin by using CxOUTEN bit. CMCON<CxPOS>

97 Analog Comparator Voltage Reference Generator
CVRCON<CVRSS> 1 CVRCON<CVR3:CVR0> VREF+ AVDD 8 R 16 – to – 1 MUX CVRCON<CVREN> R R R R CVREF 16 Steps R This is block dia of voltage reference generator used for analog comparator. The input for this generator can be either AVDD or can be the voltage fed on VREF+ pin. This is selected by CVRSS bit of CVRCON There are 16 steps of resistor ladder and the steps can be selected using CVR3:CVR0 bits The step size is also configurable and are “show the table’ R R CVRCON<CVROE> CVRCON<CVRR> 8 R 1 (CVR<3:0>)*CVRSrc/24 1 ((CVR<3:0>)+8)*CVRSrc/32 Step Size CVRR VREF- AVSS CVRCON<CVRSS>

98 Timers

99 Timer Features Five 16-bit General Purpose Timers / Counters
Similar functionality between all 5 timers Asynchronous counter feature only in Timer1 Period Registers for each Interrupt generation on match Reset on match Gated Timer operation on each Interrupt on falling edge of gate Four of these timers (Timer 2+3 & 4+5) can make two 32-bit timers/counters Read out

100 ADC Event Trigger Timer4/5
Timer x PRx ADC Event Trigger Timer4/5 ALL TIMERS TIMER1 ONLY Eq. Comp TSYNC 1 Sync Tx Int Flag TMRx Rst 1 CK TGATE Q D TGATE TCS TCKPS<1:0> SOSC1 SOSC2 LP OSC SOSCEN TON TxCKI 1 X 0 1 0 0 Five 16-bit General Purpose Timers / Counters Similar functionality between all 5 timers Period Registers for each Interrupt generation on match Reset on match Gated Timer operation on each Interrupt on falling edge of gate Four of these timers can make a 32-bit timers/counters Timer function enabled with TON Timer can select internal or external clocks TCS=0 : Internal; TCS=1 : External Timer can pre-scale input clock by 1, 8, 64, 256 TCKPS<1:0> - Timer pre-scale settings Timer can count internal clocks based on an external gate signal TGATE=1 : Gated time accumulation mode Timers differ on handling of external clock TIMER1 is asynchronous Input clock frequency < 25MHz TIMER2 and TIMER4 synchronize the clock after the prescaler Input clock frequency < (prescale * 1/2 Fcy) TIMER3 and TIMER5 synchronize the clock at the input of the timer Input clock frequency < 1/2 Fcy Timer1 can run on separate oscillator which runs on KHz Timer1 can count an asynchronous external clock Gate Sync Prescaler 1, 8, 64, 256 TCY TGATE TCS

101 **T3CON/T5CON SFRs bits are ignored when in 32-bit timer mode
32-bit Timer (T2+T3/T4+T5) Write TMR2/4 TMR3/5HLD TxCON<T32> Read TMR2/4 Reset TMR2/4 TMR3/5 Sync ADC Event Trigger (Timer 5 only) MSW LSW Comparator x 32 Equal T3/T5 Interrupt Flag PR2/4 PR3/5 1 TGATE TGATE TCS Q D Timer3/Timer2 pair into 32-bit Timer Timer5/Timer4 pair into 32-bit Timer They are configured as 32 bit by setting T32 bit. Once configured as 32 bit timers t3 con and t5 con regs becomes useless. 16-bit writes buffered to allow 32-bit counter updates TGATE TCS CK TCKPS<1:0> TON 1 X T2CKI/ T4CKI Prescaler 1, 8, 64, 256 Gate Sync 0 1 **T3CON/T5CON SFRs bits are ignored when in 32-bit timer mode 0 0 TCY

102 Configuration of 32-Bit Timers
Lab 5 Configuration of 32-Bit Timers

103 Lab 5: Configuration of 32-Bit Timers
Goal Understand working of Timers in 32 bit mode Configure the Timer 2/3 pair for 32 bit mode Implement a stop watch To Do: Look into the Hand out provided Expected Result: Press the Switch S3 to start timer Again press the Switch S3 to stop timer and LCD displays the Time elapsed between the start and stop

104 Input Capture

105 Timer running Frequency
Why Do We Need IC Module Consider an Example to measure the Pulse width of the signal The IC Module should be configured to Capture on Every Edge Interrupt on every Second Event Then the Pulse width of the signal can be found by using the formula: - This is one of the example to show the usage of IC module Here we are measuring the pulse width of a signal………. = Buffer 1 Buffer 0 Pulse Width Timer running Frequency

106 Input Capture Input Capture Up to five Input Capture Channels
Captures 16-bit timer value Tcy Resolution Timer 2 or Timer 3 as time base Read out

107 Edge Detection Logic and Sync
Input Capture TMR2 TMR3 Prescaler Counter ICx Edge Detection Logic and Sync ICTMR Module Control Logic ICxF Interrupt Flag ICxBUF FIFO Input capture is the module which captures the timer value on the selected event. There is a 4 level FIFO to store the captured values. The events on which capture can happen are “read out the ICM2:ICM0 combinations”. When to get interrupted also can be selected. There are four options they are “read out ICI1:ICI0 combinations” ICxCON<ICI1:ICI0> ICxCON<ICM2:ICM0> 11: Interrupt on every fourth capture event 10: Interrupt on every third capture event 01: Interrupt on every second capture event 00: Interrupt on every capture event 111: Input Capture functions just as an interrupt pin while in SLEEP or IDLE mode 101: Capture on every sixteenth rising edge 100: Capture on every forth rising edge 011: Capture on every rising edge 010: Capture on every falling edge 001: Capture on every edge (both rising and falling) 000: Capture module is turned off

108 Output Compare and PWM

109 Output Compare & PWM Up to 8 Output Compare / PWM Channels
Timer 2 or Timer 3 as time base 16-bit Compare Minimum 1Tcy pulse width allowed Several Compare Modes: Set, Reset or Toggle Pin Single Pulse, Continuous pulse PWM Single Compare Match Mode (using OCxR) Dual Compare Match Mode (using OCxR & OCxRS) Read out the features

110 OCM<2:0> Mode Select
Output Compare S R Q Output Compare Logic Comparator OCxR OCxRS OCTSEL TMR2 Timer2/3 Period Match OCFA/B OCFx OCM<2:0> Mode Select OCxIF Interrupt Flag TMR3 OCxCON<OCM2:OCM0> This is the block dia of output compare. Within a PWM period we can have single (OCxR) or dual (OCxR + OCxRS) compare matches On match of timer with the compare registers any set activity will happen on the pin. The activities that can be set are “rea out OCM2:OCM0 combinations” With respect to PIC 18 there are some new modes they are: Dual compare mode for single output is accomplished by load 2 16-bit compare registers for start and end time of pulse. Start time is relative to timer = 0x0000 start. Enable peripheral and a single pulse will be generated on pin. Pin state can start low and pulse high or start high and pulse low. The period register value must be greater than the end edge compare register value for correct operation. Dual compare mode for continuous output pulses is accomplished just like above except a continuous stream of pulses is generated. The net benefit is reduced CPU intervention for the generation of output pulse(s). In addition very short pulses can be generated since no latency is involved for writing to the second compare register as before. Max resolution specified on bullet 2 is based upon 25MIPS. 111: PWM mode with Fault pin option 110: PWM mode without Fault pin option 101: Initialize OCx-low, generate continuous signal 100: Initialize OCx-low, generate single pulse 011: Toggle OCx on every compare match 010: Initialize OCx-High, pull OCx low on compare match 001: Initialize OCx-low, pull OCx high on compare match 000: Compare module is turned off

111 Output Compare Module PWM mode
16-bit glitch-less (double buffered) PWM output Full range of 0 to 100% duty cycle Wide frequency range Selectable PWM shutdown on fault detection This is an Asynchronous shutdown These are the features of PWM mode “read out”

112 OC PWM Mode On timer period match On OCxR match
PR TMR COUNT OCxR Time OCx On timer period match OCx set, TMR COUNT cleared OCxRS copied to OCxR On OCxR match OCx cleared Read out the text showing the top figure. OCxRS OCxR

113 UART

114 UART Features 4-deep FIFO Transmit Data Buffer
4-deep FIFO Receive Data Buffer Parity, Framing and Buffer Overrun Error Detection Support for 9-bit mode with Address Detect (9th bit = 1) Transmit and Receive Interrupts Loopback mode for Diagnostic Support LIN 1.2 Protocol Support IrDA® Support Read out

115 Transmit Shift Register
UART Module – Transmit 16 Internal Data Bus Word/Byte Write Word Write UxMODE UxSTA UTX8 UxTXREG Transmit Control Control UxTSR Control Buffer Generate Flags Generate Interrupt Transmit FIFO Load UxTSR UxTXIF UTXBRK Transmit Shift Register UxTSR This is the block diagram of UART module in Transmit mode. <click> The UART has a 4 level FIFO buffer which can be configured using the UxMODE register. Writes to UxTXREG load data into the buffer. The control registers UxMODE and UxSTA allow for features of the UART to be configured. UxSTA also provides bits indicating the status of the UART. The UART module has a built in parity generator which can be configured with one of 4 parity settings. These are listed in the handout The UART automatically transmits a stop bit when the TSR is empty. It can be configured to transmit one or two stop bits The CTS flow control signal is implemented in hardware. This will be explained in more detail later. Like in PIC18, the module has a break sequence which is useful in LIN protocol. (Start) (Stop) UxTX Parity Generator ÷16 Divider UxCTS

116 ReceiveShift Register
UART Module – Receive 16 Internal Data Bus Word/Byte Read Word Read UxMODE UxSTA URX8 UxRXREG Receive Control Generate Flags Generate Interrupt Shift Data Character Receive FIFO LPBACK Load UxRXREG UxRXIF UxTX ReceiveShift Register UxRSR This is the block diagram of UART Receive module <click> The UART receiver also has the 4 level FIFO buffer. Reads from UxRXREG read the first item in the buffer. The receiver module has a buffer which holds the framing and parity bits. This buffer is used to set the error flags in UxSTA based on the data that is at the top of the buffer. Loopback mode can be used to help debug an application. In loopback mode the receive pin is disabled and transmitted data is mirrored into the receiver. A full flow control system is built into the UART. The module can be configured with no flow control pins, just ~RTS, or ~RTS and ~CTS. The module also provides a 16x Baud clock which can be output to the BCLKx pin for external IrDA encoding and decoding. In addition to feature specifically noted here the UART module supports LIN 1.2 protocol IrDA 9-bit Address detect (RS-485) Hardware auto baud Fully integrated baud rate generator with 16-bit prescaler to create baud rates from 1Mbps to 1bps at 16 MIPs External 16x baud clock for external IrDA encoder/decoders -Start bit detect Parity check Stop bit detect Wake Logic UxRX ÷16 Divider 16x Baud Clock BCLKx/UxRTS UEN Selection BCLKx UxRTS UxCTS UxCTS

117 UART with CTS and RTS Controlled Transmission and Reception
Simplex Mode Flow Control Mode May I send something? I am ready to receive I am ready to receive DTE 16-bit Micro DCE Modem RTS CTS RS232 Transceivers DTE 16-bit Micro PC RTS CTS RS232 Transceivers The 16-bit controllers UART module also supports controlled transmission and reception. In previous applications handshaking would be ignored because of the overhead required. Now applications can be designed the same way, and still benefit from the robustness of handshaking. RTS can be configured to operate in either Flow Control mode or Simplex mode. In simplex mode the RTS pin should be connected to RTS pin and CTS to CTS. In this mode the transmitter in our case it is a 16 bit controller sends a request “May I send something?” by pulling the RTS line low. If the receiving end, in this case it is a Modem if ready to receive then pulls the CTS line low. The transmitter checks for CTS low and finding it starts transmission. The other example where Simplex mode is used is PC and printer In case of Flow control mode a DTE is communicating with another DTE or a DCE with another DCE. In this case the RTS one is connected to CTS of other and the RTS of that to CTS of this. In this case both can transmit and receive. Who ever is ready to receive pulls the RTS line low. Who ever wants to transmit should check CTS for low and can start transmission The other example where Flow control mode is used are PC and PC or Micro and Micro. Ok, go ahead and send. Simplex Mode Flow Control Mode

118 UART - IrDA® Support Built-in IrDA Encoder and Decoder
The IrDA Encoder and Decoder can be enabled by setting UxMODE<IREN> bit 16x Baud Clock is generated to support external IrDA Encoder and Decoder 16x Baud Clock is generated by setting UxMODE<UEN1:UEN0> to ’11’ The generated Baud Clock is available on the pin BCLKx The UART module has some key features that primarily support the IrDA, The UART module provides two types of IrDA support: External IrDA encoder and decoder device support or built in IrDA encoder and Decoder. It can generate 16x Baud clock, which is available on the BCLK output pin. This 16x baud clock can be connected to an external Encoder and Decoder device along with the UART data pins TX and RX.

119 Optical Communication
Two ways to connect LED I/O Vdd Typically some kind of LED source is used for optical communication. The control logic will depend on the physical connection of the LED. I/O Logic High = LED On Logic Low = LED off Logic Low = LED On Logic High = LED off

120 IrDA® Mode Bit Encoding
UxTX Data UxTX UxTX 16x Baud Clock UxTX Data ‘0’ Transmit Bit 8th 11th The IrDA is optical communication so LED can be connected in either of the way described earlier. Therefore module provide UxTx and UxTX\ (complemetary) output. One option to reduce the power consumption in LED is to reduce on time. The IrDA protocol does the same thing. The bit period can be divided in 16 periods. For IrDA communication the LED is turned on for smaller portion of the bit period. The built in encoder takes the serial data and encodes before transmission or the received IrDA data is decoded before giving it to the UART. This slides explains the encoding of UART data. Transmit bit data bit '0' gets encoded as shown in this slide. It remains '0' for the first 7 periods of the 16X Baud Clock, as '1' for the next 3 periods and as '0' for the remaining 6 periods. Transmit bit data of '1' gets encoded as '0' for the entire 16 periods of the 16X Baud Clock.

121 UART - LIN Support Transmission of Break Characters Autobaud Detection
A Break character can be transmitted by setting the UxSTA<UTXBRK> bit for at least 13 bit times Autobaud Detection The UART module has some key features that primarily support the LIN protocol. Setting the UART Transmit Break bit, and keeping it set for a minimum of 13 bit times, generates a ‘zero’ character on the Transmit pin. In other words, the Transmit pin is held low as long as the UART Transmit Break bit is set. A STOP bit can then be generated by clearing the UART Transmit Break bit. If the receiving device does not receive a STOP bit, then it generates a Framing Error. Unlike other characters, a Break character does not generate a Transmit Interrupt. Another feature that supports the LIN protocol is Autobaud Detection. This refers to the capability of the UART to internally route the Receive signal to a specified Input Capture pin. The corresponding Input Capture channel, IC1 for UART1 and IC2 for UART2, should be configured to capture every edge. Now, if a START bit is received, the Capture values of its falling and rising edge can be utilized by user software to determine the current Baud Rate of communications on the bus. This feature is enabled by setting the Autobaud bit in the UART Mode Register. Master or

122 LIN - Protocol UxSTA<UTXBRK> Enables Transmitting Break condition on the bus (Drive low TX pin for 13-Bit Time) UxMODE<ABAUD> Enables to measure the baud-rate using Input Capture unit during SYNCH Field (0x55). The LIN protocol is divided in three main section. Initial portion is break character. It is 12 – 13 bit period long 0 transmission. The slave device wakes up from sleep on reception of break character. The longer period provides enough time for oscillator to achieve stable clock operation. The 16-bit devices has HW support for both transmission and reception of break character. Middle portion is sync field. The character 0x55 is used to synchronize baud rate of Master and slave. The PIC24F, PIC24H and dsPIC33 devices have HW support for auto baud (for baud sync) After sync filed is a data field. The first data is called identifier field. It is like command. It is followed by data bytes. Master or

123 UART Configuration and Usage of FIFO
Lab 6 UART Configuration and Usage of FIFO

124 LAB 6: Working with UART Goal: To Do: Expected Result:
Understand Configuration of UART module Understand Transmit and Receive interrupts Write a software to Transmit and Receive data using UART To Do: Look into the Hand out provided Expected Result: LED D3 flashes at different rates to indicate lower CPU time spent handling UART data using FIFO buffer

125 I2C™

126 I2C™ Overview Synchronous 2-wire communication Master-Slave protocol
Serial interface (Half-duplex): SDA: Data line to & from the master SCL: Clock line, master controlled I2C is implemented in the PICmicro by a hardware module called the Master Synchronous Serial Port, known as the MSSP module . This module is built into many different PICmicro devices. It allows I2C serial communication between two or more devices at a high speed and communicates with other PICmicro devices and many peripheral IC’s on the market today. I2C is a synchronous protocol that allows a master device to initiate communication with a slave device. Data is exchanged between these devices. We will look at this more in detail as we progress though this presentation. Normally, the master device controls the clock line, SCL. This line dictates the timing of all transfers on the I2C bus. Other devices can manipulate this line, but they can only force the line low. This action means that item on the bus can not deal with more incoming data. By forcing the line low, it is impossible to clock more data in to any device. This is known as “Clock Stretching”. I2C is also bi-directional. This is implemented by an “Acknowledge” system. The “Acknowledge” system or “ACK” system allows data to be sent in one direction to one item on the I2C bus, and then, that item will “ACK” to indicate the data was received. We will look at this in detail later, as you can see, this is a powerful feature of I2C. Since a peripheral can acknowledge data, there is little confusion on whether the data reached the peripheral and whether it was understood. Since I2C has a clock signal, the clock can vary without disrupting the data. The data rate will simply change along with the changes in the clock rate. This makes I2C ideal when the micro is being clocked imprecisely, such as by a RC oscillator. SDA - This signal is known as Serial Data. Any data sent from one device to another goes on this line. SCL - This is the Serial Clock signal. It is generated by the master device and controls when data is sent and when it is read. As mentioned earlier, the signal can be forced low so that no clock can occur. This is done by a device that has become too busy to accept more data.

127 Note: Diagrams are symbolic
Signal Connection Serial interface (Half-duplex): SDA: Data line to & from the master SCL: Clock line, master controlled Wired-AND connection Float High (logic 1) Drive Low (logic 0) Vdd Float High Vdd Drive Low I2C lines can have only two possible electrical states. These states are known as “float high” and “drive low”. I2C works by having a pull-up resistor on the line and only devices pull the line low. If no device is pulling on the line, it will “float high”. This is why pull-up resistors are important in I2C. If no pull-up resistor were used, the line would float to an unknown state. If one tried to drive the line high, it might cause contention with a device trying to drive the line low. This contention could damage the either or both devices driving the line. To prevent this, the pull-up-drive low system controls when one device has control of the bus. If another device tried to use the bus when it was busy, it would find the bus to be driven low already and know it was busy. Even if it tried to use the bus accidentally, it would only drive it low and not damage other devices. The diagrams shown are symbolic. In each case, the solid diagram represents the ACTIVE part of the bus. In the case of driving low, the buffer is actively pulling the line low. In the case of floating high, the resistor pulls the line high, while the buffer is turned off. A buffer turned off has very high impedance and behaves as if it were disconnected. Only the output buffers are shown for simplicity. Note: Diagrams are symbolic

128 I2C™ Master mode and Slave mode 7- and 10-bit address Slave mode
Clock Stretching: Handshake Mechanism for suspend and resume operation Multi-Master operation: Detects bus collision and arbitrate accordingly General Call support Address Masking These are the features of I2C module “read out”

129 I2CBRG(9-bit) MASTER Mode
RSR I2CxRCV(8-bit) Shift Clock SDAx Add. Match Detect I2CxADD(10-bit) I2CxMSK(10-bit) SCLx I2CxTRN(8-bit) Shift Clock I2CxCON(16-bit) This is the block dia of I2C in master mode. In Master mode clock is generated by the module it uses TCY/2 as its source. On setting the bits corresponding to the start, stop conditions they are generated by control logic. On writing to I2CxTRN reg it is transferred to RSR and shifted out with the clock. When want to read generates the clock and data will be received to RSR and shifted to I2CxRCV reg. This is the block dia in slave mode. Here clock is received from Master. On address match it generates the acknowledgement the slave can be configured as 10 bit slave or 7 bit slave. Even there is a 10 bit mask for address match. So all the bits of the address need not match to generate the acknowledgement some bits can be masked. After address match it depends on Master to read or write. If master wants to read I2CxTRN is will be shifted out on the master’s clock. If Master wants to write what ever is on SDA is shifted in to RSR with Master’s clock and once 8 bit is received acknowledgement is generated and is shifted to I2CRCV reg. There is a I2CSTAT reg to indicate the different status of the slave. I2CBRG(9-bit) MASTER Mode BRG TCY/2 Control Logic MASTER I2CxSTAT(16-bit) SLAVE

130 Address Masking What is it?
It allows a PIC® MCU to ACK more than one address. What is it good for? IPMI: Intelligent Platform Management Interface Embedded system device networking: using a PIC MCU as multiple I2C™ devices A specification, developed by Dell, HP, Intel and NEC, that defines interfaces for use in monitoring the physical health of servers, such as temperature, voltage, fans, power supplies and chassis. The goal is to allow easier management of large numbers of servers from multiple vendors. it can help reduce costs by letting administrators remotely manage, diagnose and reboot servers whether the operating system is running or the system has crashed. It does it regardless of platform. Since IPMI communicates over LAN, IPMI enabled servers can be managed remotely from any location. IPMI provides vital administrative tasks including: the IPMI bus uses I2C nodes as message repeaters in a distributed network. To allow a node to repeat all messages, the slave module must accept all messages, regardless of the device address.

131 Embedded System Device Networking
PIC MCU SLV PIC® MCU MSTR SCL SDA Example of Embedded I2C network without address masking A D C E P R O M P W M R T C

132 Embedded System Device Networking
PIC MCU SLV PIC® MCU MSTR A D C R T C SCL SDA Using address masking can help you eliminate precious board space and unnecessary external peripherals without changing you master code. Eliminate external I2C™ devices E P R O M P W M

133 Address Masking Example
By setting the ADMSK bits in SSPCON2, we mask the address bits. In this case ADMSK[7:1]= S A7 A6 A5 X A3 X X R/W=0 ACK All addresses that will be ACKed: A7.A6.A5.0.A A7.A6.A5.0.A3.0.1 A7.A6.A5.0.A A7.A6.A5.0.A3.1.1 A7.A6.A5.1.A A7.A6.A5.1.A3.0.1 A7.A6.A5.1.A A7.A6.A5.1.A3.1.1

134 SPI

135 SPI - Overview Serial transmission and reception of 8/16-bit data
Full-duplex, synchronous communication 4-wire interface Supports 4 different clock formats and serial clock speeds up to 10 Mbps Buffered Transmission and Reception

136 SPI Block Diagram SCKx SSx Sync Control Clock Control Select Edge SDOx
Pre- scaler FCY SSx Sync Control Clock Control Select Edge SDOx Clock Enable SDIx MASTER SPIxSR SLAVE This is the block dia of SPI module in Master mode. There will be Clock enable signal as Master need to generate the clock. On every clock the data on SDI is shifted in to SPI SR and the data on SPI SR is shifted out onto the SDO pin. There is a 8 level FIFO to handle data in and data out. This is SPI in Slave mode, the clock is received from Master. So no clock enable signal. Remaining functions are similar to Master, like on each clock the data on SDI is shifted into SPI SR and Data from SPISR is shifted out to SDO pin. Even in Slave mode there is 8 level FIFO. 8-Level FIFO (Enhance Mode) PIC24F devices utilize FIFO. Other 16-bit devices can use DMA for data transfers SPIxBUF

137 SPI Clock CKP: Clock Polarity Select 0: Idle State of CLK is LOW
1: Idle State of CLK is HIGH CKE: Clock Edge Select 0: Transmit data on Idle to Active Edge 1: Transmit data on Active to Idle Edge SPI module supports both Idle clock states, high and low. Transmission can be done on any of the edge active clock to Idle clock or Idle clock to active clock. There are 2 prescalers Primary which can scale to 1:1, 1:4, 1:16 or 1:64 And Secondary prescaler which can scale to 1:1, or 1:2, 1:3 or so on to 1:8. SPIxCON Register bit15 bit8 - FRMEN SPIFSD - DISSDO MODE16 SMP CKE=1 bit7 bit0 SSEN CKP=0 MSTEN=1 SPRE<2:0> PPRE<1:0>

138 SPI - Serial Clock Formats
(a) CKP = 0, CKE = 0 (a) SCK (b) CKP = 0, CKE = 1 (b) SCK (c) CKP = 1, CKE = 0 (c) SCK (d) CKP = 1, CKE = 1 (d) SCK Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 SDO (0x69) (a) and (c) 1 When CKP = 0 and CKE = 0, the idle state of clock is low and on rising edge of clock data is transmitted. When CKP = 0 and CKE = 1, the idle state of clock is low and on falling edge of clock data is transmitted, but the MSB which is transmitted first will be available on pin before the clock starts. When CKP= 1 and CKE = 0, the idle state of clock is high and on falling edge of the clock the data is transmitted. When CKP = 1 and CKE = 1, the idle state of clock is high and on rising edge of clock data is transmitted, but the MSB which is transmitted first will be available on pin before the clock starts. SDO (0x69) (b) and (d) 1

139 Special Features

140 Powering CPU PIC24FJ, PIC24HJ, dsPIC33FJ
3.3V Internal on-chip regulator 2.5V nominal for the CPU 3.3V nominal for the I/O and peripheral voltage Low ESR cap required 10µf recommended VREG Control pin (PIC24F) Enable/disable the regulator BOR Vdd VREG Control Regulator Vddcore/Vcap 10µf CPU The CPU of 16-bit PICs works at 2.5 volts but the supply for the device is 3.3 volts so there is a 2.5 v Voltage regulator with in the device. In PIC24F option to enable /disable is given. In case it is disabled 2.5V has to be fed on VD core pin. In case of PIC24H/dsPICs voltage reg is always enabled. A low ESR cap of around 10uF should be connected to Vcap pin in case of using the voltage reg. And when ever voltage regulator is enabled a fixed voltage BOR is enabled. This example shows that the reg is enabled. -10uf is currently the recommended typical Vcap. (data still pending) -Some devices do not have a VREG control pin, like the 45J10 (next slide) PIC24FJ128GA

141 Power Management Power management options: Lower the supply voltage
Lower the clock speed Postscaler Clock switching Disable unused peripherals Minimal power saving Execute pwrsav instruction SLEEP IDLE DOZE mode LPRC FRC POSC SOSC FRC + PLL POSC + PLL These are the some of the options to save power. On fly clock switching is possible. There are 2 power save modes SLEEP where whole chip will go into sleep, IDLE mode where the active peripherals keep working and CPU goes to sleep. There is one more mode DOZE mode where CPU can be made run and fractional speed of the peripheral running speed.

142 Power Management Exiting Power Saving mode How to know it is a wake up
System Reset Watch Dog Timer Any enabled interrupt Interrupt Priority Level <= CPU IPL Execute the next instruction Interrupt Priority Level > CPU IPL Execute the interrupt handler How to know it is a wake up Check RCON<SLEEP> and RCON<IDLE> bits Once entered into power saving mode no application requires to be remained there permanently. They have to enter and exit as per requirements. So how to exit Power save modes. These are the ways. System Reset, Watchdog timer timeout Occurrence of any enabled interrupt. There are the status bits to tell from which mode the exit has happened. Is the exit is from SLEEP mode or IDLE mode.

143 Clock Sources Primary Oscillator EC Clock OSCI XT,HS CPU Clock
Crystal OSC Post Scaler CPU Clock 4x PLL OSCO Fast RC 8.0 MHz Post Scaler Peripherals Clock Low Pwr RC 32KHz Here is a visual representation of the system clock generation options. Let us go through part by part SOSCI SOSCO 32KHz Secondary Crystal OSC

144 Clock Sources XT,HS Crystal OSC EC Clock Primary Oscillator XT, EC OSCI , HS 4x PLL XTPLL, ECPLL, OSCO 32KHz Secondary Crystal OSC SOSC There are 3 types of primary oscillators XT, HS or EC. XT and HS are crystal based and in EC mode the clock should be fed on OSCI pin When EC or HS modes are used the clock can be fed to the PLL and get 4X times the input frequency to get the maximum CPU performance. The internal oscillator mode will save power as well as reduces EMI and can be run up-to 32MHz with PLL. In other than PIC24F the PLL can be selected one of 4x 8x or 16x The system also can be run on secondary oscillator which runs on KHz crystal. It is 4x PLL only in PIC24F. In other 16 bit controllers it can be configured into 4x, 8x or 16x PLL

145 Clock Sources Low Pwr. RC 32 KHz CLKDIV<RCDIV2:RCDIV0>
PostScaler, ÷ by 1, 2, 4, 8, 16, 32, 64 or 256 CLKDIV<RCDIV2:RCDIV0> FRCDIV Fast RC 8.0 MHz FRC 4x PLL FRCPLL (÷1 or ÷2) LPRC Low Pwr. RC 32 KHz There are 2 internal RC oscillators One is 8 MHZ Fast RC this can directly be fed to CPU Or can be fed through the divide block. There are options of divide by 1, 2, 4, 8, 16, 32, 64 and 256 to get The frequencies 8M, 4M, 2M, 1M, 500K, 250K, 125K and 31.25K The output of this divider can be fed to 4x PLL but only when to o/p frequency of divider is 4M or 8M. The other internal RC oscillator is Low power 32KHz RC oscillator.

146 Power Saving Technology
On-the-Fly Clock Switching OSCCON<OSWEN> bit to enable On Fly Clock Switching and OSCCON<NOSC2:NOSC0> bits to select the new clock source Instruction-Based Power Saving Modes Sleep Idle LPRC FRC POSC SOSC FRC + PLL POSC + PLL On the fly the clock can be switched and all possible clock switching is shown here. There is no restriction of switching to any mode from any mode. The NOSC2:NOSC0 bits in OSCCON should be configured to select the new oscillator and the bits COSC2:COSC0 indicates the current oscillator selection.

147 Doze Mode CLKDIV<DOZE2:DOZE0> PostScaler ÷ By
1, 2, 4, 8, 16, 32, 64, 128 CPU Clock XT, HS, EC HSPLL,ECPLL CLKDIV<DOZEN> FRC FRCDIV Peripherals Clock FRCPLL Software-controlled Doze mode Doze mode useful for incremental power savings. For timing-sensitive applications such as serial communication. When any of the oscillator mode is running doze mode can be entered. The CPU clock can be 1, 2, 4, 8, 16, 32, 64, or 128 times slower than the peripherals. LPRC SOSC

148 Fail-Safe Clock Monitor
What happens on Oscillator Failure? Device switches automatically to the FRC oscillator if FSCM is enabled FSCM controlled by the bit FOSC<FCKSM> Oscillator Failure Trap is generated Code execution vectors to the Oscillator Fail trap handler, if one exists. Here the application should: Clear the Clock Fail bit, OSCCON<CF> Clear the Osc FAIL trap flag, INTCON1<OSCFAIL> Switch to required Clock Source form FRC Execute a RETFIE When primary or secondary clock is used clock failure can be monitored. This is done by enabling FSCM On clock failure the system clock will be automatically switched to FRC The Oscillator failure trap will be generated and will be vectored to oscillator failure trap. Here before exiting the trap, clock fail bit should be cleared, osc fail trap flag should be cleared Switch the clock from FRC to required clock other than failed clock.

149 Resets PIC24 RESETS For all the resets PC vectors to address 0
Power-on Reset (POR) Pin Reset (MCLR) RESET Instruction (SWR) Watchdog Timer Reset (WDT) Brown-out Reset (BOR) Trap Conflict Reset (TRAPR) Illegal Opcode Reset (IOPUWR) Uninitialized W Register Reset (UWR) Configuration word mismatch Reset (CM) For all the resets PC vectors to address 0 16-bit PICs has lots of resets. They are Power-on Reset (POR) Pin Reset (MCLR) RESET Instruction (SWR) Watchdog Timer Reset (WDT) Brown-out Reset (BOR) Trap Conflict Reset (TRAPR) Illegal Opcode Reset (IOPUWR) Uninitialized W Register Reset (UWR) Configuration word mismatch Reset (CM)

150 Watchdog Timer Recovers from software malfunction
Resets MCU if not attended on-time Software must clear it periodically (CLRWDT) Programmable timeout period 1 ms to 131 s typical Fuse time programmable prescaler and postscaler Both Fuse time and Run time Enable available Option to select Windowed WDT CLRWDT should be used only in last quadrant If CLRWDT is used earlier, resets the device PIC24 has Watchdog timer which helps to recover from software malfunction If wdt timeout occurs while CPU is executing then CPU gets RESET else if timeout occurs while is SLEEP or IDLE mode CPU wakes-up and continues from there. The timeout period can be programmed between 1ms to 131s. There is windowed WDT option which when selected CLRWDT instruction can be only used in last quadrant of the WDT period. Otherwise CLRWDT instruction resets the device. The purpose of the windowed WDT option is for devices with very specific loop times – if the CLRWDT instruction executes to early, then something has occurred to alter the normal program flow (PC corruption, etc.) and the device should thus be reset. Prescaler that can be configured for either 5-bit (divide-by-32) 1ms or 7-bit (divide-by-128) 4ms.

151 Programming Support In Circuit Serial Programming™ (ICSP™):
Device can be programmed in circuit Useful to Combine Programming and Final test Enhanced In Circuit Serial Programming™ (Enhanced ICSP™) capability: Uses programming executive for faster programming Run Time Self Programming (RTSP): Device can program its own Flash memory Useful for Remote code updates JTAG Interface Programming support through Serial Vector Format files Provides for boundary scan The different programming methods of 16-bit MCU are ICSP: 2 wire programming method found on all Microchip MCU and DSC products. Enhanced ICSP: This is also 2 wire programming, once entering SPI1 module gets connected to the PGC and PGD pins. The devices will be having the programming executive in them, this reads the SPI data and program the device. RTSP: A feature support on all PIC24 devices. JTAG: The JTAG Interface on the PIC24 devices provides for two basic functions: BSDL and Programming support via SVF. 1. Programming of the PIC24 will be supported implementing the SVF. We Are working this now. We are envisioning that MPLAB will support such a file format if JTAG is enabled in a future release. 2.Regarding Boundary scan Microchip will provide Boundary Scan Definition (BSDL) files for all PIC24F and PIC24H devices. The BSDL files and the devices they represent support IEEE The IEEE-1532 standard is an enhancement to the IEEE standard where the TAP state machine is predefined and designed to handle the additional ISP instructions.

152 Summary

153 Summary We reviewed the 16-Bit Family Architecture
16-bit Datapath & Key CPU registers Program/Data Memory and Data Access from Program Memory Interrupt Handling and latency We reviewed the MPLAB C30 C Language Extensions The basics of creating an embedded c-application for the PIC24F/dsPIC We reviewed the 16-bit Family Basic Peripherals I/O Ports ADC Comparators, Voltage Reference Timers Input Capture Output Compare & PWM USART I2C™ SPI Special features of 16-bit microcontrollers

154 Summary Carried out the Labs on Using MPLAB and C30
PSV initialization and usage Interrupt handling and its priority setting Initialization and ADC conversion 32-bit Timer configuration and its usage UART configuration and use of FIFO

155 Development Tools Used
Real ICE DV244005 Explorer 16 with PIC24FJ128GA010 PIM DM240001

156 References PIC24F, PIC24H, dsPIC33 F Datasheets
PIC24F family reference manual dsPIC30F family reference Manual Explorer 16 User’s Guide C30 Compiler User’s Guide Other 16-bit RTC Courses 204 ADV: Advanced 16-bit peripherals 103 ASP: Intro. To 16-Bit Arch. & Assembly Language Programming 104 DSP: dsPIC DSP Engine 301 MCW: BLDC Motor Control Using dsPIC 312 DPS: SMPS Design Using dsPIC

157

158 MPLAB C30 C-Language Extensions
Appendix A MPLAB C30 C-Language Extensions

159 MPLAB C30 Compiler 3 Products, Targets ANSI: 1989 standard
MPLAB C Compiler for PIC24 MCUs and dsPIC DSCs (SW006012) $895US (one-time cost) MPLAB C Compiler for dsPICs DSCs (SW006013) $495US MPLAB C Compiler for PIC24 MCUs (SW ) Targets ANSI: 1989 standard Built off GCC Compiler Standard C functions Run time libraries Free Student Versions available (Optimizations disabled after 60 days) The C30 compiler is used for all Microchip 16-bit devices. It is based off of the GCC C compiler and mostly complies with ANSI standards. However, it differs from ANSI in some areas necessary to support microcontroller programming. C30 provides many standard C runtime libraries such as stdio, math, etc. These can be included in your project by using the library files located in the “lib” folder of your C30 install. The documentation for these is provided with C30 (DS51456D). Some libraries are included automatically; standard C, maths library, and helper routines. Peripheral libraries and other libraries that may be shipped must be added by the programmer. Note on student version: some optimizations, not all, are disabled after 30 days

160 Development Tools Data Flow
. h C Compiler (and Preprocessor) C Source Files C Header Files Compiler Driver Program Assembly Source Files .inc Assembler Assembly Source Files Assembly Include Files Object Files Executable Archiver (Librarian) .hex C Compiler Compiles C source code into assembly language code Assembler Assembles assembly language code into object files Archiver Groups precompiled object files into a library (archive) for convenient organization of reusable code Linker Takes relocatable code and arranges it into the microcontroller’s memory map according to the guidelines provided in the linker script Compiler Driver Program This command line driver program allows application programs to be compiled, assembled and linked in a single step. Object File Libraries (Archives) Linker .map Memory Map .cof MPLAB IDE Debug Tool .gld Linker Script COFF Debug File

161 C30 C Language Extensions - Agenda -
Program Memory Variables SFR Access Mixing C and Assembly Built-in Functions Specifying Attributes of Variables & Functions Interrupt Support Configuration Settings Support Objective for this section is to cover “what you need to know” to get started with the PIC24F/dsPIC33F using C30. There is a 1-day advanced C30 class planned for release for CY08.

162 Variables in Program Memory
const - data type qualifier indicates that a variable is located in program memory space, and is to be accessed as an “Auto PSV” type (i.e. compiler-managed PSV) ex. const char data[256]; Can optionally place and access constants in data memory using the constants-in-memory memory model const data is limited to <32kB See PSV slides for more options (>32kB) This is the easiest way for you to use PM space variable access using PSV. It does not require you to program PSVPAG. Compiler limits < 32kB of data using “const” keyword See PSV section for other options for PM variable access

163 C30 C Language Extensions
Program Memory Variables SFR Access Mixing C and Assembly Built-in Functions Specifying Attributes of Variables & Functions Interrupt Support Configuration Settings Support Objective for this section is to cover “what you need to know” to get started with the PIC24F/dsPIC33F using C30. There is a 1-day advanced C30 class planned for release for CY08.

164 SFR Access Special Function Registers can be accessed directly in C code: Word access: PORTA = 0xFFEC; SFRNAMEbits.BITNAME can be used to access bits and bit fields e.g. PORTAbits.RA1 = 1; or IPC0bits.INT0IP = 0; _SFRNAME and _BITNAME can also be used to reference an SFR or bit e.g. _PORTA or _RA1 Must use standard header and linker script files SFRs can be accessed in C simply by using the SFR name. “SFRbits.xxx” can be used to access both individual bits and bit fields of any length. Additionally, SFRs and individual bits (not bit fields) can be accessed using the bit name or SFR name preceded with an underscore. NOTE: It is NOT recommended to manually accesses the W registers in C30. C30 uses these as ‘scratch pad’ registers and may write over them if you use them! You can use WREGn to reference them if necessary, but the compiler will warn against this practice (and rightly so).

165 C30 C Language Extensions
Program Memory Variables SFR Access Mixing C and Assembly Built-in Functions Specifying Attributes of Variables & Functions Interrupt Support Configuration Settings Support Objective for this section is to cover “what you need to know” to get started with the PIC24F/dsPIC33F using C30. There is a 1-day advanced C30 class planned for release for CY08.

166 Mixing C and Assembly Assembly files (.s ) can be used in C30 projects and called from C Details available in C30 User’s Guide Inline assembly can be inserted into C source code Simple method: asm(“reset”) asm(“clrwdt”) Complex method: a = b + c There are two ways to use assembly language in C programs: .s files can be included in C30 projects. The functions written in assembly can be called from C if they are declared as global using “.global func1,func2” etc. When calling assembly instructions from C, parameters can be passed through the W registers (the first 16-bits of parameter data in W0, next in W1, etc.). This is the only kind of assembly which can be used to change program flow. DO NOT call gotos/jumps/branches in in-line assembly! Refer to C30 users guide for more detail. Inline assembly can be used for single or short strings of assembly instructions. Simple instructions can be run simply by calling the asm function and passing the assembly string. NOTE: the “simple method” should NOT BE USED to modify or reference W registers! If you are changing W registers, use the complex form. The complex method should be used if you want to change W registers or pass in C variables. You pass C variables to inline assembly instructions using the syntax “%number”. The values to pass are then listed after the assembly command. Detailed syntax for this is in the C30 users guide. Please refer to it before attempting to use this kind of inline assembly! It is possible to pass multiple assembly instructions in one asm call by using the control character “\n” in the string to indicate a return. Note: usually when you use inline assembly, you should include the volatile keyword! This will ensure that C30 does not move, optimize, or otherwise change your assembly instructions asm volatile(“add %1, %2, %0” : “=r”(a) : “r”(b), “r”(c))

167 C30 C Language Extensions
Program Memory Variables SFR Access Mixing C and Assembly Built-in Functions Specifying Attributes of Variables & Functions Interrupt Support Configuration Settings Support Objective for this section is to cover “what you need to know” to get started with the PIC24F/dsPIC33F using C30. There is a 1-day advanced C30 class planned for release for CY08.

168 Built-in Functions Enable use of special hardware features Multiply
Divide Table pointers PSV – retrieve and access PSV information __builtin_mulss(const signed int p0, const signed int p1) __builtin_divsd(const long num, const int den) __builtin_tblpage(const void *p) __builtin_tbloffset(const void *p) __builtin_tblwtl(unsigned int offset, unsigned int data) __builtin_tblrdl(unsigned int offset) There are some Built in functions available in C30. They are common actions which are implemented in such a way to take advantage of features on the hardware. For example: multiply and divide ensure that these math operations are compiled in such a way that they take most advantage of the hardware’s math ability such as multiply and divide instructions. Table reads and writes to read and write non-volatile memory are also provided as built-ins. These functions will perform the NVM unlocking necessary to load the table read or write data. Tblpage and tbloffset will return the address information of a C variable which is stored in NVM memory. The PSV (program space visibility) is also supported with built-ins – we will learn more about this later. __builtin_psvpage(const void *p) __builtin_psvoffset(const void *p)

169 Built-in Functions More efficient code – Faster & Smaller
Bit toggle Locked register writes All DSP Operations Other “built-ins” Nop(), Sleep() & Idle(), ClrWdt() __builtin_btg(unsigned int *, unsigned int 0xn) __builtin_write_NVM(void); //sets WR bit __builtin_write_OSCCONL(unsigned char value) __builtin_write_OSCCONH(unsigned char value) Some things are best done using built-in functions because of efficiency. For example, toggling bits using the C compliment operation “~” is very inefficient due to the way it must be compiled, and will compile as multiple instructions. The built-in __builtin_btg uses the bit toggle instruction of the hardware to toggle a bit in a single cycle. Often, we lock registers from writes to prevent accidental changes to critical data. It is also more efficient to use built-in functions to perform writes to these locked registers. Eg. NVM and OSCCON. These functions ensure that you are not making a mistake with the register unlock sequence and use the most efficient mechanism to unlock and write them. Some commonly used instructions are provided in C that are not technically “built-ins” examples are: nops and power saving modes, as well as clearing the WDT. These can be called as if they were defined as C functions and will execute the corresponding instruction. __builtin_mac(…)

170 C30 C Language Extensions
Program Memory Variables SFR Access Mixing C and Assembly Built-in Functions Specifying Attributes of Variables & Functions Interrupt Support Configuration Settings Support Objective for this section is to cover “what you need to know” to get started with the PIC24F/dsPIC33F using C30. There is a 1-day advanced C30 class planned for release for CY08.

171 Attributes of Variables
The keyword __attribute__ allows you to specify special attributes of variables or structures including Placement of objects in certain locations in memory Alignment of objects to memory boundaries

172 Data Attributes: Examples
Place data at a specific address int MyVar __attribute__((address(0x860))) int __attribute__((address(0x862))) MyVar2 Be careful about overlap and auto variables Place into near memory (below 8kB) char __attribute__((near)) MyVar3, MyVar4 The following slides show examples of possible data attributes. For a full list of attributes, see the C30 Users guide. Read out examples

173 Data Attributes: Examples
Place in a specific section or space int foo __attribute__((section(“ThePlace”))) int bar __attribute__((space(psv))) New section will be created, if needed Spaces: data, prog, psv, eedata Align begin or end to a multi-byte boundary char __attribute__((aligned(32))) MyArray[18] int __attribute__((reverse(64))) EndArray[25] Read out examples. Note the PSV attribute, it will be used in Lab 2.

174 Attributes of Functions
The keyword __attribute__ allows you to declare certain things about your function which help the compiler optimize function calls and check your code Examples include Absolute function placement in memory Specification of ISR functions

175 Function Attributes: Examples
Placement of a function at a particular address Declaration of interrupt service routines… void foo() __attribute__ (address(0x100))) { ... }

176 C30 C Language Extensions
Program Memory Variables SFR Access Mixing C and Assembly Built-in Functions Specifying Attributes of Variables & Functions Interrupt Support Configuration Settings Support Objective for this section is to cover “what you need to know” to get started with the PIC24F/dsPIC33F using C30. There is a 1-day advanced C30 class planned for release for CY08.

177 Interrupt Support Declaring interrupts with the compiler has two components: Declaring a function as an interrupt service routine (ISR) Specifying additional attributes

178 Interrupt Support Declare an interrupt function
void __attribute__((interrupt))_ADCInterrupt(void) Make function use shadow registers void __attribute__((interrupt,shadow))_ADCInterrupt(void) Saves W0-W3 and SR bits with push.s and pop.s Optionally, save other variables on context save void __attribute__((interrupt(save(var1,var2))))_ADCInterrupt(void) Note that 2 new interrupt function attributes have been added to C30 v3.01 (“auto_psv” and no_auto_psv”) Details are in Section 7.10 of the C30 user’s guide, but to summarize: If your ISR is using const variables or strings (compiler-managed PSV, or “auto-psv”), you need to declare the ISR as: void __attribute__((interrupt, auto_psv)) _ADCInterrupt(void) – basically this instructs the compiler to save the PSVPAG context If your ISR is NOT using const variables or strings, you should declare the ISR as: void __attribute__((interrupt, no_auto_psv)) _ADCInterrupt(void) – this will reduce the latency of the ISR If you do not declare “auto_psv” or “no_auto_psv”, the default is “auto_psv” and you will be issued a warning on compile, that the latency will be longer.

179 C30 C Language Extensions
Program Memory Variables SFR Access Mixing C and Assembly Built-in Functions Specifying Attributes of Variables & Functions Interrupt Support Configuration Settings Support Objective for this section is to cover “what you need to know” to get started with the PIC24F/dsPIC33F using C30. There is a 1-day advanced C30 class planned for release for CY08.

180 Configuration Settings
Device configuration can be set in MPLAB IDE using “Configuration bits” window A better way is to use _config directives in C code _CONFIG1(<VALUE1> & <VALUE2>) ; _CONFIG2(<VALUE>); MCU header files contain valid config definitions and mnemonics e.g. _CONFIG1(GCP_OFF & GWRP_OFF & FWDT_ON & ICS_PGx2) Device configuration bits can be set two ways: The Configuration Bits window in MPLAB can set the bits. Note that if you change devices it will reset the bits, so if you use this method, check them often! Config directives can be added to the C code to set the bits. The syntax is _CONFIG1 or 2 with a series of ands to indicate what bits/fields are set or cleared. These config keywords are defined the device header files, so you can look there for information of what they are and what values they set the config bits to.

181 Trademarks The Microchip name and logo, the Microchip logo, Accuron, dsPIC, KeeLoq, microID, MPLAB, PIC, PICmicro, PICSTART, PRO MATE, PowerSmart, rfPIC and SmartShunt are registered trademarks of Microchip Technology Incorporated in the U.S.A. and other countries. AmpLab, FilterLab, Migratable Memory, MXDEV, MXLAB, SEEVAL, SmartSensor and The Embedded Control Solutions Company are registered trademarks of Microchip Technology Incorporated in the U.S.A. Analog-for-the-Digital Age, Application Maestro, dsPICDEM, dsPICDEM.net, dsPICworks, ECAN, ECONOMONITOR, FanSense, FlexROM, fuzzyLAB, In-Circuit Serial Programming, ICSP, ICEPIC, Linear Active Thermistor, Mindi, MiWi, MPASM, MPLIB, MPLINK, MPSIM, PICkit, PICDEM, PICDEM.net, PICLAB, PICtail, PowerCal, PowerInfo, PowerMate, PowerTool, REAL ICE, rfLAB, rfPICDEM, Select Mode, Smart Serial, SmartTel, Total Endurance, UNI/O, WiperLock and ZENA are trademarks of Microchip Technology Incorporated in the U.S.A. and other countries. SQTP is a service mark of Microchip Technology Incorporated in the U.S.A. All other trademarks mentioned herein are property of their respective companies.


Download ppt "MCU bit Standard Peripherals and Programming using C30"

Similar presentations


Ads by Google