Skip to content

Commit 724e8af

Browse files
paulfertsergroeck
authored andcommitted
hwmon: (tmp421) fix rounding for negative values
Old code produces -24999 for 0b1110011100000000 input in standard format due to always rounding up rather than "away from zero". Use the common macro for division, unify and simplify the conversion code along the way. Fixes: 9410700 ("hwmon: Add driver for Texas Instruments TMP421/422/423 sensor chips") Signed-off-by: Paul Fertser <[email protected]> Link: https://lore.kernel.org/r/[email protected] Signed-off-by: Guenter Roeck <[email protected]>
1 parent 540effa commit 724e8af

File tree

1 file changed

+8
-16
lines changed

1 file changed

+8
-16
lines changed

drivers/hwmon/tmp421.c

Lines changed: 8 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -100,23 +100,17 @@ struct tmp421_data {
100100
s16 temp[4];
101101
};
102102

103-
static int temp_from_s16(s16 reg)
103+
static int temp_from_raw(u16 reg, bool extended)
104104
{
105105
/* Mask out status bits */
106106
int temp = reg & ~0xf;
107107

108-
return (temp * 1000 + 128) / 256;
109-
}
110-
111-
static int temp_from_u16(u16 reg)
112-
{
113-
/* Mask out status bits */
114-
int temp = reg & ~0xf;
115-
116-
/* Add offset for extended temperature range. */
117-
temp -= 64 * 256;
108+
if (extended)
109+
temp = temp - 64 * 256;
110+
else
111+
temp = (s16)temp;
118112

119-
return (temp * 1000 + 128) / 256;
113+
return DIV_ROUND_CLOSEST(temp * 1000, 256);
120114
}
121115

122116
static int tmp421_update_device(struct tmp421_data *data)
@@ -172,10 +166,8 @@ static int tmp421_read(struct device *dev, enum hwmon_sensor_types type,
172166

173167
switch (attr) {
174168
case hwmon_temp_input:
175-
if (tmp421->config & TMP421_CONFIG_RANGE)
176-
*val = temp_from_u16(tmp421->temp[channel]);
177-
else
178-
*val = temp_from_s16(tmp421->temp[channel]);
169+
*val = temp_from_raw(tmp421->temp[channel],
170+
tmp421->config & TMP421_CONFIG_RANGE);
179171
return 0;
180172
case hwmon_temp_fault:
181173
/*

0 commit comments

Comments
 (0)