51单片机BH1750测试光照强度显示在LCD1602上
时间: 2024-04-08 15:28:54 浏览: 95
您好!您可以使用51单片机和BH1750光照强度传感器来测试并将结果显示在LCD1602上。下面是一个简单的示例代码:
```C
#include <reg51.h>
#include <intrins.h>
#define LCD1602_DATAPORT P0
sbit LCD1602_RS = P2^0;
sbit LCD1602_RW = P2^1;
sbit LCD1602_E = P2^2;
sbit BH1750_SCL = P3^6;
sbit BH1750_SDA = P3^7;
void delay_ms(unsigned int ms) {
unsigned int i, j;
for(i = 0; i < ms; i++) {
for(j = 0; j < 112; j++);
}
}
void LCD1602_WriteCommand(unsigned char cmd) {
LCD1602_RS = 0;
LCD1602_RW = 0;
LCD1602_E = 0;
LCD1602_DATAPORT = cmd;
_nop_();
_nop_();
LCD1602_E = 1;
_nop_();
_nop_();
LCD1602_E = 0;
delay_ms(1);
}
void LCD1602_WriteData(unsigned char dat) {
LCD1602_RS = 1;
LCD1602_RW = 0;
LCD1602_E = 0;
LCD1602_DATAPORT = dat;
_nop_();
_nop_();
LCD1602_E = 1;
_nop_();
_nop_();
LCD1602_E = 0;
delay_ms(1);
}
void BH1750_Start() {
BH1750_SDA = 1;
delay_ms(1);
BH1750_SCL = 1;
delay_ms(1);
BH1750_SDA = 0;
delay_ms(1);
BH1750_SCL = 0;
delay_ms(1);
}
void BH1750_Stop() {
BH1750_SCL = 0;
delay_ms(1);
BH1750_SDA = 0;
delay_ms(1);
BH1750_SCL = 1;
delay_ms(1);
BH1750_SDA = 1;
delay_ms(1);
}
bit BH1750_WaitAck() {
unsigned char ucErrTime = 0;
BH1750_SDA = 1;
_nop_();
BH1750_SCL = 1;
_nop_();
while (BH1750_SDA) {
ucErrTime++;
if (ucErrTime > 250) {
BH1750_Stop();
return 1;
}
}
BH1750_SCL = 0;
return 0;
}
void BH1750_SendByte(unsigned char txd) {
unsigned char t;
BH1750_SCL = 0;
for(t = 0; t < 8; t++) {
BH1750_SDA = (txd & 0x80) >> 7;
txd <<= 1;
BH1750_SCL = 1;
_nop_();
BH1750_SCL = 0;
_nop_();
}
}
unsigned int BH1750_ReadData() {
unsigned int i, dat;
BH1750_SDA = 1;
dat = 0;
for(i = 0; i < 16; i++) {
BH1750_SCL = 0;
_nop_();
BH1750_SCL = 1;
_nop_();
dat <<= 1;
if (BH1750_SDA) {
dat++;
}
}
return dat;
}
void LCD1602_Init() {
delay_ms(20);
LCD1602_WriteCommand(0x38);
delay_ms(5);
LCD1602_WriteCommand(0x38);
delay_ms(5);
LCD1602_WriteCommand(0x38);
delay_ms(5);
LCD1602_WriteCommand(0x38);
delay_ms(5);
LCD1602_WriteCommand(0x08);
delay_ms(5);
LCD1602_WriteCommand(0x01);
delay_ms(5);
LCD1602_WriteCommand(0x06);
delay_ms(5);
LCD1602_WriteCommand(0x0C);
delay_ms(5);
}
void main() {
unsigned int lux;
unsigned char str[16];
LCD1602_Init();
while(1) {
BH1750_Start();
BH1750_SendByte(0x23);
if (BH1750_WaitAck() == 1) {
continue;
}
BH1750_Stop();
delay_ms(180);
BH1750_Start();
BH1750_SendByte(0x23 | 0x01);
if (BH1750_WaitAck() == 1) {
continue;
}
lux = BH1750_ReadData();
BH1750_Stop();
sprintf(str, "Light: %d lx", lux);
LCD1602_WriteCommand(0x80);
for(int i = 0; i < 16; i++) {
if (str[i] == '\0') {
break;
}
LCD1602_WriteData(str[i]);
delay_ms(1);
}
delay_ms(1000);
}
}
```
请注意,该代码仅提供了基本的示例,您可能需要根据实际情况进行修改和适配。此外,确保您的开发环境已正确配置并连接了BH1750传感器和LCD1602显示屏。祝您成功完成项目!如果您还有其他问题,请随时提问。
阅读全文