Watchdog

This page last updated: 27 January 2025.

Note: all of the source files created by me for this project (Blender, C code, etc.) can be found on Github.  If you want to try making this, or something similar, yourself, see the parts list and the things I would improve next time at the end.

As the Front Garden Railway project was nearing a real thing in November 2024, it occurred to me that I should have some surveillance: provide a "you are being watched" signal and actually do some watching at the same time.  This shouldn't be scary, we didn't want to scare the kiddies away, a friendly face, but it should have red eyes that glow at night, after the kiddiwinkles have gone to bed, to make the point to miscreants. After some discussion we settled on a dog's head.

Various platforms can do video streaming over Wi-Fi (ESP32 and Raspberry Pi amongst them) but the wide-angle (120 degree) non-IR filtered (for night-time use) camera for Pi seemed the best choice so I went Pi-wards.  I already had stepper motors recovered from when my old Prusa MK3 3D printer did itself in and had two Sparkfun EasyDriver stepper motor driver boards and a 3 Amp Pololu D15V35F5S3 (later upgraded to a 5 Amp Pololu D24V50F5 ) 5 V step-down voltage regulator board in the spares drawer. I didn't think it would be a long job and I turned out to be right for once; about two months to this:
 

Whichdog?

Browsing Thingiverse, the friendliest dog's head already modelled seemed to be Gromit from reddadsteve's marvellous Wallace and Gromit.  I only really needed the head, and could probably mount the camera in the nose.  I downloaded the relevant files and printed off the Gromit as-is in rPLA as a test; the original STL files can be found ZIPped here in case they ever disappear from the source.

Original Gromit

This was fine: I tried it in the position it would ultimately take, on the windowsill in the front room, and it would need to be about three times higher than its current 130 mm for my purposes, which would also make room for the relatively large stepper motors.

Which Pi?

I started out using a Pi Zero 2W, since it is advertised as being able to support video capture.  With Python I found that just loading the libcamera and OpenCV libraries I would need was taking about a minute, so I switched to working in C++ (of which the libcamera stuff uses a pretty modern syntax, almost like a different language for me).  I concentrated on getting a video stream running using FFmpeg, since that would be a good stress test, and it quickly became clear that, though the Pi Zero 2W can indeed capture video, if you want to do anything with that video (like H.264 encode it into a stream) it is out of grunt: with an 854x480 resolution stream it could manage only 22 frames per second on average; 1920x1080 (which the camera can do very nicely, and beyond in fact) was out of reach, the codec would just stop for 10 to 15 seconds.  My guess is that the half a gigabyte of RAM is the limitation.

So I made room in the watchdog's nose for a Pi 5 with 8 gigabytes of RAM and that flew.

3D Printing

I spent a week designing in Blender, test printing in rPLA, test fitting the various components, repeating, adding a couple of Gearotic-generated cogs, until I had:

Watchdog in blender,
                front
Watchdog in Blender,
                back
Watchdog, draft
                print, front
Watchdog, draft
                print, back

Note: the printed body pictured above is missing its lower portion for speed while prototyping.

I ordered the filament I would require for the final print: natural and black ASA (to be UV safe); plus, for the cogs that allow the torso to dip, I already had polycarbonate (employed for its hardness).  You can find printing instructions, along with all of the files, on Github. Printing took a few days in a room warmed to 40 C (to avoid ASA warp); these are large parts.

Printed parts Cogs printed in
                polycarbonate

Initial assembly required:
First I cut all of the threads: the M5 ones that hold the body parts together (six of them), the M5 one for the grub screw that holds the neck to the upper/rotating stepper motor and the M2 one for the grub screw that holds the small cog/pinion to the lower/dipping stepper motor.

The stepper motor would only fit into the torso, and the torso into the body, one way:

