ESP32-WROOM-32 & BH1750-获取环境亮度并调节屏幕亮度
一、电路连接
二、烧录测试程序
#include <Wire.h>
#include <BH1750.h>
BH1750 lightMeter;
void setup(){
Serial.begin(9600);
// Initialize the I2C bus (BH1750 library doesn't do this automatically)
// On esp8266 devices you can select SCL and SDA pins using Wire.begin(D4, D3);
Wire.begin();
lightMeter.begin();
Serial.println(F("BH1750 Test"));
}
void loop() {
float lux = lightMeter.readLightLevel();
Serial.print("Light: ");
Serial.print(lux);
Serial.println(" lx");
delay(1000);
}
对于 ESP32,根据您使用的是什么板,SDA 和 SCL 默认引脚可能不同。如果那是 ESP32 WROOM 开发套件,那么默认情况下,您的 SDA 引脚为 21,SCL 引脚为 22。或者您可以简单地使用:
Wire.setPins(, );
并将您使用的任何引脚号替换为 SDA 和 SCL。您只需在 Wire.begin() 命令之前执行此操作。
三、通过蓝牙串口将环境亮度数据传给pc
#include <Wire.h>
#include <BH1750.h>
#include <Arduino.h>
#include "BluetoothSerial.h"
#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif
BH1750 lightMeter;
BluetoothSerial SerialBT;
void setup(){
pinMode(LED_BUILTIN, OUTPUT);
SerialBT.begin("ESP32test"); //Bluetooth device name
Serial.begin(115200);
// Initialize the I2C bus (BH1750 library doesn't do this automatically)
// On esp8266 devices you can select SCL and SDA pins using Wire.begin(D4, D3);
Wire.begin();
lightMeter.begin();
Serial.println(F("BH1750 Test"));
}
void loop() {
digitalWrite(LED_BUILTIN, HIGH);
float lux = lightMeter.readLightLevel();
while (SerialBT.available() > 0){
delay(10);
}
SerialBT.println(lux);
Serial.print("Light: ");
Serial.print(lux);
Serial.println(" lx");
digitalWrite(LED_BUILTIN, LOW);
delay(100);
}
四、pc端python接收
# coding=gbk
import serial
import time
while True:
ser = serial.Serial('com12', 115200, parity='E', stopbits=1, bytesize=8, timeout=0.5)
print('光照强度:' + ser.readline().decode('gbk'))
time.sleep(1)
ser.close()
五、python修改屏幕亮度(vga不支持)
# coding=gbk
import serial
import time
import screen_brightness_control as sbc
while True:
ser = serial.Serial('com12', 115200, parity='E', stopbits=1, bytesize=8, timeout=0.5)
print('光照强度:' + ser.readline().decode('gbk'))
sbc.set_brightness(float(ser.readline().decode('gbk'))/5) #亮度调节,这颗传感器的分辨率范围为(0-54612.5)
time.sleep(1)
ser.close()
库链接