ksonic(hcsr04)

koadrobot/devices/ksonic(hcsr04)

No description
ksonic(hcsr04)
@/ksonic(hcsr04)
TRIGport
Board port to which sensor’s `trig` pin is connected.
ECHOport
Board port to which sensor’s `echo` pin is connected.
MAXnumber
Max distance in meter.
S0Snumber
Sound of Speed cm/sec.
PINGpulse
Triggers new ultrasonic ping which would result in the output update once sound echo will be captured. Pulses coming within 60 ms window after last one are ignored to fight sensor’s PCB resonance.
ksonic(hcsr04)
TRIG
ECHO
MAX
S0S
PING
DIST
DONE
DONEpulse
Fires when ping is done
DISTnumber
Last measured distance in meters.
To use the node in your project you should have the koadrobot/devices library installed. Use the “File → Add Library” menu item in XOD IDE if you don’t have it yet. See Using libraries for more info.

C++ implementation

struct State {
};

{{ GENERATED_CODE }}

void evaluate(Context ctx) {

    if (!isInputDirty<input_PING>(ctx))
        return;

    uint8_t echoPort = (uint8_t)getValue<input_ECHO>(ctx);
    uint8_t trigPort = (uint8_t)getValue<input_TRIG>(ctx);
    Number max = getValue<input_MAX>(ctx);

    uint32_t Max_RoundTrip = (uint32_t)(2000000 * max / getValue<input_SOS>(ctx));
    
    // Request measurement: make a pulse for 10 μs.
    pinMode(trigPort, OUTPUT);
    // short pulse for clean high
    digitalWrite(trigPort, LOW);
    delayMicroseconds(5);
    digitalWrite(trigPort, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPort, LOW);

    // Wait for echo pin rise which means ultrasonic burst success
    uint32_t maxUs = micros() + Max_RoundTrip;
    pinMode(echoPort, INPUT);
    while (digitalRead(echoPort) == LOW) {
        if (micros() > maxUs) {
            emitValue<output_DIST>(ctx, max);
            emitValue<output_DONE>(ctx, 1);
            return;
        }
    }

    // Now wait for echo line to be pulled back low which means echo capture
    uint32_t tStart = micros();

    maxUs = tStart + Max_RoundTrip;
    while (digitalRead(echoPort) == HIGH) {
        if (micros() > maxUs) {
            emitValue<output_DIST>(ctx, -max);
            emitValue<output_DONE>(ctx, 1);
            return;
        }
    }

    Number dist = ((micros() - tStart) * sos * 0.5);
    dist = (dist > max) ? max : (dist < 0) ? 0 : dist ;

    emitValue<output_DIST>(ctx, max);
    emitValue<output_DONE>(ctx, 1);

}

Tabular tests

ENINOUT
false00
true00
false320
true1010
true0.30.3