From 7e96b4caddf3f8a3a4e29d8328f00a2aa5124589 Mon Sep 17 00:00:00 2001 From: Kshitij Date: Thu, 10 Oct 2024 22:40:20 +0530 Subject: [PATCH] Code now shows temperature and humidity infinitely until keyboard interrupt. --- temp-calc.py | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/temp-calc.py b/temp-calc.py index 7af256d..0130e86 100755 --- a/temp-calc.py +++ b/temp-calc.py @@ -2,20 +2,25 @@ import RPi.GPIO as GPIO import dht11 +import time # initialize GPIO GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.cleanup() -# read data using pin 16 -instance = dht11.DHT11(pin = 16) -result = instance.read() +try: + while True: + # read data using pin 16 + instance = dht11.DHT11(pin = 16) + result = instance.read() -if result.is_valid(): - print("Temperature: %-3.1f C" % result.temperature) - print("Humidity: %-3.1f %%" % result.humidity) -else: - print("Error: %d" % result.error_code) - -GPIO.cleanup() + if result.is_valid(): + print("Temperature: %-3.1f C" % result.temperature) + print("Humidity: %-3.1f %%" % result.humidity) + else: + print("Error: %d" % result.error_code) + time.sleep(3) +except KeyboardInterrupt: + print("Program stopped by user.") + GPIO.cleanup()