本帖最后由 fydabcd 于 2022-6-22 18:38 编辑
主机模式,从机为24C04,24C04的随机读写,需要发完器件地址和子地址后,重新发送起始位和器件地址才能读。
调试调用函数I2c_Buffer_Read(I2C0_SFR, 0xA0, i2c_read_buffer, 10);
另外比较疑惑的是官方的里程中,读和写的函数都没有子地址的参数,这个不应该是I2C的标配吗?
/*发送起始位*/void I2c_Buffer_Read(I2C_SFRmap* I2Cx, uint16_t Read_I2C_Addr, uint8_t *p_buffer, uint16_t number_of_byte)
{
I2Cx->SR = 0;
I2C_Cmd(I2Cx, TRUE);
I2C_Clear_INTERRUPT_Flag(I2Cx);
I2C_Generate_START(I2Cx, TRUE);
while (!I2C_Get_INTERRUPT_Flag(I2Cx));
/*发送器件地址*/
I2C_SendData8(I2Cx, Read_I2C_Addr | 0x01);
I2C_Clear_INTERRUPT_Flag(I2Cx);
while (!I2C_Get_INTERRUPT_Flag(I2Cx));
I2c_Wait_Ack_Flag(I2Cx);
if(AckTimeoutFlag == 1)
{
return (void)0;
}
/*发送子地址*/
I2C_SendData8(I2Cx, 0x0);/*此处调试中,子地址固定为0*/
I2C_Clear_INTERRUPT_Flag(I2Cx);
while (!I2C_Get_INTERRUPT_Flag(I2Cx));
I2C_Clear_INTERRUPT_Flag(I2Cx);
I2c_Wait_Ack_Flag(I2Cx);
if(AckTimeoutFlag == 1)
{
return (void)0;
}
/*重发起始位*/
I2C_Clear_Start_Flag(I2Cx);
I2C_Clear_INTERRUPT_Flag(I2Cx);
I2C_Generate_START(I2Cx, TRUE);
while (!I2C_Get_INTERRUPT_Flag(I2Cx));
/*重发器件地址*/
I2C_SendData8(I2Cx, Read_I2C_Addr | 0x01);
I2C_Clear_INTERRUPT_Flag(I2Cx);
while (!I2C_Get_INTERRUPT_Flag(I2Cx));
I2c_Wait_Ack_Flag(I2Cx);
if(AckTimeoutFlag == 1)
{
return (void)0;
}
/*读取数据*/
while (number_of_byte)
{
while (!I2C_Get_INTERRUPT_Flag(I2Cx));
if (I2C_Get_Receive_Buff_Flag(I2Cx))
{
I2C_Ack_DATA_Config(I2Cx, I2C_ACKDATA_ACK);
*p_buffer = I2C_ReceiveData(I2Cx);
I2C_Clear_INTERRUPT_Flag(I2Cx);
p_buffer++;
}
number_of_byte--;
}
/* Stop bit */
I2C_Generate_STOP(I2Cx, TRUE);
/* Clear the ISIF bit of the I2C interrupt flag */
I2C_Clear_INTERRUPT_Flag(I2Cx);
/* Wait for the stop to complete */
while (!I2C_Get_INTERRUPT_Flag(I2Cx));
// ;
/* Clear the ISIF bit of the I2C interrupt flag */
I2C_Clear_INTERRUPT_Flag(I2Cx);
/* Clear the I2C stop flag PIF bit */
I2C_Clear_Stop_Flag(I2Cx);
/* Turn off the I2C module */
I2C_Cmd(I2Cx, FALSE);
}
|