温湿度传感器

湿度温度传感器电路

MicroPython 代码示例 运行在 Raspberry Pi Pico 2 W 微控制器上 在面包板上连接温湿度传感器模块 (DHT11) 和 OLED 显示模块 (SSD1306)。 测量并显示相对湿度和环境温度,单位分别为摄氏度和华氏度

温湿度传感器测量环境温度和空气湿度. 在机器人领域,大多数电子元件都内置了温度传感器。. 它们可用于热保护,例如在温度超过安全限度时自动关闭机器人。. 你知道吗?智能手机内部大约有8个不同的温度传感器,分别用于测量屏幕温度、背部温度、电池温度、CPU温度等等。湿度传感器则用于监测智能手机或智能手表内部的冷凝情况。.

这是DHT11传感器. 我们导入 dht 库并按如下所示设置 GP28 引脚:

1
2
3
4
5
6
from time import sleep
from machine import Pin
from oled import OLED
from dht import DHT11

humidity_temp_sensor = DHT11(Pin(28))

然后,在主循环中,我们使用测量函数来获取温度和湿度。. 我们可以使用简单的数学公式将摄氏度转换为华氏度。.

1
2
3
4
5
6
7
while True:
    humidity_temp_sensor.measure()
    humidity = humidity_temp_sensor.humidity()
    temp_c = humidity_temp_sensor.temperature()
    temp_f = temp_c * 9/5 + 32
    oled.print(f"{humidity:.0f}% Humidity", f"{temp_c:.1f} Degrees C", f"{temp_f:.1f} Degrees F")
    sleep(0.5)

要运行完整脚本,请在 Thonny 中创建一个名为 humidity_temp_sensor.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
print("\nHumidity Temp Sensor")

# DESCRIPTION

# A humidity and temperature sensor measures the ambient temperature and air humidity.
# In robotics, temperature sensors are built into most electronic components. 
# They can be used for thermal protection, such as to automatically shutdown a robot 
# when temperatures exceed safe limits. Did you know that a smartphone has about 8 different
# temperature sensors in it, measuring screen temperature, back temperature, 
# battery temperature, CPU temperature, etc.? Humidity sensors monitor condensation 
# inside a smartphone or smartwatch.

# CONNECTIONS REQUIRED

# Connect Humidity and Temperature Sensor (KY-015) module 
# (it includes a big blue waffle block)
#   Pins: + => VCC, OUT => GP28, - => GND

from time import sleep
from machine import Pin
from oled import OLED
from dht import DHT11

humidity_temp_sensor = DHT11(Pin(28))
oled = OLED(scl_pin=15, sda_pin=14)

try:
    while True:
        humidity_temp_sensor.measure()
        humidity = humidity_temp_sensor.humidity()
        temp_c = humidity_temp_sensor.temperature()
        temp_f = temp_c * 9/5 + 32
        oled.print(f"{humidity:.0f}% Humidity", f"{temp_c:.1f} Degrees C", f"{temp_f:.1f} Degrees F")
        sleep(0.5)

except KeyboardInterrupt:
    print("\nInterrupted by user!")

finally:
    oled.reset()

返回顶部

让教师和学生更容易参与动手发明创造.
© 2026 Inventor Pi, Inc.
Inventor Pi, Inc.是一家注册的 501(c)(3) 非营利组织