BH1750是一种用于光照强度检测的传感器,并以I2C接口的方式来工作,为了便于程序移植这里是以GPIO口模拟I2C的方式来驱动该传感器。 SCL--- PE.4 SDA--- PA.0 故使这2个引脚输出高低电平的语句定义为: #define SCL_Set() rt_pin_write(pin_clk, PIN_HIGH) #define SCL_Clr() rt_pin_write(pin_clk, PIN_LOW) #define SDA_Set() rt_pin_write(pin_dat, PIN_HIGH) #define SDA_Clr() rt_pin_write(pin_dat, PIN_LOW) 而控制数据引脚输入输出模式的语句为: #define IIC_INPUT_MODE_SET() rt_pin_mode(pin_dat, PIN_MODE_INPUT_PULLUP) #define IIC_OUTPUT_MODE_SET() rt_pin_mode(pin_dat, PIN_MODE_OUTPUT) 控制数据引脚读取电平状态的语句定义为: #define IIC_SDA_IN rt_pin_read(pin_dat) 为了能直观地观察检测数据,这里是有OLED屏来显示检测值,相应的实物连接及检测效果图如下:
实物连接及检测效果图 BH1750的初始化函数为:
- void BH1750_Init(void)
- {
- rt_pin_mode(pin_dat, PIN_MODE_OUTPUT);
- rt_pin_mode(pin_clk, PIN_MODE_OUTPUT);
- }
复制代码
BH1750的起始与停止函数为:
- void BH1750_Start()
- {
- IIC_OUTPUT_MODE_SET();
- SDA_Set();
- SCL_Set();
- rt_hw_us_delay(5);
- SDA_Clr();
- rt_hw_us_delay(5);
- SCL_Clr();
- }
复制代码
- void BH1750_Stop()
- {
- IIC_OUTPUT_MODE_SET();
- SDA_Clr();
- SCL_Set();
- rt_hw_us_delay(5);
- SDA_Set();
- rt_hw_us_delay(5);
- }
复制代码
BH1750发送与接收字节数据的函数为:
- void BH1750_SendByte(char data)
- {
- char i;
- IIC_OUTPUT_MODE_SET();
- SCL_Clr();
- rt_hw_us_delay(2);
- for (i=0;i<8;i++)
- {
- if(data & 0x80) SDA_Set();
- else SDA_Clr();
- data <<= 1;
- rt_hw_us_delay(2);
- SCL_Set();
- rt_hw_us_delay(2);
- SCL_Clr();
- rt_hw_us_delay(2);
- }
- }
复制代码
- char BH1750_RecvByte()
- {
- char i;
- char data = 0;
- IIC_INPUT_MODE_SET();
- for (i=0;i<8;i++)
- {
- SCL_Clr();
- rt_hw_us_delay(2);
- SCL_Set();
- data <<= 1;
- SCL_Set();
- if(IIC_SDA_IN==1) data |= 0x01;
- rt_hw_us_delay(1);
- }
- SCL_Clr();
- return data;
- }
复制代码
读取光照强度检测值的函数为:
- void Get_Sunlight_Value()
- {
- int dis_data=0;
- float temp;
- char i=0;
- unsigned int sd;
- Single_Write_BH1750(0x01);
- Single_Write_BH1750(0x10);
- rt_thread_mdelay(180);
- Multiple_Read_BH1750();
- for(i=0;i<3;i++) dis_data=BUF[0];
- dis_data=(dis_data <<8)+BUF[1];
- temp=(float)dis_data/1.2;
- sd=temp;
- OLED_ShowString(0,2,"Sunlight= lx",16);
- OLED_ShowNum(72,2,sd,5,16);
- }
复制代码
实现显示效果的主程序为:
- int main(void)
- {
- pin = rt_pin_get("PE.1");
- rt_pin_mode(pin, PIN_MODE_OUTPUT);
- pin_clk = rt_pin_get("PE.4");
- pin_dat = rt_pin_get("PA.0");
- pin_scl = rt_pin_get("PE.3");
- pin_sda = rt_pin_get("PE.2");
- rt_pin_mode(pin_dat, PIN_MODE_OUTPUT);
- rt_pin_mode(pin_clk, PIN_MODE_OUTPUT);
- rt_pin_mode(pin_scl, PIN_MODE_OUTPUT);
- rt_pin_mode(pin_sda, PIN_MODE_OUTPUT);
- OLED_Init();
- OLED_Clear();
- OLED_ShowString(0,0,"AB32VG1 RISC-V",16);
- OLED_ShowString(0,2,"OLED & BH1750",16);
- rt_thread_mdelay(2000);
- OLED_Clear();
- while(1)
- {
- Get_Sunlight_Value();
- rt_pin_write(pin, PIN_LOW);
- rt_thread_mdelay(500);
- rt_pin_write(pin, PIN_HIGH);
- rt_thread_mdelay(500);
- }
- }
复制代码
|