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
22 *
33 * Product:
44 * * SparkFun Qwiic Ultrasonic Distance Sensor - HC-SR04 (SEN-1XXXX)
@@ -23,9 +23,15 @@ QwiicUltrasonic myUltrasonic;
2323uint8_t deviceAddress = kQwiicUltrasonicDefaultAddress ; // 0x2F
2424// uint8_t deviceAddress = 0x00;
2525
26+ // Adjust these to your setup.
2627const int triggerPin = 7 ; // Trigger Pin of Ultrasonic Sensor
2728const 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
2935
3036void setup () {
3137
@@ -49,32 +55,26 @@ void setup() {
4955
5056void loop () {
5157
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.
6362
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 ;
6668
67- // Print measurement
68- Serial.print (" Distance (mm): " );
69- Serial.println (distance);
69+ // Print measurement
70+ Serial.print (" Distance (mm): " );
71+ Serial.println (distance);
7072
71- // Serial.println("Distance (cm): ");
72- // Serial.print((distance / 10.0), 2);
73+ // Serial.println("Distance (cm): ");
74+ // Serial.print((distance / 10.0), 2);
7375
74- // Serial.println("Distace (in): ");
75- // Serial.print((distance / 25.4), 2);
76+ // Serial.println("Distace (in): ");
77+ // Serial.print((distance / 25.4), 2);
7678
77- distanceRequested = 0 ;
78- }
7979 delay (500 );
8080}
0 commit comments