GLOBAL KNOWLEDGE ARK

Electronics · Optional embedded electronics and a sensor logger

Optional sensor logger: timing, calibration and stale data

A useful logger records what a number means and when it became available. A successful bus transfer can return an old result, and a recent host timestamp can hide stale data. This project makes those distinctions visible with a complete supplied record instead of requiring a sensor purchase or program run.

Lesson preparation and course links

Use the optional first-program/timer ideas and the sensor, conversion and calibration introductions. Signed decoding, timestamp meaning, acceptance/freshness rules and buffer accounting are developed here. The supplied-data route requires no purchase, wiring, simulator or program run.

Back to the Electronics chapter

After reading, you can

Build a reproducible supplied-data logger record with decoded temperature, conversion-completion bounds, host-read time and validity status. Diagnose missing, duplicate and out-of-range records; check conservative freshness, a one-point reference comparison and bounded-buffer loss.

01

Define the measurand, source and acceptance policy

The source model is a TMP117 digital temperature sensor. Its result represents sensor-die temperature under the device’s conversion/averaging behaviour; it is not an instantaneous ambient-temperature measurement. A physical system adds thermal coupling, gradients, self-heating and response delay.

For this supplied-data task, choose a continuous 1 Hz conversion cycle with eight averages, a documented compatible 3.3 V interface, and readiness observations at 10 ms spacing. Each readiness/result association is assumed completed before the next conversion, without an intervening missed conversion. These are explicit fixture assumptions, not proof of an unspecified driver.

The application accepts decoded values from 0 to 50 °C inclusive. That is a rule for reported values, not a guarantee that true ambient temperature lies in that interval. Missing, duplicate, out-of-range or time-invalid records do not refresh last-valid data. A decoded value of 0 °C is a possible measurement and must not serve as an error sentinel.

Use the supplied seven-row record as the complete project route. Its boot/session ID is 7, and recording time 0 is a chosen origin within that boot after configuration; a conversion can already be in progress. The first row does not assert that a new conversion completed immediately at power-on. No sensor, bus, firmware or simulator is run here.

02

Decode signed register data and keep resolution separate

The temperature result is a signed 16-bit two’s-complement integer with scale 1/128 °C per count: 0.0078125 °C. For an unsigned raw word u, use signed=u when u<32768, otherwise signed=u−65536; then T=signed/128 °C.

For 0C88 hexadecimal, u=3208 and T=3208/128=25.0625 °C. For F380, u=62336, signed=−3200 and T=−25 °C. The second is a legal decoded sensor result, but it fails the chosen application range.

Resolution is the spacing between representable values, not the maximum error of the measurement system. The cited TMP117 specification includes a maximum ±0.1 °C accuracy region from −20 to 50 °C under its stated conditions. Do not turn the much finer 1/128 °C increment into an ambient-accuracy promise or add a separate half-LSB term again when an accuracy specification already includes digitization.

Original decode checks for the supplied register words
Raw hexUnsigned integerSigned integerDecoded °CApplication range
0C803200320025.0000Inside
0C883208320825.0625Inside
0C983224322425.1875Inside
F38062336−3200−25.0000Outside
0CA03232323225.2500Inside
03

Preserve conversion evidence through a read-to-clear flag

The temperature register can retain its previous result between conversions. A successful read therefore proves transport success, not that a new conversion occurred. The TMP117 Data_Ready flag is set when the result is updated and is cleared by reading the configuration or temperature register.

A reader must retain the readiness observation and associate it with the corresponding result. Reading the flag, discarding that evidence, and later treating any successful temperature read as new loses the very fact needed for freshness. The association must also precede a following conversion that could replace the result.

This device supplies no native sample sequence or timestamp in the temperature word. attempt_sequence, boot_id and timestamps below are logger metadata. Repeated numeric equality alone cannot prove duplication: two genuine new conversions may have the same value. Here the duplicate row has explicit new_conversion=False evidence.

With the stated 10 ms readiness-observation spacing, completion is bounded between the preceding not-ready observation and the ready observation. These bounds describe conversion completion, not the instant of a physical temperature sample; averaging covers an earlier active interval. The host-read timestamp comes later and has a different meaning.

04

Keep all attempt records, then update last-valid selectively

Each attempt records identity, raw data or an explicit missing state, the completion bounds when known, the later host-read time, new-conversion evidence and status. A failed attempt remains in the diagnostic log. Rejection from last-valid eligibility does not mean silently deleting the attempt.

The supplied record below contains expected teaching data. Blank raw/time fields mean unavailable, not a zero measurement. OK rows are eligible only when new evidence, decoded application range and coherent same-session times also pass. Retain status and both time meanings instead of replacing a missing result with the previous temperature and a new timestamp.

An explicit acceptance rule is: require OK status, present decodable raw data, new-conversion evidence, an in-range decoded value, and valid associated completion bounds at or before host read, all within the same timebase. Then update last-valid from that record. Any failure leaves the prior last-valid unchanged and records the reason.

The diagram shows two uses of the same attempt: every attempt can enter the bounded diagnostic queue; only an eligible record refreshes last-valid. If no eligible record has yet arrived, freshness is unavailable rather than automatically true.

Complete supplied record; all times are recording-relative ms within session 7
AttemptRaw hexDecoded °CCompletion lo…hi msHost read msNew?Status
00C8025.00…1030TrueOK
10C8825.06251000…10101030TrueOK
2———2030FalseMISSING
30C9825.18753000…30103030TrueOK
40C9825.18753000…30104030FalseSTALE_DUPLICATE
5F380-25.05000…50105030TrueRANGE
60CA025.256000…60106030TrueOK
Logging attempts and certifying freshness are different actionsEvery attempt record goes to the bounded diagnostic queue. A separate eligibility check refreshes last-valid only for OK, new, in-range, time-valid records. A failed check preserves the prior last-valid. Freshness uses its completion lower bound. No physical acquisition is represented.All attempts are evidence; eligibility controls freshnessAttempt recordRaw/status and timesEligibility checksOK + new + range + timeUpdate last-validKeep conversion boundsDiagnostic queueEvery attempt enters queueNo refreshKeep previous last-validConservative agenow − completion_loPassFailQueue retention is bounded; overflow/loss and invalid records stay visible.
Every acquisition attempt creates a diagnostic record with raw data/status and times and can enter the bounded queue. In parallel, eligibility requires OK status, a new conversion, an in-range value and valid associated same-session timing. Passing records update last-valid; failures leave it unchanged. Freshness uses the accepted record’s conversion-completion lower bound, not the most recent read time.
05

Use the earliest completion bound for conservative age

For a valid same-session query time now, use maximum possible age=now−completion_lo of the last accepted record. Classify it fresh when that upper age bound is ≤2000 ms. Using host_read_ms instead would make delayed reads look younger than their conversion evidence permits.

At query time 5000 ms, the latest accepted row is attempt 3, whose completion bounds are 3000…3010 ms. Attempt 4 was read at 4030 ms but is an explicit duplicate and does not refresh it. The conservative age bound is 5000−3000=2000 ms, meeting the inclusive policy limit.

At 5001 ms the bound is 2001 ms, so the record fails this conservative freshness policy. That does not prove the unknown actual completion instant makes it older than 2000 ms; it means the available bounds no longer certify the requirement.

Attempt 5 is only read later at 5030 ms. Its −25 °C result is outside the application range and cannot restore last-valid freshness. After eligible attempt 6 is read at 6030 ms, its completion lower bound 6000 ms gives a 30 ms conservative age bound at that read time. Do not use future records when judging an earlier query.

Reset or clock discontinuity starts another time epoch. Recording-relative milliseconds are not synchronized UTC. An actual runtime must follow its wrap-safe API and allowed interval; the chosen storage-field width does not change the runtime counter’s rules.

