Atmega328p TWI无法发送起始位

时间:2018-07-23 15:08:05

标签: arduino i2c atmega

我正在尝试实现基本的i2c代码以与DAC设备进行通信。但是,发送起始位后,我编写的代码会挂在while循环中。我已经把数据表,其他人的代码等弄翻了。我不知道自己在做什么错。似乎无论出于何种原因,从未设置TWINT。我知道硬件设置是正确的,因为我加载了Arduino草图来测试设备,并且运行良好。

void i2c_init() { 

   // from datasheet (haven't seen anywhere else though)
   PRR &= ~(1 << PRTWI);
   TWSR &= ~((1 << TWPS1) | (1 << TWPS0));
   TWBR = ((F_CPU / I2C_FREQ) - 16) / (2 * 1);
   PORTC |= (1 << PC5) | (1 << PC4);
   TWCR = (1 << TWEN);
   TWAR = 0;
}

// starts a transmission on the i2c line
// inputs: sl_addr - address of the slave device to be written to
// outputs: 0 - no error
//          1 - start bit not transmitted
//          2 - address not transmitted
uint8_t i2c_start(uint8_t sl_addr) {

   TWCR = (1 << TWINT) | (1 << TWSTA) | (1 << TWEN); 
   while (!(TWCR &= (1 << TWINT)));
   // never gets here! 

   if ((TWSR & 0xf8) != 0x08)       
      return 1;

   TWDR = 0;
   TWDR |= (sl_addr << 1);

   TWCR = (1 << TWINT) | (1 << TWEN);
   while (!(TWCR &= (1 << TWINT)));

   if (TWSR != 0x18)        
      return 2;

   // assume success
   return 0;
}

0 个答案:

没有答案