Supplier photo of an assembled infinity mirror light cube illuminated on a dark background.
Supplier photo
Temu affiliate offer ยท Project idea

Build an infinity light cube

Listing specifies 5-volt direct current. Soldering required; battery and glue not included.

View kit on Temu

Tricky Circuit may earn a commission through these links. Product ideas have not been bench-tested by Tricky Circuit and are not verified lesson parts lists.

MCP9808: An Alarm Flag Is Different from a Temperature Reading

A temperature reading can return to normal while an alarm remains active. That is useful when a brief excursion must be noticed, but confusing if software treats every high or low signal as a fresh temperature comparison. This experiment separates the measured number, the device’s limit flags, its alarm status and the voltage on a physical wire.

Serial data (SDA) carries the bus data, and serial clock (SCL) times the transfers. Units used below are volts (V), millimetres (mm), kilohms (kฮฉ, 1,000 ohms), nanofarads (nF, one billionth of a farad), milliseconds (ms) and degrees Celsius (ยฐC).

The exact sensor is the Microchip MCP9808-E/MS in an eight-lead micro small-outline package (MSOP), mounted on a passive 0.65 mm-pitch adapter. The controller is an original Raspberry Pi Pico with RP2040 and MicroPython 1.26.0. The Inter-Integrated Circuit (I2C) bus is the two-wire digital interface used to configure and read the sensor. This is a locally checked design with a complete register driver and injected host tests. It has not been assembled or run on a Pico, and no thermal response or measurement accuracy has been demonstrated.

Parts and the four observations

Part Purpose
MCP9808-E/MS, exact MSOP8 variant Measures its local temperature and produces configurable window/critical alarm behavior.
Passive MSOP8 adapter, 0.65 mm pitch Brings each chip pad to accessible terminals without adding unidentified circuitry.
Original Pico RP2040 Provides the 3.3 V rail, I2C transactions and one alarm input.
Three separate 4.7 kฮฉ resistors Pull SDA, SCL and ALERT high to the same 3.3 V rail.
100 nF ceramic capacitor, at least 10 V Bypasses the chip’s supply locally between pins 8 and 4.
Short leads; optional digital multimeter (DMM) Permit a controlled bench connection and a check of the alarm voltage.

There are four distinct results. The numerical temperature comes from the signed field in register 0x05. Three limit flags occupy the other high bits of that same word. CONFIG, the configuration register, has an alarm-output status bit. Finally, a Pico general-purpose input/output (GPIO) input reads the ALERT wire. The program exposes each result; it does not replace them with one reassuring green label.

These values are read sequentially. A conversion or output transition can occur between accesses, so a momentary pin/status disagreement is not automatically a software bug or proof of a broken sensor. A persistent disagreement deserves inspection. A disconnected ALERT wire can read high through its pull-up even when the chip reports an active alarm.

Exact pins and one voltage domain

MCP9808-E/MS MSOP8 circuit at 3.3 V with original Pico GP4 SDA, GP5 SCL and GP15 ALERT, three 4.7 kฮฉ pullups, 100 nF supply bypass and address pins A2 A1 A0 grounded for 0x18.
Original circuit schematic. Bridges cross without joining; all numbered chip pads belong to the selected MSOP8 package. Verify the passive adapter mapping before applying power.
Sensor physical pin Connection and job
8 VDD; 4 GND Pico 3V3 OUT, physical 36; common ground, physical 18. Fit 100 nF directly across sensor pins 8 and 4.
1 SDA Pico GP4, physical 6, plus its own 4.7 kฮฉ pull-up. SDA carries serial data in both directions.
2 SCL GP5, physical 7, plus its own 4.7 kฮฉ pull-up. SCL carries the controller’s serial clock.
3 ALERT GP15, physical 20, plus its own 4.7 kฮฉ pull-up. The program selects an active-low alarm.
5 A2; 6 A1; 7 A0 All to ground, giving normal seven-bit address 0x18.

The selected chip’s operating supply range is 2.7โ€“5.5 V; its 6.0 V absolute maximum is a stress limit. This circuit deliberately uses 3.3 V for supply and every pull-up. The Pico input is not made 5 V tolerant by connecting a sensor that can itself operate at 5 V. Power the assembly from the Pico rail and Universal Serial Bus (USB), and keep external powered signals away when the controller is unpowered.

ALERT is open-drain: the sensor can pull the line down but needs an external resistor to bring it high when released. At 3.3 V, a 4.7 kฮฉ pull-up supplies at most about 3.3/4700 = 0.70 mA when low, below the datasheet’s 3 mA low-output test condition. That calculation does not qualify long-wire rise time, noise immunity or a modified breakout’s parallel pull-ups.

Check pin 1 orientation and every adapter connection with power disconnected. A printed circuit board (PCB) that adds a regulator, level converter or existing pull-ups is a different circuit and needs its own schematic review. The selected MSOP part has eight pins; a dual flat no-lead (DFN) package also requires its exposed-pad layout and must not be treated as the same physical adapter. The datasheet has a special factory address-code option; this driver deliberately expects the normal 0x18 device and checks its manufacturer/device identification.

Window, hysteresis and a latched alarm

The demonstration limits are TLOWER = 18 ยฐC, TUPPER = 28 ยฐC and TCRIT = 35 ยฐC. A hysteresis setting of 1.5 ยฐC creates different switching boundaries depending on the direction of temperature change. That separation prevents repeated switching around one boundary; it is not extra measurement accuracy.

For the upper boundary in comparator mode, a temperature above 28 ยฐC asserts the output. On cooling, it releases at or below 28 โˆ’ 1.5 = 26.5 ยฐC. The lower boundary is directional too: Figure 5-10 of the datasheet shows assertion below TLOWER โˆ’ THYST = 16.5 ยฐC and comparator release on warming to at least TLOWER. Do not build a symmetric โ€œ18 ยฑ 1.5โ€ rule from the word hysteresis.

In interrupt mode, an ordinary window alarm remains asserted until the controller explicitly acknowledges it by writing CONFIG bit 5. A later temperature read does not perform that acknowledgement. Setting the read-only status bit to zero in a software variable cannot clear the hardware alarm either. The program never acknowledges as a side effect of monitoring.

Synthetic temperature plot above and below the 28 ยฐC upper threshold and 26.5 ยฐC hysteresis release, with comparator and interrupt ALERT waveforms and manual clear; separate critical plot shows forced LOW from 35 ยฐC until below 33.5 ยฐC.
Original synthetic switching plots. The upper episode stays below the critical limit. The separate critical band shows when ALERT is forced LOW; outside it an uncleared window interrupt may still hold LOW. No thermal or electrical waveform was measured.

The critical limit has priority. At TA โ‰ฅ TCRIT, the output is forced to comparator behavior even if interrupt mode was selected. It leaves that override only when TA < TCRIT โˆ’ THYST. An uncleared interrupt can still remain afterwards. Thus an acknowledged clear-command write is not proof that ALERT went high. Read the resulting status and wire again instead of assuming that a successful bus transaction resolved the condition.

Complete driver and deliberate acknowledgements

Download the complete program (ZIP; file: tricky-circuit-batch-006/code/mcp9808-alert-window.py). For interactive use, copy it onto the Pico as mcp9808_alert_window.py, using underscores so it can be imported. The driver verifies manufacturer ID 0x0054 and device ID high byte 0x04; the low byte is the reported revision. It refuses an existing limit lock rather than pretending that a normal write can unlock it.

Configuration disables the output while writing the three limits, selects 0.0625 ยฐC numerical resolution and then enables the chosen active-low mode with 1.5 ยฐC hysteresis. It reads back configuration, limits and resolution. If final setup verification fails, the object is not authorized to produce normal observations. Limit values must be exactly representable in 0.25 ยฐC steps; silently rounding a requested boundary would change the experiment.

"""MCP9808-E/MS on passive adapter, original Pico, MicroPython1.26.0.
Explicit register readbacks; alert acknowledgement is manual, never automatic.
No hardware execution, guaranteed conversion freshness or CRC is claimed.
"""
import math

CONFIG_MASK = 0x07cf  # Exclude read-only status4 and self-clearing clear5.


def encode_limit(celsius):
    if not isinstance(celsius, (int, float)) or not math.isfinite(celsius):
        raise ValueError('Finite temperature limit required')
    if celsius < -40 or celsius > 125 or celsius * 4 != int(celsius * 4):
        raise ValueError('Limit must be -40..125C in exact0.25C steps')
    return (int(celsius * 16) & 0x1fff) & 0x1ffc


