#include <avr/io.h>
#include <util/delay.h>
#include "i2c.h"

// *************************************************
// FCE: ovladani sbernice I2C (TWI)
// INC: "i2c.h"
// DAT: 17.2.2012
// VER: 1
// *************************************************

void I2CInit()
{
	TWBR = 2;
	TWSR |=((1<<TWPS1)|(1<<TWPS0));

	TWCR|=(1<<TWEN);
}


void I2CClose()		
{
	TWCR&=(~(1<<TWEN));
}


void I2CStart()
{
	TWCR=(1<<TWINT)|(1<<TWEN)|(1<<TWSTA);

	while(!(TWCR & (1<<TWINT)));
}


void I2CStop()
{
	TWCR=(1<<TWINT)|(1<<TWEN)|(1<<TWSTO);

	while(TWCR & (1<<TWSTO));
	//_delay_loop_2(250);
}


uint8_t I2CWriteByte(uint8_t data)
{	
	TWDR=data;	

	TWCR=(1<<TWEN)|(1<<TWINT);

	while(!(TWCR & (1<<TWINT)));

	if((TWSR & 0xF8) == 0x18 || (TWSR & 0xF8) == 0x28 || (TWSR & 0xF8) == 0x40)
	{
		return TRUE;
	}
	else
	return FALSE;	//Error
}


uint8_t I2CReadByte(uint8_t *data,uint8_t ack)
{
	if(ack)
	{
		TWCR|=(1<<TWEA);
	}
	else
	{
		TWCR&=(~(1<<TWEA));
	}

	TWCR|=(1<<TWINT);

	while(!(TWCR & (1<<TWINT)));

	if((TWSR & 0xF8) == 0x58 || (TWSR & 0xF8) == 0x50)
	{
		*data=TWDR;
		return TRUE;
	}
	else
	return FALSE;	//Error
	
}
