如何解决在 Arduino 的实例中创建一个实例
我有一个 TemperatureSensor
类,它在自身内部创建 OneWire
和 Dallastemperature
并显示实际温度。问题是当我创建它时,它不起作用。我感觉到与在 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 举报,一经查实,本站将立刻删除。