06

Compare one point without inventing a global calibration

For a separate supplied reference check near 25 °C, take reference 25.000 °C with a stated ±0.020 °C comparison allowance and sensor reading 0C88=25.0625 °C. For this classroom comparison, use the sensor ±0.100 °C allowance under its applicable conditions; the conservative sum is 0.120 °C.

The absolute discrepancy is 0.0625 °C, within the chosen 0.120 °C allowance. This is one-point compatibility with those supplied bounds. It does not establish slope, across-range accuracy, thermal coupling to ambient or a complete measurement-uncertainty evaluation.

Do not automatically subtract 0.0625 °C from all future readings. A correction requires a calibration model and enough appropriate reference evidence. No offset or sensor EEPROM change is applied in this task.

07

Make bounded storage loss visible

For a separate capacity model, choose eight queued attempt records with drop-oldest on overflow. Suppose attempts 0…10 are produced without any consumer drain. This stress case concerns record identities; it does not invent additional temperature measurements beyond the seven-row supplied trace.

After the first eight records, the queue holds 0…7. Inserting 8 drops 0, inserting 9 drops 1, and inserting 10 drops 2. The final queue holds 3…10 and dropped_count=3. Keep attempt sequence and the loss count so the consumer can detect gaps.

A hypothetical packed payload budget uses boot ID u32, attempt sequence u32, completion lower/upper times u32 each, host-read time u32, raw temperature i16 and validity/status flags u16: 5×4+2+2=24 bytes per record, or 192 bytes for eight payloads. Missing-field validity must be represented separately; a placeholder raw bit pattern is ignored when unavailable.

This is a payload-size budget, not a complete binary serialization specification or actual Python RAM measurement. Byte order, flag encoding, framing and field overflow need an implementation contract; queue objects, allocation and filesystem overhead add memory. The displayed table remains the complete supplied-data record for this lesson.

Drop-oldest assumes acquisition keeps producing while consumption stalls. If the producer itself blocks, the failure is missed acquisition rather than a magically growing queue. Flash/filesystem durability through power failure is another property and is not established by an in-memory capacity calculation.

Separate drop-oldest stress case with no consumer drain
After insertionRetained attempt IDsTotal dropped
70…70
81…81
92…92
103…103
08

Complete the project with the evidence route you have

On paper, decode the raw values, apply the eligibility rule, identify the last-valid record at each host-read/query time, perform the one-point comparison, and trace the queue loss. Keep the original rows alongside the derived decisions. This fully exercises the stated supplied-data logger task.

A physical extension would need a documented matched sensor/module, supply and bus pullups/pin ratings, explicit conversion configuration, associated readiness/result reads, a qualified timebase and a recorded test. A simulator would need a stated sensor/timing/failure model. Neither route is required or claimed here.

The result of this project is an explainable record and an acceptance/freshness policy with deliberately missing, duplicate and range cases. It does not establish an instantaneous ambient measurement, a calibrated product or lossless durable storage.

Why a recent read does not refresh the logger

Attempt 3 is a new, in-range 25.1875 °C result with completion bounded 3000…3010 ms and host read 3030 ms. Accept it as last-valid. Attempt 4 repeats that result at 4030 ms with new_conversion=False and STALE_DUPLICATE status, so retain its diagnostic row while leaving last-valid at attempt 3.

At 5000 ms, use the lower completion bound 3000 ms: maximum possible age 2000 ms satisfies the inclusive freshness limit. At 5001 ms, 2001 ms fails the conservative rule. Using attempt 4’s recent host timestamp would have hidden the absence of new-conversion evidence.

The range-failing attempt 5 arrives at 5030 ms and still cannot refresh last-valid. Eligible attempt 6 arrives at 6030 ms and restores a recently completed accepted record. The order of observations matters: attempt 5/6 are unavailable to the earlier 5000 ms query.

