stevan
New Coder
I'm trying to get data from my temperature and humidity sensor and write the data to a JSON file every minute. I started learning Python two days ago, so I have no idea why these errors occur (the output is in the attachment):
The Code:
The Code:
Python:
import time
import board
import adafruit_dht
import psutil
import io
import json
import os
from datetime import date
from datetime import datetime
# We first check if a libgpiod process is running. If yes, we kill it!
for proc in psutil.process_iter():
if proc.name() == "libgpiod_pulsein" or proc.name() == "libgpiod_pulsei":
proc.kill()
sensor = adafruit_dht.DHT11(board.D23)
# init
temp_values = [10]
hum_values = [10]
counter = 0
#check if file is there
def startupCheck():
if os.path.isfile("data.json") and os.access("data.json", os.R_OK):
# checks if file exists
print("File exists and is readable")
else:
print("Either file is missing or is not readable, creating file...")
# craete json file
with open("data.json", "w"):
print("The json file is created.")
def calc_avgValue(values):
sum = 0
for iterator in values:
sum = sum + iterator
return sum / len(values)
startupCheck()
while True:
try:
#insert values in array
temp_values.insert(counter, sensor.temperature)
hum_values.insert(counter, sensor.humidity)
counter = counter + 1
time.sleep(0.2)
if counter >= 10:
print(
"Temperature: {}*C Humidity: {}% ".format(
round(calc_avgValue(temp_values), 2),
round(calc_avgValue(hum_values), 2),
)
)
print("Error occured in line 58")
# get time
today = date.today()
now = datetime.now()
print("Error occured in line 63")
# init json object
data = {
"temperature": round(calc_avgValue(temp_values), 2),
"humidity": round(calc_avgValue(hum_values), 2),
"fullDate": today,
"fullDate2": today.strftime("%d/%m/%Y"),
"fullDate3": today.strftime("%B %d, %Y"),
"fullDate4": today.strftime("%b-%d-%Y"),
"date_time": now.strftime("%d/%m/%Y %H:%M:%S"),
}
print("Error occured in line 74")
json_object = json.dumps(data, indent = 4)
print(json_object)
with open("data.json", "w") as outfile:
outfile.write(json_object)
counter = 0
except RuntimeError as error:
continue
except Exception as error:
sensor.exit()
raise error("I occured randomly because I'm gay")
time.sleep(0.2)