【问题标题】:How to run various temperature readings based on user input in Python?如何根据 Python 中的用户输入运行各种温度读数?
【发布时间】:2020-02-01 06:37:09
【问题描述】:

在 Python(用于 Raspberry Pi)编程方面,我是一个完全的业余爱好者,我想要实现的是询问用户他想要的样本数量,然后读取并打印出这样数量的样本,每个读数由一个简单的按键分隔。

我所拥有的是一个简单的设置,其中包含一个 DHT11 温度和湿度传感器、一个 10 KΩ 电阻器、几根跨接电缆,当然还有一个面包板。当按照以下代码进行测试时,该电路可以完美运行:

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 sensors


    【解决方案1】:

    你不再需要 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()
    

    【讨论】:

      猜你喜欢
      • 2019-12-12
      • 1970-01-01
      • 2017-07-17
      • 1970-01-01
      • 1970-01-01
      • 2015-05-21
      • 2020-01-31
      • 1970-01-01
      相关资源
      最近更新 更多