const uint8_t AO_PIN = A0;
const float GAMMA = 0.7;
// 照度が 10[lx] の時の LDR の抵抗
const float RL10 = 50;
void setup() {
Serial.begin(9600);
}
float convertToLux(uint16_t analogValue) {
// analogValue (0 ~ 1023) を
// (0.0 ~ 5.0) に変換
float voltage = analogValue / 1024. * 5;
/*
LDR の抵抗値
voltage
resistance = ------------------
( Vcc - voltage )
(---------------)
( 1000 )
を変形
Vcc = 5[V]
*/
float resistance = 2000 * voltage / (1 - voltage / 5);
/*
照度
GAMMA は, 10[Lux] と 100[Lux] の間において,
10[Lux], 100[Lux] の時の抵抗をそれぞれ R10, R100 として
( R10 )
log (------)
( R100 )
--------------
( 100 )
log (-----)
( 10 )
のように与えられる (log の底は 10)
参考: https://www.digikey.jp/en/htmldatasheets/production/5858660/0/0/1/02-ldr2
ここで, 照度が lux の時の抵抗を resistance とし,
10[Lux] と lux[Lux] の間における GAMMA の値を求めると,
( R10 )
log (------------)
( resistance )
-------------------
( lux )
log (-----)
( 10 )
となる
以下の式は, 上記の式を lux について解いたものである
*/
float lux = pow((RL10 * 1000 * pow(10.0, GAMMA) / resistance), (1 / GAMMA));
return lux;
}
void loop() {
uint16_t analogValue = analogRead(AO_PIN);
float lux = convertToLux(analogValue);
if(isfinite(lux)) {
Serial.print("明るさ: ");
Serial.print(lux);
Serial.println(" [lx]");
} else {
// lux が inf (無限) のとき
Serial.println("明るすぎるため, 計測できません");
}
delay(1000);
}