学习arduino遇到点疑惑,请大家帮忙指点下怎么办?
arduino使用dht22温湿度传感器按照参考教程需要导入一个头文件dht,使用时要调用相关函数,读出具体的温湿度,从而打印输出。
但是很多传感器并非为arduino设计,但是可以兼容使用。没有现成的头文件,这种情况怎么arduino如何接受数字信号呢?
我查了很多资料,只能查到数字引脚可以通过判断low还是high来输出0或者1,但是像温湿度传感器这样的,输出内容不会这么简单,至少是整数或者是小数,因此怎么样才能让arduino接收到数字传感器所发出的8bits数据呢
因为是初学者,对于传感器所说的Data bits不理解,这个8bits的到底能表达一个多大数据量呢,看起来不应该只是0和1,感觉应该更大一点
最好找传感器厂商要接口, 想了解原理的话读一下dht的库源代码就好了, 很好理解的.
int dht11::read(int pin)
{
// BUFFER TO RECEIVE
uint8_t bits[5];
uint8_t cnt = 7;
uint8_t idx = 0;
// EMPTY BUFFER
for (int i=0; i< 5; i++) bits[i] = 0;
// REQUEST SAMPLE 请求采样
pinMode(pin, OUTPUT);
digitalWrite(pin, LOW);
delay(18);
digitalWrite(pin, HIGH);
delayMicroseconds(40);
pinMode(pin, INPUT);
// ACKNOWLEDGE or TIMEOUT
unsigned int loopCnt = 10000;
while(digitalRead(pin) == LOW)
if (loopCnt-- == 0) return DHTLIB_ERROR_TIMEOUT;
loopCnt = 10000;
while(digitalRead(pin) == HIGH)
if (loopCnt-- == 0) return DHTLIB_ERROR_TIMEOUT;
// READ OUTPUT - 40 BITS => 5 BYTES or TIMEOUT 共需读取5个字节x8=40比特
for (int i=0; i<40; i++)
{
loopCnt = 10000;
while(digitalRead(pin) == LOW)
if (loopCnt-- == 0) return DHTLIB_ERROR_TIMEOUT;
unsigned long t = micros();
loopCnt = 10000;
while(digitalRead(pin) == HIGH)
if (loopCnt-- == 0) return DHTLIB_ERROR_TIMEOUT;
if ((micros() - t) > 40) bits[idx] |= (1 << cnt);
if (cnt == 0) // next byte?
{
cnt = 7; // restart at MSB
idx++; // next byte!
}
else cnt--;
}
// WRITE TO RIGHT VARS
// as bits[1] and bits[3] are allways zero they are omitted in formulas. 字节1和3总是零
humidity = bits[0]; //湿度
temperature = bits[2]; //温度
uint8_t sum = bits[0] + bits[2];
if (bits[4] != sum) return DHTLIB_ERROR_CHECKSUM; //校验
return DHTLIB_OK;
}