Skip to main content

Ironed curtains



Deep in the perilous land Whitehall officials call the West Country, a hidden menace stalks the pothole-ridden streets.  Under the cover of darkness, these miscreants loiter outside local Co-op stores and Lad-is-broke betting dens, and brutally ambush any odorous victim that they encounter (where the only known repellent is a black-market fragrance known as David Beckham's Intimate).  At the faint hint of a pungent nappy or a discarded Fosters tinnie (an Aussie mineral water drink with a dash of yeast) these beasts opportunistically pounce on and tear apart the sole pride of every Englishman and Englishwoman: their glorious refuse sack.


Clearly, the once-in-a-generation referendum on the exit from the union of the weekly bin collection, Bindyref II,  has not decisively settled the bitter divide, and a foul stench continues to linger on in every town and village up and down Blighty.  Perhaps, however, we can seek comfort from history: that this existential threat to our beloved trinity of wheelie bins, compost caddies and reusable rubbish bags grudgingly handed out by cash-strapped local authorities, is - in fact - not wholly a new one.

Such is the trail of destruction left behind by this timeless scourge, the Great Bard himself once recounted the almighty quandary regular English townsfolk grapple with when they are not in a local Lidl stocking up on 5L tubs of Greek yoghurt.  In arguably the playwright's most poignant masterpiece - Taming of the Doo Doo - the immutable question that haunts every resident the night before their biweekly visit by a fleet of exotic council vehicles was succinctly surmised in a single, momentous observation:

To bin, or not to bin, that is the question

...After all, the consequences of a premature "send off" of the family's un-recyclables can be monumentally catastrophic. Thanks to the unknown beast that roams the streets.


But recent advances in modern Pi-ence have allowed residents of these tormented isles to begin their courageous fightback.

These part-time warriors are no longer content to tolerate the humiliation of watching their gossipy neighbours inspect the remnants of their takeaway from the night before (and the 13 consecutive weekdays of Bindaloo before that).  Nor do they want to suffer the indignity of a morning sprint down their suburban cul-de-sac before the school run to retrieve a rogue bank statement blowing in the wind (yes, the nightly curries do eventually take their toll).

It's time to deploy a black-op reconnaissance apparatus that Farmer McGregor would have deployed, had he had a monthly subscription to The MagPi Magazine: the Pesky Animal Near-field Detection 'n' Alarm system.  Also known by its totally fictitious NATO reporting name:- the M4D "P.A.N.D.A".

The Spade Race:

What does a contribution of 2% of GDP towards to the Star Wars Rebel Alliance get us?  Let's enter our disused garden shed and dig up our corroding arsenal.
  • We start with a steadfast, ironclad assumption.  That these special ops incursions of the feral variety only take place in darkness, at night, while homeowners remain incapacitated from a Game of Thrones binge.  And this is precisely why we have equipped ourselves with an infra-red (IR) night-vision camera.  We connect the camera to a Raspberry Pi 3 Model B running Raspbian OS using the on-board Camera Serial Interface (CSI) port.  Job done.
  • Trust nothing.  Trust no-one.  Don't push Cheerios up your nostrils.  The post-war world is still awash with mistrustful advice steeped in paranoia.  Well here's another: keep your JPEGs safe.  As the International Court of Justice requires concrete evidence of a rubbish collection day ambush by unruly extras from Springwatch, we'll automatically upload photos taken by a camera to a pre-created bucket in AWS S3.
  • But... continuously taking photos of a council-branded reusable rubbish bag - all through the night - sounds kinda wasteful, and would take trashspotting to a whole new level.  OK, then.  Point taken.  We'll use a passive infra-red (PIR) motion sensor connected to an ESP32 development board running MicroPython to instruct the Raspberry Pi - using MQTT - to take a photo when it thinks it has detected movement.  And the development board will also have a light-dependent resistor to detect if it should be night-vision, or nay-vision.
Lock away your organic turnips.  And your vegan, lactose-free goji berry and flaxseed flapjacks.  We have received reports that an elite unit of unidentified animals is preparing an imminent incursion into our exposed backyard.  All units.  We repeat.  All units.  You are authorised to deploy the P.A.N.D.A.  Yes, sometime today would be nice.

The Sewage Crisis:

No thanks to austerity, we have patiently waited - precisely - 20160 minutes for the El Clásico, La Grande Boucle, the Weston-super-Mare AFC vs Chippenham Town FC, the Saturday kick-off.  Yes: the grand spectacle that is the weekly fortnightly bin collection day.

Picture the scene.  Bins are overflowing.  There are towers of Prosecco bottles that can be observed from the International Space Station.  Half-eaten kebabs lining the pavements that are mistaken for the Great Wall of China.  And the stench is simply overwhelming.  But enough about a typical Saturday night out in Bristol.  Let's for a second reminiscence of the good old I-O-Tea days, when things weren't quite like this:
  1. Frozen Pi
  2. Have-ocado
  3. Green, green grass of /home
  4. Quantitative wheezing
  5. LoRa-Wan Kenobi
  6. Soreen seems to be the hardest word

N-A-T2-O:

The Japanese soybeans might have become fermented, but this is unlikely to put off a vast cross-section of the four-legged, tailed mammal population whose ideas of a Michelin Star dining experience is a nibble on leftover Doritos crumbs.

As they say, rubbish is a dish served cold.  Well, here's the recipe for our three-course meal, straight out of Heston Blumenthal's Christmas cookery book.
  • First things first, we'll attach the infra-red night-vision camera to the Raspberry Pi using the CSI connector.  And simply by using Python's picamera module, we can carry out pest surveillance of the highest calibre.  And since we're all paranoid from watching too much news (and Love Island), we'll upload the images directly to AWS S3 using boto3 to protect us against dishonesty and heartache.
  • The PIR motion sensor simply outputs a HIGH when it believes that it has detected movement.  We can test this by attaching the module to the ESP32 development board, and monitoring in MicroPython a GPIO pin configured as an input.  MicroPython's built-in umqtt.simple can be used to dispatch a MQTT payload to the Raspberry Pi, instructing it to take a burst of photos.
  • The output voltage of a photoresistor-based voltage divider circuit, measured using ESP32's analogue to digital converter, can tell us whether it's light or dark.  We'll package this information up in the MQTT payload as well, since we only want to use the night-vision camera during the night.
 

Cuban Junk-pile Crisis:

The objective is so simple, it really doesn't require much explanation.  Except we've already created a catchy heading for this section.  So here's a rather dry paragraph to accompany it:

A conniving animal of some description will enter the scene and will trigger the motion sensor.  If it is sufficiently dark, the ESP32 development board will instruct the Pi to start taking photos using its night-vision camera.  We'll take a photo every 2 seconds, for a total duration of 10 seconds before resetting the counter.  The resulting photos are uploaded to AWS S3, so that we can view them later, from anywhere.

The end.

End of the Cold Sore:

We first encountered a very ordinary Raspberry Pi Camera back in Lights, camera, satisfaction!  It was so ordinary, all it did was take pictures.  Like. A. Camera.  None of that Steady Shot, Dynamic Fine Zoom, Ultra HD, 6th Sense, I See Dead People nonsense.

OK then, fancy night-vision camera time.  Here we go.

It turns out, despite its far bulkier exterior, an infra-red night-vision Pi Camera is driven in exactly the same way as its less exciting cousin.  This rather menacing-looking brute of a camera is armed with a pair of high intensity infra-red spotlights.  Nonetheless, it can be attached directly into the Camera Serial Interface Type-2 (CSI-2) slot of the Raspberry Pi. And if dark, the infra-red lights start to glow alarmingly red and radiate heat.  It certainly acts to heighten the sense of tension.  Clearly, there's a terrifying gargoyle hiding behind that oversized Amazon package that the delivery man left lying at the top of the garden.  Last Christmas.

Furthermore, in Python, we are able to use the very same picamera library we used before to interact with the device to take our photos (or videos).

Oh yes. And don't forget to remove the cap before use. Unless you simply want 7 million 3MB JPEGs of the colour #000000. A friend of a friend we know may have done exactly that.


All connected up?  Good.  Let's instantiate a PiCamera class, and attempt to take a photo using capture().

from picamera import PiCamera
import time
c1 = PiCamera()
c1.resolution = (2592, 1944)
c1.start_preview()
time.sleep(2)
c1.capture("capture/test.jpg")
c1.stop_preview()
c1.close()


It's done something, it seems.  Although that something is to take a night-time photo of a stuffed teddy bear loitering in the back garden and this isn't exactly the Pulitzer-winning evidence we were after.


Now judging by this terrifying trespasser's (non-existent) clothing, he is desperately short on cash.  Which means that there is a real possibility that Paddington's estranged and troubled uncle will walk off with our precious Rapsberry Pi with the aim of pawning it at the local Cash Converters.  And where would the evidence be if that happened?  How would we explain that to the Avon and Somerset Constabulary?  Clearly, the photos need to be stored off-site immediately after they are taken.  And cloud object storage in the form of Amazon's S3 seems to fit the bill nicely as an unceremonious dumping ground for our (mostly) uninteresting photos.

The starting point? An AWS S3 bucket called "rosietheredrobot", and a folder named "capture".

Thereafter, we can use the boto3 client in Python to upload the files that the camera is producing.

AWS_ACCESS_KEY_ID = "set_yours_here"
AWS_SECRET_ACCESS_KEY = "set_yours_here"
import boto3
session = boto3.Session(
    region_name="eu-west-1",
    aws_access_key_id=AWS_ACCESS_KEY_ID,
    aws_secret_access_key=AWS_SECRET_ACCESS_KEY
)
client = session.resource("s3")
client.meta.client.upload_file("capture/test.jpg", "rosietheredrobot", "capture/evidence.jpeg")


Ground Control to Major Tom: did our file make it up there?  It turns out, it has.  Although going forwards, we'll incorporate a timestamp in the filename so that we know exactly when each photo has been taken (in fact, we took this a step further and overlaid text containing the timestamp over the actual photo, using Pillow).


Although these night-vision cameras can take fairly usable photos during the day, we'd probably in reality refrain from using an infra-red camera when it's light.  After all, raiders of the lost bin only appear to do their raiding at night.  To this end, we'll attempt to ascertain current light conditions and only use our infra-red camera when it is suitably dark.

For this purpose we'll sacrifice a single ESP32 development running MicroPython and equip it with a light-dependent resistor (photoresistor) in a voltage divider circuit configuration.  Did we use one before?  Sure, we did.  Back in Quantitative wheezing.  And this was how.

import machine
p_adc = machine.ADC(machine.Pin(33))
p_adc.atten(machine.ADC.ATTN_11DB)
photoresistor_v = p_adc.read() * 3.6 / (2 ** 12 - 1)
print(photoresistor_v)


Out of curiosity (and possibly boredom), we left two voltage divider circuits, one consisting of a photoresistor, other a UV sensor, running outdoors for a few days.


As light and UV levels fluctuate between day and night time, so do the voltages registered by our ESP32 analogue to digital converter ports.  The polarity simply depends on the placement of the resistors in the voltage divider circuits, or the ends positive and ground terminals are connected to. The important conclusion is that we can recognise night time with relative ease, and more reliably using the photoresistor.


That's that.  Back to our important mission for the North Atlantic Trash Organisation.

Incidentally, nothing bad happens when we use the infra-red night vision camera during the day.  The photos end up looking a tad colourless, that's all.

Hey cute kitty.  What do you get up to at night when you think we're not looking? Nothing..?

ARE YOU SURE?


Oh, and you too, fox.  WHERE HAVE YOU BIN?


It would simply be a monumental waste of humankind's resources (more specifically, AWS's) to continually take photos 24/7.  That's why we'll be using a passive infrared (IR) motion sensor.  We used this with the Pi back in Lights, camera, satisfaction!, and since it requires one GPIO pin to operate besides power, we'll rig it to an ESP8266 and leave it do its thing at the designated wildlife entry point.

Here's a highly professional mock-up.  Complete with the usual security guard with croissant hair.


Aside from the two potentiometers used to tweak the sensitivity and delay in the sensor's ability to detect human (or animal) motion, it's simply a case of monitoring for the output to go HIGH. 

import machine
import time
pir_sense = machine.Pin(15, machine.Pin.IN, machine.Pin.PULL_DOWN)
warn_pin = machine.Pin(23, machine.Pin.OUT, machine.Pin.PULL_DOWN)
while True:
    if pir_sense.value():
        print("PIR motion detected!")
        warn_pin.on()
        time.sleep_ms(3000)
        warn_pin.off()


This is classified footage of this highly sophisticated sensor seeing action in Fort Knox.  Notice how the gold bullions remain safe from the threat. Where are the bullions, we hear you ask? They are... Wait!


Combining the output from the PIR motion sensor with the output from the photoresistor allows us to send a short and sweet MQTT payload to the Pi equipped with the camera.  If it's been informed that it is night time, the night-vision camera should start taking photos.


Here's a couple of schematics.

Full MicroPython code is at the very bottom of this post.

Before we deployed this system to the back garden, we did note that the same light detection technique could be used to detect the interruption in a laser beam (drum roll please... a "trip wire"). In other words, when a photoresistor no longer detects direct light from a laser emitter, it could be configured to raise an alarm.

Here is this theory in action, this time, at the Bank of England.


import machine
p_adc = machine.ADC(machine.Pin(33))
p_adc.atten(machine.ADC.ATTN_11DB)
warn_pin = machine.Pin(13, machine.Pin.OUT, machine.Pin.PULL_DOWN)
while True:
    photoresistor_v = p_adc.read() * 3.6 / (2 ** 12 - 1)
    if photoresistor_v < 1:
        warn_pin.off()
    else:
        warn_pin.on()


Random plastic gold thief girl: you don't stand a chance against this high-tech, laser-beam malarky.


With the sensors all ready, it's time to package them up in Flora tubs and place them outside our refuse bag.  Despite the testing, we didn't deploy the laser tripwire (due to our obligations under international treaty to reduce our arms stockpile) so it was left out of our final battalion.  It may, however, make a return in the future when things are really on the brink. As it could prove to be useful to set off a countermeasure to ward off the assault.


Oh, yes, it's Refuse Night
And the feeling's right
Oh, yes, it's Refuse Night
Oh, what a night (oh, what a night)

As they say, proof is in the rotting pudding.

With this curious rig operational, it's simply a case of visiting AWS S3 in the morning to see if any photos were taken.  And the results may indeed surprise you.


The photos are more than adequate in terms of quality to identify the suspects, even if their eyes are scarily lit up like Halloween masks.  What's that?  An innocent-looking cat.  Just harmlessly exploring.  Aww, cute.  You wouldn't desecrate our bin, would you?


But over the course of a number of nights, the real state of modern British society became apparent.  They are all at it.  All night.  Every cat and its fox.  Brazenly ambushing our vulnerable rubbish bag at any given opportunity.



Well, at least we now know what's really been going on.  And I guess we can count ourselves lucky to have such varied visitors.

Sure, we - technically - didn't really learn anything new in this experiment, the use of an infra-red night vision camera and AWS S3 aside.  But the results were arguably more satisfying than from one of our many other past times; for example, pointlessly gathering GPS coordinates of a banana and dispatching them half way across the globe using radio frequencies.  Just because we can.

But don't believe the state propaganda.  Instead, trust the words of our excited little one who put together the following summary off the back of this operation for her show and tell at school.


And keep a look out for our follow-up - 20th Entry Fox - in which we will be getting ourselves involved in some machine learning label detection shenanigans with the noble aim of prioritising the threats we are facing.

Code

Here's the main.py running in MicroPython on the ESP32 development board.


Mutually assured instruction:

An excellent guide on the use of Passive Infra-Red (PIR) motion sensors by Adafruit can be found here:
Pi Camera library is documented here:
Image manipulation, like placing text on the photo with a timestamp, can be achieved using Pillow:
We are using AWS S3 and the Boto3 API client to store our incriminating photographs in the cloud:

Comments

MOST VISITED (APPARENTLY)

LoRa-Wan Kenobi

In the regurgitated words of Michael BublĂ©: It's a new dawn .  It's a new day .  It's a new Star Wars film .  For me .  And I'm (George Lucas, and I'm) feeling good .  Unfortunately for Canadian Mike, the Grammy that year was won by the novelty disco classic with the famous refrain: We love IoT, even in Planet Tatooine * . *Not true. Clearly, the Star Wars producers didn't sincerely mean the last Jedi the previous time around.  Return of the Jedi, released during the decade that spearheaded cultural renaissance 2.0 with the mullet and hair-metal , was less economic with the truth.  Either way, we're going to take inspiration from the impressive longevity of the money-spinning space-opera and reboot our franchise with some Jedi mind tricks.  Except this particular flick doesn't require an ever-growing cast of unrecognisable characters, unless ASCII or UTF counts.  In place of an ensemble gathering of Hollywood stars and starlets, we will b

Battle of BLEtain

The trolling . The doxing . An army of perplexing emojis. And endless links to the same - supposedly funny - viral video of a cat confusing a reflection from a dangling key for a golden hamster, while taking part in the mice bucket challenge. Has social media really been this immense force for good? Has it actually contributed significantly to the continued enlightenment of the human (or feline) race? In order to answer these poignant existential questions about the role of prominent platforms such as Critter, StinkedIn and Binterest, employing exceptional scientific rigour equal to that demonstrated by Theranos , we're going to set up a ground-breaking experiment using the Bluetooth Low Energy feature of MicroPython v1.12, and two ESP32 development boards with inexplicable hatred for one another.  And let them hurl quintessentially British expressions (others call them abuse) at each other like two Wiltshire residents who have had their internet access curbed by the co

Hard grapht

You would all be forgiven for assuming that bar , pie and queue line are favourite pastimes of the British .  Yet, in fact – yes, we did learn this back in GCSE maths – they are also mechanisms through which meaningless, mundane data of suspect origin can be given a Gok Wan -grade makeover, with the prime objective of padding out biblical 187-page PowerPoint presentations and 871-page Word reports (*other Microsoft productivity tools are available).  In other words, documents that nobody has the intention of ever reading.  But it becomes apparent over the years; this is perhaps the one skill which serves you well for a lifetime in certain careers.  In sales.  Consultancy.  Politics.  Or any other profession in which the only known entry requirement is the ability to chat loudly over a whizzy graph of dubious quality and value, preferably while frantically waving your arms around. Nevertheless, we are acutely conscious of the fact that we have spent an inordinate amount