Question

I'm trying to read the ADC pins ADC0 to ADC5, using a periodic task once every 10 seconds. For this I'm using read() to read 4 bytes. The value read can vary between 0 - 4095 (theoretically). However, I don't seem to be getting accurate readings everytime. Moreover, when I comment this [printf ("value of pin ADC%d =%.4s \n", pin, val);] line in adc_read() function, I'm getting incorrect values, and usually end up with all pins displaying the same value.

Is this the right way to do this?

Note: I'm using the -O0 switch with gcc to avoid issues with optimization.

Thanks.

This is the read function I'm using---->

int adc_read(unsigned int pin)
{
int fd, len, j;
char buf[MAX_BUF];
char val[3];



len = snprintf(buf, sizeof(buf), "/sys/devices/ocp.2/helper.9/AIN%d", pin);

fd = open(buf, O_RDONLY);
if (fd < 0) {
    perror("adc/get-value");

}

read(fd, &val, 4);
close(fd);
}
printf ("value of pin ADC%d =%.4s \n", pin, val);
return atoi(&val);
}

Which I'm calling in a periodic task like this----->

int main(int argc, char **argv, char **envp)
{

    int v0, v1, v2, v3, v4, v5;
    adc_ports_enable();         // Enable ADC pins
    make_periodic (10000000, &info);
    while (1)
    {

    v0 = adc_read(0);               
    v1 = adc_read(1);
    v2 = adc_read(2);
    v3 = adc_read(3);
    v4 = adc_read(4);
    v5 = adc_read(5);

    printf("At %d:%d:%d  v0= %d v1= %d v2= %d v3= %d v4= %d v5= %d\n", tm.tm_hour, tm.tm_min, tm.tm_sec, v0, v1, v2, v3, v4, v5);

    wait_period (&info);
    }

    return 0;


}

Sample output:

value of pin ADC0 =1798
value of pin ADC1 =1714
value of pin ADC2 =1229
value of pin ADC3 =736

value of pin ADC4 =579

value of pin ADC5 =678

At 0:56:0  v0= 1798 v1= 1714 v2= 1229 v3= 736 v4= 579 v5= 678

Sample output when printf() in adc_read is commented:

At 1:29:26  v0= 648 v1= 1711 v2= 577 v3= 577 v4= 577 v5= 577
At 1:29:36  v0= 762 v1= 762 v2= 762 v3= 762 v4= 762 v5= 762
At 1:29:46  v0= 6 v1= 6 v2= 6 v3= 6 v4= 6 v5= 6
At 1:29:56  v0= 1797 v1= 1797 v2= 1797 v3= 1797 v4= 1797 v5= 1797
Was it helpful?

Solution

in your function adc_read() you have...

char val[3];  // three bytes! 

but then later in the same function...

read(fd, &val, 4); // Oops! reads four bytes! 

So, the val string is un-terminated. The function atoi() needs a null terminated string. It's getting garbage.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top