PulseIn issue with two servos and one US

Dear all,

I’m building a robot which has two US servos mounted on two servos. But I’m experiencing some problems. If I uncomment the line with pulseIn which reads the pulse from SRF05, one of my servos does not work! Any ideas what I should do to make it wokr?

Here is my code:

#include <Wire.h>
#include <Servo.h> 

//Ultrasound
Servo US_left;
Servo US_right;
int US_right_dist[18];
int US_left_dist[18];
int US_position_right=90;
int US_position_left=90;
int US_step=10;
int tmp;
int echopin_left=2;
int trigpin_left=3;


int count=1;

void setup() {
  Serial.begin(9600);
  
  //US
  pinMode(echopin_left,INPUT);
  pinMode(trigpin_left,OUTPUT);
  US_left.attach(52);
  US_left.write(90);  
  US_right.attach(23);
  US_right.write(90);  
  delay(1000);
}

void loop() { 
  if (count==10){
    Scan();
    count=1;
  }
  delay(10);
}

void Scan(){
  int tmp2;
  tmp=US_position_left/US_step;
  digitalWrite(trigpin_left,LOW);
  delayMicroseconds(2);
  digitalWrite(trigpin_left,HIGH);
  delayMicroseconds(10);
  digitalWrite(trigpin_left,LOW);
  //US_left_dist[tmp] = pulseIn(echopin_left,HIGH)/58; <----THIS IS THE PROBLEMATIC LINE! 
  delay(50);
  Serial.flush();
  US_position_right=US_position_right+US_step;
  US_position_left=US_position_left-US_step;
  US_left.write(US_position_right); 
  US_right.write(US_position_left);
  if(US_position_right==180 || US_position_right==0){
    US_step=-US_step;
  }
  Serial.print("Distance left");
  Serial.println(US_left_dist[tmp]);
}

Could it be that 'tmp' is outside the range 0 to 17? Possibly when US_step is changed to -10?

I've changed the following line to:

if(US_position_right==150 || US_position_right==30)

But the result still is the same. Actually both motors work at first, but when one of them reaches the limit, the other disengages. I'm too confused about why omiting the row with pulseIn helps to solve the issue...

int US_left_dist[18];
int US_position_right;
int US_step=10;

if(US_position_right == 180)
    US_step = -US_step;  // Change from 10 to -10

  tmp = US_position_left/US_step;  // tmp = 180 / -10 == -18

  US_left_dist[tmp] = pulseIn(echopin_left,HIGH)/58; <----THIS IS THE PROBLEMATIC LINE!

So at some time you are using an index of -18 in an array with indexes from 0 to 17. You a causing a crash by clobbering data outside your array.

Thanks! That was really the case. I am really really grateful for your help!