Weatherizing a Raspberry Pi Camera with a Microscope slide

Sticking a Raspberry Pi camera exposed to the elements doesn’t do it any good over time, resulting in the hazy crazed lens problem.

Flare on the camera lens after a year in the open
Flare on the camera lens after a year in the open

The solution is to put some glass in front of the lens – and indeed this is exactly what this commercial outdoor spec little lipstick CCTV camera does

it's hard to see, but there is a round glass against an O ring in gront of the camera lens on this weatherpoof camera, which has spent several years outside and still works well
it’s hard to see, but there is a round glass against an O ring in gront of the camera lens on this weatherproof camera, which has spent several years outside and still works well

I discovered this when I took it apart to unscrew the lens a bit to make a close focus. And then cracked the glass refitting it as the lens stuck out too much. If you ever need a flat round piece of glass, search for watch crystal on ebay and they are to be had in lots of diameters. A watch crystal is apparently a term for the glass on a watch as well as the 32,768 Hz timing quartz crystal. A flat watch crystal repaired this camera.

The direct exposure of the camera lens to the elements is the biggest weakness of the now-defunct PICE weatherproof Pi case. But it is easily rectified now, using a piece of flat glass fitted with Sugru or Milliput putty. I used sugru and a cut down microscope slide, since I didn’t want to buy another watch crystal when microscope slides are optically flat and cheaper. It is a lot easier to cut glass under water, and you can remove the viciously sharp edges using a cheap diamond sharpening stone to smooth the cut edge and chamfer the corner.

Microscope slide fitted with Sugru to shed the water and seal the camera from the elements
Microscope slide fitted with Sugru to shed the water and seal the camera from the elements

Continue reading “Weatherizing a Raspberry Pi Camera with a Microscope slide”

Aspirated air temperature sensor for a Polytunnel

In the UK air temperature is normally measured in a passively cooled Stevenson screen. The louvred design of the screen allows air to flow around the thermometer. The trouble with a polytunnel is there is no wind at all, as a result the sun heats the sensor up and without airflow you don’t know by how much.

By running a computer fan driven off a solar panel I can move enough air past the sensor to exchange the heated air from the sun shining on the sensor. For the sensor I use the standard Chinese supplied DS18B20 encapsulated in a stainless steel tube

Dallas DS18B20 epoxied in a stainless tube housing, from a Chinese Ebay supplier
Dallas DS18B20 epoxied in a stainless tube housing, from a Chinese Ebay supplier

The sensor is housed in a 6cm piece of white plastic waste pipe

sensor mounter in centre of white waste pipe
sensor mounted in centre of white waste pipe

The fan is mounted at the top of the pipe, designed to pull in air from below; this way the sensor is not heated by air passing the fan motor, and the airflow works with the natural tendency of warm air to rise. I’ve tried to keep the airflow as unimpeded as possible.

side view - the flange for the fan is made from a piece of wood glued to the pipe
side view – the flange for the fan is made from a piece of wood glued to the pipe

Looking at the results there is a difference of a few degrees

the difference opens up a few degrees at high temperature

between the aspirated sensor and another sensor mounted on the outside of the plastic tube. They track at low temperatures but not when the sun is shining – the difference here is about 6 degrees, even in March, before the vernal equinox. It is remarkable just how much the air temperature swings – 27 degrees on a couple of days which still have hazy sun.

Sensor mounted in polytunnel
Sensor mounted in polytunnel

Weatherproofing the sensor is easier in a polytunnel because as well as the wind not blowing, it also doesn’t rain. I can use a cheaper indoor solar panel, the one I used is a 12V 1.5W unit, Maplin L58BF bought on sale for about £6, not the £20 they seem to be charging for it. even £6 is a little dear! I extracted the flashing blue LED and series diode to maximise the power available to the motor. This also charges the battery of the temperature sensor dual unit, which reports back to the collecting station using Ciseco’s XRF every 10 minutes.

Solar panel schematic
Solar panel schematic

The computer fan was a 12V brushless unit but I run it at about 7V, we’re not after blowing a gale through the tube. It will start at 5V. The Zener is there to limit overcharging of the 4.8V NiMH battery pack in the electronics to about 4mA. It only reports every 10mins so this is enough. The 1N4148 diode stops the battery discharging back through the fan and solar panel in the night. I should really measure what the leakage current of that Zener is 😉

I used a PIC 16F628A driving a Ciseco XRF to send the temperature data from two sensors back. Nowadays I would use the Ciseco RFu which includes an Arduino and low-power standby mods to make this cheaper.

Other implementations

This is a nice weatherproof design – I can’t work out if I missed a trick with using just one plastic tube rather than a coaxial design. Lots more ideas here.

Postscript (July 20 2015)

five months of data
five months of data

This rig works reasonably well; if power were available I’d run the fan all the time in daylight for a more rigorous result on summer cloudy days. The biggest problem in a polytunnel is that they are shockingly dusty places, and you have to sponge the dust of off the solar panel every month or so.

The Texas LP2950 oscillates as an adjustable regulator

Nowhere in the datasheet does Texas tell you “hey use this fixed regulator as an adjustable”. However, I’m used to being being able to do that with the venerable 78XX series – indeed Texas tell you that you can do that with the 78L05 datasheet in Fig 14.

Adjustable 78l05. bear in mind the shocking Iq of 3mA that'll stand you up an extra 3V if resistor R2 is 1k, keep 'em low...
Adjustable 78l05. Bear in mind the shocking Iq of 3mA that’ll stand you up an extra 3V if resistor R2 is 1k, keep ’em low…

Given that there’s an adjustable variant of the LP2950 that appears on the same datasheet (the LP2951) I laid out a PCB and being the lazy sort I am I assumed that since I was using a load of these parts in their 3.3V KY5033 variant, where I wanted an 8V stabilised voltage for an audio mic amp sourced off a 12V supply I can simply do the LM317 trick, drop in a couple of resistors from the output to ground and the ground pin to real ground, job done.

what I planned...
what I planned…

For this I made R1 6k8 and R2 10k.I expected an output voltage of 3.3+3.3/6800*10,000=8.2V or near enough. I screwed up labelling the o/p 10V, mistakes happen…

What does that look like then?

Oy vey, about 4V of massive oscillation (I’m using 10x probes). At least it’s centred on the right value-ish. Let’s take that output capacitor out

1503_lp2950_openLooking good, only 1V of oscillation, now at 370kHz or thereabouts.

So if you come here from Google wanting to know why the LP2950 doesn’t work as an adjustable reg, now you know. There is a tiny clue in the datasheet in the ground current variation

LP2950 variation in ground current with output current

which varies by two orders of magnitude with a load current variation of 1000. This will be impressed upon R2, varying the target voltage – as more current charges the capacitor the target voltage will rise, then ease off as it is charged, making a handy relaxation oscillator.

There’s another clue that the output cap can give interesting results in this line

1503_2950_cap

which actually specifies a ESR range, rather than less is better

No criticism of Texas’ product implied – these are great little fixed voltage regs with a low quiescent current and are my goto device for running 3.3V devices off a 5V rail because of that superb dropout voltage of 600mV max, across the entire range of load current and -40 to 125°C which is easily in spec off a 4.75V min 78L05. It’s just one less thing to worry about. Im future I won’t be a doofus and try and use one where a LM317L is called for 😉

 

Raspberry Pi Camera and Motion out of the box – Sparrowcam

The idea is simple enough – a bird feeder camera on the network, using the Pi and associated camera. Using motion detection software I can pick out the birds. Of course I will also get the feeders swinging in the wind 😉

Although this is about running motion I can use videolan instead to stream the video as a netcam and use motion on a second machine. Videolan streaming

cvlc v4l2:///dev/video0 --v4l2-width 640 --v4l2-height 480 v4l2-chroma h264 --sout  '#standard{access=http,mux=ts,dst=0.0.0.0:8082}'

is nice on the Pi, because it seems the camera can do the h264 in some sort of hardware/accelerated mode in the V4l driver. I can then watch the birds with realtime update rates on my LAN. That’s for another day…

width 1296 looks okay
Spadgers

Up to about mid 2014 it used to be a load of hurt to run Motion and the Raspberry Pi camera because there were no videoforlinux drivers for the camera. That way you don’t get a /dev/video0 for the Pi Camera and needed workarounds for Motion.

Now there is a driver which you’ll already have on a Raspbian install, and it’s easy to use. right out of the box. Continue reading “Raspberry Pi Camera and Motion out of the box – Sparrowcam”

Oxford Real Farming Conference 2015 – making a remote farm camera

This is a description of how to make a remote farm camera. Smallholders don’t always live on site, or you may have an island site somewhere without power. The simplest solution to get pictures from a remote site without power is to use a 3G trail camera and these work very well for tracking wildlife.

The trouble with this solution on a farm is that animals are meant to be on a farm all the time, Trail cameras look for warm-blooded critters so mammals and birds will set it off all the time, making this an expensive operation in MMS messages, which seems to be the preferred method. Even if you get a MMS bundle, trawling through the false alarms will bore you.

What we wanted of a remote farm camera

was to be able to check on how things were going, and whether something has been damaged by stormy weather. A CCTV camera on the farm would be fine, but the problem with this is the power drain, and getting the pictures back. If we had mains power this would be a lot easier, we could use a 3G CCTV DVR with remote access capability. You can easily get 12V CCTV gear, but the power drain of a typical DVR and camera is quite harsh – typically 1A or more. A typical leisure battery is 80Ah, but you should only use half of the capacity of a lead-acid battery that to avoid reducing the service life of the battery, and you must never fully discharge it. This gives you a battery life of less than two days.

Our remote farm camera uses a Raspberry Pi Model A and associated camera to take a picture every 15 minutes in the daytime and upload it to a website

1501_rpcam02
Example picture from the camera

Continue reading “Oxford Real Farming Conference 2015 – making a remote farm camera”

Audio Measurements and beyond rightMark

The goto program for audio measurement in the Internet age is RightMark Audio Analyzer (RMAA). It’s not an easy program to use in isolation, and is used best with some old-skool analogue technology. In particular, it doesn’t really do absolute level in any way – everything is referenced to 0dBFS.

RMAA testing is deconstructed by NwAvGuy here. His thesis is that it is impossible to use RMAA right. particularly if you have no experience of analogue electronics and no other test gear. And I’m guilty as charged of publishing RMAA test results on the internet 🙂

It saddens me a little bit that measurement has now become go out and buy £x,000 worth of test gear, plug it it, attach to D.U.T. press the button and report the result. And if you can’t do that, well, no Audio Precision test kit, no comment. I’m not dissing NwAvGuy’s observation – it’s the loss of other ways of testing audio gear I regret. I don’t test for distortion – I scan for it. That’s because I’m testing finished gear usually for how noisy it is with mics at low levels. If distortion/frequency response looks okay/reasonable with RMAA that’s great, if it doesn’t I look for what I have done wrong in setup. Most manufacturers get the distortion and frequency response basics right, but mic preamp noise does vary because most audio recording is music and therefore has plenty of signal, so preamp noise is not usually a key parameter in a field recorder.

BBC Designs EP14/1 audio test set - a tone source and a meter
BBC Designs EP14/1 audio test set – a tone source and a meter

Way back when I was working at BBC Designs, using their EP14/1 test set things were a little more from first principles than ‘press the button of this expensive gear and report back’. The EP14/1 was basically a tone source and a meter with a precision attenuator in front of it.The meter was used comparatively – you would adjust the attenuators to make it read the same as a reference reading, and the wanted information was in the different setting of the attenuators. This way any nonlinearity of the meter scale was greatly minimised. Continue reading “Audio Measurements and beyond rightMark”

Field recording using an iPod mic input and SpectrumView

recording sound using a smartphone is like a dog’s walking on his hind legs. It is not done well; but you are surprised to find it done at all.

After Samuel Johnson

The smartphone/iDevice is the preferred window to the world of many people – it’s small, it’s handy, it does everything. It’s always with you. And it will do field recording, of sorts.

The internal microphone is usually a noise cancelling microphone designed to favour nearby sounds over ones far away – usually by letting ambient sounds sneak onto the back of the mic capsule to cancel out the ambient sounds impinging on the front. You, being closer to the front and shaded from the back cancel out less. Crude, but it sort of works.

Use an external microphone, not the handset one

That’s not where you want to go as a field recordist, indeed if you could discriminate against your fumbling and breathing noises you’d be better off 🙂

You want to be able to use an external mic. Omni for general run and gun ambient drive-by recordings, and a directional/shotgun mic if you want to pick out a particular birds. To use the latter well you need to be able to hear what you’re doing. Shame, is one of the big failings of smartphone audio is that your can’t record and monitor at the same time. It’s not unreasonable, you rarely want to hear that much of yourself in a phone conversation.

You need an external adaptor lead to convert the 4 pole headphone socket to a stereo headphone + mono microphone connector, these are cheap enough on ebay

You can’t do stereo microphone recording this way, it’s mono only. The input provides plug-in-power to energise electret mic capsules, because this is the typical active device in a phone headset.

Testing frequency response and sensitivity

I tested the frequency response using Rightmark audio analyser, and it looks good enough

Frequency sweep - this is good (the vertical scale is highly expanded)
Frequency sweep – this is good (the vertical scale is highly expanded)

Going in with 1k  tone at -67dBu and 150Ω source impedance the tone level was -32dBFS RMS   and with the tone off the signal was -70dBFS RMS implying a self-noise of -105dBu [ref]44.1kHz sampling, 22kHz BW, PCM, manual gain using the app SpectrumView[/ref] Which is acceptable for urban field recording, though not stellar.

Big FAIL in the field – no monitoring

The big trouble, however, is that you can’t hear anything through the headphones, so you can’t aim a directional mic. Which makes the whole rig a bit crap to use in the field, and this doesn’t seem to be fixable.

There are other bits that grate – for instance the iPod doesn’t always pick up there’s an external microphone, so you can end up viewing the internal mic instead. Then there’s the usual rattiness of apps all round, about 1 in 30 times it just hangs outputting trash on the screen. In general, as a field recorder, smartphones suck. They can be used, but anyone who has used a real field recorder will miss the positive action of real buttons, real record level controls, real metering, and yes, being able to hear what they are doing.

Wild Mountain Echoes has a good summary of the sort of hurt associated with smartphone audio recording. Dr Johnson was right. It can be done, just not well.

Big WIN in the field – live spectrum display

Being able to watch a live sonogram using spectrumview is pretty awesome, and it’s a good sonogram, too, quite well suited to general bird sounds.

