Skip to content

AM2320 driver does not handle negative temperatures correctly #1

Closed
@jerryneedell

Description

@jerryneedell

The AM2320 sends a 16 bit temperature value with the MSB indicating sighn and the low 15 bits indicating magnitude. The driver as written does not handle negative values correctly.
I put the sensor in a freezer:

Temperature:  0.2
Humidity:  14.5
Temperature:  0.1
Humidity:  14.6
Temperature:  0.1
Humidity:  14.6
Temperature:  0.0
Humidity:  14.7
Temperature:  3276.9
Humidity:  14.8
Temperature:  3276.9
Humidity:  14.8
Temperature:  3277.0

A simple fix is to change

def temperature(self):
        """The measured temperature in celsius."""
        temperature = struct.unpack(">H", self._read_register(AM2320_REG_TEMP_H, 2))[0]
        return temperature/10.0

to

def temperature(self):
        """The measured temperature in celsius."""
        temperature = struct.unpack(">H", self._read_register(AM2320_REG_TEMP_H, 2))[0]
        if temperature >= 32768:
            temperature = 32768 - temperature
        return temperature/10.0

I tried this in the freezer

Temperature:  0.1
Humidity:  17.6
Temperature:  0.1
Humidity:  17.7
Temperature:  0.0
Humidity:  17.7
Temperature:  -0.1
Humidity:  17.8
Temperature:  -0.1
Humidity:  17.9
Temperature:  -0.2
Humidity:  17.9
Temperature:  -0.3
Humidity:  18.0
Temperature:  -0.3
Humidity:  18.0
Temperature:  -0.4
Humidity:  18.1
Temperature:  -0.4

If you concur with this change, I can put in a PR.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions