Mesusa - Physical Intrusion Detector

Trust, but verify. Proposed electronic device gives strong indication whether physical violation of privacy has actually occured, or not, while we were absent. Also providing for a mobile alarm system.


Even worse than classic burglary can covert activities be, aiming at violating privacy and undermine basic trust.
Criminals have duplicate keys, lock picking expertise or backdoor knowledge on the alarm system. Just imagine:
Optimistic as we are, we wouldn't necessarily expect such unpleasant events to happen. Maybe we do not have no 'enemies' (= don't know 'em yet?). Maybe we won't consider ourselves in the focus of any investigation or snitches. Maybe we are pretty content with strong looking locks and burglar-entertainment recently purchased at the home improvement center. And there is nothing wrong with such gadgets, since they're supposedly better than nothing...
Being realistic, none of the regular commercial and even professional 'security stuff' can actually prove that nothing has happened. They are only to report obvious security breaches of brute force. Even worse, some appliances are quite easy to manipulate and/or featured ex-works with blatant backdoors.

It's plain to see: Only an undoubted instance of sensoring can prove that suspicious activities have NOT taken place and help rebuilding confidence!

Top | Index

Codename "Mesusa"

And here it is - possibly the first practical compromise between "hair glued with spit on door and post" and "red queen laser hallway" ;-)

General considerations:

Technological considerations:

Etymological considerations:

Top | Index

Modes of operation

Functionality 1: "Was-someone-in" (door control / door keeper)

Due to its technical implementation, it is much more difficult to restore the previous logical state of the appliance, than to allow one of thousands of different states. Almost any attempt of manipulation in favour of an attacker who wants to leave no traces of his unauthorized intrusion, would likely leave other striking marks. Covert mission: failed!
In contrast to an ordinary alarm system, the Mesusa can be active all of the time, yet we do not have to take a notice of it. For example, in times of several people going in and out of your appartment and you would unconditionally trust them, you may simply ignore the information that the Mesusa offers. No one shall trade freedom for security!

Timeouts: All interactions are limited to about 1 minute of duration. This is to prevent batteries from being exhausted in case of a defective door switch or improperly closed door. Closing of door will always forward to the next operational state (i.e. armed/disarmed)!

Functionality 2: "Alarm device"

Security considerations: In the alarm-functionality, we must somehow identify as 'authorized'. Our ticket is the four-digits code number that's been agreed on before leaving the hut. It is of course valid for only one operational cycle.
Chance that an attacker can guess the right access code and enter this code correctly, is about 1 to 9999. Brute-forcing numerous codes is therefore totally unrealistic option, given the fact that every failed attempt will result in 1-minute of acoustic alarm plus further delays. This is why four digits seem more than sufficient for this application.
If an attacker somehow spied on our valid code, he may indeed disarm the Mesusa instead of ours and continue his insiduous activities unchallenged. But now this ticket is no longer valid. When we return and enter this code to disarm the system, it won't work. Also any attempts from an attacker to perform a controller reset or power interruption will result in a invalid code from our perspective. That is to say: We will be informed about any door event or attempts to sabotage the Mesusa by a third-party.

Input method of the code number:
Assuming the door has just been opened. In order to disarm the device, one must identify as the legitimate user. Mesusa prompts to enter the right code number with a blinkin "CodE" symbol. But how? Actually this is a very simple and easy protocol:
One may have to get used to this method at the first time, but then it is probably the simplemost method that goes with a minimum of switchplay. In practice it works pretty well! (We can, alternatively, keep the door switch open and use a pushbutton parallel to the current loop for faster / more responsive code entry.).

Timeout before Leaving: If we simply wait more than 1 minute after a newly generated code has been displayed, the Mesusa will simply discard this code and stay 'disarmed'. With the next door opening, Mesusa would again be in the Leaving mode and not require authentification. This feature has proven very helpful in conjunction with receiving a visitor or postman at the door.

