Detailed Example: Initialising Analog to Digital Converter 0
void adcInit(void)
{
PCB_PINSEL1 &= ~PCB_PINSEL1_P030_MASK;
PCB_PINSEL1 |= PCB_PINSEL1_P030_AD03;
SCB_PCONP |= SCB_PCONP_PCAD0;
AD0_CR = AD_CR_CLKS10 | AD_CR_PDN | ((11 - 1) << AD_CR_CLKDIVSHIFT) | AD_CR_SEL3;
}
The example above demonstrates how to initialize ADC0 (Analog to Digital Converter 0), specifically AD 0.3 (there are 8 available channels on AD0 from 0..7). It starts by setting P0.30 to act as AD0.3 (looking at the pin layout for the LPC2148, we can see that this pin can also be configured to work as a standard GPIO [P0.30], an External Interrupt [EINT3], or Capture Input Timer [CAP0.0]). (For more information on this selecting pin functions, you might want to look at our notes on PINSEL.)
Once the appropriate pin has been told to work as AD0.3, we need to make sure that the analog to digital block is actually turned on. This is done by using PCONP. The line that accomplishes this is the third one, where you can see that we are assigning a value to SCB_PCONP. Depending on the value that we assign to SCB_PCONP, we can enable or disable any of the peripherals available on the device.
In this particular case, line two leaves the SCB_PCONP exactly as it is, except that it switches bit 12 (AD0) to '1', which will power up analog to digital converter 0. Please note that it's important to use the '|=' operator so that you don't inadvertendly turn off all the other devices, which is what would happen if you had simply written "SCB_PCONP = SCB_PCONP_PCAD0;". You would still be setting bit 12 to '1', turning AD0 on, but you would be setting everything else to '0', turning everything else off! The '|=" is essentially saying 'keep the value as it is, except this one specific bit. (For more information on this, feel free to consult our page on Bitwise Operators in C.)
Line four simply configures the AD0 converter. It's out of the scope of this article to explain all the details, but you can find more information on configuring the ADC peripherals in Lesson 3 - Analog Input (ADC).
"SCB_PCONP" is the name or 'alias' used in the header file we are using in these articles (LPC214x.h), and this 'alias' may be different in header files made by other authors for the LPC214x family. For example, Philips'/NXP's standard 214x header file simply uses "PCONP" as an alias for this address, but the code functions identically when compiled since they both point to the exact same memory address beneath the surface (0xE01FC0C4). It's a matter of taste, but personally I prefer J.C. Wren's header file since I find it clearer and better organized. You can use whichever you want, though, since it doesn't make a difference once the code is compiled. You simply need to adjust your code to use PCONP or whatever other name is used used instead of SCB_PCONP. (If you're curious, SCB_xxx stands for System Control Block.)
..