Raspberry Pi – camera box

This weekend, I was finally happy that I’d managed to implement a reasonable temperature and humidity project as well as a motion detecting camera for my Raspberry Pi. I decided to invest £19 in a ModMyPi camera box to consolidate them onto my Pi 3. It arrived today, and after an evening’s fun this is the result.

Pi Camera BoxLid open for testing. The DHT22 temperature and humidity sensor is at the front, with the motion sensor and camera mounted in the lid.

Pi Camera Box - installed in the garageIn situ.

I think it looks much better than my original attempt, even if the rather fiddly assembly took a couple of hours (with testing) rather than the 10 minutes claimed by the manufacturer! It also means that as my camera is now mounted the correct way up, I no longer need to rotate the image by 180 degrees in my code …

Update: After I’d installed this in the garage, I started to get a large number of false positives. A change back to my Pi2 made little difference (although the original version I’d put together but without the DHT22 had worked well). Finally, soldering a 10k resistor between the data and ground wires of the PIR detector seems to have resolved the issue of the data pin going high without it sensing movement.

Humidity and temperature monitoring with a Raspberry Pi

Continuing my quest to protect my Caterham 7 using my Raspberry Pi, I bought a bargain box of 37 assorted sensors for £21. One of the devices supplied was a DHT11, capable of monitoring temperature and humidity. A quick internet search led me to discover the very useful pigpio libraries and daemon. Wiring up the DHT11 to the Pi’s GPIO pins was simple – 3 wires, 1 to the 3V3 supply, 1 to a ground pin and the data pin of the device to GPIO pin 17. The author of the pigpio library also provides some example code for the sensor.

This was enough to demonstrate that I could get it to work, but the accuracy of the DHT11 was woeful. It’s advertised as having an accuracy of +/- 2 Celsius, but my experiments suggested that the one I had acquired for the princely sum of 57p had an accuracy of around +/- 5 Celsius. As I also wanted the sensor to work in an unheated garage, another limitation was that the DHT11 is unable to read values below freezing.

Encouraged, I decided to invest a further £6 in a plug compatible DHT22 sensor. This has an operating range of -40 Celsius to 125 Celsius, with an accuracy of +/- 0.5 degrees. Initial tests suggested that it was far more accurate than the DHT11. While the sensor produces a slightly different data stream to the DHT11, it was close enough for the example code to have been written in a way that it would still work.

As part of my experiments, I made a small modification to the example code (testDHT.c) to calculate the dew point from the temperature and relative humidity readings. I’ve also changed the way it outputs data, to write it to a file rather than the screen.

void cbf(DHTXXD_data_t r)
{
   FILE* fp;
   char buff[100];
   time_t now;
   float rdwpt,rtemp,rhum;
   extern float rdewpt_();
 
   if (r.status == 0) {
       now = time (0);
       strftime (buff, 100, "%Y%m%d-%H%M", localtime (&now));
       rtemp=r.temperature;
       rhum=r.humidity;
       rdwpt=rdewpt_(&rtemp,&rhum);
       fp=fopen("readings.txt", "a");
       fprintf(fp,"%s ",buff);
       fprintf(fp,"%.1f ", rtemp);
       fprintf(fp,"%.1f ", rhum);
       fprintf(fp,"%.1f", rdwpt);
       fprintf(fp,"\n");
       fclose(fp);
   }
}

While it would have been simple enough to write a dew point calculation in C, I decided to write it in FORTRAN instead. Hey, the more people who get to love FORTRAN the better. Here’s the function I wrote, which uses the Magnus formula. It’s declared in the C fragment above as an external function that returns a float. Parameters are passed to FORTRAN by address, rather than by value.

C
C     DEWPOINT CALCULATION FROM TEMPERATURE IN CELSIUS - RTEMP
C                               RELATIVE HUMIDITY - RHUM
C     USING THE MAGNUS FORMULA WITH CONSTANTS SUITABLE FOR A
C     TEMPERATURE RANGE OF -45 TO 60 CELSIUS
C
C     AUTHOR: TJH 28-01-2017
C
      REAL FUNCTION RDEWPT(RTEMP,RHUM)
      REAL RH
      RH = (LOG10(RHUM)-2)/0.4343+(17.62*RTEMP)/(243.12+RTEMP)
      RDEWPT = 243.12*RH/(17.62-RH)
      RETURN
      END

Compiling and linking the C and FORTRAN code using gfortran:

gfortran -Wall -pthread -o DHTXXD *.c *.f -lpigpiod_if2

