title: beagle bone ADC read values
body: <p>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. </p>
  
  <p>Is this the right way to do this?</p>
  
  <p>Note: I'm using the -O0 switch with gcc to avoid issues with optimization.</p>
  
  <p>Thanks.</p>
  
  <p><strong>This is the read function I'm using----></strong></p>
  
  <pre><code>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 &lt; 0) {
      perror("adc/get-value");
  
  }
  
  read(fd, &amp;val, 4);
  close(fd);
  }
  printf ("value of pin ADC%d =%.4s \n", pin, val);
  return atoi(&amp;val);
  }
  </code></pre>
  
  <p><strong>Which I'm calling in a periodic task like this-----></strong></p>
  
  <pre><code>int main(int argc, char **argv, char **envp)
  {
  
      int v0, v1, v2, v3, v4, v5;
      adc_ports_enable();         // Enable ADC pins
      make_periodic (10000000, &amp;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 (&amp;info);
      }
  
      return 0;
  
  
  }
  </code></pre>
  
  <p><strong>Sample output:</strong></p>
  
  <pre><code>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
  </code></pre>
  
  <p><strong>Sample output when printf() in adc_read is commented:</strong></p>
  
  <pre><code>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
  </code></pre>