Timeout after Return: If no code number has been entered, or the entered number was wrong, the audible alarm will be triggered and after that, Mesusa will enter sleep mode. Minimum duration of such alarm is about 1 minute. There is no realistic way for an intruder to bypass the acoustic alarm and its registration. There is also no way to conceal failed attempts of code entry; when we enter our correct code later on, we will also be informed if and how many alarm events have occurred in the meantime. Door closing or timeout does not change alarm status!


Directly after connecting to a battery the respective jumper (J2) is being checked by the programme's reset-routine, then a display feedback about the chosen mode lights up:
J2 closed = display "F-1" = function 1 (door guard)     or
J2 open = display "F-2" = function 2 (alarm device)

Switching between those general functionalities is possible ONLY in the course of a hardware reset and after removing and reinstall of the battery. If the jumper has changed within normal course of operation, it won't be noticed at all.
Very first initialization: Directly after the microcontroller has been flashed with a new firmware by way of ISP (full chip erase), the firmware is going to gain some real entropy from one or two switching events, that delivers unforeseeable starting value for the pseudo random sequence of code numbers. For more details, see firmware.

... heeey, what if i lost my code?

Your bad!!! Since there is some hardly known software-triggered mechanism of self-destruction implemented that will be launched after three attempts of code entry have failed. It renders the chip in a useless state and will bring the battery to overheat and explosion by internal latchup of all controller registers...
Just kidding! Yet, in the function of alarm device, it is of course desirable that we have a reset-option that could end an alarm status in case of a lost code number. Thinkin' of a "Master Code"? This conjured additional security risks and is quite unneccessary in our case,  since we will definitely have physical access to the Mesusa device. A compromise would be a cold start (removing and reinserting battery).

Top | Index


Schaltung 'Mesusa' Tür-Sensor

Circuit schematics on 'Mesusa door control and alarm device':
Check accompanying documents especially for the components marked with an asterisk '*'.

Power supply (X1): At the point marked with X1 on the printed circuit board a direct pinheader of 5 millimeters grid or direct wiring to a battery holder may be soldered. As an alternative, the layout provides for pads that enable a buttoncell-holder to be directly soldered onto the pcb. This allows 3-volts lithium button cells to be set in onboards.
For reasons of energy efficiency, battery voltage is not stabilized or limited, as the controller could operate reliably with everything from 1.8 V up to 5.5 V. So two or three alkaline cells or a single lithium cell of around 3 V will suit the needs of this circuit perfectly. With the red coloured high-efficiency LED displays we will get very good exploitation of all battery options.
Check the correct polarity! In the photo we can see clearly the battery holder for 20-mm (CR20xx) lithium button cells, the most common form factor (also known as CMOS backup battery on PC mainboards).
The quiescent current of the whole circuit is only 10 µA in deactivated (sleep) state, and will full display brightness on about 4.5V it temporatily reaches current peaks of 15 mA. Regarding the energy consumption, i did some measurements and model calculations down below.

Mikrocontroller (IC1): The ATtiny2313 features good number of port lines, power saving features, useful interrupts and favorable pinout for this application. Its "only" 2 Kilobytes of Flash memory provide more than enough space, since we did not waste a thought on botching this security-related firmware together with higher-level-programming...
The ATtiny is to be configured by the fusebits for only 500 kHz of clock frequency (internal oscillator at 4 MHz with division by 8) by fusebits. Prior to installation on the Mesusa board, the chip must be flashed by means of an external programmer, because the layout does not provide for an ISP connector and it rather blocks any ISP by permanently holding the Reset pin at Vcc, so that ISP or High-Voltage programming within the circuit is rendered impossible. The idea is to solder the ATtiny2313 directly onto the Mesusa board which makes possible attempts of firmware manipulation even more laborious. Security-paranoid users could even up the ante and further protect the firmware by lockbits and a password-protected bootloader. For the latter option, the portlines PA0 and PA1 can be utilized to communicate via two- or one-wire-protocols, as they are already accessible by the jumper pins. See below for further explanation.

