> ## Documentation Index
> Fetch the complete documentation index at: https://docs.edgeimpulse.com/llms.txt
> Use this file to discover all available pages before exploring further.

# EleTect X: So Elephants and People Both Survive thanks to EdgeAI

> A solar powered guardian that senses an elephant coming, then deters it safely with the same sounds nature already taught it to fear

Created By: Abhinav Krishna

* Public Project Links: [ETX-V (vision, 1097972)](https://studio.edgeimpulse.com/public/1097972/live) and [ETX-A (acoustic, 1110036)](https://studio.edgeimpulse.com/public/1110036/live)
* Github repository: [https://github.com/Abhinavkrishna3211/EleTect-X](https://github.com/Abhinavkrishna3211/EleTect-X)
* Published Write-ups: [Arduino Project Hub](https://projecthub.arduino.cc/abhinav_krishna_n/eletect-x-detect-deter-learn-4b7846) and [Hackster](https://www.hackster.io/abhinav123krish/eletect-x-so-elephants-and-people-both-survive-8963e7)

![EleTect X: So Elephants and People Both Survive](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/eletect-x-thumbnail.jpg?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=69596eaffec6eefe30fa39faf25e2096)

## The problem this is built to stop

Human-elephant conflict is one of India's worst wildlife problems, and it is getting worse. It costs lives, harvests and livelihoods, and the death toll is still rising. Government data placed before India's Parliament shows elephants killed 2,853 people across the country between 2019 and 2023, with the toll climbing every year in that window to 628 deaths in 2023 alone, a five-year high. Kerala specifically recorded 124 conflict deaths between 2019 and 2023, and separate data for 2021 to 2025 puts the figure at 103, close to 20 lives a year in this one state alone. It has not stopped. In June 2026, a 36-year-old mother was killed by an elephant near Munnar, the same forest landscape this project is deployed in, her son left severely injured beside her. Many of these deaths also leave a farm without its main earner. Crop and property losses add up on top of that, and Kerala's Forest Department has admitted its compensation system cannot keep up. A 2022 departmental proposal for a state-wide conflict management overhaul states that "the existing rate of compensation for various crops damaged by wild animals has not been revised for a long time" and that forest divisions "are not able to release all the claims of compensation due to shortage of funds," recommending a fresh Rs. 15 crore a year just to keep the backlog from growing. The problem behind that backlog is large: a 2018 peer-reviewed review of human-elephant conflict management strategies puts the number of Indian families directly affected by elephant crop raiding at roughly 500,000 a year, nationally. That is the scale a claim-by-claim compensation office is being asked to handle, on top of the deaths. A 2025 field study on wildlife crop losses in India found the country still has no unified system for counting what elephants and other wildlife cost farmers season to season, and its authors call for a national human-wildlife conflict mission because the state-by-state claims process still cannot produce a reliable figure.

**It is not just Kerala, or just India.** Human-elephant conflict runs wherever elephants and dense human agriculture now overlap, which the same 2018 review counts as thirteen Asian elephant range countries and thirty-seven African nations. India has the highest recorded toll, but many other countries are paying too. Sri Lanka logged a record 433 elephant deaths and 145 human deaths to conflict in 2022 alone, and more than 150 elephants were already dead in just the first four months of 2023, according to Mongabay's reporting on Sri Lankan wildlife department figures. Things have not improved: the Wildlife and Nature Protection Society of Sri Lanka counts more than 6,400 elephants lost to conflict there over the past 24 years, an average above 260 a year, and the first six months of 2025 alone had already accounted for 250 more elephant deaths, a pace that would match or beat 2022's record by year's end. Kenya's crop-raiding incidents, nearly half of them elephant-driven, more than doubled between 2020 and 2023, from 156 recorded cases to 363, and the country's own wildlife-conflict compensation office is sitting on a Sh1.2 billion backlog of unpaid claims, the same kind of stalled ledger Kerala's own Forest Department describes above, according to Kenyan government figures reported by the Daily Nation; Kenya's government has since raised its own compensation budget in response, from Sh908 million in 2023 to a planned Sh1.95 billion in 2025, an admission that the old budget was never enough. A deterrent that works here could help from the Western Ghats to the Rift Valley.

Elephants die in this conflict too. On 9 September 2026, an elephant calf was electrocuted by a fallen power line at Kottappady, near Kothamangalam. It was one of many: nearly 750 wild elephants died in Kerala alone between 2019 and 2025, more than one in ten of them from conflict with people rather than natural causes. Electrocution is the leading cause of elephant death in India, most of it from illegally electrified fencing farmers string up to keep elephants off their crops, or from sagging low-hanging power lines like that one. In the five years to December 2022, 348 elephants died this way nationally, more than train collisions and poaching combined over the same period, according to figures the Ministry of Environment, Forest and Climate Change gave Parliament directly. Roughly 100 elephants a year die in retaliation nationally as well, mostly poisoning, electrocution, or explosives hidden in food, by the central government's own figures.

![News coverage of human-elephant conflict in Kerala](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/image61.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=f23ee6ba5959d8f729b2902a5fd4e76c)

**Why the deterrents already out there stop working.** Every fixed deterrent tried so far has failed the same way: elephants get used to it. A captive study found elephants stopped responding to fixed deterrents after repeated exposure, even though each one caused alarm and avoidance the first few times, and Human-Elephant Conflict handbooks describe the same pattern from the other direction, bolder, habituated elephants pushing straight through deterrents that used to work reliably. A fixed light, noise or smell works only until the elephant learns it is harmless. Then farmers escalate, and that is when it turns deadly. Illegal electric fences, poison and explosives hidden in food kill elephants, livestock and sometimes the farmers themselves, and they still do not fix the problem: a fixed deterrent cannot change once the animal stops fearing it.

**Wild boar are a problem too.** They cause a large share of Kerala's crop losses, digging up tubers and root crops overnight. They rarely kill anyone, but they keep hitting the same small farms that already live with elephants. Our own family farm deals with boar, and we have lost crops to them. Some farms face both animals at once.

## 2. The solution: EleTect X

![An EleTect X node on a forest boundary](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/image11.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=374b86625f31aaa47f3558c651083128)

![News coverage of human-elephant conflict in Kerala](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/image61.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=f23ee6ba5959d8f729b2902a5fd4e76c)

EleTect X is a solar-powered node that sits on a forest boundary and watches for elephants and wild boar. It uses three senses to decide how seriously to take an approach: a buried geophone for ground vibration, a day/night camera to confirm what the animal is, and a microphone for gunshots, chainsaws and elephant calls. It deters with sounds and lights backed by published field research, and it changes its response from one night to the next so the animal never learns the pattern is safe. It radios forest officers and nearby residents only when the situation calls for it. The whole loop runs on the node and ends in a physical action at the boundary.

Most projects in this space are a camera on a trail with a model behind it. EleTect X is different in three ways. It does not stop at detection; it deters, and each deterrent choice comes from field studies, bio-inspired research and the knowledge of people who live on this boundary. Its decision loop is built around the failure described in Section 1, so it varies its response instead of repeating one until it stops working. And it treats wild boar as seriously as elephants, because for a family living behind this boundary, a dug-up tuber field is a loss even on a night no elephant comes.

EleTect X detects and deters both elephants and wild boar, the two animals that cause the most damage to farms along boundaries like this one. Nothing in the sensing or anti-habituation logic is tied to these two species, so the system can be extended to whatever animals cause trouble somewhere else.

Boar have gone through our farm more than once. It was our grandfather, who has worked this land for longer than we have been alive, who first asked us to build something that could stand watch over it. That is why boar get the same training, testing and reporting as elephants throughout this write-up.

**What we learned before writing any firmware.** Every sensing and deterrence choice below traces to one of three sources: published field biology and behavioural ecology, direct consultation with the Kothamangalam Divisional Forest Office, and conversations with the people who live and farm on this boundary, forest watchers and farmers who have spent years watching elephants and boar. Section 3 covers what came from each source, for both animals.

### Real-world dataset collection and early model verification

![Collecting our own elephant images for the vision dataset](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/image53.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=ba11e0eb1797dc4360ded8049c810e4f)

The on-ground survey described in Section 3 below told us where to look; it did not hand us a dataset. Stock elephant photos have the wrong light, the wrong poses and usually another continent's trees, which is no use for a model that has to work at dusk in the Western Ghats. So the vision dataset in Section 8 started with our own captures. The Arducam IMX462 day/night rig this project deploys (Section 7) hadn't arrived yet when this first push started (procurement was running behind the rest of the build), so the first sessions were shot on a Raspberry Pi camera module. That was enough to show a local dataset was worth the effort. Once the Arducam rig was built and nodes were in the field, later sessions added field-collected frames on top of that starting set. Alongside our own captures, Section 8 also draws on public, license-tracked wildlife datasets (Roboflow Universe, WCS Camera Traps, and others, each one audited for contamination and logged with its source). These are camera-trap and field images of the right species, just not from our rig. The elephant and boar classes in Section 8 are therefore a mix of all three: early Raspberry Pi camera captures, our own workbench and field-trial frames, and vetted public datasets.

Every frame we shot went through the same curation pass Section 8 describes in more depth: clean bounding boxes, a by-eye check for contamination, and a Background class so the model learns what an empty scene looks like.

![Early field runs of the first vision model](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/image37.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=f81d2607d83fa2338812e8d4f59a85a1)

Early field runs with that first dataset were encouraging. The model picked out elephants against foliage and changing light, not just in clean bench shots, so we kept building the local dataset. Section 8 holds that early result to a harder standard: held-out test splits, per-class recall and precision, and the threshold trade-offs behind the model that shipped.

## 3. What we studied before designing detection, deterrence, or anti-habituation

Elephants and boar needed separate research. For both, we used more than one source and checked what we learned with people on the ground before building anything.

### On-Ground Survey & Study Area

The field research took place in **Kothamangalam** and **Kottappady**, Kerala regions at the edge of the **Western Ghats** that experience frequent elephant incursions into farmlands and villages.

We conducted household-level surveys to assess the **scale and nature of human–elephant conflict (HEC)** in these areas. From **100 surveyed households**, **85 reported direct encounters** with elephants, while:

* **66%** suffered **crop destruction**, and

* **38%** experienced **human injury or fatalities** related to elephant incidents.

Those numbers made the need for early warning and deterrence clear, and they shaped everything below.

### Elephant: biology, behaviour, and what the boundary itself taught us

![Asian elephants at the forest edge](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/image64.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=029a34236c9663c162c3ff0897e89c06)

The seismic sensing decision traces directly to Caitlin O'Connell-Rodwell's field research in Etosha National Park, which showed elephants detect and orient toward alarm signals delivered purely through ground vibration, with no airborne sound present at all, using specialised mechanoreceptors in their feet that pick up bone-conducted signal at ranges far past their airborne calls. If elephants listen to each other through the ground, we can listen for them the same way, so the geophone comes first in the detection chain. The deterrent sound selection traces to Dr Lucy King's nine-year beehive fence field study with Save the Elephants, Oxford, and the Kenya Wildlife Service, which measured an 86.3 percent deterrence rate during peak crop season across more than three thousand approaches, because a bee swarm threatens the sensitive lining of an elephant's trunk and the resulting fear response is innate rather than learned. The anti-habituation requirement traces to the captive habituation study and the Human-Elephant Conflict handbooks cited in Section 1, both of which describe the same problem: a fixed response eventually stops working.

Papers were only part of it. Before any node went into the ground, we walked the actual Kothamangalam boundary with forest watchers attached to the Kothamangalam Divisional Forest Office, who pointed out which specific stretches see elephant crossings versus which stretches only look like they should on a map, and neighbouring residents who described, in their own words, what an approaching elephant sounds and feels like at their own homes before they ever see it. No paper had recorded any of that. Because of what they told us, we place nodes at known crossings instead of spacing them evenly along the line.

### Wild boar: a different animal, a different set of instincts, checked the same way

![Wild boar](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/image48.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=a3c8ebfd490c34e46a63d73cf952a4c8)

Boar are not small elephants, and we could not treat them as a cheaper version of the same detection problem. Boar are primarily nocturnal, move in family groups, and root through soil for tubers and invertebrates rather than approaching in the open the way an elephant does. To tell a boar from an elephant we need both the geophone, which reads footfall rhythm, and the camera, which reads shape and gait. Boar get used to a fixed deterrent as quickly as elephants, maybe faster, so the anti-habituation bandit in Section 11 covers both.

We asked the same local questions about boar. Farmers along this boundary described specific patterns, matching what we see on our own farm: which crops draw boar first, what time of night they move, and what a half-hearted deterrent looks like failing in real time, a boar pausing, testing the response, and coming back within the same night once it decides the noise or light is not dangerous. That is the same habituation the research describes in elephants, seen in boar. So boar recall, boar false positives and boar deterrence tiers are core requirements in this project.

## Hardware and software used in this project

These are the components used to build EleTect X:

* **Arduino UNO Q** (4 GB), main compute: Qualcomm QRB2210 MPU for vision and sensor fusion, STM32 MCU for real-time sensor/actuator control
* **LoRa radio**, Grove LoRa-E5 (IN865), long-range alert uplink to the gateway
* **Geophone**, 10 Hz, buried, for seismic (footstep) sensing
* **INA333 instrumentation amplifier** + **ADS1115 external ADC** (I²C), conditions and digitises the geophone signal ahead of the reflex layer
* **BOYA BY-M1 lavalier microphone** (USB, MPU-side capture), acoustic sensing (trumpets, rumbles, chainsaws, gunshots)
* **Arducam IMX462 day/night USB camera** + 940 nm IR illuminator, vision confirmation stage, day and night
* **Powered USB-C hub**, on its own 5 V buck rail, expands the UNO Q's single USB-C port for the camera and the microphone's audio card
* **External USB audio card** (CM108/PCM2902-class USB sound adapter), connects the BOYA microphone to the hub for MPU-side capture
* **TPA3116D2 Class-D amplifier** + **Ahuja SUH-15 horn speaker** (8 Ω), audio deterrent playback
* **DFPlayer PRO**, stores and triggers deterrent audio clips
* **White (cool-white) and royal-blue (\~450 nm) high-power LED stars** + IRLZ44N low-side switches on an 8 V XL4015 buck rail, visual deterrent
* **4S LiFePO4 battery pack** (\~6 Ah) with integrated BMS, field power
* **20 W solar panel**, continuous field charging
* **MPPT/PWM solar charge controller** (LiFePO4 profile), charges the battery from the panel
* **PETG 3D-printed enclosure** (designed in Fusion 360), weatherproof housing, IP-rated cable glands, pressure-equalizing vent
* **Supporting passives**, TVS diodes and RC filtering on sensor inputs, logic-level MOSFET load switches for camera/IR/amp/LED rails, reverse-polarity protection

### Software

* **Arduino App Lab**, builds, deploys and runs the app on the UNO Q
* **[Edge Impulse](https://edgeimp.com/community26)**, dataset, training and deployment for the vision model (ETX-V) and the acoustic model (ETX-A)
* **KiCad**, schematics for the geophone, LED and IR, sound and LoRa, and power sheets
* **Fusion 360**, enclosure design
* **ChirpStack**, LoRaWAN network server for the alert path
* **Supabase (Postgres)**, web app backend: database, auth, row-level security and edge functions

## 4. System architecture: Sense, Decide, Act, Learn

EleTect X splits the work between the UNO Q's two processors and gives each the job it does best. The diagram below shows the whole loop, and the walkthrough after it follows one approach from the first footstep to the response.

### What happens when an elephant or boar approaches

* **Sense.** The geophone samples continuously on the reflex layer, whether or not anything is nearby, while the acoustic model on the cognition side listens on its own 30-second cycle, recording about 15 seconds of every 30, independently of the geophone. An animal's footfall shows up as seismic rumble in the geophone; a call, chainsaw, or gunshot shows up as an acoustic event in the microphone, a USB device on the Linux side. The camera and the vision model only run when the geophone fires; between events the camera is off and vision sits idle.

* **React locally, first.** The reflex layer runs its own safety gates and checks on the STM32U585 microcontroller alone. The seismic trigger is decided here, without waiting on the Linux side.

* **Start the vision check.** Only once the reflex layer decides a reading is worth a closer look does it send a Bridge call across to the Qualcomm QRB2210. That call starts the vision check: the camera opens and the Python client sends its frames to the Edge Impulse vision runner, which stays loaded in memory between events. Vision only does work when the geophone has found a reason.

* **Fuse the evidence.** The vision model's read on the camera frame and the reflex layer's sensor data both feed into a weighted log-odds sensor fusion step, which turns three independent, imperfect senses into one calibrated probability, P, that this really is an elephant or a boar and not a false alarm.

* **Decide how hard to respond.** An epsilon-greedy contextual bandit takes that probability P and picks a deterrence tier. It decides how to respond as well as whether to, so the same approach at the same spot does not always get the same response. This is the anti-habituation engine from Sections 1 and 2 at work.

* **Act, in the real world.** The decision drives one of three kinds of outcome: the horn (DFPlayer Pro through the TPA3116D2 amplifier) plays the track the bandit picks from a library that includes honeybee swarms and tiger recordings; the LED wings fire a strobe pattern; or, if the situation is out of range or the system's confidence is too low to act safely on its own, a LoRa alert goes out to the ranger dashboard instead.

* **Learn from what happened.** After the horn or LEDs fire, the quiet duration that follows, how long it takes before the animal is detected again at that spot, feeds back into the bandit as its own reward signal. A response that worked buys a longer quiet stretch, one the animal ignored does not, and the bandit adjusts its next pick at that spot. Each node keeps a separate ladder for each species, so a night of boar or fox visits cannot wear down the response an elephant gets the next morning (Section 11). Over time, this makes the system harder to get used to.

### The two layers behind that loop

**The reflex layer** lives on the STM32U585 microcontroller, under Zephyr, and effectively never sleeps. A state machine cycles through IDLE, SENSING, EVENT, and COOLDOWN on every loop iteration: geophone sampling and STA/LTA trigger detection run continuously in IDLE and SENSING, and once a trigger crosses threshold the state machine moves to EVENT and starts timing the actuators directly, the horn and LED firing durations, the safety gates that stop them from re-firing back to back, and the COOLDOWN window that follows before the cycle can trigger again. All of this runs on the microcontroller, independently of the Linux side.

**The cognition layer** lives on the Qualcomm QRB2210, under Debian Linux. The microphone (a USB device), the vision model, the sensor fusion step, and the bandit that decides how strongly to respond all run here in Python. The vision check starts when the reflex layer signals a trigger.

**How the two halves talk to each other.** Arduino's own Arduino\_RouterBridge library is the only link between them, and it runs in both directions for two different reasons. Microcontroller to Linux is a one-way, fire-and-forget notify: the reflex layer calls it once, the moment a trigger crosses threshold, purely to start the vision check on the Linux side, and it never blocks the sensing loop waiting for a reply. Linux to microcontroller runs the other way, as RPC calls the cognition layer makes once it has decided what to do, reaching hardware adapters registered on the microcontroller side that fire the horn and the LEDs. One direction starts the vision check; the other tells the microcontroller what to fire.

**Why the UNO Q specifically**: detection needs a real-time sensor loop that never misses a footstep, and decision-making needs Linux and enough compute for a vision model and a learning system. Most setups make you pick one, or join two boards with a fragile link. The UNO Q has both on one board, with a bridge between them out of the box.

## 5. Getting started with the Arduino UNO Q

![Arduino UNO Q](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/image50.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=932cb4edc3d808880fb798c228257ac3)

The Arduino UNO Q is more than a traditional Arduino board. It combines a powerful Linux computer and a real-time microcontroller on a single board, allowing you to run high-level applications alongside real-time hardware control.

### Key Hardware on the Arduino UNO Q

* **MPU:** Qualcomm Dragonwing QRB2210, quad-core ARM Cortex-A53 up to 2.0 GHz

* **Operating system:** Debian Linux

* **MCU:** STM32U585, ARM Cortex-M33 up to 160 MHz

* **MCU memory:** 2 MB Flash and 786 KB SRAM

* **Memory & storage:** 4 GB LPDDR4 RAM and 32 GB eMMC

* **Wireless:** Dual-band Wi-Fi 5 and Bluetooth 5.1

* **USB-C:** Power, data and expansion

* **I/O:** 14 digital I/O, 6 analog inputs, I2C, SPI and UART

* **Expansion:** Qwiic/STEMMA QT, camera, display and additional expansion interfaces

* **On-board features:** 8×13 LED matrix, RGB LEDs and user button

![Arduino UNO Q pinout](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/image5.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=c840afc3a85d8add9329dfbfd0e99d42)

![Arduino UNO Q board layout, top and bottom](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/image21.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=37b5b38cc5f2812f7201ca794ca28235)

Think of the UNO Q as two processors working together. The Linux side handles tasks such as networking, AI, image processing and web applications, while the STM32 microcontroller handles GPIO, sensors, actuators and real-time control.

### Setting Up the UNO Q

To get started, you will need:

* A computer running **Windows 10/11, macOS 11+ or Ubuntu 22.04+**

* An **Arduino UNO Q**

* A **USB-C data cable**

* An internet connection

* A Wi-Fi network and its credentials

#### 1. Connect the UNO Q

We will initially use the UNO Q in **PC Mode**.

Connect the UNO Q to your computer using a USB-C cable.

**Important:** Make sure your USB-C cable supports **both power and data**. Power-only cables will not work for this setup.

For the best experience, use a USB-C or USB 3.x port on your computer.

#### 2. Get the Software

Download the following software from Arduino:

* **Arduino App Lab**

* **Arduino Flasher CLI**

![Arduino App Lab and Arduino Flasher CLI download page](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/image28.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=8946849539a8a09269b6e5686e681cb3)

Download the versions appropriate for your operating system.

#### 3. Update the Firmware

Before using your UNO Q, it is recommended to make sure the board firmware is up to date.

**Warning:** Flashing the board can erase the contents of the UNO Q. Make sure you do not have anything important stored on the board before proceeding.

#### Set Up Flasher CLI

The Flasher CLI is provided as a compressed ZIP file.

* Extract the ZIP file.

* Open **Terminal** or **Command Prompt**.

* Navigate to the folder containing the arduino-flasher-cli executable.

#### macOS / Linux

Run:

```bash theme={"system"}
./arduino-flasher-cli
```

#### Windows

Run:

```bash theme={"system"}
arduino-flasher-cli
```

On Windows, you may be prompted to install a driver. Accept the prompt and complete the driver installation.

#### 4. Prepare the UNO Q for Flashing

Before flashing, place a jumper or jumper wire between the two end pins of the **JCTL connector**.

Once the jumper is installed, connect the UNO Q to your computer using USB-C.

![JCTL jumper position for flashing](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/jctl_usb_boot_jumper.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=bddf97334945f88add8559ab0e8a1960)

The jumper goes across the bottom row of the JCTL header, boxed in green above: the USB\_BOOT pin and the GND pin next to it.

#### 5. Flash the Latest Firmware

Open Terminal or Command Prompt and navigate to the folder containing the Flasher CLI.

Run:

#### macOS / Linux

```bash theme={"system"}
./arduino-flasher-cli flash unoq
```

#### Windows

```bash theme={"system"}
arduino-flasher-cli flash unoq
```

On Flasher CLI versions older than 0.5.4, use `flash latest` instead. The tool will download and install the latest firmware. This may take several minutes because the firmware package can be large.

**Do not disconnect the USB cable or interrupt the process while flashing.**

When flashing is complete:

* Disconnect the UNO Q.

* Remove the JCTL jumper.

* Reconnect the UNO Q to your computer.

The board will boot and the LED matrix should display the Arduino startup animation.

#### 6. Install Arduino App Lab

Arduino **App Lab** is the development environment designed for the UNO Q. It allows you to create applications that combine:

* **C/C++ Arduino sketches** running on the MCU

* **Python applications** running on the Linux MPU

* **Bricks** that provide additional functionality

Install App Lab according to your operating system:

* **Windows:** Run the installer and follow the prompts.

* **macOS:** Drag the application into the Applications folder.

* **Linux:** Extract the archive and run the AppImage.

Once installed, start **Arduino App Lab**.

#### 7. Set Up Your UNO Q in App Lab

When App Lab opens, it will search for connected UNO Q boards.

Connect your UNO Q through USB. A new board should appear in App Lab.

![App Lab detects the UNO Q as a new board](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/image18.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=7f073618e334ff734ec50f92bd195213)

Select the **UNO Q** marked as **NEW BOARD**.

You will then be guided through a three-step setup process.

#### Step 1: Board Configuration

![App Lab setup, Step 1: board configuration](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/image27.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=fd80a943f6c4a7ea3aa6ab5a023384bf)

Choose your **keyboard layout**.

Then give your UNO Q a name.

For example:

`EleTect-X`

You can choose any meaningful name for your board.

Click **Next**.

#### Step 2: Network Setup

App Lab will scan for available Wi-Fi networks.

Select your Wi-Fi network and enter its credentials.

![App Lab setup, Step 2: network setup](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/image15.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=52486a3af2b36faf57f0f92fddfa8771)

If your network does not appear, use **Setup Manually** or scan again.

The UNO Q needs network connectivity for several of its Linux-side features and software updates.

Click **Next**.

#### Step 3: Linux Credentials

You will now create the Linux credentials for your UNO Q.

The username is:

`arduino`

Enter a password of your choice and confirm it.

![App Lab setup, Step 3: Linux credentials](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/image26.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=b4d9e84ee3cbbeaf624cd2eb5fddb010)

Keep this password safe. You may need it later when accessing the Linux side of the board.

Click **Confirm**.

#### 8. Complete the Updates

Once the initial setup is complete, App Lab will check the UNO Q for available software and firmware updates.

You may see a screen such as:

**"Looking for updates..."**

![App Lab checking for updates](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/image40.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=0cbd7ac1b858d2f7cc7be52279b1dadd)

If updates are available, allow App Lab to download and install them.

Updates may include components for:

* Arduino UNO Q software

* Arduino App Lab

* Arduino CLI

* Arduino App CLI

* Other board support packages

The update process can take a few minutes.

**Do not disconnect the UNO Q while the update is in progress.**

You may see the update log while the process runs.

![App Lab update log](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/image8.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=0e4add38ffba9b3875b20da58d371ab3)

Once the update is complete, App Lab may ask you to restart.

Click **Restart App Lab** and allow the application to reconnect to your UNO Q.

#### Setup complete!

Once App Lab reconnects successfully, your UNO Q is ready to use.

#### 9. Exploring App Lab

After setup, App Lab provides several sections for working with your UNO Q.

The **Examples** section is a good place to start if you are using the UNO Q for the first time.

![App Lab welcome screen: Apps, Bricks and Examples](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/image58.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=8398bf3172377f36c2730b7a3167501d)

![App Lab Examples](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/image13.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=e2d0cd0e60e6eb6f05fc740522e4d4b6)

You will find example applications covering different capabilities, including:

* **Blink LED**

* **Blink LED with UI**

* **QR and Barcode Scanner**

* **Home Climate Monitoring**

* **LED Matrix applications**

* And more

You can open an example to understand how an UNO Q application is structured before creating your own.

#### Apps and Bricks

The UNO Q introduces a different approach to Arduino development through **Apps** and **Bricks**.

#### Apps

An **App** is a complete UNO Q project that can combine code running on both processors:

* **MCU:** Arduino sketch / C++

* **MPU:** Python / Linux application

* **Configuration:** App configuration files

* **Bricks:** Optional additional services

This allows one project to combine real-time hardware control with Linux-based processing.

#### Bricks

**Bricks** are reusable components that provide specific functionality to an App.

Examples include:

* Camera and image processing

* Object detection

* Web interfaces

* Data storage

* AI services

* Sensor functionality

Instead of building these systems completely from scratch, you can add the required Brick to your App and configure it for your application.

#### In simple terms

**Apps are your projects. Bricks are the building blocks that add functionality to those projects.**

Once you understand this structure, you are ready to start building with the Arduino UNO Q.

#### 10. Reaching the Linux side over SSH

Later sections run commands on the board itself, such as the Edge Impulse runner in Section 8. From a terminal on the same network, connect with the board's IP address and the username and password you set in Step 3:

```bash theme={"system"}
ssh arduino@<ip-address>
```

Find the IP address in your router's list of connected devices.

## 6. The geophone: giving EleTect X a sense of the ground

A geophone is a sensor that converts ground vibration into a small electrical voltage, the same idea as a seismograph, but small and cheap enough to bury at a farm boundary.

**Why a geophone.** Section 3 has the full source. In short, Caitlin O'Connell-Rodwell's field research in Etosha National Park showed elephants themselves detect and orient toward alarm signals carried purely through ground vibration, picked up by specialised mechanoreceptors in their feet, at ranges well past what their airborne calls reach. If elephants sense danger through the ground, the ground is a good place to listen for them, so the geophone comes before the camera.

![SG10 10 Hz geophone](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/image49.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=45de87e124322f02f8515a17341501ad)

**The signal chain, as built.** The geophone's raw output is too weak to sample directly, so it first goes through an INA333 instrumentation amplifier, with three resistors on the front end to shape and protect that stage. The amplified signal then reaches an ADS1115 external ADC over I2C for digitization. The leads from the buried geophone to the enclosure are shielded, because an unshielded pair that long picks up noise like an antenna. The geophone ends up potted inside a sealed PVC capsule with a stainless steel spike, buried vertically, sealed back to the electronics through an M12 4-pin IP68 connector, but only after bench testing shows the sensor and its chain work.

![Geophone analog front-end schematic](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/schematics_final/geophone_afe.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=b122245f387b777e7353fcda169e7fc1)

**Testing it before it ever went in the ground.** Before burying the geophone, we bench-tested it. Each footstep of a person walking nearby showed up clearly as a spike in the STA/LTA ratio described below. Jumping next to it, a sharper and heavier hit, showed up just as clearly. Then we tried something much smaller: writing with a pen on a wooden table near the mount. It picked that up too. If a pen on a table registers clearly, an elephant or boar footstep, with far more mass and force behind it, should register at field distances too. The sensor has plenty of margin for an animal.

![Bench test: gentle touch on the ground](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/image30.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=abb0879ab144bd8ac04caeb73a00e3ce)

![Bench test: a short walk, then a stomp on the ground](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/image41.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=e40e7274d2255018a02ee75879b3c100)

![Bench test: continuous jumping next to the geophone](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/image10.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=0c380dc6c9819707b7ea02c72a151de1)

![Bench test: writing with a pen on a wooden table near the mount](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/image55.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=0000c2498831a589f46f603a371a288d)

After the bench test passed, the geophone went into its final form: potted inside the sealed PVC capsule described above, buried vertically about 400 mm deep, well clear of the main enclosure. The depth and orientation follow how the signal travels through the ground at these ranges.

**Reading it without ever blocking the reflex loop.** geophone\_service() polls the ADS1115 once per nominal sample period and writes into a ring buffer sized to exactly one detection window. It is timed by millis() rather than a hardware ready-bit because the ADS1115 runs in continuous-conversion mode with its ALERT/RDY pin unused, so there is no ready signal to poll in the first place, only a nominal conversion period to respect. A failed or timed-out I2C read does not crash or stall the loop. It skips that write and the next call tries again, and if the buffer goes stale for longer than a fixed window, geophone\_ok() flips false on its own so a dead sensor is reported, not silently zeroed:

[device/mcu/src/geophone.cpp](https://github.com/Abhinavkrishna3211/EleTect-X/blob/main/device/mcu/src/geophone.cpp#L119)

```cpp theme={"system"}
if (g_ok && (now_ms - g_last_fill_ms) > GEOPHONE_WINDOW_STALE_MS) {
    g_ok = false;
}
if (now_ms - g_last_poll_ms < (1000 / SEISMIC_SAMPLE_RATE_HZ)) {
    return;  // not time for the next sample yet, never blocks
}
```

**Deciding whether a window contains a footstep.** sta\_lta\_detect() (device/mcu/src/sta\_lta.cpp) takes the buffer of geophone samples and only does the maths on it, without touching the ADC or any pins itself. That means we can test it on a laptop with hand-made sample arrays, as well as on the board with live data. It slides a short-term-average window and a long-term-average window across the buffer (both use mean absolute value rather than RMS, so a test answer can be worked out by hand) and reports the highest short/long ratio it finds. An empty or all-zero window, which is what read\_seismic\_window() returns on a timeout, reports no trigger instead of dividing by zero:

![STA/LTA ratio equation](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/equations/sta_lta_ratio.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=1f4df5789d75118c75430201ac957cdc)

[device/mcu/src/sta\_lta.cpp](https://github.com/Abhinavkrishna3211/EleTect-X/blob/main/device/mcu/src/sta_lta.cpp#L46-L56)

```cpp theme={"system"}
const float ratio = (lta > 0.0f) ? (sta / lta) : 0.0f;
if (ratio > result.peak_ratio) {
    result.peak_ratio = ratio;
    ...
}
result.triggered = result.peak_ratio >= trigger_ratio;
```

**What runs on the board today.** footfall\_features.cpp is a stand-in for a trained model, calibrated on our own measurements: it turns the STA/LTA result into a saturating confidence score using the curve below, anchored against measurements this project has, a quiet-floor ratio of 1.03 to 1.13 mapping near zero and a bench stomp-test ratio of 4.60 mapping high, without letting that one trial become a hard ceiling, where x is the STA/LTA ratio above and c is the calibration constant those two measurements set:

![Saturating confidence equation](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/equations/saturating_confidence.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=3015f95d68cbecdcb6769cf07fbab377)

We did not use a cleaner exp() curve for a practical reason: `expf` needs `__errno` on this board's `libm_nano.a`, and this firmware's no-stdlib build provides none, so the exponential form does not link on the hardware at all. That same function also builds the eight-value feature vector, STA, LTA, peak ratio, trigger index, and four statistics over the raw window, that goes upstream.

The goal beyond that stand-in is a footfall classifier that can tell what kind of footstep is approaching, elephant, boar, or human, distinct from each other and from everything else that can shake the ground, straight from the seismic signature alone, without waiting on the camera to confirm anything. The human class matters most: a ranger or resident walking the boundary should never trigger the response meant for an elephant or boar. There is no such model yet, because there is no public labelled dataset of elephant and boar footfalls recorded in the field.

Our first plan was a round of field trials: walk elephants and boar (or the closest safe stand-ins) past a geophone and label the recordings. That is still the cleanest way and we have not dropped it, but it is slow. Arranging animals, handlers and field access takes far longer than the rest of the project, and the seismic channel would sit idle while we waited. So, in parallel, we use the two nodes already in the field. Each node logs its own raw footfall window whenever a seismic trigger fires and files it by what the camera confirms: a named species, two species at once, a watch the camera could not resolve, or no animal at all. The camera's confirmation becomes the label, and the geophone window from that moment becomes the training example. Triggers the camera could not resolve are kept separate. That way every label is backed by a photo of an animal, which matters because plenty of things that shake the ground are not elephants or boar. We want this to grow into a public dataset that others working on human-wildlife conflict can use. For now it is still a plan: neither path has produced a dataset yet.

So each node is also a research instrument. Months of camera-confirmed footfall from a real boundary could become the first field dataset of its kind, useful to us for a small on-device classifier and to anyone else who hits the same missing-dataset wall.

**How a footstep starts the vision check.** The reflex layer runs this whole chain, sampling, STA/LTA, the feature vector, entirely on the STM32U585. Only when a trigger crosses threshold does the reflex loop call Bridge.notify("report\_footfall\_event", ...), a fire-and-forget one-way call across the same Arduino\_RouterBridge link described in Section 4, which does not wait for a reply and cannot stall the sensing loop on a round trip to the Linux side. That one notify is how a footstep starts the vision check on the cognition layer, which opens the camera, polls the vision runner, runs fusion (Sections 7 to 10) and decides whether, and how hard, the horn and LEDs fire (Section 12).

> **Source files.** device/mcu/src/geophone.cpp, sta\_lta.cpp, and footfall\_features.cpp in the project repository.

## 7. Vision system: the camera and the infrared array

Section 6 covered how a footstep starts the vision check. This section is a build guide for what it looks at: an Arducam IMX462 day/night USB camera on the Qualcomm side, an infrared illuminator fired from the reflex side, a day/night decision that reads the scene itself rather than a clock, and an Edge Impulse vision model that turns a frame into "Elephant" or "Boar" with a confidence score. Follow the steps in order: wiring, then software, then calibration. Every number below was measured on our hardware.

![Camera with the 940 nm IR illuminator and LED wings in the enclosure](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/image65.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=0696ca41910448ae2eb1cff02b4b2836)

**What you need for this part.**

* Arducam IMX462 day/night USB camera.

* 940 nm IR illuminator board (this build uses a VISTORA 48-LED board, ASIN B0H2DQ9DVK, 300 mA).

* Logic-level MOSFET to switch the illuminator: either a bare IRLZ44N with a 220-330 Ω series gate resistor and a 10 kΩ pulldown from gate to source, or a pre-built low-side switch module like the LR7843 with both already built in. Check the module's own markings for which screw terminal is signal, ground, and load, they are not universal between brands.

* Multimeter, to check the supply voltage and fuse before anything is connected to the board.

No soldering required if you use a screw-terminal version of the switch module.

**Step 1: Power the illuminator from the fused battery bus.** Check the IR board's datasheet for its rated input range first, and confirm it covers the whole swing of the bus, 12.8 V nominal up to 14.6 V at absorption, before anything is connected. Then take the supply from the fused +BATBUS branch (a 1 A fuse, F407 on the power sheet in Section 14) to the board's positive input. The board's negative return does not go to ground directly; it goes to the MOSFET in Step 2. With the board still disconnected, put a multimeter on the fused branch and confirm it reads the bus voltage, and only then connect the board. Do not skip or rush this step.

**Step 2: Wire the illuminator's on/off switch.** Wire it as shown in the schematic below. The D7 pin on the board switches a MOSFET (an IRLZ44N, or a ready-made LR7843 switch module) that turns the IR board on and off. The schematic already includes the two small resistors the MOSFET needs, so just follow it.

![LED wing and IR illuminator MOSFET driver schematic](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/schematics_final/led_ir_drivers.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=b3ea36572f57256caa0bde9c050c81ac)

The right-hand block is the IR illuminator. The centre block is the LED wings covered in Section 12, and both get their power from the power sheet in Section 14.

**Step 3: Know the limits the firmware enforces, before you power anything on.** We chose 940 nm because the IMX462 can see it once its IR-cut filter swings out of the way. ir\_init() configures IR\_ILLUMINATOR\_PIN as a PWM output, off by default, and pulse\_ir() drives it through the same rule\_gate.h clamp-and-cooldown core the horn and LEDs already share (Section 4), so a runaway or repeated request can't overdrive it. Two limits matter here: a pulse is capped at 500 ms (IR\_PULSE\_MAX\_MS) because the illuminator board's MOSFET is sized for pulsed duty, not continuous, and pulses are held at least 5000 ms apart (IR\_MIN\_INTERVAL\_MS), which keeps duty cycle at or under 10% at the maximum pulse width, within the gate MOSFET's thermal limit:

[device/mcu/src/ir.cpp](https://github.com/Abhinavkrishna3211/EleTect-X/blob/main/device/mcu/src/ir.cpp#L45-L47)

```cpp theme={"system"}
analogWrite(IR_ILLUMINATOR_PIN, gain_to_duty(gate.gain_pct));
delay(gate.duration_ms);
analogWrite(IR_ILLUMINATOR_PIN, 0);
```

**Step 4: Run the pre-power-on checklist.** With everything from Steps 1 and 2 wired but not yet powered: confirm the fused branch voltage again with a multimeter, still with no load beyond the IR board itself; confirm any fuse and switch in this circuit sit in the positive leg only, with ground common and unfused; and confirm the MOSFET's gate pulldown is in place, an undriven, floating gate on a logic-level MOSFET can partially turn on unpredictably, and you will not see that problem until the board is powered.

**Step 5: Flash the firmware and fire a test pulse.** This project's MCU code lives where Arduino App Lab expects a sketch, so flashing it is the same one-click action App Lab uses for any app: open this project in App Lab (set up per Section 5 if you have not already), find FIRE\_TEST\_HARNESS in config.h inside the sketch folder and set it to 1, then click Run. App Lab compiles, flashes and starts the app in one step. Open the Serial Monitor tab in the console panel at the bottom of the editor: the board prints a menu of test commands over Serial at 115200 baud, "1=horn 2=led\_wing\_left 3=led\_wing\_right 4=ir", type 4 and press enter to fire the illuminator on demand (if that panel does not accept typed input on your App Lab version, any serial terminal connected at the same baud rate does the same job). Better still, point the camera at it: on our hardware a 500 ms pulse raised scene brightness by 99.5% over the same frame with the illuminator off. That is an easy, repeatable check that the wiring and firmware agree before you move on.

**Step 6: Plug in the camera.** The IMX462 is a standard UVC USB camera. Plug it into a USB-C powered hub, and connect the hub to the UNO Q's USB-C port. The hub gets its power from its own 5 V buck on the power sheet in Section 14, so the camera never draws from the board. No GPIO and no soldering: if the camera shows up as a V4L2 device, the wiring side of this step is done.

**Step 7: Bring the camera up in software.** perception/camera.py is a capture-only wrapper around the IMX462 over V4L2, built on OpenCV's cv2.VideoCapture with the V4L2 backend passed explicitly rather than auto-selected:

```python theme={"system"}
from perception.camera import Camera

with Camera() as cam:          # opens the device, applies format, warms up
    frame = cam.capture_frame()  # a Frame, or None on a failed grab
```

Request 1920x1080 in MJPG, not uncompressed YUYV: a 1080p-class UVC sensor will not sustain a useful frame rate over USB2 in an uncompressed format, the same bandwidth reasoning that shapes the event-recording pipeline further down this section. Every open() should discard a handful of warmup frames before trusting anything the camera reports, since UVC auto-exposure and auto-gain need a few frames to settle after stream start; this project discards 3 and retries up to 20 times with a 2 second backoff between attempts, because a brief USB dropout at the moment of opening (a hub renegotiating, a jostled connector) should not count as a hard failure on a node nobody is standing next to. A failed frame grab is reported as a failure: capture\_frame() returns None rather than a black filler image, on purpose, for the same reason read\_seismic\_window() in Section 6 never fakes a zero-filled sample, a black frame is visually indistinguishable from a genuine dark night-IR frame, so the rest of the system could not tell a fake one apart. If the camera stops delivering frames entirely mid-session, a USB brown-out or a hub power blip, reopen() releases and reopens the same device path in place, which recovers the node once the kernel re-enumerates it seconds later, without restarting the whole board.

One setting is easy to skip and expensive to miss: force-assert auto-exposure at the top of every open(), before warmup even starts. The exposure control lives on the physical device, not on any one process's file handle, so whatever the previous opener left it at is what the next opener inherits, and this rig once showed why: a bench characterisation session locked manual exposure for its own measurements and never reset it, and the camera was still sitting in that stale mode more than a day later, even after a reboot. Setting the known-good mode before warmup fixes this, whatever state the camera was left in.

![Arducam IMX462 day/night USB camera](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/image54.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=76a4ce724c4d7d430c13ecac891b938a)

**Step 8: Calibrate day from night for your own site, without a clock or a photocell.** The IMX462 swaps its own mechanical IR-cut filter in and out as the scene darkens. In daylight it sits in front of the sensor and blocks the near-IR the illuminator emits; when it is dark enough, it swings clear and the sensor becomes IR-sensitive. Nothing on the board reports the filter's position, but the swap shows in the frame itself: a mono, filter-out frame carries almost no colour, so its mean HSV saturation collapses to a handful of units, while any daylight frame, even a dull, overcast one, keeps chroma in the tens of units. Grab a few frames with the camera in place at your own site, one dark, one in ordinary daylight, and run them through frame\_mean\_saturation() to see where your own hardware and location land:

```python theme={"system"}
from perception.camera import Camera
from perception.night import frame_mean_saturation

with Camera() as cam:
    frame = cam.capture_frame()

print(frame_mean_saturation(frame.image))  # low at night, tens of units in daylight
```

Do this once after dark and once in daylight, then open services/config.py and set NIGHT\_SATURATION\_THRESHOLD to a number that sits between your two readings, closer to the middle than either edge. On the project's own rig, a night frame read a mean saturation of 0.0, a daylight frame read above 30, so the threshold that decides "night" for the rest of the system was set at 12.0, with margin on both sides. Because it reads the frame instead of a sunset table or a photocell, it stays correct in the awkward cases: heavy overcast at noon, a yard light near the lens at 3 a.m., the few minutes either side of the filter's own mechanical switch. It reads the same optical state that decides whether the illuminator would help.

**Why it keeps re-checking.** ExposureAutoLock re-evaluates day/night state every 30 seconds for as long as a session runs, and debounces three separate ways before it acts on a flip, it requires two consecutive agreeing readings before treating a change as real, so a single ambiguous frame right at the filter's mechanical transition can't flap the lock, and it holds off on a confirmed flip for 5 minutes after the last actual lock or restore call. Two traps we hit on this rig, if you build it yourself:

* Locking exposure once at camera open and never revisiting it means a scene whose lighting changes over the session, an indoor test under room lighting, or a dusk-to-dawn cycle, can stay locked at the wrong value for its whole duration. That is why ExposureAutoLock keeps re-checking instead of deciding once.

* A self-sustaining lock/restore cycle is possible without the 5-minute cooldown above: under a partially covered lens, locking to a fixed dark exposure can make the scene read dark enough to justify another lock, and restoring can make that same scene read bright enough to justify a restore, and neither of the other two debounces catches that on its own.

**A dawn blind spot.** Saturation-based gating has one weak spot: a mono, filter-out frame reads near-zero saturation no matter how bright the ambient light gets, so the classifier alone cannot see daybreak coming. In our field trial, this cost us footage at dawn: the system held "night" straight through sunrise while the frame's own median brightness climbed from a locked value around 138 to over 190, the exposure lock never released, and the resulting over-exposed frames drove a run of false Boar detections on foliage. The fix reads brightness, not just saturation: if the day/night classifier says night but the frame's own median brightness is at or above 175, the answer is forced to day before the debounce above ever sees it. That override can only release a lock, it can never impose one, so a scene that is dark but happens to read bright for some other reason only costs one extra interval on auto-exposure, never an unwanted lock.

**Cutting false positives by design.** A single spurious box on just one frame of a burst is the usual shape of a false alarm, so this system never lets one frame's detection stand in for the whole burst. Detections come back per-frame rather than flattened into one undifferentiated list, and Boar specifically has to appear on a strict majority of a burst's frames before it counts for anything. Measured against a two-hour board run, that per-frame majority gate holds the Boar false-positive rate well under what the system's raw single-frame rate starts from, and far under what a naive flatten-everything-together aggregation would produce on the same detections, since collapsing a burst's frames into one list amplifies noise rather than cancelling it. The majority requirement alone, before the debounce is even added, accounts for most of that improvement:

[device/mpu/services/config.py](https://github.com/Abhinavkrishna3211/EleTect-X/blob/main/device/mpu/services/config.py)

```python theme={"system"}

# Boar's problem is precision, not recall, so the majority gate is scoped to

# the class that actually has it. Elephant's measured recall (0.906) is

# already below the >=92% field-readiness bar, and majority-of-N trades

# recall for precision, the wrong direction when a missed elephant, not a

# false one, is the safety-relevant failure.

VISION_SPECIES_BURST_MAJORITY_LABELS: tuple[str, ...] = ("Boar",)
```

**Detecting an animal is one thing; keeping a record of it is another.** A model saying "Elephant" or "Boar" does not show what happened, so every qualifying encounter is also saved as one video, built from the JPEG burst frames the vision check already captures. Nothing extra runs on the camera. A separate on-board script, assemble\_encounters\_onboard.py, stitches each encounter's saved frames into an MP4 afterward using OpenCV's own bundled FFmpeg, no extra install needed. Alongside the video, a timestamped log records every detection and every moment the horn or LEDs fired, so the footage and the log can be read together.

We want to see how animals behave around the deterrent, one encounter at a time and over months, and to build a regional dataset of the animals that visit this boundary.

**What that gives us is the full arc of an encounter.** A 40-second pre-roll, held in a rolling ring buffer ahead of the first qualifying detection, means the clip already has the animal approaching before the model was confident enough to say anything, which is usually the most interesting part and would be lost without the buffer. The encounter stays open through a 45-second no-detection departure timeout, long enough to ride out an animal briefly walking behind a bush without splitting one visit into several false-ended ones, and once it does close, a further 20-second post-roll keeps recording so the clip shows the animal leaving rather than cutting on the last frame it was seen in. So one clip shows the whole visit: empty frame, the animal arriving, the detection and the deterrent firing, the animal leaving, and the empty frame again.

![How an encounter becomes one continuous recording](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/diagrams/encounter_capture2.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=c775fe5b218e32fc3378f1a04622976e)

Clips like these show how an animal approaches, how it reacts to a given tier and how it leaves, which is what we need to judge whether a tier works on real animals. Across many encounters, they also show habituation: whether a tier keeps working at the same spot or starts to fade, as Section 11 assumes it will. Each logged encounter is also a labelled field observation, the same kind of data the research in Section 3 is built on. We plan to release the archive as an open dataset for other researchers and conservation groups, like the footfall dataset in Section 6.

Field recorded video

[EleTect X field recorded video](https://www.youtube.com/embed/3Dm8IDxwZ88)

> **Source files.** device/mcu/src/ir.cpp, and in device/mpu/perception/, camera.py, night.py, detector.py, and video.py, and device/mpu/bench/camera\_check/assemble\_encounters\_onboard.py, in the project repository.

## 8. Edge Impulse, step by step: the vision model (ETX-V)

Section 7 covered how the trained detector runs on the board, as an edge-impulse-linux-runner HTTP endpoint the vision service calls. This section covers how we trained it: the Edge Impulse project (ETX-V), the dataset behind it, the dead ends hit getting there, and the unrounded numbers the shipped model clears.

**Creating the project.** Start a new project in Edge Impulse and name it whatever you like (ours is ETX-V). Then, on the project **Dashboard**, choose **Object Detection**.

![Creating the ETX-V project in Edge Impulse](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/image3.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=c051b3f6a1b2acf104c9f81aa371ba51)

**Four classes, sourced and licensed carefully.** Elephant, Boar, Fox, and Background, an explicit "nothing here" class, are the classes this model ships with (Fox was added after the first version, and is covered further down). Every image source carries its own license. Every class also includes frames from our own camera and from our field trials, on top of the public sources below:

| Class | Sources | Images | Boxes |
| :- | :- | -: | -: |
| Elephant | 5 public sources (Roboflow Universe elephant-detection-cxnt1 and asian-elephants-dataset, WCS Camera Traps' *Elephas maximus* subset, a relabelled night source, and a synthetic pseudo-IR derivative), plus our own camera and field-trial frames | 4,094 | 6,204 |
| Boar | 7 public sources (Roboflow Universe wild-boar-a1flm and wild-boar-deterrent-pzq5t, Roboflow 100's trail-camera, WCS Camera Traps' *Sus scrofa* subset, a relabelled night source, SWG's Eurasian wild pig subset, and a synthetic pseudo-IR derivative), plus our own camera and field-trial frames | 7,597 | 9,985 |
| Fox | 6 public sources (Roboflow Universe fox-sldyl, fox-xdf1l, fox-detection-7iqxq and animal\_redfox, a project-one wildlife monitoring set, and a far-infrared animals set), plus our own camera and field-trial frames | 2,782 | 2,858 |
| Background | 3 sources (SWG's confirmed-empty frames, plus our own board captures, daytime and IR night, and field-trial frames) | 2,631 | 0 |

Background has no boxes by design. Those counts are the curated source corpus. The live Studio project holds more once every own-capture and field-trial frame is added (18,666 images in total, split out in the table further down).

**Why a Background class.** A detector trained only on animals never learns what an empty scene looks like, so it will happily draw a box on an empty frame. Empty images with no boxes teach it that directly, and they had the biggest effect on the false-positive rate reported below. The own-camera frames in that table come from the same camera and UNO Q rig we deployed, shot on the workbench before it went out. We later added curated frames from an overnight field trial, shot in harder conditions. The result was mixed, as covered below.

**Auditing the data before trusting it.** A by-eye seeded sample of 144 Boar images found roughly 28% contamination: domestic pig rather than wild boar, warthog (the wrong species entirely), watermarked stock photography, hunting-trophy shots, zoo-enclosure backgrounds, and a handful of images carrying black redaction rectangles baked into the pixels by some prior export's own augmentation step. None of it showed on the source's listing page; we only found it by opening the images. We did this before the first training run, because dropping forty bad files from an upload list is cheap and retraining to find out why recall is stuck is not.

**Uploading and labeling.**

1. In the left sidebar, click **Data acquisition**.
2. Click the **Upload data** icon above the dataset table.
3. Select a folder of images. If the source already has boxes, add its COCO-format annotation file too.
4. Choose the split for the upload: **Training** or **Test**. We set the split ourselves so frames from one clip stay together (see the next step).
5. Open the **Labeling queue** tab for any images without boxes. Draw a box around each animal with the bounding-box tool (the crosshair icon on the sample viewer, on the right of the screenshot below) and give it its class.

**Splitting the data.**

* Keep about 80% for training and 20% for testing.
* Split by clip, not by image. Frames from the same clip look almost identical, so if one lands in training and another in testing, the test score is inflated.
* Group images by shared filename stem, then send each whole group to one side only.

![Uploading and labelling images in Data acquisition](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/image2.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=2de7309b1827ca332c4dfec6fc3b9e44)

**Pick the target.** In the top-right corner of Studio, choose **Arduino UNO Q** as the target device.

**Build the impulse.**

1. Click **Create impulse** in the sidebar.
2. In the **Image data** block, set the image width and height to **96** and **96**, and set Resize mode to **Squash**.
3. Click **Add a processing block** and choose **Image**.
4. Click **Add a learning block** and choose **Object detection**.
5. Click **Save impulse**.

![Create impulse: Image data, Image and Object detection blocks](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/image25.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=6c11080c3976cec655aeda110992f8c6)

**Choose and configure the model.**

1. In the sidebar, under Impulse design, click **Object detection**.
2. Click **Choose a different model** and pick **YOLO-Pro**.
3. Set the values below by hand. We kept them fixed so every run is comparable.

| Parameter | Value |
| :- | :- |
| Architecture variant | no\_attn\_relu |
| Model size | medium (16.6M params) |
| Epochs | 100 |
| Learning rate | 0.001 |
| Batch size | 16 |
| Pretrained weights | on |
| Freeze backbone | off |
| Spatial augmentation | low |
| Color-space augmentation | low |
| Auto class weights | on |
| INT8 quantization profiling | on |

Medium is the sweet spot. It gave the biggest recall jump over small, while large did not help (Boar recall dropped). At medium size, no\_attn\_relu gave better Elephant recall and fewer false positives than attn\_silu.

![Object detection training settings for the three-class model](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/image6.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=c2c9fe6dd8863769d58b7ca335784f7e)

**Train and read the per-class numbers.** A run at this size takes roughly an hour. Studio shows overall accuracy first; for this project the number to check is Elephant recall, because the system exists to never miss an elephant.

Clicking **Save & train** on the settings screen above kicks off the run; Studio's job log streams live underneath while it trains, and the Model panel shown below appears once it finishes:

![Model panel for the three-class, 96x96 model](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/image42.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=1953498ce22a2c367c503625cae97a50)

This is Studio's read-out for the three-class, 96x96 model. MAP\@50 (a standard detection score) is 0.73. Studio's on-device estimate for the int8 build is 519 ms; on the board it runs faster (measured below).

**Evaluating on the held-out split, then sweeping the threshold.** Model testing runs every image in the test split, which the model never saw in training. From its results we worked out precision, recall and F1 for each class. Those are the numbers to report; validation numbers from training usually run a little higher. The confidence threshold is a second lever on top of the trained weights: lower it and recall climbs while precision and the false-positive rate fall, raise it and the reverse happens. We re-scored the same trained model at several thresholds, with no retraining, and picked the deployed value on recall rather than accuracy, because a missed elephant costs far more than an extra alert:

| Threshold | Boar recall | Boar precision | Elephant recall | Elephant precision | Background false-positive rate |
| :- | -: | -: | -: | -: | -: |
| 0.05 | 0.852 | 0.875 | 0.906 | 0.872 | 0.166 |
| 0.10 | 0.827 | 0.923 | 0.893 | 0.908 | 0.106 |
| 0.15 | 0.815 | 0.944 | 0.881 | 0.922 | 0.079 |
| 0.20 | 0.806 | 0.961 | 0.875 | 0.936 | 0.064 |
| 0.25 | 0.790 | 0.967 | 0.867 | 0.944 | 0.052 |
| 0.30 | 0.779 | 0.973 | 0.856 | 0.955 | 0.041 |
| 0.40 | 0.755 | 0.982 | 0.834 | 0.972 | 0.031 |
| 0.50 | 0.724 | 0.989 | 0.806 | 0.981 | 0.024 |

0.05 looks very low, and it comes with a 16.6% false-positive rate on held-out data, but it is where both animal classes reach their best recall. We would rather send an extra alert than miss an elephant. The right threshold depends on which mistake costs more where you deploy; 0.05 is our choice for this boundary.

**Export the model for the board.** The UNO Q's Linux side runs the model as its own standalone program, so we export a Linux model file instead of an Arduino library or brick. That way the model is a separate file we can swap or retrain without rebuilding the app, and Section 7's runner service loads the same file every time.

1. Click **Deployment** in the sidebar.
2. Choose **Linux (AARCH64)** as the target.
3. Under Model optimizations, pick **Quantized (int8)**.
4. Click **Build**.
5. Optional: scan the **Run this model** QR code to test the model on a phone camera first.
6. On the board (over the SSH route in Section 5), download the model file:

```bash theme={"system"}
edge-impulse-linux-runner \
--force-target runner-linux-aarch64 \
--force-engine tflite \
--force-variant int8 \
--download etx_cpu.eim
```

![Studio's int8 and float32 estimates for the three-class model (the same for any deployment target)](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/image19.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=ca94618ba3648250e81c1b9577049e5f)

| Build | Latency (Studio estimate) | RAM | Flash |
| :- | :- | :- | :- |
| Quantized (int8) | 519 ms | 1.0M | 17.4M |
| Unoptimized (float32) | 403 ms | not shown | not shown |

int8 is slightly slower than float32 here because this board's CPU has no int8 acceleration, but it uses less memory, so int8 is what we ship. Both numbers are Studio estimates. The board is measured below.

**Measuring on the board.** `edge-impulse-linux-runner --run-http-server 1337` is the same standing endpoint Section 7's vision client calls into. Measured inference over 123 live classify cycles on the actual board came to 136 to 146 milliseconds per frame, a mean of 138 ms, roughly 5.7 frames per second end to end including camera capture and JPEG encoding, comfortably inside Studio's int8 estimates. We also tried Studio's GPU delegate export for the board's Adreno 702 GPU (currently in beta). It builds and links, but the board's stock OS image does not yet ship libtensorflowlite\_gpu\_delegate.so, so it cannot launch there yet. The CPU is fast enough on its own, so we shipped on CPU and left the GPU path as a follow-up.

![Live view from the vision runner on a deployed node](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/image63.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=c1757bdbce44345a6a3e8b9467aec849)

This frame is from the standing `--run-http-server` endpoint's live view, straight off the deployed camera in the field. The overlay (last poll age and current fire threshold) is our own instrumentation on the raw feed, and it shows the model polling live on the forest scene.

**Running it in the field.** In the field, the runner is a background service under systemd instead of a terminal session, so it stays loaded and survives reboots and brown-outs. The Python client from Section 7 polls it during each event, while the camera is open. An overnight field trial showed failures no test split could: a dawn burst of thousands of tiny, low-confidence boxes as the light changed, and a handful of saturated, near-full-frame false detections on an empty scene at very high confidence. A confidence floor, a requirement for two consecutive detections before an alert fires, and a reject rule for implausibly large boxes were added after the model to catch these. They are cheap and easy to undo, and they stop one bad frame from becoming a bad alert while we keep improving the detector.

**What the numbers say.** The model-capacity ladder that justified medium sizing, same corpus, same attention variant, threshold fixed at 0.5 so size is the only variable:

| Size | Boar recall | Elephant recall |
| :- | -: | -: |
| nano | 0.706 | 0.781 |
| small (6.9M params) | 0.730 | 0.787 |
| medium (16.6M params) | 0.770 | 0.812 |
| large (30M params) | 0.762 | 0.826 |

The six configurations we tried, at the deployed 0.05 threshold:

| Configuration | Boar recall | Elephant recall | Background false-positive rate |
| :- | -: | -: | :- |
| FOMO mobilenet\_v2\_a35, 96px, default threshold | 0.666 | 0.693 | not measured |
| YOLO-Pro-nano attn\_silu, first real corpus | 0.760 | 0.914 | 0.380 |
| + background top-up (656 to 2,424 negatives) | 0.764 | 0.918 | 0.179 |
| + decontamination and split-leak fix | 0.837 | 0.888 | 0.207 |
| + domain-matched Boar data, medium, attn\_silu | 0.863 | 0.880 | 0.173 |
| medium, no\_attn\_relu (shipped) | 0.852 | 0.906 | 0.166 |

The model that shipped is the last row above, YOLO-Pro medium with the no\_attn\_relu variant, at the deployed 0.05 threshold: 85.2% Boar recall and 90.6% Elephant recall, with a 16.6% Background false-positive rate: the best Elephant recall and false-positive rate of all our runs, at a small cost in Boar recall compared with one earlier setup.

**A fourth class: Fox.** We have a boar problem on our own small farmland, but a wild boar does not show up on a testing schedule. A fox visiting our property does. When the first fox walked in front of a deployed node (Section 17), the three-class model did not fire, because it had never seen a fox. So we added Fox as a fourth class, to test the full detect, confirm and deter sequence on a wild animal. Section 17 covers the field side; this section covers the retrained model.

**Add the class.** In the same ETX-V project, open **Data acquisition**, upload the Fox images, and draw a box and a **Fox** label on each one with the labeling tool.

![The Dataset tab after adding Fox: 18,666 items, split 78% / 22%.](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/ETX-V/etxv-fox-01-dataset-labeled-sample.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=acb578ed998bad730238fc969b6aebd5)

Retraining ran against the same project (ETX-V) and the same YOLO-Pro medium, no\_attn\_relu recipe, with input resolution raised from 96x96 to 160x160. The dataset grew to 14,278 training / 4,388 test images (18,666 total, split 78% / 22% as Studio reports it), with every new image split by filename group as before:

| Class | Train images | Test images | Train boxes | Test boxes |
| - | - | - | - | - |
| Fox | 2,335 | 601 | 2,487 | 626 |
| Boar | 5,592 | 1,586 | 8,071 | 2,236 |
| Elephant | 2,628 | 844 | 4,936 | 1,402 |
| Background (no box) | 3,723 | 1,357 | n/a | n/a |

Fox images come from six public sources (all CC BY 4.0, listed in `ml/vision/dataset_manifest.json`) plus frames from our own board. Frames from the same fox clips with no fox in them (370) and reviewed morning false-positive frames (362) went into Background.

**Reconfiguring the impulse for the larger input.** Raising the resolution meant reopening Create Impulse, not just starting a new training job: on the Image data block, image width and height both went from 96 to 160, resize mode stayed Squash for the same edge-of-frame reason given above, and Train on data subset stayed at 100%. On the Image processing block, colour depth stayed RGB rather than grayscale, for the same reason as before: a fox's reddish coat stands out against grey forest litter, and colour costs little at this size. The Object detection learning block's output updated itself to 3 output features (Boar, Elephant, Fox) the moment the third label existed in the dataset, with no manual step needed:

![Create impulse at 160x160 with Fox added](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/ETX-V/etxv-fox-03-create-impulse.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=c15830e8aca8998767d1d0eab3891e0d)

At 160x160 with 3 RGB channels the input block now feeds the network 76,800 raw features, about 2.8 times the 27,648 (96x96x3) of the three-class model. That jump, not the extra class, is why classification time went from about 138 ms to 374 ms on the board (see below).

![Image block output for a Fox sample](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/ETX-V/etxv-fox-04-image-dsp-block.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=1cbcc5ef42fe26a3f4276dbeb9faba22)

Studio's DSP result panel on a single Fox sample, shown above, is a quick sanity check: the preview shows the 160x160 RGB values (roughly 0 to 1) that reach the network, so you can confirm the input is right before spending an hour of GPU time.

**Generate features.** Open **Image** in the sidebar, then the **Generate features** tab, and click **Generate features** before training.

![The Generate features tab, with the Feature explorer on the right](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/ETX-V/etxv-fox-05-feature-explorer.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=d995a71cf532f3d90eb11a1ee6e8206c)

**Training settings.** Use the configuration below. The learning rate is lower than in the 96x96 run (0.0005 instead of 0.001):

![Training settings for the four-class model](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/ETX-V/etxv-fox-07-object-detection-settings.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=d9d341290cbbe184d2e5e05d365952a2)

Training processor GPU, 100 training cycles, learning rate 0.0005, model size medium (16.6M parameters), and Use pretrained weights checked. That last checkbox matters. YOLO-Pro medium comes pretrained on a large general detection dataset, so the retrain fine-tunes from those weights; 18,666 images would be nowhere near enough to train 16.6M parameters from scratch. Transfer learning is what let us add a fourth class in the time Section 17 describes.

With a fourth class in the mix, we swept the confidence threshold again: 0.05, 0.1, 0.2, 0.3, and 0.5, all re-scored against the same trained weights. The model still runs at 0.05, for the same recall reasons as before. On the board, the deterrent only fires when a detection also clears a second floor of 0.60. We chose it by replaying recorded field clips on the board: at 0.60 it caught all 7 fox visits and fired on none of the 47 false triggers.

| Threshold | Boar R / P / F1 | Elephant R / P / F1 | Fox R / P / F1 | Background FP |
| - | - | - | - | - |
| 0.05 | .895 / .920 / .842 | .920 / .890 / .872 | .761 / .902 / .753 | 11.6% |
| 0.10 | .882 / .939 / .832 | .913 / .915 / .869 | .740 / .917 / .733 | 8.6% |
| 0.20 | .863 / .960 / .815 | .900 / .938 / .857 | .704 / .939 / .694 | 5.5% |
| 0.30 | .846 / .978 / .799 | .886 / .955 / .844 | .675 / .948 / .666 | 3.8% |
| 0.50 | .811 / .988 / .767 | .850 / .974 / .814 | .608 / .973 / .590 | 2.4% |

Adding the fourth class and more data improved Elephant and Boar recall as well. The fair comparison is against a same-recipe retrain on today's corpus before Fox was added (Run R), not against the original three-class champion's own older test set, since that would be comparing two different held-out splits:

| | Run R (no Fox) | Retrained with Fox |
| - | - | - |
| Boar recall | 0.841 | 0.895 |
| Elephant recall | 0.885 | 0.920 |
| Background FP | 10.6% | 11.6% |

**Studio's own metrics.** Everything above comes from our own Model Testing sweep on the held-out split. Studio also reports its own validation metrics on the trained model directly, using a different metric family (mAP and COCO-style recall-by-detection-count, not the per-class Recall/Precision/F1 this section builds its own sweep from), so the two sets of numbers are not interchangeable:

![Model panel for the four-class, 160x160 model](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/ETX-V/etxv-fox-08-training-metrics.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=57242fe0e2dc15cf76583a3534995c2a)

MAP\@50 came out to 0.83 on the validation set, with mAP (averaged across IoU thresholds 0.50-0.95, the stricter COCO definition) at 0.54, and a Precision score (legacy metric) of 83.2%. In the area-based breakdown, `mAP@[area=small]` sits at just 0.24 against 0.78 for large boxes, so the model is much better with large boxes than with small, distant animals, which fits the resolution and camera-placement tradeoffs in Section 7. Studio's own on-device performance estimate for this build, shown at the bottom of that same panel, reads 1,235 ms inferencing time, 1.4M peak RAM, and 17.4M flash, using its EON Compiler (RAM optimized) engine. Do not confuse this with the 374 ms classification time below: this is Studio's estimate, while 374 ms is our measurement of the .eim running live on the board, so the two are not comparable.

**Deploy the four-class model.**

![Deploying the four-class model](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/ETX-V/etxv-fox-09-deployment.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=07499d9df3339062a6185d321dd98f1b)

Same steps as before: Deployment, Linux (AARCH64), Quantized (int8), Build.

| Build | Latency (Studio estimate) | RAM | Flash |
| :- | :- | :- | :- |
| Quantized (int8) | 1,221 ms | 1.4M | 17.4M |
| Unoptimized (float32) | 858 ms | not shown | not shown |

We ship int8: it is smaller, and the board is fast enough either way. Measured on the board, classification takes about 374 ms per frame, against about 138 ms for the three-class model. The board also runs warmer with the larger model, so it is listed in Section 19.

> **Source files.** ml/vision/README.md, ml/vision/dataset\_manifest.json, and ml/vision/fox-representation-audit.md in the project repository.

## 9. Edge Impulse, step by step: the acoustic model

This model listens through the BOYA microphone, which connects to the powered USB hub through an adapter, and tells four sounds apart: `gunshot`, `chainsaw`, `elephant_call` and `ambient` (background). It ships from Edge Impulse project ETX-A. If Studio's built-in audio blocks already fit your sounds, Step 2 may be all you need; the later steps show how to go further with custom blocks.

**Why we built custom blocks.** Our first impulse used Edge Impulse's standard audio path: an MFE block and a small classifier trained from scratch. Untuned, it scored 61.7% on our 605 test clips, with chainsaw recall at 8.8%. After tuning it reached about 82%, but chainsaw stayed the weak class. Two things pointed us to a pretrained model:

* **Long windows.** We tested windows from 3 to 10 seconds, and 10 seconds gave the best elephant-call recall. Edge Impulse's keyword-spotting transfer learning block is built for 1-second clips, so it did not suit sounds this long.
* **Limited data.** About 3,700 training clips is not much for a model learning from scratch. PANNs Cnn10 is an audio model pretrained on Google's AudioSet, which already includes chainsaws and gunshots, so it starts out knowing what these sounds are.

PANNs needs exactly the log-mel features it was trained on, so Edge Impulse's custom block support let us add two small blocks of our own: a processing block that produces those features, and a learning block that trains a small classifier on top of the pretrained PANNs Cnn10 model. The result is 92.6% accuracy on the same test clips, with chainsaw recall at 91.2%. Custom blocks need some extra work at export time (Steps 7 and 8).

**What you need**

* An Edge Impulse account and a project, plus a copy of this project's repository (`git clone https://github.com/Abhinavkrishna3211/EleTect-X`). Both custom blocks and the C++ port used below are in `ml/acoustic/ei_blocks/`.
* Python 3, Node.js and Docker, then `npm install -g edge-impulse-cli` (this installs `edge-impulse-blocks`).
* A Linux machine or WSL for the custom blocks and the export build.
* An Arduino UNO Q to run the result.

**Step 1: Collect and upload the audio**

1. Choose your target classes. Ours are `gunshot`, `chainsaw`, `elephant_call` and `ambient`.
2. Gather clips from open sources and record each clip's source, license and checksum in a manifest file.
3. Convert every clip to 8 kHz, the rate our microphone records at. Use a resampler that filters out high frequencies first, such as `scipy.signal.resample_poly(audio, 8000, original_rate)` in Python; simply dropping samples adds false low-frequency noise.
4. Cut or pad every clip to exactly 10 seconds.
5. Split the clips into training and testing yourself before uploading. The automatic split works clip by clip, so two 10-second clips cut from the same long recording can land on opposite sides. We kept every clip from one recording on the same side: 3,688 for training and 605 for testing. If each of your clips is a separate recording, the automatic split is fine.
6. In **Data acquisition**, click **Upload data**. Upload your training folder with the category set to **Training**, then your test folder with **Testing**, so the split stays exactly as you made it. For thousands of files, `edge-impulse-uploader --category training` (and `--category testing`) does the same from the command line.
7. Open **Data acquisition** and check the counts match your split (ours: 3,688 training and 605 test).

![ETX-A dataset: 3,688 training and 605 test clips](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/etxa/etxa-01-dataset.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=3ac4179cd6b8aabe88173de58f3d9f84)

**Step 2: Build the stock impulse as a baseline**

1. Click **Create impulse**.
2. Set the input to 8000 Hz audio with a 10,000 ms window and a 10,000 ms window increase, and check **Zero-pad data**.
3. Add an **MFE** processing block and a **Classification** learning block. In the MFE block, set Frame stride to 0.02 s: at the default 0.01 s, a 10-second window gives 998 frames, which is more than MFE accepts.
4. Train it, then open **Model testing**, click **Classify all**, and read the per-class numbers rather than the headline accuracy.

Three things we learned from this baseline:

| Test | Result |
| :- | :- |
| MFE vs MFCC | MFE won by more than 2 to 1. MFCC misread most gunshots as ambient. |
| Class weighting | Helped the weakest classes but cost elephant and gunshot double-digit recall, so we turned it off. |
| Window length (3, 4, 6, 8, 10 s) | 10 seconds won, mostly on elephant call. |

**Step 3: Set up the custom processing block**

1. Open the processing block from the repository and link it to your own account. Delete its `.ei-block-config` file first, because that file links the block to the account it was first pushed from:

```sh theme={"system"}
cd EleTect-X/ml/acoustic/ei_blocks/dsp-panns-logmel
rm .ei-block-config
edge-impulse-blocks init        # links the block to your own account
```

2. `dsp.py` already implements `generate_features()`. It reproduces the PANNs front end exactly, with these settings:

| Setting | Value |
| :- | :- |
| STFT | 1024-point Hann window |
| Hop length | 320 samples |
| Mel filters | 64 (Slaney-normalised) |
| Frequency range | 50 to 14,000 Hz |
| Output | log power, no floor clipping |

3. The block upsamples each window from 8 kHz to 32 kHz itself. PANNs defines its filterbank at 32 kHz, but the impulse input stays at 8 kHz; both numbers are correct.
4. If you change the block, run `parity_check.py` to compare it with the reference PANNs code on test clips. Ours matches to 0.0002 dB, against a tolerance of 0.01 dB.
5. Push the block. The first push asks you to log in, because a project API key is not accepted for pushing blocks:

```sh theme={"system"}
edge-impulse-blocks push
```

On a free account, the processing block runs on your own machine during training and testing. Before Step 5, start it with `edge-impulse-blocks runner` in the `dsp-panns-logmel` folder, and keep that terminal open and the machine awake until each job finishes. Enterprise accounts can host the block on Edge Impulse's servers.

**Step 4: Set up the custom learning block**

1. Do the same for the learning block, again deleting `.ei-block-config` first:

```sh theme={"system"}
cd ../learn-panns-cnn10
rm .ei-block-config
edge-impulse-blocks init
```

2. `train.py` freezes the pretrained PANNs Cnn10 model, computes an embedding for each window once, and trains a small two-layer head on top, oversampling the smaller classes. It exports one ONNX file holding both the backbone and the head. The pretrained Cnn10 weights are downloaded from Zenodo when the block's Docker image is built, so there is nothing extra to fetch.
3. The export uses `dynamo=False`. Keep it if you edit `train.py`: without it, recent PyTorch versions can ignore the requested opset and the file will not convert.
4. Optional: test it locally before pushing. This is the same command Studio runs, and it needs the features Studio generates for your project (`X_split_train.npy`, `Y_split_train.npy`, `X_split_test.npy` and `Y_split_test.npy`) in `./data`. You can skip this and let Studio run it when you train:

```sh theme={"system"}
python train.py --info-file info.json --data-directory ./data --out-directory ./out
```

5. Push it:

```sh theme={"system"}
edge-impulse-blocks push
```

**Step 5: Create the impulse in Studio**

1. Click **Create impulse**.
2. In **Time series data**, set Window size to 10,000 ms, Window increase to 10,000 ms and Frequency to 8000 Hz. Leave **Zero-pad data** checked.
3. Click **Add a processing block** and choose **PANNs log-mel** (the custom processing block you pushed in Step 3).
4. Click **Add a learning block** and choose **PANNs Cnn10 transfer** (the custom learning block from Step 4).
5. Check that Output features shows 4 classes, then click **Save impulse**.

![ETX-A impulse with the custom PANNs blocks](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/etxa/etxa-02-create-impulse.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=bc82895e7e49fbb42bde55c97de0c503)

6. Click **PANNs log-mel** in the sidebar. Check the parameters match Step 3 (64 mel filters, FFT length 1024, hop length 320, low frequency 50, high frequency 14000).

![PANNs log-mel block parameters](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/etxa/etxa-03-logmel-params.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=cc10686eaf34599fd4e3f583b1437885)

7. Open the **Generate features** tab and click **Generate features**. The number of training windows should match your training count (3,688 for us).

**Step 6: Train and read the results**

1. Click **PANNs Cnn10 transfer** in the sidebar.
2. Set the values below, then click **Save & train**.

| Setting | Value |
| :- | :- |
| Training processor | CPU |
| Epochs | 100 |
| Learning rate | 0.0008 |
| Backbone | cnn10 |
| Balance classes | on |
| Label smoothing | 0.1 |
| Random seed | 0 |

![PANNs Cnn10 transfer training settings](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/etxa/etxa-04-training-settings.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=7c0b94f6450fb1bc2c92a627cd202d3d)

3. Read the result panel. The 94.9% here is the validation score, measured on a slice of the training data; the number to report is the held-out test score in the next step.

![ETX-A training results](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/etxa/etxa-05-training-results.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=48156819b6fc70f01f263a0d38a0c70d)

4. Then open **Model testing** and click **Classify all** to score the model on the held-out test clips. Ours, on all 605:

| Class | Recall | Precision | Test clips |
| :- | -: | -: | -: |
| ambient | 92.8% | 92.8% | 236 |
| chainsaw | 91.2% | 89.9% | 68 |
| elephant\_call | 93.1% | 91.5% | 58 |
| gunshot | 92.6% | 93.4% | 243 |
| **Overall** | **92.6%** | | **605** |

This is the shipping configuration: impulse 19, deploy v7. Three notes on reading these numbers:

* The public Studio dashboard shows 87.8% because it applies a 0.6 confidence threshold by default; the table above uses no threshold, which gives 92.6%.
* Treat differences under about 1.5 points between runs as normal run-to-run variation.
* Studio's on-device estimate is designed for standard blocks, so for this custom-block impulse we measure latency on the board instead (Step 9).

**Step 7: Export the model**

**Why C++ library.** Studio offers several deployment targets. For a project with a custom block, the C++ library is the right fit:

| Target | Usable? | Why |
| :- | :- | :- |
| Arduino UNO Q, or Linux aarch64 (ready-made) | No | Ready-made builds run without Python on the device, so a custom Python block goes through the C++ library instead. |
| TensorFlow Lite | No | It carries the classifier; the custom log-mel block sits outside it. |
| **C++ library** | **Yes** | It exports everything as source code: the model, the settings, and an empty slot for the custom block's code. |

We keep the **EON Compiler** engine and the **Unoptimized (float32)** version, which is the build we register on the board. For this impulse the panel offers float32 only. Our `parameters.json` already sets `"cppType": "panns_logmel"`, so the export leaves an empty slot for the block's C++ code.

1. Click **Deployment** in the sidebar.
2. Choose **C++ library** as the target and **EON Compiler** as the engine.
3. Leave **Unoptimized (float32)** selected and click **Build**. Studio downloads the C++ library as a .zip.

![ETX-A deployment as a C++ library](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/etxa/etxa-06-deployment.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=810145f47e3a31937d51794b2b9dd6ae)

The panel's latency estimate covers the PANNs Cnn10 learning block only. The custom log-mel block, RAM and flash are left blank, so use the Step 9 measurement for the full figure.

4. Our C++ port fills that slot: `panns_logmel.cpp` and `panns_logmel_core.hpp` in `ml/acoustic/ei_blocks/dsp-panns-logmel/cpp/`. If you change the Python block, change the C++ to match and check it to the same tolerance as Step 3.
5. Clone Edge Impulse's `example-standalone-inferencing-linux` repository with Unix line endings (`git -c core.autocrlf=false -c core.eol=lf clone https://github.com/edgeimpulse/example-standalone-inferencing-linux`), unzip the export over it, and copy the `tensorflow-lite` folder at the top of that repository into `edge-impulse-sdk/`, where the Makefile looks for it.
6. Copy both C++ files into `source/` and add `CXXSOURCES += source/panns_logmel.cpp` to the Makefile.

**Step 8: Build for the board**

App Lab runs the model inside an Ubuntu 20.04 container on the board. A binary built on a current Linux runs on the board itself but fails inside that container, so build inside an Ubuntu 20.04 (Focal) environment too. You need a Linux machine (or WSL) with sudo.

1. Create the build environment once. This downloads a minimal Ubuntu 20.04 and installs the Arm cross-compiler inside it. The three `mount` lines need running again after a reboot:

```sh theme={"system"}
curl -fsSLO https://cdimage.ubuntu.com/ubuntu-base/releases/20.04/release/ubuntu-base-20.04.5-base-amd64.tar.gz
mkdir -p focal/rootfs
sudo tar xzf ubuntu-base-20.04.5-base-amd64.tar.gz -C focal/rootfs
sudo cp /etc/resolv.conf focal/rootfs/etc/
sudo mount -t proc proc focal/rootfs/proc
sudo mount --rbind /sys focal/rootfs/sys
sudo mount --rbind /dev focal/rootfs/dev
sudo chroot focal/rootfs apt-get update
sudo chroot focal/rootfs apt-get install -y --no-install-recommends crossbuild-essential-arm64 make
```

2. Mount the build folder from Step 7 at `/build` inside it, then build:

```sh theme={"system"}
sudo mkdir -p focal/rootfs/build
sudo mount --bind <your-build-folder> focal/rootfs/build
sudo chroot focal/rootfs /bin/bash -c 'cd /build && make clean && \
    APP_EIM=1 USE_FULL_TFLITE=1 TARGET_LINUX_AARCH64=1 \
    CC=aarch64-linux-gnu-gcc CXX=aarch64-linux-gnu-g++ make -j"$(nproc)"'
```

3. The build writes `build/model.eim`. It is an Arm binary, so copy it to the board (for example with `scp`, using the SSH login from Section 5) and check it describes itself correctly there:

```sh theme={"system"}
./model.eim --print-info
# 8000 Hz, 80000 features, 4 labels, project 1110036, impulse 19

```

4. Still on the board, check it against an Ubuntu 20.04 container, the same base the brick runs in, rather than the board's own system:

```sh theme={"system"}
docker run --rm -v "$PWD:$PWD" ubuntu:20.04 ldd "$PWD/model.eim"
```

5. When we moved to this toolchain, we ran the same 16 test clips through our earlier build and this one. Both gave identical predictions and identical confidence, so the 92.6% figure carries over.

**Step 9: Put it on the UNO Q and measure**

1. On the board, make sure `model.eim` is executable (`chmod +x model.eim`).
2. Create a folder named `/home/arduino/.arduino-bricks/models/<model-id>/` and put `model.eim` in it. We use `etx-acoustic-panns-20260930`; the folder name must match the `id` in `model.yaml`.
3. Add a `model.yaml` next to it. Keep the whole `metadata` block: with `source: "edgeimpulse"`, the board expects every `ei-` field to be filled in, and `ei-model-type` must be `float32`.

```yaml theme={"system"}
id: "etx-acoustic-panns-20260930"
name: "EleTect-X acoustic (PANNs Cnn10)"
description: "Four-class forest audio classifier: ambient, chainsaw, elephant_call, gunshot."
runner: "brick"
bricks:
  - id: "arduino:audio_classification"
    model_configuration:
      CUSTOM_MODEL_PATH: "/home/arduino/.arduino-bricks/models/etx-acoustic-panns-20260930"
      EI_AUDIO_CLASSIFICATION_MODEL: "/home/arduino/.arduino-bricks/models/etx-acoustic-panns-20260930/model.eim"
metadata:
  source: "edgeimpulse"
  ei-project-id: "1110036"
  ei-impulse-id: "19"
  ei-impulse-name: "Impulse #19"
  ei-deployment-version: "7"
  ei-model-type: "float32"
  ei-engine: "tflite"
```

4. Confirm the board sees it:

```sh theme={"system"}
arduino-app-cli model list --format json
```

5. In App Lab, open the audio classification brick's **Brick configuration** and pick this model. Registering it only makes it available. It does not make it the one the brick loads.

Measured on the board while the rest of the application was running, one 10-second window takes 3.9 to 4.3 seconds. That is a real-time factor of about 0.4. In the field build the acoustic model runs on its own 30-second cycle, recording about 15 seconds of every 30, independently of the geophone.

| | Per 10 s window |
| :- | :- |
| Total | 3,915 to 4,310 ms |
| Classifier | 3,491 to 3,647 ms (84%) |
| Processing block | 15 to 16% |

An int8 version of the same graph shrank from 21.4 MB to 7.4 MB for a 0.17-point accuracy cost on the same 605 clips. That was measured with a local ONNX runtime, not an int8 Edge Impulse build on the board, because the deployment panel offers float32 only for this impulse (see Step 7). A naive whole-graph int8 conversion scored 15.4% with zero gunshot recall, so the quantization recipe matters.

> **Source files.** `ml/acoustic/README.md` (the full evidence record), `ml/acoustic/TUTORIAL.md` (the complete version of this walkthrough, including the exact shell commands), and `ml/acoustic/harness/split.json` (the frozen 4,293-clip split) in the project repository.

## 10. The fusion math

The sensors that have something to say about an event are combined with the weighted log-odds update below. It is a plain formula, and every term traces back to a sensor reading:

![Each available sensor's log-odds, relative to its own baseline, is summed into one value; the sigmoid turns that sum back into the probability that services/reflex\_loop.py and the bandit (Section 11) use.](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/diagrams/fusion_arch.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=985b80d7949ed70272bd49a92595b607)

![Log-odds fusion equation](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/equations/fusion_logodds.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=1493ef18526b335a021aa266f750a344)

![Sigmoid equation](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/equations/sigmoid.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=61f1ad3cb66c07cf6ded7b45b8959395)

L\_prior is the fused log-odds with no evidence at all. Each modality i (seismic, acoustic, vision) contributes wᵢ (ℓᵢ − ℓ₀ᵢ), its own log-odds reading ℓᵢ, relative to its own baseline ℓ₀ᵢ, scaled by a per-modality weight, but only if aᵢ (availability) is true. P = σ(L) turns the fused log-odds back into a probability via the logistic sigmoid.

![The curve is the same sigmoid from the formula above, plotted to show its shape: log-odds near zero swing probability fast, while further out the curve flattens and an extra unit of evidence buys less and less additional confidence.](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/diagrams/sigmoid_plot.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=d68ff4a58303cf7c4f6e2c72ce5a721f)

device/mpu/cognition/fusion.py is the implementation. It is a pure function, with no ADC calls, no Bridge RPC, no SQLite, no logging inside the function body:

[device/mpu/cognition/fusion.py](https://github.com/Abhinavkrishna3211/EleTect-X/blob/main/device/mpu/cognition/fusion.py)

```python theme={"system"}

def fuse(readings: list[ModalityReading], params: FusionParams) -> FusionResult:
    log_odds = params.l_prior
    contributions: dict[Modality, float] = {}
    used: list[Modality] = []
    dropped: list[Modality] = []
    for reading in readings:
        if not reading.available:
            dropped.append(reading.modality)
            continue
        weight = params.weights[reading.modality]
        baseline = params.baselines[reading.modality]
        contribution = weight * (reading.log_odds - baseline)
        contributions[reading.modality] = contribution
        log_odds += contribution
        used.append(reading.modality)
    return FusionResult(
        log_odds=log_odds,
        probability=sigmoid(log_odds),
        contributions=contributions,
        used=tuple(used),
        dropped=tuple(dropped),
    )
```

Two design choices were deliberate:

* **A dropped modality contributes no term at all, never a term equal to zero.** Zero log-odds is itself a legitimate reading a sensor can report (perfectly ambiguous evidence). Encoding "this sensor had nothing to say" as available=False instead of log\_odds=0.0 keeps those two cases from being silently confused, and FusionResult.contributions only carries a key for modalities that fired, checking key membership, not value, is how a caller tells "dropped" from "contributed exactly zero."

* **Dropout is not renormalised.** Losing the vision term when it's too dark for the camera does not redistribute vision's weight onto seismic and acoustic. That would silently inflate confidence in whatever data happens to still be available, which is the wrong thing to do for a system that fires a horn next to a public road.

Every function is unit-tested against known inputs (device/mpu/tests/test\_fusion.py), including the unavailable-vs-genuine-zero case above. The fused probability P is used downstream: services/reflex\_loop.py calls this to decide whether an event opens, and cognition/bandit.py (Section 11) picks a deterrence tier once it does. On the deployed nodes, all three modalities (seismic, acoustic and vision) feed fuse().

## 11. The anti-habituation engine

A fixed siren or strobe stops working on elephants because they are intelligent and learn fast. The deterrence studies in the Sources list all name habituation as the main way simple deterrents fail. The fix here is a **contextual bandit**, device/mpu/cognition/bandit.py, run through the same four-step cycle every event: **sense** (fusion decides an event is real) → **decide** (the bandit picks a tier) → **act** (drive\_horn/drive\_led/pulse\_ir fire over Bridge RPC) → **learn** (the outcome updates that tier's stored value for next time).

![The same cycle named above, with the function that does each step. Learn feeds back into Sense for the next encounter at the same location, not the same run of the program, the stored value it updates is what select\_tier() reads the next time this node sees a repeat in that bucket.](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/diagrams/bandit_cycle.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=239802f387f25eb266a97402fc711ad4)

**Each species learns its own response ladder.** One node sees more than one kind of animal. If every visit fed a single shared ladder, a night of boar or fox visits would push the response up to tier 3, and an elephant arriving at dawn would meet full gain before anything had deterred it. A separate node per species at each site would avoid that, but it is not practical: the sites with elephants also have boar and fox, and each site has one node. So the bandit keeps a separate ladder for each species (ADR 0034), as described below.

**Deciding what "context" means.** We kept context simple: it is how many times this node has been triggered recently, within one shared window. Nothing in our data yet justifies anything richer.

[device/mpu/cognition/bandit.py](https://github.com/Abhinavkrishna3211/EleTect-X/blob/main/device/mpu/cognition/bandit.py#L138-L171)

```python theme={"system"}

def habituation_context(repeat_count: int, bucket_count: int) -> int:
    return min(max(repeat_count, 0), bucket_count - 1)
```

With this project's bucket\_count of 3, that function saturates like this:

| repeat\_count (this node, recent window) | habituation\_context() bucket |
| :-: | :-: |
| 0 (first trigger) | 0 |
| 1 | 1 |
| 2 | 2 |
| 3 | 2 (saturated) |
| 10 | 2 (saturated) |

"What worked on a first trigger" and "what worked on a third trigger in ten minutes" are learned separately instead of being blurred into one number. The top bucket saturates, so a 4th, 5th and 20th repeat share one context instead of spreading the data over cells no field trial could fill.

**Escalation is a hard rule, not something the bandit has to discover:**

```python theme={"system"}
def escalation_floor(context: int, params: BanditParams) -> Tier:
    floors = params.tier_floor_by_context
    return floors[min(max(context, 0), len(floors) - 1)]
```

With this project's checked-in `tier_floor_by_context`, the floor per bucket is Tier 1 on a first trigger, Tier 2 on a second, and Tier 3 on a third or later. This was not always true in the tree: a one-night field test pinned every context to Tier 3, and that override lived in committed source for three weeks before it was found and moved to an environment variable (`ELETECT_TIER_FLOOR`), where a field test can still ask for it without it silently becoming the shipped default again. An animal that comes back within minutes was clearly not deterred by what just fired. Waiting for epsilon-greedy exploration to stumble onto a stronger response would repeat an already-ineffective one an unbounded number of times first, so the floor only ever raises the minimum tier as repeats stack up, and de-escalation happens naturally as the repeat count ages out of the habituation window, never by a separate decay rule.

**The floor is partitioned per species; how hard the node watches is not.** The repeat count is kept two ways, for two purposes. How long the node keeps the camera watching after a trigger uses a species-blind count, because looking longer costs little and a node that has seen a lot of activity should watch harder regardless of what caused it. The escalation floor above, the thing that fires a horn, uses a **species-scoped** repeat count instead, so a night of fox visits can only ever walk the fox ladder, never the elephant one. Underneath, `action_values` is keyed by `(species, context, tier)`, not just `(context, tier)`, and the experience store hands `select_tier()` below a plain per-species slice of that table, so the bandit's own selection logic does not need to know species exist at all.

That partition only works if the species is known at the right moment, and there is a catch: the footfall trigger that starts the clock arrives up to 45 seconds before the camera confirms what caused it. The experience store handles this with two-phase attribution rather than waiting: every trigger is recorded immediately under a placeholder species, UNATTRIBUTED, and is only renamed once the vision watch resolves. A trigger that is never confirmed, wind, cattle, a branch falling, stays UNATTRIBUTED, which is the correct outcome for a node woken by something it could not identify.

**Tier selection itself is epsilon-greedy, with one deliberate tie-break:**

```python theme={"system"}
def select_tier(context, action_values, params, rng, floor=Tier.TIER_1):
    candidates = [tier for tier in Tier if tier >= floor]
    if rng.random() < params.epsilon:
        return rng.choice(candidates), True
    best = candidates[0]
    best_value = action_values.get((context, best), 0.0)
    for tier in candidates[1:]:
        value = action_values.get((context, tier), 0.0)
        if value > best_value:
            best, best_value = tier, value
    return best, False
```

On a cold experience store every tier ties at 0.0, and ties resolve to the **lowest** tier, on purpose, so an untrained node starts with its gentlest response.

**Learning uses a constant step size, not a running average, because habituation is non-stationary by definition:**

```python theme={"system"}
def updated_value(old_value: float, reward: float, step_size: float) -> float:
    return old_value + step_size * (reward - old_value)
```

A sample average keeps weighting the first few events forever; a constant alpha keeps an exponentially-decaying window on recent experience instead, which reacts exactly when an animal's response to a stimulus is changing.

**Each species gets its own policy.** A night of foxes or boar cannot touch the elephant ladder. Fox borrows Boar's horn tracks and LED patterns rather than inventing its own: they were chosen for a mid-sized mammal, and there is no fox-specific evidence to choose differently.

## 12. Deterrents: the horn and the LEDs

Two LED wings (D3 left, D6 right, mixed cool-white and royal-blue \~450 nm) and the horn chain (STM32 → DFPlayer PRO → TPA3116D2 amplifier BTL → Ahuja SUH-15, 8 Ω) both escalate together through three content tiers, ordered by the deterrence literature's own effectiveness numbers, mildest first:

| Tier | Content | Source | Evidence |
| :- | :- | :- | :- |
| 1 (mildest) | Disturbed honeybee swarm | Freesound 788025, CC0 | King, Douglas-Hamilton & Vollrath 2007, *Current Biology*: a significant majority of 18 elephant family groups fled the playback |
| 2 | Lion roar/growl | Freesound 212764, CC-BY 3.0 | Thuppil & Coss 2016, *Oryx*: 72.7-83.3% raid-attempt deterrence |
| 3 (full response) | Tiger roar/growl | Freesound 149190, CC-BY 4.0 | Thuppil & Coss 2016: 90-100% raid-attempt deterrence, the best number in the reviewed literature |

We are also field-testing other curated sounds. There are many possible combinations of sound and LED pattern across the tiers, so the table above is the starting set, not the only one.

**Why blue and white.** Elephants are reported to be dichromats: they have two types of colour receptor, one most sensitive to blue-violet light and one to yellow-green, so they see blues well and reds poorly. Royal blue (\~450 nm) sits in the range they see best, and cool-white adds broad brightness. We chose the mix because the animal can see it, not from a measured elephant-response result.

**The fire sequence** (device/mcu/src/horn.cpp), amp held in shutdown while every AT command goes out so neither the DFPlayer's command latency nor the TPA3116's own soft-start reaches the horn as a pop:

[device/mcu/src/horn.cpp](https://github.com/Abhinavkrishna3211/EleTect-X/blob/main/device/mcu/src/horn.cpp)

```cpp theme={"system"}
digitalWrite(HORN_AMP_ENABLE_PIN, LOW); // amp stays in shutdown
dfplayer_apply_playback_config(cmd, sizeof(cmd)); // AT+PLAYMODE, AT+PROMPT - resent every fire
dfplayer_send("AT+PLAYNUM=<track_id>"); // select + start the tier's track
dfplayer_send("AT+VOL=<n>"); // absolute volume for this tier
delay(HORN_AMP_ENABLE_DELAY_MS); // AT processing + track seek
digitalWrite(HORN_AMP_ENABLE_PIN, HIGH); // amp on - audio already flowing, no pop
delay(duration_ms);
digitalWrite(HORN_AMP_ENABLE_PIN, LOW);
```

This sequence came out of bugs we found and fixed: AT+PLAYMODE/AT+PROMPT were originally sent once at boot on the assumption the module would always be settled by the time an event fired. A bench harness fire landing seconds after a fresh reflash broke that assumption, the DFPlayer missed the send, dfplayer\_send() has no ack check to catch it, and the wrong play mode stayed latched for the rest of the session (clips auto-advancing into each other instead of playing one and stopping). Now every command is resent on every single fire. A second trial moved the amp-enable line ahead of the AT commands, on the theory that the amp's own power-up sweep should land on silence instead of the track's onset, that produced a worse failure, a live switching amplifier turned out to be a plausible noise source onto the DFPlayer's own UART RX, and AT+PLAYNUM was dropped outright with no visible error. Reverted: an audible sweep on every fire (still unsolved, logged in docs/KNOWN\_GAPS.md) beats a horn that sometimes plays nothing. The DFPlayer link itself also moved during bring-up, originally planned as a bit-banged software UART on D9/D10, which turned out to be impossible on this part, and a second D20/D21 candidate was ruled out (I2C2-only on the official pinout, no UART function at all) before landing on the board's one hardware UART, USART1 on D0/D1.

![DFPlayer PRO, horn amplifier and shared UART schematic](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/schematics_final/dfplayer_horn_uart.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=8229824a3733bfe39157ee60849ad678)

The right-hand block above is the horn chain this section describes: the DFPlayer PRO's DACL output feeds the XH-M543 (TPA3116D2) amp's INL input directly, not through the module's own L+/L- speaker-level pins, and D11 gates the amp's ground return through an IRLZ44N so the amp is fully powered down, not just muted, until a fire needs it, the same hold-in-shutdown-until-ready sequence the code above implements. A 3 A fuse, a TVS diode, and a bulk capacitor protect the amp's raw 12.8 V battery-bus supply, which runs independently of the 5 V the DFPlayer PRO and LoRa-E5 take off the UNO Q. The centre block, the 74HC4053 UART mux shared with the LoRa-E5, is Section 13's circuit.

The LEDs (device/mcu/src/led.cpp) drive many flash pattern and brightness combinations, from steady light to pulsing, strobing and random flicker, entirely as on/off timing inside drive\_led()'s existing blocking window, so pattern choice adds zero new blocking cost; every pattern's on/off spans sum to exactly the resolved duration\_ms, confirmed by direct on-hardware timing measurement (burst duration + \~15 ms regardless of pattern). Each tier on the ladder (cognition/config.py) picks its own wing, pattern, and brightness, the ladder gets louder and busier as escalation continues.

![LED wing and IR illuminator MOSFET driver schematic](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/schematics_final/led_ir_drivers.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=b3ea36572f57256caa0bde9c050c81ac)

The centre block above is the LED driver this section describes: D3 (WING\_L) and D6 (WING\_R) each gate an IRLZ44N low-side switch, 270 Ω on the gate to limit inrush and a 10 kΩ pulldown to hold it off at boot. Each wing is a set of parallel strings of two LEDs in series (6.6 V at 3.3 V forward voltage) fed from the 8 V LED buck on the power sheet, with a 2 Ω 2 W resistor per string setting roughly 700 mA, three strings on the left wing, two on the right. The right-hand block is the IR illuminator switch Section 7 covers in detail.

## 13. LoRa E5: alerts, and the board's one shared UART

Nodes are meant to coordinate over a LoRaWAN star network on India's legal **IN865** band, 868 MHz is not legal to transmit on in India, which is easy to miss if you copy a European reference design. device/mcu/src/mac.cpp implements the OTAA join sequence as an explicit state machine:

[device/mcu/src/mac.cpp](https://github.com/Abhinavkrishna3211/EleTect-X/blob/main/device/mcu/src/mac.cpp)

```cpp theme={"system"}
// non-blocking OTAA join, no delay() anywhere in the sequence
case lora_join_state::kJoining:
    if (poll_line() && rx_contains("+JOIN: Done")) {
        g_state = lora_join_state::kJoined;
    } else if (poll_line() && rx_contains("+JOIN: Join failed")) {
        enter_failed_or_retry(lora_join_state::kSettingMode, now_ms);
    } else if ((now_ms - g_step_start_ms) > LORA_JOIN_TIMEOUT_MS) {
        enter_failed_or_retry(lora_join_state::kSettingMode, now_ms);
    }
    break;
```

Every step (AT, AT+MODE=LWOTAA, AT+DR=IN865, AT+ID=AppEui, AT+KEY=APPKEY, AT+JOIN) is non-blocking, timed, and retried with backoff up to a bounded retry budget before the whole sequence waits out a cooldown and tries again from the top, so a brief gateway problem never leaves the node stuck for good. The AppKey is loaded from a gitignored secrets.h and is never logged, even at the AT-command level.

**Sharing the one UART with a mux.** The STM32U585 exposes exactly one hardware UART, and the horn chain (Section 12) needs it for the DFPlayer's AT-command link. AUDIO\_TRIGGER\_PIN 's old GPIO-pulse fallback could only ever play one fixed track at one fixed volume, not the tier ladder's two independently controlled axes, so falling back to it instead of sharing the UART was never an option. The fix is a UART multiplexer, switched by LORA\_ENABLED in config.h, that routes the single hardware UART to either the DFPlayer or the LoRa-E5 on demand, so the two devices take turns on the same UART.

![Grove LoRa-E5 module](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/image46.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=df882756816eb96d383dd4951c92b06e)

![DFPlayer PRO, horn amplifier and shared UART schematic](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/schematics_final/dfplayer_horn_uart.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=8229824a3733bfe39157ee60849ad678)

The centre block above is the shared-UART mux just described: a 74HC4053 switches USART1 (D0/D1) between the DFPlayer PRO and the LoRa-E5 on D4's select line, R5 pulling D4 low at reset so the DFPlayer is the default rather than the radio, with 10 kΩ pull-ups holding the deselected module's RX line idle high and 1 kΩ series resistors limiting clamp current if either module's TX swings above 3.3 V. The right-hand block, the DFPlayer-to-horn audio chain, is Section 12's circuit.

**Getting a gateway and ChirpStack talking to each other, step by step.** Everything above is the node's side of the radio link: it gets a frame onto the air. To get that frame into Supabase, which feeds our web app, you need a LoRaWAN gateway and a network server in between. We use a SenseCAP M2 gateway. It is sold as regional SKUs (EU868, US915, AU915, AS923) with no separate IN865 SKU, but the EU868 unit offers an IN865 channel plan, as Step 3 shows. Here is the full bring-up:

![SenseCAP M2 LoRaWAN gateway](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/image66.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=87f9f3b5d502150205093396583a5d5f)

**Step 1: log into the gateway's own console.** Power it on, join its setup Wi-Fi hotspot or reach it over Ethernet, and browse to its local IP. It asks for the credentials printed on the unit's own label, not a fixed default:

![SenseCAP M2 console login](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/chirpstack2/01_sensecap_login.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=2b2464d1c7f6872b4e457e4755b43a05)

**Step 2: confirm what you have before changing anything.** The Status page names the exact model and the gateway's own EUI, worth reading before touching a setting, because this unit is labelled `M2-EU868-4G` on its own dashboard, the EU868 SKU:

![SenseCAP M2 status page](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/chirpstack2/02_sensecap_status.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=ecbd773bf2f576fa1f6dc2948ff6affe)

**Step 3: select the IN865 channel plan.** `LoRa` → `Channel Plan`, and pick IN865-867 from the list:

![Selecting the IN865 channel plan](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/chirpstack2/03_sensecap_channel_plan.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=b4f4826babf11f926a897aefb49f641b)

**Step 4: point the gateway's packet forwarder at your ChirpStack host.** `LoRa` → `LoRa Network`, Mode set to **Packet Forwarder**, deliberately not the gateway's own `SenseCAP` mode and not `Local Network Server`, both of which run a different stack than the external ChirpStack server this project's architecture calls for. The Gateway EUI auto-fills; Server Address is the LAN IP or hostname of the machine running ChirpStack, ports 1700 up and down (the standard Semtech UDP packet-forwarder port):

![Packet forwarder settings](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/chirpstack2/04_sensecap_packet_forwarder.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=e45e3732253e04524dd3d1e5cf340e92)

**Step 5: stand up ChirpStack itself.** `web/chirpstack/` in the repo is a trimmed, hardened copy of the official `chirpstack-docker` stack (MIT-licensed, attributed in `LICENSE.chirpstack-docker`), only the `in865` region files are carried, not all forty ChirpStack ships. On a machine with Docker and Compose v2:

```bash theme={"system"}
cd web/chirpstack
cp .env.example .env
# fill in CHIRPSTACK_API_SECRET and POSTGRES_PASSWORD - .env.example

# says how to generate each

docker compose up -d
```

First start pulls images and initialises the database, so give it a minute; `docker compose ps` should show every service `running`. Open `http://localhost:8080` and sign in with `admin`/`admin`, the upstream default, and change it immediately, since that account can read every uplink the stack ever receives. We changed ours; `admin`/`admin` no longer authenticates against it, confirmed directly.

**Step 6: register the gateway.** `Gateways` → `Add gateway`, the gateway's own EUI from Step 2 or 4:

![ChirpStack Gateways page](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/chirpstack2/05_chirpstack_gateways_empty.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=3120d825990c6716dec3bea45b21bc38)

One gotcha: ChirpStack 4 defaults the Downlink priority field to `0` but then rejects it on submit with `Validation error: downlink_priority must be > 0`. Set it to at least `1` before submitting:

![The Downlink priority validation error](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/chirpstack2/06_chirpstack_add_gateway_error.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=ca06cad9cc0213558772ae206fb67d22)

![Gateway registered in ChirpStack](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/chirpstack2/07_chirpstack_gateway_created.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=5ed6a2281318ac7968784a268db582a6)

**Step 7: add a device profile for the node.** Region IN865, **MAC version: LoRaWAN 1.0.3**, **Regional parameters revision: A**, OTAA turned on. The description field records the intent: this node ships a status uplink on FPort 10 every ten minutes, with **no payload codec configured on purpose**, because `web/ingest` (Section 18) decodes the raw frame bytes itself per ADR 0031 rather than asking ChirpStack to do it twice:

![Device profile for the node](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/chirpstack2/08_chirpstack_device_profile.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=239dbd86a349843b72e10204e54d313d)

**Step 8: create an application, then add the device.** An application is just a grouping, name it anything:

![Creating the application](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/chirpstack2/09_chirpstack_application.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=d9e7a714455a2e1177540c4e6c4a2cd7)

Then **Devices** → **Add device**, the node's Device EUI (from `device/mcu/src/secrets.h`, which is gitignored, see `secrets.h.example` for the shape) and the device profile from Step 7. Join EUI stays all-zeros unless the node's own firmware sets one:

![Adding the node as a device](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/chirpstack2/10_chirpstack_add_device.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=a1e3766a1998098344c95f9adcb7237a)

**Step 9: point the bridge at the application, and watch for "Never."** Copy the application's UUID into `CHIRPSTACK_APPLICATION_ID` in `web/ingest/.env`, then `docker compose up -d eletect-ingest`. The device dashboard shows where things stand: a freshly-registered device reads `Last seen: Never` until an OTAA join happens over the air, which is expected:

![Device dashboard before the first join](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/chirpstack2/11_chirpstack_device_dashboard.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=2ae2946f077f386e64da8679b98dbdb4)

**What this chain looks like once a node joins, as measured:** node → (LoRa) → gateway → (UDP) → `chirpstack-gateway-bridge` → Mosquitto → ChirpStack → (MQTT) → `eletect-ingest` → Supabase → `send-alert` → email. This exact path was run end to end on production Supabase from a bench UNO Q through this same SenseCAP M2 and ChirpStack stack: a status frame became a `health` row, a boar detection stayed `normal` with no page, an elephant detection paged as `high`, and an elephant flagged no-retreat paged as an **URGENT** `critical` email. A bridge-outage test, stop the bridge, send a frame, start it again, delivered the queued frame rather than losing it, because ChirpStack's MQTT integration publishes at QoS 1 and Mosquitto persists its queue to disk; without either setting, a database hiccup could lose a night's alerts. Two things are still open: email delivery today only reaches the Resend account owner until a sending domain is verified, and the firmware's join handler does not yet recognise the LoRa-E5's throttled or "No band" replies, so a join failure from either of those causes still needs a human looking at the module's own AT-command log to diagnose.

> **Source files.** `docs/research/sensecap_gateway_in865_chirpstack_setup.md`, `web/chirpstack/README.md`, `web/ingest/README.md`, `docs/decisions/0031-lora-uplink-payload.md` in the project repository.

## 14. Power: battery and solar

A 4S **LiFePO4** 12.8 V pack, a solar charge controller with a LiFePO4 profile, a 20 W solar panel, and surge/reverse-polarity protection at the input. The battery is a LiFePO4 pack of this type, 12.8 V and 6 Ah with an integrated BMS, sized against a daily-energy-budget calculation (hardware/bom/eletect-x-power-budget.xlsx).

![Power schematic: solar panel, battery and buck converters](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/schematics_final/power.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=276177ce127681961f1b6ff84b4ad141)

**A brown-out we found and fixed.** The LED deterrent bank and the camera/UNO Q board were originally sharing one 5 V buck converter. LED actuation current transients sagged that shared rail enough to brown out the camera and board mid-event. For several field sessions it looked like an unrelated crash-reboot problem, until we traced it to the shared rail. The fix: **a separate, dedicated 8 V buck now powers the LED rail only**, while the camera and its USB hub run from their own 5 V buck, independent of the LED rail, so an LED fire can no longer pull the camera/board supply down with it. The UNO Q itself runs directly from **VIN** (7–24 V accepted) off the battery bus, keeping its USB-C port free for the camera. Power distribution follows a single-point star-ground topology from the battery's negative terminal, and the LED bank is wired to avoid a known problem with bare parallel LEDs: LED forward voltage drops slightly as a die warms, so in an unbalanced parallel array the branch that warms first pulls more current, gets hotter, and pulls more still, over-driving that one LED while its neighbours run dim. Each wing is therefore a set of parallel strings of two LEDs in series, and every string carries its own 2 Ω 2 W resistor, which sets roughly 700 mA per string from the 8 V rail and keeps one string from running away with a neighbour's current. We added the per-string resistors after spotting this risk during bring-up.

## 15. Manufacturing and assembly: designed in Fusion 360, printed in PETG

![3D-printed PETG enclosure parts](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/image52.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=46d98bcaeaf4704955c65d67256104f7)

All of this needs a body. The enclosure is designed in Fusion 360 ([hardware/cad/eletect\_x\_final.f3z](https://github.com/Abhinavkrishna3211/EleTect-X/blob/main/hardware/cad/eletect_x_final.f3z) / [.step](https://github.com/Abhinavkrishna3211/EleTect-X/blob/main/hardware/cad/eletect_x_final.step)) and printed in-house in PETG, split across two printers depending on which one is free.

**The horn mounts outside the enclosure.** The Ahuja SUH-15 horn (253×152×284 mm, 1.5 kg) is bigger than every other component combined, and it is already weatherproof, so it needs no enclosure of its own. We bolt it to the pole below the main enclosure and connect it to the node through a waterproof aviation connector, so the horn can be swapped without opening the electronics. Keeping it outside makes the main shell much smaller, which matters for a 3-person, under-20-minute pole install because wind load scales with the enclosure's frontal area. It also keeps the horn's magnet away from the LoRa antenna.

**Why the SUH-15.** It reproduces the low-frequency sounds our deterrents need. Smaller horns that do the same job cost much more, so the SUH-15 is the budget choice.

The main shell splits into a fixed pole-mount collar and a removable service hatch, so opening the unit never re-torques a fastener that carries the enclosure's weight on the pole. The exterior is a two-part head and body with a visor band.

![Assembled node on the pole with the horn below](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/image60.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=674e4816cba9695f54d1b9a1379fce54)

**Keeping water out.** Silicone O-ring cord gaskets seal the seams, an e-PTFE pressure-equalization vent lets the sealed volume breathe with temperature without letting rain in, PG7/PG9 IP68 cable glands carry each wire run through the shell wall, brass heat-set inserts (M3×10, M4×4) are reflow-set into the PETG print with a soldering iron so the enclosure can be opened and closed on machine screws instead of self-tapping into plastic every time, and SS-304 M3/M4 screws with a tamper bit hold it shut. A U-bolt/bracket sized for a 60-110 mm pole carries the main enclosure, and the SUH-15 bolts to the pole below it on its own mounting bracket. The geophone gets its own separate sub-assembly, covered in Section 6: potted into a sealed PVC capsule with a stainless steel spike, buried about 400 mm down, and sealed back to the main enclosure through an M12 4-pin IP68 connector.

## 16. Making it field ready: self-healing and watchdogs

A node left alone on a forest boundary for days cannot rely on someone noticing it has gone dark. Recovery on the board's Linux side runs in layers, each covering a different failure:

* **Docker restart policy (unless-stopped)**: the container comes straight back after a crash or a power cut, with no supervisor needed.

* **eletect-x-boot-reassert.sh** (at boot): App Lab regenerates the container's compose file on every launch and drops our settings, so this unit recreates the container from a protected app-compose.golden.yaml that App Lab never writes to.

* **eletect-x-watchdog.sh** (every 5 min): re-applies the unless-stopped policy if it has drifted, and restarts the app if it has been down for more than a 300 s grace period. It also probes the Edge Impulse vision runner on :1337/api/info and restarts its systemd unit if it stops answering for 300 s; the unit's own Restart=always covers the runner dying outright.

* **eletect-x-mcu-heal.sh** (at boot): checks that the STM32 still answers Bridge calls. If it has dropped into its bootloader, the script resets and reflashes it and re-applies the golden compose. A separate unit, eletect-x-boot0-hold, holds the BOOT0 line low so a cold boot lands in the sketch in the first place.

* **eletect-x-fire-tap.sh** (every few minutes): copies every drive\_horn/drive\_led/pulse\_ir ack and encounter-start line into a log on the host, so the record survives container recreation and power cuts.

A separate **per-thread stall watchdog** covers another case: a hung-but-alive worker thread (one that's still running but has stopped doing useful work) stops updating its heartbeat, is\_healthy() notices, and the process exits the same way a real crash would, so Docker's restart policy recovers both. Alongside it, a rate-limited telemetry log (device/mpu/services/board\_health.py) records board vitals every 30 seconds:

[device/mpu/services/board\_health.py](https://github.com/Abhinavkrishna3211/EleTect-X/blob/main/device/mpu/services/board_health.py#L69-L76)

```python theme={"system"}

def snapshot(disk_path: Path) -> dict[str, Any]:
    return {
        "cpu_temp_c": read_cpu_temp_c(),  # highest of every thermal zone, the one that throttles
        "mem_available_mb": read_mem_available_mb(),
        "load_avg": read_load_average(),
        "disk_free_mb": read_disk_free_mb(disk_path),
    }
```

Every reader here returns None on failure instead of raising, since this module is read by the performance log only, and a bad reading must never be able to reach the capture or deterrence path.

## 17. Field testing: two nodes, and what they recorded

Two Arduino UNO Q nodes run the same software and configuration at two sites: one on a forest edge where elephant encounters occur, and one in our farmland where boar attacks occur. A forest edge and a farm see different animals, so we need field data from both.

**A fox turned up, and the system correctly left it alone.** One of the two nodes opened an encounter on motion at its site, the camera recorded the full event the same way it would for anything else that trips a reflex-layer trigger, and the footage showed a fox, not an elephant or a boar. The vision model had three classes at the time, Elephant, Boar, and Background (Section 8), so a fox did not read as either target species, the fused probability never cleared the fire threshold, and neither the horn nor the LEDs fired. The event was logged and the footage kept like any other encounter, but nothing fired, because only elephants and boar are meant to be deterred.

[*https://youtu.be/3Dm8IDxwZ88?si=ENmB7Ew7WzWHmVIJ*](https://youtu.be/3Dm8IDxwZ88?si=ENmB7Ew7WzWHmVIJ)

**From three classes to four.** We built the system with a three-class model first. A fox kept wandering into the deployed site, so we moved to four classes and added Fox (Section 8). It is also a useful stand-in: we want to test the full detect, confirm and deter pipeline on a wild elephant or boar, but neither turns up on a schedule, and a fox visiting our own property does.

We added a deterrence response for Fox so the whole pipeline could be tested. A fox is deterred just like a boar, with the same tier ladder, LED patterns and IR timing, but it has its own learning bandit and its own anti-habituation tracking, so a night of foxes never affects the Boar or elephant ladders.

**The four-class model in the field.** When a fox came back on a later field test, the retrained model identified it as Fox and the node fired the Fox deterrent:

[https://youtu.be/MSTuE-OOPm8?si=HwlELcYV4ClNUe3f](https://youtu.be/MSTuE-OOPm8?si=HwlELcYV4ClNUe3f)

**An open, growing dataset: every future encounter, uploaded.** Every Elephant and Boar detection the two deployed nodes record from here on, video and stills alike, is uploaded as it comes in.

Dataset: [Click here](https://drive.google.com/drive/folders/14I1K6XiSnI00WZ8HbcUF69TllK7GCBQK?usp=sharing)

This footage is also the raw material for Section 6's footfall classifier, since no public dataset of elephant or wild boar footfall signatures exists. It will be added to the project's GitHub repository.

## 18. The web app: what the ranger, the resident, and the public each see

![Public site: home page](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/image57.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=93428b45b14f1cdb595ef9e9faf9095c)

![Public site: comparison with existing deterrents](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/image62.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=812ed22e4c1718935776283fa499c16b)

![Public site: what EleTect protects](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/image17.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=273c852d5a5e918e42c7470b1ab66a2d)

A node firing a horn in the forest is only half the system. The cloud side is only for monitoring and coordination; no animal's safety depends on it. Every decision described in Sections 10-12 happens locally on the node, with or without connectivity. The web app gives visibility: a place for a forest officer to see what happened, a place for a resident to opt in to a warning, and a public-facing site explaining the project to anyone who lands on it. It's a React PWA (web/frontend) on Supabase (Postgres, auth, RLS, realtime, edge functions) and ChirpStack-over-MQTT ingest (web/ingest). We tested the whole path, from a node's alert through ingest to the dashboard.

**Live:** [**Click** here](https://eletect.vercel.app/)

### The ranger/officer dashboard

![Ranger dashboard: Overview](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/image29.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=f4e85a945935e4c73edece58b3c7a364)

* **Overview**: the live operational snapshot, clock kept in IST (the sector's actual operating timezone) so a timestamp on screen means the same thing it does on the ground.

![Ranger dashboard: Fleet](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/image38.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=3e6ba31772509a0135062c1f47a2a1c0)

* **Fleet**: the node roster, sorted by urgency: a dead node outranks a merely degraded one, which outranks a healthy one, so the node that needs attention is always at the top. For now a ranger has to look at the list: a node that misses its check-in moves to the top, but nobody gets paged the way they do for a detection. The fix is simple, the same push/email channel Stay Safe already uses, triggered by silence, but it has not been built yet.

![Ranger dashboard: Corridor](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/image4.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=78172a70cad2d10a5add1a298c8aa9e3)

* **Corridor**: a live view of the safe-herding corridor logic (deter on the village side, leave the forest-side escape lane open): the map shows the herd handing off from node to node as it moves, with the dwell time at each node before the next handoff.

![Ranger dashboard: Planner](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/image32.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=baaa7b3419a7fb5603d409156546b295)

* **Planner**: a deployment-planning tool with preset boundaries around the Sector-7 pilot area, so a ranger can get a node/gateway-count estimate for a new boundary in one click, without needing to draw a custom shape first.

![Ranger dashboard: Replay](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/image44.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=bf52a6b6687194ad5f09f94147ee9ca7)

* **Replay**: replays a recorded incident from start to finish (\~14 s per incident) with a continuously-interpolated position marker, not a series of jump-cuts between log entries.

![Ranger dashboard: Learning](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/image33.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=eb672218a722ac55face437bbb90aa7b)

* **Learning**: a direct window into the bandit from Section 11: a per-pattern effectiveness bar chart, so "what has this node learned works" is something a ranger can see.

![Ranger dashboard: Admin (user details masked)](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/image36.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=eb14ddd501f9b9a3be235d4134980ce0)

* **Admin**: user and role management, enforced server-side (every action is authorized inside the database by an is\_admin() check in the RPC layer itself, not just hidden in the UI, so a non-admin calling the same function directly with their own credentials is rejected by Postgres, not by the page). Deliberately **does not** include a firmware/OTA panel: the device has no firmware-update pipeline yet, and the screen will come with it.

![Ranger dashboard: Officer approvals](https://mintcdn.com/edgeimpulse/fEWXIyhWAsjgviVQ/.assets/images/eletect-x/image9.png?fit=max\&auto=format\&n=fEWXIyhWAsjgviVQ\&q=85\&s=7cf1139d40682bc16f49aff58dcc1aae)

* **Officer approvals**: the workflow for bringing a new officer account onto the platform.

### The resident-facing app

* **Stay Safe**: the public opt-in page for residents: enable alerts and choose a channel.

* **Resident view**: once opted in, a resident sees public\_area\_risk: an aggregate, privacy-scoped risk signal (counts per day, by area), deliberately **not** species, exact location, or anything a resident's role isn't meant to see. The database enforces this with row-level security, like the admin panel; the page does not just hide it.

### The public site

Home, About, Technology, Research, Deployments, Solutions, and Contact: for anyone who is not a ranger or resident: what the project is, how it works and where it runs.

## 19. Known limitations and current status

Two EleTect X nodes are running right now, one at the forest and one in our agricultural field. Here is what is still open:

* **The seismic channel detects footsteps but does not yet tell which animal is coming.** We do not have a good dataset yet, so we are not using an edge model to classify the animal. We are collecting that data now, and once we have it we will build that model and make the dataset public so everyone can use it.
* **The retrained, four-class vision model runs warmer.** Adding Fox raised the input resolution from 96x96 to 160x160 (Section 8), and classification time went from about 138 ms to 374 ms per frame. The board's temperature needs watching on hot days.
* **Anti-habituation is still in field testing.** It works on the board and in tests, but we need months of field data to know its true effectiveness. In the one to one-and-a-half months of field testing so far, the results look good.

Each of these is also covered in its own section; this list puts them in one place.

## 20. Conclusion: what this buys back, for people and for elephants

Building this taught us more about restraint than about machine learning. Putting a geophone ahead of a camera, building the anti-habituation engine around how fixed deterrents fail, treating boar as seriously as elephants because the family behind this boundary loses sleep over both: each of these came from choosing what fits how an animal moves through this ground over what sounds more impressive. We have not hidden the unfinished parts. A device meant to stand between a person and a five-tonne animal should not fail quietly, and whoever picks this up next, whether that is us in six months or a forest department engineer somewhere else, should know what it can and cannot do yet.

The next steps build on what the two nodes are already doing. The dataset described in Section 17 is the path to a footfall classifier that can tell an elephant from a boar from a fox by ground vibration alone, before the camera or the microphone ever has to weigh in. The corridor and fleet tools already built into the web app are what turn our two current nodes, one on a forest edge and one in our agricultural field, into a fleet, deployed wherever a forest department or a farming community asks for one. That is the next build, on the same hardware.

This forest was never only ours to begin with. The land along this boundary has had elephants crossing it for longer than any of the people farming beside it have been alive, and an elephant did not choose to have a farm appear on its route any more than a farmer chose to have a five-tonne animal appear on theirs. Neither side wins by treating the other as something to be fenced out, shocked into staying away, or outlasted. We built EleTect X because we believe the answer is coexistence: a boundary that a person and an elephant can both cross and both survive. We are building it for the people who farm this land, and for the elephants, boar and the occasional fox that still call it home.

### Sources

The claims in Sections 1 and 3 trace to the sources below.

Human-elephant conflict, the scale of it:

* [Over 2,500 people died in 5 years in human-elephant conflicts: Govt data](https://www.business-standard.com/india-news/over-2-500-people-died-in-5-years-in-human-elephant-conflicts-govt-data-124072600517_1.html), Business Standard, reporting the Ministry of Environment, Forest and Climate Change's own figures placed before Parliament (2,853 deaths 2019–2023, 628 in 2023, Kerala 124).
* [India lost 528 elephants due to 'unnatural causes' in 5 years, most from electrocution: Govt data](https://www.business-standard.com/india-news/india-lost-528-elephants-due-to-unnatural-causes-in-5-years-govt-data-124072900824_1.html), Business Standard, on the same Parliament reply.
* [Human-Elephant Conflict: A Review of Current Management Strategies and Future Directions](https://www.frontiersin.org/journals/ecology-and-evolution/articles/10.3389/fevo.2018.00235/full), Frontiers in Ecology and Evolution, 2018: the source for the \~500,000 affected families a year and the thirteen Asian/thirty-seven African range-country count.
* ["One elephant a day": Sri Lanka wildlife conflict deepens as death toll rises](https://news.mongabay.com/2023/05/one-elephant-a-day-sri-lanka-wildlife-conflict-deepens-as-death-toll-rises/), Mongabay, on Sri Lanka's 2022 record (433 elephant deaths, 145 human deaths).
* [Sri Lanka's Elephant Crisis: "No Single Solution, but a…"](https://www.wnpssl.org/sri-lankas-elephant-crisis-no-single-solution-but-a-collective-will-jehan-canagaretna/), Wildlife and Nature Protection Society of Sri Lanka, the source for the 6,400-elephant, 24-year toll and the 250 further deaths in the first half of 2025.
* [Sh1.2bn debt of pain as human-wildlife conflict persists](https://nation.africa/kenya/health/-sh1-2bn-debt-of-pain-as-human-wildlife-conflict-persists-5206740), Daily Nation, on Kenya's crop-raiding rise (156 to 363 cases, 2020–2023) and its compensation backlog.

The field biology behind the deterrent and detection choices:

* O'Connell-Rodwell, C., Wood, J. D., Rodwell, T. C., Puria, S., Partan, S. R., Keefe, R., Shriver, D., Arnason, B. T., & Hart, L. A. (2006). [Wild elephant (Loxodonta africana) breeding herds respond to artificially transmitted seismic stimuli](https://www.researchgate.net/publication/225849764_Wild_elephant_Loxodonta_africana_breeding_herds_respond_to_artificially_transmitted_seismic_stimuli). *Behavioral Ecology and Sociobiology*, 59, 842–850. The Etosha playback study behind putting a geophone ahead of a camera in this system's detection chain (Sections 3 and 6).
* [New study confirms beehive fences as highly effective in reducing human-elephant conflict](https://savetheelephants.org/news/new-study-confirms-beehive-fences-as-highly-effective-in-reducing-human-elephant-conflict-but-researchers-warn-of-future-risks/), Save the Elephants, summarising the nine-year Kenya field trial (86.3% peak-season deterrence across 3,000+ approaches) behind this project's honeybee-swarm deterrent track. Full paper: [Impact of drought and development on the effectiveness of beehive fences as elephant deterrents over 9 years in Kenya](https://conbio.onlinelibrary.wiley.com/doi/10.1111/csp2.13242), *Conservation Science and Practice*, 2024.
