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

i2c::i2c()
{
    TWBR = 72;                                  //neu : Bitrate 400 khz
    TWSR = 3;//0;                               //Prescaler 64/ 0
}

void i2c::start()
{
        TWCR = _BV(TWINT) | _BV(TWSTA) | _BV(TWEN); //start, und warte bis angekommen
        while (!(TWCR & (1<<TWINT)))
        {
        }
}

void i2c::stop()
{
        TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWSTO); //stop
}

unsigned char i2c::read()
{
        TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);      //read mit ACK
        while ((TWCR & (1<<TWINT)) == 0)
        {
        }
        return TWDR;
}

unsigned char i2c::read_end()
{
        TWCR = (1<<TWINT)|(1<<TWEN);                //read ohne ACK (NACK)
        while ((TWCR & (1<<TWINT)) == 0)
        {
        }
        return TWDR;
}

void i2c::write(unsigned char wert)
{
        TWDR = wert;
        TWCR = (1<<TWINT) | (1<<TWEN) ;
        while (!(TWCR & (1<<TWINT)))               //data und warte
        {
        }
}