def decode_temperature(word):
    if not isinstance(word, int) or not 0 <= word <= 0xffff:
        raise ValueError('Temperature word must contain16 bits')
    temperature = (word & 0x0fff) / 16.0
    if word & 0x1000:
        temperature -= 256.0
    if not -40 <= temperature <= 125:
        raise ValueError('Reported temperature is outside experiment scope')
    return {'temperature_c': temperature,
            'raw_flag_critical': bool(word & 0x8000),
            'raw_flag_upper': bool(word & 0x4000),
            'raw_flag_lower': bool(word & 0x2000)}


class MCP9808:
    def __init__(self, i2c, read_alert, sleep_ms, sleep_us, address=0x18):
        if address != 0x18:
            raise ValueError('This exact experiment straps A2/A1/A0 LOW:0x18')
        self.i2c, self.read_alert = i2c, read_alert
        self.sleep_ms, self.sleep_us, self.address = sleep_ms, sleep_us, address
        self.expected_config = None
        self.limits = {}

    def _read(self, register, size):
        # Separate STOP-delimited pointer and read accesses; no auto-increment.
        self.sleep_us(10)
        if self.i2c.writeto(self.address, bytes([register])) != 1:
            raise OSError('Register pointer was not acknowledged')
        self.sleep_us(10)  # Standard-mode bus-free allowance between accesses.
        data = self.i2c.readfrom(self.address, size)
        if len(data) != size:
            raise OSError('Short register response')
        return data[0] if size == 1 else (data[0] << 8) | data[1]

    def _write(self, register, word, size=2):
        data = bytes([register, word]) if size == 1 else bytes([register, word >> 8, word & 255])
        self.sleep_us(10)
        if self.i2c.writeto(self.address, data) != len(data):
            raise OSError('Register write was not fully acknowledged')

    def configure(self, mode='interrupt', lower=18.0, upper=28.0, critical=35.0):
        if mode not in ('interrupt', 'comparator'):
            raise ValueError('Choose interrupt or comparator')
        limits = {3: encode_limit(lower), 2: encode_limit(upper), 4: encode_limit(critical)}
        if not lower < upper < critical:
            raise ValueError('Need lower < upper < critical')
        self.expected_config = None  # Failed setup cannot authorize observations.
        manufacturer = self._read(6, 2)
        device_revision = self._read(7, 2)
        if manufacturer != 0x0054 or device_revision >> 8 != 0x04:
            raise ValueError('Wrong manufacturer/device identity')
        current = self._read(1, 2)
        if current & 0x00c0:
            raise ValueError('Limit lock present: power-cycle sensor and recheck')
        self._write(1, 0)  # Disable Alert, keep continuous conversion, no locks.
        for register, word in limits.items():
            self._write(register, word)
        self._write(8, 3, 1)  #0.0625C resolution,250ms typical conversion.
        expected = 0x0208 | (1 if mode == 'interrupt' else 0)
        self._write(1, expected)  #1.5C hysteresis, active LOW, all limits enabled.
        self.limits = limits
        self.expected_config = expected
        try:
            self._verify()
            self.sleep_ms(1000)  # Application allowance, NOT a guaranteed tCONV max.
        except BaseException:
            self.expected_config = None
            self.limits = {}
            raise
        return {'mode': mode, 'lower_c': lower, 'upper_c': upper, 'critical_c': critical,
                'manufacturer_id': manufacturer, 'device_id_revision': device_revision}

    def _verify(self):
        if self.expected_config is None:
            raise ValueError('Run a successful configure first')
        config = self._read(1, 2)
        if config & CONFIG_MASK != self.expected_config:
            raise ValueError('CONFIG_CHANGED_RESTART_REQUIRED')
        for register, word in self.limits.items():
            if self._read(register, 2) != word:
                raise ValueError('LIMIT_CHANGED_RESTART_REQUIRED')
        if self._read(8, 1) != 3:
            raise ValueError('RESOLUTION_CHANGED_RESTART_REQUIRED')
        return config

    def observe(self):
        config = self._verify()
        result = decode_temperature(self._read(5, 2))
        pin = self.read_alert()
        if pin not in (0, 1):
            raise ValueError('Alert pin must be0 or1')
        asserted = bool(config & 0x10)
        result.update(status='READ_COMPLETE', config_alert_asserted=asserted,
                      alert_pin_low=(pin == 0), pin_status_disagree=(asserted != (pin == 0)),
                      config_word=config, freshness_independently_verified=False)
        return result

    def acknowledge(self):
        self._verify()
        if not self.expected_config & 1:
            raise ValueError('Comparator mode is not cleared by an interrupt acknowledgement')
        # Write owned configuration, never copy read-only status or set locks.
        self._write(1, self.expected_config | 0x20)
        result = self.observe()
        result['ack_write_completed'] = True
        return result  # A critical condition can keep Alert active despite this write.


