Skip to content

Instantly share code, notes, and snippets.

@likersacademia
Last active August 29, 2018 01:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save likersacademia/72794a8d4ad63f7ccb18b40a7c440e7a to your computer and use it in GitHub Desktop.
Save likersacademia/72794a8d4ad63f7ccb18b40a7c440e7a to your computer and use it in GitHub Desktop.
//10センチよりちかくなったら、遅く回転していたモーターが回るのをやめ、明かりがつくプログラム
#include <Servo.h> //サーボモーターを動かす関数を用意します
#define echoPin 11 //5を11に変更
#define trigPin 12 //6を12に変更。この2つで、距離センサーの準備をします。
#define cdsPin 1 //スイッチの文章を消して、光センサーの文章に変えます。このとき、数値は1番ピンにさしたので1になります。
#define moterPin 3 //これは、このままです。
#define ledPin 2 //ブザーをLEDに変更します。ピン番号はそのまま2番です。
double Duration = 0; //距離センサーを使うのでこの文章が必要です。
double Distance = 0; //距離センサーを使うのでこの文章が必要です。
Servo myservo; //モーターを使うのでこの文章が必要です。また下にあった文章はスイッチのものですので、消しましょう。
void setup() {
Serial.begin(9600);
pinMode(echoPin,INPUT); //距離センサーをいれるときは、この文章をいれます。
pinMode(trigPin,OUTPUT); //距離センサーをいれるときは、この文章をいれます。
pinMode(cdsPin, INPUT); //光センサーですので、この文章をいれます。スイッチのものは消しましょう。
myservo.attach(moterPin,700,2300); //モーターをいれるときは、この文章をいれます。
pinMode(ledPin, OUTPUT); //LEDですので、この文章をいれます。ブザーのものは消しましょう。
}
void loop() {
//距離センサー
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH); //超音波を出力
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
Duration = pulseIn(echoPin, HIGH); //センサからの入力
if (Duration > 0) {
Duration = Duration/2; //往復距離を半分
Distance = Duration*340*100/1000000; //音速を340m/sに設定
Serial.print("Distance:");
Serial.print(Distance);
Serial.println("cm");
}
//ここまでです。このあとのスイッチの情報は消して光センサーの情報を追加します。
// 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 (lux > 20) {
Serial.println("High lux");
delay(2000);
} else {
Serial.println("Low lux");
delay(2000);
}
//・・・ここまでが光センサーです。
if(Distance < 10 && lux < 20) //Distance(距離)<10センチ &&(あと)lux < 20 光の強さが20より小さいです。10センチより近くて、暗かったら何かが起こる仕組みの命令文に変更しましょう。
{
myservo.write(1500); //上の条件になったとき、モーターは止まるので、数値は700(早い回転)を1500(止まる)に変更します。
digitalWrite(ledPin, HIGH); //光がつく(ブザーではなく、LEDのものに変えます。)
delay(200);
}
else //もしそれ以外であれば、下の動作が起きます。
{
myservo.write(1350); //700は、早いので、それ以外の数値にかえましょう。何度も調整してください!
digitalWrite(ledPin, LOW); //光がとまる。明かりがつくということは、それ以外のときは、ついてなかったということ
delay(200);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment