• Welcome to our site! Electro Tech is an online community (with over 170,000 members) who enjoy talking about and building electronic circuits, projects and gadgets. To participate you need to register. Registration is free. Click here to register now.

Analog to Digital Conversion in PIC18F4520

Status
Not open for further replies.

meijunfun

New Member
HI,
I need help in my programming. I am using accelerometer which gives analog signal. I need to convert this signal into digital in order for my microcontroller to read. I am having trouble in my programming part, not sure to write the conversion part.


this is the example of my programming:

#include<p18f4520.h>
#include<delays.h>

void main(){
int t;
ADCON0 = 0b00000001;//READ ANALOG VOLTAGE FROM RA0
ADCON1 = 0b00001110;//CONFIGURE ADC, RA0
ADCON2 = 0b10000001;
TRISA = 0b00000001;// RA0 INPUT

while(1){

Delay10TCYx(12);
ADCON0bits.GO = 1;
while(ADCON0bits.DONE);
t=ADRESH+256;

if(t>255){

int x=t;
}
}
}
Is there anything wrong with my programming?


Thanks:)
 

Pommie

Well-Known Member
Most Helpful Member
You have the result right justified and only read ADRESH so you will only get 2 bits of information. You also add 256 to it and test if greater than 255!:confused:

Try changing it to,
Code:
void main(){
int t;
    ADCON0 = 0b00000001;//READ ANALOG VOLTAGE FROM RA0
    ADCON1 = 0b00001110;//CONFIGURE ADC, RA0
    ADCON2 = 0b[COLOR="Red"]0[/COLOR]0000001;
    TRISA = 0b00000001;// RA0 INPUT

    while(1){

        Delay10TCYx(12);
        ADCON0bits.GO = 1;
        while(ADCON0bits.DONE);
        t=ADRESH[COLOR="red"]*256+ADRESL[/COLOR];

        if(t>255){

            int x=t;
        }
    }
}
Your variable will now contain 0 to 1023.

Mike.
 
Status
Not open for further replies.

EE World Online Articles

Loading
Top