|
贴上我的I2C函数吧,我敢用while()等待,因为我反复试了,软件很健壮,即使死掉在while()里一次,也有狗看着,怕什么
void I2C2_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
I2C_InitTypeDef I2C_InitStructure;
// Configure I2C2 pins: SCL and SDA
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10 | GPIO_Pin_11;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_OD;
GPIO_Init(GPIOB, &GPIO_InitStructure);
I2C_InitStructure.I2C_Mode = I2C_Mode_I2C;
I2C_InitStructure.I2C_DutyCycle = I2C_DutyCycle_2;
I2C_InitStructure.I2C_OwnAddress1 = 0xa2;
I2C_InitStructure.I2C_Ack = I2C_Ack_Enable;
I2C_InitStructure.I2C_AcknowledgedAddress = I2C_AcknowledgedAddress_7bit;
I2C_InitStructure.I2C_ClockSpeed = 100000;
I2C_Cmd(I2C2, ENABLE);
I2C_Init(I2C2, &I2C_InitStructure);
}
void I2C_AcknowledgePolling(u8 sla)
{
vu16 SR1_Tmp;
I2C_ClearFlag(I2C2, I2C_FLAG_ADDR);
do
{
I2C_GenerateSTART(I2C2, ENABLE);
SR1_Tmp = I2C_ReadRegister(I2C2, I2C_Register_SR1);
I2C_Send7bitAddress(I2C2, sla, I2C_Direction_Transmitter);
}while(!(I2C_ReadRegister(I2C2, I2C_Register_SR1) & I2C_FLAG_ADDR));
I2C_ClearFlag(I2C2, I2C_FLAG_AF);
}
void I2C_SequentialRead_AT24C01A_02(u8 sla, u8 suba, u8 *pHead, u8 len)
{
u8 i;
I2C_AcknowledgePolling(sla);
I2C_GenerateSTART(I2C2, ENABLE);
while(!I2C_CheckEvent(I2C2, I2C_EVENT_MASTER_MODE_SELECT));
I2C_Send7bitAddress(I2C2, sla, I2C_Direction_Transmitter);
while(!I2C_CheckEvent(I2C2, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED));
I2C_SendData(I2C2, suba);
while(!I2C_CheckEvent(I2C2, I2C_EVENT_MASTER_BYTE_TRANSMITTED));
I2C_GenerateSTART(I2C2, ENABLE);
while(!I2C_CheckEvent(I2C2, I2C_EVENT_MASTER_MODE_SELECT));
I2C_Send7bitAddress(I2C2, sla+1, I2C_Direction_Receiver);
while(!I2C_CheckEvent(I2C2, I2C_EVENT_MASTER_RECEIVER_MODE_SELECTED));
if(len > 1)
{
for(i=0; i<(len-1); i++)
{
while(!I2C_CheckEvent(I2C2, I2C_EVENT_MASTER_BYTE_RECEIVED));
*pHead++ = I2C_ReceiveData(I2C2);
I2C_AcknowledgeConfig(I2C2, ENABLE);
}
}
while(!I2C_CheckEvent(I2C2, I2C_EVENT_MASTER_BYTE_RECEIVED));
*pHead = I2C_ReceiveData(I2C2);
I2C_AcknowledgeConfig(I2C2, DISABLE);
I2C_GenerateSTOP(I2C2, ENABLE);
}
void I2C_PageWrite_AT24C01A_02(u8 sla, u8 suba, u8 *pHead, u8 len)
{
u8 wLen, addr;
wLen = len;
addr = suba;
ScrollPage: I2C_AcknowledgePolling(sla);
I2C_GenerateSTART(I2C2, ENABLE);
while(!I2C_CheckEvent(I2C2, I2C_EVENT_MASTER_MODE_SELECT));
I2C_SendData(I2C2, sla);
while(!I2C_CheckEvent(I2C2, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED));
I2C_SendData(I2C2, addr);
while(!I2C_CheckEvent(I2C2, I2C_EVENT_MASTER_BYTE_TRANSMITTED));
I2C_SendData(I2C2, *pHead++);
while(!I2C_CheckEvent(I2C2, I2C_EVENT_MASTER_BYTE_TRANSMITTED));
addr++;
wLen--;
while(wLen)
{
if(addr%8)
{
I2C_SendData(I2C2, *pHead++);
while(!I2C_CheckEvent(I2C2, I2C_EVENT_MASTER_BYTE_TRANSMITTED));
addr++;
wLen--;
}
else
{
I2C_GenerateSTOP(I2C2, ENABLE);
goto ScrollPage;
}
}
I2C_GenerateSTOP(I2C2, ENABLE);
} |
|