Last active
March 10, 2016 10:55
-
-
Save atrakeur/0cb2e1ebfb0251a2f7e0 to your computer and use it in GitHub Desktop.
Code sample for my article on HC-SR04 on https://www.atrakeur.com/blog/art30-comment_utiliser_un_capteur_a_ultrasons_hcsr04_avec_arduino
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Define the echo pin (receive the echo from the ultrasound) | |
#define SENSOR_ECHO_PIN 7 | |
//Define the trig pin (trigger the ultrasonic emitter) | |
#define SENSOR_TRIG_PIN 8 | |
//On some sort of sensors, echo and trig can be on the same pin | |
//Precalculate some values | |
const float SpeedOfSound = 343.2; // ~speed of sound (m/s) in air, at 20°C | |
const float MicrosecondsPerMillimetre = 1000.0 / SpeedOfSound; // microseconds per millimetre | |
const float MicrosecondsToMillimetres = (1.0 / MicrosecondsPerMillimetre); //distance by time elapsed | |
const float MicrosecondsToMillimetresDistance = MicrosecondsToMillimetres / 2.0; //because the ping make twice distance to object | |
void setup() { | |
// initialize serial communication to debug | |
Serial.begin(9600); | |
//Set pin modes | |
pinMode(SENSOR_ECHO_PIN, INPUT); | |
pinMode(SENSOR_TRIG_PIN, OUTPUT); | |
//Enable internal pull down for echo (to force it to zero when not in HIGH) | |
digitalWrite(SENSOR_ECHO_PIN, LOW); | |
} | |
void loop() { | |
//Send a high pulse on the trigger for a given amount of time | |
digitalWrite(SENSOR_TRIG_PIN, HIGH); | |
delayMicroseconds(10); // Some sensor need more than 10 us | |
digitalWrite(SENSOR_TRIG_PIN, LOW); | |
//Sound wave is in transit, wait for it to come back (ECHO pin goes to LOW) | |
long microseconds = pulseIn(SENSOR_ECHO_PIN, HIGH) | |
long millimetres = MicrosecondsToMillimetresDistance * microseconds; | |
//Print result | |
char buff[32]; | |
sprintf(buff, "Distance: %d cm", millimetres); | |
Serial.println(buff); | |
//Add a delay to avoid flooding Serial, and avoiding soundwave collisions | |
delay(1000); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment