0

I'm trying to access HMC5883L module using atmega2560. I've written a class (I2C) containing basic methods essential for I2C communication.

First, I'll explain the problem. This is what I've done.

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);
    }
}

(Consider the terms have their ordinary meanings. SLAW = SLA+W (Slave address + write)...)

Everything goes well till it comes to the while loop. In the loop, it seems to be get stucked at i2c.stop()

i2c.stop() is implemented like this;

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

Have i done something wrong ? How can i solve this?

(All other functions are implemented simply as in the datasheet examples.)

Anubis
  • 6,995
  • 14
  • 56
  • 87

1 Answers1

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

doesn't look right. The TWSTO flag indicates stop, and you correctly write to it to stop. But it stays 1, which produces an infinite loop. If anything, you will want

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

but the code examples don't have a loop at all.

UncleO
  • 8,299
  • 21
  • 29