The ears are glued to the neck (but not the face, so that the face can be removed).  The hole in the neck into which the rotation stepper motor's shaft fits was left deliberately tight, to make sure the head stays vertical; it needed letting-out by hand with a 4.9 mm drill.  The camera is aligned with the square hole in the front of the nose and then gently lifted over a couple of ledges either side/below the hole for a friction fit, the flexible cable concertina-ed inside the nose [addendum: make sure the flexible cable comes out of the board carrier straight, held that way by the little sticky-out bit on the end of the board carrier insert; this way it doesn't get in the way of a heat-sink mounted on the Pi's processor].  The nose will, on final assembly, be tacked in place top and bottom with a couple of drops of cyanoacrylate adhesive so that it can be easily removed if required.  If it proves more convenient, from the point of view of not twisting the flexible cable, to mount the nose upside-down, just set the conditional compilation flag W_CAMERA_ROTATED_180 when building the software and the image will be rotated appropriately.  The whites of the eyes will be similarly tacked in place on one side only, the black parts of the eyes just pushed fitted.

The remainder of the assembly is fairly obvious, performed in the pictures below as a test (i.e. no glue, except for the ears to the back of the neck) since the watchdog will need to be disassembled again for the wiring up of the electronics.

Base
Body, front Body, back Large gear
                inserted
Inside torso Top of torso Side of torso Small cog attached
Torso inserted into
                body Upper/rotating
                motor inserted into torso Collar in position
Yorick Gromit Back of the head
Pi in carrier Carrier in mouth Camera coming out
                of face Camera inserted
Camera in nose
Watchdog

Software, Proof Of Concept

The software is now at a stage where it can detect motion and obtain position information on the moving objects that would allow it to move the watchdog's head.  Here it is running:

 
Before the software could progress any further, the electronics needed to be wired up.

Electronics

I started by making all of the contacts for the limit sensors: these consisted of lengths of 1.5 mm diameter brass bar with a wire soldered on, the bar then inserted into the hole in the model, as follows:

Location
Bar Length
Wire Length
Wire Attachment Point
Pictures
Neck
30 mm
300 mm
At the 20 mm mark.
NeckNeck contact
                  fitted
Collar left and right
30 mm
400 mm
On the end. Wire soldered to
                  collar contactCollar contact
                  fittedNeck and collar
                  done
Base, back
50 mm, bent in an "n" shape 10 mm wide.
600 mm
On the top to the left.
Wire attached to
                bent base contactBase, back, contact
                fitted
Torso, back
35 mm
600 mm
On the end.
Torso, back contact
                being fittedStick-out of barRear contacts
                fitted
Base, front
50 mm, bent in an "n" shape 10 mm wide.
700 mm
On the top at the back.
Base, front
Torso, front
30 mm
700 mm
At the 20 mm mark.
Torso, front

My procedure in each case was:
Notes:
With all that done, I applied small spots of cyanoacrylate adhesive in strategic positions to provide some strain relief for the wires, see pictures below.  I ran the base-front wire down and then out at the back, so that it wouldn't get in the way of removing the torso, and I made a loop of slack in the torso-front wire to allow for the brass bar being removed when the torso needs to be removed.

Strain relief
Strain relief
Strain relief
Strain relief

The wires were twisted together in pairs and led up into the hole in the back of the neck, leaving plenty of slack.

Sensors wired-up

I wired up two high-brightness 5 mm diameter through-hole LEDs and tried various series resistors to a 3.3 V supply until I found one that would get me slightly under 16 mA, the maximum current draw of a pin of the Pi; a 68 Ohm series resistor achieved 12 mA.  I cut lengths of black and red 7-strand hook-up cable, 200 mm long, for each LED, soldering the series resistors in-line, with heat shrink to avoid any shorts, then I mounted the LEDs in the eyes, running the cable down the channels behind the eyes and into the nose.  Note that these LEDs have a clear lens so they appear simply grey when not powered.  The brightness looked OK to me from a distance.

LEDs wired
LEDs off
LEDs on
LEDs from a
                distance

Since I am now using a Pi 5, the little 3 Amp/5 Volt Pololu D15V35F5S3 step-down voltage regulator wasn't going to be enough: I replaced it with a 5 Amp/5 Volt Pololu D24V50F5 step-down voltage regulator.  The board and a small connector block were initially held in place with a couple of sticky pads but, after a little accident, these were replaced with pairs of M2 bolts (6 mm and 12 mm in length respectively) which self-tapped into 1.6 mm diameter holes set into the watchdog base.  A cable tie was used to provide some form of strain relief.

Voltage regulator board

