1
- /* SparkFun Ulrasonic Distance Sensor - Example 2 Basic Distance Sensing using Trigger and Echo Pins.
1
+ /* SparkFun Ulrasonic Distance Sensor - Example 3 - Distance using Trigger and Echo Pins
2
2
*
3
3
* Product:
4
4
* * SparkFun Qwiic Ultrasonic Distance Sensor - HC-SR04 (SEN-1XXXX)
@@ -23,9 +23,15 @@ QwiicUltrasonic myUltrasonic;
23
23
uint8_t deviceAddress = kQwiicUltrasonicDefaultAddress ; // 0x2F
24
24
// uint8_t deviceAddress = 0x00;
25
25
26
+ // Adjust these to your setup.
26
27
const int triggerPin = 7 ; // Trigger Pin of Ultrasonic Sensor
27
28
const int echoPin = 8 ; // Echo Pin of Ultrasonic Sensor
28
- int distanceRequested = 0 ;
29
+
30
+ // Used for distance calculation
31
+ float distance = 0.0 ;
32
+ float duration = 0.0 ;
33
+ const float speedOfSound = 340.00 ; // Speed of sound in m/s
34
+ const float convMilli= 1000.00 ; // Speed of sound in m/s
29
35
30
36
void setup () {
31
37
@@ -49,32 +55,26 @@ void setup() {
49
55
50
56
void loop () {
51
57
52
- if (distanceRequested == 0 )
53
- {
54
- // To trigger we write the pin high and then back to its resting state.
55
- digitalWrite (triggerPin, HIGH);
56
- delay (5 );
57
- digitalWrite (triggerPin, LOW);
58
- // We don't want continually trigger while data is being retrieved from the sensor.
59
- distanceRequested = 1 ;
60
- }
61
-
62
- if (digitalRead (echoPin) == HIGH) {
58
+ digitalWrite (triggerPin, HIGH);
59
+ delay (5 );
60
+ digitalWrite (triggerPin, LOW);
61
+ // We don't want continually trigger while data is being retrieved from the sensor.
63
62
64
- uint16_t distance = 0 ;
65
- myUltrasonic.getTriggeredDistance (distance);
63
+ duration = pulseIn (echoPin, HIGH);
64
+ // Time until sound detected * speed of sound * conversion to mm
65
+ // Divide by two because we only want the time the wave traveled to the object,
66
+ // not to the object and back.
67
+ distance = (duration * speedOfSound * convMilli) / 2 ;
66
68
67
- // Print measurement
68
- Serial.print (" Distance (mm): " );
69
- Serial.println (distance);
69
+ // Print measurement
70
+ Serial.print (" Distance (mm): " );
71
+ Serial.println (distance);
70
72
71
- // Serial.println("Distance (cm): ");
72
- // Serial.print((distance / 10.0), 2);
73
+ // Serial.println("Distance (cm): ");
74
+ // Serial.print((distance / 10.0), 2);
73
75
74
- // Serial.println("Distace (in): ");
75
- // Serial.print((distance / 25.4), 2);
76
+ // Serial.println("Distace (in): ");
77
+ // Serial.print((distance / 25.4), 2);
76
78
77
- distanceRequested = 0 ;
78
- }
79
79
delay (500 );
80
80
}
0 commit comments