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