
部屋の明るさをパーセントで表示するシンプルな光の測定器です。光センサーが周囲を測定し、ESP32が暗い状態を0、十分に明るい状態を100として値を変換し、0.5秒ごとにコンピューターの画面に表示します。ナイトライトなどのプロジェクトでは、まずこの測定で、どの明るさになったらライトを点灯させるかを決めます。
動画
回路図

ソースコード
Arduino (C++)
1// ─────────────────────────────────────────
2// BlueGrays · bluegrays.com
3// Reading Light Intensity with the ESP32 LDR Module
4// ─────────────────────────────────────────
5// Reads the analog output (AO) of the LDR module with the 12-bit ADC and
6// converts it to a 0-100 light percentage using the calibration values.
7// The result is printed to the Serial Monitor (115200 baud) every 0.5 s.
8//
9// Pins:
10// GPIO 34 (classic ESP32) / GPIO 1 (ESP32-S2/S3) -> LDR module AO
11// LDR module VCC -> 3V3, GND -> GND
12
13#if defined(CONFIG_IDF_TARGET_ESP32S2) || defined(CONFIG_IDF_TARGET_ESP32S3)
14 const int LDR_PIN = 1; // ESP32-S2/S3: ADC1_CH0
15#else
16 // Classic ESP32 DevKit V1: ADC1_CH6, input-only. GPIO 1 clashes with Serial TX here
17 const int LDR_PIN = 34;
18#endif
19
20// Calibration: measure in your own room and enter the values here. On the LDR module the AO voltage
21// (and raw) DROPS as the light gets brighter.
22const int RAW_DARK = 4000; // Dark raw
23const int RAW_LIGHT = 100; // Light raw
24
25void setup() {
26 Serial.begin(115200);
27 analogReadResolution(12); // Force 12-bit
28 Serial.println("LDR Okuma / LDR Reading");
29 Serial.println("-----------------------------");
30}
31
32void loop() {
33 int raw = analogRead(LDR_PIN);
34 // Clip to the calibration range, dark = 0%
35 int clipped = constrain(raw, RAW_LIGHT, RAW_DARK);
36 int percent = map(clipped, RAW_DARK, RAW_LIGHT, 0, 100);
37
38 Serial.print("Raw: ");
39 Serial.print(raw);
40 Serial.print(" | Light: %");
41 Serial.println(percent);
42
43 delay(500);
44}
45
よくある質問
ESP32のADCはどのような値を返しますか?▾
ESP32のADCは12ビットで、0~4095の値を返します。Arduino Unoの0~1023とは範囲が異なるため、それに合わせてしきい値や計算を調整してください。
Wi-Fiを有効にするとアナログの読み取り値が乱れるのはなぜですか?▾
ESP32では、Wi-Fiが有効な間はADC2チャネル(GPIO 0, 2, 4, 12–15, 25–27)を使えません。アナログセンサーをADC1ピン(GPIO 32–39)に接続すると、この問題を防げます。
読み取り値は実際のルクス値ですか?▾
いいえ、このコードはルクスを計算しません。生のADC値と、設定した暗い状態・明るい状態の基準値に対する相対的な明るさの割合を表示します。LDRの応答は直線的ではなく、モデルによっても異なります。正確なルクス測定には、BH1750のような校正済みのセンサーを使います。
ESP32のADCで範囲の両端付近の測定に誤差が出るのはなぜですか?▾
ESP32のADCは、0 Vや3.3 Vに近い領域では直線的に応答しません。`analogReadMilliVolts()`は校正済みの値を返します。精度が重要な測定では、0.1–3.1 Vの範囲で使うと最も正確な結果が得られます。
