我有一个DHT11传感器,一个带有3个连接器的pcb,连接到arduino。当我尝试从该传感器读取值时,会得到它们,但更多时候却得到校验和错误。如果我忽略此错误,但传感器仍在工作,但我想知道为什么出现此错误。
这只是为了尝试传感器并学习arduino,所以没有什么关键的。我刚学过arduino,所以我是新手。我已经编写了一个完整的Web界面,用于与Python中的树莓派上的可寻址LED灯条进行交互。 '
void start_test()
{
digitalWrite(DHpin, LOW); //Pull down the bus to send the start signal
delay(30); //The delay is greater than 18 ms so that DHT 11 can detect the start signal
digitalWrite(DHpin, HIGH);
delayMicroseconds(40); //Wait for DHT11 to respond
pinMode(DHpin, INPUT);
while(digitalRead(DHpin) == HIGH);
delayMicroseconds(80); //The DHT11 responds by pulling the bus low for 80us;
if(digitalRead(DHpin) == LOW)
delayMicroseconds(80); //DHT11 pulled up after the bus 80us to start sending data;
for(int i = 0; i < 5; i++) //Receiving temperature and humidity data, check bits are not considered;
dat[i] = read_data();
pinMode(DHpin, OUTPUT);
digitalWrite(DHpin, HIGH); //After the completion of a release of data bus, waiting for the host to start the next signal
}
byte read_data()
{
byte i = 0;
byte result = 0;
for (i = 0; i < 8; i++) {
while (digitalRead(DHpin) == LOW); // wait 50us
delayMicroseconds(30); //The duration of the high level is judged to determine whether the data is '0' or '1'
if (digitalRead(DHpin) == HIGH)
result |= (1 << (8 - i)); //High in the former, low in the post
while (digitalRead(DHpin) == HIGH); //Data '1', waiting for the next bit of reception
}
return result;
}
void loop()
{
start_test();
//Serial.println(total);
humidone = dat[0];
humiddec = dat[1];
tempone = dat[2];
tempdec = dat[3];
checksum = dat[0] + dat[1] + dat[2] + dat[3];
Serial.print(checksum, BIN);
Serial.println("checksum ");
Serial.print(dat[4], BIN);
Serial.println("dat4 ");
if ((dat[4]) != checksum){
Serial.println("-- Checksum Error!");
delay(100);
}
else{
//Serial.println("-- OK");
temp = tempone + '.' + tempdec;
humid = humidone + '.' + humiddec;
Serial.print(humid);
Serial.print(",");
Serial.println(temp);
humidprev = humid;
tempprev = temp;
tempint = temp.toInt() * 10;
ledbright = map(tempint, 250, 290, 0, 255);
Serial.println(ledbright, DEC);
analogWrite(ledpin, ledbright);
Serial.println(' ');
delay(3000);
}
}
上面我已经输入了代码。这是我从互联网上获得的一个示例,但他们没有对此错误说任何话。我还尝试了其他示例,但这些示例根本不起作用或存在相同的错误。问题出在程序控制针对dat [4]的校验和(dat [0] + dat [1] + dat [3])时。这些应该是相同的,但通常不是。 dat [4]是8位的二进制数。如果我以binairy的形式将校验和和dat [4]记录到Serial.monitor中,我会发现它通常只是一个1,在校验和中未更改,但在dat [4]中已更改。但我找不到为什么会这样。
有人知道为什么我会收到此校验和错误以及如何解决吗?我非常感谢帮助,因为我是arduino和电子行业的新手,我想学习。
谢谢!