BAT12-7670 example

From embeddedTS Manuals
Revision as of 10:27, 15 December 2016 by Mpeters (talk | contribs) (removed c++ elements, moved functions above main(), deleted prototypes, unified functions to camelCase, added comment and link to ftp where header file and sample source exist.)

This source and its accompanying header file 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 "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()
{
	static 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;
}

/// Program Main Entry Point.
int main(void)
{
	int raw, fd;
	float voltage;

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