DEV Community

Emelie Fogelström
Emelie Fogelström

Posted on

FenceGuard, part 2: the sensor arrived — and it works

First contact: a PIR sensor, a LoPy4, and a loop that prints 0s and 1s.


Mail for me, the sensor has arrived!


The sensor arrived yesterday. A PIR motion detector — passive infrared, the same basic technology used in every security light and burglar alarm since the 1980s. Cheap, proven, low-power. A good place to start.

Hardware: HC-SR501

HC-SR501

The sensor is an HC-SR501 — a standard PIR module with two adjustable potentiometers and a jumper for trigger mode.

For testing I've set it to:

  • Time delay: counter-clockwise to minimum (~5 sec repeat inhibit time)
  • Sensitivity: ~3m range
  • Trigger mode: L (single trigger)

Single trigger means the output goes high once per detection event, then stays low until the inhibit timer expires. That suits this phase of testing, I want clean, discrete events, not a continuous high signal while something is moving.

HC-SR501 connected to LoPy4

First connection

I connected it to the LoPy4's expansion board and wrote the simplest possible test:

import machine
import time

pir = machine.Pin('P20', machine.Pin.IN)

while True:
    print(pir.value())
    time.sleep(2)
Enter fullscreen mode Exit fullscreen mode

That's it. Poll the pin every two seconds, print the value. Walk in front of it: 1. Walk away and wait: 0.

It works.

What this doesn't tell me yet

A stream of 1s and 0s is a long way from "there's a fox near the fence." Right now I have no idea:

  • how long a real motion event lasts versus a false trigger
  • how the sensor behaves in wind, or when temperature changes rapidly
  • whether polling every 2 seconds is too slow, too fast, or about right

That's what the next step is for. Tomorrow I'm replacing the raw values with timestamps and logging when something happens rather than just that something happened. Once I have timestamped events I can start looking at patterns.


FenceGuard is a project I'm building in public. I'll be documenting hardware choices, firmware, and data analysis as I go. Follow along if that's your kind of thing.

Top comments (0)