esp/arduino/Update sketchDistanceSerial...

35 lines
809 B
C++

//Définition des constanntes
// PIN Echo
const int EchoPin = 8;
// PIN Trigger
const int TriggerPin = 9;
void setup() {
Serial.begin(9600);
pinMode(TriggerPin, OUTPUT);
pinMode(EchoPin, INPUT);
}
void loop() {
int cm = ping(TriggerPin, EchoPin);
Serial.print("Distance mesurée : ");
Serial.println(cm);
delay(1000); // 1 s
}
//Calculer la distance
int ping(int TriggerPin, int EchoPin) {
long duration, distanceCm;
digitalWrite(TriggerPin, LOW); //Pause de 4 µs
delayMicroseconds(4);
digitalWrite(TriggerPin, HIGH); //Génération de 10 µs
delayMicroseconds(10);
digitalWrite(TriggerPin, LOW); //Pause
duration = pulseIn(EchoPin, HIGH); // lecture
distanceCm = duration * 10 / 292/ 2; // Vitesse du son converti en cm
return distanceCm;
}