To make getting all of the connections to the Pi an easier job I created a face-jig in Blender by cutting away the top half of the face and printed it in rPLA.

Face jig

I decided on the connections to the Pi being from GPIO 1 upwards, pretty much in order, so that I could mark each of the white limit-sensor wires with bars (one bar for GPIO 1, etc.) using an indelible pen to indicate what they were.

Wiring

Unmarked limit-sensor wires were then tagged with a ring of mains ground-coloured sleeving; the limit GPIOs are all set in software to have a pull-up, so the other end of each of the limit contacts just needed to be connected to one of the eight ground pins on the Pi.  The wires running from the two stepper motors already, conveniently, had little X (for the rotation motor) and Y (for the up/down motor) tags on them.  The wires to the LEDs in the left and right eyes were visually clear anyway.  While outside the body, the non-white cables were run inside white fabric sleeving for neatness.

Sleeving

After cutting all of the wires to the right length, fitting connectors and marking them all, I took it all apart again and, for testing while I finished off the rest of the software, I reassembled everything in the board carrier inside the face jig with the wires placed as neatly as possible, not fouling edges that would ultimately be squished against the cavity when inside the face for real.  The best procedure was to start at the neck-end of the Pi connector and work down using a stout tweezers; there's not much room in there.  The current limit adjustment on the Sparkfun EasyDriver stepper motor driver boards was left at minimum.

Pi 5 in board
                  carrier
Driver board
Driver boards in
                  position
Plugging wires
                  in
Wired-up Crammed in
Ready for testing

Hot Dog

With the electronics still visible like this I completed most of the software over the Christmas period 2024; all of the bits of software that did not require the camera to be fixed in place.  Then I assembled everything, noting that the torso is now black as I had needed to re-print it to loosen-up some tolerances and was out of natural ASA filament at the time.

Face in place
Nose in place

Notes:
Within minutes the Pi 5 had switched itself off.  Running btop showed:

btop

...that the Pi 5 processor, which shuts down at 85 C, was getting up to 96 C while idle.  I bought a stick-on heat-sink plus a 50 mm square, 10 mm deep, 5 Volt DC, 2 pin, brushless fan with a nice long (270 mm) lead and made a hole in the bottom of the face to accommodate it, wiring the leads to the spare 5 V/GND output pins provided on one of the stepper-motor driver boards.  When stuck down, the heat-sink was aligned with the edge of the processor furthest from the camera cable, so as not to melt the cable.  The design of the board carrier and insert was modified to leave as much room as possible for air to flow above the heat-sink and down, beneath the PCB, into the mouth of the fan.  A sticky-out bit was added on the camera-end of the board carrier insert to keep the flexible camera cable in line.

Heat-sink and
                  fan
Heat-sink
                  mounted
With insert
Fan hole

With that done the Pi processor never got much above mid 60s C when streaming and with the motor drivers operating.  Here's a video of the watchdog running with an initial software implementation, one which just allows the head to move a step each time it thinks the focus has moved from the centre of the screen and then waits a short while for the image to steady.
 
This is not really going to fly: the image needs longer to stabilise than it can reasonably get, one of the penalties of having the camera in the nose.  I will try again with a "glancing" kind of approach, one in which a significant direction change is decided upon, moved, pause a number of seconds, etc.

Power Interlude

While finishing off this "glance" operation and completing the web interface, the watchdog fell of its perch; it was on a stand on a table and joggled itself off, falling just a short distance to the top of the table.  No apparent harm was done but afterwards I began to get spontaneous shut-downs of the Pi and the only reason I could occasionally find for that in the Pi's log was "brown-out".

From this post on Raspberry Pi Stack Exchange the earlier Pi, models, and I assume it is the same on the Pi 5, have a power management chip that knows when the supply voltage has fallen below 4.63 Volts (+/- 0.25 Volts from the 5 Volt nominal being permissible), at which point the Pi can decide to shut itself down in an organised way.  I found the brown-out to be repeatable ONLY if the Pi was running my watchdog application; it also NEVER happened when the Pi was running from its own USB power supply.

I stripped things back until there were no LEDs connected, no stepper-motor drivers connected, no stepper motors connected, the only thing being powered from the Pololu D24V50F5 was the bare Pi-with-camera, open on the desk.  I couldn't remove the camera as my program would do nothing of use without it; the obvious thing the watchdog program does, of course, is cause the Pi to draw more current, it having to run at full tilt to process images and encode video.  But the Pi should only draw 2 Amps and the Pololu D24V50F5 can deliver 5 Amps.  I probed the supply lines.

The plot below is of the current drawn by the Pi (worked out from the voltage dropped across a 0.1 Ohm [high-current] resistor in the supply line) across a one second period during which the watchdog program was started.  The current drawn sits just under 1 Amp until the watchdog program is run, when it rises pretty rapidly to 2 Amps.  The voltage drop across even a 0.1 Ohm resistor is too much at that point and the Pi switched itself off; it is quite a stark and immediate change.

Current

But this is well within the capabilities of the Pololu D24V50F5.  I measured the voltage at the Pi-end and at the PSU-end of the 30 cm cable across a 20 second period during which the watchdog program was started (the red line being a moving average):

PSU-end
                  voltage
Pi-end
                  voltage
 
The effect of the 30 cm lengths of 7-strand hook-up cable is fairly significant: a drop of about 150 mV and a magnification of the switching-noise from the regulator.  But still, nothing is going as low as 4.63 Volts.

I tried adding capacitors to smooth out the bumps but the only place I had room to add them was at the PSU-end and even a 1000 uF capacitor had no significant effect there.

In the process of this re-wiring/re-running etc., I did notice that the processor on the Pi was getting pretty darned hot: out of the watchdog's body it had no active cooling, but why would that only result in an over-temperature shut-down if the Pi was running from the Pololu D24V50F5 rather than the USB power block?  Maybe the processor draws more current when it is slightly under voltage and therefore runs hotter, etc.?  There is a hint of this in the slight droop of the plot on the left below, which is a plot of the voltage at the Pi-end across an 18 minute period (too long for me to have a tool that would add an average line I'm afraid) of running the watchdog program; or maybe the droop is down to the increase in resistance of the 30 cm of copper wire as it warms up?  The detailed plot beside it shows the moment the Pi switches off and there is still no dip as low as 4.63 Volts; the data is sampled every microsecond so it is unlikely to have missed a glitch.  That said, the specification limit is 4.75 volts (+/-0.25 Volts from 5 Volts), and maybe there are losses on the board itself which mean that 4.7 V (reached in this case) breaches the limit set by the power management chip?

Long term plot
Moment of Pi self-switch-off

It was also possible that I had a bad connection somewhere, a wire just-about-connecting and becoming less connected when it warmed-up due to the higher current flowing, which could be a result of the fall.  At least, after taking most of the power connections apart and putting them back together again, then sitting the fan next to the Pi so that it was being cooled to a representative mid 60's C, the problem no longer occurred.  To reduce the chances of such mechanical issues occurring in future I made mounting holes in the base to hold the PSU board and the connector block securely with M2 bolts.

In order to determine whether it was worth using thicker wire, I cut 40 cm lengths of the 7-strand (22 AWG) hook-up wire and an alternative 22-strand (18 AWG) hook-up wire, then ran the 20 minute scenario above for both wire types.  In terms of test conditions, the Pi was open on a desk at ambient 19 C, not actively cooled (no fan to be seen); the Pi processor started off at 55 C when idle, getting up to 85 C, but no higher, when running the watchdog program (50% CPU load).

Thin wire
Thick wire

The red moving average line stayed above 4.8 Volts, so within the 4.75 Volt specification limit, for both, but the troughs of the thin-wire case did breach 4.7 Volts; the thicker wire is clearly better, with an average of 4.95 Volts versus 4.85 Volts for the thinner wire.  The thin wire test, left running for a few hours, did eventually switch off, long after I'd stopped recording results and with the Pi temperature no higher than 85 C, though no "brown-out" marker made it into the log; the thick wire test continued running overnight: I had my answer.

I used the thicker wire up to the head and made room for a connection block inside the neck.  The stepper-motor power lines were left running directly to the Pololu D24V50F5 in the base; I didn't want the current for the motors causing droopy-draws on the Pi supply.

Distribution point in neck

Correct Facial Tension

The other thing I learned while completing the "glance" operation software was the need for some mechanical improvements:
  1. the weight of all of the components that make up the face, put together, was about 235 gm, which:
    • caused quite a "clunk" when the head fell to the limit sensor at power-off, jarring the electrical connections inside the face and potentially causing the head to rotate if it happened not to be directly forward at the time, losing rotational calibration,
    • put stress on the gears/motor trying to lift the head,
  2. 5 degrees of "throw" in the meshing of the gears meant the software didn't always know where the head was vertically, losing vertical calibration,
  3. the body cavity was relatively tight to the torso/collar and, if it happened to make contact, the dog would squeak annoyingly when it moved vertically.
Throw and face
              weight

In an attempt to resolve (a), as you might have seen in the video above, I had tried adding counter-weights to the torso.  This worked but was relatively cumbersome and the bar leading to the weights had some spring in it, which caused the watchdog to joggle when [even smoothed] motion was stopped; this was what, at least in part, led to the watchdog falling off its perch during software development.  This solution also led to me finding problem (b) since, with the counter-weights in place, balance just flipped over into a backward-tilt at the top-most limit.

I figured that (b) would be resolved if I kept tension on the gears: they begin by lifting the head from rest position, I needed to balance the head such that the cogs were always in that "I'm preventing a forward-drop" state and never ticked-over across the 5 degrees of no-man's land into "I'm preventing a backward-drop" state.  And, if the tension were asymmetrically applied, it might do the job of the counter-weights also.

Time to experiment: to avoid scuffing the face while messing about I attached the face jig instead and opened a variety-box of springs.  I drilled a hole in a sticky-out bit of the torso and a few holes in the back of the body (until I got it right) then trimmed an expansion spring, attached at both holes, until the head just tilted forward to its limit when released.

Sprung

I assembled the face proper, which weighed around 70 gm more than the face jig, sufficient weight at the front to keep tension in the right place to resolve (b) while also providing sufficient pull-back to resolve (a).  I ran the real software, glancing for several hours, and all motions seemed good, unstressed, so I made the changes properly in Blender.  I resolved (c) by adding a lip, just where the metal rod sits in the base of its slot on the non-cog side, so that the body pushes on the bearing there rather than making contact with the torso or collar at shoulder-level.  I reprinted the body and the torso with these changes.

Spring
                      properly attached
Lip

Note that there was a little separating of the ASA in the re-printed body, which you can see beside the spring in the picture above, but it was only at the back and so was tolerable.

Completed Software: Statistics

Nothing much to say about the software, all on Github; here are some stats:

  • watchdog application .cpp files: 7122 lines of which 38% comments,
  • watchdog web page .js file: 1689 lines of code of which 34% comments,
  • on the Pi: watchdog launches 24 threads, max 55% total CPU load (using all four cores) @ 2.4 GHz, 102 Mbytes dynamic memory, uploading HLS video required between 730 kbits/s and 1.3 Mbits/s network bandwidth,
  • in Chrome: web page requires 18 Mbytes JavaScript heap, each 2 second long HLS .ts file took between 70 and 150 ms to download over WiFi, 162 kbytes of data downloaded each time.

Recording

I had originally intended to store video within the watchdog itself, using a 128 gigabyte SD for that purpose, which I had intended to partition appropriately.  However, since this will be constantly active I feared that I would be hoist to SD card wear.  HLS had proved to be pretty darned stable for me so I opted instead to configure a Linux box already on my LAN as a consumer/recorder of the stream.  Not wanting to waste time writing code for a roll-over store, I looked for open source solutions that must be out there, I thought.  Well, just.  I needed only storage management and live display, actively did not want object/motion recognition since my camera is already processing the image and moving of its own accord.

I first tried Frigate, which recorded fine but seemed to be aimed more at solving the problem of recognising specific objects (person, cat, car, bike, etc.); getting an HLS source to play back at more than 5 FPS required another assistant application to be configured.  Since our aims clearly didn't align I tried ZoneMinder instead; an older application that looked more my kind of thing.  However, it was so old as to have originated before the days of HLS and hence its HLS integration relied heavily upon knowing how to configure FFmpeg and I've been there before: a week of pain I didn't fancy repeating.

