[英]Sensor data from DHT-11 temperature/ humidity sensor to CSV file (python/ raspberry pi 3)
I have minimal coding experience and am relatively new to python, but am trying to write a python program for raspberry pi (3B+) that will get temperature and humidity data from the DHT-11 sensor and save it to a.csv file with 3 headers: timestamp of when data was collected, temperature value, humidity value.我的编码经验很少,并且对 python 相对较新,但我正在尝试为树莓派 (3B+) 编写 python 程序,该程序将从 DHT-11 传感器获取温度和湿度数据,并将其保存到带有头文件的 a.Z628CB5675FF524F3FEZE719 文件中。 :收集数据时的时间戳,温度值,湿度值。
I have already done testing to know that I am getting readings from the sensor just fine.我已经完成了测试,知道我从传感器获得的读数很好。 I want to get those readings, along with timestamps, into a csv file with each under the appropriate header.我想将这些读数连同时间戳一起放入 csv 文件中,每个文件都位于相应的 header 下。 I am getting a TypeError: 'NoneType' object is not subscriptable
error.我收到TypeError: 'NoneType' object is not subscriptable
错误。 I'm a little lost on how I can fix the error since I'm new to the language (and coding in general).由于我是该语言的新手(以及一般的编码),因此我对如何修复错误有点迷茫。 This is what I'm seeing in terminal when I run the program:这是我在运行程序时在终端中看到的内容:
pi@rgbpi: ~ Documents $ sudo python3 temp_humidity_csv.py
Beginning cycle 1
Traceback (most recent call last):
File "temp_humidity_csv.py", line 66, in <module> main()
File "temp_humidity_csv.py", line 33, in main add_to_file(data)
File "temp_humidity_csv.py", line 55, in add_to_file data_writer.writerow({'Time': data['timestamp'], 'Temperature': data['temperature'], 'Humidity': data['humidity']})
TypeError: 'NoneType' object is not subscriptable
The following is my code:以下是我的代码:
import RPi.GPIO as GPIO
import csv
import time, datetime
from time import sleep
import Adafruit_DHT
import os.path
#initialize GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.cleanup()
#set up DHT sensor
dht_sensor = Adafruit_DHT.DHT11
dht_pin = 7
#global variables
datafile = "/home/pi/Desktop/Temp_Humid.csv"
#main function - will take temp, humidity and timestamp and write to csv every 10s
def main():
i = 1
while(1):
print("Beginning cycle " + str(i))
data = get_data()
add_to_file(data)
sleep(10)
print("End of cycle " + str(i))
i = i+1
#get temp and humidity and add to 'data' dictionary
def get_data():
now = datetime.datetime.now()
humidity, temp = Adafruit_DHT.read(dht_sensor, dht_pin)
if humidity is not None and temp is not None:
data = {'timestamp':str(now.strftime("%Y%m%d_%H-%M-%S")), 'temperature':temp, 'humidity':humidity}
print(data)
return(data)
#write temp, humidity and time stamps to csv file
def add_to_file(data):
if os.path.isfile(datafile): #checks if file exists. if yes, appends values for dictionary under corresponding header in a new line
with open(datafile, 'a', newline='') as csvfile:
fieldnames = ['Time', 'Temperature', 'Humidity']
data_writer = csv.DictWriter(csvfile, fieldnames=fieldnames, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)
data_writer.writerow({'Time': data['timestamp'], 'Temperature': data['temperature'], 'Humidity': data['humidity']})
else: #creates file (that has been checked and does not yet exist) and adds headers and values for all 3 keys in dict
with open(datafile, 'w', newline='') as csvfile:
fieldnames = ['Time', 'Temperature', 'Humidity']
data_writer = csv.DictWriter(csvfile, fieldnames=fieldnames, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)
data_writer.writeheader()
data_writer.writerow({'Time': data['timestamp'], 'Temperature': data['temperature'], 'Humidity': data['humidity']})
if __name__ == "__main__":
main()
Function get_data()
returns dictionary with data if neither humidity
nor temp
are None
. Function get_data()
如果humidity
和temp
都不是None
,则返回带有数据的字典。 Otherwise it returns None
.否则返回None
。 Then you pass whatever get_data()
returned to add_to_file(data)
where you are using that as if it were a dictionary which it might be but it also might be None
.然后,您将get_data()
返回的任何内容传递给您正在使用的add_to_file(data)
,就好像它可能是字典一样,但也可能是None
。 You can modify main
to only call add_to_file(data)
if get_data()
returned something actually useful - data
is not None.如果get_data()
返回了一些实际有用的东西,您可以修改main
以仅调用add_to_file(data)
- data
不是 None。 For example like this:例如像这样:
def main():
i = 1
while(1):
print("Beginning cycle " + str(i))
data = get_data()
if data is not None:
add_to_file(data)
sleep(10)
print("End of cycle " + str(i))
i = i+1
As kukabadl said, your problem is that when your DHT_11 sensor fails due to the wiring being flimsy, get_data outputs None.正如 kukabadl 所说,您的问题是当您的 DHT_11 传感器由于接线脆弱而出现故障时,get_data 输出 None。 your get_data() function only records data in case where data isn't None.您的 get_data() function 仅在数据不是 None 的情况下记录数据。 By adding an else: statement below your if: statement you can account for cases in which data is None:通过在 if: 语句下方添加 else: 语句,您可以解释数据为无的情况:
else:
data = {'timestamp':None, 'temperature':None, 'humidity':None}
print(data)
return(data)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.