The best of all worlds, use a field recorder before the iPod!

It is not done well; but you are surprised to find it done at all.

Best not argue with Dr Johnson 🙂 As a recorder my iPod was flaky and with an input noise level some 20dB off what it could be and mono it’s nothing special even when it does record.

You can get the sonogram by feeding the iPod or smartphone/i-Device downstream of your field recorder – simply use a headphone y-splitter out of the recorder with one side going to your headphones and the other to the iDevice input, and set the gain of the iDevice waaaay down. You don’t have to record with it.

You now have a reliable recorder, decent mic preamps, you get to monitor what you record and if the iDevice throws a wobbly then you still have a good recording. But you how get a lovely spectrogram in live real-time. This is something that’s really excellent. In an ideal world the spectrogram would be built into the field recorder, however running it really hammers battery life so it’s good to have it optional. And it needs to be in colour.

A lower energy more expandable Pigcam network

Is covering a 12-acre farm with WiFi a reasonable idea? If so, I could run multiple cameras, say have one on the cows and one on the pigs, all connected to a central location, On the upside, the farm is roughly square and with a mild slope to the ridge at the top. Everything is pretty much line of sight. On the downside, there’s no good central location, which would be the obvious way to service the farm with 2.4GHz WiFi. Distances are long – the field is about 250m wide/long, and I could easily pick up a 300m path length feeding from the edge.

the MiFi node and power management
the MiFi node and power management

Earlier experiments showed that I could in theory use native WiFi, using a router to receive BTFon from a broadband connection in the town over a high-gain antenna and redistributing it from a WiFi AP. The trouble is I am desperately short of power – every extra piece of kit means more frequent battery changing. In the end I went with a more powerful MiFi access point – one that supported an external WiFi aerial. I used a 9dB TP-Link patch antenna

This feed the farm from one edge, as it happens the antenna is furthest away from the most likely camera sites but slightly higher than the target sites. The signal pattern fans out quite well, serving the likely points of interest. I was chuffed with the performance of the aerial – it gives the right balance of directionality, as I don’t need to bother to serve the field behind me, but it gives very useful gain in the wanted direction – I can just about get a wifi connection with the internal antenna of my iPod touch from the opposite corner of the field. As the forest garden and some of the windbreak trees grow I may experience problems, but that is for another day. By then perhaps we have a site with mains power 🙂

For the MiFi unit I used a TP-Link MR3220 – it’s surprisingly hard to find a MiFi box with an external WiFi aerial socket, because not unreasonably they anticipate you using this sort of thing as a personal cloud. I had to live with the 9V powering and used a Chinese Ebay 12V to 9V converter switchmode converter to efficiently turn the 12V battery power to 9VDC

The other part of improving range is to upgrade the camera end with a WiFi card with an external rather than internal antenna; since the Pice case has been withdrawn I need another solution for that. The PICE case also still exposes the Raspberry Pi camera lens to the elements which is Not a Good Thing leading to the lens haziness problem.

It doesn’t really matter how big the camera is, so I took the opportunity of using a much larger box – a  Hammond case 1599 to fit it all in.

If you’re going to put something outside then the fewer holes you can drill the better, hence the use of sticky pads and cable ties as mounts, and the single 2.1mm power socket on the base, so water could drain out that way if necessary, and could be standing 0.5cm without affecting the electronics.

The case has several mounting lugs in the lid, but in the end I will have to drill a hole for the camera. I placed an O ring on the case and a microscope slide pressed down by foam and the camera to make a watertight seal but keep the elements out of the lens; that way hopefully I get to either clean or replace the microscope slide after a season is out rather than the camera.

camera mounted in the lid
camera mounted in the lid. Reed switch is top left wit the yellow wires, the 1p glued to the case holds the magnet there because they are made of steel these days not copper.

The 12V to 5V converter is mounted in the case; that way any cable losses aren’t too bad and the current in the supply cable is reduced, it is about 200mA max.

Setting it up in the field

Pig Camera in service
Pig Camera in service

The paving slab is there because the first version of the tripod ended up flat on its back in the morning. At least the construction can survive a fall of 2m. Perhaps the neoprene sunshade and the extra area at the top of the pole presents too much wind loading.

Camera close-up
Camera close-up

Controlling the Pi

I postulated all sorts of complex feedback when first considering this, letting the Pi tell the microcontroller to turn the Pi off with a GPIO pin, but it’s been massively simplified. A microcontroller powers up the Pi, and pulls the power after 5 minutes. Then it waits 10 minutes and does it again, provided that the 12V supply is enough (>11.5V) and it is daylight.

I use similar Python code to the first cut, but this time I start running the takepic.py camera code on startup. I look for a switch closed on the GPIO, and if so, abort uploading the picture because the Pi is in service mode1. This switch is a reed switch mounted on the inside of the case and activated by sticking a magnet to it, this saves a hole. It lets me get onto the Pi and configure it. Normally the switch is open, in which case the Pi tells the system to do a shutdown in 4 minutes, which is enough to connect, get Wifi network DHCP and SFTP the picture to the website. 5 minutes after powerup, the microcontroller managing power pulls the power from the Pi.

