C++温湿度計
DHT-11とシリアル通信をして温度と湿度を受信します
/******************************************************************************************** *Filename : dht11p.cpp *Description : make a thermometer *Author : Alan *Website : www.osoyoo.com *Update : 2017/07/06 ********************************************************************************************/ #include <wiringPi.h> #include <iostream> #include <iomanip> using namespace std; #define MAXTIMINGS 85 #define DHTPIN 4 //DHT connect to TxD->GPIO4 int dht11_dat[5] ={0,0,0,0,0};//store DHT11 data void read_dht11_dat(); void print_info(); void read_dht11_dat() { unsigned int laststate = HIGH; unsigned int counter = 0; unsigned int j = 0,i; float f;//fahrenheit dht11_dat[0] = dht11_dat[1] = dht11_dat[2] = dht11_dat[3] = dht11_dat[4] = 0; //pull pin down to send start signal pinMode( DHTPIN, OUTPUT ); digitalWrite( DHTPIN, LOW ); delay( 18 ); //pull pin up and wait for sensor response 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( 2 );//1->2 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; cout << "Humidity = " << dec << dht11_dat[0] << "." << dec << dht11_dat[1] << "% Temperature = " << dec << dht11_dat[2] << "." << dec << dht11_dat[3] << "C (" << fixed << setprecision(1) << f << " F)\n"; } else { cout << "Data not good, skip\n"; cout << "[0]=" << hex << dht11_dat[0] << endl; cout << "[1]=" << hex << dht11_dat[1] << endl; cout << "[2]=" << hex << dht11_dat[2] << endl; cout << "[3]=" << hex << dht11_dat[3] << endl; } } void print_info() { cout << "\n"; cout << "|***************************|\n"; cout << "| DHT11 test |\n"; cout << "| --------------------------|\n"; cout << "| DHT11 connect to GPIO4 |\n"; cout << "| --------------------------|\n"; cout << "| OSOYOO|\n"; cout << "|***************************|\n"; cout << "Program is running...\n"; cout << "Press Ctrl+C to end the program\n"; } int main( ) { if ( wiringPiSetupGpio() == -1 ) { cout << "Can't init wiringPi\n"; exit(EXIT_FAILURE); } print_info(); while ( 1 ) { read_dht11_dat(); delay(1000);//wait ls to refresh } return(0); }
時々、受信に失敗しながらも受信してくれます