在 Arduino 的实例中创建一个实例

问题描述

我有一个 TemperatureSensor 类,它在自身内部创建 OneWireDallastemperature显示实际温度。问题是当我创建它时,它不起作用。我感觉到与在 Attach 方法中创建的对象范围相关的非常奇怪的行为。

如果我从外部向 Dallastemperature 方法提供 Attach 实例,则一切正常。如果我尝试在类中实例化它 - 则草图不起作用,温度始终为 -127.0C

我尝试实例化构造函数初始化列表中的成员 - 结果相同。 我做错了什么?

#include <OneWire.h>
#include <Dallastemperature.h>

class CTemperatureSensor {
    private:
        OneWire *ow;
        Dallastemperature *dt;
        float toF(float c);
    public:
        float Celsius;
        float Fahrenheit;
        void Attach(uint8_t SignalPin,Dallastemperature *_dt = NULL);
        void Read();
};

void CTemperatureSensor::Attach(uint8_t SignalPin,Dallastemperature *_dt) {
    if (_dt == NULL) {
        // This branch does not work: the sensor returns -127.0.
        // All other devices behave in the same way:
        // instantiating an object inside another object creates weird behavior.
        ow = &OneWire(SignalPin);
        dt = &Dallastemperature(ow);
    } else {
        // When OneWire and Dallastemperature are declared directly in the sketch
        // and supplied as a refence,all seems to work.
        dt = _dt;
    }
    pinMode(SignalPin,INPUT);
    Celsius = 0;
    Fahrenheit = toF(Celsius);
}

void CTemperatureSensor::Read() {
    dt->requestTemperatures(); 
    Celsius = dt->getTempCByIndex(0);
    Fahrenheit = toF(Celsius);
}

float CTemperatureSensor::toF(float c) {
    return (c * 9.0) / 5.0 + 32.0; }

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)