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.



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

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 0 – 100 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 0 – 100 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.

Metadata

Release files for c4002-python 0.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for c4002-python 0.2.0
File Size Uploaded Provenance Actions
c4002_python-0.2.0.tar.gz 117.3 kB With provenance Details for c4002_python-0.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for c4002-python 0.2.0
File Interpreter ABI Platform Actions
c4002_python-0.2.0-py3-none-any.whl Python 3 none any Details for c4002_python-0.2.0-py3-none-any.whl

Total release size: 129.2 kB

Release files / c4002_python-0.2.0.tar.gz

Download URL c4002_python-0.2.0.tar.gz
Size 117.3 kB
Tags Source
SHA-256 checksum
How to use checksums
b4ae3d51a1dd0168c279d466b51794a9752c560d5ae52037b476b5e5501d4689
BLAKE2b-256 checksum
How to use checksums
2ade26c78d3b6fe9325b0f0724e76a59258427bc08ee87a026ee164c99e46084
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 12, 2026.

Transparency log

Release files / c4002_python-0.2.0-py3-none-any.whl

Download URL c4002_python-0.2.0-py3-none-any.whl
Size 11.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
3d8e87113cd17e91752fe3af9c9017ecadaf50aa83f60e94e0448889071b1e17
BLAKE2b-256 checksum
How to use checksums
1ec5cc03ce6c1faff19bb3998f8ca4d652ed8d050e61929a6f035c56d2a10711
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 12, 2026.

Transparency log

Security for c4002-python 0.2.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for c4002_python-0.2.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 12, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.2.0 This release

2 release files Full provenance

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