Skip to content

Instantly share code, notes, and snippets.

@likersacademia
Created October 15, 2018 04:26
Show Gist options
  • Save likersacademia/2a71e15e6b6e4e6b1cbb97b5f75d1a04 to your computer and use it in GitHub Desktop.
Save likersacademia/2a71e15e6b6e4e6b1cbb97b5f75d1a04 to your computer and use it in GitHub Desktop.
// はじめライトは消えていて、距離20㎝以下でなおかつ電気を消すとライトがつく。
#define cdsPin 1 //光センサーが1番ピンに入っています。
#define echoPin 11 //距離センサーの「echo」が11番ピン
#define trigPin 12 //距離センサーの「trig」が12番ピン
#define ledPin 2 //LEDが2番ピン
double Duration = 0; //受信した間隔
double Distance = 0; //距離
void setup() {
Serial.begin(9600);
pinMode(echoPin,INPUT);
pinMode(trigPin,OUTPUT);
pinMode(cdsPin, INPUT);
pinMode(ledPin, OUTPUT);
}
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH); //超音波を出力
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
Duration = pulseIn(echoPin, HIGH); //センサからの入力
// R1のAD値を取得
float cds_ad = analogRead(cdsPin);
// AD値を電圧値に変換
float cds_v = cds_ad * 5 / 1023;
// 電圧値より、Lux計算
float lux = 10000 * cds_v / (5 - cds_v) / 1000;
Serial.print(lux);
Serial.println(" Lux ");
if (Duration > 0) {
Duration = Duration/2; //往復距離を半分
Distance = Duration*340*100/1000000; //音速を340m/sに設定
Serial.print("Distance:");
Serial.print(Distance);
Serial.println("cm");
}
if (Distance < 20 && lux < 20) { //Distance<20(20cmより小さい)、lux < 20(20luxより小さい)→<、>と数値の変更ができます。
digitalWrite(ledPin, HIGH); //HIGH:光る LOW:光らない(LEDのこと)
delay(200);
} else {
digitalWrite(ledPin, LOW); //HIGH:光る LOW:光らない(LEDのこと)
delay(200);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment