關(guān)于ATMEGA32的TWI使用
前段時(shí)間使用ATMEGA32的TWI,總結(jié)如下:
unsigned char WriteRtc( unsigned char SlaAddr, unsigned char RegAddr, unsigned char *SlaData, unsigned char Length )
{
unsigned char i;
TWCR = ( 1TWINT ) | ( 1TWSTA ) | ( 1TWEN );
while( !( TWCR ( 1TWINT ) ) ); //wait for TWINT set , caused by start signal
TWDR = SlaAddr; //TWDR must be written when TWINT set
TWCR = ( 1TWINT ) | ( 1TWEN );
while( !( TWCR ( 1TWINT ) ) ); //wait for TWINT set , caused by transmit SlaAddr signal
TWDR = RegAddr; //write register address
TWCR = ( 1TWINT ) | ( 1TWEN ); //clear TWINT
while( !( TWCR ( 1TWINT ) ) ); //wait for TWINT set , caused by RegAddr signal
for( i = 0; i Length; i++ )
{
TWDR = *( SlaData+i );
TWCR = ( 1TWINT ) | ( 1TWEN );
while( !( TWCR ( 1TWINT ) ) );
}
TWCR = ( 1TWINT ) | ( 1TWEN ) | ( 1TWSTO ); // I2c stop
return(1);
}
//read RTC
unsigned char ReadRtc( unsigned char SlaAddr, unsigned char RegAddr, unsigned char *pRead, unsigned char Length )
{
unsigned char i;
TWCR = ( 1TWINT ) | ( 1TWSTA ) | ( 1TWEN ); //I2c start
while( !( TWCR ( 1TWINT ) ) ); //wait TWINT
TWDR = SlaAddr-1; //send slave address
TWCR = ( 1TWINT ) | ( 1TWEN );
while( !( TWCR ( 1TWINT ) ) );
TWDR = RegAddr; //send register of device
TWCR = ( 1TWINT ) | ( 1TWEN );
while( !( TWCR ( 1TWINT ) ) );
TWCR = ( 1TWINT ) | ( 1TWEN ) | ( 1TWSTO ); //I2c stop
DDRC = 0XFD; //set SDA as input
PORTC |= 0X02; //set pull-up resistor
TWCR = ( 1TWINT ) | ( 1TWSTA ) | ( 1TWEN ); //start I2c
while( !( TWCR ( 1TWINT ) ) ) ;
TWDR = SlaAddr;
TWCR = ( 1TWINT ) | ( 1TWEN ) ;
while( !( TWCR ( 1TWINT ) ) );
for( i = 0; i Length - 1; i++ )
{
TWCR = ( 1TWINT ) | ( 1TWEN ) | ( 1TWEA ); //send ack
while( !( TWCR ( 1TWINT ) ) );
*( pRead+i ) = TWDR;
}
TWCR = ( 1TWINT ) | ( 1TWEN ); //send nack
while( !( TWCR ( 1TWINT ) ) );
*( pRead+i ) = TWDR;
TWCR = ( 1TWINT ) | ( 1TWEN ) | ( 1TWSTO ); //I2c stop
DDRC |= 0X03;
return(1);
}
剛開始用的時(shí)候,老是讀出錯(cuò)誤的數(shù)據(jù),最后用Beagle-GUI.抓取I2C,結(jié)果發(fā)現(xiàn)讀I2C時(shí),送出叢機(jī)地址和寄存器地址后就退出,原來是從機(jī)未發(fā)出ACK響應(yīng)主機(jī),因此關(guān)于ATMEGA32的TWI有幾點(diǎn)要注意:
1. 首先,關(guān)于TWI寫順序是: I2cStart ----> WriteSlaAddr -----> WriteRegAddr ----> WriteData ----> I2cStop;
2. 其次, 關(guān)于TWI讀N字節(jié)的順序是:I2cStart ----> WriteSlaAddr ----> WriteRegAddr ----> I2cStop ----> I2cStart ---> WriteSlaAddr ----> sendAck----> receive data( (N-1) bytes ) ----->SendNACK ---->receive data ( the last byte) -----> I2cStop;
3. 最后提醒:讀TWI的時(shí)候,讀時(shí)的ACK是不一樣的,前(N-1)個(gè)字節(jié)應(yīng)該發(fā)出ACK信號響應(yīng),但是最后一個(gè)字節(jié)應(yīng)該發(fā)送ACK信號。
以上的代碼未加入容錯(cuò)機(jī)制,需要改善
評論