Nov-16-2020, 09:06 AM
If you compare the old Library and the new from Circuit Python, you see that they raise a RuntimeError if something wrong happens.
https://github.com/adafruit/Adafruit_Cir...ht.py#L205
https://github.com/adafruit/Adafruit_Cir...ht.py#L209
https://github.com/adafruit/Adafruit_Cir...ht.py#L237
https://github.com/adafruit/Adafruit_Cir...ht.py#L241
The old library is also raises a RuntimeError: https://github.com/adafruit/Adafruit_Pyt...erry_Pi.py (just seek "raise ")
Corrected version, but not tested.
For example the module from Adafruit is a third-party module. This should be imported after first party packages like sys, os, etc.
Other changes:
https://github.com/adafruit/Adafruit_Cir...ht.py#L205
https://github.com/adafruit/Adafruit_Cir...ht.py#L209
https://github.com/adafruit/Adafruit_Cir...ht.py#L237
https://github.com/adafruit/Adafruit_Cir...ht.py#L241
The old library is also raises a RuntimeError: https://github.com/adafruit/Adafruit_Pyt...erry_Pi.py (just seek "raise ")
Corrected version, but not tested.
import logging import sys import time import Adafruit_DHT as adht logging.basicConfig( filename="temperature.log", filemode="a", format="%(created)f %(message)s", level=logging.INFO, ) log = logging.getLogger() def main_loop(): while True: try: humidity, temperature = adht.read_retry(adht.DHT22, 23) except RuntimeError as e: # this block, if RuntimeError were raised from adht.read_retry log.error(f"RuntimeError: {e}") else: # this block, if no Exception were raised by adht.read_retry log.info(f"Temp={temperature:0.1f} C and Humidity={humidity:0.1f} %") # this is always executed print("Waiting for 60 seconds… Sensor 0", file=sys.stderr) time.sleep(60) if __name__ == "__main__": try: main_loop() except KeyboardInterrupt: print("\nCTRL+C\n", file=sys.stderr)By the way, I use always black and isort for code formatting and sorting of imports.
For example the module from Adafruit is a third-party module. This should be imported after first party packages like sys, os, etc.
Other changes:
- f-strings
- log = logging.getLogger() and use this instead of logging.error, logging.info
- printing to sys.stderr
- loop is in a function
- try-except around main_loop
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!