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.

Carsington eight: a Seven driving route

Here’s an enjoyable driving route around Mid Derbyshire. Especially on a cold but sunny Saturday in February in a Caterham 7. What other way is there to travel?

This slideshow requires JavaScript.

My route map is below, just in case anyone is interested in replicating the experience. I can recommend Kedleston Hall, Carsington Water’s Visitor Centre and Middleton Top as places to visit on this route if you’re not in a hurry …

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.

Star Wars, Aliens, Zombies. Cinema firsts.

I’m not much of a film buff. I am occasionally persuaded to go to the cinema by my better half and even though I tend to gripe somewhat a lot beforehand, I usually enjoy the experience. However, I can only remember one time where I’ve visited a cinema alone – which was to see The Damned United. I even own a copy on DVD, but I don’t tend to watch it that often as it makes me cry. This is because I don’t expect to see Derby County win anything again in my lifetime, let alone The Premiership.

Anyway, the latest and 107th suggestion from Post40Bloggers is to write about your first cinema experience. As always, I’m going to bend the rules (what rules?) slightly and talk about my first three cinematic firsts instead.

My first ever trip to the cinema was with my brother to see Star Wars in 1977. My mother took us, under protest, to the long-demolished Ladbroke Film Centre in Chaddesden. Even as a mere thirteen year old I could tell that the place had seen better days. What had once been a glorious single screen Art Deco cinema had been turned into a failing bingo hall with two small upstairs screens where the balcony had once been. I remember the carpet being sticky with popcorn and something that was too orangey for crows. Star Wars seemed exciting enough at the time, but you have to remember that I didn’t have anything to compare it with. I haven’t watched Star Wars, or any of the many sequels / prequels since and I don’t feel as if I’ve missed out on life.

The second experience I’ve decided to recall is the first X certificate film I saw. I can date this precisely, to the Saturday afternoon of 24th November 1979. This was the day that the then European Cup holders lost to the mighty Rams 4-1. I know this to be the case as when I was traveling home on the 102 bus there were several people reading “the green ‘un” football special which had the glorious news splashed all over it. The joy was short-lived – Derby were relegated at the end of the season.

The film I saw? Alien. I fell in love with Sigourney Weaver, but not with the film. I’ve tried to watch it again a number of times, but I don’t think I’ve ever made it all the way through to the end.

My third cinematic first is from the summer of 1980. This was the first time I took a girl on a date to the cinema. To watch Zombies – Dawn of the dead. The one set in a shopping mall. With lots of gore and violence. Not exactly romantic. With hindsight, it perhaps wasn’t the best choice of film. Somewhere towards the end, there’s a particularly gruesome scene involving a helicopter. It certainly disturbed my companion, as she drove her very sharp nails deeply into the back of my hand. I still carry some tiny white scars from that evening today. The relationship didn’t last.

As I wrote at the start, I’m not a film buff. At all. But given my early experiences of the cinema, is it any real wonder?

Lymphoma: facing change

Last night I was on a flight from Rome to London. A couple of hours into the flight I was bored and distractedly looking at photographs on my tablet. I came across a selfie I’d taken in May 2015. I’ve no idea why I took it (I suspect that I hadn’t realised that I’d taken it), but it reminded me how much the left side of my face and neck has changed since my lymphoma diagnosis.

Here’s the photograph I found from May 2015 …

May 2015 selfie… and here’s the one I took last night somewhere over the English Channel.

January 2017 selfieI’m pleased to see that my eyebrows remain as wild and as out of control as ever. But those lumps. Crumbs. That’s some progression. It’s a good job I’ve never been vain about my astoundingly handsome looks. (I did however have to put the camera into ‘beauty face’ mode, so as not to scare the young and impressionable).

The good news is that chemotherapy will reduce the size of the lumps if it’s successful. The bad news is, well, chemotherapy. At the moment I’m happier without it given the general outcomes for MCL treatment, as the longer I can safely put treatment off the longer I’m likely to live.

I’d still got my tablet out as we were coming into land and was treated to some lovely views over London as the night was clear. I was over the wing, so my view was restricted, but here’s the most in-focus shot I managed, to distract you from gazing on my lovely countenance. Canary Wharf is in the centre, with the Millennium Dome (or whatever it’s called now) on the right. London is so much more attractive from 4,000m than at ground level.

London from the air, 14-01-2017

Inspired by the 48th post40bloggers writing prompt: Sit in front of a mirror and write about your face.

Open University enrolments fell again in 2015/16

It’s the time of year when HESA – The Higher Education Statistics Agency – issue their statistical first release covering student enrolments and qualifications obtained. Against a background of a small annual rise in all enrolments at UK HE providers (up 1%) and a slight fall in part-time ones (down 1%) on the previous year, Open University enrolments fell a little over 4% (*). This marks the sixth straight year of decline from a peak of 209,705 in 2009/10 to 126,620 in 2015/16. Postgraduate enrolments are around half of what they used to be.

Part-timers now account for 24% of undergraduate and postgraduate students. In the years preceding significant changes to HE finances (the abolition of ELQ funding under Labour and the tuition fee reforms under the coalition) this figure was closer to 40%.

Open University enrolments 2008/09 to 2015/16 However, the drop is nothing like as dramatic as in previous years. As a graduate of the OU, I hope that this signals it has managed to identify a new ‘core’ market and has a sustainable future. After all, in an increasingly competitive and uncertain world, top class HE providers offering accessible second chances will become ever more important.

 

 

