All posts

[ Raspberry Pi ] บันทึกอุณหภูมิ-ความชื้นจากเซ็นเซอร์ลงไฟล์ csv

ก่อนหน้าโน้นเราอ่านค่าอุณหภูมิและความชื้น จากนั้นก็ทวิตขึ้นทวิตเตอร์ มารอบนี้ลองมาบันทึกค่าลงไฟล์ .csv

อันก่อนหน้าอ่านค่าอุณหภูมิ-ความชื้นอย่างไร ลงไปอ่านดูก่อนนะ https://playelek.com/raspberry-pi-temp-humidity-am2302/

เราสร้างไฟล์ python ชื่อว่า datalog.py ใส่ไว้ directory ไหนก็ได้ตามสะดวก แค่อย่าลืมติดตั้งไลบรารี่  DHT ของ Adafruit ก่อน ดูลิงก์ตอนที่แล้วเน้อ
แล้วเขียนโค้ดดังนี้

#!/usr/bin/python
import os
import sys
import csv
import time
import datetime
import Adafruit_DHT

# Parse command line parameters.
sensor_args = { '11': Adafruit_DHT.DHT11,
                '22': Adafruit_DHT.DHT22,
                '2302': Adafruit_DHT.AM2302 }
if len(sys.argv) == 3 and sys.argv[1] in sensor_args:
	sensor = sensor_args[sys.argv[1]]
	pin = sys.argv[2]
else:
    print('usage: sudo python datalog.py [11|22|2302] GPIOpin#')
    print('example: sudo python datalog.py 2302 4 - Read from an AM2302 connected to GPIO #4')
    sys.exit(1)

today = datetime.date.today()
fname = "data_logging" + str(today) +".csv"
filelog = csv.writer(open(fname, "wb"))
i=0

if os.stat(fname).st_size == 0:
    filelog.writerow(["Date","Time","Temp","Humidity"]) #

while True:
    i=i+1
    now = time.strftime("%H"+":"+"%M"+":"+"%S")
    humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)

    if humidity is not None and temperature is not None:
        print(str(today) + ' ' + now +' '+'Temp={0:0.1f}*  Humidity={1:0.1f}%'.format(temperature, humidity))
        filelog.writerow([str(today), str(now), '{0:0.1f}*'.format(temperature), '{0:0.1f}%'.format(humidity)])
        time.sleep(5)
    else:
        print('Failed to get reading. Try again!')
        sys.exit(1)

ใน Terminal ใส่คำสั่งรันไฟล์ datalog.py

sudo python datalog.py 2302 4

2302 คือเซ็นเซอร์ AM2302 ถ้าคุณใช้ DHT 11 ก็สามารถเปลี่ยนเป็นเลข 11 หรือ DHT22 ก็เปลี่นเป็น 22

4 คือ GPIO 4 ของ Raspberry Pi ที่ Pin2 SDA ของเซ็นเซอร์ต่อเข้ามา ถ้าคุณใช้ GPIO ขาอื่นก็เปลี่ยนเลข

ลองหยุดรันไฟล์แล้วไปดูในไดเรคทอรี่ที่เราสร้างไฟล์ datalog ไว้จะพบไฟล์ที่โปรแกรมเราสร้างขึ้น อย่างในนี้มันสร้างไฟล์ที่ชื่อว่า data_logging2016-10-28.csv

datalog1

ลองเปิดไฟล์ data_logging2016-10-28.csv ขึ้นมา ถ้าเปิดด้วย texteditor จะได้หน้าตาแบบนี้

datalog2

แต่ถ้านำไปเปิดด้วย LibreOffice Calc หรือ MS Excel จะได้แบบนี้

datalog3

References
http://www.instructables.com/id/Raspberry-Pi-Data-Logging/?ALLSTEPS
http://ccm.net/faq/2091-python-read-and-write-csv-files

Discussion