PcDuino ADC access from C

From Hamsterworks Wiki!

Jump to: navigation, search

This pcDuino project was completed March 2013.

Here is how to read the ADC port from 'C'. Different ADC channels have different bit depth, either six or twelve bits. From testing full range appears to be 3.3V.

The only gotcha is that the ADC module has to be loaded as it is not loaded on boot. The code below uses the "system()" function to attempt to load the required module - not the best practice, but it works! It will however be broken if the current kernel changes as the path to the module includes the kernel version.

adctest.c

/*******************************************
* adctest.c : read values from the ADC ports
*
* 2013-03-25 Mike Field <hamster@snap.net.nz>
*
* You can use this however you wish! 
********************************************/
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>

int read_adc_value(FILE *f)
{
  int value=0, c;

  fseek(f,0,SEEK_SET);

  /* Drop the adcx: string at start */
  c = getc(f);
  while(c != EOF && c != ':')
    c = getc(f);
  if(c == EOF) return -1;

  /* Read the value */
  c = getc(f);
  while(c >= '0' && c <= '9') {
    value = value * 10 + c -'0';
    c = getc(f);
  }
 
  /* Read to the end of file */
  while(c != EOF) 
    c = getc(f);

  return value;
}

int main(int argc,char *argv[])
{
  FILE *f;
  int i;
  char buffer[30];
  int adc_no = 1;

  if(argc != 2) {
    fprintf(stderr,"usage: %s [adc number]\n",argv[0]);
    return 0;
  }
  adc_no = atoi(argv[1]);

  /* Load the kernel module */
  system("sudo insmod /lib/modules/3.0.8+/adc.ko > /dev/null 2>&1");

  sprintf(buffer,"/proc/adc%i",adc_no);

  f = fopen(buffer,"r");
  if(f == NULL) {
    fprintf(stderr,"Unable to open '%s'\n",buffer);
    return 0;
  }

  for(i = 0; i < 100; i++) {
    printf("adc(%i) value is %i\n",adc_no,read_adc_value(f));
    sleep(1);
  }

  fclose(f);
  return 0;
}

Personal tools