Cooldown on servo motor

Hello,

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);

 }

}

Thank you.

Hi @mhazte ,

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.. :slight_smile:

good luck.. ~q

What is this conversion? cm, inches, feet?

mm i think

How can i solve my erroneous readings problems its really driving me crazy and the delay was just to fix some issues i already adjusted

That would be 0.343/2.0
So you are checking to see if the distance is less than 25mm??

Well the main problem is that my sensor is catching things up at distances like 3,5,7 cm which are just not there so my servo just doesnt stop

What is this sensor is it an HC-SR04?

Yes

Then to convert to cm use distance= duration*0.0343/2.0;

Also check to see if the distance is less than 25 but greater than 0.
0 may be an invalid reading

with the code up top now it works perfectly fine, thanks

Works perfectly fine now, thanks. :heart:

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.