使用AVR TWI接口的问题

问题描述:

我试图使用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)); 
} 

我做错了什么?我该如何解决这个问题?

(所有其他功能都简单地实现为数据表的例子。)

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

看起来不正确的。 TWSTO标志指示停止,并且您正确写入停止。但它保持为1,这会产生无限循环。如果有的话,你会想

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

但示例代码没有循环可言。