The shutdown command on the Pi minimizes the chance of corrupting the SD card, and the picture is written to the /run/shm/ ramdisk prior to uploading, since there is no point using up SD card write cycles with ephemeral data like that.

#!/usr/bin/python
#$Id: takepic.py 58 2014-11-06 20:54:02Z ermine $
import time
import picamera
import paramiko
import os
import socket
import datetime
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BOARD) # USE Pi BOARD pins, not the BCM ver
GPIO.setup(7, GPIO.IN, pull_up_down=GPIO.PUD_UP) # 7 is next to gnd on pin 9, so set pull up

# defs
camerafail=False;
DIR='/run/shm/'
imagename=socket.gethostname()+'.jpg'
remotename='WEBSITE.COM' # assuming this is reachable by ssh and www
try :
    with picamera.PiCamera() as camera:
        #camera.resolution = (2592, 1944)
        # The following is equivalent
        #camera.resolution = camera.MAX_IMAGE_RESOLUTION
        # run half res to test out connectivity etc and save money
        #camera.led = False
        camera.resolution = camera.MAX_IMAGE_RESOLUTION
        #camera.resolution = (1296, 972) # do half real to eliminate Bayer softness and save TX bandwidth
        camera.exposure_mode='night'
        camera.meter_mode='matrix'
        camera.start_preview()
        time.sleep(2)
        camera.capture(DIR+imagename, resize=(1296,972), format='jpeg', quality=20)
except picamera.PiCameraError,e :
    print e
    camerafail=True
finally :
        camera.close()
time.sleep(10) # hopefully nw is up by now 
if(GPIO.input(7) ==1):
    #print "will shutdown"
    os.system("/usr/bin/sudo /sbin/shutdown -h +4 &")

    if not(camerafail) :


        timedout=False
        connected=False
        counter=0

        while (not timedout) and not connected :
            try :
                s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
                s.connect((remotename,80))
                print(s.getsockname()[0])
                connected=True
            except socket.error,e :
                
                counter += 1
                print counter
            finally: 
                s.close()
            time.sleep(5)
            if counter >= 5:
                timedout=True
                print 'Failed to connect to ',remotename,' ',datetime.datetime.now().strftime("%y/%m/%d %H:%M")
        
        

         
        #upload
        if not timedout: 
            print 'ftp image starting ',datetime.datetime.now().strftime("%y/%m/%d %H:%M")
            try :
                ssh = paramiko.SSHClient()
                ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                ssh.connect(remotename, port=2222, username='USERNAME', password='PASSWORD')
                sftp = ssh.open_sftp();
                sftp.put(DIR+imagename, '/home/DIR/'+imagename)
                sftp.close()
                print "closed SFTP"
            except paramiko.AuthenticationException,e :
                print e
            except socket.error,e :
                print e
else :
    print "manually aborted by jumper 7 to 9"

Power savings

This has massively reduced the power drain of the camera – it is < 200mA for a third of the time, with an outage during the night of about 1/3 of the time, so about 1/3 × 2/3 × 200mA average, ie ~50mA. The original power drain was about 300mA 24×7.This power drain is much less than an electric fence which is usually about 150mA, so it could be used from the fence battery, which would then let us monitor the fence battery voltage as a bonus.

It also suits solar panel charging well, as the power drain is proportional to day length. The WiFi node draws more (a sustained 200mA during the day) but at least it is just one place where the battery needs changing more often – about once every two weeks. That’s livable with, but if I’d used a WiFi long-distance connect and a WiFi high power AP that would be shortened too much, particularly as logging into BT Fon would require another Pi to keep the connection open. GiffGaff run about £7.50 per Gb PAYG which isn’t bad.

Got pigs

Got pigs
Got pigs, end of the day picture in lowish light, 4:30 pm November

So far so good. The new pigcam

  • works all over the likely sites on the farm
  • concentrates the data through one GiffGaff SIM[ref]data service gets cheaper with volume, so this is much better than each camera having a SIM[/ref]
  • reduces power at camera sites to minimal
  • lets me add more than one camera to the system

which is a success compared to the single site version which had a very high power drain because it wasn’t being power-managed.

Pigs
Pigs, photo taken with a regular camera earlier in the day

  1. In service mode I get to ssh into the Pi to configure it, and issue the shutdown command manually – I bypass the microcontroller shutdown for that 

Testing the Wolfson Audio Board and Raspberry Pi

The trouble with birds is they get up earlier than I do, so a time-delay start recorder lets me scout locations without loads of early starts.Autonomous recorders are sometimes known as frogloggers in the nature recording community. Commercial variants and great, reliable, but dear. I want something I’m prepared to take the risk of losing to some inquisitive dog-walker, and preferably something I can make enough of to scout several locations.

