I2C programming ATTiny88

attinyi2cmicrocontrollerprogrammingsensor

I am beginner at programming uC's. I have read all the tutorials on what is I2C and how it works, but I couldnt find any help specific on how to create a connection between my sensor and ATTiny88 (ATTiny88 datasheet.

I use SHT21 sensor (SHT21 datasheet) and want to communicate with ATTiny88 (MUC sends command to getData, and then sensors sends to MUC back the data (temperature, humidity)) – can someone help me guide through?

Once you help me, I'll understand it for future, but I really need a jump start here.

Thanks!

Best Answer

I have done I2C Communications for the Atmega32 and I interfaced a temperature sensor. Looking at the datasheet ATtiny and atmega has the same registers for I2C Communications. So you can use the following code I made for I2C Communication

This function will write the data to the I2C bus:

void i2c_write(unsigned char data)
{
  TWDR = data ;
  TWCR = (1<< TWINT)|(1<<TWEN);
  while ((TWCR & (1 <<TWINT)) == 0);
}

This function will start the I2C Communication:

void i2c_start(void)
{
  TWCR = (1 << TWINT) | (1 << TWSTA) | (1 << TWEN);
  while ((TWCR & (1 << TWINT)) == 0);
}

This function will stop the communication:

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

This function will initiate the I2C bus:

void i2c_init(void)
{
  TWSR=0x00;            
  TWBR=0x47;            
  TWCR=0x04;            
}

Now you can use these functions in you main

int main (void)
{
  i2c_init();   
  i2c_start();          
  i2c_write(address);   
  i2c_write(address);   
  i2c_stop();           
  while(1);         
  return 0;
}

NOTE: Make the last bit of your address to 0 for writing and 1 reading from the i2c bus