Skip to content

Instantly share code, notes, and snippets.

@likersacademia
Last active August 29, 2018 06:59
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/788d79598e52c25bae6646fbe0f031af to your computer and use it in GitHub Desktop.
Save likersacademia/788d79598e52c25bae6646fbe0f031af to your computer and use it in GitHub Desktop.
// 15センチ以内だと、モーターが5秒間右回転し、3秒間左回転しLEDもつくプログラム
#include <Servo.h> //サーボモーターを動かす関数を用意します
#define moterPin 3 //モーターが3番ピン
#define echoPin 11 //距離センサーの「echo」が11番ピン
#define trigPin 12 //距離センサーの「trig」が12番ピン
#define ledPin 2 //LEDが2番ピン
double Duration = 0; //受信した間隔
double Distance = 0; //距離
Servo myservo;
void setup() {
pinMode(echoPin,INPUT);
pinMode(trigPin,OUTPUT);
pinMode(ledPin, OUTPUT);
myservo.attach(moterPin,700,2300);
Serial.begin(9600);
}
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");
if(Distance<15){ //Distance<15(15cmより小さい)→<、>と数値の変更ができます。
digitalWrite(ledPin, HIGH); //HIGH:光る LOW:光らない
delay(200);
//時計回り(when 1450~700 µsec) 逆時計回り(when 1550~2300 µsec) 1500に近い方が回転がおそくなる
myservo.write(700); //700はモーターが右回転で一番速く回ります
delay(5000); //5秒間
myservo.write(2300); //2300はモーターが左回転で一番速く回ります
delay(3000); //3秒間
}else{
myservo.write(1500); //1500はモーターが止まる数値です。変更可能です。
digitalWrite(ledPin, LOW); //HIGH:光る LOW:光らない
delay(200);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment