0% found this document useful (0 votes)
10 views3 pages

Arduino Servo Control with Ultrasonic Sensor

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)
10 views3 pages

Arduino Servo Control with Ultrasonic Sensor

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

#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

[Link](servoPin);

[Link](0); // 0 degrees = closed position


// Start Serial Monitor (for debugging)

[Link](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

[Link](“Distance: “);

[Link](distance);

[Link](“ cm”);

// Control Lid Based on Distance

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

If (!isLidOpen) {

[Link](90); // Open lid (90 degrees)

isLidOpen = true;

[Link](“Lid opened!”);

lastDetectionTime = millis(); // Reset timer


} else {

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

[Link](0); // Close lid

isLidOpen = false;

[Link](“Lid closed!”);

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

Common questions

Powered by AI

Including a delay in the loop is crucial for stabilizing the readings from the ultrasonic sensor. Without this delay, the sensor may provide erratic or inconsistent distance readings due to its rapid cycling. The 100-millisecond delay ensures that the sensor has time to reset and prepare accurately for the next measurement cycle, thus reducing noise and improving reliability .

Boolean logic is used in this system to maintain and toggle the state of the lid through the isLidOpen variable. By storing a simple true or false status, the system efficiently checks and changes the lid's state without unnecessary actions. This approach minimizes processing load and ensures quick decision-making, which is essential for maintaining responsiveness in real-time applications .

The servo motor in this setup functions as a mechanism to open and close the lid, which is controlled by the lidServo object. It changes state based on the distance measured by the ultrasonic sensor. If the sensor detects an object within the detectionThreshold range, the servo is commanded to move to 90 degrees, opening the lid. If no object is detected within a specified delay time (closeDelay), the servo returns to 0 degrees to close the lid .

While the system efficiently opens and closes the lid based on sensor data, the logic could be refined for enhanced efficiency. For instance, the delay function could be modified or removed in favor of more sophisticated timing mechanisms, such as interrupts, to optimize processing time and responsiveness. Additionally, implementing state-saving mechanisms could facilitate better power management and possibly include other sensor inputs to reduce false triggers in complex environments .

This automated lid system can be used in various scenarios, including smart trash bins, automated pet feeders, and hygiene touches containers. Its impact on user experience is significant; it offers convenience by allowing hands-free operation, thus enhancing accessibility and maintaining hygiene by reducing direct contact with surfaces prone to contamination. These applications could be particularly beneficial in environments like hospitals or kitchens, where hands-free operation is advantageous .

The system uses nested conditional statements to manage the lid's operation. It first checks if the measured distance is within the detection threshold and if the lid is not already open. If both conditions hold, it opens the lid and logs the time. Conversely, if the distance is greater than the threshold, it checks if the current time minus lastDetectionTime exceeds closeDelay to decide if the lid should be closed. This logical structuring ensures the lid only responds to valid triggers, thereby preventing unnecessary operations .

The lastDetectionTime variable holds the time of the last detection when the distance was within the threshold. It is pivotal in determining how long the lid remains open after the last detected object. When the distance is below the threshold, lastDetectionTime is reset to the current time from millis(). If no object is detected within closeDelay milliseconds afterward, the system interprets this as a cue to close the lid. Thus, it provides a timed logic to control the state of the lid based on recent activity .

Pin initialization in the setup function is essential for defining the roles of the hardware components connected to the microcontroller. For instance, setting the trigPin as OUTPUT and echoPin as INPUT configures the ultrasonic sensor to send and receive signals properly. This initialization ensures that each component interacts correctly with the main board, thus facilitating accurate sensor readings and effective control over the servo motor .

The system uses the Serial Monitor to output current sensor readings and state changes, such as when the lid opens or closes. By printing the measured distance continuously, the system provides real-time feedback that helps in verifying the sensor's accuracy and the logic's correctness. This debugging information is crucial in the development stage to diagnose errors or unexpected behaviors, ultimately ensuring reliable performance .

The ultrasonic sensor determines the distance to an object by sending a pulse from the trigPin and measuring the time it takes for the echo to return to the echoPin. The duration of this echo is measured and used to calculate the distance using the formula: distance = duration * 0.034 / 2. This calculation is necessary because the sensor measures the round-trip time, and dividing by 2 gives the one-way distance. The factor 0.034 is used to convert the duration from microseconds to centimeters .

You might also like