新聞中心

EEPW首頁 > 嵌入式系統(tǒng) > 設(shè)計應(yīng)用 > 關(guān)于ATMEGA32的TWI使用

關(guān)于ATMEGA32的TWI使用

作者: 時間:2013-12-12 來源:網(wǎng)絡(luò) 收藏

前段時間使用的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ù)據(jù),最后用Beagle-GUI.抓取I2C,結(jié)果發(fā)現(xiàn)讀I2C時,送出叢機地址和寄存器地址后就退出,原來是從機未發(fā)出ACK響應(yīng)主機,因此關(guān)于的TWI有幾點要注意:

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的時候,讀時的ACK是不一樣的,前(N-1)個字節(jié)應(yīng)該發(fā)出ACK信號響應(yīng),但是最后一個字節(jié)應(yīng)該發(fā)送ACK信號。

以上的代碼未加入,需要改善



關(guān)鍵詞: ATMEGA32 TWI使用 容錯機制

評論


相關(guān)推薦

技術(shù)專區(qū)

關(guān)閉