Mehran University of Engineering & Technology,
Jamshoro
Department of Telecommunication Engineering
Microcontroller & Applications
Programming I2C or TWI
By:
Engr. Azam Rafique
Instrumentation Engineer
TQCIC, IIT Building, MUET,
Jamshoro, Pakistan
email: azammemon2000@gmail.com
Inter-Integrated Circuit/Two Wire
Interface
Registers
TWBR (TWI Bitrate Register)
To TWI Clock Frequency
TWSR (TWI Status Register)
TWCR (TWI Control Register)
TWBR (TWI Bit-rate Register)
=
24
16)
TWPS is in TWSR to set Pre-scaler
TWSR (TWI Status Register)
TWCR (TWI Control Register)
Programming Steps
1. Set Frequency and Enable TWI
2. Start TWI (TWCR)
3. Write Address (TWDR & TWCR)
4. Write Data (TWDR & TWCR)
5. Stop TWI (TWCR)
Address:
b0=0
b0=1
// Write Operation
// Read Operation
1. Write Byte in master Mode @ 50KHz
#include avr/io.h
int main(void)
{
TWSR=0x00;
TWBR=0x48;
TWCR=0x04;
TWCR |= (1<<TWSTA);
while(TWCR & (1<< TWINT) == 0);
// start TWI
// wait till op. finish
TWDR=0xD0;
while(TWCR & (1<<TWINT) == 0);
// Address + Write(0)
// wait till tx completes
TWDR=0xF0;
while(TWCR & (1<<TWINT) == 0);
// Data
// wait till tx completes
TWCR |= (1<<TWSTO);
while(1);
// Stop TWI
return 0;
}
2. Read Data from Address 0x98 and
display data at Port A @ 50KHz
#include avr/io.h
int main()
{
DDRA=0xFF;
TWSR=0x00;
TWBR=0x48;
TWCR=0x04;
TWCR |= (1>>TWSTA);
while(TWCR & (1<<TWINT) == 0);
TWDR=0x99;
//Address + Read (1)
while(TWCR & (1<<TWINT) == 0);
while(TWCR & (1<<TWINT) == 0);
PORTA=TWDR;
TWCR |= (1<<TWSTO);
while(1);
return 0;
}