Try   HackMD

(project) 智能垃圾桶

需求

  1. 自動開起垃圾桶
  2. 根據垃圾量,亮起指示燈

電路圖

Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More →

程式碼

#include <Servo.h> Servo myservo; // 定義舵機對象,最多八個 #define ledPin 2 #define person_echoPin 3 #define person_trigPin 4 #define trash_echoPin 8 #define trash_trigPin 9 #define servoPin 13 #define open_dist 15 // cm #define open_time 10000 // ms #define trash_dist 20 // cm void setup() { Serial.begin(9600); pinMode(person_echoPin, INPUT); pinMode(person_trigPin, OUTPUT); pinMode(trash_echoPin, INPUT); pinMode(trash_trigPin, OUTPUT); } void loop() { open_trash_can(); detect_trash_capacity(); } void open_trash_can() { digitalWrite(person_trigPin, HIGH); delayMicroseconds(1000); digitalWrite(person_trigPin, LOW); float duration = pulseIn(person_echoPin, HIGH); float distance = (duration/2) * 0.034; // Serial.print(distance); // Serial.println(" cm"); if (distance <= open_dist) { myservo.attach(servoPin); myservo.write(135); delay(open_time); } myservo.write(0); delay(500); myservo.detach(); } void detect_trash_capacity() { digitalWrite(trash_echoPin, HIGH); delayMicroseconds(1000); digitalWrite(trash_trigPin, LOW); float duration = pulseIn(person_echoPin, HIGH); float distance = (duration/2) * 0.034; if (distance < trash_dist) { digitalWrite(ledPin, HIGH); } else { digitalWrite(ledPin, LOW); } }