此代码从 BME280 探针提取数据。 它返回正确的值。 但我写入 .json 文件是错误的。 我的输出如下所示: 探测嗡嗡声:55.58 探头温度:84.0 探针新闻:29.81 探头DP:64.6 探头SP:19.4
我的代码:
#!/usr/bin/python3
import time
import math
import board
from adafruit_bme280 import basic as adafruit_bme280
i2c = board.I2C() # uses board.SCL and board.SDA
bme280 = adafruit_bme280.Adafruit_BME280_I2C(i2c)
b = 17.62
c = 243.12
gamma = (b * bme280.temperature /(c + bme280.temperature)) + math.log(bme280.humidity / 100.0)
dewpoint = (c * gamma) / (b - gamma)
dewpoint= dewpoint *9 /5 +32
temperature = bme280.temperature * 9/5 +32
pressure = bme280.pressure /3386 *100 +.92
humidity = bme280.humidity +3.5
humidity = (round(humidity,2))
temperature =(round(temperature,2))
pressure = (round(pressure,2))
dewpoint = (round(dewpoint,2))
spread = (round(temperature-dewpoint,2))
probe = open("/home/pi/allsky/config/overlay/extra/usertemphum.txt","w")
probe.write ("ProbeHum:" +str(humidity)+"\n")
probe.write ("ProbeTemp:" +str(temperature)+"\n")
probe.write ("ProbePress:" +str(pressure)+"\n")
probe.write ("ProbeDP:" +str(dewpoint)+"\n")
probe.write ("probeSP:" +str(spread)+"\n")
probe.close()
Json 文件需要有一个打开
{
和关闭 }
键。
您可以将它们添加到文件的开头和结尾
# changed extension to .json
probe = open("/home/pi/allsky/config/overlay/extra/usertemphum.json","w")
probe.write("{") # Added opening key
probe.write ("ProbeHum:" + str(humidity)+"\n")
probe.write ("ProbeTemp:" + str(temperature)+"\n")
probe.write ("ProbePress:" + str(pressure)+"\n")
probe.write ("ProbeDP:" + str(dewpoint)+"\n")
probe.write ("probeSP:" + str(spread)+"\n")
probe.write("}") # Added closing key
probe.close()
您还可以进行其他改进,例如使用
with
块打开文件、使用 f 字符串或先创建字典并使用库将其转储为 json 文件,而不是将 json 写入 txt 文件。