将数据从DHT11记录到CSV文件中

时间:2018-12-09 15:04:33

标签: python raspberry-pi3 iot

下面的代码经过精心设计,因此当触发运动传感器时,它将开始记录来自DHT11的数据。然后将数据发送到名为cayenne的站点进行数据传输。问题在于,正在记录并发送给cayenne的数据没有存储到也创建的CSV文件中。它可以成功打印每条数据的标题,但是不会打印正在读取的图形。 使用Raspberry Pi 3B +,DHT11温湿度传感器和PIR运动传感器。

import sys
import os 

import Adafruit_DHT as dht
import cayenne.client

import RPi.GPIO as GPIO

# Added to deal with RPi 3B+
import platform
import re

import time 
from time import strftime 
import datetime

#Cayenne authentification info stuff
MQTT_USERNAME="4ff7bed0-f66b-11e8-a08c-c5a286f8c00d"
MQTT_PASSWORD="82e9cd4df60e9a8e864d0f4f80262322ad692068"
MQTT_CLIENT_ID="66751010-f7d6-11e8-898f-c12a468aadce"


client = cayenne.client.CayenneMQTTClient()
client.begin(MQTT_USERNAME, MQTT_PASSWORD, MQTT_CLIENT_ID)

# DHT sensor connected to Raspberry Pi to GPIO dhtpin. 
dhtpin = 3 #pin03 is BCM2; 2 in BOARD
# Pin for Pir sensor
pirsensor = 17  # BOARD11

#GPIO.setmode(GPIO.BOARD) #for using the WiringPi numbers
GPIO.setmode(GPIO.BCM) #for the Broadcom numbers instead of the WiringPi numbers
#GPIO.setwarnings(False)
GPIO.setup(dhtpin, GPIO.OUT)  # Set dhtpin as an output

GPIO.setup(pirsensor,GPIO.IN) #Set pirsensor to input

# Sensor should be set to Adafruit_DHT.DHT11, Adafruit_DHT.DHT22, or Adafruit_DHT.AM2302. 
sensor = dht.DHT11 

# Set Duration in second between two mesures. 
period =  1

# Pir status
state = 0


#Create the log file in CSV format with header columns
with open('dhtpir.csv', 'a+') as f:
    f.write(" DATE & TIME \t " + " , \t"+ "% HUMIDITY " + " , " + "T(Celcius)" + " , \t" + " T(Fahrenheit),\n")


while True: 
    # Note that sometimes you won't get a reading and the results will be null 
    # (because Linux can't guarantee the timing of calls to read the sensor). 
    # If this happens try again!
    client.loop()
    # Pir 
    time.sleep(0.1)
    state = GPIO.input(pirsensor)
    if state == 1:
        humidity,tempC = dht.read_retry(dht.DHT11, dhtpin)
        #Convert from Celcius to Farenheit
        tempF = (9.0/5.0)*(tempC)+32

        print("GPIO PIR pin %s is %s" % (pirsensor, state))


        #Get the data

        if humidity is not None and tempC is not None:
        # Get the timestamp
            timestamp = datetime.datetime.now().strftime("%Y%m%d %H:%M:%S")

            client.celsiusWrite(1, tempC)
            client.luxWrite(2, humidity)

            # Print data to the terminal 
            print('{}'.format(timestamp),'\t Humidity: {0:0.1f}% Temperature: {1:0.1f} C'.format(humidity, tempC) , '({0:0.1f} F)'.format(tempF)), # print temperature in Celcius
            # Fill the previously created log wile with the sensor data in csv format
            # 
            with open('dhtpir.csv', 'a+') as f:
                f.write('{}'.format(timestamp)+ " , \t" + (repr(humidity))+"%" + " , \t" + str(tempC)+" C" + " , \t" + '{0:0.1f} F,'.format(tempF) + " \n"),
                #f.write(timestamp + " , \t" + (repr(humidity))+"%" + " , \t" + str(tempC)+" C" + " , \t" +  str(tempF) + " F\n"), # just a different formating output
                f.close() # not absolutly needed when using the 'with' syntax

        else:
            print('Exiting: failed to get reading.\n Try again!')  
            with open('dhtpir.csv', 'a+') as f:
                f.write('{}'.format(timestamp)+ " , \t Exiting: failed to get reading.\n Try again!")
                f.close()
            sys.exit(1)
        # Wait for the period in second between data reading
        time.sleep(period)


GPIO.cleanup()

0 个答案:

没有答案