I am just using nodejs. I wrote a function that returns a variable. When I call that function, I get undefined returned even through the variable I am trying to return has value.
function getDistance() {
var MICROSECDONDS_PER_CM = 1e6 / 34321;
var trigger = new Gpio(23, { mode: Gpio.OUTPUT });
var echo = new Gpio(18, { mode: Gpio.INPUT, alert: true });
trigger.digitalWrite(0); // Make sure trigger is low
var startTick;
var prox;
trigger.trigger(10, 1);
echo.on('alert', (level, tick) => {
if (level == 1) {
startTick = tick;
} else {
var endTick = tick;
var diff = (endTick >> 0) - (startTick >> 0); // Unsigned 32 bit arithmetic
prox = diff / 2 / MICROSECDONDS_PER_CM;
distance = prox;
console.log(prox);
}
});
return prox;
};
Shouldn't it return the prox value ? When I make a call, I get "undefined returned"