I am currently coding a new trash can using a sensor and a servo motor, i am facing problems with my sensor catching thing that makes my servo go insane and just not stop so i need a solution with making my servo work once and not work for another 5-10 seconds
The code im using right now:
//define Pins
#include <Servo.h>
Servo servo;
int trigPin = 9;
int echoPin = 8;
// defines variables
long duration;
int distance;
void setup()
{
servo.attach(6);
servo.write(0);
delay(2000);
// Sets the trigPin as an Output
pinMode(trigPin, OUTPUT);
// Sets the echoPin as an Input
pinMode(echoPin, INPUT);
// Starts the serial communication
Serial.begin(9600);
}
void loop()
{
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(100);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance= duration*0.0200/2;
// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
if ( distance <= 25 ) // Change Distance according to Ultrasonic Sensor Placement
{
servo.write(0);
delay(5000);
}
else
{
servo.write(180);
}
}
Welcome to the forum..
Yes, looks like to me that you are reading your "sensor catching thing" at loop speed too fast and sometimes they can give erroneous readings..
I do see you have a delay(5000) 5 seconds, just after servo.write(0)..
Try moving that to the end of the loop, just above the last }..
Can also try reducing this value, don't want to be waiting 5 seconds just throw a tissue away..