DS18B20 sensor code for arduino ide not working on platformio

This is what i am trying to do,

class TEMP
{
private:

#define ONE_WIRE_BUS 26
OneWire oneWire(ONE_WIRE_BUS); 
DallasTemperature sensors(&oneWire);
public:
    TEMP();
    float getTemp();
};

and I have tried to crate them in the constructor but cannot return the values.

float TEMP::getTemp(){

}
TEMP::TEMP(){
    // Setup a oneWire instance to communicate with any OneWire devices  
// (not just Maxim/Dallas temperature ICs) 
OneWire oneWire(ONE_WIRE_BUS); 
// Pass our oneWire reference to Dallas Temperature. 
DallasTemperature sensors(&oneWire);
 sensors.begin(); 
}

Thanks

How can I create new object from the OneWire library and DallasTemperature library to use the sensor, vscode gives me this error.
image

We can’t say anything about this error without the platformio.ini.

this is my ini file

[env:esp32dev]
platform = espressif32
board = esp32dev
framework = arduino
lib_extra_dirs = ~/Documents/Arduino/libraries

Well this does not work anyways, you have to use use constructor initializer lists here. But the code you’ve shown that errors out is

See https://stackoverflow.com/a/11491003/5296568:

You can initialize the data members at the point of declaration, but not with () brackets:

Which means with a slight modifications this works

However, this is still all static data. What you should be doing is allow the class to have a construcot with the one wire pin and then forward that into the constructors of the underlying objects…

#include <Arduino.h>
#include <OneWire.h>
#include <DallasTemperature.h>

class TEMP
{
private:
    OneWire oneWire;
    DallasTemperature sensors;
public:
    TEMP(uint8_t pin) : 
        oneWire(pin), sensors(&oneWire) {}
    float getTemp() {
        DeviceAddress addr;
        sensors.getAddress(addr, 0);
        return sensors.getTempC(addr);
    }
};

#define ONE_WIRE_BUS 26
TEMP temp(ONE_WIRE_BUS);

void setup() {}
void loop() { float t = temp.getTemp(); }
1 Like