A Raspberry Pi via Wifi is also a good remote startable recorder over WiFi . A bit like the Tascam DR-44WL but without the nice display. the trouble is the Raspberry Pi has no record facilty. If it had, you can start recording by logging in via SSH and issuing the arecord function. The audio can even be transferred off the Pi remotely via SFTP over WiFi. Enter the Wolfson Audio board – a piggyback audio card for the Pi, which takes over all the IO so you aren’t going to be running any other custom hardware on that Pi.

Installing the Wolfson

Physical installation is easy enough, the Wolfson board uses the bizarre approach of connecting to the GPIO using a standard header and the P5 header using a set of pogo pins.[ref]I did have trouble with these once – what happens is you issue the record for x seconds command and in simply sits there and never times out. Then you press the GPIO down again and it comes good… P5 carries the i2c bus  SCL0 and SDA0 pins which control the Wolfson, lose contact on one of those and you aren’t talking to it any more.[/ref] I’d have been easy with soldering an extra set of pins or a header myself and this is probably a reliability hazard, but I’ll run with it for now. Just as well I’m not going to use the badly aligned yellow and white SPDIF sockets, eh?

I started with a Model A running a stock Raspbian image, 2014-06-20-wheezy-raspbian.zip and ignored Wolfson’s recommendation to avoid a USB hub, because I needed that to see what I was doing to set up WiFi.

bizarre use of pogo pins, it's a wonder these make enough contact for the board to work at all!
bizarre use of pogo pins, it’s a wonder these make enough contact for the board to work at all!

No standard Raspberry Pi Drivers for the Wolfson

Unlike other bits of hardware, to run up the Wolfson card you can’t use the stock Raspbian and do an apt-get install some-sort-of-wolfson-driver. You’re in for a world of hurt here.

You either download the SD card image which is recommended by Wolfson. It’s 8Gb and it means 8Gb, and wouldn’t fit on my 8Gb card, because it requires a card with no dead sectors presumably.

Maybe time to compile the drivers myself following this? Nope – life is too short and I do not have the skillz to firefight what goes wrong. And what with the takeover of Wolfson by Cirrus it looks like the drivers are delayed still more. I like the Torygraph’s opener

Wolfson Microelectronics, the struggling Scottish microchip company, has been acquired by its American rival Cirrus Logic for £278m.[…]
Wolfson has become increasingly reliant on a few big customers including BlackBerry, which as seen sales of its smartphones collapse.
The company reported flat revenues of $179m and mounting losses of $13m last year.
Wolfson admitted it had been blindsided by the rate at which consumers were adopting 4G smartphones, which gave Qualcomm an advantage because it had developed an all-in-one 4G microchip that included an audio processor.

Damn. Those drivers aren’t going to happen any time soon, or maybe ever… I then used Ragnar Jensen’s zip described in this post, and the usage instructions here to install it. Which worked for me. I have no real idea how.

Don’t get the Wolfson card if you want playback until there are normal drivers available

My only interest in the card is to record – everyone else seems to want to take advantage of the whizzy playback options. To be honest there are alternatives if you want playback only, and it looks like the product is at risk of getting orphaned, since it is Pi Model A or B Rev 2 only, not B+, and is still driverless. You run the risk of getting stuck on an old version of Raspbian. That doesn’t bother me, as I will only use this for recording and not run anything else exotic on the Pi. If you want to run a media centre then you could start to hate being stuck on older versions of Raspbian.

How does it record, then?

I made the mistake of firing up ALSAmixer after installing, it certainly showed a lot of options and stuff going on which gave me a good feeling that the Wolfson card was present. But it is easier to adopt their installed ‘use cases’ that are installed in /home/pi

./Record_from_lineIn.sh

then issue

arecord -c 2 -f S16_LE -d 10 -r 44100 record_from_line_in.wav

to record a 10 second stereo track from Line in (that’s the -d 10 seconds, -d3600 would do you an hour, etc)

I experienced random buffer errors every 30s or so. Mindful of Wolfson’s warning about USB hubs I removed the keyboard (which has a hub) though I still used a hub to power the device, and because this was a Model A I had the wifi on the hub, and still took overruns

arecord -c 2 -f S16_LE -d 130 -r 44100 record_from_line_in1.wav
Recording WAVE 'record_from_line_in1.wav' : Signed 16 bit Little Endian, Rate 44100 Hz, Stereo
overrun!!! (at least 90.703 ms long)
overrun!!! (at least 50.601 ms long)
overrun!!! (at least 15.111 ms long)

Although it looks ghastly here is an MP3 of the original file that I played into the Pi –

and here is the file recorded with the overruns above, converted to MP3

Which doesn’t sound so terrible to me at all. I should still not be such a cheapskate and buy SD cards from ebay, if a Class 6 card is what’s needed for audio 😉

I still got overruns with FLAC but they were shorter, which points towards disk IO as being the problem, since FLAC ups CPU load a lot but reduces disk writing, because that’s its job

