Mathematica and the Sense HAT: collect and analyse real world data on a Raspberry Pi

By Russell Barnes. Posted

Collect and display environmental data using the Sense HAT
and Wolfram’s language function'

Mathematica and the Wolfram Language is included with Raspbian on the Raspberry Pi. The Wolfram Language is particularly useful in partnership with the Sense HAT, which features an LED array and a collection of environmental and movement sensors.

Ever since the partnership between the Raspberry Pi Foundation and Wolfram Research began, people have been excited to discover – and are often surprised by – the power and ease of using the Wolfram Language and Mathematica on a Raspberry Pi.

These give users the ability to read in data from the physical world and display or manipulate it in the Wolfram Language with simple, one-line functions. With the release of Mathematica 11, Wolfram Research has been working hard to refine functions that connect to the Sense HAT, allowing Mathematica to communicate directly with the device.

Programming the Sense HAT

The Sense HAT’s functionality is built on Wolfram’s Device Driver Framework, so connecting to the device is incredibly simple. To start, use the DeviceOpen function to establish a connection. This will return a DeviceObject, which we will use later to tell Mathematica which device we want to read from or write to.

hat = DeviceOpen["SenseHAT"]

In the case of the Sense HAT, there are three on-board sensors that Mathematica can read from. To access the data from these sensors, simply call DeviceRead with the name of the measurement wanted. For instance:

temp = DeviceRead[hat, "Temperature"]
hum = DeviceRead[hat, "Humidity"]

A total of seven measurements can be read from the Sense HAT: temperature, humidity, air pressure, acceleration, rotation, magnetic field, and orientation. All the readings are returned with appropriate units, making it easy to convert the values to other formats if necessary.

accel = DeviceRead[hat, "Acceleration"]
accelSI = UnitConvert[accel, "Meters"/"Seconds"^2]

The other physical component of the Sense HAT is the 8×8 LED array. You can use the DeviceWrite function to send an image or a string to the array. For strings, the text scrolls sideways across the device. You can set the speed and colour of the scrolling text.

DeviceWrite[hat, "Hello, world!"]
DeviceWrite[hat, {"Now in color!", "ScrollSpeed" -> 0.25, "Color" -> {255, 0, 128}}]

Alternatively, the Sense HAT can receive an 8×8 list of RGB values to be displayed on the LED array. Using this method, it is possible to display small images. Download and run the code from magpi.cc/2slmDoa to see a display like the one in Figure 1.

Practical uses for Mathematica

Using these functions, you can write Mathematica programs that process the data received from the sensors on the Sense HAT. For example, at the Wolfram Technology Conference in October 2016, the Sense HAT was demonstrated by reading the temperature, humidity and air pressure around the Pi every five minutes, and pushing that data to the Wolfram Data Drop.

db = CreateDatabin[]
SaveReadingToDataDrop[
   bin_Databin] := (Module[{dev, hum, temp, pres}, 
    dev = DeviceOpen["SenseHAT"];
    temp = DeviceRead[dev, "Temperature"];
    pres = DeviceRead[dev, "Pressure"];
    hum = DeviceRead[dev, "Humidity"];
    DatabinAdd[
     bin, <|"temperature" -> temp, "humidity" -> hum, 
      "air pressure" -> pres|>];
    DeviceClose[dev];]);
cronTask = RunScheduledTask[SaveReading
ToDataDrop[db], 300]

This function generates a new databin to store data, but what does that data look like once it has been recorded? Let’s look at the recordings made at the Wolfram Technology Conference (Figure 2).

Mathematica and Sense HAT. Figure 2. Humidity Plot Large

That data was available to be downloaded into Mathematica by anyone, at any time after the conference, to show the changes in atmospheric conditions using DateListPlot.

DateListPlot[Databin["gwSkMvMW"]]["air pressure"]

In Figure 2, you can see the rise in air pressure inside the conference centre as more people gathered to see the demos from Wolfram employees, followed by a drop as the conference ended.

Another demo run at the conference made use of DeviceWrite. Using the Wolfram Language’s financial database, the Sense HAT was transformed into a miniature stock ticker. This demo downloads the current stock market data from Wolfram’s servers, then picks a random stock from the list and shows the stock’s name and price on the Sense HAT’s LED array.

StockTickerPi[
   dev_DeviceObject] := (Module[{len, price, str, stock, stockList}, 
    stockList = FinancialData["NYSE:*", "Lookup"];
    Do[stock = RandomChoice[stockList];
     price = FinancialData[stock];
     If[Head[price] === Real, 
      str = StringDrop[ToString[stock], 5] <> "$" <> ToString[price];
      DeviceWrite[
       dev, {str, "ScrollSpeed" \[RightArrow] 0.05, 
        "Color" -> {200, 0, 0}}]], 100];]);
StockTickerPi[hat]

Let’s play a game

The final demo run at the conference used the Sense HAT’s LED array to run Conway’s Game of Life, a famous cellular automaton. For those unfamiliar with the game, imagine each lit LED is a cell in a Petri dish. If a cell has too few or too many neighbours, it dies out. If an empty space has exactly three living neighbours, a new cell appears there. When these rules have been applied to all of the spaces on the grid, a new ‘generation’ begins, and the rules are reapplied. This pattern can continue indefinitely, given the right conditions. In the demo, a random array of lit and unlit LEDs constitutes the starting pattern. The automaton then runs for a given number of iterations.

Check out the code download to see how this was done. The rounds, pause, and color parameters can all be modified to change the way the automaton is displayed, and to adjust how long Mathematica waits before displaying the next iteration.

What next?

This is only a taste of what is possible with Mathematica and the Sense HAT. Click here to discover more ideas for using them together. Once you’ve tried some of the ideas, why not share your work on the Raspberry Pi Wolfram group to inspire other users? We’ll see you there!

This article was by Brett Haines and appeared in The MagPi #60

Brett is a Junior Release Engineer at Wolfram Research, where he’s been working with the Raspberry Pi for more than two years.

From The MagPi store

Subscribe

Subscribe to the newsletter

Get every issue delivered directly to your inbox and keep up to date with the latest news, offers, events, and more.