├── LICENSE ├── README.md ├── examples ├── simple │ └── simple.ino └── temperature │ └── temperature.ino ├── hcsr04.jpg ├── keywords.txt ├── library.properties └── src ├── HCSR04.cpp └── HCSR04.h /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 Martin Šošić 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Arduino library for HC-SR04 ultrasonic distance sensor. 2 | 3 | HC-SR04 is an ultrasonic sensor that measures distances from 2 to 400cm. 4 | 5 | ![HC-SR04](/hcsr04.jpg) 6 | 7 | This is a simple library for it! 8 | 9 | ## Usage 10 | Sensor is initialized by creating instance of class UltraSonicDistanceSensor and providing trigger and echo pins. 11 | ```c 12 | UltraSonicDistanceSensor sensor(triggerPin, echoPin); 13 | ``` 14 | 15 | Default value for maximum measurement distance is 4m, since HC-SR04 sensor can't measure reliably beyond that. 16 | However, if you are using another sensor or if you you don't care about distances larger than some value, you can set a maximum distance in cm yourself. 17 | ```c 18 | UltraSonicDistanceSensor sensor(triggerPin, echoPin, maxDistanceCm); 19 | ``` 20 | 21 | Besides defining max distance, you can also define max time of measurement (in micro seconds). This is important when you want to ensure your program does not block for longer than specific period of time. 22 | ```c 23 | UltraSonicDistanceSensor sensor(triggerPin, echoPin, maxDistanceCm, absoluteTimeout); 24 | ``` 25 | 26 | Then, to measure the distance, you just call `measureDistanceCm()`, which will return distance in centimeters. If distance is larger than 400cm, it will return negative value. 27 | 28 | The calculation assumes a temperature of around 20°C. For improved accuracy you may also provide a temperature yourself, either an average for your location or directly measured from another sensor. The call for a temperature of 3.5°C would as such look like this: `measureDistanceCm(3.5)`. 29 | 30 | ## Example 31 | 32 | In this simple example, we need to connect sensors pins like this: 33 | 34 | - vcc to 5V 35 | - trig to digital pin 13 36 | - echo to digital pin 12 37 | - gnd to gnd 38 | 39 | ```c 40 | #include 41 | 42 | // Initialize sensor that uses digital pins 13 and 12. 43 | const byte triggerPin = 13; 44 | const byte echoPin = 12; 45 | UltraSonicDistanceSensor distanceSensor(triggerPin, echoPin); 46 | 47 | void setup () { 48 | Serial.begin(9600); // We initialize serial connection so that we could print values from sensor. 49 | } 50 | 51 | void loop () { 52 | // Every 500 miliseconds, do a measurement using the sensor and print the distance in centimeters. 53 | float distance = distanceSensor.measureDistanceCm(); 54 | Serial.println(distance); 55 | delay(500); 56 | } 57 | ``` 58 | -------------------------------------------------------------------------------- /examples/simple/simple.ino: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | UltraSonicDistanceSensor distanceSensor(13, 12); // Initialize sensor that uses digital pins 13 and 12. 4 | 5 | void setup () { 6 | Serial.begin(9600); // We initialize serial connection so that we could print values from sensor. 7 | } 8 | 9 | void loop () { 10 | // Every 500 miliseconds, do a measurement using the sensor and print the distance in centimeters. 11 | Serial.println(distanceSensor.measureDistanceCm()); 12 | delay(500); 13 | } 14 | -------------------------------------------------------------------------------- /examples/temperature/temperature.ino: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | //This example uses a DS18B20 1Wire Temperature sensor 4 | //Of course you can use something else like DHT22, LM35 or whatever you have lying around. 5 | #include 6 | #include 7 | 8 | UltraSonicDistanceSensor distanceSensor(13, 12); // Initialize sensor that uses digital pins 13 and 12. 9 | OneWire oneWire(11); 10 | DallasTemperature sens_temperature(&oneWire); 11 | 12 | void setup () { 13 | Serial.begin(9600); // We initialize serial connection so that we could print values from sensor. 14 | } 15 | 16 | void loop () { 17 | // Every 1 second, do a measurement using the sensor and print the distance in centimeters. 18 | sens_temperature.requestTemperatures(); 19 | float temperature = sens_temperature.getTempCByIndex(0); 20 | float distance = distanceSensor.measureDistanceCm(temperature); 21 | 22 | Serial.print(F("Temperature: ")); 23 | Serial.print(temperature); 24 | Serial.print(F("°C - Distance: ")); 25 | Serial.print(distance); 26 | Serial.println(F("cm")); 27 | delay(1000); 28 | } 29 | -------------------------------------------------------------------------------- /hcsr04.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Martinsos/arduino-lib-hc-sr04/46a8be5ab2211152601d16748d95df1702bcee72/hcsr04.jpg -------------------------------------------------------------------------------- /keywords.txt: -------------------------------------------------------------------------------- 1 | UltraSonicDistanceSensor KEYWORD1 2 | measureDistanceCm KEYWORD2 3 | -------------------------------------------------------------------------------- /library.properties: -------------------------------------------------------------------------------- 1 | name=HCSR04 2 | version=2.0.0 3 | author=Martin Sosic 4 | maintainer=Martin Sosic 5 | sentence=Library for HC-SR04 ultrasonic distance sensor. 6 | paragraph=You can measure distance in centimeters. 7 | category=Sensors 8 | url=https://github.com/Martinsos/arduino-lib-hc-sr04 9 | architectures=* 10 | -------------------------------------------------------------------------------- /src/HCSR04.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | HCSR04 - Library for arduino, for HC-SR04 ultrasonic distance sensor. 3 | Created by Martin Sosic, June 11, 2016. 4 | */ 5 | 6 | #include "Arduino.h" 7 | #include "HCSR04.h" 8 | 9 | UltraSonicDistanceSensor::UltraSonicDistanceSensor( 10 | byte triggerPin, byte echoPin, unsigned short maxDistanceCm, unsigned long maxTimeoutMicroSec) { 11 | this->triggerPin = triggerPin; 12 | this->echoPin = echoPin; 13 | this->maxDistanceCm = maxDistanceCm; 14 | this->maxTimeoutMicroSec = maxTimeoutMicroSec; 15 | pinMode(triggerPin, OUTPUT); 16 | pinMode(echoPin, INPUT); 17 | } 18 | 19 | float UltraSonicDistanceSensor::measureDistanceCm() { 20 | //Using the approximate formula 19.307°C results in roughly 343m/s which is the commonly used value for air. 21 | return measureDistanceCm(19.307); 22 | } 23 | 24 | float UltraSonicDistanceSensor::measureDistanceCm(float temperature) { 25 | unsigned long maxDistanceDurationMicroSec; 26 | 27 | // Make sure that trigger pin is LOW. 28 | digitalWrite(triggerPin, LOW); 29 | delayMicroseconds(2); 30 | // Hold trigger for 10 microseconds, which is signal for sensor to measure distance. 31 | digitalWrite(triggerPin, HIGH); 32 | delayMicroseconds(10); 33 | digitalWrite(triggerPin, LOW); 34 | float speedOfSoundInCmPerMicroSec = 0.03313 + 0.0000606 * temperature; // Cair ≈ (331.3 + 0.606 ⋅ ϑ) m/s 35 | 36 | // Compute max delay based on max distance with 25% margin in microseconds 37 | maxDistanceDurationMicroSec = 2.5 * maxDistanceCm / speedOfSoundInCmPerMicroSec; 38 | if (maxTimeoutMicroSec > 0) { 39 | maxDistanceDurationMicroSec = min(maxDistanceDurationMicroSec, maxTimeoutMicroSec); 40 | } 41 | 42 | // Measure the length of echo signal, which is equal to the time needed for sound to go there and back. 43 | unsigned long durationMicroSec = pulseIn(echoPin, HIGH, maxDistanceDurationMicroSec); // can't measure beyond max distance 44 | 45 | float distanceCm = durationMicroSec / 2.0 * speedOfSoundInCmPerMicroSec; 46 | if (distanceCm == 0 || distanceCm > maxDistanceCm) { 47 | return -1.0 ; 48 | } else { 49 | return distanceCm; 50 | } 51 | } -------------------------------------------------------------------------------- /src/HCSR04.h: -------------------------------------------------------------------------------- 1 | /* 2 | HCSR04 - Library for arduino, for HC-SR04 ultrasonic distance sensor. 3 | Created by Martin Sosic, June 11, 2016. 4 | */ 5 | 6 | #ifndef HCSR04_H 7 | #define HCSR04_H 8 | 9 | #include "Arduino.h" 10 | 11 | class UltraSonicDistanceSensor { 12 | public: 13 | /** 14 | * @param triggerPin Digital pin that is used for controlling sensor (output). 15 | * @param echoPin Digital pin that is used to get information from sensor (input). 16 | * @param maxDistanceCm Maximum distance sensor can measure, defaults to 4m for HC-SR04. 17 | * You might want to set this value if you are using different sensor than HC-SR04 18 | * or if you don't care about distances larger than whatever you will set it to 19 | * (therefore reducing time it takes for a single measurement). 20 | * @param maxTimeoutMicroSec Single measurement will never take longer than whatever value you provide here. 21 | * You might want to do this in order to ensure your program is never blocked for longer than some specific time, 22 | * since measurements are blocking. 23 | * By default, there is no limit on time (only on distance). By defining timeout, you are again limiting the distance. 24 | */ 25 | UltraSonicDistanceSensor(byte triggerPin, byte echoPin, unsigned short maxDistanceCm = 400, unsigned long maxTimeoutMicroSec = 0); 26 | 27 | /** 28 | * Measures distance by sending ultrasonic waves and measuring time it takes them 29 | * to return. 30 | * @returns Distance in centimeters, or negative value if distance is greater than 400cm. 31 | */ 32 | float measureDistanceCm(); 33 | 34 | /** 35 | * Measures distance by sending ultrasonic waves and measuring time it takes them 36 | * to return. Measurement can not exceed duration calculated with maxDistanceCm or maxTimeoutMicroSec. 37 | * @param temperature Temperature in degrees celsius 38 | * @returns Distance in centimeters, or negative value if distance is greater than 400cm. 39 | */ 40 | float measureDistanceCm(float temperature); 41 | private: 42 | byte triggerPin, echoPin; 43 | unsigned short maxDistanceCm; 44 | unsigned long maxTimeoutMicroSec; 45 | }; 46 | 47 | #endif // HCSR04_H 48 | --------------------------------------------------------------------------------