produces an executable that can create a data file. This example was created using the command:

./DHTXXD -g17 -i600

which reads the data from GPIO pin 17 every 10 minutes.

20170128-2009 6.9 72.0 2.2
20170128-2019 6.9 71.7 2.1
20170128-2029 6.8 71.3 2.0
20170128-2039 6.8 71.4 2.0
20170128-2049 6.8 71.7 2.0
20170128-2059 6.8 71.4 2.0
20170128-2109 6.7 71.1 1.8

This provides data in a suitable format to use some relative simple gnuplot commands to create a charts. The first example plots the relative humidity readings over time, with the larger spikes in the relative humidity data correlating to the garage door being opened while it was raining.

set xdata time
set xlabel "Time"
set ylabel "Relative Humidity %"
set timefmt '%Y%m%d-%H%M'
set format x '%H%M'
plot 'readings.txt' using 1:3 title 'Relative Humidity' with linespoints

HumidityThe second example graphs the air temperature reading directly from the DHT22 with the dew point temperature calculated from the Magnus formula.

set xdata time
set xlabel "Time"
set ylabel "Temperature in degrees Celsius"
set timefmt '%Y%m%d-%H%M'
set format x '%H%M'
plot 'readings.txt' using 1:2 title 'Air Temperature' with linespoints, \
     'readings.txt' using 1:4 title 'Dew Point' with linespoints

Air temperature and dew pointI’m going to be keeping an eye on the data, to understand if it might be beneficial to seal the garage door more effectively than at present and invest in a dehumidifier.

Benchmarking the Raspberry Pi 3

I was fortunate enough to be able to order a Raspberry Pi 3 on Monday morning from The Pi Hut. This was because I’d taken the day off work as holiday, because I’d been to see the brilliant Adam Hills in Birmingham the evening before. This meant that the email announcing the Pi 3’s arrival was just about the first thing I read that day – and I ordered it immediately. It arrived today, so as is my tradition, the first thing that I’ve done with it is to run the FORTRAN version of the Whetstone Double Precision benchmark, compiled using gfortran.

Before I get to the results, it’s worthwhile noting how simple the Pi 3 was to set up and attach to my wireless network. I still remember my experience with the original Pi some four years ago, where simply getting an operating system onto an SD card took quite a lot of effort, and persuading it to work over WiFi even more. I think I spent a couple of days getting it to work properly – possibly longer – and got to play around in configuration files that I’d forgotten all about in the 25 or so years that had passed since I used to hack Sun UNIX kernels for a living.

Now, four years on, the first startup process is stupidly easy. Along with the Pi 3 (£30) and a case (£13), I’d bought a micro SD card with Raspbian pre-loaded (£6). This automatically configured itself when I powered up the Pi 3 for the first time and once that had finished (around 10 minutes or so) immediately rebooted into the desktop environment. A simple right-click on the WiFi Networks icon on the task bar allowed me to select my network and enter its password.

Installing a FORTRAN compiler was simple – all I had to do was open a terminal window and type:

sudo apt-get install gfortran

I also installed a copy of scrot (for taking screenshots) and gimp, so that I could edit them. A pre-installed version of Libre Office meant that I’d also got a spreadsheet editor with no effort – and no additional cost. Both gimp and Libre Office Calc seem to run exceptionally well on the Pi 3. I did try gimp on the original Pi, but lost the will to live waiting for it to do anything. As for Libre Office, I wouldn’t have dreamt of trying it.

So, to the results. The graph below compares the same benchmark using identical source code on the original Pi B, the Pi 2, Pi Zero and Pi 3. Over 10 runs, it manages an average of just under 400 MIPS – and like the Pi 2, that’s on one of its four cores (as the benchmark isn’t threaded). So at a cost of £30, that works out an amazing 7.5 pence per MIP – or less than 2 pence per MIP if you’re running something that can utilise all four cores simultaneously. The Raspberry Pi Foundation say that the Pi 3 is 10x faster than the original – this benchmark result therefore more than supports their claim.

Whetstone Double Precision Benchmark

All I need to do now is to find something useful to do with it (I have a couple of Internet of Things projects I’m looking at), although if my Windows 10 desktop ever gives up the ghost I think I might be tempted to simply replace it with a Pi 3, attached to my network storage device. The whole of this article has been prepared using the Pi 3, using the pre-installed Epiphany web browser to access my self-hosted WordPress site.

Raspberry Pi 3 - Raspbian Desktop

