/* 
 * To compile get_vin, use the appropriate cross compiler and run the
 * command:
 *
 *  gcc -fno-tree-cselim -Wall -O0 -mcpu=arm9 -o get_vin get_vin.c
 */

/* This software is intended to run on the TS-7670 Rev. D or later
 *
 * The math below is done with all integers, the values are multiplied up
 * and then divided down to get the best resolution.  This software works
 * for the full VIN range read through the on-board supervisory microcontroller.
 */


#include <assert.h>
#include <unistd.h>
#include <fcntl.h>
#include <linux/i2c-dev.h>
#include <stdio.h>
#include <strings.h>
 
int main(void)
{
	unsigned char data[4];
	unsigned int vin;
	int fd;
 
	fd = open("/dev/i2c-0", O_RDWR);
	assert (fd != -1);
	
	if (ioctl(fd, I2C_SLAVE_FORCE, 0x78) < 0) {
		perror("MCU did not ACK 0x78\n");
		return -1;
	}
 
	bzero(data, 4);
	read(fd, data, 4);
	vin = (data[3]<<8)|data[2];
	vin = (((vin*24438)*172)/100000); /* 5.82% div., 2.5 Vref, 10b acc. */
	printf("vin_mv=%d\n", vin);

	return 0;
}
