Stop Servo if the certain condition is met

Hello. Can anyone help me? What is the code for making the servo pause/stop temporarily if it hits greater than 50cm distance? then spin again at 180 degrees when reaches 50cm less? I tried servoMotor.detach() but it stops permanently even I turn the distance to less than 50cm. Also tried servoMotor.write(90) ,delay(4000) but it just spin 90degrees back and forth.

Here is my code below.

#include <Servo.h>

const int trigPin = 9;
const int echoPin = 8;
int green = 12;
int blue = 4;
int pos = 0;

Servo servoMotor;

void setup()
{
servoMotor.write(pos);
Serial.begin(9600);
pinMode(trigPin,OUTPUT);
pinMode(echoPin,INPUT);
pinMode(blue, OUTPUT);
pinMode(green, OUTPUT);
servoMotor.attach(2);
servoMotor.write(0);

}

void sinetch()
{
float duration, dicm;

digitalWrite(trigPin, LOW);
delay(100);
digitalWrite(trigPin, HIGH);
delay(100);
digitalWrite(trigPin, LOW);
duration=pulseIn(echoPin, HIGH);
dicm = (duration/2) / 29.1;

if (dicm <= 50)
{
	digitalWrite(blue, HIGH);
    digitalWrite(green, LOW);
  	

servoMotor.write(180);
    delay(100);
  	Serial.print("The distance in cm. is ");
  	Serial.println(dicm);
  

}
else if (dicm > 50)
{
	digitalWrite(green, HIGH);
    digitalWrite(blue, LOW);
  	servoMotor.write(179);
  	delay(100);
    Serial.print("The distance in cm. is ");
  	Serial.println(dicm);
}

}

void loop()
{
sinetch(); //Repeat sinetch.

}

I'm doing this at tinkercad. Please do reply if you have any idea. Thank you!

Welcome to the forum

Please follow the advice given in the link below when posting code, in particular the section entitled 'Posting code and common code problems'

Use code tags (the </> icon above the compose window) to make it easier to read and copy for examination

the code you posted invokes servoMotor.write() to set the servo to 180 or 179 depending on the distance measure. i'll guess that one or even both of those values results in a distance being either > or < 50

more likely the difference in values (180 or 179) needs to be greater. but may also be constrained by physical limits

so it may make more sense to gradually change the value but then then the code is likely to slowly oscillate between the points where it is just > and just < 50 cm

you could try specifying a target distance value thru the serial monitor and move the servo reach that target within some tolerance (x +/-10). in other words, if moving the servo more position (toward 180) increases the distance, if the current position is < the target, increase the servo position and do the opposite for the target < current position

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