感應掀蓋 led亮

#include <Servo.h>

#define trigPin 9

#define echoPin 8

#define sr04Pin 6

#define ledPin 5

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


// 開啟LED 

  digitalWrite(ledPin, HIGH); 

   }




else {


Serial.print(distance);

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

servo.write(90);//stop_close


// 關閉LED 

digitalWrite(ledPin, LOW); 


}


delay(500);


}


留言