BAT12-7670 example
From embeddedTS Manuals
// 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 <iostream>
#include "i2c-dev.h"
#define CONVERSION_DIVISOR 24.7
#define DATASET_SIZE 28
using namespace std;
const char copyright[] = "Copyright (c) Technologic Systems - " __DATE__ ;
/// Convert raw ADC value into voltage level.
/// \arg rawValue The raw ADC value to be converted.
float vConvert(int rawValue);
/// Read I2C bus, grab ADC value for vin.
/// \arg twifd File descriptor for i2c bus.
int get_vin_adc(int twifd);
/// Open the file descriptor for i2c.
int i2cInit(void);
/// Program Main Entry Point.
int main(void)
{
int raw, fd;
float voltage;
fd = i2cInit();
if(fd == -1) {
cout << "VIN=ERROR\n I2C=FAIL" << endl;
return 1; // quit on error.
}
raw = get_vin_adc(fd);
voltage = vConvert(raw);
cout << "VIN=" << voltage << endl;
return 0;
}
/// Divide raw by conversion value.
float vConvert(int rawValue){
float theConversion;
theConversion = (float)rawValue / CONVERSION_DIVISOR;
return theConversion;
}
/// Gets ADC value from i2c.
/// \arg twifd file descriptor for i2c.
/// \out adcValue raw ADC data. Byte 3 is MSB, byte 2 is LSB.
int get_vin_adc(int twifd)
{
uint8_t data[DATASET_SIZE];
bzero(data, DATASET_SIZE);
int adcValue = 0;
read(twifd, data, DATASET_SIZE); // most of this data is garbage
// but the microcontroller will
// only dump all or none so...
adcValue = data[3]<<8|data[2];
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) {
perror("Hardware did not ACK 0x78\n");
return -1;
}
}
return fd;
}