As the title says... Chat on...

User avatar
By mickles
#54140 I have a function which needs to query a sensor, then wait some amount of time while the sensor takes a measurement, and then query the sensor again to receive the measurement.

Something along the lines of the code below is what I'd like to do. However, it won't work because the function returns (with no value) before the timer callback runs. Now I could do this by using tmr.delay(), but I'd like to avoid that if at all possible, since these wait times can be quite slow in some cases.

Anyone have any neat ideas on how to hold off returning a value until the sensor conversion is complete?

Code: Select allfunction returnSensor()

  querySensor()

  tmr.alarm(0, 100, tmr.ALARM_SINGLE, function()

    val = querySensor()

    return val

  end)

end
User avatar
By xtal
#54170 You might try modifying the following to fit what you want to do...
-------------------------------------
do_next = c_station -- was 250 ms
tmr.alarm( 0, 500, 1, function() do_next() end) --.5ms chek next do


every .5 ms do_next() is performed 1> c_station then in c station do_next = c_server
2> C_server etc etc ,,,
User avatar
By marcelstoer
#54271
mickles wrote:Anyone have any neat ideas on how to hold off returning a value until the sensor conversion is complete?


I'm not sure I fully understand but I have the feeling you're looking at this from the "wrong" perspective. Lua/NodeMCU is asynchronous and event-driven (reactive if you like buzz words). So, rather than "holding off returning until X" you need to define a callback function to "execute after X happened".
Something like the following may be more promising:

Code: Select allfunction querySensorThenTrigger(callback_func)
  querySensor()
  tmr.alarm(0, 100, tmr.ALARM_SINGLE, function(callback_func)
    querySensor()
    callback_func()
  end)
end