Skip to content

Instantly share code, notes, and snippets.

@likersacademia
Last active October 12, 2018 17:45
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/171050b70e63ee1c6e3b64b82f2a6072 to your computer and use it in GitHub Desktop.
Save likersacademia/171050b70e63ee1c6e3b64b82f2a6072 to your computer and use it in GitHub Desktop.
//電源を入れると前進し、障害物から15cm離れたところで停止する車のプログラム
#include <Servo.h> //サーボモーターを動かす関数を用意します
#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(echoPin,INPUT);
pinMode(trigPin,OUTPUT);
myservo1.attach(moterPinR,700,2300);
myservo2.attach(moterPinL,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");
//時計回り(when 1450~700 µsec) 逆時計回り(when 1550~2300 µsec) 1500に近い方が回転がおそくなる
if(Distance>15){
myservo1.write(700); //700はモーターが一番早く回る数値です
myservo2.write(2300);
}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