Rummys Blog An world of endless Monday

Monday, 8 October, 2018

An IoT Mousetrap Part 2

Filed under: ESP,ESP32,World of Warcraft — Andrew.Rowbottom @ 11:35 am

The Mousetrap code has gone through several iterations, this iteration Number 2  has changed the code quite a lot..

The aim of this iteration was to significantly reduce the “ON” time from 3seconds to reduce the consumed watts in this phase.


I have switched from connecting to WiFi (about 3 seconds on time!) to using espNow sending to a “receiver” permanently connected to my Raspberry Pi, this is to reduce the “On” time during the regular status updated. I’ll try to post some information about using espNow in another post.


The “On” time is now reported as approx 300ms (mainly due to the huge number of status messages I send), well down from the roughly 3 seconds connecting to WiFi and sending using MQTT/HTTPS takes.

Unfortunately this has not made a huge difference to the overall battery life which is still running at around 3 months for a fully charged “600mAh” LiFePo4.

Further investigation is showing 2 major current draws:

  1. the LDO at approx 70µA
  2. the pullup/down current approx 70µA

Iteration #3 will look at how to reduce this .. until I un-solder the LDO Voltage-Regulator I’m limited to removing the pull-up/pull-down current. There are a few options:

  1. switch from using the internal pullup/down to an external resistor
  2. use the wakestub and poll the switch/mousetrap state regularly but not too frequently
  3. use the ULP and poll using that.

An IoT Mousetrap

Filed under: ESP,ESP32 — Andrew.Rowbottom @ 11:23 am
NOTE: this has been sat waiting to post for many months. I am posting it because I have updates incoming.


IoT! Who needs a mousetrap on the internet! Turns out I do.

We occasionally have some mice visiting our cupboards, so we tucked a mousetrap in a dark corner of a cupboard.

But the old adage “out of sight out of mind” really applies to us! And, after checking daily for a week only to find nothing we got lazy and started checking only when we remembered. Predictably one day we found a particularly smelly little corpse! Finally a potential use for those ESP boards I’ve got lying around!

Thus is born yet another IoT mousetrap!


  • Mousetrap
  • ESPea32
  • A replacement LDO voltage regulator
  • A bit of Soldering skill to replace the LDO
  • Edge Connector
  • Wire
  • Tin Foil salvaged from a tea-light
  • Battery Box
  • Internet

Modding the trap.

My mouse trap comes in three parts a white top and a base and a red “tongue” which is the lever that triggers the top part.

When its armed the top is tilted “backwards” and makes contact with the lever.

To wire it up for IoT all I needed to do was to put a contact on the top part and and one on the tongue, and then detect when the two are (or aren’t) in contact.

For the contacts I have used the tin-foil cup from a tea light, originally I used cooking foil, but it proved too thin, the foil cup on a tea-light is thick enough to hold its shape and still easy to trim with scissors.

The top contact is cut to fit neatly onto the top section. I left a couple of tabs of foil to fold over and tuck under the metal spring. I shove a piece of wire under the spring to complete the connection between the ESP and the top contact.

The bottom contact is nothing like as tidy, it’s a strip of foil, soldered at one end, and placed lightly over the tongue so it makes contact with the upper plate when the trap is armed. A bit of tape at one end stops it moving around too much without interfering with the action.


Using an ESP32ea (any ESP32 should do) I wire one plate to GND, and the other one to a GPIO, it doesn’t matter which way around, the voltages are low and it’s only “contact” that is important.

The GPIO is set to “INPUT_PULLUP”, so when the two plates are in contact it is pulled “LOW”, and when separated it goes “HIGH”.

The ESP is put into Deep Sleep (to conserve battery), set to wakeup (esp_sleep_enable_ext0_wakeup) when the GPIO goes into the opposite of what it currently is (ESP32 feature) It will wake up when the trap is closed, or when I open it ready for the next mouse.

When the ESP wakes up (either GPIO state change, or Timer), it checks the wakeup cause, and if the GPIO state is different from what it was when it went to sleep, it sends a whole bunch of messages.

I have a timer wakeup so I can sample the battery and send a “battery needs charging” message.


Modding the ESPea32 for low deep-sleep current

I only have a couple of esp32 boards, several cheap ESPea32’s and a more expensive FireBeetle-32. The firebeetle, although it has much better deep sleep current draw as supplied is slightly too long to fit in an AA battery box, so I’m using an ESPes32.

The ESPea32, though nice, is not really good for running off a battery in deep sleep.

The CP2104 seems to be correctly wired so that it is only powered when the USB is connected, something I checked on the schematic before I bought it.

