Update Update sketchDistanceSerial.ino

This commit is contained in:
Cédric Abonnel 2022-05-15 21:38:15 +00:00
parent 2ccde493d6
commit f6cd912f7b
1 changed files with 35 additions and 30 deletions

View File

@ -1,34 +1,39 @@
//Définition des constanntes // ---------------------------------------------------------------- //
// PIN Echo // Arduino Ultrasoninc Sensor HC-SR04
const int EchoPin = 8; // Re-writed by Arbi Abdul Jabbaar
// PIN Trigger // Using Arduino IDE 1.8.7
const int TriggerPin = 9; // Using HC-SR04 Module
// Tested on 17 September 2019
// ---------------------------------------------------------------- //
#define echoPin 2 // attach pin D2 Arduino to pin Echo of HC-SR04
#define trigPin 3 //attach pin D3 Arduino to pin Trig of HC-SR04
// defines variables
long duration; // variable for the duration of sound wave travel
int distance; // variable for the distance measurement
void setup() { void setup() {
Serial.begin(9600); pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT
pinMode(TriggerPin, OUTPUT); pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT
pinMode(EchoPin, INPUT); Serial.begin(9600); // // Serial Communication is starting with 9600 of baudrate speed
Serial.println("Ultrasonic Sensor HC-SR04 Test"); // print some text in Serial Monitor
Serial.println("with Arduino UNO R3");
} }
void loop() { void loop() {
int cm = ping(TriggerPin, EchoPin); // Clears the trigPin condition
Serial.print("Distance mesurée : "); digitalWrite(trigPin, LOW);
Serial.println(cm); delayMicroseconds(2);
delay(1000); // 1 s // Sets the trigPin HIGH (ACTIVE) for 10 microseconds
} digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
//Calculer la distance digitalWrite(trigPin, LOW);
int ping(int TriggerPin, int EchoPin) { // Reads the echoPin, returns the sound wave travel time in microseconds
long duration, distanceCm; duration = pulseIn(echoPin, HIGH);
// Calculating the distance
digitalWrite(TriggerPin, LOW); //Démarrage de la séquence de 4 µs distance = duration * 0.034 / 2; // Speed of sound wave divided by 2 (go and back)
delayMicroseconds(4); // Displays the distance on the Serial Monitor
digitalWrite(TriggerPin, HIGH); // Impulsion de déclenchement 10 µs Serial.print("Distance: ");
delayMicroseconds(10); Serial.print(distance);
digitalWrite(TriggerPin, LOW); // Arrêt de l'impulsion Serial.println(" cm");
duration = pulseIn(EchoPin, HIGH); // Émission du signal et lecture
distanceCm = duration * 10 / 292/ 2; // Vitesse du son converti en cm
return distanceCm;
} }