单片机PIC24F256GA108,用的硬件I2C2,发送器件地址后就一直收不到ACK信号了,麻烦高手帮忙看下是什么问题,难道是没初始化好?我I2C初始化就两句话:写BRG寄存器设置速率和将I2CEN位置1,是不是还缺了什么?程序如下:
#define I2C2_Enable() I2C2CONbits.I2CEN = 1
#define I2C2_Disable() I2C2CONbits.I2CEN = 0
#define I2C2_SetBRG(BRG) I2C2BRG = BRG
#define I2C2_Start() I2C2CONbits.SEN = 1;while(I2C2CONbits.SEN)
#define I2C2_Restart() I2C2CONbits.SEN = 1;while(I2C2CONbits.SEN)
#define I2C2_Stop() I2C2CONbits.PEN = 1;while(I2C2CONbits.PEN)
#define I2C2_Idle() while(/*I2C2CON & 0x1f*/ I2C2STATbits.TRSTAT);
#define I2C2_GetAck() while(!I2C2STATbits.ACKSTAT);
#define I2C2_GetNack() while(I2C2STATbits.ACKSTAT);
#define I2C2_SendAck() I2C2CONbits.ACKDT = 0;I2C2CONbits.ACKEN = 1;while(I2C2CONbits.ACKEN)
#define I2C2_SendNack() I2C2CONbits.ACKDT = 1;I2C2CONbits.ACKEN = 1;while(I2C2CONbits.ACKEN)
void I2C2_Init()
{
I2C2BRG = 0x004e;
I2C2CON = 0x1000;
}
void I2C2_Write(uint8_t byte)
{
I2C2TRN = byte;
while (I2C2STATbits.TBF);
}
uint8_t I2C2_Read()
{
uint8_t byte;
I2C2CONbits.RCEN = 1;
while(I2C2STATbits.RBF);
byte = I2C2RCV;
return byte;
}
void Eeprom_Init()
{
I2C2_Init();
}
void Eeprom_Write(uint8_t Device_Addr,uint8_t Data_Addr,uint8_t Data)
{
I2C2_Start();
I2C2_Idle();
I2C2_Write(Device_Addr);
I2C2_Idle();
I2C2_GetAck();
I2C2_Write(Data_Addr);
I2C2_Idle();
I2C2_GetAck();
I2C2_Write(Data);
I2C2_Idle();
I2C2_GetAck();
I2C2_Stop();
I2C2_Idle();
}
uint8_t Eeprom_Read(uint8_t Device_Addr,uint8_t Data_Addr)
{
uint8_t byte;
I2C2_Start();
I2C2_Idle();
I2C2_Write(Device_Addr);
I2C2_Idle();
I2C2_GetAck();
I2C2_Write(Data_Addr);
I2C2_Idle();
I2C2_GetAck();
I2C2_Restart();
I2C2_Idle();
I2C2_Write(Device_Addr | 0x01);
I2C2_Idle();
I2C2_GetAck();
byte = I2C2_Read();
I2C2_SendNack();
I2C2_Stop();
I2C2_Idle();
return byte;
}
发送完器件地址后就一直停在了I2C2_GetAck() 即 while(!I2C2STATbits.ACKSTAT)处。 |