前面介绍的温度大气压传感器相近,光照强度传感器BH1750也是一种I2C接口的器件。 除了具体的功能处理不同外,其它的基本差不多。 BH1750方式与接收字节数据的函数如下:
void BH1750_SendByte(char data1)
{
char i;
OUTPUT_MODE_SET();
SCLK=0;
Delay_us(2);
for (i=0;i<8;i++)
{
if(data1&0x80) SDIN=1;
else SDIN=0;
data1 <<= 1;
SCLK=1;
Delay_us(2);
SCLK=0;
Delay_us(2);
}
}
char BH1750_RecvByte()
{
char i;
char data1 = 0;
INPUT_MODE_SET();
for (i=0;i<8;i++)
{
SCLK=0;
Delay_us(2);
SCLK=1;
data1 <<= 1;
SCLK=1;
if(SDA_IN ) data1|=0x01;
Delay_us(2);
}
SCLK=0;
return data1;
}
写入寄存器的函数为: void Single_Write_BH1750(char REG_Address)
{
BH1750_Start();
BH1750_SendByte(SlaveAddress);
BH1750_RecvACK();
BH1750_SendByte(REG_Address);
BH1750_RecvACK();
BH1750_Stop();
}
读取BH1750数据的函数为:
void Multiple_Read_BH1750()
{
BH1750_Start();
BH1750_SendByte(SlaveAddress+1);
BH1750_RecvACK();
BUF[0] = BH1750_RecvByte();
BH1750_SendACK(0);
BUF[1] = BH1750_RecvByte();
BH1750_SendACK(1);
BH1750_Stop();
Delay(5);
}
读取并显示光照强度的函数为: void Get_Sunlight_Value()
{
int dis_data=0;
float temp;
char i=0;
unsigned int sd;
Single_Write_BH1750(0x01);
Single_Write_BH1750(0x10);
Delay(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;
LCD_ShowNum(120,50,sd,5,YELLOW);
}
显示光强检测与显示的主程序为: void main(void)
{
P0CON = 0xFF;
P0PH = 0x00;
P1CON = 0x00;
P1PH = 0x00;
P2CON = 0xFF;
P2PH = 0x00;
P3CON = 0xFF;
P3PH = 0x00;
P4CON = 0xFF;
P4PH = 0x01;
P5CON = 0xFF;
P5PH = 0x00;
GPIO_Init(GPIO0, GPIO_PIN_4 | GPIO_PIN_5 |GPIO_PIN_6, GPIO_MODE_OUT_PP);
GPIO_Init(GPIO2, GPIO_PIN_2, GPIO_MODE_OUT_PP);
GPIO_Init(GPIO5, GPIO_PIN_3, GPIO_MODE_OUT_PP);
GPIO_Init(GPIO4, GPIO_PIN_2 | GPIO_PIN_3 | GPIO_PIN_4 | GPIO_PIN_5, GPIO_MODE_OUT_PP);
Delay(100);
Lcd_Init();
LCD_Clear(RED);
BACK_COLOR=RED;
LCD_Picturea();
LCD_ShowChinese(80,10,0,16,YELLOW);
LCD_ShowChinese(96,10,1,16,YELLOW);
LCD_ShowChar(112,10,':',0,YELLOW);
LCD_ShowChinese(80,30,2,16,YELLOW);
LCD_ShowChinese(96,30,3,16,YELLOW);
LCD_ShowChar(112,30,':',0,YELLOW);
LCD_ShowChinese(80,50,4,16,YELLOW);
LCD_ShowChinese(96,50,5,16,YELLOW);
LCD_ShowChar(112,50,':',0,YELLOW);
while(1)
{
Get_Sunlight_Value();
Delay(1000);
}
}
经程序的编译与下载,其运行效果如下图所示。
光强检测效果
|