Skip to content

Commit dcff99e

Browse files
Leonard Pollaknashif
authored andcommitted
drivers: sensor: sgp40: fix rounding errors
This fixes/improves the rounding errors that are introduced through the truncation of integer division. Signed-off-by: Leonard Pollak <[email protected]>
1 parent f2f99c0 commit dcff99e

File tree

1 file changed

+4
-2
lines changed

1 file changed

+4
-2
lines changed

drivers/sensor/sgp40/sgp40.c

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,8 @@ static int sgp40_attr_set(const struct device *dev,
7171
int32_t tmp;
7272

7373
tmp = CLAMP(val->val1, SGP40_COMP_MIN_T, SGP40_COMP_MAX_T);
74-
t_ticks = ((tmp + 45) * 65535) / 175;
74+
/* adding +87 to avoid most rounding errors through truncation */
75+
t_ticks = (((tmp + 45) * 65535) + 87) / 175;
7576
sys_put_be16(t_ticks, data->t_param);
7677
data->t_param[2] = sgp40_compute_crc(t_ticks);
7778
}
@@ -82,7 +83,8 @@ static int sgp40_attr_set(const struct device *dev,
8283
int32_t tmp;
8384

8485
tmp = CLAMP(val->val1, SGP40_COMP_MIN_RH, SGP40_COMP_MAX_RH);
85-
rh_ticks = (tmp * 65535) / 100;
86+
/* adding +50 to eliminate rounding errors through truncation */
87+
rh_ticks = ((tmp * 65535) + 50) / 100;
8688
sys_put_be16(rh_ticks, data->rh_param);
8789
data->rh_param[2] = sgp40_compute_crc(rh_ticks);
8890
}

0 commit comments

Comments
 (0)