超音波控制綠燈行紅燈停

 #include <Servo.h>


// 定義超音波sg90信號黃線引腳

#define sg90Pin 6


// 定義超音波SR04引腳

#define echoPin 8

#define trigPin 9



// 定義RGB引腳

  #define RED_PIN 10

  #define GREEN_PIN 11

  #define BLUE_PIN 12


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


  

  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 < 100) {

Serial.print(distance);

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

servo.write(90); //run _open


// 共陽極 紅燈

  analogWrite(RED_PIN, 0);   

  analogWrite(GREEN_PIN, 255 );

  analogWrite(BLUE_PIN, 255 );

  delay(5000);  //停5秒

                        }

else {

Serial.print(distance);

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

servo.write(180);//stop_close


   // 共陽極 綠燈

  analogWrite(RED_PIN, 255);   

  analogWrite(GREEN_PIN, 0);

  analogWrite(BLUE_PIN, 255);


     }


delay(500);


}

留言