If my Pi 3 continues to perform reliably, I’m not sure why I’d ever need to buy a traditional Windows desktop again.

Whetstone FORTRAN benchmark on the Raspberry Pi Zero

I eventually succumbed to my gadget cravings over Christmas and spent the princely sum of £4 on a Raspberry Pi Zero(*). This has enabled me to re-run the Whetstone double precision FORTRAN benchmarks that I’d previously tried out on my original model B and the Pi 2 last year.

Pi Zero and a 1964 penny coinMy Pi Zero with a 1964 penny coin for scale …

My configuration is currently headless as the HDMI output appeared to stop working after around 5 minutes use. At less than the price of a sandwich at an average motorway service station, it’s not worth the hassle to send it back for the refund graciously offered by the supplier to my somewhat tetchy tweet … I’ll simply replace it with another one when they’re a little easier to obtain.

Anyway, taking an average of 10 runs over 100,000 loops, the benchmark indicates a performance of 201,159 double Whetstone KIPS (thousands of instructions per second), which puts it squarely between that of the original model B (150,962) and a single core of the quad-core Pi 2 (276,369).

The Raspberry Pi Zero running the FORTRAN Whetstone double precision benchmarkBenchmark output

Hmm. Now what?!

(*) In reality £18.50, including postage and packaging, an 8Gb micro SD card and the Pi Zero essentials kit from The Pi Hut.

Benchmarking the original Raspberry Pi Model B

Yesterday, I used the FORTRAN double precision Whetstone benchmark to assess the new Raspberry Pi 2. The results are rather impressive.

For the sake of completeness, I spent this morning dusting off my original RPi, installing the same operating system (Raspbian) and compiler (gfortran) to repeat the test.

Double Precision Whetstone Benchmark Results, RPi 1 Model B The result – an average of 150,962 KIPS over 10 runs of 100,000 loops, compared with 276,369 on a single core for the RPi 2. Which on this single, somewhat flawed (albeit interesting) benchmark, makes the RPi 2 around 1.8 times faster than my original model B, or 7.2 times faster across all four cores.

 

Benchmarking the Raspberry Pi 2

When I saw that the Raspberry Pi 2 had been launched earlier on this week, I immediately decided that I had to have one. My original Raspberry Pi had been slowly gathering dust on the study windowsill for a couple of years, largely because my initial enthusiasm for it had waned rather quickly. It was simply too slow and unresponsive for me to be able to do anything very interesting with it.

However, my experience so far with the RPi 2 is making me wonder why I bothered to buy a new PC towards the end of last year. For the princely sum of £29.93 (delivered) from CPC (plus an additional £16 for a 5V, 2.1A power supply – the 700mA phone charger that worked with my original model B simply wasn’t up to the job), it’s more than adequate for programming tasks.

The RPi 2 even runs a web browser sensibly, which is more than I ever really managed to achieve with my first RPi. (Geek note: this post was written on my RPi 2, using the Chromium browser).

But just how good is it? A number of people have been testing its performance by playing old computer games on emulators, but that seemed a little bit too subjective for my tastes.

So instead, I installed a FORTRAN compiler and dug out a copy of the double-precision Whetstone benchmarking program(+). An average of 10 runs over 100,000 loops each (on a single core of the quad-core ARM v7 processor of the RPi 2) gave me a result of 276,369 double Whetstone KIPS (thousands of instructions per second).

Double Precision Whetstone Benchmark Results, RPi 2

It’s only when you dig out the historical results for this benchmark(*) that you start to realise how astounding this performance figure is. For example, the VAX 11/750 that I used for the first time at Warwick University in 1982 delivered around 510 KIPS of performance and was typically shared by two dozen people at once. At particularly busy times you could wait for whole minutes simply for the text editor to start.

The Prime 9955 that was the mainstay of development work when I joined my first company, PAFEC, delivered 3,450 KIPS, according to its 1986 benchmark results. I still have my original contract of employment, which stated that staff who worked on “the computer” were encouraged to adopt some rather unusual working hours. The Silicon Graphics Indigo2, the workstation that everyone wanted to use in 1993 as it was a byword for high performance computing, clocked up a very respectable 90,000 KIPS.

It’s only when you get to the release of Pentium II based PCs in 1998 that you start to see similar performance figures to that of a single core of the RPi 2. And you need at least a Celeron M or Pentium IV based PC from 2003 or 2004 to match the performance across all four cores.

I suppose I really ought to knock the dust off my original RPi and see how it performs with the same code …

