Arduino distance logger

Un petit bout de code pour utiliser le module à ultrasons compatible Arduino.

const int TrigPin = 2;
const int EchoPin = 3;
float cm;

void setup() {
  Serial.begin(9600);
  pinMode(TrigPin, OUTPUT);
  pinMode(EchoPin, INPUT);
}

void loop() {
  digitalWrite(TrigPin, LOW); //Low-high-low level sent a short time pulse to TrigPin
  delayMicroseconds(2);
  digitalWrite(TrigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(TrigPin, LOW);
  cm = pulseIn(EchoPin, HIGH) / 58.0; //Echo time converted into cm
  cm = (int(cm * 100.0)) / 100.0; // retain two decimal places
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();
  delay(1000);
}
Share