|
#include <Servo.h>
// Pin definitions int TRIGGER_PIN = 7; int ECHO_PIN = 6; int SERVO_PIN = 9;
// Distance and servo angles int MAX_DISTANCE = 20; int OPEN_ANGLE = 90; int CLOSE_ANGLE = 0;
// Create servo object Servo servo;
// Variables long duration; int distance;
void setup() {
// Set pin modes pinMode(TRIGGER_PIN, OUTPUT); pinMode(ECHO_PIN, INPUT);
// Connect servo motor servo.attach(SERVO_PIN); }
void loop() {
// Send ultrasonic signal digitalWrite(TRIGGER_PIN, LOW); delayMicroseconds(2);
digitalWrite(TRIGGER_PIN, HIGH); delayMicroseconds(10);
digitalWrite(TRIGGER_PIN, LOW);
// Read echo time duration = pulseIn(ECHO_PIN, HIGH);
// Calculate distance distance = (duration / 2) / 29.1;
// Check object distance if (distance <= MAX_DISTANCE) {
// Open lid servo.write(OPEN_ANGLE); delay(1000);
} else {
// Close lid servo.write(CLOSE_ANGLE); }
delay(500); }
|