【发布时间】:2019-10-08 16:49:34
【问题描述】:
所以,我正在尝试在 C 环境中设置一个 DHT11,以尝试学习更多的嵌入式软件编程。
我在 other sources 和 documentation 的帮助下创建了这个,温度只显示一次,然后默认为 0。
我使用 Arduino 作为微控制器(因为它是我唯一拥有的)并使用 Linux Ubuntu 环境将程序加载到微控制器中。
最后,代码是这样的:
#include <avr/io.h>
#include <stdio.h>
#include <stdlib.h>
#include <util/delay.h>
#include "dht.h"
// Trying to set up the DHT11 so it can be used in this project
void read() {
// The bits are for to get the temperature values in.
// reqCounter is for the request later on.
uint8_t bits[5];
// Setting up the DDRD as OUTPUT and PORTD as HIGH
DDRD |= (1 << DDD5);
PORTD |= (1 << PORTD5);
_delay_ms(100);
/*
* Makes an request to get the data from the DHT11
* Set the the PORTD5 as LOW
*/
PORTD &= ~(1 << PORTD5);
_delay_ms(18);
// Setting it back to high and DDRD as an input
PORTD |= (1 << PORTD5);
_delay_us(1);
DDRD &= ~(1 << DDD5);
/*
* Checking to see if the ACK is happening
*/
_delay_us(39);
if ((PIND & (1 << PIND5))) {
return;
}
_delay_us(80);
if (!(PIND & (1 << PIND5))) {
return;
}
_delay_us(80);
// Holds the temperature
uint8_t temp;
// Reading the data
for (uint8_t i = 0; i < 5; i++) {
// Create a for loop that looks in to every 8 bits
for (uint8_t j = 0; j < 8; j++) {
// While it isn`t high, loop this while loop
while (!(PIND & (1 << PIND5)))
;
_delay_us(30);
// Looking if the input is still high after 30us
if (PIND & (1 << PIND5)) {
temp |= (1 << (7-i));
}
// Wait until the input is low.
while (PIND & (1 << PIND5))
;
}
// Put the temperature in the bit array
bits[i] = temp;
}
// Resets the pins
DDRD |= (1 << DDD5);
PORTD |= (1 << PORTD5);
_delay_ms(100);
uint8_t temperature ;
//checks the sum and gets the temperature
if (bits[0] + bits[1] + bits[2] + bits[3] == bits[4]) {
temperature = bits[2];
}
printf("temperature : %d\n", temperature );
/*printf("%d", bits[0]);
printf("%d", bits[1]);
printf("%d", bits[2]);
printf("%d", bits[3]);
printf("%d\n", bits[4]);*/
}
这只会产生 15 次,然后记录更多。我试图吹它以提高温度,但没有任何反应。
这可能是什么问题?
提前致谢
【问题讨论】:
-
请在第一个 while 循环后仔细检查缩进,它不一致且在逻辑上具有误导性。
-
我对这个
temp |= (1 << (7-i));有一种不好的感觉,感觉它想要一个j而不是i。它最初还使用未初始化的temp。我认为您想在内部for之前将外部for中的温度初始化为0。 -
让我知道我的 cmets 是否解决了这个问题(在这里写一个评论,其中包括“@Yunnosch”)。然后我会给他们一些解释的答案。
-
我知道在等待反馈时我应该耐心等待。但是问一个问题然后上床睡觉是一种习惯,通常会对我的情绪产生一定的影响......
-
我的回答可能无法解决您的问题,但无论如何它在语义上都是不正确的。我不知道
bits[0] + bits[1] + bits[2] + bits[3] == bits[4]的表达方式是什么,或者即使它会起作用,但我正在努力解决这个似是而非的问题——奇怪的代码。指向温度传感器数据表的链接和有关其连接方式的信息会很有帮助,并且会链接到神秘的“其他来源和文档”。很多人都可以在不熟悉 DHT11 或读取它所需的 I/O 和处理的情况下提供帮助。