Showing posts with label Sense HAT. Show all posts
Showing posts with label Sense HAT. Show all posts

Is there a difference in air pressure between your head and toes?

It has been a lovely day in England today, with highs of 20 degrees (that's 68 F) and a gentle breeze. It has been the sort of weather for relaxing in the sun with a cool drink and a sun hat, and maybe a good book, because it is not often we get the chance to produce some vitamin D in this country. But I couldn't just sit around all day. During the peak of the midday sun, I retreated to the relative safety and coolness of my geek cave and tinkered with my Raspberry Pi Sense Hat data logger.

The 8-by-8 LED matrix on the Sense Hat, which is useful for anything your imagination can conceive. 

The Raspberry Pi Sense Hat data logger uses the brilliant Sense Hat to log temperature, pressure and humidity from its many sensors. You can grab my code from the link above, or read about other Sense Hat projects, and if you have a Raspberry Pi then this is an brilliant add on device that will guarantee hours of fun.


It was this tinkering that made me ponder the question raised in the title of this post.

Is there a difference in air pressure between your head and toes?
Assuming that you have toes on the ends of your feet (as I do), and not growing out of your forehead (as I don't), then there should be a difference in air pressure between these two points due to the difference in height between them (assuming that you are standing vertically). More to the point I wondered whether it was possible to measure this difference. Sadly, Raspberry Pi is not maneuverable enough to lift off my desk (so many things plugged in) which led me to look for barometer apps in the app store.

I soon found Barometr by SeNSSoft for my Lumia 950.

Air pressure at ground level

Air pressure at head height.
And there you have it. The answer is 'Yes', about 0.2 hecopascal (or about 0.1 hecopascal if your name is Frodo).

Improved SenseHat headlines ticker

Last time I introduced my SenseHat RSS feed display code. Today I have made some improvements to the script.

The Sense HAT provides an 8x8 LED maxtrix display, accelerometer, gyroscope, magnetometer, air pressure sensor, temperature sensor and air pressure sensor, as well as a small joystick.  Basically a bundle of sensors that plug in directly to the GPIO pins on your Raspberry Pi. They are well worth purchasing should you wish to upgrade your Pi.



First off, the list 'feedlink' can be populated with as many RSS feeds as you like.  Here I have three BBC feeds, but they could be substituted for any feed you like.  Currently the ticker loops through all of the articles in each feed. You could change it so that each feed is chained to the end of the previous one.  With this code you can switch the the start of the next feed by shaking the Raspberry Pi.  The shake is detected by a change in the 'pitch' of the SenseHat.  You can change the sensitivity of the shake with the THRESHOLD variable.  The new feed will be displayed after the previous article has finished.
The RSS feed ticker scrolling over the SenseHat, however my camera frame rate can't keep up.

I have added some exception handling to the showFeed routine to handle an index out of bounds error. I think this could occur with the previous code.



#Sense Hat RSS reader
#version 2
#For Python 2
from sense_hat import SenseHat
import feedparser
import time


def showFeed(d, n):
    """Shows feed (d) article (n)"""
    try:
        sense.show_message(d.entries[n].description,
                           back_colour=[255,0,0],
                           text_colour=[255,255,255],
                           scroll_speed=0.07)
    except IndexError as e:
        sense.show_message("ERROR")



        
sense = SenseHat()
sense.set_rotation(270)
sense.low_light = True

feed = []
feedlink = ['http://feeds.bbci.co.uk/news/rss.xml?edition=uk',
            'http://feeds.bbci.co.uk/news/technology/rss.xml',
            'http://feeds.bbci.co.uk/news/uk/rss.xml']

ARTICLE_LIMIT = 20
THRESHOLD = 15 # threshold for tilt (changes feed)

print "Running on SenseHat:"
while True:
    #read the feeds in
    for thisFeed in range(len(feedlink)):
        feed.append(feedparser.parse(feedlink[thisFeed]))

    i = 0 #article pointer
    f = 0 #feed pointer
    
    while i < ARTICLE_LIMIT:
        orientation1 = sense.get_orientation_degrees()
        time.sleep(0.5)
        print 'feed ',f,'article',i
        showFeed(feed[f],i)
        orientation2 = sense.get_orientation_degrees()
        #check for shake
        print 'shake detected ',abs(orientation2['pitch'] - orientation1['pitch'])
        if (abs(orientation2['pitch'] - orientation1['pitch'])> THRESHOLD):
            f += 1 #change feed
            i = 0 # return to start of feed
            if (f == len(feed)):
                f = 0
        else:
            i += 1
    time.sleep(2.5)

RSS feed for Raspberry Pi SenseHat

I have written a short script for running a news feed on a Raspberry Pi SenseHat.  The Sense HAT provides an 8x8 LED maxtrix display, accelerometer, gyroscope, magnetometer, air pressure sensor, temperature sensor and air pressure sensor, as well as a small joystick.  Basically a bundle of sensors that plug in directly to the GPIO pins on your Raspberry Pi. They are well worth purchasing should you wish to upgrade your Pi.



The feed picks up the headlines from the BBC news service and then runs continuously on the SenseHat display. Any other valid newsfeed could be substituted for the BBC feed.

RSS feed running on the Raspberry Pi with SenseHat.  I couldn't get a much better photo then this.

Step 1

I used feedparser for the RSS feeds.  This can be installed on your Pi using the following command:

sudo pip install feedparser

Step 2

The following Python 2 code runs an infinite loop which loads the first twenty articles from the BBC website and displays them continuously on the SenseHat display.

#Sense Hat RSS reader
#For Python 2
from sense_hat import SenseHat
import feedparser
import time

sense = SenseHat()
sense.set_rotation(270)
ARTICLE_LIMIT = 20

print "Ticker running on SenseHat"
while True:
    for i in range(ARTICLE_LIMIT):
        time.sleep(0.5)
        d = feedparser.parse('http://feeds.bbci.co.uk/news/rss.xml?edition=uk')
        sense.show_message(d.entries[i].description,
                           back_colour=[255,0,0],
                           text_colour=[255,255,255],
                           scroll_speed=0.07)
        
    time.sleep(2.5)

If you liked this article, then you might like my other SenseHat posts, or my other Raspberry Pi posts.

Bug squashed in data logger

Ooops!  I've just spotted a bug in my Raspberry Pi Sense HAT datalogging script.  The 'time' command causes the system to crash.  This is because you can't concatenate a date/time object to a string without first converting it to a string.  

The code should read:

    def do_time(self, args):
        """\n>Displays the current date/time"""
        self.mylog.setTime()
        print("\n>"+str(self.mylog.getTime()))

It is all fixed now.


Raspberry Pi Sense HAT data logger

I have been working on a command line temperature/humidity/pressure data logger for my Raspberry Pi Sense HAT.

You can get the Python code from this folder.

The data logger command line running on the Raspberry Pi 2 showing all available commands.

The script provides the following commands for accessing the Sense HAT sensors:


  • temp (gets the current temperature)
  • pressure (gets the current air pressure)
  • humid (gets the current relative humidity)
  • time (gets the current time/date)


You can also set up a 'log' which will automatically log data from the sensors to a csv file. The duration of the log run and the time interval between measurements can be set through commands.

This log shows the change in temperature and humidity over a few hours.
Running a log.

Sense HAT data logger 01

OK it is day two with my Raspberry Pi Sense HAT and here is my first attempt at a data logger program.  You can read about my first day with Sense HAT and the problems I have encountered so far.



This program simply logs the time, temperature, humidity and air pressure every six seconds.  The data is saved into a text file for later inspection.



Is it getting hot in here? Actually this is the temperature of the air just near the CPU (I am actually really cold right now in my hovel - please send warm jumpers).

I have read the output file over my home server and produced this graph in Windows 10.



# Data Logging App
# Logs the time, temperature, humidity and air pressure
# Tim Street
# 2015-01-14
#
# version history
# ---------------
# 1.0.0.1
#   logger class with time, temp, humidity and pressure

from datetime import datetime
import time
from sense_hat import SenseHat

VERSION = "1.0.0.1"
FILE_PATH = "log.csv" # file path used to log data


class logger:
    """ A logger provides methods for reading the sensor values and saving to a file """
    def __init__(self, filepath):
        self.__time = 0
        self.__temp = 0
        self.__humidity = 0
        self.__pressure = 0
        self.__sense = SenseHat()
        self.__savepath = filepath

    def __str__(self):
        """ String representation of logger """
        return "Time:\t\t"+str(self.getTime())+"\nTemp:\t\t"+str(self.getTemp())+"C\nHumidity:\t"+str(self.getHumidity())+"%\nPressure:\t"+str(self.getPressure())+"mb"

    def __toCSV(self):
        """ Retuns a CSV file line """
        return str(self.getTime())+","+str(self.getTemp())+","+str(self.getHumidity())+","+str(self.getPressure())+",\n"

    def __setTime( self ):
        """ sets log to current date and time """
        self.__time = datetime.today()

    def getTime(self):
        """ returns the date and time from the log """
        return self.__time

    def __setTemp(self):
        """ logs the current temperature """
        self.__temp = self.__sense.get_temperature()

    def getTemp(self):
        """ returns the temperature """
        return self.__temp

    def __setHumidity(self):
        """ logs the current humidity """
        self.__humidity = self.__sense.get_humidity()

    def getHumidity(self):
        """ returns the humidity """
        return self.__humidity

    def __setPressure(self):
        """ logs the current air pressure """
        self.__pressure = self.__sense.get_pressure()

    def getPressure(self):
        """ returns the pressure """
        return self.__pressure

    def update(self):
        """ updates all sensors """
        self.__setTime()
        self.__setTemp()
        self.__setHumidity()
        self.__setPressure()

    def save(self):
        file = open(self.__savepath, 'a')
        file.write( self.__toCSV() )
        file.close()
        
#main

log = logger( FILE_PATH )
while True:
    log.update()
    log.save()
    print(log)
    time.sleep(6)
    

The program needs to append a comma separated file "log.csv" which you can create yourself, or run the script below to create it automatically.

# creates a new output file
file = open("log.csv", "w")
file.write("time,temp /C,humidity /%,pressure /mb\n")
file.close()

Features I intend to implement next:
  • Command line interface
  • Multiple logs by name
  • Option to toggle sensors on off
  • Variable log sleep time
  • LED matrix icons for each state - 'ready', 'sensing', 'writing', 'sleeping'
Well that's it for now, but do check back soon!

#raspberrypi #pi #sensehat #python #datalogging

Hello Sense HAT

Yesterday I bought one of the wonderful Sense HAT boards from element14.com. The Sense HAT provides an 8x8 LED maxtrix display, accelerometer, gyroscope, magnetometer, air pressure sensor, temperature sensor and air pressure sensor, as well as a small joystick.  Basically a bundle of sensors that plug in directly to the GPIO pins on your Raspberry Pi. They are well worth purchasing should you wish to upgrade your Pi.  I would like to set up a data- logging weather station, however I have only had time for a brief experiment with the features so far.

Follow link for buying options.


Setting up is very easy: the board just plugs straight in and the online instructions are very easy to follow. I suggest you download the Sense HAT Python API or you wont get very far with Sense HAT.

Listed in this post are two of my 'hello world' programs.

Space Invader


I am your father...
This program creates a space invader tile on the LED matrix display and flashes the colours.

# Displays a space invader on the LED panel
# and flashes the colours a bit
import time
from sense_hat import SenseHat

def getInvader():
    return [
            O, O, X, X, X, X, O, O,
            O, X, X, X, X, X, X, O,
            X, X, O, X, X, O, X, X,
            X, X, X, X, X, X, X, X,
            X, X, X, X, X, X, X, X,
            O, X, X, O, O, X, X, O,
            O, X, X, O, O, X, X, O,
            O, X, O, O, O, O, X, O
            ]

sense = SenseHat()

while True:
    for r in range(255, 0,-5):
        for b in range(0, 255,5):
            X = [r, 0, 0]
            O = [0, 0, b]
         
            sense.set_pixels( getInvader() )
            time.sleep(0.1)




Thermometer


Displaying a scrolling display of the sensor outputs.
This program simply displays a continuous scrolling readout of the temperature and air pressure. The colour of the display depends on the current air temperature.

# Displays the temperature and pressure
# on the LED panel
import time
from sense_hat import SenseHat

sense = SenseHat()

while True:
    # find temp in celsius
    t = sense.get_temperature_from_humidity()
    # find temp in fahrenheit
    f = ((t/5)*9)+32
    # find pressure in mb
    p = int(sense.get_pressure())
    # find display colour
    # this depends on the current tremperature
    if t<12:
        myCol = [ 0, 200, 230 ] # a cold colour
    elif t<22:
        myCol = [ 0, 220, 0 ] # a neutral colour
    elif t<29:
        myCol = [ 200, 100, 0 ] # a warm colour
    else:
        myCol = [250, 0, 0 ] # very hot colour
    #display message
    sense.show_message( str((int(t*10))/10)+"C   "+str((int(f*10))/10)+"F    "+str(p)+"mb", text_colour=myCol)
    time.sleep(0.5)


Sense HAT reading the wrong temperature

One problem: the temperature sensor is positioned on the board so that it is directly above your Raspberry Pi processor. This means that it picks up the ambient air temperature as well as some of the heat from the processor. Positioning the Pi vertically along its widest edge alleviates some of this problem due to better convection however not altogether.

I do not have a decent thermometer to test the callibration, however I suspect that the Pi can become inaccurate by 12 degrees Celsius or greater.

The manufacturers make no apologies for this.

One solution is to make a heuristic algorithm (a fudge-y guess) at the temperature, however this is not very satisfactory.

Another solution will be to position the Sense HAT further away from the motherboard using a 40 pin ribbon cable and GPIO cobbler. I have a 20cm cable currently with the Royal Mail (along with some blu-tak). I'll let you know how I get on with this.

Still awake? That's all for now, but try these...
More Raspberry Pi adventures.
More programming things.
Something completely different.

#raspberrypi #senseHAT

Label

World Karma Game