From aceaa9b83e55f62691fe85a67df6745ed512ac6a Mon Sep 17 00:00:00 2001 From: Marian Buschsieweke Date: Wed, 31 May 2023 20:05:11 +0200 Subject: [PATCH] drivers/mq3: avoid use of floats --- drivers/include/mq3.h | 8 ++++---- drivers/mq3/mq3.c | 16 ++++++++++------ 2 files changed, 14 insertions(+), 10 deletions(-) diff --git a/drivers/include/mq3.h b/drivers/include/mq3.h index cac5b135ef602..fac2275fb6342 100644 --- a/drivers/include/mq3.h +++ b/drivers/include/mq3.h @@ -50,8 +50,8 @@ typedef struct { * @param[out] dev device descriptor of an MQ-3 sensor * @param[in] adc_line the ADC device the sensor is connected to * - * @return 0 on success - * @return -1 on error + * @retval 0 success + * @retval -1 failure */ int mq3_init(mq3_t *dev, adc_t adc_line); @@ -62,7 +62,7 @@ int mq3_init(mq3_t *dev, adc_t adc_line); * * @return the raw sensor value, between 0 and MQ3_MAX_RAW_VALUE */ -int mq3_read_raw(const mq3_t *dev); +int16_t mq3_read_raw(const mq3_t *dev); /** * @brief Read the scaled sensor value of PPM of alcohol @@ -71,7 +71,7 @@ int mq3_read_raw(const mq3_t *dev); * * @return the scaled sensor value in PPM of alcohol */ -int mq3_read(const mq3_t *dev); +int16_t mq3_read(const mq3_t *dev); #ifdef __cplusplus } diff --git a/drivers/mq3/mq3.c b/drivers/mq3/mq3.c index d89f92564ea27..d8fd2c52f85de 100644 --- a/drivers/mq3/mq3.c +++ b/drivers/mq3/mq3.c @@ -19,10 +19,14 @@ */ #include "mq3.h" +#include "macros/math.h" #define PRECISION ADC_RES_10BIT -#define MIN (100U) /* TODO: calibrate to useful value */ -#define FACTOR (2.33f) /* TODO: calibrate to useful value */ +/* TODO: calibrate to useful value */ +#define MIN (100U) +/* TODO: calibrate to useful value */ +#define SHIFT (12U) +#define FACTOR DIV_ROUND(233U << SHIFT, 100) int mq3_init(mq3_t *dev, adc_t adc_line) { @@ -30,14 +34,14 @@ int mq3_init(mq3_t *dev, adc_t adc_line) return adc_init(dev->adc_line); } -int mq3_read_raw(const mq3_t *dev) +int16_t mq3_read_raw(const mq3_t *dev) { return adc_sample(dev->adc_line, PRECISION); } -int mq3_read(const mq3_t *dev) +int16_t mq3_read(const mq3_t *dev) { - float res = mq3_read_raw(dev); + uint32_t res = mq3_read_raw(dev); res = (res > MIN) ? res - MIN : 0; - return (int)(res * FACTOR); + return (res * FACTOR) >> SHIFT; }