void I2C_Send(u8 D_Addr, u8 R_Addr, u8 Data)
{
while(I2C_GetFlagStatus(I2C1, I2C_FLAG_BUSY)); /*检测总线是否忙 就是看 SCL 或SDA是否为 低 */
/*允许1字节1应答模式*/
I2C_AcknowledgeConfig(I2C1, ENABLE);
/* 发送起始位 */
I2C_GenerateSTART(I2C1, ENABLE);
while(!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_MODE_SELECT)); /*EV5,主模式*/
/*发送器件地址(写)*/
I2C_Send7bitAddress(I2C1, D_Addr, I2C_Direction_Transmitter);
while (!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED));
I2C_SendData(I2C1, R_Addr);
while (!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_BYTE_TRANSMITTED)); /*数据已发送*/
I2C_SendData(I2C1, Data);
while (!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_BYTE_TRANSMITTED)); /*数据已发送*/
I2C_GenerateSTOP(I2C1, ENABLE); //发送停止位
}
u8 I2C_Receive(u8 D_Addr, u8 R_Addr)
{
u8 a;
while(I2C_GetFlagStatus(I2C1, I2C_FLAG_BUSY)); /*检测总线是否忙 就是看 SCL 或SDA是否为 低 */
/*允许1字节1应答模式*/
I2C_AcknowledgeConfig(I2C1, ENABLE);
I2C_GenerateSTART(I2C1, ENABLE);
while(!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_MODE_SELECT));
I2C_Send7bitAddress(I2C1, D_Addr+1, I2C_Direction_Receiver);
while(!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_RECEIVER_MODE_SELECTED));
Put_String("\n\r读数据\n\r");
I2C_AcknowledgeConfig(I2C1, DISABLE);
I2C_GenerateSTOP(I2C1, ENABLE);
while( !((I2C1->SR1) & 0x40) || ((I2C1->SR2) & 0x20));
a=I2C_ReceiveData(I2C1);
I2C_AcknowledgeConfig(I2C1,ENABLE);
return a;
} |