Last active
August 29, 2018 02:14
-
-
Save likersacademia/1b459060114ff10aea2335e62aa20a62 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 距離20㎝以下でなおかつ電気を消すとブザーが鳴る | |
#define cdsPin 1 //光センサーが1番ピンに入っています。 | |
#define echoPin 11 //距離センサーの「echo」が11番ピン | |
#define trigPin 12 //距離センサーの「trig」が12番ピン | |
#define buzzerPin 2 //ブザーが2番ピン | |
double Duration = 0; //受信した間隔 | |
double Distance = 0; //距離 | |
void setup() { | |
Serial.begin(9600); | |
pinMode(echoPin,INPUT); | |
pinMode(trigPin,OUTPUT); | |
pinMode(cdsPin, INPUT); | |
pinMode(buzzerPin, 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(buzzerPin, HIGH); //HIGH:鳴る LOW:鳴らない | |
delay(200); | |
} else { | |
digitalWrite(buzzerPin, LOW); //HIGH:鳴る LOW:鳴らない | |
delay(200); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment