31 lines
1.0 KiB
C++
31 lines
1.0 KiB
C++
// Ultrasonic - Library for HR-SC04 Ultrasonic Ranging Module.
|
|
// Rev.4 (06/2012) - J.Rodrigo ( www.jrodrigo.net ) - www.ardublog.com
|
|
// more info at https://www.abonnel.fr/electronique/lois-et-composants/500-capteur-de-distance-ultrasons#principe
|
|
|
|
#include "Ultrasonic.h"
|
|
|
|
#define echoPin 9 // attach pin D2 Arduino to pin Echo of HC-SR04
|
|
#define trigPin 8 //attach pin D3 Arduino to pin Trig of HC-SR04
|
|
|
|
Ultrasonic sensor(trigPin,echoPin); // Trig et Echo
|
|
|
|
// defines variables
|
|
int distance; // variable for the distance measurement
|
|
|
|
void setup() {
|
|
Serial.begin(9600);trigPin as an OUTPUT
|
|
pinMode(echoPin, INPUT); // Sets the echoPin as an 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 and Ultrasonic.h");
|
|
}
|
|
|
|
void loop () {
|
|
distance = sensor.Ranging(CM); // CM or INC
|
|
Serial.print("Distance: ");
|
|
Serial.print(distance);
|
|
Serial.println(" cm");
|
|
|
|
delay(100); // 100 ms
|
|
}
|