STM8 I2C从机

宏定义

#define SLAVE_ADDR 0x51
#define I2CSPEED 400000 //i2c速度

stm8l051 i2c从机初始化

    /* I2C  clock Enable*/
    CLK_PeripheralClockConfig(CLK_Peripheral_I2C1, ENABLE);

    I2C_DeInit(I2C1);
    I2C_Init(I2C1, I2CSPEED, SLAVE_ADDR ,
        I2C_Mode_I2C, I2C_DutyCycle_2,
        I2C_Ack_Enable, I2C_AcknowledgedAddress_7bit);
    /* Enable Error Interrupt*/
    I2C_ITConfig(I2C1, (I2C_IT_TypeDef)(I2C_IT_ERR | I2C_IT_EVT | I2C_IT_BUF), ENABLE);

stm8s103 i2c从机初始化

I2C_Init(I2CSPEED, SLAVE_ADDR , I2C_DUTYCYCLE_2, I2C_ACK_CURR, I2C_ADDMODE_7BIT, I2CCLK);//I2C初始化
I2C_ITConfig(I2C1, (I2C_IT_TypeDef)(I2C_IT_ERR | I2C_IT_EVT | I2C_IT_BUF), ENABLE);

中断处理

{
  /* In order to detect unexpected events during development,
     it is recommended to set a breakpoint on the following instruction.
  */
//接收发送
    Uchar temp = 0;
    if (I2C1->SR1&0x02)//地址已经匹配(读SR1,SR3清除该位)
    {
        temp = I2C1->SR3&0x07;
    }
    else if ((I2C1->SR1&0x84)&&(I2C1->SR3&0x04))//数据字节传送完
    {
        temp = 0xA5;    //假设这里发送0xA5
        I2C1->DR = temp;
    }
    else if ((I2C1->SR1&0x40)&&(0 == (I2C1->SR3&0x04)))//接收时数据寄存器
    {
        temp = I2C1->DR;    //读取数据寄存器

    }
    else if (I2C1->SR1&0x10)//检测到停止位
    {
        I2C1->CR2 = I2C1->CR2;//清除停止位
    }
    //错误处理
    if (I2C1->SR2&0x01)//总线错误
    {
        I2C1->SR2 &= ~0x01;//清零
    }
    else if(I2C1->SR2&0x02)//仲裁失败
    {
        I2C1->SR2 &= ~0x02;//清零
    }
    else if(I2C1->SR2&0x04)//应答失败
    {
        I2C1->SR2 &= ~0x04;//清零
    }
    else if(I2C1->SR2&0x08)//上溢、下溢
    {
        I2C1->SR2 &= ~0x08;//清零
    }
    return;
}

以上程序已长时间测试未发生过任何异常,所以他们说stm8的I2C存在硬件BUG应该是谣言。

你可能感兴趣的:(STM8)