Updated SenseHAT weather station

Still pondering how best to improve my simple Raspberry Pi SenseHAT weather station, but I thought I’d share some improvements.

The code now keeps track of highs and lows over the period it’s been logging and displays them on the chart along with the current readings for temperature, humidity and air pressure.

This FTPs the chart and data in a CSV file to a remote web server for display on a web page and it’s also designed to run headless at startup, so it doesn’t need a windowed environment running to plot the graph. It will also show on the SenseHAT display when it’s uploading a file and if there’s been an FTP problem.

The downside of this is, of course, the code is much longer…

#!/usr/bin/python

# v5 runs headless, info on LEDs, FTPs CSV file & only charts last 24 hrs
# v4 FTPs chart to remote web server
# v3 adds real timestamping and logging to a CSV file
import matplotlib
matplotlib.use('Agg')   # used as running headless without windows
import matplotlib.pyplot as plt
from time import sleep
from sense_hat import SenseHat
import time
from datetime import datetime
import os
import ftplib

def getCPUtemperature():
 res = os.popen('vcgencmd measure_temp').readline()
 return(res.replace("temp=","").replace("'C\n",""))

sense = SenseHat()

interval_min = 5 # measurement interval in minutes
hrs_shown = 24  # number of hours covered by chart
chart_span = int(hrs_shown*(60/interval_min)) # calculate number of readings to show

# uncomment these lines to write headers to CSV file
#fd = open('logging.csv','a')
#fd.write('time,pressure,temperature,humidity\n')
#fd.close()

while True:
    pressure_list = []
    temp_list = []
    humidity_list = []
    x = []
    a = 0
    daily_max_humidity = 0
    daily_max_temp = 0
    daily_max_pressure = 0
    daily_min_humidity = 2000
    daily_min_temp = 2000
    daily_min_pressure = 2000

    for a in range (chart_span):
        sense.clear()
        fd = open('/home/pi/Desktop/logging.csv','a')
        pressure = sense.get_pressure()-1000
        pressure_list.append(pressure)
    # attempt to calculate ambient temperature
    # based on dgaust in https://www.raspberrypi.org/forums/viewtopic.php?f=104&t=111457
        cpuTemp=int(float(getCPUtemperature()))
        ambient = sense.get_temperature_from_pressure()
        calctemp = ambient - ((cpuTemp - ambient)/ 1.5)
        temp_list.append(calctemp)

        humidity = sense.get_humidity()
        humidity_list.append(humidity)

        timestamp = str(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
        fd.write(timestamp+','+str(pressure)+','+str(calctemp)+','+str(humidity)+'\n')
        fd.close()
#        print(timestamp, pressure, calctemp, humidity)

        x.append(a)
        a = a + 1

        if humidity > daily_max_humidity:
            daily_max_humidity = humidity
        if calctemp > daily_max_temp:
            daily_max_temp = calctemp
        if pressure > daily_max_pressure:
            daily_max_pressure = pressure
        if humidity < daily_min_humidity:
            daily_min_humidity = humidity
        if calctemp < daily_min_temp:
            daily_min_temp = calctemp
        if pressure < daily_min_pressure:
            daily_min_pressure = pressure

        print('max humidity '+str(daily_max_humidity))
        print('max temp '+str(daily_max_temp))
        print('max pressure '+str(daily_max_pressure))
        print('min humidity '+str(daily_min_humidity))
        print('min temp '+str(daily_min_temp))
        print('min pressure '+str(daily_min_pressure))

        fig = plt.figure()
        plt.plot(x,humidity_list)
        plt.plot(x,temp_list,'r')
        plt.plot(x,pressure_list,'g')
        plt.title('@blogmywiki SenseHAT WX '+timestamp)
        plt.figtext(0, 0.9, "max "+str(round(daily_max_humidity,0))+"%",color='blue',fontsize=8)
        plt.figtext(0, 0.85, "min "+str(round(daily_min_humidity,0))+"%",color='blue',fontsize=8)
        plt.figtext(0, 0.8, "max "+str(round(daily_max_temp,0))+"C",color='red',fontsize=8)
        plt.figtext(0, 0.75, "min "+str(round(daily_min_temp,0))+"C",color='red',fontsize=8)
        plt.figtext(0, 0.7, "max "+str(round(daily_max_pressure,0)+1000)+"mb",color='green',fontsize=8)
        plt.figtext(0, 0.65, "min "+str(round(daily_min_pressure,0)+1000)+"mb",color='green',fontsize=8)
        plt.figtext(0, 0.04, "current humidity "+str(round(humidity,0))+"%",color='blue',fontsize=10)
        plt.figtext(0.25, 0.04, "temp "+str(round(calctemp,1))+"$^\circ$C",color='red',fontsize=10)
        plt.figtext(0.4, 0.04, "pressure "+str(round(pressure,1)+1000)+" mb",color='green',fontsize=10)
        fig.savefig('/home/pi/Desktop/wx_chart6.png')
        sense.show_message("Updating", text_colour=[0,80,0])

        try:
            session = ftplib.FTP('FTP-SERVER-ADDRESS','FTP-USERNAME','FTP-PASSWORD')
            file = open('/home/pi/Desktop/wx_chart6.png','rb')          # open chart file
            session.storbinary('STOR /SERVER_PATH/wx_chart.png', file)  # send the file
            file.close()                                                # close file
            file = open('/home/pi/Desktop/logging.csv','rb')            # open csv file
            session.storbinary('STOR /SERVER_PATH/logging.csv', file)   # send the file
            file.close()
            session.quit()
            sense.show_letter(".",text_colour=[0, 80, 0])   # green dot to show it's running & FTP'd ok
        except ftplib.all_errors as e:
            print(e)
            sense.show_message("FTP error", text_colour=[80,0,0])
            sense.show_letter(".",text_colour=[80, 0, 0])  # red dot to show it's running but not FTP'd
        sleep(interval_min*60)
This entry was posted in Raspbian and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>