Connector for door-switches / external reed switches (X2):
A closed switch (door closed) will draw PB0 / PCINT0 (pin 12 of IC1) to circuit ground (GND) and the port will read a safe low level. Normally the whole appliance is in power-down mode (deep sleep) then. However, when the switch is open (door opened), the controller must be activated (wokeup from sleep mode) in a timely manner by a High level that will trigger the pin-change interrupt. So we'll need some pullup-resistor here. Yet we DO NOT use the internal pullup that may be added by software, since this pullup is rated to about 20 to 50 kiloohms only and would cause a quiescent current of around 100 uA (0.1 mA) most of the time when the door-switch is being closed. That would be a significant waste of energy in this application.
So, the circuit provides for an external pullup R9 (470 kiloohms) that will cause substantially less quiescent current of only 10 µA of permanent current while being tied to GND.
It has to be mentioned, that this method is not "dirty" or "critical" at all in conjunction with the AVR's pin-change interrupt. This interrupt is being triggered by absolute voltage level (level-triggered) and not by rising or falling edges (positive / negative-edge-triggered). In fact, it doesnt really matter how slow the voltage rises after the door switch has been opened. Just when threshold voltage of about half of Vcc has been exceeded, the AVR's logic will fire up the pin-change-interrupt pretty reliably. We can even afford to protect this high impedance portline by a blocking capacitor C3 (220nF ... 470nF) against possible interference.
All designated door-switches or individual constructions should work well with the input circuitry of the ATtiny, but expecially some Reed-switch based detectors are recommendable. Since X2 is present in 2.5 mm pitch, we could also place a jumper here, e.g. for transport purposes or functional testing. Last but not least, X2 may be connected to a push button (normally opened), which could make for a more convenient code entry in alarm functionality.

Connectors for internal reed switches (X2a-d): All four cardinals on the pcb feature soldering pads for connecting reed-tubes (only the glass body). This allows for a more compact and elegant setup of the Mesusa system and makes extra wiring obsolete. Since we only need these two components to install: the electronic device and the moving magnet (resp. moving device and fixed magnet). Just ensure that the magnet will move towards the device when the door is closed and departs as the door is getting opened. No extra wiring, no possible weakness from electromagnetic disturbance.
Rather, there is opportunity to fully protect our electronics against sophisticated attacks by means of radio frequency or radar pulses, if we use a high-quality metal case that provides good shielding.
Of course we need to equip only a single reed tube, once the positioning for an installation is known.
Free distance between magnet and reed should not exceed 1 cm with door closed. When we use stronger or larger magnets, it may also be no problem to span 3 cm or more.

Speaker/Buzzer (Bz1): At this point a small dynamic speaker or a piezoelectric speaker may be directly soldered onto the pcb. This component is not mandatory if we only plan to use door-control-functionality (F-1), as the optical feedback given by the LED-display is unmistakable. Yet a little tweeter would give convenient acoustic feedback anyway.
In the acoustic alarm functionality (F-2), we need some speaker for obvious reasons ;-) In order to achieve a pretty high volume in the event of an alarm, the speaker is being connected between two portlines (PD5 + PD6), which are push-pull-driven, so the speaker will rather see double the voltage-swing compared to a single portline driver. The protective resistor is merely precautious to limit the peak current to approximately 20 mA in a worst-case-scenario with portlines latched-up by any reason.
With high-impedance piezoelectric transducers whose resonant frequencies are around 4 kHz, we will receive a very unpleasant, high-pitched siren sound in case of an alarm. As the frequency is swept about an octave, we do not necessarily have to think about optimized resonance of the case, but of course it's reasonably good idea to provide sound holes...

LED-Seven-segment-displays  (Dis1-4):
These are 12.5-mm LED-based single digit displays of type SA39-11SRWA (12.5mm height) (being driven in multiplex. Resistors R1-R7 are dimensioned for the high-efficiency red glowing variant SA39-11SRWA (high efficiency red) to work in a comparably wide range of operating voltage range while enabling best utilization of the battery. Of course, the green or yellow variant may also be used; particularly at higher battery voltage (4.5 V, for example, from 3x AAA cells).
If the red glowing variant appears too bright at higher supply voltage, we can either increase the resistors to approximately 470 ohms or utilize the energy-saving mode of the Firmware, which dims the display by halving the PWM-duty cycle.
Notes: There seems to be no reasonable alternative to the LED-display-solution. Though it seemed quite evident from a first estimate, that any LCD could work even more energy-efficient, but bare LCDs with single or four digits, that are easy to multipley, are difficult to procure. However, one of these LCD-modules that come with an integrated controller (e.g. HD44780 compatible) would be pure overkill in this application, not to mention the security risks by their proprietary, non-transparent hardware implementation.
Modern LEDs like these SA39's seem to be the least evil in that context. They will not shot exhaust the battery in a few seconds, because they're really high efficiency and have only minimum operation cycles compared to the long periods of inactivity in this application. Detailed assessments on the lifetime of this application have been done below.

Using sockets, these should be of good quality. It's really annoying when microcontroller pins got destroyed because of a cheap socket.

Jumper J1/J2 and bootloader interface:
Portlines PA0 and PA1 are led out to a 4-pin caret in 2,54-mm-grid that allows for so-called 'jumpers' to be set or removed and thus connecting the respective portline to logical Low or leaving it at logical High. Those 2 bits allow to setup the general functionality of the Firmware and the pinheader provides for a convenient programming connector for an (optional) bootloader.

Printed Circuit Board:
The PCB, that has been designed with dimensions of 53 x 100 mm, does not present too high requirements on the process and suits well into several types of standard case, see the worksheet with parts list which is part of the Download package).

Top | Index


Mesusa's firmware has been conceived and compiled in Assembly language for well-known reasons of reliability, effectivity and safety. The source code is well featured with English comments. In here we will only discuss its general ideas and concepts of implementation.

Ressources: The firmware makes consequent use of a Pin-Change-Interrupt, that can wake-up the MCU from Power-Down-Mode (deepest sleep mode with only a few microamperes of current consumption left). Of course the programme also uses several registers, the stack (SRAM) and especially the EEPROM as a fallback memory against sabotage attempts.

Fuses are to be set up for a clock rate of 500 kHz (RC-oscillator 4 MHz, divided by 8) as well as Brown-Out-Detector at 1,8 volts. There are several options for protection of memory contents by Lockbits and protection against unauthorized ISP/High-voltage programming and Self-Programming in conjunction with an (optional) bootloader on the chip. Actual fusebit-configurations are being listed in the Worksheet.

Jumpers: There is two main functionalities in the current firmware, plus option of an energy saving mode for both. These may be configured by hardware jumpers, which are being checked with activated pullup only when the AVR has just been reset. This is to avoid unwanted power consumption by the current that a set-in-place (closed) jumper would cause.

Jumper 1
Jumper 2
Function 1
Door control, Normal
Function 1
Door control, Energy saving
Function 2
Alarm, Normal
Function 2
Alarm, Energy saving

Pseudo-randomness: Both main functionalities make use of an LFSR to generate deterministic but random looking sequence.
The software implemented LFSR has 13 bits using Fibonacci-style feedbacks from register taps at position 13,4,3 and 1.
Thus it delivers a period of maximum lenght sequence (MLS) of 2^13 - 1 = 8191 consecutive states.
The current LFSR-state is provided as a binary word in two register bytes, ranging from "00000000:00000001" to "00011111:11111111" (highbyte:lowbyte). Values are being converted into four BCDs, which are then decoded to seven-segment bitpatterns for display. So, every distinct register state is mapped to a discrete decimal display in the range of "0001" to "8191".
To repeat any given number within the range of this 13-bits-LFSR, one would have to apply 8190 consecutive clock cycles. Manipulating the device by repeatedly closing and opening the door, is thus a quite futile undertaking because of the built-in delay of at least 10 seconds per cycle.

