【发布时间】: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()
所需操作的示例:
- “样本数?”
- 2
- 用户按任意键
- “温度=23.0C 湿度=63.0%”
- 用户按任意键
- “温度=24.0C 湿度=64.0%”
知道如何修复代码以使其符合我的要求吗?
【问题讨论】:
标签: python python-3.x raspberry-pi sensors