But the voltage regulator is a bog standard AMS1117 with a quiescent current draw in the order of several mA, far too much for a deep-sleep battery powered device. Fortunately it’s a nice large (for SMD) SOT-233 package than can be reasonably easily un-soldered and replaced with a much more efficient device. Once that is done my ESPea32 now draws under 0.2mA in deep sleep, a 100 times improvement, though a “naked” esp32 can draw even less. NOTE: the LDO draws approx 70­µA

Headers / Terminals

I didn’t use standard headers for this project, instead I’ve used 2.54mm screw terminal blocks. This is the first project I’ve done this way, and so far I’m liking it! The wires don’t come loose as easily, the overall height (8.5mm, 11.5mm including pins) remains small enough to fit in the battery box. I can squeeze 2 wires into one terminal (for example GND to battery + a wire to the mousetrap), reducing the component count.

I did think about using the supplied PCB headers and dupont jumper wires, but the overall height is way too large to fit in the box. A standard PCB header is about 11mm overall, including through hole pins. The jumper wire pins add an extra 14mm onto that . And then the wire has to be bent. Lets call the overall height 25mm. An AA battery is only 14mm in diameter.

Wiring up the Mousetrap

My mousetrap is not your traditional wire one, which complicates things a little. Its a plastic module, so it needs some sort of conductive layer applying. I originally used cooking foil, but its thin, tears easy, doesn’t solder well and looks really horrible. The current version uses tin-foil taken from a “tea-light” which is thick enough to retain it’s shape with minimal gluing.

One piece is folded around the top, with a “tag” slid under the spring. Also slid under the spring is one of the “detector” wires.

Another piece is a lightly bent strip placed over the lever, and stuck to the bottom of the trap, a “detector” wire is soldered onto this strip.

Hardware choices


I have a stock of LiFePo4 batteries lying around, they’re not your usual LiIon batteries, they have a lower voltage, between 3.6 and 2.8v with a long flat stable period at 3.2v. A perfect voltage range for powering ESP devices directly without needing a voltage regulator. They’re less prone to catching fire, though I doubt they’re 100% safe in that regards – certainly you can short circuit them, and 10A even at 3.2v can cause a fire in thin wires.

In theory this means I should be able to remove the Voltage Regulator from the circuit, and if I had a supply of “naked” ESP32, that’s the path I’d have gone down.


I like these boards, they’re not ideal for this kind of project by a long shot, but they’re not bad. I managed to snarf some cheaply, and they fit tidily into my switched 4x AA battery box. They also seem to have a “correct” implementation of the USB/UART which reduces battery drain. Unfortunately they use the horrible LMS1117 in a comparatively large SOT-233 that has to be replaced or unsoldered if you want low deep sleep battery life. Perfectly you would unsolder it completely but then programming via Arduino would be a pain, unless you add a jumper.

My ideal board would look pretty much like the espea32 have a disableable/bypassable Voltage Regulator to remove quiescent current drain when powered by a LiFePo4. And had a Gnd pin immediately alongside the 3v3 connector .. perhaps a layout like 5v,GND,3v3 (or a second GND). And had an ADC pin connected to a voltage divider (and also 3v3 via a breakable PCB wire)… yes I know that would lose an ADC channel, but you’d gain a battery meter!

I’m actually a bit 50/50 about a LIPO connector/Charger, they’re extra cost, and you have to check carefully to see if they’ll fit in a cheapo project box.. 4xAA switched boxes are dirt cheap 🙂 !


Setting up the hardware

Break the dividers in the battery box so there’s room for the board and 1 battery.
Solder in the 3 screw connector so it covers 5v, Gnd, and a GPIO. I’d rather have used 3v3 direct, but it’s not besides the GND connector. Screw in the battery connectors, and the 2 detector wires.
Job done.. no extra components required


This isn’t a traditional “looping” arduino program, it does all of its work in setup, and goes to Deep Sleep before it enters the loop.

It will
Store the boot count in RTC memory, not strictly needed, but “tidy”.
Store the last state of the GPIO in RTC Memory, so it can tell if something has changed between wake-ups.
Store whether it successfully sent the notifications (in case there’s a WiFi or internet connectivity issue) [Distributed Computing Fallacy: The network is reliable]
Sample the battery voltage, so I can get low battery alerts.

Set the ADC to input (it’s input only anyway)
Set the GPIO to INPUT_PULLUP so it goes high unless it’s being pulled to ground by the mousetrap wiring.
Read the wakeup Cause
Read the GPIO state
Read the ADC
Set the deep sleep trigger to wake if the GPIO goes to the opposite of its current state.
Set the deep sleep to wakeup in 30 minutes in case the GPIO doesn’t trigger or it fails to send.

Decide if a status message should be sent, this will be sent if
it’s first boot (PREVIOUS GPIO level is -1).
the GPIO level is different from what it was last time it was checked.
the message didn’t get sent successfully last time.

