4Introducing the PIC16F1XXX OverviewMemory MapNew InstructionsEnhanced Indirect Memory Features
5PIC® Microcontroller Family Roadmap Enhanced PIC16(14-bit instruction word)dsPIC® DSCPIC24PIC18(16-bit instruction word)Memory/PerformanceAt the bottom are the devices with a 12-bit instruction word. These devices have 33 instructions, small memories and no interrupts. Next we find the 14-bit instruction word devices that add a few instructions and interrupts. These devices are limited to 8 K words of program memory and 512 bytes of memory shared with the special function registers. Above the 14-bit instruction word devices you will find PIC18 devices with a 16-bit instruction word.PIC18 devices are quite capable, but the addition of a 16-bit instruction word requires the program memory to be larger than a similar memory on a PIC16. If the additional features of the PIC18 are required, then the additional memory size is valuable. However, for a simpler design that needs only a little more capability, the increase of the program memory size may not be optimal.PIC16(14-bit instruction word)PIC10/12(12-bit instruction word)Price
6Maintain 14-bit program memory, to keep cost low PIC16 Enhancement GOALSIncrease maximum program memoryIncrease space for peripheralsIncrease maximum data memoryReduce penalty for paging/bankingImproving ‘C’ efficiencyMinimize difficulty of migrationMaintain14-bit program memory,to keep cost lowThe goal was to add more program memory to the device (the 8 K word limit was too limiting). Increase the maximum data memory, 384 bytes is too small. Reduce the penalty for paging/banking; in an ideal world, this would be eliminated. Add more space for peripherals. The PIC16F886 and PIC16F917 completely use all the available SFRs.See what we can do about making the part more C friendly.Keep migration simple AND LEAVE THE PROGRAM MEMORY 14-bits WIDE so the part stays low cost.
7Front Page Comparison of PIC16XXX and PIC16F1XXX OLDNEWHigh-Performance RISC CPU:Only 35 instructionsAll single-cycle instructions except branchesOperating speed:DC – 20 MHz oscillator/clock inputDC – 200 ns instruction cycleInterrupt capability8-level-deep hardware stackDirect, Indirect and Relative Addressing modesHigh-Performance RISC CPU:Only 49 instructionsAll single-cycle instructions except branchesOperating speed:DC – 32 MHz oscillator/clock inputDC – 125 ns instruction cycleInterrupt capability with automatic context saving16-level-deep hardware stack with Overflow/Underflow ResetDirect, Indirect and Relative Addressing modesTwo full 16-bit File Select Registers (FSRs)read program and data memory
8Quick Comparison PIC16 Enhanced PIC16 PIC18 Max GPR/SFR 336 / 110 2496 / 3164096/159+more, if the SFRs are outside of the access bank.Max Program8Kx1432Kx1416K is likely the largest device1Mx16FSRs12can access program memory3Instruction Count35497583 including the optional extended instructionsStack816with over/underflow Reset31Interruptshardware context saveoptional hardware context saveProgram Memory ReadAll devices via RETLW. Some devices via EEPROM interfaceAll devices via RETLW or FSR. All devices via EEPROM interface.All devices via TABLRD instructions.As engineers, we like charts and graphs. So here is a comparison between the PIC16, enhanced PIC16 and PIC18 devices.There are a few caveats here. For example, the PIC18 is “limited” to 159 SFRs. This is a little arbitrary and there are examples of PIC18s with more memory. This limit is the reserved space in the access memory for SFRs. By using the access memory, all the SFRs in a PIC18 can be used without banking. In the PIC16 and enhanced PIC16, the SFRs are scattered across the memory banks; so, banking has not been eliminated.
9New Data Memory Map 32 Banks of File Registers 15 banks are reserved for the futureThe Memory Map is SimplifiedBottom 16 bytes of each bank are commonFirst 12 bytes of each bank are for the CPU registersSFRs are located at address 12-31New FeaturesW is mapped to “w reg”Banks are reserved for future funBank 31 has advanced functionsThe new device has 32 banks of memory. This would seem to be 8 orders of magnitude (base 2) more complex so we added some rules.<CLICK THE MOUSE>First the bottom 16 bytes of every bank OF EVERY DEVICE will be common across all banks.This rule will be enforced for ALL TIME.How many people remember the PIC16F874?The common memory was different within the family and the ISR context saving became complex.We will not do this on the enhanced devices.Next we made the first 12 bytes of EVERY bank identical. These registers are the CPU registers.Lastly we made ALL SFRs located between addresses (decimal). With 16 banks available, there is room for 304 SFRs.That should be enough for the next few parts.< CLICK THE MOUSE >Just for fun, we mapped the W register. This PIC18 feature is very useful, so we brought it back to the PIC16.Banks are reserved. Advanced ICD ONLY functions are located in Bank 30.Bank 31 has functions intended for ICD, but are available for normal code also. These include access to the stack and ISR context save registers. More on this later.
10Data Memory Map 12 Common CORE SFRs Common Memory (16 bytes) Bank 0 0x00012 Common CORE SFRs0x00B0x00CSFRs20SFRs20SFRs20SFRs20SFRs20SFRs20Bank 31SpecialFunctionsStack AccessandDebuggingRegisters0x01F0x020GPR80 BytesGPR80 BytesGPR80 BytesGPR80 BytesGPR80 BytesGPR80 BytesHere is the memory map in graphical form.No access bank like PIC18.SFRs are contained within 20 bytes of SFR area within each bank.Bank 31 is for advanced features. Typically it can be ignored.Banks 6-300x06F0x070Common Memory (16 bytes)0x07F
11Common Core Registers 0x00 INDF0 Indirect Register 0 0x01 INDF1 AddressRegisterFunction0x00INDF0Indirect Register 0NEW0x01INDF1Indirect Register 10x02PCLProgram Counter Low0x03STATUSStatus RegisterNEW0x04FSR0 LowFile Select Register 0 Low Byte0x05FSR0 HighFile Select Register 0 High ByteNEW0x06FSR1 LowFile Select Register 1 Low ByteNEWHere are the first 12 memory locations of EVERY bank.<CLICK MOUSE>These registers are the new registers from the PIC16.As an added bonus, these registers are automatically saved and restored during interrupts.0x07FSR1 HighFile Select Register 1 High ByteNEW0x08BSRBank Select RegisterNEWNEW0x09WREGWorking Register0x0APCLATHProgram Counter Latch High0x0BINTCONInterrupt Control Register
12Data Memory BankingThe old device required banking via RP0 and RP1 in the Status Register.These bits NO LONGER EXIST.Now the BSR register handles all banking.The new MOVLB instruction selects the bank in one instruction.OLDNEWIRPRP1RP0TOPDZDCCSTATUS---TOPDZDCCBanking in the past was handled by bit clears and bit sets on the RP0 and RP1 bits in the status register.This forced one or two cycles and many tricks to handle banking.The BANKSEL macro took care of these issues behind the scenes.<CLICK MOUSE>THESE BITS DO NOT EXIST. Old banking code WILL NOT WORK.Unless you use the BANKSEL macro. That still works fine.The observant PIC18 programmers will have noticed the BSR register on the previous slide. This is the Bank Select Register.BSR allows access to all 32 banks.To prevent the problem of using the W to load BSR…The move literal to BSR instruction will load the BSR from a literal in one cycle. BANKSEL will use this instruction so all code with BANKSEL is ready to go with the enhanced PIC16.BSR---432100011011123431
13Program Memory Program Memory Extended to 16 Pages of 2 Kbytes Paging Simplified with MOVLP Instruction654321MOVLPPCLATHPCL--1413-121110987654321We added more pages.Now, there are 16 pages of program memory.<CLICK MOUSE>Move literal to PCLATH instruction.The PAGESEL macro will automatically use this instruction to implement all paging.Therefore, any existing code with PAGESEL is already done.The new device adds the ability to use the FSR to read the program memory. This allows the FSR to be a single pointer and access all the ram and flash memory (except the EEPROM). The classical memory read methods are still in place and you will see shortly that the RETLW method has a few new twists.10987654321GOTO/CALL1413121110987654321ProgramCounter
14New FSRSFRsandGPRsRESERVEDPROGRAMMEMORY0x00000x0FFF0x10000x7FFF0x80000xFFFFFSR AddressesProgram Counter AddressesBSR + File Register AddressesLinear GPR RegionReachable by FSR only0x29FF0x3A000x1FFF0x20002 x 16-bit FSRsAccess All File Registers and All Program MemoryNew FSRs Allow 1 Data Pointer for All MemoryFSRs Are Now Supported By New InstructionsFSR MSb is setHere is the NEW FSR.There are two 16-bit FSRs on the enhanced PIC16.These new FSRs can access nearly ALL the memory in the device. Constants in ROM can be used as easily as variables in RAM.When the FSR points at the program memory, there is 1 additional instruction cycle in instructions using INDF to allow the data to be fetched.Because the INDF is only 8-bits wide, only the low 8-bits of the program memory can be read by the FSR method.So ANY literal instruction can be used to build the data tables for the FSR system.The use of the DT directive will produce a table useable by the FSR pointer method.Additionally, there are three new instructions that allow pre/post operations, literal indexed moves and literal adds to the FSR.More on that in a few more slides.An interesting new feature is the linear GPR region added at address 0x2000.This region is simply a different view of the GPR memory to allow data constructs larger than 80 bytes.Lets take a closer look at this.<CLICK MOUSE>
15Linear GPR Region Shadows 80 byte GPR blocks into linear array Keeps FSR operations inside GPR areaAllows large stacks, arrays, buffers, etc.Access is via the FSR and a second address range12 Common CORE SFRsSFRs20SFRs20SFRs20SFRs20SFRs20SFRs20Bank 31SpecialFunctionsStack AccessandDebuggingRegistersBANK 0GPR80 BytesBANK 1GPR80 BytesBANK 2GPR80 BytesBANK 3GPR80 BytesBANK 4GPR80 BytesBANK 5GPR80 BytesThe linear GPR region is simply a different view into the GPR area of memory.Essentially, the GPR space is shadowed into the FSR, so there are no gaps between the end of one GPR bank and the beginning of the second GPR bank.The SFRs and common memory do not get in the way.<CLICK MOUSE>Banks 6-30Common Memory (16 bytes)
16Linear GPR Region Shadows 80 byte GPR blocks into linear array BANK 0GPR80 BytesBANK 2BANK 3BANK 4BANK 1BANK 5Linear GPR RegionShadows 80 byte GPR blocks into linear arrayKeeps FSR operations inside GPR areaAllows large stacks, arrays, buffers, etc.Access is via the FSR and a second address range0x20000x204F0x20500x20A00x209F0x20EF0x20F00x213F0x21400x218FBANK 0BANK 1BANK 2BANK 3BANK 40x21900x21DFBANK 5FSRAddresses12 Common CORE SFRsSFRs20SFRs20SFRs20SFRs20SFRs20SFRs20Bank 31SpecialFunctionsStack AccessandDebuggingRegistersBANK 0GPR80 BytesBANK 1GPR80 BytesBANK 2GPR80 BytesBANK 3GPR80 BytesBANK 4GPR80 BytesBANK 5GPR80 BytesThe linear GPR region is simply different view into the GPR area of memory.Essentially, the GPR space is shadowed into the FSR so there are no gaps between the end of one GPR bank and the beginning of the second GPR bank.The SFRs and common memory do not get in the way.<CLICK MOUSE>Banks 6-30Common Memory (16 bytes)
17Fast Context Save Interrupts automatically save the context WSTATUSBSRFSRsPCLATHRETFIE automatically restores the contextYou cannot disable fast context saveOne extra complexity of all interrupt service routines is saving/restoring the context.This is not difficult because you simply need to copy the code from the Microchip supplied template.Unfortunately, it adds time to the ISR. To speed this process the PIC18 has a fast return option that allows an optional hardware context save.The new PIC16 has a hardware context save but it is not optional.The existing save/restore code can simply be removed. If your application does something unusual with the context after an interrupt that code will need to be rewritten to use the context save registers that are located in bank 31. The save registers are made available so the debugger can show them, but this is also useful for operating systems and user creativity.The RETFIE instruction now restores the context in addition to setting the GIE. Be careful because some legacy code uses the RETFIE at the end of the initialization code to save one instruction (BSF INTCON,GIE).<CLICK MOUSE>
18Stack 16 Stack Entries Over/Underflow Reset (optional) User/ICD Stack Access in Bank 31Read/Write the Stack in Bank 31Useful for RTOS or Safety Critical Debugging891011121314157654In the original PIC16, the stack was a simple circular buffer of 8 entries.If more than 8 calls were performed, the stack overflowed and started over at 0.If more than 8 returns were performed, the stack underflowed and continued at 15.The new stack is bigger.<CLICK MOUSE>With 16 entries.It still wraps around.But now, it has a few new features.Over/Underflow Reset.And, read/write access on bank 31.Lets look a little closer.321
19Stack Reset ModeThe STRVEN (Stack Reset Violation Enable) Config bit enables the Stack Reset modeStack Reset Mode causes:Return when stack is emptyCall or interrupt when stack is fullReading the top of stack when stack is empty returns 0
20Normal ModeThe stack works exactly as the legacy device, plus the following features16-entry stackStack access via STKPTR and TOSH/TOSL
21New Instructions Mnemonic Description ADDWFC Add W+F with Carry SUBWFB Subtract F-W with BorrowLSLFLogical Shift LeftLSRFLogical Shift RightASRFArithmetic Shift RightMOVLPMove Literal to PCLATHMOVLBMove Literal to BSRBRABranch Relative (signed)BRWBranch PC + W (unsigned)CALLWCall PCLATH:WADDFSRAdd Literal to FSRn (signed)MOVIWMove Indirect to WMOVWIMove W to IndirectRESETReset Hardware and SoftwareIt is now time to show you the new instructions.We will go over each instruction in more detail, shortly. You have a quick reference sheet in your lab notes.As we go over each instruction, feel free to interrupt and ask questions.
22Arithmetic with Carry ADDWFC SUBWFB Add with CarrySUBWFBSubtract with BorrowLiteral Operations with Carry or Borrow Are Not SupportedOriginal Add and Subtract Operations Still AvailableExisting algorithms will still work!These two instructions add carry/borrow support to the add and subtract instructions. They do not replace the original ADDWF and SUBWF–they are in addition to the original instructions. Consequently, your original code will still work.<CLICK MOUSE>
23Shift Instructions ASRF LSRF LSLF Arithmetic Right Shift Logical Right ShiftLSLFLogical Left Shift(This is the same as Arithmetic Shift Left.)We have always had rotate instructions but now we have shifts.Shift operations can be emulated with rotates, but the extra work to correctly handle the Carry bit could be tedious in tight loops–especially for sign extend operations. Now, this is simple.Incidentally…Question: Why did we ignore Arithmetic Left Shift?Answer: it is the same as logical left shift. A ASLF pseudo opcode is in the assembler.<CLICK MOUSE>
24Shift Instructions 1 ASRF 0X7F16 Arithmetic Right Shift REGISTERx 10X7F16CARRY BIT
28Shift Instructions 1 LSRF 0X7F16 Logical Right Shift REGISTERx 10X7F16CARRY BIT
29Shift Instructions 1 LSRF 0X3F16 1 ZERO SHIFTED IN Logical Right Shift REGISTERx10X3F16CARRY BIT1ZERO SHIFTED IN
30Shift Instructions 1 LSRF 0X8016 Logical Right Shift REGISTERx 0X8016CARRY BIT
31Shift Instructions 1 LSRF 0X3F16 ZERO SHIFTED IN Logical Right Shift REGISTERx10X3F16CARRY BITZERO SHIFTED IN
32Shift Instructions 1 LSLF 0X7F16 Logical Left Shift REGISTERx 10X7F16CARRY BIT
33Shift Instructions 1 LSLF ZERO SHIFTED IN 0XFE16 Logical Left Shift REGISTERx10XFE16CARRY BIT
34Shift Instructions 1 LSLF 0X8016 Logical Left Shift REGISTERx 0X8016CARRY BIT
35Shift Instructions LSLF ZERO SHIFTED IN 0X0016 1 Logical Left Shift REGISTERx0X0016CARRY BIT1
36Paging/Banking MOVLP MOVLB Places 7-bit literal in PCLATH MOVLP HIGH LABELPAGESEL in 1 cycleMOVLP + CALL/GOTO takes 3 cycles and 2 instructions, but reaches ANYWHERE in memoryMOVLBPlaces 5-bit literal in BSR.BANKSEL in 1 cycle for ANY number of banksIRP, RP0, RP1 are obsolete and have been removedWe have already touched on the new instructions to streamline paging and banking.Here is a little more detail.MOVLP will place a 7-bit literal in the PCLATH. The HIGH macro isolates the upper 8 bits of LABEL to make this easier. PAGESEL now performs this in one instruction.The advantage is a large update to the PCLATH without disturbing W. In the old core you had to move through W or perform bit sets or clears on each bit in the PCLATH. With a small PCLATH this was not too bad; but with 4 bits to update, the result is not ideal.MOVLB is the banking equivalent. Adding many banks would make the traditional banking methods very tedious. We debated about forcing banks 0-3 with writes to the old bits, but decided that this was not useful because the registers have moved around. It is better to force a MOVLB and have clean code than to mix modes and leave trouble.<CLICK MOUSE>So, we completely removed these bits. The IRP bit is also obsolete, because the FSRs are now 16 bits, not 9 bits.Just use BANKSEL and these problems will be handled by the compiler.
37Relative BranchingRelative Branching allows MOST code to eliminate the paging concerns.BRA N (Branch Relative)Always branch to PC + NRange is -256 <= N <= 255PC + N is 15-bit math, so no paging issuesBRW (Branch Relative with W)Always branch to PC + W (unsigned)Fast Lookup Tables/State MachinesPC + W is 15-bit math, so no paging issuesCALLW (Call Absolute with W)Call to PCLATH, WFast Lookup Tables/State Machines/Function PointersPCLATH:W direct address
38FSR Support Instructions ADDFSR instructionAdds a signed literal to the selected FSRLiteral range is -32 to +31MOVIW/MOVWI – Move Indirect to W and Move W to IndirectSpecial ModesPre/Post-IncrementPre/Post-DecrementRelative OffsetSame range as ADDFSRA few slides back I promised more excitement regarding the FSRs.Here it is. Three new instructions.ADDFSR simply adds a signed literal to the selected FSR.<CLICK MOUSE>The range of the add is +31 to -32The add is on the full 16 bits of the FSR.MOVIW and MOVWI are much more complex.In both cases, there is a pre/post- increment/decrement option.This is nice, but there is a second option for a literal offset on the selected FSR.This literal offset can reach +31 to -32 bytes from the FSR address.The FSR is not affected by the offset.This is very useful for loading structure elements into W or accessing multiple SFRs in a different bank.Lets take a look at some MOVIW/MOVWI syntax.
39MOVIW/MOVWI Syntax Standard Pre Decrement Pre Increment Post Decrement MOVWI 0[INDF0]Pre IncrementMOVIW ++INDF0Post IncrementMOVWI INDF0++Pre DecrementMOVIW --INDF0Post DecrementMOVWI INDF0--OffsetMOVWI k[INDF0]-32 <= k <= 310These move instructions are very powerful, lets start with the basics.<CLICK MOUSE>This version takes care of the trivial case. Move the value in W into the specified INDIRECT register. This could also be done with MOVWF INDF0. There is no advantage either way. Naturally, the MOVIW works in reverse with a value access via the INDF being loaded into the W register. And MOVF INDF0,W would be the equivalent.Here is where the fun begins.Placing a ++ before the INDF0 or INDF1 makes the FSR do a full 16-bit increment before loading the value that is pointed to by the FSR into W (or saving the value in W to the INDF).This allows a buffer pointer to be quickly updated before the value is written.Sometimes it is appropriate to store (or load) a value before updating the pointer. So the post increment version is also nice.Naturally we can also pre-decrement the FSR pointer……and post-decrement the FSR pointer.Combining a pre-increment with a post-decrement is a fast way to build a stack or a circular buffer in software. The easy way to “wrap” the buffer is to use ANDWF to mask the correct bits in the pointer and force the wrap.For even more fun you can reach ahead or behind the FSR pointer and retrieve a value or save the W. This reach does not affect the value of the pointer, so less setup is required.Imagine pointing the FSR into the beginning of the SFRs in a different bank. Using this offset load allows SFR values to be copied into W without changing banks and incurring additional banking penalty.The Green Xs mark instructions that modify the value of FSR.The Orange Xs mark instructions that leave the FSR unchanged.Modifies FSRDoes not modify FSR
40Misc. Features RESET instruction No more GOTO 0 All peripherals are resetSoftware version of MCLR ResetAnother PCON bit is available to indicate a software ResetProgram Memory Read (PMR) is in every device.Full 14-bit read of program memory for check summingDevice ID, User ID and Config Word are now readable by the firmware.User ID can be used for a serial numberHere are three miscellaneous features that you may find interesting.First, how many times have you wished for a full hardware Reset instruction? Here it is. In the old days, you had to have the dog enabled, and then wait for the dog, when a Reset was required. Now, you can simply call Reset. Of course, on resetting, it is usually nice to know why a Reset happened. The PCON register has a new bit to indicate a software Reset.Additionally, the EECON extension to read the program memory is not a permanent feature of all enhanced core devices with EEPROM. This allows a full 14-bit read of the program memory for check summing the memory or more tightly packing constants into the Flash.Lastly, the device ID, die revision, User ID and Configuration Word can be read by the firmware. This enables the software to include multiple errata fixes and choose appropriate workarounds, depending on the silicon version. OR, the User ID can be used for a serial number.
42Migration Paging Banking Interrupts Indirect Memory The basics of Migration can be simplified to these four areas.Paging,Banking,Interrupts,and Indirect Memory.In this section we are simply concerned with moving existing code to the new CPU. We are not concerned with device specific issues such as peripheral changes, nor are we concerned with optimizations that can be performed with the new CPU.<CLICK MOUSE>
43Paging OR Use the PAGESEL macro Update all PCLATH code Automatically uses MOVLPORUpdate all PCLATH codeAssure 7-bit data in PCLATHConvert to relative branchesThis will eliminate most paging issues.Paging is actually the simplest area of concern.All the paging will be in one of two forms.1. PAGESEL–no change needed2. Direct edits of PCLATH–changes may be neededAny existing code that uses PAGESEL is already converted.The new assembler will use MOVLP correctly.<CLICK MOUSE>
44PAGESEL Maintains Portability PAGESEL MACRO PIC16 PAGESEL MACRO ENHANCED PIC16My ASSEMBLY CodeMy_Functionmovlw 0x04movwf delay_cntrMy_function_loopdecfsz delay_cntrgoto My_function_loopreturnMaindo lots of stuffPAGESEL My_Functioncall My_Functiondo lots of other stuffendMy_Functionmovlw 0x04movwf delay_cntrMy_function_loopdecfsz delay_cntrgoto My_function_loopreturnMaindo lots of stuffbsf PCLATH,5bcf PCLATH,4call My_Functiondo lots of other stuffendMy_Functionmovlw 0x04movwf delay_cntrMy_function_loopdecfsz delay_cntrgoto My_function_loopreturnMaindo lots of stuffmovlp high My_Functioncall My_Functiondo lots of other stuffendMaintainsPortabilityI have been advocating the use of PAGESEL for all writes to the PCLATH.This macro will allow you to maintain portability should you have a code library that needs to run on old and new devices.This will also allow you to begin modifying existing code to be ready for the new device.<CLICK MOUSE>The legacy PAGESEL is a macro that produces a combination of two BSF and/or BCF instructions on PCLATH bits 4 and 5 to prepare for a call or a goto.
45Banking Use BANKSEL macro, Replace writes to STATUS with writes to BSR Automatically uses MOVLB ORReplace writes to STATUS with writes to BSR
46and accesses more banks of memory BANKSELMy ASSEMBLY CodeBANKSEL MACROPIC16BANKSEL MACROENHANCED PIC16dataVar1 res 1Var2 res 1Var3 res 1codeMaindo lots of stuffBANKSEL Var1addwf Var1do lots of other stuffenddataVar1 res 1Var2 res 1Var3 res 1codeMaindo lots of stuffbsf STATUS,RP0bcf STATUS,RP1addwf Var1do lots of other stuffenddataVar1 res 1Var2 res 1Var3 res 1codeMaindo lots of stuffmovlb Var1 >> 7addwf Var1do lots of other stuffendSaves 1 instructionand accesses more banks of memoryAlways worksSPEAKER INFORMATIONThe LEGACY BANKSEL is a macro that produces BCF and/or BSF instructions on Status bits RP0 and RP1 to prepare the banks for the next instructions.
47Interrupts RETFIE works a little differently Interrupts should not pass parameters with W (bad practice)W will be restored!Remove core context save/restore softwarePCLProgram Counter Latch High0x0A0x090x080x070x060x050x040x030x02PCLATHWorking RegisterWREGBank Select RegisterBSRFile Select Register 1 High ByteFSR1 HighFile Select Register 1 Low ByteFSR1 LowFile Select Register 0 High ByteFSR0 HighFile Select Register 0 Low ByteFSR0 LowStatus RegisterSTATUSProgram Counter Low<CLICK MOUSE>The OLD RETFIE instruction simply did a return and set GIE.This was used by some applications in the initialization routine to save a BSF INTCON,GIE instruction.The interrupt context saved in the backup registers will be restored. This could cause a page or bank change.The best way to resolve this is to remove the RETFIE and add the BSF INTCON,GIE.I have heard rumors of code that passes parameters via the W out of the interrupt.I suppose we can think of ways to make that work; but now, that practice is a challenge.The hardware will restore the context, including W, after the RETFIE.OF course, if you MUST do this method, you can go to bank 31 and edit the context restore values before returning.I will leave that as an exercise for the student.If you leave the context save/restore software in existing code, it will simply waste CPU cycles, but nothing bad will happen. The ISR will take the same number of cycles to run as the original code.However, since the peripherals causing the interrupt are probably a bit different, the context software should be simply deleted.
48Indirect Memory IRP bit is gone Accessing > 256 bytes requires an update to FSRxH RegisterFastest Method Update FSRxH RegisterRequires modifying WFor example, MOVLW and MOVWFBANKISEL is PortablePerforms 8 bcf’s or bsf’s (e.g., 8 TCY)Does not preserve WIn the old days, the IRP bit allowed access to the second 256 bytes of data memory.This made a simple bit set or clear on the IRP sufficient to handle all FSR banking.BANKISEL performed this task.You can use W to perform the update.Or you can do many bit sets or clears.It is a good idea to use BANKISEL because it will be portable.However, the new BANKISEL does not preserve W.So add 2 lines of code around BANKISEL to save the W and it will work on old and new architectures.<CLICK MOUSE>
49Migration Summary Migrating to the PIC16F1xxx should be simple. Using the BANKSEL and PAGESEL macros will be a big help.In summary, migrating to the PIC16F1xxx should be simple. The resulting code will probably run slightly faster.BANKSEL/PAGESEL handle most of the migration hassles.<CLICK MOUSE>
50New Coding Tricks So far we have introduced the enhanced PIC16. We have learned to perform a basic migration to the enhanced PIC16.But we have not optimized any code to use the new features.Those of you with experience on the PIC18 should notice many similar concepts.In fact, one of my engineers finds it easier to migrate certain types of applications from PIC18 code to enhanced PIC16.
51New Code Tricks Relative Branching Table Reads 16-bit Arithmetic Robust TechniquesThe new code ideas we will cover are:<CLICK MOUSE>Relative BranchingTable Reads16-bit ArithmeticUsing the Offset Modes on the FSRMemory CopyingData Structures
52Relative Branches NEW ASSEMBLY ENHANCED PIC16 ORIGINAL ASSEMBLY Code Page Boundary at this point will force the need for a PAGESELBefore My_function_loopAdditional CodeMy_Functionmovlw 0x04movwf delay_cntrMy_function_loopdecfsz delay_cntrgoto My_function_loopreturnMy_Functionmovlw 0x04movwf delay_cntrMy_function_loopdecfsz delay_cntrbra My_function_loopreturnMaindo lots of stuffPAGESEL My_Functioncall My_Functiondo lots of other stuffendRelative branch makes this code ALWAYS work with no paging issues.In every non-trivial program it is necessary to branch the program flow. Most of the time, the target of the branch is nearby. A good example is a delay loop in which a variable is updated, a decision made and a branch taken or skipped.<CLICK MOUSE>Such as this code.This is a typical delay function that we have all written in one form or another.Calling this function is quite simple.If there is a page boundary between the call My_Function and the location of My_Function……then, a PAGESEL needs to be added to make the call work.If My_Function was part of a code library, you probably already had the PAGESEL in Main.But what happens if you add code that pushes My_Function down slightly?Now the delay loop is across the page boundary from the function start, and PCLATH is no longer appropriate for the GOTO.To solve this a PAGESEL could be added; but, that would change the delay time, OR the code to be reordered.If this is a library, then you do not want to make edits–so, there must be a better way.Relative branches fix this problem.Now, there is no dependency on code location within the library.The PAGESEL is probably still required in the Main function, because My_Function could be across a page boundary.CALLW is a fast way to call a function pointer–so it is not useful for this example.No relative CALL support.CALLW is not relative.Maindo lots of stuffPAGESEL My_Functioncall My_Functiondo lots of other stuff
53Table Reads The PIC16F1XXX Has New ROM Table Access Methods FSR Relative BranchThe original PIC16 could access ROM tables by adding an index to the program counter.This method works very well, but it requires the data table to be aligned with a multiple of 256.If the table was not aligned properly, then additional effort was required to access the data.This method still exists, but there are a few new methods to access ROM tables.First, the FSRs can be used.Second, the relative branching instructions can be used to make this task fast.<CLICK MOUSE>
54Tables using FSR Long setup The_CODE movlw high Table_start movwf FSR0Hmovlw low Table_startmovwf FSR0Lmovlw 3addwf FSR0Lmovf INDF0,wTable_startDT 3,4,5,6,7,8,9Here is a quick example of using FSR0 with the indexed addressing mode to copy the third and fourth data byte into the W register.Obviously, another instruction is required to actually do something with the value loaded from FLASH.The first data byte is retrieved in 8 instruction cycles.Constant offsets using MOVWI only require 6 cycles to set up, but are not always useful.<CLICK MOUSE>
55Fast Call TablesThis code returns a constant from a table aligned on a 256 word boundaryThe_CODEmovlw 3call Table_FunctionTable_Functionmovwf tempmovlw high Table_startmovwf PCLATHmovf temp,wmovwf PCLTable_startDT 3,4,5,6,7,8,9The_CODEmovlw 3movlp high Table_startcallwTable_startDT 3,4,5,6,7,8,9The CALLW can be used to make a very fast table.Simply locate the table on a 256 instruction boundary.CALLW will combine PCLATH and W to create a destination address.The byte is retrieved in 6 instruction cycles.DT is used to build the table, because RETLW is required for the proper operation of the table.<CLICK MOUSE>
56More Fast Tables Returns a const from a table. NO Alignment Issues. Table Start Can Occur ANYWHEREThe_CODEmovlw 3call Table_FunctionTable_Functionmovwf tempmovlw high Table_startmovwf PCLATHmovlw low Table_startaddwf temp,wbtfss STATUS,Cincf PCLATH,fmovwf PCLTable_startDT 3,4,5,6,7,8,9The_CODEmovlw 3call Table_FunctionTable_Functionmovlp high Table_startbrwTable_startDT 3,4,5,6,7,8,9To build a table that does not have alignment restrictions, the BRW instruction can be used.BRW adds W to the complete PC. This is a 16-bit Add, so there are page restrictions.The extra branch instruction adds 2 cycles from the previous example.So, the byte is retrieved in 8 cycles.<CLICK MOUSE>
574TCY 6TCY 16-bit Arithmetic Carry Support Speeds 16-bit Math OLD NEW movf lsb_a,waddwf lsb_b,fmovf msb_a,fbtfsc STATUS,Caddlw 0x01addwf msb_b,fmovf lsb_a,waddwf lsb_b,fmovf msb_a,waddwfc msb_b,f4TCY6TCYThis simple example shows a 16-bit Add.On the old PIC16, this could take 6 cycles.On the new PIC16, this is quicker–at 4 cycles.This small improvement can make a big impact if your code makes extensive use of multi-byte operations.<CLICK MOUSE>
58Robust Techniques RESET instruction Stack Over/Underflow Reset The RESET instruction is very valuable for improving code robustness.There are many application examples involving fast transients in which the PC can be forced to change to a random value.The chances of causing problems are reduced if the unused portions of memory are filled with RESET. Critical sections can also be guarded by Reset instructions.Now, if problems occur the device will restart.Setting the Over/Underflow Reset Configuration bit is also a good idea. In the past, the stack had to be preloaded to improve robustness. Now, the Reset option makes stack robustness much simpler.<CLICK MOUSE>
60Advanced Topics Accessing the Stack Accessing the Context Shadows Reading the Device IDPreemptive MultitaskingError Diagnostics
61Accessing the Stack Available through the TOS and STKPTR registers STKPTR is current value of the Stack PointerTOS points to the TOP of the STACKBoth registers are read/writeableTOS is split into TOSH and TOSL, due to the 15-bit size of the PCThe first advanced idea of the new PIC16 is the ability to access the stack.Addition stack access was required to support new debugging features. Because stack access is also useful to a user program, we opened it up.With this power comes great responsibility. Very subtle bugs can be introduced into your software when you play on the stack.However, you also can do nice things like change your return location or maintain independent stacks for different operations.Access to the stack is indirect. There are three registers to look at.First is the SPTR register. This is simply the current stack position.The second are the TOSH and TOSL registers. These are the top of stack access registers.<CLICK MOUSE>
62Stack Access The STKPTR indicates current stack position TOSH,TOSL is the stack at the SPTR positionChanging SPTR will move TOSH,TOSL.SPTR is 5 bitsSTKPTR5Level 0TOSHTOSLLevel 1Level 2Level 3Level 4Level 5TOSH,TOSLLevel 6Level 7Level 8To access the stack, you will adjust the value of SPTR which will position TOSH,TOSL.Then, you will read/write to TOSH, TOSL.During normal program operation, calls and interrupts will increment SPTR while RETURN and RETFIE will decrement SPTR.At any time you can inspect SPTR to see how much stack you have left.The SPTR always points at the next empty place on the stack. Therefore, a call will write the PC and then increment the SPTR–while a return will decrement the STKPTR and then unload the PC.This information is important if you intend to edit the stack to modify the return address.If Overflow/Underflow Reset is enabled, the Reset will occur on the 17th call or the 1st return (if there are no calls).The full 16 entries of stack are available.SPTR is 5 bits, to allow detection of overflow and underflow.The extra length also allows the ICD to access an extra 4 stack levels for debugging.Stack Empty occurs when the SPTR = 0x1FStack Underflow occurs when SPTR < 0x1F after a return, retlw or retfie occurs.Stack Overflow occurs when the MSb of SPTR is set after a call or an interrupt.If the Stack Reset is enabled, a Reset will occur on the overflow or underflow conditions.If the Stack Reset is not enabled, over and under flow flags are set on those conditions.<CLICK MOUSE>Level 9Level 10Level 11Level 12Level 13Level 14Level 15
63Accessing the Context Save Shadow The interrupt context save registers are read/writeable in bank 31STATUSSTATUS_SHADFSR0 LowFSR0L_SHADFSR0 HighFSR0H_SHADFSR1 LowFSR1L_SHADFSR1 HighTo enable the possibilities of editing the context restore of fast interrupt return, the context save shadows have been mapped into bank 31.The shadow names are:STATUS_SHADFSR0L_SHADFSR0H_SHADFSR1L_SHADFSR1H_SHADBSR_SHADWREG_SHADPCLATH_SHADFSR1H_SHADBSRBSR_SHADWREGWREG_SHADPCLATHPCLATH_SHAD
64Device IDSelect registers in the Configuration memory are now accessible via the EE interfaceThe User ID, Device ID and Configuration Word can be read
65Preemptive Multitasking Access to the stack and shadows allows an interrupt to replace the current task with a second taskThis allows easier RTOS programming for these devices
66Error DiagnosticsAccess to the stack and context shadows also allows more extensive self-checkStack verification is critical for some safety-critical applications