Wednesday, September 7, 2016

Using Analog To Digital Converter of Cortex-M3

Click Here to read the Led Blink Using Timer of Cortex-M3.
In this tutorial, ADC of LPC1343 is used to sense the voltage at the ADC pin connected with a  variable resistor (potentiometer), and raw ADC count sensed and then its corresponding voltage is displayed on semi-hosting window.
To more about Semi-Hosting read the first post.

Schematic Diagram:
Schematic Diagram
As clearly seen in the circuit diagram above, potentiometer is connected at ADC0 channel, CooCox Community provide very good ADC library for LPC13XX, but in this tutorial that library is not used, as CooCox library is generic and thus makes it very difficult to understand, the library provided here is very simple and just for LPC13XX series of micro-controller, with each line explaining meaning properly using comments.

The code is as follow:

 #include "config.h"  
 #include "lpc13xx_gpio.h"  
 #include "adc.h"  
 #ifdef SEMIHOSTING  
 #include "semihosting.h"  
 #endif  
 int main()  
 {  
  u16_t adc_value = 0;  
  u16_t voltage  = 0;  
  // Initialize System  
  InitializeSystem();  
  // Initialize ADC  
  ADC_Init();  
  while(1)  
  {  
   // Read ADC Count from Channel-0  
   adc_value = ADC_Read(ADC_CHANNEL_0);  
   voltage = adc_value*3300 / 1023;  
 #ifdef SEMIHOSTING  
   printf("RAW Value = %d, Voltage = %dmV\n", adc_value, voltage);  
 #endif  
  }  
 }  

In the above code ADC_Init() function is used to configure the ADC of LPC13XX, the function definition of this function is as follow:

 void ADC_Init( void )  
 {  
  // Initialize ADC Settings  
  LPC_SYSCON->SYSAHBCLKCTRL |= (1<<13); // Enable Clock for ADC  
  LPC_SYSCON->PDRUNCFG &= ~(1<<4);   //Disable Power Down bit for ADC  
  // Configure ADC Pins, Potentiometer is connected to ADC3/PIO0.11  
  LPC_IOCON->JTAG_TDI_PIO0_11 &= ~0x8F;    //Analog Input Mode is Selected  
  LPC_IOCON->JTAG_TDI_PIO0_11 |= 0x02;     //ADC0 as ADC Input Pin  
  //Analog to Digital Control Registers  
  /*  
  SEL = 1 Select First Channel  
  ADC Clock must be Less than 4.5MHz (I am taking 3MHz)  
  (CLKDIV+1) = PCLK/3MHz = 72/3 = 24  
  CLKDIV = 24          (24<<8)  
  BURST = 0           (0<<16)  
  CLKS = 0x0 11 Clock Cycles  (0<<17)  
  START = 0  No ADC Conversion (0<<24)  
  */  
  LPC_ADC->CR = (1<<0)|(24<<8)|(0<<16)|(0<17)|(0<<24);  
 }  

The code is self explanatory and it configures the ADC at Clock 3MHz (ADC Clock must be Less than 4.5MHz).
Then ADC_Read(Channel Number), function can be used to get the 10-bit result from that particular channel. 
There are in total 8 channels in LPC1343 which can be selected by using ADC_CHANNEL_0, ADC_CHANNEL_1, ADC_CHANNEL_2, ADC_CHANNEL_3, ADC_CHANNEL_4, ADC_CHANNEL_5,  ADC_CHANNEL_6, ADC_CHANNEL_7 keywords in ADC_Read function.

Have a look at the following video for project demonstration.
Click Here to Download the Code.

No comments:

Post a Comment