Store the GPIO State for the next wakeup.


Current consumption in deep sleep is approx 0.12mA, NOTE: I *did* replace the abhorrent AMS1117 with a much more efficient LDO. I think that having WiFi connectivity enabled at all raises the deep sleep current by about 0.04mA, but I guess that’s something I’ll have to investigate further. Forgetting to turn off WiFi before going into deep-sleep [WiFi.disconnect(true /*means wifiOff*/)] changes the deep sleep current by a LOT more I measured 1.33mA!

Sunday, 18 June, 2017

ESP8266 and Artik Cloud, Part 2 – Integration

Filed under: ESP,ESP8266 — Andrew.Rowbottom @ 5:27 pm


This entry is long, and a bit complex. I wrote it in quite a hurry (same goes for the code), so it’s as good as it should be!

So what does Artik cloud do?

I don’t really know in any significant detail, because I’ve been focusing entirely and only on getting GHome integration working, without that it’s useless to me, so I’ve not done any exploring. I do know it can

  • record data (for 30 days)
  • send actions – aka commands
  • do simple IF statements, and as a result send actions, yup multiple actions as a result
  • Let you define and control your own “custom devices”

Custom Devices

Custom devices is where I’m interested,  ARTIK Cloud lets you create custom devices, you get to define the data it makes available and the commands it can receive. Support is available for the devices to :

  • post data using https REST (fairly simple to do)
  • send and receive commands via secure websockets/wss (simple to do on an ESP)
  • Supports secure mqt  (mqtts) (untried)
  • Supports secure CoaP untried

I can tell you that my implementation was using secure websockets (wss) – for me this has an advantage that the connection is initiated from INSIDE my house (no inbound holes in my firewall), and it can still receive commands.


Defining a device in ARTIK Cloud – Step by step

Creating a device is fairly simple, though it only defines what a device can do, we’ll actually create an instance of it once this is done.

First off: login to the ARTIK Cloud developer pages

Select “Device Types” in the menu to get to the device types pages

Click on + New Device Type

give it a “name”, don’t be too specific, e.g. ESP8266-Light
give it a unique name such as your domain name and some extra bits

and “Create Device Type”.

So now you have a device type, and it will appear in the list of device types on the left.

So far it’s kinda empty, and needs a Manifest which lets you define the data it can send (e.g. state, level, batteryLevel and so on), and the actions you can perform on it e.g. setLevel, setOn, setOff – these 3 are significant because according to this is what’s needed to make it appear in Google Home Control. You can add plenty more, but these three are what I have added.

Click + New Manifest to enter the Manifest editor, since the stuff we’re adding is pretty basic, we can use the “standard” fields. Don’t worry you can update the manifest later to add more stuff.

So, add 2 standard fields, “state” and “level”

Move onto the actions, we want 3 – setOn, setOff, setLevel

And Activate the Manifest


So now we’ve defined data about our device and defined what it can do in our manifest, but the device itself doesn’t actually exist yet. We do that in a different part of Artik Cloud

Adding a Device to Artik Cloud..

This is done in a different section of Artik Cloud, probably because in a real world IoT development you’d be creating lots of devices owned by lots of different users, but only a limited number of “types”. For us there’s only the one user, ourselves, and we’re defining the device and implementing it. So…

Login to

Select Devices..

My personal devices screen is full of rubbish, but you’ll need to click 


Pick the one you created in the previous section.. there’s a lot, so start typing the name “ESP8266-Light” and select it when you can.

Then press “Connect Device” .. this device will now appear in your devices list..

At this point you can simulate it and send actions to it using the “…” and “lightning bolt”, hardly worth it without any hardware attached, but well, there it is.

We’re pretty much done here for the moment, Now we need to hop over to our GHome control on our Android Device

Connecting to Google Home

  • On your Android open Assistant / Google Home
  • use the three dot menu on your Google Home device, and select Settings
  • Press “Home control”
  • Press the circled Plus
  • Scroll down and Press  Samsung ARTIK Cloud
  • Sign in with Google, this bit can be a bit flakey , but persist!
  • Back on the Add Devices Screen Samsung ARTIK Cloud should be in the “Linked Services” section
  • And in the Devices section you should see “ESP8266-Light”, you will probably want to give it a nickname, I called mine “MCU Light” because saying “ESP8266-Light” is both a pain, and GHome wants to call it “eight thousand two-hundred and sixty-six spanish pesetas Light” which is a serious mouthfull!

NOTE: adding new devices in artik cloud doesn’t seem to refresh the devices seen in Android, I usually have to “unlink” and “link” again

OK, so now we’ve

  • created the metadata for a device in ARTIK Cloud
  • added one of them to our personal list of devices
  • Integrated ARTIK Cloud into Google Home
  • Seen the device appear on our phone and given it a more sensible name

