主机接收n个字节:
void I2C_ByteRead(void)
{
while(I2C_GetFlagStatus(I2C2,I2C_FLAG_BUSY));
I2C_GenerateSTART(I2C2, ENABLE);
//EV5
while(!I2C_CheckEvent(I2C2,I2C_EVENT_MASTER_MODE_SELECT));
//while(!((uint16_t)(I2C2->SR1)&(uint16_t)(0x0001)));//SB=1
//while(((uint16_t)(I2C2->SR2)&(uint16_t)(0x0003))!=0x0003);//BUSY=1
I2C_Send7bitAddress(I2C2, I2C2_SLAVE_ADDRESS7, I2C_Direction_Transmitter);
//EV6
while(!I2C_CheckEvent(I2C2,I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED));
//while(((uint16_t)(I2C2->SR1)&(uint16_t)(0x0002))!=0x0002);//??????????
//while(((uint16_t)(I2C2->SR2)&(uint16_t)(0x0003))!=0x0003);
while(RxCounter!=BUFFER_SIZE)
{
if(RxCounter==(BUFFER_SIZE-1))
{
if(I2C_GetFlagStatus(I2C2, I2C_FLAG_RXNE)==1)
{
I2C_AcknowledgeConfig(I2C2, DISABLE);
I2C_GenerateSTOP(I2C2, ENABLE);
}
}
//EV7
while(!(I2C_CheckEvent(I2C2,I2C_EVENT_MASTER_BYTE_RECEIVED)));
//while(((uint16_t)(I2C2->SR1)&(uint16_t)(0x0040))!=0x0040);
//while(((uint16_t)(I2C2->SR2)&(uint16_t)(0x0003))!=0x0003);
RxBuffer[RxCounter++] = I2C_ReceiveData(I2C2);
}
I2C_GenerateSTOP(I2C2, ENABLE);
I2C_AcknowledgeConfig(I2C2, ENABLE);
RxCounter=0;
}
从机发送n个字节:
void I2C_ByteWrite()
{
while(((uint16_t)(I2C2->SR1)&(uint16_t)(0x0002))!=0x0002);//ADDR=1 receive address matched
while(((uint16_t)(I2C2->SR2)&(uint16_t)(0x0006))!=0x0006);//BUSY=1+MSL=0+TRA=1
I2C_SendData(I2C2,TxBuffer[TxCounter++]);
while(TxCounter!=BUFFER_SIZE)
{
while(((uint16_t)(I2C2->SR1)&(uint16_t)(0x0080))!=0x0080);//DRΪ¿ÕʱΪ1£¬Ð´ÈëDRÇå³ý¸Ãλ
I2C_SendData(I2C2,TxBuffer[TxCounter++]);
}
while(((uint16_t)(I2C2->SR1)&(uint16_t)(0x0010))!=0x0010);
TxCounter=0;
} |