DHT11 Temperature and Humidity Sensor with Raspberry Pi Pico W
Introduction
Exploring DHT11 Temperature and Humidity Sensor with Raspberry Pi Pico W- The Raspberry Pi Pico W is a powerful microcontroller board that offers a wide range of possibilities for DIY projects. One of the many sensors that can be integrated with the Pico W is the DHT11 temperature and humidity sensor. In this article, we will explore how to connect and read data from the DHT11 sensor using the Raspberry Pi Pico W.
Connecting the DHT11 Sensor to Raspberry Pi Pico W:
To connect the DHT11 sensor to the Raspberry Pi Pico W, you will need a few components:
*Please Note: These are affiliate links. I may make a commission if you buy the components through these links. I would appreciate your support in this way!
What is the DHT11 Sensor?
The DHT11 is a low-cost digital temperature and humidity sensor that uses a capacitive humidity sensor and a thermistor to measure the surrounding air conditions. It provides reliable readings with a temperature range of 0°C to 50°C and a humidity range of 20% to 90%.
Humidity Measuring
Humidity Range: 20-80% RH (Relative Humidity).
Humidity Accuracy: ±5% RH.
Humidity Resolution: 1% RH.
Temperature Measuring
Temperature Range: 0-50°C.
Temperature Accuracy: ±2°C.
Temperature Resolution: 1°C.
Other Specifications
Operating Voltage: 3 to 5.5 Volts.
Output: Digital signal.
Sampling Rate: Measurement can be taken every second.
Long-term Stability: <±1% RH/year.
Size and Dimensions: Small, easy to integrate into systems and devices.
Ease of Use: Simple digital control and output, straightforward interfacing with microcontrollers like Arduino and Raspberry Pi.
Power Consumption: Low, suitable for battery-operated applications.
Response Time: Humidity – 5s, Temperature – 1s.
DHT11 Temperature and Humidity Sensor with Pi Pico W:
Connect the VCC pin of the DHT11 sensor to the 3.3V pin on the Raspberry Pi Pico W.
Connect the GND pin of the DHT11 sensor to the GND pin on the Raspberry Pi Pico W.
Connect the DATA pin of the DHT11 sensor to any GPIO pin on the Raspberry Pi Pico W. In this example, we will use GPIO pin 16.
Once the connections are made, you are ready to write the code to read data from the DHT11 sensor.
dht library:
Ensure that the dht library is installed on your Raspberry Pi Pico W. To do this, simply create a new file in your IDE, paste the following dht library code into it, and save the file with the name ‘dht.py‘.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 |
import array import micropython import utime from machine import Pin from micropython import const class InvalidChecksum(Exception): pass class InvalidPulseCount(Exception): pass MAX_UNCHANGED = const(100) MIN_INTERVAL_US = const(200000) HIGH_LEVEL = const(50) EXPECTED_PULSES = const(84) class DHT11: _temperature: float _humidity: float def __init__(self, pin): self._pin = pin self._last_measure = utime.ticks_us() self._temperature = -1 self._humidity = -1 def measure(self): current_ticks = utime.ticks_us() if utime.ticks_diff(current_ticks, self._last_measure) < MIN_INTERVAL_US and ( self._temperature > -1 or self._humidity > -1 ): # Less than a second since last read, which is too soon according # to the datasheet return self._send_init_signal() pulses = self._capture_pulses() buffer = self._convert_pulses_to_buffer(pulses) self._verify_checksum(buffer) self._humidity = buffer[0] + buffer[1] / 10 self._temperature = buffer[2] + buffer[3] / 10 self._last_measure = utime.ticks_us() @property def humidity(self): self.measure() return self._humidity @property def temperature(self): self.measure() return self._temperature def _send_init_signal(self): self._pin.init(Pin.OUT, Pin.PULL_DOWN) self._pin.value(1) utime.sleep_ms(50) self._pin.value(0) utime.sleep_ms(18) @micropython.native def _capture_pulses(self): pin = self._pin pin.init(Pin.IN, Pin.PULL_UP) val = 1 idx = 0 transitions = bytearray(EXPECTED_PULSES) unchanged = 0 timestamp = utime.ticks_us() while unchanged < MAX_UNCHANGED: if val != pin.value(): if idx >= EXPECTED_PULSES: raise InvalidPulseCount( "Got more than {} pulses".format(EXPECTED_PULSES) ) now = utime.ticks_us() transitions[idx] = now - timestamp timestamp = now idx += 1 val = 1 - val unchanged = 0 else: unchanged += 1 pin.init(Pin.OUT, Pin.PULL_DOWN) if idx != EXPECTED_PULSES: raise InvalidPulseCount( "Expected {} but got {} pulses".format(EXPECTED_PULSES, idx) ) return transitions[4:] def _convert_pulses_to_buffer(self, pulses): """Convert a list of 80 pulses into a 5 byte buffer The resulting 5 bytes in the buffer will be: 0: Integral relative humidity data 1: Decimal relative humidity data 2: Integral temperature data 3: Decimal temperature data 4: Checksum """ # Convert the pulses to 40 bits binary = 0 for idx in range(0, len(pulses), 2): binary = binary << 1 | int(pulses[idx] > HIGH_LEVEL) # Split into 5 bytes buffer = array.array("B") for shift in range(4, -1, -1): buffer.append(binary >> shift * 8 & 0xFF) return buffer def _verify_checksum(self, buffer): # Calculate checksum checksum = 0 for buf in buffer[0:4]: checksum += buf if checksum & 0xFF != buffer[4]: raise InvalidChecksum() |
Reading Data from the DHT11 Sensor Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
from machine import Pin import dht import time # DHT11 sensor setup sensor_pin = Pin(16, Pin.IN, Pin.PULL_UP) dht_sensor = dht.DHT11(sensor_pin) # Web server loop while True: try: # Read sensor dht_sensor.measure() temp = dht_sensor.temperature # Access as property, not method hum = dht_sensor.humidity # Access as property, not method # Print the values if the sensor is working print("Temperature:", temp, "°C") print("Humidity:", hum, "%") except Exception as e: # Print an error message if there's an issue with the sensor print("Failed to read from the sensor:", str(e)) # Delay before the next read time.sleep(2) |
The code snippet above initializes the DHT11 sensor on GPIO pin 16 and continuously reads and prints the temperature and humidity values. If there is an error reading the data, it will display an error message.
Interpreting the Data
Once you run the code, you will see the temperature and humidity values printed in the console. The temperature will be displayed in Celsius, and the humidity will be displayed as a percentage.
applying some heat
It is important to note that the DHT11 sensor has a limited accuracy and response time compared to more advanced sensors. Therefore, it is recommended to use it for general temperature and humidity monitoring rather than critical applications.
Conclusion
The DHT11 sensor is a cost-effective solution for measuring temperature and humidity with the Raspberry Pi Pico W. By following the steps outlined in this article, you can easily connect and read data from the DHT11 sensor. Whether you are building a weather station or monitoring the conditions in a greenhouse, the combination of the Raspberry Pi Pico W and DHT11 sensor offers a versatile and affordable solution.
Remember to experiment with different GPIO pins and explore additional functionalities of the DHT11 sensor to expand your project possibilities.