STM32 IIC读取AT24C02
扫描二维码
随时随地手机看文章
1、数量:I2C1与I2C2
2、时钟: RCC_APB1PeriphClockCmd(RCC_APB1Periph_I2C1 |RCC_APB1Periph_I2C2,ENABLE);
3、IO配置为开漏输出,在输入时亦可读取,此处使用功能复用。
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB | RCC_APB2Periph_AFIO,ENABLE );
RCC_APB1PeriphClockCmd(RCC_APB1Periph_I2C1,ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_OD;
GPIO_Init(GPIOB, &GPIO_InitStructure);
4、IIC本身配置
I2C_InitStructure.I2C_Mode = I2C_Mode_I2C ; //配置为普通IIC模式
I2C_InitStructure.I2C_DutyCycle = I2C_DutyCycle_2;
I2C_InitStructure.I2C_OwnAddress1 = 0x0a; //自身设备地址
I2C_InitStructure.I2C_Ack = I2C_Ack_Enable; //使能自动应答
I2C_InitStructure.I2C_AcknowledgedAddress = I2C_AcknowledgedAddress_7bit;
I2C_InitStructure.I2C_ClockSpeed = 5000; //40K的速度?
I2C_Init(I2C1, &I2C_InitStructure);
I2C_Cmd(I2C1,ENABLE);
I2C_AcknowledgeConfig(I2C1, ENABLE);
5、IIC读取一个字节:生成一个起始信号-》发送命令码-》等待信号-》发送地址-》发送起始信号-》发送读取命令-》接收数据-》发送发送终止信号-》读取寄存器接收值 么一步都有应答信号,是从设备发送的一个低信号。
vu8 IIC_Read(vu8 addr)
{
vu8 dataValue;
while(I2C_GetFlagStatus(I2C1,I2C_FLAG_BUSY));
I2C_GenerateSTART(I2C1,ENABLE);//起始信号
while(!I2C_CheckEvent(I2C1,I2C_EVENT_MASTER_MODE_SELECT));
I2C_Send7bitAddress(I2C1,ATMADDR,I2C_Direction_Transmitter);//发送设备地址+写信号
while(!I2C_CheckEvent(I2C1,I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED));//
I2C_Cmd(I2C1,ENABLE);
I2C_SendData(I2C1,addr);//发送存储单元地址,从0开始
while(!I2C_CheckEvent(I2C1,I2C_EVENT_MASTER_BYTE_TRANSMITTED));
I2C_GenerateSTART(I2C1,ENABLE);//起始信号
while(!I2C_CheckEvent(I2C1,I2C_EVENT_MASTER_MODE_SELECT));
I2C_Send7bitAddress(I2C1,ATMADDR,I2C_Direction_Receiver);//发送设备地址+读信号
while(!I2C_CheckEvent(I2C1,I2C_EVENT_MASTER_RECEIVER_MODE_SELECTED));
I2C_AcknowledgeConfig(I2C1,DISABLE);
I2C_GenerateSTOP(I2C1,ENABLE);
while(!(I2C_CheckEvent(I2C1,I2C_EVENT_MASTER_BYTE_RECEIVED)));
dataValue=I2C_ReceiveData(I2C1);//读出寄存器数据
return dataValue;
}
6、写一个字节:产生起始信号-》发送设备号+指令-》发送地址-》产生起始信号-》读取数据-》产生结束信号
void IIC_Write(vu8 addr,vu8 dataValue)
{
I2C_GenerateSTART(I2C1,ENABLE);
while(!I2C_CheckEvent(I2C1,I2C_EVENT_MASTER_MODE_SELECT));
I2C_Send7bitAddress(I2C1,ATMADDR,I2C_Direction_Transmitter);
while(!I2C_CheckEvent(I2C1,I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED));
I2C_SendData(I2C1,addr);
while(!I2C_CheckEvent(I2C1,I2C_EVENT_MASTER_BYTE_TRANSMITTED));
I2C_SendData(I2C1,dataValue);
while(!I2C_CheckEvent(I2C1,I2C_EVENT_MASTER_BYTE_TRANSMITTED));
I2C_GenerateSTOP(I2C1,ENABLE);
}
7、AT24C02相关
2K大小:256*8bits 也就是256页,每页8个bits
地址从0x00开始到0xff个字节