As the title says... Chat on...
User avatar
By JBFUK
#78519 Hi all,

I'm very new to NodeMCU and LUA having previously tinkered quite a lot with Arduino.

My little introduction project is to collect environmental information and store it away in a database for analysis. I have this running successfully using a DHT sensor.

I now want to expand this to use a waterproof DS18b20 temperature probe. Using the inbuilt C library I am able to read the temperature from a probe but I'm struggling with how to pass the value back to the rest of my application.

Essentially I want to define a function, 'read_DS18B20_Temp' to which I pass the pin number the sensor is connected to, and it will return the temperature. I've done something with the DHT sensor and it works fine.

This is my current attempt:

Code: Select allfunction read_DS18B20_Temp(ds18B20_pin)

  local T

  -- Setup Sensor
  ds18b20.setup(ds18B20_pin)

  local function readout(INDEX, ROM, RES, TEMP, TEMP_DEC, PAR)
    print(TEMP)
    return TEMP
  end

  -- Read Sensor
  T = ds18b20.read(readout,{})

  --Return temp
 print(T)
  return T

end


If I call this function from my main app like 'DS_T1 = read_DS18B20_Temp(2)' then DS_T1 is always 'nil'. Monitoring the terminal, I notice that the printing of the temperature is somewhat delayed and shows up on the terminal after the execution of read_DS18B20_Temp() completes. I can tell this because I see 'nil' printed before the temp. I presume this 'nil' comes from the 'print(T)' command.

I have tried setting T=TEMP within the readout() function but it does the same thing.

I appreciate that the sensor is slow to read and return a value, I don't mind that, but I want my read_DS18B20_Temp() function to wait for the sensor read to complete and return the temperature value to my main application.

If I use a global variable and write to that in the readout function, it does get set at the same time as the print command kicks in. This isn't really workable as I want to be able to have multiple sensors on different pins, call read_DS18B20_Temp(pin) and get the reading from that sensor returned.

It seems this must be possible but I've hit a bit of a roadblock due to inexperience.

Could somebody tell me where I'm going wrong, or if I'm trying to do something that just isn't possible with the way that the ds18b20 library works.

Thanks.
User avatar
By JBFUK
#78594 Answering my own question. In the end I gave up trying to get the built-in ds18b20 module to work the way I wanted and used a function to manually detect/query the sensor using the OneWire (ow) library.