BAT12-7670 example

From embeddedTS Manuals

This source can be found on the Technologic Systems FTP here.

// TS-7670 BAT12 Monitor
// Written by Michael D. Peters
// C. 2016 Technologic Systems, Inc.

// Read ADC at I2C address 0x78, parse bytes 3 (adc high byte)
//  and 2 (adc low byte), divide by magic 24.7 and presto input
//  voltage.
// Output VIN=<input voltage> so a script can parse and use.

#include <stdio.h>
#include <stdint.h>
#include <fcntl.h>
#include <stdlib.h>
#include <strings.h>
#include <linux/i2c-dev.h>

#define CONVERSION_DIVISOR 24.7
#define DATASET_SIZE 28

const char copyright[] = "Copyright (c) Technologic Systems - " __DATE__ ;

/// Divide raw by conversion value.
/// \arg rawValue The ADC value to convert to volts.
float vConvert(int rawValue){
	float theConversion;

	theConversion = (float)rawValue / CONVERSION_DIVISOR;

	return theConversion;
}

/// Gets ADC value from i2c.
/// \arg twifd file descriptor for i2c.
int getVinAdc(int twifd)
{
	uint8_t data[DATASET_SIZE];
	bzero(data, DATASET_SIZE);
	int adcValue = 0;

	read(twifd, data, DATASET_SIZE); // most of this data is reserved
					   // but the microcontroller will
					   // only dump all or none.
	adcValue = data[3]<<8|data[2];  // Byte 3 is MSB, byte 2 is LSB.
	return adcValue;
}

/// Opens I2C to 0x78.  Returns file descrptor if OK else quits.
int i2cInit()
{
	int fd = -1;
	fd = open("/dev/i2c-0", O_RDWR);
	if(fd != -1) {
		if (ioctl(fd, I2C_SLAVE_FORCE, 0x78) < 0) {
			return -2;
		}
	}
	return fd;
}

/// Main Entry Point.
//  program quits with -1 on file io error, -2 on i2c error.
int main(void)
{
	int raw, fd;
	float voltage;

	fd = i2cInit();
        if(fd == -1 || fd == -2) {
          printf("VIN=%d\n", fd);
          return fd; // quit on error.
        }
	raw = getVinAdc(fd);
	voltage = vConvert(raw);
        printf("VIN=%f\n", voltage);
	return 0;
}