arecord -c 2 -f S16_LE -d 130 -r 44100 | flac -o test1.flac - --channels=2 --sample-rate=44100 -f

flac 1.2.1, Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007  Josh Coalson
flac comes with ABSOLUTELY NO WARRANTY.  This is free software, and you are
welcome to redistribute it under certain conditions.  Type `flac' for details.

Recording WAVE 'stdin' : Signed 16 bit Little Endian, Rate 44100 Hz, Stereo
-: 23% complete, ratio=0.468overrun!!! (at least 20.023 ms long)
-: 69% complete, ratio=0.513overrun!!! (at least 0.553 ms long)
-: wrote 11620131 bytes, ratio=0.507

Using FLAC (free lossless audio compression)

you must apt-get install flac

to get the codec first

Pipe the output of the record chain into FLAC to reduce file sizes by about 40% on field recordings

 arecord -c 2 -f S16_LE -d 130 -r 44100 | flac -o test.flac - --channels=2 --sample-rate=44100 -f

flac 1.2.1, Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007  Josh Coalson
flac comes with ABSOLUTELY NO WARRANTY.  This is free software, and you are
welcome to redistribute it under certain conditions.  Type `flac' for details.

Recording WAVE 'stdin' : Signed 16 bit Little Endian, Rate 44100 Hz, Stereo
-: wrote 11692886 bytes, ratio=0.510

with the flac command the single – means  process stdin and -f means overwrite existing file

FLAC used to be a resource hog so I thought I’d look at the CPU usage, which seems to run about 12-15% on a stock Raspbian (no overclocking etc)

top - 18:07:28 up  1:54,  2 users,  load average: 0.05, 0.04, 0.05
Tasks:  74 total,   1 running,  73 sleeping,   0 stopped,   0 zombie
%Cpu(s): 12.4 us,  2.3 sy,  0.0 ni, 84.9 id,  0.0 wa,  0.0 hi,  0.3 si,  0.0 st
KiB Mem:    187592 total,   145604 used,    41988 free,    14664 buffers
KiB Swap:   102396 total,        0 used,   102396 free,    98588 cached

  PID USER      PR  NI  VIRT  RES  SHR S  %CPU %MEM    TIME+  COMMAND
 2713 pi        20   0  7488 1380  940 S  12.1  0.7   0:03.71 flac
 2710 pi        20   0  4672 1372 1036 R   1.0  0.7   0:00.50 top
 2676 root      20   0     0    0    0 S   0.7  0.0   0:03.14 kworker/u2:3
   13 root      20   0     0    0    0 S   0.3  0.0   0:00.96 kworker/0:1
 2683 root      20   0     0    0    0 S   0.3  0.0   0:01.61 kworker/u2:0
 2695 pi        20   0  9260 1584 1000 S   0.3  0.8   0:00.12 sshd
 2711 root      20   0     0    0    0 S   0.3  0.0   0:00.18 kworker/u2:1
 2712 pi        20   0  4944 1336 1128 S   0.3  0.7   0:00.19 arecord
    1 root      20   0  2148  720  616 S   0.0  0.4   0:04.29 init
    2 root      20   0     0    0    0 S   0.0  0.0   0:00.00 kthreadd
    3 root      20   0     0    0    0 S   0.0  0.0   0:00.46 ksoftirqd/0
    5 root       0 -20     0    0    0 S   0.0  0.0   0:00.00 kworker/0:0H
    7 root      20   0     0    0    0 S   0.0  0.0   0:00.75 rcu_preempt
    8 root      20   0     0    0    0 S   0.0  0.0   0:00.00 rcu_bh
    9 root      20   0     0    0    0 S   0.0  0.0   0:00.00 rcu_sched
   10 root       0 -20     0    0    0 S   0.0  0.0   0:00.00 khelper
   11 root      20   0     0    0    0 S   0.0  0.0   0:00.00 kdevtmpfs

Wolfson Card Analogue Line-up

So it’s time to line the card up and find out what analogue levels it takes. I’m going to need outboard audio processing anyway to bring mic level up to line level, and to be honest that’s probably better done off the board anyway away from all the digital power-supply sizzle. I can control levels in the analogue domain, so no need ot run alsamixer unless I want to do remote live recording.

I injected 1kHz tone from a Farnell Wien bridge oscillator ad found that the default gain setting is exactly right for a 1V rms input

1V rms exactly...
1V rms exactly…
on a scope, not the readout is 10x too low because I used a 10x probe
on a scope, not the readout is 10x too low because I used a 10x probe, so that’s 2.8V p-p or 1.4V peak

When I ftp the file to my PC and look at it with a WAV player I see it is as close to 0dBFS as you can get

You aren't going to get closer to 0dBFS than this without clipping
You aren’t going to get closer to 0dBFS than this without clipping

The audio doesn’t start recording instantly, there is an elegant fade in combined with an inelegant DC shift

Audio fades in softly over a short period
Audio fades in softly over a short period

