感應通行綠燈 停止紅燈

 #include <Servo.h>


// 定義超音波SR04引腳

#define sg90Pin 6

#define echoPin 8

#define trigPin 9


// 定義RGB引腳

  #define RED_PIN 10

  #define GREEN_PIN 11

  #define BLUE_PIN 12

// 共陽極全彩LED燈模組的V接5V     R接pin9    G接pin10    B接pin11

  

  Servo servo;

int sound = 250;



void setup() {

Serial.begin (9600);


 pinMode(RED_PIN, OUTPUT);

 pinMode(GREEN_PIN, OUTPUT);

 pinMode(BLUE_PIN, OUTPUT);


pinMode(trigPin, OUTPUT);

pinMode(echoPin, INPUT);


servo.attach(sg90Pin);



}




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


 // 共陽極 綠燈

  analogWrite(RED_PIN, 255);   

  analogWrite(GREEN_PIN, 0);

  analogWrite(BLUE_PIN, 255);

                        }


else {

Serial.print(distance);

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

servo.write(90);//stop_close

  // 共陽極 紅燈

  analogWrite(RED_PIN, 0);   

  analogWrite(GREEN_PIN, 255 );

  analogWrite(BLUE_PIN, 255 );


     }


delay(500);


}



留言