0

so I am using an Ultrasonic Distance Sensor with Servomotors and I want it that when the sensor senses a distance of 50 cm the servomotors move to the selected position and then stay in that position even if the distance <50 after reaching that initial point. Here is the code I am using:

#include <Servo.h>

const int trigPin = 10;
const int echoPin = 11;
int pos1;
int pos0;
int sound = 250;
int pos2;

Servo one;
Servo two;

void setup(){
  Serial.begin(9600);
  pinMode(trigPin,OUTPUT);
  pinMode(echoPin,INPUT);
  pos1 =45;
  pos2 =25;
  pos0 =0;
  one.attach(13);
  two.attach(12);
}


void loop(){
  long duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);

  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2)/29.1;

  if(distance>50){
    one.write(pos1);
    two.write(pos2);
  }
  else{
    one.write(pos0);
    two.write(pos0);

  }
}

I tried making the code without the else command but then the servos automatically move to position even without hitting the distance I want. Is there another function I can use to make this happen (I am new to coding in general)?

  • your code is something like read sensor ... if distance = 50 then move servo ..... split the reading of sensor and moving of servo into separate actions, mainly because the two are completely separate .... use a boolean flag .... read sensor ... if distance = 50 then set flag (distanceReached = true) ... then further down in loop() do something like if distanceReached then move servo ..... then you can expand with if distance > 75 then distanceReached = false; outOfRange = true .... if outOfRange then flash lights ... etc. etc. – jsotola Mar 4 at 8:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.