Perhaps we can do something with it even now, lets see…

Try saying “OK BOO BOO, turn on the MCU Light”, you might have to try a couple of times, my nicknames always seem to take two attempts to register after I’ve just renamed.

GHome believes it exists, but of course there’s nothing on the other end of the “Wire” .. for that we need a “real” ESP!

Programming the ESP

I’ve put a first draft of the code for my ESP up at ..

It is very flakey code, truly a first draft / Mininal Viable Product, it doesn’t even check the fingerprint for the wss:// connection!

To get it running

You’ll need to supply your WiFi SID/password at the top of the file: wifi.cpp,
AND comment out #include “nogit_wifi.h”!

You need a device type and token to supply to ESP8266-ArtikIntegration.ino

To get this ..

  • go to
  • click on the text “ESP8266-Light”
  • COPY the long number under “DEVICE ID” and replace “YOUR_DEVICE_ID” in the #define
  • Click on “Generate Device Token … ” and replace “YOUR_DEVICE_TOKEN” with this string in the #define
  • delete the line #include “nogit_artik.h

Compile, upload, watch the serial output.. it should

  • connect to your wifi
    • connected with XXXX, channel YY
      dhcp client start...
      WiFi Connected
      WiFi Connected
      please start sntp first !
  • connect to artik cloud
    • WSc] Connected to url: /v1.1/websocket?ack=true
      [WSc] get text: {"data":{"code":"200","message":"OK","cid":"1234567890"}}
      Type is empty
       "data": {
       "code": "200",
       "message": "OK",
       "cid": "1234567890"
  • receive the odd “ping” eveey 30 seconds
    • WSc] get text: {"type":"ping", "ts":1497806528357}
      Ping Received
       "type": "ping",
       "ts": 1497806528357


Now the LED on your Wemo / ESP should be be controllable by voice!

A quick demo of the limited control is on youtube at


Thursday, 15 June, 2017

ESP8266 and Artik Cloud

Filed under: ESP,ESP8266 — Andrew.Rowbottom @ 11:57 am

The Quest to Control an ESP8266 using Google Home

I’ve been looking into how to control an ESP8266 from google home in the UK.

I have several “requirements”.

  •  The first is that it works without needing a “third party” app, primarily because these aren’t available in the UK, but also I’d like to be able to say “OK Boo Boo, turn on the ESP thingy”.
  • The second is to reduce the number of extra boxes I have to use, more boxes == more things to fail.

It looks like this level of integration is available through “services” more specifically the “Home Control” stuff.

My first approach was to put some kind of emulation in place.. only 3 seem to be readily available:

  • IFTTT integration
  • Philips Hue Hub Emulation
  • Wemo emulation


This is just built in, not part of Home Control, is definitely a possibility, but, well, I’ve had issues with it in the (long ago) past where it was silly slow, like minutes! And anyway, how can you call yourself a hacker if you don’t write any code?

Philips Hue Hub Emulation

If you don’t have a Philips Hue Hub, then this is probaby the route to go down, hub emulation is fairly mature and probably works with the Google Home.
BUT, I already have a genuine Philips Hue Hub, and I don’t see a way to add a second to Google Home. It would also require a separate *ix device to do the emulation, and then I’d still ahve to hook it up to the ESP8266.

Wemo Emulation

Again there’s a Wemo emulator, and apparently it works with Amazon Echo, but I think it doesn’t work with Google Home.


I continued scanning through the available Home Control Integrations, and one particularly caught my eye … ARTIK Cloud, there may well be others, but the sign-in page for the Artik Cloud had hints on it that suggested it might be what I was looking for.

This is the route I’ve been going down.

My First Steps with Artik Cloud

Well, unsurprisingly you need to create an account (its been a while, I think you have to create two accounts, a normal one, and a developer one), because I’m using a Google Home, I just used the “sign in with Google” buttons.

I created an account, and a developer account, and heaven knows, I may have created other accounts!

In the ARTIK Cloud “dashboard” I added a device “Philips Hue”, authorised it etc.. and found that I got a whole buncha lights shown in the dashboard.

Then I enabled Artik Cloud in the Google Home App  / Google Assistant, lo and behold! All of the new lights became available in the Google Home! Unsurprisingly every single one was duplicate for ones that it already knew about, though fortunately with slightly different names.

I added the new ones into a new room, I called it ARTIK just so I could keep them separate, and what do you know? I could actually control them!

“Ok Boo Boo, turn off the ARTIK lights”

Onwards and Upwards

My next trick is to find out what ARTIK can actually do, and how to get my ESP8266 to link in.

Teaser: I’m making good progress so far!

Powered by WordPress