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.


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... in which we will be getting ourselves involved in some machine learning classification shenanigans with the noble aim of prioritising the threats we are facing!

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

Popular posts from this blog

Tea minus 30

We're fast approaching Christmas time.  And if robots were to make one simple observation about the human species during the Christmas festivities, it's that they watch a lot of TV.  A LOT.  Often, accompanied by an inappropriate amount of greenhouse gas-producing food.  Stuff you don't normally eat during the remainder of the year - for good reason.

And most so-called shows on TV are boring to robots like Rosie.  After all, why watch a minor subspecies of the human race - celebrities - stumble awkwardly around the dance floor, dressed like a faulty, sparking circuit board?  Such branch of entertainment doesn't require robots to engage any of their proud circuitry.  Their processors remain idle.  Memory under-utilised.

But if robots are to be part of people's homes (and blend in), they need to look at least a little interested in some of this irrational nonsense.  Nobody likes a party pooper.  A killjoy.  And this is where a certain subgenre of TV entertainment co…

Break an egg! You've got to be in it to win it.

What the 'egg? It turns out: parenting is actually quite hard.

Not least because you suddenly find yourself responsible for one, two, or - in our household - three little miniature versions of us that need to be kept well away from the soldering iron. Or the 3D printer. Or that marauding hexapod that you forgot to power off before you left for work in a hurry.  But to compound matters further, you find yourself well and truly ambushed - financially.  You are at all times being pressurised by dark forces beyond your control to make an investment, however dubious the return.

That's right.  Clearly, you will be considered an abject failure as a responsible adult if you don't purchase the latest, trendy parenting gizmo. That feeding bottle sterilising kit clinically proven to kill all known bacteria through the science of nuclear fission. Or that titanium alloy buggy guaranteed not to crumple in the event of a sudden collision with falling Soviet-era space debris.  Evidently,…

Beam me up, Rosie!

How do you get from A to B?

You can't, as As and Bs are just letters in the alphabet. But if A is your house, and B is a meerkat village at your favourite safari park, you'd probably use a device equipped with GPS.  Not to be confused with UPS, who will deliver you your chosen meerkat through the post. And why on Earth would Rosie Patrol need one? Precisely, it's because she is on Earth that she needs one. Because our planet is rather big. Big enough to get lost in. And we don't want to lose our friendly plastic boxes on wheels. And maybe, eventually when she's clever enough, she'll go and defeat baddies on her own. And return home afterwards for a well deserved Earl Grey tea.

Besides, why wouldn't we want to add another three letter acronym to Rosie Patrol's repertoire?
All superheroes need:One Raspberry Pi 3, running Raspbian OSComputer from which you are connecting to the Raspberry Pi Probably the most important bit: a GPS receiver thingmy. …

LoRa-Wan Kenobi

In the regurgitated words of Michael Bublé: It's a new dawnIt's a new dayIt's a new Star Wars filmFor meAnd 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 lastJedi 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 be assembling together a…

Raspberry bye, hello

Let us make this very clear from the onset of this exotic excursion.

This is not a case of Raspberry Bye. Our relationship with our favourite single-board computer hasn't at all soured. In fact, we've become wholly inseparable. There's been many months of undeniable fun that's been had with the venerable computer strangely named after an edible fruit. To the extent that our relationship requires a healthy break. And quite frankly, our Pis require a well earned summer holiday to do whatever it is that robots and computers do during their time off. Crash. Burn. Refuel (with questionable toxins). Not at all unlike their human counterparts. And ultimately, it would be nice if they could return to a brand new, adorable pet waiting for them at home, a likeable little companion that they can just get along with.

Well, we visited a pet shop, but couldn't find anything as small and smart as this adorable pup we stumbled up on while searching the Internet for a new, miniat…