c - 与 EEPROM 的 I2C 通信

标签 c pic i2c

我基本上有这个问题,已经困扰我一段时间了。我有一个 PIC32MX128L128H 处理器和一个基本 I/O 扩展板。除了使用 I2C 与 EEPROM 进行通信外,引脚和一切都正确完成。我将复制下面的代码,但在此之前,我有控件:

I2C1CON: bit 0 SEN:启动条件使能位 bit 2 PEN:停止条件使能位 bit 3 RCEN:接收使能位 bit 4 ACKEN:应答序列使能位 bit 5 ACKDT:应答数据位

I2C1STAT: bit 15 ACKSTAT:应答状态位(1 = 未收到,0 = 已收到) bit 14 TRSTAT:发送状态位 bit 6 I2COV:I2C 接收溢出状态位

谢谢!

void EEPROM_wait(){
  while(I2C1STAT & (1 << 15)){

    I2C1CON |= 0x1;
    while(I2C1CON & 0x1);

    I2C1TRN = 0xa0;
    while(I2C1STAT & (1 << 14));

  }
}

void i2c_wait(){
  while(I2C1CON & 0x1f || I2C1STAT & (1 << 14));
}




void writeByte(uint8_t lowByte, uint8_t highByte, uint8_t data){


  //Start Procedure
  do{
  I2C1CON |= 0x1;
  i2c_wait();
  I2C1TRN = 0xa0;
  i2c_wait();
  } while(I2C1STAT & (1 << 15));
  //Send the adress of the EEPROM and also R/W bit

  //Send highByte
  I2C1TRN = highByte;
  i2c_wait();

  //Send lowByte
  I2C1TRN = lowByte;
  i2c_wait();

  //Send actual data
  I2C1TRN = data;
  i2c_wait();

  //Stop the procedure
  I2C1CON |= 0x4;
  i2c_wait();

  EEPROM_wait();



}


uint8_t readByte(uint8_t lowByte, uint8_t highByte)
{



  //Initialize Procedure
  do{
  I2C1CON |= 0x1;
  i2c_wait();
  I2C1TRN = 0xa0;
  i2c_wait();
  }while(I2C1STAT & (1 << 15));

  //Send the address of the EEPROM
  //I2C1TRN = 0xa0;
  //i2c_wait();

  //Send highByte
  I2C1TRN = highByte;
  i2c_wait();

  //Send lowByte

  I2C1TRN = lowByte;
  i2c_wait();

  //Initialize Procedure Read
  do{
  I2C1CON |= 0x1;
  i2c_wait();
  I2C1TRN = 0xa1;
  i2c_wait();
  } while (I2C1STAT & (1 << 15));

  //Send the address of the EEPROM with Read bit
  //I2C1TRN = 0xa1;
  //i2c_wait();

  //Enable Receive Procedure
  I2C1CON |= 1 << 3;
  i2c_wait();
  I2C1STATCLR = 1 << 6;

  //Read from the EEPROM
  uint8_t rtn = I2C1RCV;

  //Acknowledge
  I2C1CON &= ~(1 << 5);
  I2C1CON |= 1 << 4;

  //Stop Procedure
  I2C1CON |= 1 << 2;
  i2c_wait();

  return rtn;

}

最佳答案

我意识到问题出在哪里了。芯片组总线时钟速率未设置为与 i2c 总线时钟相同,导致中间写入或误读。

关于c - 与 EEPROM 的 I2C 通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54728534/

相关文章:

c - 学习C : noob suitable debugger

c++ - 显示占用 8 个字节的 int

c - 当变量更改时如何打破 if

c - XC8 寄存器声明冲突(例如 TRIS、SSP1CON1 等)

使用 Micropython 和 NodeMCU 12E 的 I2C 扫描返回空列表

c - STM32F4-探索板: Print out data from connected sensor on the PC screen

c - 内存映射显示分配给神秘变量 _powers_ 和 _npowers_ 的空间

c - 我的指针错误地更改了地址

c - 使用C语言的PIC单片机

c - 用于 i2c 设备的 linux 驱动程序——读取两个字节