Created
August 24, 2018 16:37
-
-
Save likersacademia/b63c404a684740849e88141f5c0e3c8d 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
// ある程度明るいと車が前進、障害物を避ける。暗いと停止。 | |
#include <Servo.h> //サーボモーターを動かす関数を用意します | |
#define cdsPin 1 | |
#define moterPinR 2 | |
#define moterPinL 3 | |
#define echoPin 11 | |
#define trigPin 12 | |
double Duration = 0; //受信した間隔 | |
double Distance = 0; //距離 | |
Servo myservo1; | |
Servo myservo2; | |
void setup() { | |
pinMode(cdsPin,INPUT); | |
pinMode(echoPin,INPUT); | |
pinMode(trigPin,OUTPUT); | |
myservo1.attach(moterPinR,700,2300); | |
myservo2.attach(moterPinL,700,2300); | |
Serial.begin(9600); | |
} | |
void loop() { | |
float cds_ad=analogRead(cdsPin); | |
float cds_v=cds_ad * 5 /1023; | |
float lux = 10000 * cds_v/ (5 - cds_v) / 1000; | |
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"); | |
Serial.print("lux:"); | |
Serial.println(lux); | |
//時計回り(when 1450~700 µsec) 逆時計回り(when 1550~2300 µsec) 1500に近い方が回転がおそくなる | |
if(lux>20){ | |
if(Distance>15){ | |
myservo1.write(700); //700はモーターが一番早く回る数値です | |
myservo2.write(2300); | |
}else{ | |
myservo1.write(2300); //1500はモーターが止まる数値です | |
myservo2.write(700); | |
delay(1000); | |
myservo1.write(700); //1500はモーターが止まる数値です | |
myservo2.write(1600); | |
delay(3000); | |
} | |
}else{ | |
myservo1.write(1500); //1500はモーターが止まる数値です | |
myservo2.write(1500); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment