STM32的IIC(模拟)读写AT24c02
时间: 2023-11-08 16:06:02 浏览: 195
stm32实现IIC控制24c08进行数据读写.rar_24c02_STM32 at24C08_STM32F103_i2c_po
5星 · 资源好评率100%
以下是STM32的IIC(模拟)读写AT24c02的代码:
```
#include "stm32f10x.h"
#include "delay.h"
#define IIC_SCL_H GPIOB->BSRR = GPIO_Pin_10
#define IIC_SCL_L GPIOB->BRR = GPIO_Pin_10
#define IIC_SDA_H GPIOB->BSRR = GPIO_Pin_11
#define IIC_SDA_L GPIOB->BRR = GPIO_Pin_11
#define IIC_SDA GPIOB->IDR & GPIO_Pin_11
void IIC_Start()
{
IIC_SDA_H;
IIC_SCL_H;
delay_us(5);
IIC_SDA_L;
delay_us(5);
IIC_SCL_L;
}
void IIC_Stop()
{
IIC_SDA_L;
IIC_SCL_H;
delay_us(5);
IIC_SDA_H;
delay_us(5);
}
void IIC_Ack()
{
IIC_SDA_L;
delay_us(5);
IIC_SCL_H;
delay_us(5);
IIC_SCL_L;
IIC_SDA_H;
}
void IIC_NoAck()
{
IIC_SDA_H;
delay_us(5);
IIC_SCL_H;
delay_us(5);
IIC_SCL_L;
}
uint8_t IIC_WaitAck()
{
uint8_t ucErrTime = 0;
IIC_SDA_H;
delay_us(1);
IIC_SCL_H;
delay_us(1);
while (IIC_SDA)
{
ucErrTime++;
if (ucErrTime > 250)
{
IIC_Stop();
return 1;
}
}
IIC_SCL_L;
return 0;
}
void IIC_SendByte(uint8_t ucByte)
{
uint8_t i;
for (i = 0; i < 8; i++)
{
if ((ucByte << i) & 0x80)
{
IIC_SDA_H;
}
else
{
IIC_SDA_L;
}
delay_us(1);
IIC_SCL_H;
delay_us(1);
IIC_SCL_L;
}
}
uint8_t IIC_ReadByte()
{
uint8_t i, ucByte = 0;
IIC_SDA_H;
for (i = 0; i < 8; i++)
{
ucByte <<= 1;
IIC_SCL_H;
delay_us(1);
if (IIC_SDA)
{
ucByte |= 0x01;
}
IIC_SCL_L;
delay_us(1);
}
return ucByte;
}
void IIC_Init()
{
GPIO_InitTypeDef GPIO_InitStruct;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_10 | GPIO_Pin_11;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_Out_OD;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStruct);
IIC_SDA_H;
IIC_SCL_H;
}
void AT24C02_WriteByte(uint8_t ucAddr, uint8_t ucData)
{
IIC_Start();
IIC_SendByte(0xa0);
IIC_WaitAck();
IIC_SendByte(ucAddr);
IIC_WaitAck();
IIC_SendByte(ucData);
IIC_WaitAck();
IIC_Stop();
delay_ms(10);
}
uint8_t AT24C02_ReadByte(uint8_t ucAddr)
{
uint8_t ucData;
IIC_Start();
IIC_SendByte(0xa0);
IIC_WaitAck();
IIC_SendByte(ucAddr);
IIC_WaitAck();
IIC_Start();
IIC_SendByte(0xa1);
IIC_WaitAck();
ucData = IIC_ReadByte();
IIC_NoAck();
IIC_Stop();
return ucData;
}
int main(void)
{
uint8_t ucData;
IIC_Init();
AT24C02_WriteByte(0x00, 0x55);
ucData = AT24C02_ReadByte(0x00);
while (1);
}
```
阅读全文