80以下伺服馬達轉 80-180伺服馬達轉停






 #include <Servo.h>

#define trigPin 9

#define echoPin 8

Servo servo;

int sound = 250;


void setup() {

Serial.begin (9600);

pinMode(trigPin, OUTPUT);

pinMode(echoPin, INPUT);

servo.attach(6);

}


void loop() {

long duration, distance;

digitalWrite(trigPin, LOW);

delayMicroseconds(2);

digitalWrite(trigPin, HIGH);

delayMicroseconds(10);

digitalWrite(trigPin, LOW);

duration = pulseIn(echoPin, HIGH);

distance = (duration/2) / 29.1; 


if (distance < 80) {

Serial.print(distance);

Serial.println(" cm distance < 80 run-servo.write(180)");

servo.write(180); //run _open

}


else if (distance<180) {

Serial.print(distance);

Serial.println(" cm 80<distance<180  stop-servo.write(90)");

servo.write(90);//stop_close

}


else {

Serial.println("The distance is more than 180cm");

}


delay(500);

}

留言