---
title: "2. Write your first node"
description: "Write a motion detector in Tato Studio's Code view, give it a setting, drop it into the stream, connect it to the camera, and watch its reports in the Node visualizer."
type: "docs-page"
url: "https://tatolab.com/docs/tutorial/first-node"
site: "Tatolab"
section: "Tutorial"
---

# 2. Write your first node

> Write a motion detector in Tato Studio's Code view, give it a setting, drop it into the stream, connect it to the camera, and watch its reports in the Node visualizer.

In this step you'll write `MotionDetector`, a node that compares the camera's frames and reports how much of the picture changed. Its reports are ordinary data, which in the next step you'll share with another project.

## Add numpy

The detector uses numpy. Open the **Code** view from any area's view menu, press **+**, and open `pyproject.toml`. Add numpy to its dependencies:

```toml title="pyproject.toml"
dependencies = ["tatolab-stream>=0.54.2", "numpy"]
```

Keep the `tatolab-stream` version your project already names, and save with ⌘S. The runtime installs numpy into the project's environment when it next loads the project, which happens when you save the node below.

## Create the node

Open the **Files** view, press **New node file**, and name it `nodes/motion_detector.py`. Studio creates it from the node template and opens it in the Code view. Replace the template with:

```python title="nodes/motion_detector.py"
from dataclasses import dataclass
from typing import Annotated

import numpy
from tatolab.stream import (
    Image,
    Input,
    Output,
    Records,
    RuntimeContextFullAccess,
    RuntimeContextLimitedAccess,
    log,
    node,
)


@dataclass
class MotionDetectorConfig:
    threshold: Annotated[float, "How much of the picture has to change to count as motion: 0.02 is 2%."] = 0.02


@node.meta(category="Analysis", description="Reports how much of the picture changed since the last frame.")
@node.process
class MotionDetector:
    video = Input(Image, delivery="newest", description="The frames to watch.")
    motion = Output(Records, names=("changed", "moving"), description="One report per frame.")

    def __init__(self, config: MotionDetectorConfig) -> None:
        self.threshold = config.threshold
        self.previous: numpy.ndarray | None = None
        self.moving = False

    def configure(self, config: MotionDetectorConfig) -> None:
        self.threshold = config.threshold

    def setup(self, ctx: RuntimeContextFullAccess) -> None:
        log.info("watching for motion", threshold=self.threshold)

    def process(self, ctx: RuntimeContextLimitedAccess) -> None:
        frame = ctx.inputs.read(self.video)
        if frame is None:
            return
        with frame.cpu() as pixels:
            grey = pixels[::8, ::8, :3].mean(axis=2)
        if self.previous is not None:
            changed = float(numpy.mean(numpy.abs(grey - self.previous)) / 255.0)
            moving = changed > self.threshold
            if moving != self.moving:
                log.info("motion started" if moving else "motion stopped", changed=round(changed, 4))
                self.moving = moving
            ctx.outputs.write(self.motion, {"changed": changed, "moving": moving}, timestamp_ns=frame.timestamp_ns)
        self.previous = grey
```

Save it with ⌘S. Studio reloads the project, which installs numpy on the way.

What each part does:

- **`MotionDetectorConfig`** is the node's settings. `threshold` shows in Properties when the node is selected, with its description and its default, `0.02`. The value you set is saved with the stream.
- **`@node.meta`** gives the node a category and a description. Studio and agents read both from the node catalog.
- **`@node.process`** makes it a process node: a class the runtime runs in a process of its own. By default it's `reactive`, so the runtime calls `process` when a frame arrives.
- **`video = Input(Image, delivery="newest")`** declares an input of pictures. `newest` means each read gets the latest frame, so if the detector is ever slower than the camera, it skips frames instead of falling behind.
- **`motion = Output(Records, names=("changed", "moving"))`** declares an output of Records, small structured values, and the names every record carries.
- **`configure`** takes a new threshold while the stream runs. Without it, a change to `threshold` would wait for the next play.
- **`process`** reads the newest frame, copies it to the CPU with `frame.cpu()`, takes every eighth pixel in each direction, and compares it with the last one. It writes one report per frame, stamped with the frame's own time, and logs when motion starts and stops.

The camera's picture stays on the GPU. `frame.cpu()` copies one frame back for numpy to read, and the 8× subsampling keeps that cheap. A heavier model would read the frame on the GPU instead; see [Use your model](https://tatolab.com/docs/build/models).

## Drop it into the stream

Click the graph, press **Tab**, type `motion`, and place **Motion Detector**. It's filed under Analysis, the category its `@node.meta` gives it. Drag a wire from the camera's `video` pin to the detector's `video` pin. The runtime starts the detector in a process of its own.

Click the detector. The Node visualizer shows its latest report, live: `changed`, a small number, and `moving`, `false`. Wave at the camera, and `moving` turns `true`.

The project's log, under the Code view, shows the detector's records:

```txt title="Output"
info  watching for motion  threshold=0.02
info  motion started  changed=0.1391
info  motion stopped  changed=0.0018
```

## Change it while it runs

With the detector selected, set `threshold` to `0.1` in **Properties**. The detector's `configure` takes it at once, and only bigger movements count now.

Change the code instead, say the `::8` to `::4`, and save. Studio reloads the project and the detector starts again with your change, while the camera keeps running.

If a save breaks something, the detector's card says why, and the log has the rest. Fix it and save again.

## What the stream holds now

Two nodes, `camerasource` and `motiondetector`, a wire from one to the other, and the threshold you set. The detector's type is its module and class, `nodes.motion_detector:MotionDetector`: that's how the runtime finds your code, and how an agent or the graph document names it.

## Next

Next you'll share the reports with another project: [Share the motion reports](https://tatolab.com/docs/tutorial/share).
