获取温湿度传感器数据的代码

电源接的3v

c语言版

#include 
#include 
#include 
 
typedef unsigned char uint8;
typedef unsigned int  uint16;
typedef unsigned long uint32;
 
#define HIGH_TIME 32
 
int pinNumber = 2;  //use gpio1 to read data
uint32 databuf;
 
uint8 readSensorData(void)
{
    uint8 crc; 
    uint8 i;
 
    pinMode(pinNumber,OUTPUT); // set mode to output
    digitalWrite(pinNumber, 1); // output a low level
    delayMicroseconds(4);
    digitalWrite(pinNumber, 0); // output a high level 
    delay(25);
    digitalWrite(pinNumber, 1); // output a low level
    delayMicroseconds(60); 
    pinMode(pinNumber, INPUT); // set mode to input
    pullUpDnControl(pinNumber,PUD_UP);
 
    if(digitalRead(pinNumber)==0) //SENSOR ANS
    {
        while(!digitalRead(pinNumber)); //wait to high
        delayMicroseconds(80);
        for(i=0;i<32;i++)
        {
            while(digitalRead(pinNumber)); //data clock start
            while(!digitalRead(pinNumber)); //data start
            delayMicroseconds(HIGH_TIME);
            databuf*=2;
            if(digitalRead(pinNumber)==1) //1
            {
                databuf++;
            }
        }
 
        for(i=0;i<8;i++)
        {
            while(digitalRead(pinNumber)); //data clock start
            while(!digitalRead(pinNumber)); //data start
            delayMicroseconds(HIGH_TIME);
            crc*=2;  
            if(digitalRead(pinNumber)==1) //1
            {
                crc++;
            }
        }
        return 1;
    } else {
        return 0;
    }
}
int main (void)
{
    if (-1 == wiringPiSetup()) {
        printf("Setup wiringPi failed!");
        return 1;
    }
 
    pinMode(pinNumber, OUTPUT); // set mode to output
    digitalWrite(pinNumber,1); // output a high level 
 
    pinMode(pinNumber,OUTPUT); // set mode to output
    digitalWrite(pinNumber,1); // output a high level 
    if(readSensorData())
    {
        printf("RH:%ld.%ld\n",(databuf>>24)&0xff,(databuf>>16)&0xff); 
        printf("TMP:%ld.%ld\n",(databuf>>8)&0xff,databuf&0xff);
        databuf=0;
    } else {
        printf("Error!\n");
        databuf=0;
    }
    return 0;
}

编译命令:
gcc -Wall -o dht11 mydht11.c -lwiringPi

python版

import Adafruit_DHT
  
# Set sensor type : Options are DHT11,DHT22 or AM2302
sensor=Adafruit_DHT.DHT11
  
# Set GPIO sensor is connected to
gpio=27
  
# Use read_retry method. This will retry up to 15 times to
# get a sensor reading (waiting 2 seconds between each retry).
humidity, temperature = Adafruit_DHT.read_retry(sensor, gpio)
  
# Reading the DHT11 is very sensitive to timings and occasionally
# the Pi might fail to get a valid reading. So check if readings are valid.
if humidity is not None and temperature is not None:
  print('Temp={0:0.1f}*C  Humidity={1:0.1f}%'.format(temperature, humidity))
else:
  print('Failed to get reading. Try again!')

你可能感兴趣的:(获取温湿度传感器数据的代码)