0% found this document useful (0 votes)
7 views4 pages

Arduino Servo Control with Distance Sensor

Uploaded by

Hasan Mujtaba
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views4 pages

Arduino Servo Control with Distance Sensor

Uploaded by

Hasan Mujtaba
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

#include <Servo.

h>

// Pins

const int trigPin = 9;

const int echoPin = 10;

const int servoPin = 6;

const int ledPin = 11; // LED connected to pin 11

const int buzzerPin = 12; // Buzzer connected to pin 12

// Conversion factor: µs → cm

const float DIST_FACTOR = 0.01715;

Servo lidServo;

// Parameters

const float THRESHOLD_CM = 15.0; // distance to trigger opening

const unsigned long OPEN_TIME_MS = 4000; // lid open time = 4 sec

unsigned long lastOpenMs = 0;

bool isOpen = false;

void setup() {

[Link](9600);

pinMode(trigPin, OUTPUT);

pinMode(echoPin, INPUT);
pinMode(ledPin, OUTPUT);

pinMode(buzzerPin, OUTPUT);

[Link](servoPin);

[Link](0); // start closed

digitalWrite(ledPin, LOW);

digitalWrite(buzzerPin, LOW);

float readDistanceCm() {

// Send 10µs pulse

digitalWrite(trigPin, LOW);

delayMicroseconds(2);

digitalWrite(trigPin, HIGH);

delayMicroseconds(10);

digitalWrite(trigPin, LOW);

// Measure echo

unsigned long duration = pulseIn(echoPin, HIGH, 30000);

if (duration == 0) return -1.0; // no echo

return duration * DIST_FACTOR; // distance in cm

}
void loop() {

float d = readDistanceCm();

if (d > 0) {

[Link]("Distance: ");

[Link](d);

[Link](" cm");

// Open lid if object is close

if (!isOpen && d > 0 && d <= THRESHOLD_CM) {

[Link](90); // open lid

digitalWrite(ledPin, HIGH); // turn LED on

digitalWrite(buzzerPin, HIGH); // buzzer on

delay(200); // short beep

digitalWrite(buzzerPin, LOW);

isOpen = true;

lastOpenMs = millis();

// Close lid after time

if (isOpen && (millis() - lastOpenMs >= OPEN_TIME_MS)) {

[Link](0); // close lid

digitalWrite(ledPin, LOW); // turn LED off

digitalWrite(buzzerPin, LOW);
isOpen = false;

delay(200);

You might also like