4 Ping sensor Question

JimmySticks2001:

Your code could be simplified and made a bit more readable as follows (note that I haven't tested this code in any manner - use at your own risk!):

#define FWD_PING 2
#define BCK_PING 8

long cm1 = 0;
long cm2 = 0;

void setup()
{
  Serial.begin(9600);
}

void loop()
{
  cm1 = ping(FWD_PING);
  delay(5);

  cm2 = ping(BCK_PING);
  delay(5);

  Serial.print(cm1);
  Serial.print("cm, ");
  Serial.print(cm2);
  Serial.print("cm");
  Serial.println();
}

long ping(int pin)
{
  pinMode(pin, OUTPUT);
  digitalWrite(pin, LOW);
  delayMicroseconds(2);
  digitalWrite(pin, HIGH);
  delayMicroseconds(5);
  digitalWrite(pin, LOW);
  pinMode(pin, INPUT);
  
  long duration = pulseIn(pin, HIGH);

  return (microsecondsToCentimeters(duration));
}

long microsecondsToCentimeters(long microseconds)
{
  return microseconds / 29 / 2;
}

I don't think the 250 millisecond (1/4 second) delays are absolutely necessary; 5 milliseconds should suffice (and even that might be overkill). You could potentially do a ping, serial print, then ping another, serial print - and the serial prints would take care of any delay needed (if any is really needed).

Other than that, I made the pin definitions #defines, and created a single function for the ping action; potentially, the return values on the ping() and microsecondsToCentimeters() could be ints instead of longs, with some conversion/casting done to make sure of type (or something could be done with floats, so that you could get back fractional values).

I'm just posting these changes to allow others, and perhaps yourself, understand how by consolidation of functional definitions into as few functions as possible can lead to better code reuse, cleaner code, and a more maintainable structure overall.

:wink: