The Grumpy Lion
The Grumpy Lion

Reputation: 173

How to run various temperature readings based on user input in Python?

I'm a complete amateur when it comes to Python (for Raspberry Pi) programming, what I'm trying to achieve is to ask the user the number of samples that he wants and then read and print out such number of samples, each reading separated by a simple key stroke.

What I have is a simple set-up with a DHT11 Temperature & Humidity sensor, one 10 KΩ resistor, a couple of jumper cables, and of course a breadboard. The circuit works perfectly when tested along the following code:

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)

What this code does is essentially reading/printing out both temperature and humidity every three seconds, indefinitely.

However, like I said, what I'm trying to achieve is to ask the user the number of samples that he wants and then read and print out such number of samples, each reading separated by a simple key stroke. Here's the code I've been working on:

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()

Example of the desired operation:

  1. "Number of samples?"
  2. 2
  3. User presses any key
  4. "Temperature=23.0C Humidity=63.0%"
  5. User presses any key
  6. "Temperature=24.0C Humidity=64.0%"

Any idea how to fix the code so it does what I want?

Upvotes: 1

Views: 648

Answers (1)

OneCricketeer
OneCricketeer

Reputation: 191711

You don't need the while loop anymore

The for loop itself will repeat for the requested number of times

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()

Upvotes: 1

Related Questions