如何根据Python中的用户输入运行各种温度读数?

问题描述 投票:0回答:1

关于Python(对于Raspberry Pi)编程,我是一个完全的业余爱好者,我想要实现的目标是询问用户所需的样本数量,然后读取并打印出如此数量的样本,每个读数之间都用一个简单的按键分开。

我所拥有的是一个简单的设置,带有DHT11温湿度传感器,一个10KΩ电阻,几根跨接电缆,当然还有一块面包板。按照以下代码进行测试时,该电路可以正常工作:

import Adafruit_DHT
import time

DHT_SENSOR = Adafruit_DHT.DHT11
DHT_PIN = 4

while True:
    humidity, temperature = Adafruit_DHT.read(DHT_SENSOR, DHT_PIN)
    if humidity is not None and temperature is not None:
        print("Temperature={0:0.1f}C Humidity={1:0.1f}%".format(temperature, humidity))
    else:
        print("Sensor failed. Check wiring.");
    time.sleep(3)

此代码的作用本质上是每三秒钟读取/打印温度和湿度,无限期地

但是,就像我说的那样,我要达到的目的是询问用户所需的样本数量,然后读取并打印出这样的样本数量,每个读数之间都用一个简单的按键分开。这是我一直在努力的代码:

import Adafruit_DHT

DHT_SENSOR = Adafruit_DHT.DHT11
DHT_PIN = 4

n = int (input("Number of samples?\n"))
print()


for x in range (n):
    input()
    while True:
        humidity, temperature = Adafruit_DHT.read(DHT_SENSOR, DHT_PIN)
    if humidity is not None and temperature is not None:
        print("Temperature={0:0.1f}C Humidity={1:0.1f}%".format(temperature, humidity))
    else:
        print("Sensor failed. Check wiring.")
    input()

所需操作的示例:

  1. “样本数量?”
  2. 2
  3. 用户按下任意键
  4. “温度= 23.0C湿度= 63.0%”
  5. 用户按下任意键
  6. “温度= 24.0C湿度= 64.0%”

任何想法如何解决该代码,以便它做我想要的吗?

python python-3.x raspberry-pi sensor
1个回答
0
投票

您不再需要while循环

for循环本身将重复请求的次数

for x in range (n):
    input()
    humidity, temperature = Adafruit_DHT.read(DHT_SENSOR, DHT_PIN)
    if humidity is not None and temperature is not None:
        print("Temperature={0:0.1f}C Humidity={1:0.1f}%".format(temperature, humidity))
    else:
        print("Sensor failed. Check wiring.")
    input()
© www.soinside.com 2019 - 2024. All rights reserved.