Random initialization: To avoid possible attack, the programme would never start with fixed default value after battery replacement, warmstart (reset pulse) or coldstart. Instead, there is two precautions that provide for a real random start value:
From a "virgin" chip that was just flashed with the firmware, the programme will draw some timing randomness by the very first switchplay. That is to say: The Mesusa will NEVER start or restart with a fixed default value!
In daily business, LFSR sequence is of course deterministic. This is to make sure that a certain display value will re-occur only after more than eight thousands of cycles.
After activation, the next code number has already been calculated in advance and stored to the controller's EEPROM.
Should the controller be forced into a reset cycle, the programme will always continue with this number from the EEPROM buffer, and never return to a state that has occured shortly before. So, Mesusa will never display the same number in short succession, even with coldstarts or EMP might have caused an ungentle reset of the device ;)

EEPROM access: Actually, we'd only need two EEPROM memory addresses to buffer the last date of LFSR for a safe restart in case of sabotage or accidental reset. Since every single EEPROM cell would endure about 100,000 write cycles, this would last for decades of use in this application.
Yet... it's kinda foolish to restrict on the same two cells, while there is 126 further ones there just waitin' to be poked...
Instead, the programme distributes EEPROM write load to all 128 memory cells. Each access entails 4 byte writes to be performed; old word will be overwritten to $FF while the next two bytes ahead are written with the current word. By continuous exchange of cells, each single EEPROM adress is being stressed 32 times less now, thus the EEPROM life will extend to incredible 3.2 million of programming cycles - which should be sufficient for this application 'til the end of all times. (Anyway - Taking good care of an EEPROM preserves its resale value ;-)

Display driving: The 4 portlines PD0 to PD3 connect the common anode of a chosen SA39-11-digit to High level, and the 7 port lines of PB1 to PB7 will then draw the cathodes of segments a-g at Low logical level to make the respective segments light up according to the bitpattern loaded into the port register. The decimal point is not needed and not connected to the controller. Multiplex frequency is about 250 Hertz, any digit will be switched for 1 ms, the duty cycle is already 1:4 (25%) in normal mode and 1:8 (12,5%) in energy saving mode. In sleep mode, all respective port lines are being passified (high Z) to make sure that no leak currents can occur.

Entering codes: The additional feature of an 'Alarm device' was actually added to the firmware after the actual Mesusa functionalities have already proven well for months. The input method therefore had to come along with the existing hardware, display and door-switch. Modus operandi has been described further above. It should be noted (for security/vulnerability assessment regarding Power-Anylysis or related attack), that the code is course stored in RAM while being entered, and only after the fourth digit has been entered, counterchecked against the correct code for disarming the current alarm cycle.

Energy saving (Jumper 1): The energy-saving feature is being activated by hardware jumper J1. For normal condition (i.e. NO special energy savings), J1 must be CLOSED (= PA1 is Low). When J1 was OPEN, PA1 sees logical High when being checked by the programme, and some energy-saving measures are being implemented at different stages of the programme. In particular, the duty cycle (pulswidth) of the LED driver is being halved (inserting 4 ms of 'blanking'). Display will not appear quite as bright, but also consumes only half as much battery current.

Activation (wake-up):
When the door switch was opened, the current loop was interrupted and the portline PB0 becomes a logic High level that triggers the PCINT (pin-change-interrupt) which will wakeup the Controller from sleep mode and continue programme execution directly after the sleep-opcode where is has fallen into sleep. Immediately after the programme has woke up, it will then deactivate the PCINT to make sure that further switchung events or interference on the (high impedance) port input could not cause any confusion whilst executing the respective programme subroutines (like generating sounds, display of code number etc.)

Deaktivation (sleep/power-down state):
The program decides whether it returns to sleep state and allows pin-change interrupts for later wakeup. It will only re-activate PCINTs after the respective programme function has been ended either by timeout or by closing the door. To detect further switch-play, the portline PB0 is only being checked by the polling method. As already mentioned, this is to exclude any risk of uncontrolled interrupts.

