stm32 i2c eeprom 24C02

电路图
1

2

相关文章:http://blog.csdn.net/zhangxuechao_/article/details/74936798

2

举例

#define i2c_scl PBout(10)
#define i2c_sda PBout(11)
#define i2c_ack PBin(11)

void I2C_init()
{
    GPIO_InitTypeDef gpio10 = 
    {
        GPIO_Pin_10,
        GPIO_Speed_50MHz,
        GPIO_Mode_Out_PP
    };

    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE); //时钟使能

    GPIO_Init(GPIOB, &gpio10);
}

void I2C_in()
{
    GPIO_InitTypeDef gpio11 = 
    {
        GPIO_Pin_11,
        GPIO_Speed_50MHz,
        GPIO_Mode_IPD
    };

    GPIO_Init(GPIOB, &gpio11);
}

void I2C_out()
{
    GPIO_InitTypeDef gpio11 = 
    {
        GPIO_Pin_11,
        GPIO_Speed_50MHz,
        GPIO_Mode_Out_PP
    };

    GPIO_Init(GPIOB, &gpio11);
}

void I2C_start()
{
    I2C_out();

    i2c_sda = 1;
    i2c_scl = 1;
    delay_us(5);
    i2c_sda = 0;
    delay_us(5);

    i2c_scl = 0;
}

void I2C_stop()
{
    I2C_out();

    i2c_sda = 0;
    i2c_scl = 1;
    delay_us(5);
    i2c_sda = 1;
    delay_us(5);

    i2c_scl = 0;
}

void I2C_ack(u8 ack)
{
    i2c_scl = 0; //必须的

    I2C_out();

    i2c_sda = ack;  
    delay_us(2);    
    i2c_scl = 1;
    delay_us(5);

    i2c_scl = 0;
}

u8 I2C_wait_ack()
{
    u8 flag = 0;

    I2C_in();

    i2c_scl = 1;
    delay_us(2);

    while(i2c_ack == 1)
    {
        flag++;
        if(flag > 250)
        {
            return 1;
        }
    }
    i2c_scl = 0;

    return 0;
}

void I2C_send_byte(u8 data)
{
    u8 i = 0;

    I2C_out();

    i2c_scl = 0;

    for(i = 0; i < 8; i++)
    {
        if((data & 0x80) > 0)
            i2c_sda = 1;
        else
            i2c_sda = 0;            
        data <<= 1;
        delay_us(2);

        i2c_scl = 1;
        delay_us(2);
        i2c_scl = 0;
        delay_us(2);
    }
}

u8 I2C_recv_byte()
{
    u8 i = 0;
    u8 data;

    I2C_in();

    for(i = 0; i < 8; i++)
    {
        i2c_scl = 0;
        delay_us(2);
        i2c_scl = 1;
        delay_us(2);
        data <<= 1;
        data |= i2c_ack;
        delay_us(2);
    }

    I2C_ack(0);

    return data;
}

void at24c02Write(u8 addr, u8 d)
{
    I2C_start();
    I2C_send_byte(0xa0);
    I2C_wait_ack();
    I2C_send_byte(addr);
    I2C_wait_ack();
    I2C_send_byte(d);
    I2C_wait_ack();
    I2C_stop();  

    delay_ms(10);
}

u8 at24c02Read(u8 addr)
{
    u8 d = 0;

    I2C_start();    
    I2C_send_byte(0xa0);
    I2C_wait_ack();
    I2C_send_byte(addr);
    I2C_wait_ack();
    I2C_start();    
    I2C_send_byte(0xa1);
    I2C_wait_ack();
    d = I2C_recv_byte();
    I2C_stop();

    return d;   
}

void at24c02Read_buf(u8 *buf, u8 addr, u16 num)
{
    u8 i = 0;

    for(i = 0; i < num; i++)
    {
        buf[i] = at24c02Read(addr + i);
    }
}

void at24c02Write_buf(u8 *buf, u8 addr, u16 num)
{
    u8 i = 0;

    for(i = 0; i < num; i++)
    {
        at24c02Write(addr + i, buf[i]);
    }
}
posted @ 2017-08-16 18:28  thomas_blog  阅读(170)  评论(0编辑  收藏  举报