def monitor(sensor, sleep_ms, emit=print, cycles=None):
    count = 0
    while cycles is None or count < cycles:
        try:
            emit(sensor.observe())
        except (OSError, ValueError) as exc:
            emit({'status': 'BUS_OR_CONFIG_ERROR', 'temperature_c': None,
                  'config_alert_asserted': None, 'alert_pin_low': None, 'error': str(exc)})
        count += 1
        sleep_ms(1000)


def connect(mode='interrupt', lower=18.0, upper=28.0, critical=35.0):
    from machine import Pin, SoftI2C
    from time import sleep_ms, sleep_us
    bus = SoftI2C(sda=Pin(4), scl=Pin(5), freq=100000, timeout=50000)
    sensor = MCP9808(bus, Pin(15, Pin.IN).value, sleep_ms, sleep_us)
    print(sensor.configure(mode, lower, upper, critical))
    return sensor


def main():
    from time import sleep_ms
    sensor = connect()
    print('Manual interrupt acknowledgement only. READ_COMPLETE is not a freshness certificate.')
    monitor(sensor, sleep_ms)


if __name__ == '__main__':
    main()

The driver uses a fresh pointer for every register and does not assume sequential register auto-increment. The 100 kHz software bus requests ten microseconds between STOP-delimited accesses. A pointer acknowledgement must contain one byte; a normal 16-bit register write must acknowledge three bytes including its pointer. A short reply, lost acknowledgement or changed configuration produces an error with absent current data.

The temperature field is signed separately from its three flag bits: mask the lower 12 bits and divide by 16, then subtract 256 ยฐC when the sign bit is set. For example, 0x1FB0 represents โˆ’5 ยฐC before adding any limit flags. Keep the hardware flags as separate values and interpret their documented hysteresis/critical rules; they are not flags recalculated from a rounded display number.

To use the console, a readโ€“evaluateโ€“print loop (REPL), import the file and retain the sensor object:

import mcp9808_alert_window as lab
from time import sleep_ms
s = lab.connect('interrupt', lower=18, upper=28, critical=35)
lab.monitor(s, sleep_ms)  # Ctrl-C returns to this console.
# After inspecting the condition, explicitly request acknowledgement:
print(s.acknowledge())

Use lab.connect(‘comparator’, …) in a separately labelled trial to compare modes. Starting or reconfiguring this experiment deliberately changes the alarm configuration and its observation context; it is not a method for preserving a production alarm history. Acknowledge refuses comparator mode, and in interrupt mode writes the owned configuration plus the self-clearing clear bit without copying read-only status or setting lock bits.

Honest freshness and error limits

The selected resolution has a typical 250 ms conversion interval. The one-second setup wait is an application allowance, not a guaranteed maximum conversion time. This interface supplies no conversion sequence number or ready flag in this driver, so repeated reads are not independent evidence of a new sample. READ_COMPLETE means the register transaction completed; freshness_independently_verified remains false.

Numerical resolution is not accuracy. The manufacturer’s temperature-error limits depend on range and conditions; its headline ยฑ0.5 ยฐC range is narrower than the full operating span. Our wiring, thermal placement and software have not established any physical error bound. The chip measures its local temperature, which can differ from air elsewhere or be affected by heat from a nearby board.

