ESP32笔记, 利用BH1745测量色温与亮度, 及用U8G2库显示。
#include <Arduino.h>
#include <BH1745NUC.h>
#include <U8g2lib.h>
#define SDA 23
#define SCL 18
float h,s,v;
BH1745NUC bh1745nuc = BH1745NUC(SDA,SCL);
U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ SCL, /* data=*/ SDA);
void setup()
{//bh1745
Serial.begin(115200);
Wire.begin();
//U8g2
u8g2.begin();
u8g2.enableUTF8Print();
if (!bh1745nuc.begin())
{
Serial.println("BH1745NUC not detected or failed to initialize!");
while (1) { ;; }
}
// optional: configure non-default I2C address:
// bh1745nuc.begin(0x39)
// optional: set measurement time
// bh1745nuc.setMeasurementTime(bh1745nuc.Time160ms);
// optional: set gain
// bh1745nuc.setGain(bh1745nuc.Gain1X);
// optional: start or stop measurement (power down mode)
// bh1745nuc.startMeasurement();
// bh1745nuc.stopMeasurement();
}
void loop()
{
if (!bh1745nuc.read())
{
Serial.println("BH1745NUC: failed to read measurement values!");
delay(500);
return;
}
// Serial.printf("Red: %hu, Green: %hu, Blue: %hu, Clear: %hu\n", bh1745nuc.red, bh1745nuc.green, bh1745nuc.blue, bh1745nuc.clear);
double cct=bh1745nuc.Calculate_Color_Temperature(bh1745nuc.red, bh1745nuc.green, bh1745nuc.blue);
// Serial.printf("色温是:%f\n",cct);
double brightNess=bh1745nuc.Calculate_lightness(bh1745nuc.red, bh1745nuc.green, bh1745nuc.blue);
// Serial.printf("亮度是:%f\n",brightNess);
bh1745nuc.rgb_to_hsv(&h,&s,&v,bh1745nuc.red,bh1745nuc.green,bh1745nuc.blue);
u8g2.setFont(u8g2_font_zzy); // use chinese2 for all the glyphs of "你好世界"
//u8g2.setFont(u8g2_font_b10_t_japanese1); // all the glyphs of "こんにちは世界" are already included in japanese1: Lerning Level 1-6
u8g2.setFontDirection(0);
u8g2.firstPage();
do {
u8g2.setCursor(0, 15);
u8g2.print("照度测试仪");
u8g2.setCursor(0, 40);
u8g2.print("照度(lm):"+String(brightNess));
//u8g2.print("こんにちは世界"); // Japanese "Hello World"
// u8g2.print("H:"+String(h)+"S:"+String(s)+"V:"+String(v));
u8g2.setCursor(0, 62);
u8g2.print("色温(K):"+String(cct));
} while ( u8g2.nextPage() );
delay(100);
}