Hello! Output question on phython script for Rasp. Pi temp/humidity?

Hello, I have a Pi 3 and I got the temp/humidity sensor for it. I don’t know much coding, especially python but I’ve managed to edit some script I found online to get to where I’d like. The original script used a different method which I didn’t like (doesn’t read well to a noncoder) but it seems I’ve lost 2 significant digits on the humidity variable. I added a conversion from C to F degrees, and changed the output to a string variable. Other then that it’s the same.

The original code had decimals for temp and humidity, now I only get it from temperature. I also added a rount to 2 decimal places for the output, but even if thats removed, humidity still doesnt output any decimals.

Can someone review the code and tell me why? I took texas instruments basic and C++ decades ago for 1 highschool class so thats my limit of coding in the late 90’s :slight_smile: but I hope I’m not to useless.

I don’t know what the default variable size/type for pything, in c i would have manually set it to float or something to make sure it wasn’t truncated, but i dont see where the variable types are assigned in this… and i dont know why in the regular code the output humity HAS decimals, but doesnt in my edited one.

Thanks!!

my edits:

import Adafruit_DHT

DHT_SENSOR = Adafruit_DHT.DHT22
DHT_PIN = 4

while True:
    humidity, temperature = Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PIN)

    tempf = ((temperature * 9.0) / 5.0) +32   #converts C to F

    output = "Temperature %s, Humidity %d" % (round(tempf,2), round(humidity,2))  #rounds to 2 decimals

    if humidity is not None and temperature is not None:
      
	print(output)

    else:
        print("no data")

The original google’d code:

import Adafruit_DHT

DHT_SENSOR = Adafruit_DHT.DHT22
DHT_PIN = 4

while True:
    humidity, temperature = Adafruit_DHT.read_retry(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("no data")
    output = "Temperature %s, Humidity %d" % (round(tempf,2), round(humidity,2))  #rounds to 2 decimals

%d refers here to the decimal integer, to make it display also decimal places different type presentation needs to be used. Alternatively you may try with adapting string formatting from the original code, using a more modern format method.

Thank you, I didn’t realize those letters represented variable types in a way. Switching the d to an s worked and explained why temperature continued to work after the changes.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.