#include <stdlib.h>  
#include <stdio.h>  
#include <fcntl.h>  
#include <errno.h>

#include "i2c-dev.h"

int main()
{
	int file;
	int adapter_nr = 0; /* probably dynamically determined */
	char filename[20];
	int addr; /* The I2C address */
	unsigned char reg = 0; /* Device register to access */
	unsigned char buf[10];
	int count,i;

	sprintf(filename,"/dev/i2c-%d",adapter_nr);
	if ((file = open(filename,O_RDWR)) < 0)
	{
	    fprintf(stderr, "open() failed: %s\n",strerror(errno));
	    exit(1);
	}

	addr = 0x20;
	
	printf("contacting device %0x\n", addr);
	if (ioctl(file, I2C_SLAVE, addr) < 0) {
		if (errno == EBUSY) {
			printf("device in use\n");
		} else {
			fprintf(stderr, "Error: Could not set address to 0x%02x: %s\n", addr, strerror(errno));
		}
		exit(-1);
	}
	
	for( i = 0; i < 100; i++)
	{
		for( count=0; count < 8; count++)
		{
			reg = (unsigned char)(1 << count);
			buf[0] = reg ^ 0xFF;
			if(write(file,buf,1)!=1)
			{
				fprintf(stderr,"write() failed: %s\n",strerror(errno));
				break;
			}
			if(read(file,buf,1)!=1)
			{
				fprintf(stderr,"read() failed: %s\n",strerror(errno));
	                        break;
			}
			printf("sent %0x, received %0x\n",reg,buf[0]);
		}
	}
		
	close(file);
	exit(0);
}