Safety and protection of the firmware:
All previous considerations regarding the safety/security of this device are done from the basic assumption that an attacker would not be empowered to change the firmware or deliberately manipulate memory contents of the controller. The programme has to be a black box in view of an attacker.
Access to the firmware of a ATtiny2313 would only be imaginable through a physical access on the interface lines of the controller that allow SPI/ISP or high-voltage programming. However, if the controller has been soldered directly onto the proposed board, these options of direct programming access have already been technically blocked, since the reset line is permanently held high (at Vcc), thus making programming cycles impossible from hardware.
This protection should be more than sufficient for most scenarios of application. Who would seriously assume that an attacker will disassemble the device and unsolder the AVR for access or exchange with a bogus chip? If we take that paranoid scenario into consideration, then there of course further means of protection in place: Just lock the memory access by Fuse- and Lockbits of the AVR and install a Bootloader that enables protection by a strong password. This combination of blocked read-access and bootloader will make the whole chip tamper-proof, and any supposed manipulation of the firmware could be proven with a 100 percent of confidence.

Top | Index


Suitable door switches: Any external door contact or reed switch may be directly connected to X2 at the Mesusa-PCB.
Although the regular reed switches are often being marked as "N.O." (normally open), these are just right for this application. Assuming that the door IS normally closed with magnet in proximity to the reed, actually the "N.O."-reed becomes a "N.C." (normally closed) one in this setup. To prevent further confusion with that NC/NO stuff, our simple rule of thumb is supposed to be: Switch must be closed when the door is closed. Switch must be open, when the door is open.
Of course there is option of using more than one switch in series, even in a mixed configuration of conventional and magnet switches. This could vastly improve protection against attempted sabotage or manipulation.

Reed Switch Set (external) Photo: jt
External Reed door mounting sample (Photo: jt)

Magnets: In general, the free distance between magnet and reed-switch should be minimized and the reed should be aligned to the magnetic field. Any cheap ferrite magnet (grey/black) will do fine within a range of, say, 1 cm at maximum, assuming that the magnet has similar dimensions as the reed switch. The allowable distance of safe switching is likely to increase with stronger types (e.g. neodym), occasionally even 5 cm of distance would allow safe operation.
Recycling-hint: This is a good opportunity for reusing neodym magnets, taken out of the "voice-coil" assembly from an old 3.5 inch hard drive!

Mounting: Glue or adhesive strips can do a pretty good job on a clean and smooth surface!

Battery life expectations: The very first prototype of the mesusa has run more than half a year with a small CR2032 lithium cell (BIOS battery from an old mainboard!). The rough calculations down below assume, that Mesusa is being activated in doorkeeper mode (F-1) with display lighting about 6 minutes per day. This would equal at least 3 door events (going out + coming back) with timeout being stressed each single event. Power consumption will then appear as such:

Top | Index



Once again, it all began
on a plugboard
(using big display
from the project

Test circuit on
(component side)

Test circuit on breadboard;
in my workflow, these manually routed wires are direct template for layout artwork.

First PCB, preliminary layout (with modifications) solder side
First PCB,
component side

for the LED displays

One of the first
PCB's built into
some plastic case,

Plastic prototype mounted
to an appartment door
(half open,
code lights up)

Top | Index


So, this ain't no real security system...?

Surely it isn't. The electronic Mesusa device could not prevent criminal activity, as no (legal) security system can. It is ONLY for reliable detection and registration of an unauthorized access or access attempt. Most of the time it is providing negative confirmation that such security breach did not occur.

Alternative Applications


The "Mesusa" Project (Hardware, Software and Firmware) is a free and open documented development of Julien Thomas released under the terms of Creative Commons - Attribution - Share Alike.

Top | Index



  1. Wikipedia on Reed switches

  2. Datasheet on the ATtiny2313:

  3. Wikipedia on Mezuzah (Mesusa)

  4. Kingbright datasheet on SA39-11SRWA (high efficiency red seven segment displays):

  5. PDF Xilinx Application Note 052 regarding LFSRs:

Top | Index

07/2015, 01/2016, 07/2017, 10/2020