2013-02-13 48 views
0

我試圖使用atmega2560訪問HMC5883L模塊。我寫了一個包含I2C通信基本方法的類(I2C)。使用AVR TWI接口的問題

首先,我會解釋這個問題。這就是我所做的。

int main(){ 
    I2C i2c; //an object with basic I2C communication methods 

    i2c.init(); 
    i2c.start(); 
    i2c.sendSLAW(); 
    ... 
    i2c.write(...); 
    ... //configure registers, CRA, CRB, MR ... 
    i2c.stop(); 
    while (1) 
    { 
     i2c.start();   
     i2c.sendSLAR();  
      .... //read x,y,z register values 
     i2c.stop();  
      .... //say, display x,y,z readings 
     _delay_ms(500); 
    } 
} 

(考慮術語具有其一般含義。SLAW = SLA + W(從地址+寫)...)

一切順利,直到它涉及到while循環。在循環中,它似乎被阻止在i2c.stop()

i2c.stop()是這樣實現的;

void I2C::I2C_stop(){ 
    TWCR = (1<<TWINT)|(1<<TWSTO)|(1<<TWEN); 
    while (TWCR & (1<<TWSTO)); 
} 

我做錯了什麼?我該如何解決這個問題?

(所有其他功能都簡單地實現爲數據表的例子。)

回答

0
while (TWCR & (1<<TWSTO)); 

看起來不正確的。 TWSTO標誌指示停止,並且您正確寫入停止。但它保持爲1,這會產生無限循環。如果有的話,你會想

while !(TWCR & (1<<TWSTO)); 

但示例代碼沒有循環可言。