ADS1115 Problem with C Code
Posted: Wed Mar 06, 2013 9:44 pm
I have an ADS1115 from adafruit connected to my rpi i2c 1.
I am using ain0 single ended.
I use a breadboard and a jumper to connect ain0 either to ground or vdd.
I can read the ads1115 from the command line with i2cset and i2cget. Ok.
I can read the ads1115 with the adafruit python code. Ok.
I can read the ads1115 with C code with one problem. If I ground ain0, I can read approx 0v. If I then connect ain0 to vdd, the first time I execute the code, I still get 0v. The next time I execute the code, I get 3.299v as I expect.
There must be some simple problem I am overlooking. But, what?
I am using ain0 single ended.
I use a breadboard and a jumper to connect ain0 either to ground or vdd.
I can read the ads1115 from the command line with i2cset and i2cget. Ok.
I can read the ads1115 with the adafruit python code. Ok.
I can read the ads1115 with C code with one problem. If I ground ain0, I can read approx 0v. If I then connect ain0 to vdd, the first time I execute the code, I still get 0v. The next time I execute the code, I get 3.299v as I expect.
There must be some simple problem I am overlooking. But, what?
Code: Select all
///////////////////////////////////////////////////////////////////////////////
#include <stdio.h>
#include <sys/types.h> // open
#include <sys/stat.h> // open
#include <fcntl.h> // open
#include <unistd.h> // read/write usleep
#include <stdlib.h> // exit
#include <inttypes.h> // uint8_t, etc
#include <linux/i2c-dev.h> // I2C bus definitions
////////////////////////////////////////////////
// main
int main() {
int fd;
int ads_address = 0x48;
uint8_t buf[10];
int16_t val;
// open device on /dev/i2c-1 the default on Raspberry Pi B
if ((fd = open("/dev/i2c-1", O_RDWR)) < 0) {
printf("Error: Couldn't open device! %d\n", fd);
return 1;
}
// connect to ads1115 as i2c slave
if (ioctl(fd, I2C_SLAVE, ads_address) < 0) {
printf("Error: Couldn't find device on address!\n");
return 1;
}
///////////////////////////////
// set config register and start conversion
// AIN0 and GND, 4.096v, 128s/s
buf[0] = 1; // config register is 1
buf[1] = 0xc3;
buf[2] = 0x85;
if (write(fd, buf, 3) != 3) {
perror("Write to register 1");
exit(-1);
}
//////////////////////////////
// wait for conversion complete
do {
if (read(fd, buf, 2) != 2) {
perror("Read conversion");
exit(-1);
}
} while (buf[0] & 0x80 == 0);
//////////////////////////////
// read conversion register
buf[0] = 0; // conversion register is 0
if (write(fd, buf, 1) != 1) {
perror("Write register select");
exit(-1);
}
if (read(fd, buf, 2) != 2) {
perror("Read conversion");
exit(-1);
}
//////////////////////////////
// convert output and display results
val = (int16_t)buf[0]*256 + (uint16_t)buf[1];
printf("Conversion %02x %02x %d %f\n",
buf[0], buf[1], val, (float)val*4.096/32768.0);
close(fd);
return 0;
}