Last active
August 29, 2015 14:18
-
-
Save yenjoji/a7444e5f2ddb4a94ca5f to your computer and use it in GitHub Desktop.
Raspberry Pi で DHT11を使うプログラムのMackerel対応版
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* dht11.c: | |
* Simple test program to test the wiringPi functions | |
* DHT11 test | |
*/ | |
#include <wiringPi.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <stdint.h> | |
#include <time.h> | |
#include <inttypes.h> | |
#define MAXTIMINGS 85 | |
#define DHTPIN 7 | |
int dht11_dat[5] = { 0, 0, 0, 0, 0 }; | |
int read_dht11_dat() | |
{ | |
uint8_t laststate = HIGH; | |
uint8_t counter = 0; | |
uint8_t j = 0, i; | |
float f; /* fahrenheit */ | |
time_t epoch_time; | |
dht11_dat[0] = dht11_dat[1] = dht11_dat[2] = dht11_dat[3] = dht11_dat[4] = 0; | |
/* pull pin down for 18 milliseconds */ | |
pinMode( DHTPIN, OUTPUT ); | |
digitalWrite( DHTPIN, LOW ); | |
delay( 18 ); | |
/* then pull it up for 40 microseconds */ | |
digitalWrite( DHTPIN, HIGH ); | |
delayMicroseconds( 40 ); | |
/* prepare to read the pin */ | |
pinMode( DHTPIN, INPUT ); | |
/* detect change and read data */ | |
for ( i = 0; i < MAXTIMINGS; i++ ) | |
{ | |
counter = 0; | |
while ( digitalRead( DHTPIN ) == laststate ) | |
{ | |
counter++; | |
delayMicroseconds( 1 ); | |
if ( counter == 255 ) | |
{ | |
break; | |
} | |
} | |
laststate = digitalRead( DHTPIN ); | |
if ( counter == 255 ) | |
break; | |
/* ignore first 3 transitions */ | |
if ( (i >= 4) && (i % 2 == 0) ) | |
{ | |
/* shove each bit into the storage bytes */ | |
dht11_dat[j / 8] <<= 1; | |
if ( counter > 16 ) | |
dht11_dat[j / 8] |= 1; | |
j++; | |
} | |
} | |
/* | |
* check we read 40 bits (8bit x 5 ) + verify checksum in the last byte | |
* print it out if data is good | |
*/ | |
if ( (j >= 40) && | |
(dht11_dat[4] == ( (dht11_dat[0] + dht11_dat[1] + dht11_dat[2] + dht11_dat[3]) & 0xFF) ) ) | |
{ | |
f = dht11_dat[2] * 9. / 5. + 32; | |
/* mackerel 対応のフォーマットで結果を出力 */ | |
epoch_time = time(NULL); | |
printf( "room.%d.temperatre\t%d.%d\t%d\n", DHTPIN, dht11_dat[2], dht11_dat[3], (uintmax_t)epoch_time); | |
printf( "room.%d.humidity\t%d.%d\t%d\n", DHTPIN, dht11_dat[0], dht11_dat[1], (uintmax_t)epoch_time); | |
return 1; | |
}else { | |
fprintf(stderr, "Data not good, will retry\n"); | |
return 0; | |
} | |
} | |
int main( void ) | |
{ | |
int result = 0; | |
if ( wiringPiSetup() == -1 ) | |
exit( 1 ); | |
/* センサーから値が取れるまでループし、一回取得したら終了する */ | |
while ( result == 0 ) { | |
result = read_dht11_dat(); | |
delay( 100 ); | |
} | |
return(0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment