您现在的位置是:首页 >技术交流 >IIC例程-501-stm32网站首页技术交流
IIC例程-501-stm32
#include “bh1750.h”
static void BH1750_SDA_IN(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);
///<PC12.
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOC, &GPIO_InitStructure);
}
static void BH1750_SDA_OUT(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);
///<PC12.
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_OD;
GPIO_Init(GPIOC, &GPIO_InitStructure);
}
//开始信号
static void IIC_Start(void)
{
BH1750_SDA_OUT();
BH1750_IIC_SDA = 1;
BH1750_IIC_SCL = 1;
delay_us(5);
BH1750_IIC_SDA = 0; ///<START:when CLK is high,DATA change form high to low.
delay_us(5);
BH1750_IIC_SCL = 0;
}
//停止信号
static void IIC_Stop(void)
{
BH1750_SDA_OUT();
BH1750_IIC_SCL = 0;
BH1750_IIC_SDA = 0; ///<STOP:when CLK is high DATA change form low to high.
delay_us(4);
BH1750_IIC_SCL=1;
BH1750_IIC_SDA=1; ///<·¢ËÍI2C×ÜÏß½áÊøÐźÅ.
delay_us(4);
}
//等待应该信号
//return 0 应该成功
static uint8_t IIC_Wait_Ack(void)
{
uint8_t ucErrTime=0;
BH1750_SDA_IN();
BH1750_IIC_SDA = 1;
delay_us(1);
BH1750_IIC_SCL = 1;
delay_us(1);
while(BH1750_READ_SDA)
{
ucErrTime++;
if(ucErrTime>250)
{
IIC_Stop();
return 1;
}
}
BH1750_IIC_SCL=0;
return 0;
}
//产生应答信号 —自己给个应答信号–不等待
static void IIC_Ack(void)
{
BH1750_IIC_SCL = 0;
BH1750_SDA_OUT();
BH1750_IIC_SDA = 0;
delay_us(2);
BH1750_IIC_SCL = 1;
delay_us(2);
BH1750_IIC_SCL = 0;
}
//不产生应答信号
static void IIC_NAck(void)
{
BH1750_IIC_SCL = 0;
BH1750_SDA_OUT();
BH1750_IIC_SDA = 1;
delay_us(2);
BH1750_IIC_SCL = 1;
delay_us(2);
BH1750_IIC_SCL = 0;
}
//发送一个字节数据
//return 1 有应答 0无应答
static void IIC_Send_Byte(uint8_t txd)
{
uint8_t t = 0;
BH1750_SDA_OUT();
BH1750_IIC_SCL = 0;
for(t=0; t<8; t++)
{
if((txd&0x80)>>7)
BH1750_IIC_SDA = 1;
else
BH1750_IIC_SDA = 0;
txd<<=1;
delay_us(2);
BH1750_IIC_SCL = 1;
delay_us(2);
BH1750_IIC_SCL = 0;
delay_us(2);
}
}
//读取一个字节的 ack 是否等待应答
static uint8_t IIC_Read_Byte(uint8_t ack)
{
uint8_t i,receive = 0;
BH1750_SDA_IN();
for(i=0;i<8;i++ )
{
BH1750_IIC_SCL = 0;
delay_us(2);
BH1750_IIC_SCL = 1;
receive<<=1;
if(BH1750_READ_SDA)
receive++;
delay_us(1);
}
if (!ack)
IIC_NAck();
else
IIC_Ack();
return receive;
}
void bh_data_send(uint8_t command)
{
do
{
IIC_Start();
IIC_Send_Byte(BHAddWrite); //写器件地址
}while(IIC_Wait_Ack()); //等待应答
IIC_Send_Byte(command); //发送命了
IIC_Wait_Ack(); //等待应答
IIC_Stop(); // 停止
}
uint16_t bh_data_read(void)
{
uint16_t buf;
IIC_Start();
IIC_Send_Byte(BHAddRead); //读器件地址
IIC_Wait_Ack(); ///<µÈ´ý´Ó»úÓ¦´ð.
buf = IIC_Read_Byte(1); ///<¶ÁÈ¡Êý¾Ý.
buf = buf<<8; ///<¶ÁÈ¡²¢±£´æ¸ß°ËλÊý¾Ý.
buf += 0x00ff&IIC_Read_Byte(0); ///<¶ÁÈ¡²¢±£´æµÚ°ËλÊý¾Ý.
IIC_Stop(); ///<·¢ËÍÍ£Ö¹ÐźÅ.
return buf;
}