(*) Source: Table 3 of the SFR. Numbers obtained by adding together the total number of undergraduate and postgraduate enrolments at the Open University in England (which includes overseas domiciled students), Wales, Scotland and Northern Ireland.

Raspberry Pi motion sensitive camera

Other than messing around with a few FORTRAN benchmarks and learning how to code using Python, I haven’t really used my Raspberry Pi computers for very much that’s been practical. However, having bought a Raspberry Pi camera to play with over Christmas, I decided to have a go at building a motion sensitive camera for the garage. It’s cheap and easy to find passive infrared detectors these days, so I acquired three for the princely sum of £5.

The passive infrared detector
PIR detector

The first challenge was working out the function of the three pins in the foreground. A little bit of searching led me to the conclusion that the top pin is the ground, the bottom pin the 5v supply, with the middle being the status pin. If the middle pin goes high, it means that motion has been detected. The sensitivity of the device, and the length of time the status pin stays high for, can be adjusted using the two potentiometers.

I connected the power pins to a couple of the available 5v supply and ground pins on a Raspberry Pi 2. I used physical pin 26 (GPIO pin 7) to connect up to the status pin.

The code

The next challenge was writing some code to detect changes in the status pin and take a photograph when motion is detected. Fortunately, there are plenty of code snippets available that made this task relatively straightforward. The current version of my code is below.

import RPi.GPIO as GPIO
import time
from picamera import PiCamera
 
# Initialise the camera settings
camera=PiCamera()
camera.resolution=(1024,768)
camera.rotation=(180)
camera.meter_mode=('backlit')
 
# Use GPIO pin 7 (physical pin 26) for the PIR detector
GPIO.setmode(GPIO.BCM)
GPIO_PIR=7
GPIO.setup(GPIO_PIR,GPIO.IN)
 
# Variables used to determine when a picture should be taken.
# GPIO pin 7 => high (ts==1) from low (qs==0) 
# triggers the camera.
ts=0
qs=0
 
try:
 
  # Wait until PIR GPIO pin is low (0)  
  print "Waiting ..."
  while GPIO.input(GPIO_PIR)==1:
    ts=0    
  print "... detector is ready"     
 
  # Loop until quit signal
  while 1:
 
    # Read PIR state
    ts=GPIO.input(GPIO_PIR)
    # DEBUG print ts
    if ts==1 and qs==0:
      # Create unique filename with timestamp and set qs high
      t=time.localtime()
      timestamp=time.strftime('%Y%m%d-%H%M%S',t)
      filename=("img" + timestamp + ".jpg")
      camera.capture(filename)
      print "Movement detected - ",filename," created"
      qs=1
    elif ts==0 and qs==1:
      # GPIO pin 7 has returned to low, therefore set qs low
      qs=0
 
    # Wait for a second
    time.sleep(1)      
 
except KeyboardInterrupt:
 
  # Cleanup GPIO
  GPIO.cleanup()
  print "PIR-PiCamera program terminated"
The results

My Raspberry Pi 2 is now set up in the garage with the motion detector and camera. At the moment it’s simply saving the images onto a drive available to my home network, but I’m probably going to experiment with sending email alerts as well.

Raspberry Pi motion sensitive cameraI’m pleased to report my motion sensitive camera has already caught an intruder …

C7 thief!

Lovely, lovely grudges

I hold many grudges. Truly, I do. There’s the grudge that I hold from way back in infant school, where a teacher falsely accused me of the crime of walking on the newly planted flower beds. She moved to South Africa a few weeks after the incident. (The incident that didn’t happen, except in her mind, I hasten to add). I still held onto that grudge even as she was weeping her goodbyes at a school assembly. And guess what? I started to hold a grudge against South Africa – just because they were letting her move there. I haven’t revisited that particular grudge recently, but I suspect that it’s still there, fueled by their many recent cricketing victories over England.

I hold grudges against people who I’ve never met and don’t know. For example, there’s the one that I hold against the English O level examiner who had the temerity to ‘only’ award me a grade B. The aftermath caused me immense pain, both at school and at home. The confidence I lost in my academic abilities on that fateful winter morning as I was handed the results slip has taken me the best part of a lifetime to recover from. Well, not really, but I’m not going to let a nebulous concept like “truth” get in the way of me and my grudges.

However important these issues may have seemed to me at the time, neither could be said to have had any lasting impact on my objective well-being. Yet the hair still stands up on my neck when I think about them and the blood courses furiously in my veins.

So just imagine for a moment the strength of the grudge I hold for the dissembling politicians who lied and conned the country into supporting a vote to leave the EU. It’s almost as strong as the one that I now hold for the politicians who half-heartedly supported remaining, but who are now doing everything in their power to make sure that we leave on any terms – good or bad. However, I definitely don’t hold a grudge towards the growing number of leave voters who feel (rightly) that they were duped by these folk. I’m looking forward to seeing them punish this “elite” at the ballot box for many years to come as their lies are exposed.

But perhaps these feelings about the liars for leave aren’t really grudges. For me, a grudge that I can brood over and milk for years has to be completely irrational and relate to circumstances that I can do nothing about. A bit like the feud in Romeo and Juliet between the Montague and Capulet families perhaps. That’s a proper, irrational grudge that none of the protagonists understand the origins of or can fix unilaterally. But, I am, at last, starting to do something positive in politics again, to try to change things. It’s been a few leaflets here and there in 2016, but now the MSc is out-of-the-way and provided my health holds out, I hereby resolve to become rather more active in 2017.

 

This rant was brought to you courtesy of the 105th Post 40 Bloggers writing prompt. Please don’t hold it against them.

1 2 3 83