Skip to content

Add temperature function #5

@dmccreary

Description

@dmccreary

Thanks for the driver. I got my DS3231 to tell me the temperature. Would this be of interest to others? I would like to know if this works on other systems.

def read_temperature():
    """Read temperature from DS3231 RTC."""
    # Read temperature registers
    i2c.writeto(DS3231_ADDR, b'\x11')
    temp_data = i2c.readfrom(DS3231_ADDR, 2)
    temp_msb = temp_data[0]
    temp_lsb = temp_data[1]
    
    # Get raw temp value (ignoring sign bit)
    raw_temp = temp_msb & 0x7F  # Strip off sign bit
    
    # 0xD7 & 0x7F = 0x57 = 87 decimal (original value minus sign bit)
    # If sign bit was set, make it negative
    if temp_msb & 0x80:
        raw_temp = raw_temp ^ 0x7F  # Invert the bits
        raw_temp = -(raw_temp + 1)  # Two's complement
    
    # Add fraction from LSB
    frac = (temp_lsb >> 6) * 0.25
    temp_c = raw_temp + frac
    
    # Convert to Fahrenheit
    temp_f = (temp_c * 9.0 / 5.0) + 32.0
    
    print(f"Raw temp (after sign bit removal): {raw_temp}")
    print(f"Temperature: {temp_c}°C = {temp_f}°F")
    
    return temp_f

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions