DHT11温湿度传感器 wiringPi c程序调试
需要在树莓派上跑一个MQTT客户端,连接DHT11温湿度传感器,将获取到的温度数据定时用MQTT消息发布出去。如果用python完成这个工作其实是很容易了,只是工作需要还得用c。
以前写过DHT11的示例,不过今天把以前的代码找出来跑却拿不到数据。仔细的看了代码,其实是在网络上找的很多朋友都在用代码,没有任何不对的地方,接线也没有问题,wriingPi库也没有问题。迷糊…
实在找不出原因,还是把示波器架上了,按DHT的协议重新实现了一份,或许可以帮到迷糊中的伙伴。
#include <wiringPi.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#define DHTPIN 7
//使用另外一个引脚输出高低电平的方式配合调试
#define DEBUG_PIN_OUT_ENABLE 1
#if DEBUG_PIN_OUT_ENABLE
#define DEBUG_PIN 0
#define DEBUG_PIN_LOW() digitalWrite( DEBUG_PIN, LOW )
#define DEBUG_PIN_HI() digitalWrite( DEBUG_PIN, HIGH )
#endif//DEBUG_PIN_OUT_ENABLE
uint32_t l;
#define WAIT_DHTPIN_HI() l =50000; while (digitalRead(DHTPIN) != HIGH && (l-- > 0))//wait hi
#define WAIT_DHTPIN_LOW() l = 50000; while (digitalRead(DHTPIN) != LOW && (l-- > 0))//wait low
/*DHT11会向主机发送40位(5子节)数据;
第一二个子节数据表示温度值;
第三四个子节数据代表湿度值;
最后一个子节是校验码。如果数据无误的情况下,前4个子节的和等于校验码。*/
//DHT11每一位是0或1的判定方式为,数据位高电平持续时间(us)
void read_dht11_dat()
{
uint8_t i;
uint32_t t1,t2;
int dht11_dat[5] = { 0 };
//存数据位高电平持续时间us
int dht11_bittime[40] = { 0 };
#if DEBUG_PIN_OUT_ENABLE
pinMode(DEBUG_PIN, OUTPUT);
DEBUG_PIN_LOW();
#endif//DEBUG_PIN_OUT_ENABLE
//------
//握手开始
pinMode( DHTPIN, OUTPUT );
digitalWrite( DHTPIN, LOW );
delay( 18 );
#if DEBUG_PIN_OUT_ENABLE
DEBUG_PIN_HI();
#endif//DEBUG_PIN_OUT_ENABLE
digitalWrite( DHTPIN, HIGH );
delayMicroseconds( 40 );
/* prepare to read the pin */
pinMode( DHTPIN, INPUT );
#if DEBUG_PIN_OUT_ENABLE
DEBUG_PIN_LOW();
#endif//DEBUG_PIN_OUT_ENABLE
WAIT_DHTPIN_HI();
//握手结束
//--------
#if DEBUG_PIN_OUT_ENABLE
DEBUG_PIN_HI();
#endif//DEBUG_PIN_OUT_ENABLE
WAIT_DHTPIN_LOW();
for (i = 0; i < 40; i++)
{
WAIT_DHTPIN_HI();
#if DEBUG_PIN_OUT_ENABLE
DEBUG_PIN_LOW();
#endif//DEBUG_PIN_OUT_ENABLE
//LOW->HI 电平拉高后开始计时
t1 = micros();
WAIT_DHTPIN_LOW();
//LOW->HI 电平拉低后停止计时
t2 = micros();
#if DEBUG_PIN_OUT_ENABLE
DEBUG_PIN_HI();
#endif//DEBUG_PIN_OUT_ENABLE
dht11_bittime[i] = t2 - t1;
}
#if DEBUG_PIN_OUT_ENABLE
DEBUG_PIN_HI();
delay(1);
DEBUG_PIN_LOW();
delay(1);
DEBUG_PIN_HI();
#endif//DEBUG_PIN_OUT_ENABLE
for (int i = 0; i < sizeof(dht11_bittime) / sizeof(int); i++)
{
dht11_dat[i / 8] <<= 1;
//大于60us为1,否则为0
if (dht11_bittime[i] > 60)
{
dht11_dat[i / 8] |= 1;
}
}
printf("\n[");
for (int i = 0; i<sizeof(dht11_dat) / sizeof(int); i++)
printf("%d,", dht11_dat[i]);
printf("]\n");
}
int main( void )
{
printf( "Raspberry Pi wiringPi DHT11 Temperature test program\n" );
//wiringPiSetup 采用wiringPi引脚编码
if ( wiringPiSetup() == -1 )
exit( 1 );
while ( 1 )
{
read_dht11_dat();
delay( 1000 ); /* wait 1sec to refresh */
}
return(0);
}
下图为示波器图,黄色为DHT11输出波形,蓝色为调试输出。