社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

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

Leon Horka • 5 年前 • 1677 次点击  

在Python(Raspberry Pi)编程时,我是一个完全业余的人,我所要做的是向用户询问他想要的样本数,然后阅读并打印出这样的样本数,每个读数用简单的键笔划分开。

我有一个简单的装置,一个DHT11温度和湿度传感器,一个10千欧电阻,几根跨接电缆,当然还有一个垫板。当按照以下代码进行测试时,电路工作正常:

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. 用户按任意键
  3. “温度=23.0C湿度=63.0%。”
  4. 用户按任意键
  5. “温度=24.0C湿度=64.0%。”

你知道如何修复代码,使其符合我的要求吗?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/46232
 
1677 次点击  
文章 [ 1 ]  |  最新文章 5 年前
cricket_007
Reply   •   1 楼
cricket_007    5 年前

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