低於80cm伺服馬達轉到180度_感應掀蓋

 #include <Servo.h>

#define trigPin 9

#define echoPin 8

#define sr04Pin 6

Servo servo;

int sound = 250;


void setup() {

Serial.begin (9600);

pinMode(trigPin, OUTPUT);

pinMode(echoPin, INPUT);

servo.attach(sr04Pin);

}




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 {

Serial.print(distance);

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

servo.write(90);//stop_close

}

 

delay(500);

}


留言