Skip to main content
Reacgen Biosystems

Python examples

Walk through every common scenario from a Python host (Raspberry Pi or any Linux I²C system) using the turbidvision client library.

These examples use the turbidvision Python library. Install it first. To see the underlying register transactions instead, read the I²C interface reference; the same scenarios in C++ are on the Arduino examples page, and over WiFi on the WebSocket examples page.

Setup

Import the library, open one connection, and keep it for the rest of the session. Change I2C_BUS to match your host (/dev/i2c-1 → 1). The fmt() helper prints floats with NaN/None shown explicitly.

import time, math
from turbidvision import TurbidVision

I2C_BUS = 1                       # /dev/i2c-1; change to match your host
sensor = TurbidVision(bus=I2C_BUS).open()

if sensor.is_present():
    print(f"Turbid Vision Probe found at 0x{sensor.address:02X} on bus {I2C_BUS}.")
else:
    print(f"No response at 0x{sensor.address:02X} on bus {I2C_BUS} - check wiring/power.")


def fmt(v):
    "Display helper: show NaN/None explicitly, else 4 decimals."
    if v is None:
        return "None"
    if isinstance(v, float) and math.isnan(v):
        return "NaN"
    return f"{v:.4f}"

1. Discovery and status

is_present() probes the bus; read_status() returns a decoded Status object with named flags. At power-on with no job running, all flags are False.

status = sensor.read_status()
print(status)                       # raw byte + all flags

for field in ("job_running", "has_blank", "has_initial",
              "laser_pwrctl_running", "laser_stable", "reflectance_stable"):
    print(f"  {'X' if getattr(status, field) else '.'}  {field}")

2. Start an OD job and stream readings

Start the job, wait for job_running, then allow at least 180 seconds for has_initial while the current 60-sample initial reference is captured. Then stream calibrated density, printing only when a new reading arrives.

sensor.start_job()
print("Job started.")

if not sensor.wait_for_status(sensor.STATUS_JOB_RUNNING, timeout=10):
    raise RuntimeError("Job did not start.")
print("Waiting for initial reference (allow at least 180 s)...")
if not sensor.wait_for_status(sensor.STATUS_HAS_INITIAL, timeout=180):
    raise RuntimeError("Initial reference never captured - check the fiber connection.")

print(f"\n{'reading':>8}  {'density(g/L)':>14}  {'laser(mW)':>10}")
print("-" * 38)
last = None
t_end = time.monotonic() + 30
while time.monotonic() < t_end:
    n = sensor.reading_number()
    if n != last:
        print(f"{str(n):>8}  {fmt(sensor.calibrated_density()):>14}  {fmt(sensor.laser_power_mw()):>10}")
        last = n
    time.sleep(0.5)

3. Take a blank reference

A blank captures the reflectance of clear media so the sensor can compute normalized_reflectance. The job must be stopped first. This scenario is interactive: it prompts you to swap the sample between steps.

# 1. Stop the job if running (blanks require the job stopped).
if sensor.read_status().job_running:
    print("Stopping job first...")
    sensor.stop_job()
    sensor.wait_for_status(sensor.STATUS_JOB_RUNNING, timeout=10, clear=True)

# 2. Place sensor in blank media.
input("Place the sensor in blank media (clear water / blank medium), then press Enter...")

# 3. Take the blank and wait for has_blank.
sensor.take_blank()
print("Blank requested. Waiting for has_blank...")
if sensor.wait_for_status(sensor.STATUS_HAS_BLANK, timeout=35):
    print("Blank captured.")
else:
    print("WARNING: blank did not complete within timeout.")

# 4. Place sample, restart the job.
input("Place the sensor in your sample, then press Enter to restart the job...")
sensor.start_job()
sensor.wait_for_status(sensor.STATUS_HAS_INITIAL, timeout=180)

time.sleep(1.0)
print("Normalized reflectance (with blank):", fmt(sensor.normalized_reflectance()))
print("(~1.0 in blank media; lower values indicate cell density.)")

4. Read a full snapshot

read_all() returns a Snapshot dataclass with every measurement plus the decoded status. NaN fields are unavailable (job not started, or Kalman filter disabled for the Kalman filter fields).

def print_snapshot(snap):
    print("---- Turbid Vision Snapshot ----")
    print(f"  reading_number: {snap.reading_number}")
    print(f"  {snap.status}")
    rows = [
        ("measured_reflectance",            snap.measured_reflectance),
        ("normalized_reflectance",          snap.normalized_reflectance),
        ("calibrated_density (g/L)",        snap.calibrated_density),
        ("growth_rate u (1/h)  [Kalman filter]",      snap.growth_rate),
        ("laser_power_mw",                  snap.laser_power_mw),
        ("filtered_density (g/L)  [Kalman filter]",   snap.filtered_calibrated_density),
        ("filtered_growth (g/L/h)  [Kalman filter]",  snap.filtered_calibrated_growth_rate),
        ("absolute_growth (g/L/h)  [Kalman filter]",  snap.calibrated_absolute_growth_rate),
    ]
    for label, val in rows:
        print(f"  {label:<34} {fmt(val):>10}")


print_snapshot(sensor.read_all())

5. Set laser power

set_laser_power_pct(pct) sets the target as a percentage of maximum (0–100 %) and activates the laser power controller. Wait for laser_stable, then read back the measured power.

sensor.set_laser_power_pct(80.0)
print("Laser target set to 80 %.")

if sensor.wait_for_status(sensor.STATUS_LASER_STABLE, timeout=15):
    time.sleep(0.1)
    print("Laser power settled at:", fmt(sensor.laser_power_mw()), "mW")
else:
    print("Laser did not stabilise within timeout.")

6. Collect and plot density

Collect readings for a fixed duration, then plot raw vs Kalman-filtered density. If the Kalman filter is disabled the filtered series is all NaN and is omitted.

import matplotlib.pyplot as plt

# Ensure a job is running.
if not sensor.read_status().job_running:
    sensor.start_job()
    sensor.wait_for_status(sensor.STATUS_HAS_INITIAL, timeout=180)

ts, raw, filt = [], [], []
t0 = time.monotonic()
last = None
print("Collecting 60 s of data...")
while time.monotonic() - t0 < 60:
    n = sensor.reading_number()
    if n != last:
        ts.append(time.monotonic() - t0)
        raw.append(sensor.calibrated_density())
        filt.append(sensor.filtered_calibrated_density())
        last = n
    time.sleep(0.5)
print(f"Collected {len(ts)} readings.")

fig, ax = plt.subplots(figsize=(10, 5))
ax.plot(ts, [v if not math.isnan(v) else None for v in raw],
        label="calibrated_density (raw)", color="steelblue", linewidth=1.2)
if any(not math.isnan(v) for v in filt):
    ax.plot(ts, [v if not math.isnan(v) else None for v in filt],
            label="filtered_calibrated_density (Kalman filter)", color="tomato", linewidth=1.8)
ax.set_xlabel("Time (s)")
ax.set_ylabel("Density (g/L)")
ax.set_title("Turbid Vision - Calibrated Density over Time")
ax.legend()
ax.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()

7. Kalman filter growth-rate monitoring

When the Kalman filter is enabled in firmware, the sensor estimates the specific growth rate µ (1/h) alongside a filtered density. These read NaN when the Kalman filter is disabled (enable it from the web interface or over I²C with control command 0x08; disabling is web-interface only).

if not sensor.read_status().job_running:
    sensor.start_job()
    sensor.wait_for_status(sensor.STATUS_HAS_INITIAL, timeout=180)

print(f"{'#':>6}  {'density':>10}  {'filt.dens':>10}  {'u(1/h)':>9}  {'absGR(g/L/h)':>13}")
print("-" * 56)
last = None
t0 = time.monotonic()
while time.monotonic() - t0 < 30:
    n = sensor.reading_number()
    if n != last:
        print(f"{str(n):>6}  {fmt(sensor.calibrated_density()):>10}  "
              f"{fmt(sensor.filtered_calibrated_density()):>10}  "
              f"{fmt(sensor.growth_rate()):>9}  "
              f"{fmt(sensor.calibrated_absolute_growth_rate()):>13}")
        last = n
    time.sleep(1.0)
print("\n(NaN columns mean the Kalman filter is disabled.)")

8. Graceful shutdown

Stop the job and deactivate the laser before disconnecting, then close the bus.

s = sensor.read_status()
print("Before shutdown:", s)

if s.job_running:
    sensor.stop_job()
    sensor.wait_for_status(sensor.STATUS_JOB_RUNNING, timeout=10, clear=True)
    print("Job stopped.")
if s.laser_pwrctl_running:
    sensor.deactivate_laser()
    print("Laser deactivated.")

after = sensor.read_status()
print("After shutdown: ", after)
print("Idle." if not after.job_running and not after.laser_pwrctl_running
      else "WARNING: a subsystem did not stop cleanly.")

sensor.close()
print("Bus closed.")

Library quick reference

CallPurpose
TurbidVision(bus=1)Construct (default address 0x69); use .open() / close() or a with block
is_present()Probe the bus
read_status() -> StatusDecoded status flags
read_all() -> SnapshotFull measurement snapshot
calibrated_density(), measured_reflectance(), …Named float reads (NaN if unavailable)
reading_number()Monotonic reading counter
start_job() / stop_job()Start / stop the OD job
take_blank() / take_cal_reading()Async blank / calibration capture
set_laser_power_pct(pct)Set laser target % and activate
deactivate_laser() / erase_initial()Stop the laser / clear the initial reference
wait_for_status(mask, timeout=…, clear=…)Poll until a status bit sets (or clears)

Status-bit constants live on the class: sensor.STATUS_JOB_RUNNING, STATUS_HAS_BLANK, STATUS_HAS_INITIAL, STATUS_LASER_PWRCTL_RUNNING, STATUS_LASER_STABLE, STATUS_REFLECTANCE_STABLE. For every method, dataclass, and constant, see the Python API reference; for the raw register map and protocol, see the I²C interface reference.