Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 25 additions & 2 deletions lib/ism330dl/ism330dl/device.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ def __init__(self, i2c, address=ISM330DL_I2C_DEFAULT_ADDR):
self._accel_scale = ACCEL_FS_2G
self._gyro_scale = GYRO_FS_250DPS

self._temp_gain = 1.0
self._temp_offset = 0.0

self.check_device()
self.reset()
self.configure_accel(ACCEL_ODR_104HZ, ACCEL_FS_2G)
Expand Down Expand Up @@ -149,8 +152,28 @@ def gyroscope_rads(self):
return tuple(v * pi / 180.0 for v in dps)

def temperature_c(self):
raw = self.temperature_raw()
return TEMP_OFFSET + raw / TEMP_SENSITIVITY
factory = TEMP_OFFSET + self.temperature_raw() / TEMP_SENSITIVITY
return self._temp_gain * factory + self._temp_offset

def set_temp_offset(self, offset_c):
"""Set a temperature offset in °C (gain remains 1.0)."""
self._temp_gain = 1.0
self._temp_offset = float(offset_c)

def calibrate_temperature(self, ref_low, measured_low, ref_high, measured_high):
"""Two-point calibration from reference measurements.

Args:
ref_low: reference temperature at the low point (°C).
measured_low: sensor reading at the low point (°C).
ref_high: reference temperature at the high point (°C).
measured_high: sensor reading at the high point (°C).
"""
delta = float(measured_high - measured_low)
if delta == 0.0:
raise ValueError("measured_low and measured_high must differ")
self._temp_gain = float(ref_high - ref_low) / delta
self._temp_offset = float(ref_low) - self._temp_gain * float(measured_low)

def orientation(self):
ax, ay, az = self.acceleration_g()
Expand Down
27 changes: 27 additions & 0 deletions tests/scenarios/ism330dl.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,33 @@ tests:
expect_true: true
mode: [mock]

- name: "Temperature offset shifts reading"
action: script
script: |
dev.set_temp_offset(-2.5)
result = abs(dev.temperature_c() - 22.5) < 0.1
expect_true: true
mode: [mock]

- name: "Temperature with two-point calibration"
action: script
script: |
dev.calibrate_temperature(20.0, 25.0, 30.0, 35.0)
result = dev.temperature_c()
expect_range: [19.0, 21.0]
mode: [mock]

- name: "Calibration rejects equal measurements"
action: script
script: |
try:
dev.calibrate_temperature(20.0, 25.0, 30.0, 25.0)
result = False
except ValueError:
result = True
expect_true: true
mode: [mock]

- name: "Temperature in plausible range"
action: call
method: temperature_c
Expand Down
Loading