drivers: sensor: nxp_temp_kinetis: fix potential overflow

Fix a potential 32 bit multiplication overflow (muliplying by 10000
instead of 1000000) and change the calculations and units accordingly.

Improve the code readability and traceability towards NXP AN3031 by
using the same variable name as in the application note.

Signed-off-by: Henrik Brix Andersen <hebad@vestas.com>
This commit is contained in:
Henrik Brix Andersen 2020-03-20 14:13:40 +01:00 committed by Maureen Helm
commit 2a6aa0be88

View file

@ -72,10 +72,10 @@ static int temp_kinetis_channel_get(struct device *dev,
struct temp_kinetis_data *data = dev->driver_data; struct temp_kinetis_data *data = dev->driver_data;
u16_t adcr_vdd = BIT_MASK(config->adc_seq.resolution); u16_t adcr_vdd = BIT_MASK(config->adc_seq.resolution);
u16_t adcr_temp25; u16_t adcr_temp25;
s32_t temp_mc; s32_t temp_cc;
s32_t vdd_mv; s32_t vdd_mv;
int slope_uv; int slope_uv;
u16_t m; u16_t adcr_100m;
if (chan != SENSOR_CHAN_VOLTAGE && chan != SENSOR_CHAN_DIE_TEMP) { if (chan != SENSOR_CHAN_VOLTAGE && chan != SENSOR_CHAN_DIE_TEMP) {
return -ENOTSUP; return -ENOTSUP;
@ -100,14 +100,14 @@ static int temp_kinetis_channel_get(struct device *dev,
slope_uv = config->slope_hot_uv; slope_uv = config->slope_hot_uv;
} }
/* m x 1000 */ adcr_100m = (adcr_vdd * slope_uv) / (vdd_mv * 10);
m = (adcr_vdd * slope_uv) / vdd_mv;
/* Temperature in milli degrees Celsius */ /* Temperature in centi degrees Celsius */
temp_mc = 25000 - ((data->buffer[0] - adcr_temp25) * 1000000) / m; temp_cc = 2500 -
(((data->buffer[0] - adcr_temp25) * 10000) / adcr_100m);
val->val1 = temp_mc / 1000; val->val1 = temp_cc / 100;
val->val2 = (temp_mc % 1000) * 1000; val->val2 = (temp_cc % 100) * 10000;
return 0; return 0;
} }