0% found this document useful (0 votes)
5 views

Arduino project

This document contains an Arduino sketch for controlling a servo lid using an ultrasonic sensor. The lid opens when an object is detected within a specified distance and closes after a delay once the object is no longer detected. It includes pin definitions, setup for the servo and sensor, and the main loop for measuring distance and controlling the lid's position.

Uploaded by

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

Arduino project

This document contains an Arduino sketch for controlling a servo lid using an ultrasonic sensor. The lid opens when an object is detected within a specified distance and closes after a delay once the object is no longer detected. It includes pin definitions, setup for the servo and sensor, and the main loop for measuring distance and controlling the lid's position.

Uploaded by

richard senior
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

#include <Servo.

h>

// Pin Definitions

Const int trigPin = 9;

Const int echoPin = 10;

Const int servoPin = 6;

// Parameters

Const int detectionThreshold = 20; // Distance in cm to trigger lid open

Const unsigned long closeDelay = 3000; // Time in ms to keep lid open after last
detection

// Global Variables

Servo lidServo;

Long duration;

Int distance;

Bool isLidOpen = false;

Unsigned long lastDetectionTime = 0;

Void setup() {

// Initialize Sensor Pins

pinMode(trigPin, OUTPUT);

pinMode(echoPin, INPUT);

// Attach Servo and Close Lid

lidServo.attach(servoPin);

lidServo.write(0); // 0 degrees = closed position


// Start Serial Monitor (for debugging)

Serial.begin(9600);

Void loop() {

// Measure Distance with Ultrasonic Sensor

digitalWrite(trigPin, LOW);

delayMicroseconds(2);

digitalWrite(trigPin, HIGH);

delayMicroseconds(10);

digitalWrite(trigPin, LOW);

duration = pulseIn(echoPin, HIGH);

distance = duration * 0.034 / 2; // Convert to cm

// Print Distance for Debugging

Serial.print(“Distance: “);

Serial.print(distance);

Serial.println(“ cm”);

// Control Lid Based on Distance

If (distance <= detectionThreshold && distance > 0) {

If (!isLidOpen) {

lidServo.write(90); // Open lid (90 degrees)

isLidOpen = true;

Serial.println(“Lid opened!”);

lastDetectionTime = millis(); // Reset timer


} else {

If (isLidOpen && (millis() – lastDetectionTime > closeDelay)) {

lidServo.write(0); // Close lid

isLidOpen = false;

Serial.println(“Lid closed!”);

Delay(100); // Short delay to stabilize readings

You might also like