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


void i2c_init(void)
{
  /* initialize TWI clock: 100 kHz clock, TWPS = 0 => prescaler = 1 */
  
  TWSR = 1;                         /* no prescaler */
  TWBR = ((F_CPU/SCL_CLOCK)-16)/2;  /* must be > 10 for stable operation */

}


unsigned char i2c_start(unsigned char address){
	char DATA = 0b10011000;
	//Send START condition
	TWCR =  (1<<TWINT)| 
			(1<<TWSTA)|
			(1<<TWEN);
			
	//Wait for TWINT Flag set. This indicates that the START condition has been transmitted.
	while (!(TWCR &(1<<TWINT)));
	
	//Check value of TWI Status Register. Mask prescaler bits. If status different from START go to ERROR.
	if ((TWSR & 0xF8) != TW_START){
		//ERROR();
	}
	
	//Load SLA_W into TWDR Register. Clear TWINT bit in TWCR to start transmission of address.
	TWDR = address + I2C_WRITE;
	TWCR = (1<<TWINT) |
			(1<<TWEN);
		
	//Wait for TWINT Flag set. This indicates that the SLA+W has been transmitted, and ACK/NACK has been received.	
	while (!(TWCR & (1<<TWINT)));
	
	//Check value of TWI Status Register. Mask prescaler bits. If status different from MT_SLA_ACK go to ERROR.
	if ((TWSR & 0xF8) != TW_MT_SLA_ACK){
	//	 ERROR();
	 }
	
	//Load DATA into TWDR Register. Clear TWINT bit in TWCR to start transmission of data.
	TWDR = DATA;
	TWCR = (1<<TWINT) |
			(1<<TWEN);
			
	//Wait for TWINT Flag set. This indicates that the DATA has been transmitted, and ACK/NACK has been received. 
	while (!(TWCR &(1<<TWINT)));
	
	//Check value of TWI Status Register. Mask prescaler bits. If status different from MT_DATA_ACK go to ERROR.
	if ((TWSR & 0xF8) != TW_MT_DATA_ACK){
	// ERROR();
	}
	
	//Transmit STOP condition
	TWCR = (1<<TWINT)|
			(1<<TWEN) |
			(1<<TWSTO);
	
	
	/*
	TWCR = _BV(TWINT) | _BV(TWSTA) | _BV(TWEN);
	while  (!(TWCR & (1<<TWINT)));
	if ((TWSR & 0xF8) != TW_START)
	return 1;
	//ERROR();                                                                //Fehlerbehandlung
	TWDR = address + I2C_WRITE;
	TWCR = (1<<TWINT) | (1<<TWEN);
	while (!(TWCR & (1<<TWINT)));
	if ((TWSR & 0xF8) != TW_MT_SLA_ACK)
  //ERROR();
  return 2;
 
TWDR = address;
TWCR = (1<<TWINT) | (1<<TWEN);
while (!(TWCR & (1<<TWINT)));
if ((TWSR & 0xF8) != TW_MT_DATA_ACK)
return 3;
  //ERROR();
TWCR = (1<<TWINT)|(1<<TWEN)|
(1<<TWSTO);
*/
return 0;
}







