Hongwei Zhang | cb66a9e | 2019-06-05 16:37:19 -0400 | [diff] [blame] | 1 | /***************************************************************** |
| 2 | * |
| 3 | * adcapp.c |
| 4 | * Simple interface to read and write adc. |
| 5 | * |
| 6 | * Author: Rama Rao Bisa <ramab@ami.com> |
| 7 | * |
| 8 | * Copyright (C) <2019> <American Megatrends International LLC> |
| 9 | * |
| 10 | *****************************************************************/ |
| 11 | |
| 12 | #include <stdio.h> |
| 13 | #include <unistd.h> |
| 14 | #include <sys/types.h> |
| 15 | #include <sys/stat.h> |
| 16 | #include <fcntl.h> |
| 17 | #include <sys/ioctl.h> |
| 18 | #include <errno.h> |
| 19 | #include <string.h> |
| 20 | #include <stdint.h> |
| 21 | #include "adc.h" |
| 22 | #include "adcifc.h" |
| 23 | #include "EINTR_wrappers.h" |
| 24 | |
| 25 | /** \file adcifc.c |
| 26 | \brief Source for all adc interface code |
| 27 | */ |
| 28 | |
| 29 | static int adc_directory_check() |
| 30 | { |
| 31 | int retval = 0; |
| 32 | struct stat sb; |
| 33 | if (!(stat("/sys/bus/iio/devices/iio:device0", &sb) == 0 && S_ISDIR(sb.st_mode))) |
| 34 | { |
| 35 | printf("\"/sys/bus/iio/devices/iio:device0\" is not exist!\n"); |
| 36 | retval = -1; |
| 37 | } |
| 38 | return retval; |
| 39 | } |
| 40 | |
| 41 | static int sys_get_adc_vol( get_adc_value_t *argp ) |
| 42 | { |
| 43 | int retval = -1; |
| 44 | int fd; |
| 45 | int tmp; |
| 46 | char stringArray[50]; |
| 47 | char val[5]; |
| 48 | if(argp->channel_num > 15) retval = -1; |
| 49 | retval = adc_directory_check(); |
| 50 | if(retval != 0) |
| 51 | { |
| 52 | return retval; |
| 53 | } |
| 54 | snprintf(stringArray, sizeof(stringArray), "%s%s%d%s", "/sys/bus/iio/devices/iio:device0","/in_voltage", argp->channel_num,"_raw"); |
| 55 | retval = access(stringArray,F_OK); |
| 56 | if(retval != 0) |
| 57 | { |
| 58 | return retval; |
| 59 | } |
| 60 | fd = sigwrap_open(stringArray, O_RDONLY); |
| 61 | if (fd < 0) { |
| 62 | return fd; |
| 63 | } |
| 64 | read(fd, val, 5); |
| 65 | tmp = atoi(val); |
| 66 | (void)sigwrap_close(fd); |
| 67 | argp->channel_value = (uint16_t)(tmp); |
| 68 | retval = 0; |
| 69 | return( retval ); |
| 70 | } |
| 71 | |
| 72 | /** |
| 73 | * get_adc_val |
| 74 | * |
| 75 | **/ |
| 76 | int get_adc_val( int channel , unsigned short *data) |
| 77 | { |
| 78 | get_adc_value_t adc_arg; |
| 79 | |
| 80 | /* Set the adc channel to read */ |
| 81 | adc_arg.channel_num = channel; |
| 82 | adc_arg.channel_value = 0; |
| 83 | |
| 84 | if ( -1 == sys_get_adc_vol(&adc_arg)) { return -1; } |
| 85 | *data = (unsigned short)(adc_arg.channel_value); |
| 86 | |
| 87 | return ( 0 ); |
| 88 | } |