#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h> 
#include "/usr/include/linux/i2c-dev.h"

int main(void) 
{
	int fd;
	char filename[20];
	char buf[10];
	int res;
	int range=0;

	sprintf(filename, "/dev/i2c-0");
	fd = open(filename, O_RDWR);
	if (fd < 0) {
		printf("Error on open\n");
		exit(1);
	}

	if (ioctl(fd, I2C_SLAVE, 0x70) < 0) {
		printf("Error on slave address\n");
		exit(1);
	}


	buf[0] = 0x00;
	buf[1] = 0x51;
	if ((write(fd,buf,2))!=2) {
		printf("Error send the read command\n");
		exit(1);
	}

	// Wait for the measurement
	usleep(66000);

	buf[0] = 0x02;
	if ((write(fd,buf,1))!=1) {
		printf("Error on select the Range High Byte\n");
		exit(1);
	}

	if ((read(fd,buf,1))!=1) {
		printf("Error on read the Range High Byte\n");
		exit(1);
	}
	range = buf[0]<<8;

	buf[0] = 0x03;
	if ((write(fd,buf,1))!=1) {
		printf("Error on select the Range Low Byte\n");
		exit(1);
	}

	if ((read(fd,buf,1))!=1) {
		printf("Error on read the Range Low Byte\n");
		exit(1);
	}
	range |= buf[0];
	

	printf("Range=%d cm\n",range);	
	close(fd);

	return 0;	
}