Every observation verifies the owned configuration, limits and resolution. A sensor power reset normally restores different defaults and yields RESTART_REQUIRED instead of a plausible stale number. Restore correct power and restart the experiment explicitly. Bus failures print no current temperature or alarm conclusion; restoring communication may restore readings, but cannot prove that a plausible corrupted word or an undetected frozen conversion is healthy. The data protocol here has no cyclic redundancy check (CRC), an extra integrity code used by some interfaces to detect corrupted messages.

A controlled procedure without a hot-air experiment

  1. Inspect the exact chip and passive adapter, check power-off continuity, then verify the 3.3 V rail and the released ALERT voltage. Record physical revision markings and the identification values if available.
  2. Run the interrupt trial at room temperature. Record numerical temperature, three raw flags, CONFIG status and pin state separately. Do not mark identical repeated numbers as fresh conversions merely because the bus answered.
  3. Choose boundaries around the observed room temperature, in exact quarter-degree steps and with lower < upper < critical. A labelled second configuration can place TUPPER just below the current value to assert an alarm without a high-temperature heat source.
  4. Compare comparator and interrupt trials while gently changing the sensor’s local environment, keeping connections dry and the supply stable. Wait for thermal settling. In interrupt mode, after the ordinary window condition is gone, inspect the still-active alarm before issuing s.acknowledge(). Record its actual readback.
  5. For the critical rule, select a separate valid set of room-temperature boundaries with TCRIT below the current reading. An acknowledgement should not force a release while the critical condition controls the output. Reconfigure a normal trial afterwards; this deliberate threshold change is not an independent temperature measurement.
  6. Check the lower-boundary behavior in a separately labelled trial, accounting for its direction and hysteresis. Adjust thresholds to the available controlled temperature range rather than assuming the environment will reach the original 16.5 ยฐC example.
  7. With power off, disconnect the ALERT wire and restore the assembly. Its pull-up can now read high while the chip reports an active alarm. Restore the wire after demonstrating why a high input alone is not a health certificate.
  8. Use the host fault cases for short replies and altered registers. If intentionally power-cycling the sensor, switch off the whole common-powered assembly and start again; do not inject a powered bus into an unpowered part.

The blank observation sheet (ZIP; file: tricky-circuit-batch-006/code/mcp9808-alert-window-observations-blank.csv) has no measured results. The 40 author host checks execute the actual supplied driver and loop with a register/acknowledgement fixture, signed numbers, manual clear, critical-override traces, changed configuration, locks, malformed replies and setup failures. The injected traces demonstrate software responses to specified conditions; they do not simulate the chip’s analog temperature acquisition or prove an alarm latency on hardware.

Challenge: The display says 27 ยฐC, below the selected 28 ยฐC upper limit, but ALERT is low. Is the sensor broken? Answer: Not necessarily. It may be a latched interrupt from an earlier excursion, comparator hysteresis during cooling, a critical override under different settings, a transient between sequential reads, or a wiring problem. Inspect the saved configuration, raw flags, status and actual pin before deciding what the low wire means.

Primary sources and related work

Reviewed on 20 October 2026. No separate applicable MCP9808 errata sheet was identified in the checked manufacturer documentation and targeted official search; absence is not guaranteed. The source’s alternate factory address is not silently scanned or substituted. This alarm-history experiment adds a different outcome from existing temperature-display lessons. Continue with the electronics lessons for the basic sensor and logic vocabulary.

๐Ÿ“กBroadcast the signal โ€” amplify the connection.

Leave a Reply

Temu affiliate offers

Find your next electronics project

Explore these do-it-yourself project kits. Check the selected option, included parts and instructions on each offer.

Tricky Circuit may earn a commission if you buy through these Temu affiliate links. These are product ideas; they have not been bench-tested by Tricky Circuit and are not verified lesson parts lists.

Supplier photo of a breadboard, jumper wires and assorted electronic components in a plastic storage case.

Supplier product photo

Try breadboard experiments

Breadboard, wires and assorted parts. Arduino controller board not included.

View kit on Temu

Supplier photo of an assembled blue surface-mount soldering practice board with a circular ring of small lights.

Supplier product photo

Solder a chasing-light board

Surface-mount soldering practice. Battery and battery holder not included.

View kit on Temu

Supplier photo of an assembled two-wheeled line-following car with a blue circuit board, two motors and an empty battery holder.

Supplier product photo

Build a line-following car

Soldering and assembly required. Check battery and track requirements before buying.

View kit on Temu