It isn’t a big deal, but you probably want to start it .1s before the desired sound. That’s neither here nor there with a manual start but if auto-started from a sensor trigger that would be a bear.

Audio performance

I terminated both inputs with 150 ohms and used Audition to gather the stats on silence, starting 3s in, a reasonable way past the initial DC bump.

internal noise stats. I'm not going to complain about this
internal noise stats. I’m not going to complain about this

I then scanned the spectrum of the quiet recording to look for any frequency spurs etc, on a fairly narrow IF bandwidth (wide scanning window). I’m not going to argue with the results –

Can't really argue with that
Can’t really argue with that

For reference here is the 1kHz tone (if you analyse it all the distortion comes from my 1970s era Wien Bridge oscillator)

and here is the quiet recording

I didn’t run rightmark on it since I don’t have anything good enough to generate the test signal and don’t know how to play and record at the same time on the Pi.

Since I want this for recording I didn’t bother to test playback – here’s a description of replay.

Time delay recording

The way to use this as a time delay recorder is to set cron to start on boot:

shutdown -h -t 3700

and

arecord -c 2 -f S16_LE -d 3600 -r 44100 record_from_line_in.wav

Then power on the Pi and the microphone preamplifier about half an hour before dawn and pull the power after about an hour and a quarter – the Pi should have halted by then. I will use a PIC microcontroller for that job, because it draws a very low power in the rest state, but an Arduino would work too, though it’s typically 7mA drain is higher than it has to be.

Conclusion

The Wolfson audio card records well, with low noise. You need to use a fast SD card otherwise you will get overruns. But it is poorly supported and the devil’s own job to get going. However, it seems the only game in town for high-quality recording.

Since that’s what I want to go I have to put up with the poor support and idiosyncrasies, it works well enough.

 

a Raspberry Pi camera after a season outdoors in the British weather

The old pig camera is due for a rebuild. I went with the Pice outdoor case for the new one, but  it’s interesting to see how the old one stood up to the weather. It was still operating when I decommissioned it because I needed to scavenge some of the network parts for the new one. In particular I now use a central WiFi/Mobile node to cover the whole farm, and use Wifi to upload the pictures for each camera via that node.

The original one ran the Mifi node and the Pi all the time, which was hard on battery power. Hence the rebuild, but if the case held up over a season I may as well use it rather than splash out for a new Pice…. The original case was larger than it needed to be, but I can now use this space to put the light sensor and 12V to 5V DC-DC converter inside it.

So how did it stand up to the ravages of the elements. When it was new it looked like this

best not let the IEE see that else they'll revoke C.Eng for disgraceful and outrageous bodgery of the first order ;)

and the innards looked like this

the Pi gets big fast when you hang enough onto it to make it useful
the Pi gets big fast when you hang enough onto it to make it useful

So from the outside it now looks like this

Raspberry Pi camera after a year in the open
Raspberry Pi camera after a season in the open. The messy carving of the rain-shield started out that way

Which isn’t bad. It vindicates one of the things i did, which was to use plastic screws for mounting. Unfortunately the camera needed M2 screws which were steel, and these rusted. The sun bleached the tape, but the box itself stood up to the light well.

The cheap Chinese DIN socket is starting to rust

1410_din_DSCN2527

I had fitted this on the underneath of the case. There are two philosophies when it comes to trying to run electronics outside. One is to go IP65 all the way and keep water out, which means waterproof enclosures, Dri-Plugs for power etc – you’re looking at about £20 to get the power through the case and maybe another £20 for the case itself. Farm hacks don’t really need that sort of ruggedness, which brings me ot the other philosophy

Accept water is going to get in. Mount all connectors on the bottom so it can drain out. I actually picked this up from the PICE guys – they mount the raspberry Pi on the lid of the case, so water could be standing on the bottom half and it would be okay.

No evidence of water, no creepy-crawlies - great
No evidence of water, no creepy-crawlies – great

As it was no water seems to have penetrated, no creepy-crawlies seem to have got in. The latter are a pain with electronics outside- they seem to be attracted to the heat, or maybe the power itself. It certainly helps to lift the device into the air, or simply put it on a stick a metre or so high, compared with ground mounting. But this looks clean, there’s a little bit of evidence ingress on the seam, and the PVC tape degraded in the UV so this may be worth some thought.  I will re-use this box, mounting the microcontroller timer and the light sensor on a board set into the rails, so I don’t have to drill the box for mounting.

However, one thing has been impaired, and that is the lens of the camera, which gives a hazy effect – it was clear and not foggy when this picture was taken

Flare on the camera lens after a year in the open
Flare on the camera lens after a season in the open

Normally a CCTV camera is behind a piece of glass to keep the elements out and now i know why. Cleaning the lens with IPA didn’t help. I am tempted to glue a piece of microscope coverslide over the tiny lens in future this would have the optical quality and would be cleanable/replaceable. Continue reading “a Raspberry Pi camera after a season outdoors in the British weather”