Try the reasoning

  1. Decode 0C88 and F380, and explain the application-range result.

    Show the answer and reasoning

    0C88 is 3208/128=25.0625 °C. F380 is unsigned 62336, so signed=62336−65536=−3200 and T=−25 °C. The latter is a valid signed sensor result but outside the chosen 0…50 °C decoded-value acceptance rule.

  2. Does a successful temperature read or an unchanged numeric value prove a new or duplicate sample?

    Show the answer and reasoning

    Neither does alone. The register can retain an old result, and two new conversions can yield equal values. Preserve associated new-conversion evidence through the read-to-clear flag sequence; the duplicate in this fixture is explicitly marked not new.

  3. What do completion bounds and host-read time mean?

    Show the answer and reasoning

    The bounds bracket conversion completion under the readiness-observation assumptions. Host read occurs later. Neither is an instantaneous ambient-sampling time, and metadata sequence/timestamps are supplied by the logger, not the temperature word.

  4. Which record determines freshness at 5000 ms, and what changes at 5001 ms?

    Show the answer and reasoning

    Attempt 3 remains last-valid; attempt 4 was a duplicate. Use completion_lo=3000 ms: at 5000 the upper age bound 2000 ms is fresh by the inclusive rule; at 5001 the bound 2001 ms fails the conservative policy. Actual age is not uniquely known from the bracket.

  5. Can attempt 5 refresh the record at 5030 ms, and when does attempt 6 help?

    Show the answer and reasoning

    Attempt 5 decodes −25 °C and fails the application range, so it does not refresh last-valid. After eligible attempt 6 is read at 6030 ms, its completion lower bound 6000 ms gives a 30 ms maximum-age estimate. Future rows cannot be used for earlier queries.

  6. May missing data be stored as a measured 0 °C, or milliseconds treated as UTC?

    Show the answer and reasoning

    No. Zero is a legal temperature; keep an explicit missing status and unavailable raw value. Recording-relative times belong to their boot/session/timebase. UTC and cross-reset/wrap comparisons require separately established clock/epoch rules.

  7. What does the one-point 25.000/25.0625 °C comparison establish?

    Show the answer and reasoning

    The discrepancy 0.0625 °C is inside the supplied 0.100+0.020=0.120 °C comparison allowance. It establishes one-point compatibility under those assumptions, not an across-range calibration, universal correction or complete ambient-temperature uncertainty.

  8. What remains after 11 undrained insertions into the separate eight-record drop-oldest queue?

    Show the answer and reasoning

    Attempts 3…10 remain and three records were dropped. Keep sequence gaps and dropped_count. The 192-byte figure is eight 24-byte packed payloads only, not total Python/queue/filesystem RAM.

  9. Does 1/128 °C resolution qualify ambient accuracy or durable lossless logging?

    Show the answer and reasoning

    No. Quantization spacing differs from sensor/system accuracy and thermal coupling. A bounded queue with declared drop-oldest loss is not lossless, and its memory calculation does not prove filesystem behaviour during power failure.

What to carry forward

A logger needs evidence of a new result, meaningful time bounds and a policy for invalid or old data. Keep every attempt and diagnostic status, refresh last-valid selectively, and state separately what decoding, reference comparison, buffering and physical measurement establish.

References

Sources supporting this lesson’s explanations and examples.

  1. TMP117 High-Accuracy, Low-Power, Digital Temperature Sensor With SMBus™- and I2C-Compatible InterfaceTexas InstrumentsTechnical documentation · PDFti.comRead source
  2. MicroPython project, runtime maintainer2 sources
    1. time – time related functions — MicroPython v1.26.0 documentationMicroPython project, runtime maintainerTechnical documentationdocs.micropython.orgRead source
    2. Working with filesystems — MicroPython v1.26.0 documentationMicroPython project, runtime maintainerTechnical documentationdocs.micropython.orgRead source