Skip to main content

c4002-python

Test & Lint License: MIT Python 3.8+

Python driver and CLI tools for the DFRobot C4002 (SEN0691) 24GHz mmWave Human Presence Detection Module.

Provides robust UART packet framing, real-time telemetry decoding (static presence, motion distance, speed, direction, ambient light), automated room background noise calibration, and optional digital OUT pin monitoring on Raspberry Pi and other Linux systems.


[!IMPORTANT] Disclaimer: This is an independent open-source library. It is not affiliated with, maintained by, or endorsed by DFRobot. All product names, logos, and brands are property of their respective owners.


DFRobot C4002 mmWave Sensor

Features

  • Complete Telemetry Decoding: Parses 32-byte binary notification frames from the C4002 sensor.
    • Static Presence: Detects stationary humans (breathing, sitting) with distance (m) and signal energy (0–100).
    • Motion Tracking: Measures distance (m), speed (m/s), signal energy (0–100), and direction (Approaching / Away).
    • Ambient Light: Decodes onboard light sensor intensity (Lux).
    • Gate Bitmasks & Hold Timers: Reports active distance gates and presence disappearance countdown.
  • Auto Environmental Calibration: Built-in routine to sample room reflections and store the background noise floor, preventing false triggers.
  • Reliable Checksum Verification: Validates 16-bit packet checksums to reject corrupted data.
  • Hardware Agnostic: Tested on Raspberry Pi Zero W, but works with any Raspberry Pi and standard USB-to-UART TTL serial converter on Linux, macOS, or Windows.
  • Optional GPIO Monitoring: Support for the module's digital OUT pin via RPi.GPIO (falls back gracefully if GPIO is unavailable).

Hardware Wiring

The C4002 operates at 3.6V – 5.5V with 3.3V TTL UART logic. It can be powered directly from the Raspberry Pi 5V power rail.

  Raspberry Pi GPIO Header                  DFRobot C4002
 ┌─────────────────────────┐               ┌─────────────┐
 │ Pin 2  [5V]             ├───────────────┤ VIN         │
 │ Pin 6  [GND]            ├───────────────┤ GND         │
 │ Pin 8  [GPIO 14 / TXD]  ├───────────────┤ RX          │
 │ Pin 10 [GPIO 15 / RXD]  ├───────────────┤ TX          │
 │ Pin 11 [GPIO 17]        ├───────────────┤ OUT (opt)   │
 └─────────────────────────┘               └─────────────┘

Pinout Table (Raspberry Pi 40-Pin Header)

C4002 Pin Raspberry Pi Pin Header Pin # Description
VIN 5V Power Pin 2 or 4 Power supply (3.6V – 5.5V)
GND Ground Pin 6, 9, or 14 Common ground
TX GPIO 15 (RXD0) Pin 10 Sensor TX $\rightarrow$ Pi RXD
RX GPIO 14 (TXD0) Pin 8 Sensor RX $\leftarrow$ Pi TXD
OUT (Optional) GPIO 17 Pin 11 Digital presence indicator (HIGH = presence)

Raspberry Pi Serial Port Setup

Ensure the hardware UART is enabled and the serial login console is disabled:

  1. Run sudo raspi-config
  2. Navigate to Interface Options $\rightarrow$ Serial Port
  3. "Would you like a login shell to be accessible over serial?" $\rightarrow$ Select No
  4. "Would you like the serial port hardware to be enabled?" $\rightarrow$ Select Yes
  5. Reboot the Raspberry Pi: sudo reboot

The primary serial port will be accessible at /dev/serial0.


Installation

Direct Install via pip (No git clone required)

Install directly into your Python environment from GitHub:

# Standard installation
pip install git+https://github.com/nobudev7/c4002-python.git

# With optional Raspberry Pi GPIO support
pip install "c4002-python[gpio] @ git+https://github.com/nobudev7/c4002-python.git"

From Source (For Local Development)

git clone https://github.com/nobudev7/c4002-python.git
cd c4002-python
pip install -e .

To include optional Raspberry Pi GPIO support:

pip install -e ".[gpio]"

Quick Start

import time
from c4002 import C4002Sensor, TargetState

# Initialize sensor on default serial port and optional GPIO 17
sensor = C4002Sensor(port="/dev/serial0", baudrate=115200, out_pin=17)
sensor.connect()

try:
    while True:
        data = sensor.read_packet()
        if data and not getattr(data, "is_calibrating", False):
            print(f"State: {data.target_state_name} | Light: {data.ambient_light_lux} Lux")
            if data.presence_detected:
                print(f"  Presence: {data.presence_distance_m} m (Energy: {data.presence_energy}/100)")
                if data.target_state == TargetState.MOTION:
                    print(f"  Motion: {data.motion_distance_m} m at {data.motion_speed_m_s} m/s ({data.motion_direction_name})")
        time.sleep(0.5)
except KeyboardInterrupt:
    sensor.close()

Using as a context manager:

with C4002Sensor(port="/dev/serial0") as sensor:
    data = sensor.read_packet()
    if data:
        print("Presence:", data.presence_detected)

Onboard LED Control (Dark / Stealth Mode)

The C4002 module includes two onboard LEDs:

  • Blue RUN LED: Operation / power indicator (blinks or stays solid blue).
  • OUT LED: Detection indicator (lights up when presence/motion is detected).

You can control or completely disable both LEDs via software over UART:

from c4002 import C4002Sensor, LedMode

with C4002Sensor(port="/dev/serial0") as sensor:
    # Turn off both LEDs (stealth/bedroom mode)
    sensor.turn_off_leds()

    # Or control each LED individually:
    sensor.set_run_led(False)       # Turn off blue RUN LED
    sensor.set_out_led(False)       # Turn off detection OUT LED
    sensor.set_run_led(True)        # Turn blue RUN LED back on
    sensor.set_led(run_led=LedMode.OFF, out_led=LedMode.OFF)

In the example scripts, pass the --led-off flag:

python3 examples/basic_monitor.py --led-off
python3 examples/minute_aggregator.py --led-off

[!NOTE] Like sensor detection thresholds, the LED state is stored in volatile memory on the radar module. When the sensor is power-cycled (power disconnected or Raspberry Pi rebooted), the module reverts to its hardware default (RUN LED ON). Call turn_off_leds() on startup in your script or daemon to ensure it stays dark.


Environmental Background Noise Calibration

Because 24GHz radar waves detect micro-movements, reflective objects (metal furniture, fans, moving curtains) can cause false presence triggers in an empty room.

The sensor features built-in automatic background noise calibration:

python3 examples/auto_calibrate.py
  1. Run the script.
  2. Step out of the room within 10 seconds.
  3. Keep the room empty for 30 seconds while the sensor samples static background reflections and stores dynamic noise thresholds.

1-Minute Time-Series Logging (Aggregation)

To log presence data into a CSV file for charting without missing transient movements (e.g., someone walking through the room for 10 seconds):

python3 examples/minute_aggregator.py --output presence_1min_timeseries.csv
  • Samples sensor telemetry continuously at 1 Hz and aggregates into 1-minute rows.
  • Generates metrics ideal for charting:
    • occupancy_pct: Occupancy percentage (0.0% – 100.0%) during the minute.
    • avg_distance_m: Mean presence distance (calculated only when presence is active).
    • max_motion_energy: Peak movement energy (0 – 100) recorded in that window.
    • avg_light_lux: Mean ambient light level.

Telemetry Data Reference

sensor.read_packet() returns a TelemetryData object with the following attributes:

Attribute Type Unit / Range Description
target_state TargetState Enum (0, 1, 2) NO_TARGET, STATIC_PRESENCE, or MOTION
target_state_name str String Human-readable state name
presence_detected bool True / False True if state is presence or motion
ambient_light_lux float Lux (0.0 – 6553.5) Onboard ambient light intensity
presence_distance_m float Meters Distance to static presence target
presence_energy int 0100 Reflected signal energy of static target
presence_countdown_s int Seconds Delay countdown before presence clears
motion_distance_m float Meters Distance to moving target
motion_speed_m_s float m/s Radial speed of moving target
motion_energy int 0100 Reflected signal energy of motion target
motion_direction MotionDirection Enum (0, 1, 2) AWAY, NO_DIRECTION, or APPROACHING
gate_bitmask int Bitmask Bit flags representing active distance gates

Running Unit Tests

Unit tests run without physical hardware using recorded raw telemetry packets:

# Using standard Python unittest
PYTHONPATH=src python3 -m unittest discover -s tests -p "test_*.py"

# Or using pytest (if installed)
PYTHONPATH=src pytest -v tests/

References & Documentation


License

This project is licensed under the MIT License.

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

c4002_python-0.2.0.tar.gz (117.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

c4002_python-0.2.0-py3-none-any.whl (11.9 kB view details)

Uploaded Python 3

File details

Details for the file c4002_python-0.2.0.tar.gz.

File metadata

  • Download URL: c4002_python-0.2.0.tar.gz
  • Upload date:
  • Size: 117.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/7.0.0 CPython/3.13.14

File hashes

Hashes for c4002_python-0.2.0.tar.gz
Algorithm Hash digest
SHA256 b4ae3d51a1dd0168c279d466b51794a9752c560d5ae52037b476b5e5501d4689
MD5 8abff8636ff85a40836f77c47e3be824
BLAKE2b-256 2ade26c78d3b6fe9325b0f0724e76a59258427bc08ee87a026ee164c99e46084

See more details on using hashes here.

Provenance

The following attestation bundles were made for c4002_python-0.2.0.tar.gz:

Publisher: publish.yml on nobudev7/c4002-python

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file c4002_python-0.2.0-py3-none-any.whl.

File metadata

  • Download URL: c4002_python-0.2.0-py3-none-any.whl
  • Upload date:
  • Size: 11.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/7.0.0 CPython/3.13.14

File hashes

Hashes for c4002_python-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 3d8e87113cd17e91752fe3af9c9017ecadaf50aa83f60e94e0448889071b1e17
MD5 22b2dca58214c0d0f37465d201488eef
BLAKE2b-256 1ec5cc03ce6c1faff19bb3998f8ca4d652ed8d050e61929a6f035c56d2a10711

See more details on using hashes here.

Provenance

The following attestation bundles were made for c4002_python-0.2.0-py3-none-any.whl:

Publisher: publish.yml on nobudev7/c4002-python

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Release history Release notifications | RSS feed

This release

0.2.0 This release

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page