From 82cc507e074956c45bd8c49c07e7d5a0af244af7 Mon Sep 17 00:00:00 2001 From: Sanchayan Maity Date: Mon, 24 Apr 2017 17:46:30 +0530 Subject: [PATCH] Update code for PCF8591 usage --- pcf8591/pcf8591.c | 89 +++++++++++++++++++++++++++++++++-------------- 1 file changed, 62 insertions(+), 27 deletions(-) diff --git a/pcf8591/pcf8591.c b/pcf8591/pcf8591.c index 26c4f96..a902411 100644 --- a/pcf8591/pcf8591.c +++ b/pcf8591/pcf8591.c @@ -11,58 +11,93 @@ #define PCF8591_ADDRESS 0x48 -int main( int argc, char **argv ) +int main(int argc, char **argv) { - uint8_t i; uint32_t fd; uint32_t ret; - uint8_t command[2]; - uint8_t value[4]; - useconds_t delay = 2000; + uint32_t adc_channel = 0; + uint32_t dac_output = 0; + uint8_t command[2] = {0}; + uint8_t value[4] = {0}; + useconds_t delay = 5000; char *dev = "/dev/i2c-0"; printf("PCF8591 ADC and DAC test code\n"); fd = open(dev, O_RDWR); - if(fd < 0) { + if (fd < 0) { perror("Opening i2c device node\n"); - return 1; + return -1; } ret = ioctl(fd, I2C_SLAVE, PCF8591_ADDRESS); - if(ret < 0) { + if (ret < 0) { perror("Selecting i2c device\n"); + close (fd); + return -1; } while (true) { - for(i = 0; i < 4; i++) { + printf("\n1. ADC 2. DAC 3. Exit\n"); + scanf("%d", &adc_channel); + switch (adc_channel) { + case 1: + printf("\nEnter ADC channel number 0-3:\t"); + scanf("%d", &adc_channel); + if ((adc_channel >= 0) && (adc_channel <= 3)) { + /* + * Analog output enable | Read Input i + * See Page 6 of NXP PCF8591 data sheet + */ + command[0] = 0x40 | ((adc_channel) & 0x03); /* Control Byte */ + command[1] = dac_output; /* DAC Data Register */ - /* - * Analog output enable | Read Input i - * See Page 6 of NXP PCF8591 data sheet - */ - command[0] = 0x40 | ((i + 1) & 0x03); /* Control Byte */ - command[1]++; /* DAC Data Register */ + ret = write(fd, &command, 2); + if (ret != 2) { + perror("i2c write failed"); + continue; + } + + usleep(delay); + + ret = read(fd, &value[0], 1); + if(ret != 1) { + perror("i2c read failed"); + continue; + } + + printf("\nADC Channel %d: value: %d\n", adc_channel, value[0]); + } else { + printf("Invalid ADC channel number\n"); + } + break; + case 2: + printf("Enter DAC value:\t"); + scanf("%d", &dac_output); + + command[0] = 0x40 | ((adc_channel) & 0x03); /* Control Byte */ + command[1] = dac_output & 0xff; /* DAC Data Register */ ret = write(fd, &command, 2); - if (ret != 2) - perror("writing i2c device"); - - usleep(delay); - - /* the read is always one step behind the selected input */ - ret = read(fd, &value[i], 1); - if(ret != 1) - perror("reading i2c device"); + if (ret != 2) { + perror("i2c write failed"); + continue; + } usleep(delay); + break; + case 3: + goto exit; + break; + default: + printf("Invalid input\n"); + break; } - - printf("0x%02x 0x%02x 0x%02x 0x%02x\n", value[0], value[1], value[2], value[3]); - sleep(1); } +exit: close(fd); + return(0); }