2
const int pingPin = A0;

void loop() {
  long duration, inches, cm;
  pinMode(pingpin, OUTPUT);
  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(5);
  digitalWrite(pingPin, LOW);
  pinMode(pingPin, INPUT);
  duration = pulseIn(pingPin, HIGH);
  inches = microsecondsToInches(duration);
  cm = microsecondsToCentimeters(duration);
  Serial.print(inches);
  Serial.print("in, ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();
}

How to change this code for a 4-pin ultrasonic sensor?

dda
  • 1,588
  • 1
  • 12
  • 17

1 Answers1

1

The four pin Echo))) module is basically the same as three pin ones, except for triggering is done by another pin. So you don't have to care about setting pin to the output mode and switching it back to the input mode after the trigger pulse. You can read about it for example here.

const int8_t pingPin = A0;
const int8_t trigPin = A1;

void setup()
{
  pinMode(pingPin, INPUT);
  pinMode(trigPin, OUTPUT);
}

void loop()
{
  // pulse on trigger pin:
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10); // 10us is minimum trigger pulse duration
  digitalWrite(trigPin, LOW);

  // measure HIGH pulse duration:
  long duration = pulseIn(pingPin, HIGH);

  // and rest of the code:
  long   inches = microsecondsToInches(duration);
  long       cm = microsecondsToCentimeters(duration);

  Serial.print(inches);
  Serial.print("in, ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();
}
KIIV
  • 4,742
  • 1
  • 12
  • 21