So I moved to Shinobi: written in node.js and apparently created by someone who was insulted by ZoneMinder.  The UI of Shinobi I found exceptionally confusing but the thing that made it sweet was that it used FFmpeg Probe to resolve all of the required settings for HLS and hence that bit "just worked".  It manages multiple cameras, the recorded segments from which can be viewed contiguously on a timeline of arbitrary length.  And you can switch the motion detection bit off.  I set it to have 30 gigabytes of storage for a rolling store of duration 3 days; sorted.

Shinobi UI

Parts List

Pi:

  • Raspberry Pi 5 (I used the 8 gigabyte flavour but likely any flavour would do)
  • NoIR camera 3 for Pi with correct flexible cable to attach to a Pi (rather than a PiZero)
  • 32 gigabyte SD card
  • stick-on heat-sink for Pi processor

Hardware:

  • at least 750 gm natural ASA filament (if you make a mistake you might need another reel)
  • 500 gm black ASA filament
  • a small amount of polycarbonate filament (could probably substitute ASA)
  • some PLA (e.g. to print the face jig)
  • 97 mm length of 4 mm diameter stainless steel bar
  • 140 mm length of 1.5 mm diameter brass bar
  • 2 off 4 mm x 9 mm x 4 mm (inner diameter x outer diameter x width) bearings
  • 6 off M5 pan-head bolts (two 40 mm long, the rest 20 mm long)
  • 1 off M5 hex grub screw
  • 5 off M2 bolts (three 12 mm long, two 6 mm long)
  • 1 short (~3 mm) M2 hex grub screw
  • small (e.g. 5 mm diameter) expansion spring

Electronics:

  • 2 off stepper motors, 42.3 x 42.3 mm frame, 5 mm shaft (e.g. salvaged from an old 3D printer)
  • a Pololu D24V50F5 step-down voltage regulator
  • 2 off Sparkfun EasyDriver stepper motor driver boards
  • 50 mm square, 10 mm deep, 5 Volt DC, 2 pin, brushless fan with a nice long (e.g. 270 mm) lead
  • a 12 V DC, 2 Amp, mains power supply (e.g. one retained after an old laptop had died)
  • a few metres of 7 strand hook-up cable, mostly white, some red and some black
  • half a metre each of 22 strand hook-up cable, red and black
  • large diameter (e.g. 8 mm diameter) cable sleeving, white
  • 3 Amp mains terminal connector block (6 terminals in total)
  • a 2.1 mm panel mount DC power socket (or whatever is required for the connector on the end of the 12 V DC mains supply)
  • 2 off 5 mm diameter high-brightness red LEDs
  • 2 off 68 Ohm resistors
  • approx 100 mm of 4 mm diameter heat-shrink sleeving
  • a small amount of ground-coloured cable sleeving
  • 0.1 mm pitch connector housings (1s, 2s and 4s, though could get away with just 1s) and pins

Tools/misc:

  • allen keys for the hexes
  • soldering iron
  • solder
  • flux
  • hair-drier (for the heat-shrink)
  • crimp tool for 0.1 mm pitch connector pins
  • an M5 and an M2 bottom-tap
  • a 4.9 mm (5 mm would probably do) drill
  • gloss white paint (e.g. Humbrol 40)
  • small paint brush
  • brush cleaning fluid
  • large flat-head screwdriver
  • small electrical screwdriver
  • tweezers
  • pliers
  • small file
  • small hammer
  • small hacksaw
  • metric ruler
  • indelible pen
  • old knitting needle (for removing supports behind the eyes)
  • craft knife (for removing support/brim from 3D prints)
  • wire cutter/stripper
  • cyanoacrylate adhesive (AKA Super Glue)
  • glue stick (for use on the heat bed when printing ASA)
  • space heater (to keep the printing-room nice and warm when printing ASA)
  • a Wifi network
  • a Linux box on that Wifi network with at least 30 gigabytes disk space free
  • IR flood-light (when installed, to illuminate the field of view at night)

Things I Would Improve Next Time

  • make the nose snap into place rather than requiring glue,
  • improve the 3D design at the rear of the face; some of the edges there are a bit "knife edge" and don't print so well.

Back to Meades Family Homepage