Thursday, December 16, 2010

Analog to Digital Conversion in PIC18F Series

This program converts the Analog voltage signal from the photentiometer of the development board and convert in to digital. This value is then devide by 4 and result is shown in the PORTB LEDS. Turn the Photentiomter to see the LED variation.

#include <stdio.h>
#include <P18CXXX.h>    
#include <adc.h>
#include <timers.h>
 
#pragma code page  // This code make sure the program starts from 0x0004, not from 0x0000

void OpenADC( unsigned char config,unsigned char config2 );  // prototypes
void ConvertADC( void );
void OpenTimer2( unsigned char config );
void OpenPWM1( char period );
void OpenPWM2( char period );
void SetDCPWM1( unsigned int dutycycle );
void SetDCPWM2( unsigned int dutycycle );

int data; // global variables goes to here

void delay (void) // user define delay function
{
long i,C;
for (i=0;i<30000;i++)
C = C+1;
}
void main (void) // main  function 
{
TRISB = 0; // Port,pin direction configuration
PORTB = 0;
TRISC = 0;
PORTC = 0;
TRISCbits.TRISC7 = 1;  // make sure this pin is input

OpenADC (ADC_FOSC_32 & ADC_RIGHT_JUST & ADC_5ANA_0REF, ADC_CH4 & ADC_INT_OFF );  // init ADC
OpenPWM1(0xff); // int PWM1
OpenPWM2(0xff); // int PWM1
OpenTimer2 ( TIMER_INT_OFF & T2_PS_1_16 & T2_POST_1_8 ); // int Timer2
while (1)     // this is how to make a never ending loop.
{
ConvertADC();
while( BusyADC() ); // Wait for AtoD complete.
data = ReadADC();

PORTB = data/4; // Put the AtoD value in to the PortB by deviding ADC value by 4

PORTCbits.RC0 = 1; // Set motor 1 direction
PORTCbits.RC3 = 0;

PORTCbits.RC5 = 1;  // Set motor 2 direction
PORTCbits.RC4 = 0;

SetDCPWM2(data); // Set duty cycle value for PWM2
SetDCPWM1(data); // Set duty cycle value for PWM1

delay();
}
}

No comments:

Post a Comment