gpt4 book ai didi

c++ - 软 I²C ping 功能

转载 作者:太空狗 更新时间:2023-10-29 23:07:38 28 4
gpt4 key购买 nike

我正在使用软件 I²C实现读取一组 Sensirion SHT21 传感器。我正在尝试找出一种让传感器回答以查看它们是否实际连接到设备的方法。我正在使用 Arduino,这意味着我所有的代码都是 C/C++

我使用的库是 here .

用于读取传感器的代码如下:

#include <Ports.h>
#include <PortsSHT21.h>

//Define soft I²C channels for three sensors
SHT21 hsensor2 (2); // pins A1 and D5 - Sensor 2

//define variables for temp data
float h, t;

void setup() {}

void loop()
{
// Get data from sensor soft I²C
hsensor2.measure(SHT21::HUMI);
hsensor2.measure(SHT21::TEMP);
hsensor2.calculate(h, t);
float hum2 = (h);
float temp2 = (t);
}

最佳答案

大代码块是 measure() 函数的代码。请注意,它在没有执行 connReset() 的情况下在某一时刻返回 0。这应该是一种检测有效设备的方法,例如......

bool hasHUMI;
if (hsensor2.measure(SHT21::HUMI))
{
hasHUMI=true;
}

if (hsensor2.measure(SHT21::HUMI) && hsensor2.measure(SHT21::TEMP))
{
hsensor2.calculate(h, t);
float hum2 = (h);
float temp2 = (t);
}

您的代码应该在读取之前将 h 和 t 清除为 0,以便您可以测试有效值。像这样...

void loop() 
{
h=0.00f;
t=0.00f;
// Get data from sensor soft I²C
hsensor2.measure(SHT21::HUMI);
hsensor2.measure(SHT21::TEMP);
hsensor2.calculate(h, t);
float hum2 = (h);
float temp2 = (t);
if (h>0) {
}
if (t>0) {
}
}

如果没有,那么您可以制作(复制)您自己的 measure() 函数版本,该函数测试 meas[type] 中的有效返回值。您需要在读取之前将 meas[type] 设置为已知的无效值(例如 0)。

uint8_t SHT21::measure(uint8_t type, void (*delayFun)()) {

start();
writeByte(type == TEMP? MEASURE_TEMP : MEASURE_HUMI)

for (uint8_t i = 0; i < 250; ++i) {
if (!digiRead()) {
meas[type] = readByte(1) << 8;
meas[type] |= readByte(1);
uint8_t flipped = 0;

for (uint8_t j = 0x80; j != 0; j >>= 1) {
flipped >>= 1;
}

if (readByte(0) != flipped)
break;

return 0;
}


if (delayFun)
delayFun();
else
delay(1);
}

connReset();
return 1;
}

您可能知道,如果您向库 cpp 添加方法,那么您还需要向 .h 添加相应的原型(prototype),否则 arduino 将无法编译您的代码。

.cpp

uint8_t SHT21::measureTest(uint8_t type, void (*delayFun)()) {

}

.h

uint8_t measureTest(uint8_t type, void (*delayFun)() =0);

关于c++ - 软 I²C ping 功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12250759/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com