Using ultrasonic sensor to detect wall when robot is driving

septillion:

  1. That's not all you're all your code so we're unable to tell you whre the lag is comming from. But my guess, you use some more delay()'s...

  2. From the datasheet:Do you actually do that?

Small tip, numbering things is stupid. In case of variables, use an array. In case of functions, give it a damn parameter.

Extra tip, keep functions small. The name of the function should tell everything the function does. each1() does wayyyyy more then sending out an echo :wink:

The communication receiver code is this:

void ESPcom() {
  static boolean recvInProgress = false;
  static byte ndx = 0;
  char startMarker = '<';
  char endMarker = '>';
  char rc;

  while (ESPserial.available() > 0 && newData == false) {
    rc = ESPserial.read();

    if (recvInProgress == true) {
      if (rc != endMarker) {
        payload[ndx] = rc;
        ndx++;
        if (ndx >= numChars) {
          ndx = numChars - 1;
        }
      }
      else {
        payload[ndx] = '\0'; // terminate the string
        recvInProgress = false;
        ndx = 0;
        newData = true;
      }
    }

    else if (rc == startMarker) {
      recvInProgress = true;
    }
  }
  
  if (newData == true) {
    doCommands(payload[0]);
    newData = false;
  }
}

I have changed the echo functions to use millis instead of delay for timing:

void echo1() {
  Serial.println("ECHO");
  long duration, distance;
  digitalWrite(trigPin1, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin1, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin1, LOW);
  duration = pulseIn(echoPin1, HIGH);
  distance = (duration / 2) / 29.1;
  delay(10);
  
  if (distance > 0 && distance < 10) {
    carBack(75,75);
    currentMillis = millis();
    if (currentMillis - startMillis >= 500){
    carStop();
    startMillis = currentMillis;
    }
  }
}

I still use delayMicroseconds though, as this is the way it's done in every example i've seen with this sensor.

I still have both issues where the robot wont stop at the correct time when tapping the forward button, as well as false readings on the sensor...