Update, 8th February 2015I’ve now repeated the benchmark on my original model B.

(+) The Whetstone benchmark seems particularly appropriate, as like the Raspberry Pi, it was created in the UK.

(*) I’m indebted to Roy Longbottom and his collection of benchmarks for the historical performance information referenced in this post. The documents covering the development of the Whetstone (and other benchmarks) he’s curated are a fascinating glimpse into one aspect of the history of computing over the last 60 years or so.

 

Star Trek game – a Python port from Tiny BASIC

A while back I mentioned that I was in the process of porting an old Computing Today Star Trek game from Tiny BASIC to Python on my Raspberry Pi. This was before I’d taken the edX Python course and learned to code properly in the language.

Frankly, although my code works, it is truly horrible stuff. And I didn’t even have the excuse of being limited to a couple of kilobytes of memory that the original was designed to fit into. I’ve just never had the time since to go back and do it better.

However, a couple of people have asked for the code, so here it is, in all of its – ahem – glory.

The original Tiny BASIC version (pdf format) – you’ll need this to make sense of how to play the game.

My Python port (pdf format) – you’ll need to copy and paste this into a .py file to make it work with a Python 2.7 interpreter (obviously).

Have fun!

 

Raspberry Pi, Python, Star Trek and Morecambe & Wise

I’ve now managed to get a first, very rough version of I.L.Powell’s 1979 Triton Tiny BASIC ‘Star Trek’ game to work in Python on my Raspberry Pi. Most of my effort has been spent in understanding how the original game worked – not easy, even for someone who learned to program in BASIC at about the time the original article was published.

As I wrote in an earlier post, I wanted to try to remain reasonably faithful to the way the original game worked, even to the point of preserving the original data structures and codes. I have however made a few tweaks – the most noticeable being to slow parts of the program down to try to replicate that ‘authentic’ early home computer experience! I think I’ve achieved that part of what I set out to do.

As for my other aim of producing some reasonably elegant Python … well, not yet I haven’t! My code is a hack – and a fairly nasty one too. All this exercise has convinced me of is that 20 years or so after I cut my last piece of production code I absolutely need to go back to basics (if you’ll forgive the pun) if I’m ever going to become reasonably proficient in the language.

So I think I’ll spend a little time over the next few weeks working my way through the MIT OpenCourseWare in Object-Oriented programming in Python – it seems as good a resource to try as any.

For anyone who’s really interested, this is the original Tiny BASIC version – and this is my first working attempt in Python. Shield your eyes from my attempt if you believe that code should be poetry … to be brutally honest, this code is more like Eric Morecambe playing Grieg’s Piano Concerto in the 1971 Christmas Show.

“I’m playing all the right notes—but not necessarily in the right order.”

Raspberry Pi – Python Star Trek progress

Since my Raspberry Pi arrived a few weeks ago, I’ve been tinkering with it rather a lot. For example, I’m currently on my 3rd operating system build. I’ve already been through the Debian squeeze and wheezy beta, and last night I started using a version of the Raspbian port (derived from Debian, but complied to take advantage of the floating point processor on the Pi, meaning better performance for most things).

All this tinkering means that I haven’t got as far as I hoped with my attempt to learn a little more Python by creating a port of a Star Trek Tiny BASIC game, originally published by Computing Today (CT) in October 1979. Its been slow going – and not only because I’m busy with other things!

My first problem was trying to understand how the original software worked. It’s not easy – and an extract of the original listing from the magazine illustrates why.

The limitations of the Tiny BASIC language combined with the limited memory capacity of home computers in 1979 (8 kilobytes would have been a luxury for most people) mean that it’s a rather difficult program to decipher, even with the two pages of description CT published in addition to the listing.

In some ways I’d have been better off redesigning the game from scratch. However, I’m trying to aim for as an authentic reconstruction as I can manage, but one that is better structured and in Python. My quest for authenticity applies even down to using the same data structures for the galaxy and the 64 sectors it was divided into in the original game, making sure that I’m using the same encoding for stars, starbases and Klingons. The porting task would have been far simpler if I’d decided to abandon the original data structures and used something far more powerful in their place, but that would have felt like cheating.

Even so, I think I’m around halfway there. Here’s a screenshot of the Enterprise -O- moving through Klingon >!< infested space to prove it …

… and a small snippet of Python to show how a sector of the galaxy is decoded. (Hint – the value in the galaxy array for sector 17 shown above is 305).

 

1 2