Chapter 5 Tips and Tricks

It is in Chapter 5 that we present for the first time the use of inline assembly. As a general rule in the book, this is a compromise accepted only in cases where we need to perform a task otherwise “impossible” if using only the C language, in this case: the unlock sequences of the OSCCON register and the RTCC register.

Both unlock sequences require the use of inline assembly because they must be performed in a very strict order, something we cannot “count” on the compiler to respect. Compilers are somewhat rebellious, they like to be in control of things and to be free to accomplish their tasks in the way THEY judge to be the most appropriate!

The inline assembly codes presented in the Tips and Tricks section works, but as I learned recently they are not optimal, especially when using the latest version of the MPLAB C30 compiler. A better way to do things is to still use inline assembly but, thanks to a special notation, let the compiler choose at least the registers to be used.

Here is an example showing the RTCC unlock sequence (and RTCWREN bit set) as recommended to me by the true MPLAB C30 gurus:

{int *nvmkey = &NVMKEY;
int v1 = 0x55;
asm volatile(“mov %0,[%1]\n\t”
“com %0,%0\n\t”
“mov %0,[%1]\n\t”
“bset RCFGCAL,#13” : “+r”(v1) : “r”(nvmkey));

First of all notice how two parameters (%0 and %1) are replacing what before was the explicit use of processor registers. Now the choice is left to the compiler so that there is no interference/limitation whatsoever with the compiler register optimization algorithms.

Notice how the four assembly statements are passed inside a single inline assembly statement using a special escape sequence to terminate each line (\n\t) and concatenate with the next one.

Finally notice how the statement contains two additional parameters separated by “:”. They inform the compiler of what kind of registers will be required and what kind of use we will make of them.

You will find more details on this special notation inside the MPLAB C30 compiler User Guide chapter 8. Some pretty advanced stuff!

This entry was posted in PIC24, Tips and Tricks. Bookmark the permalink.