xref: /linux/drivers/iio/chemical/bme680_core.c (revision cdd30ebb1b9f36159d66f088b61aee264e649d7a)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Bosch BME680 - Temperature, Pressure, Humidity & Gas Sensor
4  *
5  * Copyright (C) 2017 - 2018 Bosch Sensortec GmbH
6  * Copyright (C) 2018 Himanshu Jha <himanshujha199640@gmail.com>
7  *
8  * Datasheet:
9  * https://ae-bst.resource.bosch.com/media/_tech/media/datasheets/BST-BME680-DS001-00.pdf
10  */
11 #include <linux/bitfield.h>
12 #include <linux/cleanup.h>
13 #include <linux/delay.h>
14 #include <linux/device.h>
15 #include <linux/log2.h>
16 #include <linux/module.h>
17 #include <linux/regmap.h>
18 
19 #include <linux/iio/buffer.h>
20 #include <linux/iio/iio.h>
21 #include <linux/iio/sysfs.h>
22 #include <linux/iio/trigger_consumer.h>
23 #include <linux/iio/triggered_buffer.h>
24 
25 #include <linux/unaligned.h>
26 
27 #include "bme680.h"
28 
29 /* 1st set of calibration data */
30 enum {
31 	/* Temperature calib indexes */
32 	T2_LSB = 0,
33 	T3 = 2,
34 	/* Pressure calib indexes */
35 	P1_LSB = 4,
36 	P2_LSB = 6,
37 	P3 = 8,
38 	P4_LSB = 10,
39 	P5_LSB = 12,
40 	P7 = 14,
41 	P6 = 15,
42 	P8_LSB = 18,
43 	P9_LSB = 20,
44 	P10 = 22,
45 };
46 
47 /* 2nd set of calibration data */
48 enum {
49 	/* Humidity calib indexes */
50 	H2_MSB = 0,
51 	H1_LSB = 1,
52 	H3 = 3,
53 	H4 = 4,
54 	H5 = 5,
55 	H6 = 6,
56 	H7 = 7,
57 	/* Stray T1 calib index */
58 	T1_LSB = 8,
59 	/* Gas heater calib indexes */
60 	GH2_LSB = 10,
61 	GH1 = 12,
62 	GH3 = 13,
63 };
64 
65 /* 3rd set of calibration data */
66 enum {
67 	RES_HEAT_VAL = 0,
68 	RES_HEAT_RANGE = 2,
69 	RANGE_SW_ERR = 4,
70 };
71 
72 struct bme680_calib {
73 	u16 par_t1;
74 	s16 par_t2;
75 	s8  par_t3;
76 	u16 par_p1;
77 	s16 par_p2;
78 	s8  par_p3;
79 	s16 par_p4;
80 	s16 par_p5;
81 	s8  par_p6;
82 	s8  par_p7;
83 	s16 par_p8;
84 	s16 par_p9;
85 	u8  par_p10;
86 	u16 par_h1;
87 	u16 par_h2;
88 	s8  par_h3;
89 	s8  par_h4;
90 	s8  par_h5;
91 	u8  par_h6;
92 	s8  par_h7;
93 	s8  par_gh1;
94 	s16 par_gh2;
95 	s8  par_gh3;
96 	u8  res_heat_range;
97 	s8  res_heat_val;
98 	s8  range_sw_err;
99 };
100 
101 /* values of CTRL_MEAS register */
102 enum bme680_op_mode {
103 	BME680_MODE_SLEEP = 0,
104 	BME680_MODE_FORCED = 1,
105 };
106 
107 enum bme680_scan {
108 	BME680_TEMP,
109 	BME680_PRESS,
110 	BME680_HUMID,
111 	BME680_GAS,
112 };
113 
114 struct bme680_data {
115 	struct regmap *regmap;
116 	struct bme680_calib bme680;
117 	struct mutex lock; /* Protect multiple serial R/W ops to device. */
118 	u8 oversampling_temp;
119 	u8 oversampling_press;
120 	u8 oversampling_humid;
121 	u8 preheat_curr_mA;
122 	u16 heater_dur;
123 	u16 heater_temp;
124 
125 	struct {
126 		s32 chan[4];
127 		aligned_s64 ts;
128 	} scan;
129 
130 	union {
131 		u8 buf[BME680_NUM_BULK_READ_REGS];
132 		unsigned int check;
133 		__be16 be16;
134 		u8 bme680_cal_buf_1[BME680_CALIB_RANGE_1_LEN];
135 		u8 bme680_cal_buf_2[BME680_CALIB_RANGE_2_LEN];
136 		u8 bme680_cal_buf_3[BME680_CALIB_RANGE_3_LEN];
137 	};
138 };
139 
140 static const struct regmap_range bme680_volatile_ranges[] = {
141 	regmap_reg_range(BME680_REG_MEAS_STAT_0, BME680_REG_GAS_R_LSB),
142 	regmap_reg_range(BME680_REG_STATUS, BME680_REG_STATUS),
143 	regmap_reg_range(BME680_T2_LSB_REG, BME680_GH3_REG),
144 };
145 
146 static const struct regmap_access_table bme680_volatile_table = {
147 	.yes_ranges	= bme680_volatile_ranges,
148 	.n_yes_ranges	= ARRAY_SIZE(bme680_volatile_ranges),
149 };
150 
151 const struct regmap_config bme680_regmap_config = {
152 	.reg_bits = 8,
153 	.val_bits = 8,
154 	.max_register = 0xef,
155 	.volatile_table = &bme680_volatile_table,
156 	.cache_type = REGCACHE_RBTREE,
157 };
158 EXPORT_SYMBOL_NS(bme680_regmap_config, "IIO_BME680");
159 
160 static const struct iio_chan_spec bme680_channels[] = {
161 	{
162 		.type = IIO_TEMP,
163 		/* PROCESSED maintained for ABI backwards compatibility */
164 		.info_mask_separate = BIT(IIO_CHAN_INFO_PROCESSED) |
165 				      BIT(IIO_CHAN_INFO_RAW) |
166 				      BIT(IIO_CHAN_INFO_SCALE) |
167 				      BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO),
168 		.scan_index = 0,
169 		.scan_type = {
170 			.sign = 's',
171 			.realbits = 16,
172 			.storagebits = 16,
173 			.endianness = IIO_CPU,
174 		},
175 	},
176 	{
177 		.type = IIO_PRESSURE,
178 		/* PROCESSED maintained for ABI backwards compatibility */
179 		.info_mask_separate = BIT(IIO_CHAN_INFO_PROCESSED) |
180 				      BIT(IIO_CHAN_INFO_RAW) |
181 				      BIT(IIO_CHAN_INFO_SCALE) |
182 				      BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO),
183 		.scan_index = 1,
184 		.scan_type = {
185 			.sign = 'u',
186 			.realbits = 32,
187 			.storagebits = 32,
188 			.endianness = IIO_CPU,
189 		},
190 	},
191 	{
192 		.type = IIO_HUMIDITYRELATIVE,
193 		/* PROCESSED maintained for ABI backwards compatibility */
194 		.info_mask_separate = BIT(IIO_CHAN_INFO_PROCESSED) |
195 				      BIT(IIO_CHAN_INFO_RAW) |
196 				      BIT(IIO_CHAN_INFO_SCALE) |
197 				      BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO),
198 		.scan_index = 2,
199 		.scan_type = {
200 			.sign = 'u',
201 			.realbits = 32,
202 			.storagebits = 32,
203 			.endianness = IIO_CPU,
204 		},
205 	},
206 	{
207 		.type = IIO_RESISTANCE,
208 		.info_mask_separate = BIT(IIO_CHAN_INFO_PROCESSED),
209 		.scan_index = 3,
210 		.scan_type = {
211 			.sign = 'u',
212 			.realbits = 32,
213 			.storagebits = 32,
214 			.endianness = IIO_CPU,
215 		},
216 	},
217 	IIO_CHAN_SOFT_TIMESTAMP(4),
218 	{
219 		.type = IIO_CURRENT,
220 		.info_mask_separate = BIT(IIO_CHAN_INFO_PROCESSED),
221 		.output = 1,
222 		.scan_index = -1,
223 	},
224 };
225 
bme680_read_calib(struct bme680_data * data,struct bme680_calib * calib)226 static int bme680_read_calib(struct bme680_data *data,
227 			     struct bme680_calib *calib)
228 {
229 	struct device *dev = regmap_get_device(data->regmap);
230 	unsigned int tmp_msb, tmp_lsb;
231 	int ret;
232 
233 	ret = regmap_bulk_read(data->regmap, BME680_T2_LSB_REG,
234 			       data->bme680_cal_buf_1,
235 			       sizeof(data->bme680_cal_buf_1));
236 	if (ret < 0) {
237 		dev_err(dev, "failed to read 1st set of calib data;\n");
238 		return ret;
239 	}
240 
241 	calib->par_t2 = get_unaligned_le16(&data->bme680_cal_buf_1[T2_LSB]);
242 	calib->par_t3 = data->bme680_cal_buf_1[T3];
243 	calib->par_p1 = get_unaligned_le16(&data->bme680_cal_buf_1[P1_LSB]);
244 	calib->par_p2 = get_unaligned_le16(&data->bme680_cal_buf_1[P2_LSB]);
245 	calib->par_p3 = data->bme680_cal_buf_1[P3];
246 	calib->par_p4 = get_unaligned_le16(&data->bme680_cal_buf_1[P4_LSB]);
247 	calib->par_p5 = get_unaligned_le16(&data->bme680_cal_buf_1[P5_LSB]);
248 	calib->par_p7 = data->bme680_cal_buf_1[P7];
249 	calib->par_p6 = data->bme680_cal_buf_1[P6];
250 	calib->par_p8 = get_unaligned_le16(&data->bme680_cal_buf_1[P8_LSB]);
251 	calib->par_p9 = get_unaligned_le16(&data->bme680_cal_buf_1[P9_LSB]);
252 	calib->par_p10 = data->bme680_cal_buf_1[P10];
253 
254 	ret = regmap_bulk_read(data->regmap, BME680_H2_MSB_REG,
255 			       data->bme680_cal_buf_2,
256 			       sizeof(data->bme680_cal_buf_2));
257 	if (ret < 0) {
258 		dev_err(dev, "failed to read 2nd set of calib data;\n");
259 		return ret;
260 	}
261 
262 	tmp_lsb = data->bme680_cal_buf_2[H1_LSB];
263 	tmp_msb = data->bme680_cal_buf_2[H1_LSB + 1];
264 	calib->par_h1 = (tmp_msb << BME680_HUM_REG_SHIFT_VAL) |
265 			(tmp_lsb & BME680_BIT_H1_DATA_MASK);
266 
267 	tmp_msb = data->bme680_cal_buf_2[H2_MSB];
268 	tmp_lsb = data->bme680_cal_buf_2[H2_MSB + 1];
269 	calib->par_h2 = (tmp_msb << BME680_HUM_REG_SHIFT_VAL) |
270 			(tmp_lsb >> BME680_HUM_REG_SHIFT_VAL);
271 
272 	calib->par_h3 = data->bme680_cal_buf_2[H3];
273 	calib->par_h4 = data->bme680_cal_buf_2[H4];
274 	calib->par_h5 = data->bme680_cal_buf_2[H5];
275 	calib->par_h6 = data->bme680_cal_buf_2[H6];
276 	calib->par_h7 = data->bme680_cal_buf_2[H7];
277 	calib->par_t1 = get_unaligned_le16(&data->bme680_cal_buf_2[T1_LSB]);
278 	calib->par_gh2 = get_unaligned_le16(&data->bme680_cal_buf_2[GH2_LSB]);
279 	calib->par_gh1 = data->bme680_cal_buf_2[GH1];
280 	calib->par_gh3 = data->bme680_cal_buf_2[GH3];
281 
282 	ret = regmap_bulk_read(data->regmap, BME680_REG_RES_HEAT_VAL,
283 			       data->bme680_cal_buf_3,
284 			       sizeof(data->bme680_cal_buf_3));
285 	if (ret < 0) {
286 		dev_err(dev, "failed to read 3rd set of calib data;\n");
287 		return ret;
288 	}
289 
290 	calib->res_heat_val = data->bme680_cal_buf_3[RES_HEAT_VAL];
291 
292 	calib->res_heat_range = FIELD_GET(BME680_RHRANGE_MASK,
293 					  data->bme680_cal_buf_3[RES_HEAT_RANGE]);
294 
295 	calib->range_sw_err = FIELD_GET(BME680_RSERROR_MASK,
296 					data->bme680_cal_buf_3[RANGE_SW_ERR]);
297 
298 	return 0;
299 }
300 
bme680_read_temp_adc(struct bme680_data * data,u32 * adc_temp)301 static int bme680_read_temp_adc(struct bme680_data *data, u32 *adc_temp)
302 {
303 	struct device *dev = regmap_get_device(data->regmap);
304 	u32 value_temp;
305 	int ret;
306 
307 	ret = regmap_bulk_read(data->regmap, BME680_REG_TEMP_MSB,
308 			       data->buf, BME680_TEMP_NUM_BYTES);
309 	if (ret < 0) {
310 		dev_err(dev, "failed to read temperature\n");
311 		return ret;
312 	}
313 
314 	value_temp = FIELD_GET(BME680_MEAS_TRIM_MASK,
315 			       get_unaligned_be24(data->buf));
316 	if (value_temp == BME680_MEAS_SKIPPED) {
317 		/* reading was skipped */
318 		dev_err(dev, "reading temperature skipped\n");
319 		return -EINVAL;
320 	}
321 	*adc_temp = value_temp;
322 
323 	return 0;
324 }
325 
326 /*
327  * Taken from Bosch BME680 API:
328  * https://github.com/BoschSensortec/BME680_driver/blob/63bb5336/bme680.c#L876
329  *
330  * Returns temperature measurement in DegC, resolutions is 0.01 DegC. Therefore,
331  * output value of "3233" represents 32.33 DegC.
332  */
bme680_calc_t_fine(struct bme680_data * data,u32 adc_temp)333 static s32 bme680_calc_t_fine(struct bme680_data *data, u32 adc_temp)
334 {
335 	struct bme680_calib *calib = &data->bme680;
336 	s64 var1, var2, var3;
337 
338 	/* If the calibration is invalid, attempt to reload it */
339 	if (!calib->par_t2)
340 		bme680_read_calib(data, calib);
341 
342 	var1 = ((s32)adc_temp >> 3) - ((s32)calib->par_t1 << 1);
343 	var2 = (var1 * calib->par_t2) >> 11;
344 	var3 = ((var1 >> 1) * (var1 >> 1)) >> 12;
345 	var3 = (var3 * ((s32)calib->par_t3 << 4)) >> 14;
346 	return var2 + var3; /* t_fine = var2 + var3 */
347 }
348 
bme680_get_t_fine(struct bme680_data * data,s32 * t_fine)349 static int bme680_get_t_fine(struct bme680_data *data, s32 *t_fine)
350 {
351 	u32 adc_temp;
352 	int ret;
353 
354 	ret = bme680_read_temp_adc(data, &adc_temp);
355 	if (ret)
356 		return ret;
357 
358 	*t_fine = bme680_calc_t_fine(data, adc_temp);
359 
360 	return 0;
361 }
362 
bme680_compensate_temp(struct bme680_data * data,u32 adc_temp)363 static s16 bme680_compensate_temp(struct bme680_data *data,
364 				  u32 adc_temp)
365 {
366 	return (bme680_calc_t_fine(data, adc_temp) * 5 + 128) / 256;
367 }
368 
bme680_read_press_adc(struct bme680_data * data,u32 * adc_press)369 static int bme680_read_press_adc(struct bme680_data *data, u32 *adc_press)
370 {
371 	struct device *dev = regmap_get_device(data->regmap);
372 	u32 value_press;
373 	int ret;
374 
375 	ret = regmap_bulk_read(data->regmap, BME680_REG_PRESS_MSB,
376 			       data->buf, BME680_PRESS_NUM_BYTES);
377 	if (ret < 0) {
378 		dev_err(dev, "failed to read pressure\n");
379 		return ret;
380 	}
381 
382 	value_press = FIELD_GET(BME680_MEAS_TRIM_MASK,
383 				get_unaligned_be24(data->buf));
384 	if (value_press == BME680_MEAS_SKIPPED) {
385 		/* reading was skipped */
386 		dev_err(dev, "reading pressure skipped\n");
387 		return -EINVAL;
388 	}
389 	*adc_press = value_press;
390 
391 	return 0;
392 }
393 
394 /*
395  * Taken from Bosch BME680 API:
396  * https://github.com/BoschSensortec/BME680_driver/blob/63bb5336/bme680.c#L896
397  *
398  * Returns pressure measurement in Pa. Output value of "97356" represents
399  * 97356 Pa = 973.56 hPa.
400  */
bme680_compensate_press(struct bme680_data * data,u32 adc_press,s32 t_fine)401 static u32 bme680_compensate_press(struct bme680_data *data,
402 				   u32 adc_press, s32 t_fine)
403 {
404 	struct bme680_calib *calib = &data->bme680;
405 	s32 var1, var2, var3, press_comp;
406 
407 	var1 = (t_fine >> 1) - 64000;
408 	var2 = ((((var1 >> 2) * (var1 >> 2)) >> 11) * calib->par_p6) >> 2;
409 	var2 = var2 + (var1 * calib->par_p5 << 1);
410 	var2 = (var2 >> 2) + ((s32)calib->par_p4 << 16);
411 	var1 = (((((var1 >> 2) * (var1 >> 2)) >> 13) *
412 			((s32)calib->par_p3 << 5)) >> 3) +
413 			((calib->par_p2 * var1) >> 1);
414 	var1 = var1 >> 18;
415 	var1 = ((32768 + var1) * calib->par_p1) >> 15;
416 	press_comp = 1048576 - adc_press;
417 	press_comp = ((press_comp - (var2 >> 12)) * 3125);
418 
419 	if (press_comp >= BME680_MAX_OVERFLOW_VAL)
420 		press_comp = ((press_comp / (u32)var1) << 1);
421 	else
422 		press_comp = ((press_comp << 1) / (u32)var1);
423 
424 	var1 = (calib->par_p9 * (((press_comp >> 3) *
425 			(press_comp >> 3)) >> 13)) >> 12;
426 	var2 = ((press_comp >> 2) * calib->par_p8) >> 13;
427 	var3 = ((press_comp >> 8) * (press_comp >> 8) *
428 			(press_comp >> 8) * calib->par_p10) >> 17;
429 
430 	press_comp += (var1 + var2 + var3 + ((s32)calib->par_p7 << 7)) >> 4;
431 
432 	return press_comp;
433 }
434 
bme680_read_humid_adc(struct bme680_data * data,u32 * adc_humidity)435 static int bme680_read_humid_adc(struct bme680_data *data, u32 *adc_humidity)
436 {
437 	struct device *dev = regmap_get_device(data->regmap);
438 	u32 value_humidity;
439 	int ret;
440 
441 	ret = regmap_bulk_read(data->regmap, BME680_REG_HUMIDITY_MSB,
442 			       &data->be16, BME680_HUMID_NUM_BYTES);
443 	if (ret < 0) {
444 		dev_err(dev, "failed to read humidity\n");
445 		return ret;
446 	}
447 
448 	value_humidity = be16_to_cpu(data->be16);
449 	if (value_humidity == BME680_MEAS_SKIPPED) {
450 		/* reading was skipped */
451 		dev_err(dev, "reading humidity skipped\n");
452 		return -EINVAL;
453 	}
454 	*adc_humidity = value_humidity;
455 
456 	return 0;
457 }
458 
459 /*
460  * Taken from Bosch BME680 API:
461  * https://github.com/BoschSensortec/BME680_driver/blob/63bb5336/bme680.c#L937
462  *
463  * Returns humidity measurement in percent, resolution is 0.001 percent. Output
464  * value of "43215" represents 43.215 %rH.
465  */
bme680_compensate_humid(struct bme680_data * data,u16 adc_humid,s32 t_fine)466 static u32 bme680_compensate_humid(struct bme680_data *data,
467 				   u16 adc_humid, s32 t_fine)
468 {
469 	struct bme680_calib *calib = &data->bme680;
470 	s32 var1, var2, var3, var4, var5, var6, temp_scaled, calc_hum;
471 
472 	temp_scaled = (t_fine * 5 + 128) >> 8;
473 	var1 = (adc_humid - (((s32)calib->par_h1 * 16))) -
474 		(((temp_scaled * calib->par_h3) / 100) >> 1);
475 	var2 = (calib->par_h2 *
476 		(((temp_scaled * calib->par_h4) / 100) +
477 		 (((temp_scaled * ((temp_scaled * calib->par_h5) / 100))
478 		   >> 6) / 100) + (1 << 14))) >> 10;
479 	var3 = var1 * var2;
480 	var4 = (s32)calib->par_h6 << 7;
481 	var4 = (var4 + ((temp_scaled * calib->par_h7) / 100)) >> 4;
482 	var5 = ((var3 >> 14) * (var3 >> 14)) >> 10;
483 	var6 = (var4 * var5) >> 1;
484 	calc_hum = (((var3 + var6) >> 10) * 1000) >> 12;
485 
486 	calc_hum = clamp(calc_hum, 0, 100000); /* clamp between 0-100 %rH */
487 
488 	return calc_hum;
489 }
490 
491 /*
492  * Taken from Bosch BME680 API:
493  * https://github.com/BoschSensortec/BME680_driver/blob/63bb5336/bme680.c#L973
494  *
495  * Returns gas measurement in Ohm. Output value of "82986" represent 82986 ohms.
496  */
bme680_compensate_gas(struct bme680_data * data,u16 gas_res_adc,u8 gas_range)497 static u32 bme680_compensate_gas(struct bme680_data *data, u16 gas_res_adc,
498 				 u8 gas_range)
499 {
500 	struct bme680_calib *calib = &data->bme680;
501 	s64 var1;
502 	u64 var2;
503 	s64 var3;
504 	u32 calc_gas_res;
505 
506 	/* Look up table for the possible gas range values */
507 	static const u32 lookup_table[16] = {
508 		2147483647u, 2147483647u, 2147483647u, 2147483647u,
509 		2147483647u, 2126008810u, 2147483647u, 2130303777u,
510 		2147483647u, 2147483647u, 2143188679u, 2136746228u,
511 		2147483647u, 2126008810u, 2147483647u, 2147483647u
512 	};
513 
514 	var1 = ((1340LL + (5 * calib->range_sw_err)) *
515 			(lookup_table[gas_range])) >> 16;
516 	var2 = ((gas_res_adc << 15) - 16777216) + var1;
517 	var3 = ((125000 << (15 - gas_range)) * var1) >> 9;
518 	var3 += (var2 >> 1);
519 	calc_gas_res = div64_s64(var3, (s64)var2);
520 
521 	return calc_gas_res;
522 }
523 
524 /*
525  * Taken from Bosch BME680 API:
526  * https://github.com/BoschSensortec/BME680_driver/blob/63bb5336/bme680.c#L1002
527  */
bme680_calc_heater_res(struct bme680_data * data,u16 temp)528 static u8 bme680_calc_heater_res(struct bme680_data *data, u16 temp)
529 {
530 	struct bme680_calib *calib = &data->bme680;
531 	s32 var1, var2, var3, var4, var5, heatr_res_x100;
532 	u8 heatr_res;
533 
534 	if (temp > 400) /* Cap temperature */
535 		temp = 400;
536 
537 	var1 = (((s32)BME680_AMB_TEMP * calib->par_gh3) / 1000) * 256;
538 	var2 = (calib->par_gh1 + 784) * (((((calib->par_gh2 + 154009) *
539 						temp * 5) / 100)
540 						+ 3276800) / 10);
541 	var3 = var1 + (var2 / 2);
542 	var4 = (var3 / (calib->res_heat_range + 4));
543 	var5 = 131 * calib->res_heat_val + 65536;
544 	heatr_res_x100 = ((var4 / var5) - 250) * 34;
545 	heatr_res = DIV_ROUND_CLOSEST(heatr_res_x100, 100);
546 
547 	return heatr_res;
548 }
549 
550 /*
551  * Taken from Bosch BME680 API:
552  * https://github.com/BoschSensortec/BME680_driver/blob/63bb5336/bme680.c#L1188
553  */
bme680_calc_heater_dur(u16 dur)554 static u8 bme680_calc_heater_dur(u16 dur)
555 {
556 	u8 durval, factor = 0;
557 
558 	if (dur >= 0xfc0) {
559 		durval = 0xff; /* Max duration */
560 	} else {
561 		while (dur > 0x3F) {
562 			dur = dur / 4;
563 			factor += 1;
564 		}
565 		durval = dur + (factor * 64);
566 	}
567 
568 	return durval;
569 }
570 
571 /* Taken from datasheet, section 5.3.3 */
bme680_calc_heater_preheat_current(u8 curr)572 static u8 bme680_calc_heater_preheat_current(u8 curr)
573 {
574 	return 8 * curr - 1;
575 }
576 
bme680_set_mode(struct bme680_data * data,enum bme680_op_mode mode)577 static int bme680_set_mode(struct bme680_data *data, enum bme680_op_mode mode)
578 {
579 	struct device *dev = regmap_get_device(data->regmap);
580 	int ret;
581 
582 	ret = regmap_write_bits(data->regmap, BME680_REG_CTRL_MEAS,
583 				BME680_MODE_MASK, mode);
584 	if (ret < 0) {
585 		dev_err(dev, "failed to set ctrl_meas register\n");
586 		return ret;
587 	}
588 
589 	return ret;
590 }
591 
bme680_oversampling_to_reg(u8 val)592 static u8 bme680_oversampling_to_reg(u8 val)
593 {
594 	return ilog2(val) + 1;
595 }
596 
597 /*
598  * Taken from Bosch BME680 API:
599  * https://github.com/boschsensortec/BME68x_SensorAPI/blob/v4.4.8/bme68x.c#L490
600  */
bme680_wait_for_eoc(struct bme680_data * data)601 static int bme680_wait_for_eoc(struct bme680_data *data)
602 {
603 	struct device *dev = regmap_get_device(data->regmap);
604 	int ret;
605 	/*
606 	 * (Sum of oversampling ratios * time per oversampling) +
607 	 * TPH measurement + gas measurement + wait transition from forced mode
608 	 * + heater duration
609 	 */
610 	int wait_eoc_us = ((data->oversampling_temp + data->oversampling_press +
611 			   data->oversampling_humid) * 1936) + (477 * 4) +
612 			   (477 * 5) + 1000 + (data->heater_dur * 1000);
613 
614 	fsleep(wait_eoc_us);
615 
616 	ret = regmap_read(data->regmap, BME680_REG_MEAS_STAT_0, &data->check);
617 	if (ret) {
618 		dev_err(dev, "failed to read measurement status register.\n");
619 		return ret;
620 	}
621 	if (data->check & BME680_MEAS_BIT) {
622 		dev_err(dev, "Device measurement cycle incomplete.\n");
623 		return -EBUSY;
624 	}
625 	if (!(data->check & BME680_NEW_DATA_BIT)) {
626 		dev_err(dev, "No new data available from the device.\n");
627 		return -ENODATA;
628 	}
629 
630 	return 0;
631 }
632 
bme680_chip_config(struct bme680_data * data)633 static int bme680_chip_config(struct bme680_data *data)
634 {
635 	struct device *dev = regmap_get_device(data->regmap);
636 	int ret;
637 	u8 osrs;
638 
639 	osrs = FIELD_PREP(BME680_OSRS_HUMIDITY_MASK,
640 			  bme680_oversampling_to_reg(data->oversampling_humid));
641 	/*
642 	 * Highly recommended to set oversampling of humidity before
643 	 * temperature/pressure oversampling.
644 	 */
645 	ret = regmap_update_bits(data->regmap, BME680_REG_CTRL_HUMIDITY,
646 				 BME680_OSRS_HUMIDITY_MASK, osrs);
647 	if (ret < 0) {
648 		dev_err(dev, "failed to write ctrl_hum register\n");
649 		return ret;
650 	}
651 
652 	/* IIR filter settings */
653 	ret = regmap_update_bits(data->regmap, BME680_REG_CONFIG,
654 				 BME680_FILTER_MASK, BME680_FILTER_COEFF_VAL);
655 	if (ret < 0) {
656 		dev_err(dev, "failed to write config register\n");
657 		return ret;
658 	}
659 
660 	osrs = FIELD_PREP(BME680_OSRS_TEMP_MASK,
661 			  bme680_oversampling_to_reg(data->oversampling_temp)) |
662 	       FIELD_PREP(BME680_OSRS_PRESS_MASK,
663 			  bme680_oversampling_to_reg(data->oversampling_press));
664 	ret = regmap_write_bits(data->regmap, BME680_REG_CTRL_MEAS,
665 				BME680_OSRS_TEMP_MASK | BME680_OSRS_PRESS_MASK,
666 				osrs);
667 	if (ret < 0) {
668 		dev_err(dev, "failed to write ctrl_meas register\n");
669 		return ret;
670 	}
671 
672 	return 0;
673 }
674 
bme680_preheat_curr_config(struct bme680_data * data,u8 val)675 static int bme680_preheat_curr_config(struct bme680_data *data, u8 val)
676 {
677 	struct device *dev = regmap_get_device(data->regmap);
678 	u8 heatr_curr;
679 	int ret;
680 
681 	heatr_curr = bme680_calc_heater_preheat_current(val);
682 	ret = regmap_write(data->regmap, BME680_REG_IDAC_HEAT_0, heatr_curr);
683 	if (ret < 0)
684 		dev_err(dev, "failed to write idac_heat_0 register\n");
685 
686 	return ret;
687 }
688 
bme680_gas_config(struct bme680_data * data)689 static int bme680_gas_config(struct bme680_data *data)
690 {
691 	struct device *dev = regmap_get_device(data->regmap);
692 	int ret;
693 	u8 heatr_res, heatr_dur;
694 
695 	ret = bme680_set_mode(data, BME680_MODE_SLEEP);
696 	if (ret < 0)
697 		return ret;
698 
699 	heatr_res = bme680_calc_heater_res(data, data->heater_temp);
700 
701 	/* set target heater temperature */
702 	ret = regmap_write(data->regmap, BME680_REG_RES_HEAT_0, heatr_res);
703 	if (ret < 0) {
704 		dev_err(dev, "failed to write res_heat_0 register\n");
705 		return ret;
706 	}
707 
708 	heatr_dur = bme680_calc_heater_dur(data->heater_dur);
709 
710 	/* set target heating duration */
711 	ret = regmap_write(data->regmap, BME680_REG_GAS_WAIT_0, heatr_dur);
712 	if (ret < 0) {
713 		dev_err(dev, "failed to write gas_wait_0 register\n");
714 		return ret;
715 	}
716 
717 	ret = bme680_preheat_curr_config(data, data->preheat_curr_mA);
718 	if (ret)
719 		return ret;
720 
721 	/* Enable the gas sensor and select heater profile set-point 0 */
722 	ret = regmap_update_bits(data->regmap, BME680_REG_CTRL_GAS_1,
723 				 BME680_RUN_GAS_MASK | BME680_NB_CONV_MASK,
724 				 FIELD_PREP(BME680_RUN_GAS_MASK, 1) |
725 				 FIELD_PREP(BME680_NB_CONV_MASK, 0));
726 	if (ret < 0)
727 		dev_err(dev, "failed to write ctrl_gas_1 register\n");
728 
729 	return ret;
730 }
731 
bme680_read_temp(struct bme680_data * data,s16 * comp_temp)732 static int bme680_read_temp(struct bme680_data *data, s16 *comp_temp)
733 {
734 	int ret;
735 	u32 adc_temp;
736 
737 	ret = bme680_read_temp_adc(data, &adc_temp);
738 	if (ret)
739 		return ret;
740 
741 	*comp_temp = bme680_compensate_temp(data, adc_temp);
742 	return 0;
743 }
744 
bme680_read_press(struct bme680_data * data,u32 * comp_press)745 static int bme680_read_press(struct bme680_data *data, u32 *comp_press)
746 {
747 	int ret;
748 	u32 adc_press;
749 	s32 t_fine;
750 
751 	ret = bme680_get_t_fine(data, &t_fine);
752 	if (ret)
753 		return ret;
754 
755 	ret = bme680_read_press_adc(data, &adc_press);
756 	if (ret)
757 		return ret;
758 
759 	*comp_press = bme680_compensate_press(data, adc_press, t_fine);
760 	return 0;
761 }
762 
bme680_read_humid(struct bme680_data * data,u32 * comp_humidity)763 static int bme680_read_humid(struct bme680_data *data, u32 *comp_humidity)
764 {
765 	int ret;
766 	u32 adc_humidity;
767 	s32 t_fine;
768 
769 	ret = bme680_get_t_fine(data, &t_fine);
770 	if (ret)
771 		return ret;
772 
773 	ret = bme680_read_humid_adc(data, &adc_humidity);
774 	if (ret)
775 		return ret;
776 
777 	*comp_humidity = bme680_compensate_humid(data, adc_humidity, t_fine);
778 	return 0;
779 }
780 
bme680_read_gas(struct bme680_data * data,int * comp_gas_res)781 static int bme680_read_gas(struct bme680_data *data, int *comp_gas_res)
782 {
783 	struct device *dev = regmap_get_device(data->regmap);
784 	int ret;
785 	u16 adc_gas_res, gas_regs_val;
786 	u8 gas_range;
787 
788 	ret = regmap_read(data->regmap, BME680_REG_MEAS_STAT_0, &data->check);
789 	if (data->check & BME680_GAS_MEAS_BIT) {
790 		dev_err(dev, "gas measurement incomplete\n");
791 		return -EBUSY;
792 	}
793 
794 	ret = regmap_bulk_read(data->regmap, BME680_REG_GAS_MSB,
795 			       &data->be16, BME680_GAS_NUM_BYTES);
796 	if (ret < 0) {
797 		dev_err(dev, "failed to read gas resistance\n");
798 		return ret;
799 	}
800 
801 	gas_regs_val = be16_to_cpu(data->be16);
802 	adc_gas_res = FIELD_GET(BME680_ADC_GAS_RES, gas_regs_val);
803 
804 	/*
805 	 * occurs if either the gas heating duration was insuffient
806 	 * to reach the target heater temperature or the target
807 	 * heater temperature was too high for the heater sink to
808 	 * reach.
809 	 */
810 	if ((gas_regs_val & BME680_GAS_STAB_BIT) == 0) {
811 		dev_err(dev, "heater failed to reach the target temperature\n");
812 		return -EINVAL;
813 	}
814 
815 	gas_range = FIELD_GET(BME680_GAS_RANGE_MASK, gas_regs_val);
816 	*comp_gas_res = bme680_compensate_gas(data, adc_gas_res, gas_range);
817 	return 0;
818 }
819 
bme680_read_raw(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,int * val,int * val2,long mask)820 static int bme680_read_raw(struct iio_dev *indio_dev,
821 			   struct iio_chan_spec const *chan,
822 			   int *val, int *val2, long mask)
823 {
824 	struct bme680_data *data = iio_priv(indio_dev);
825 	int chan_val, ret;
826 	s16 temp_chan_val;
827 
828 	guard(mutex)(&data->lock);
829 
830 	ret = bme680_set_mode(data, BME680_MODE_FORCED);
831 	if (ret < 0)
832 		return ret;
833 
834 	ret = bme680_wait_for_eoc(data);
835 	if (ret)
836 		return ret;
837 
838 	switch (mask) {
839 	case IIO_CHAN_INFO_PROCESSED:
840 		switch (chan->type) {
841 		case IIO_TEMP:
842 			ret = bme680_read_temp(data, &temp_chan_val);
843 			if (ret)
844 				return ret;
845 
846 			*val = temp_chan_val * 10;
847 			return IIO_VAL_INT;
848 		case IIO_PRESSURE:
849 			ret = bme680_read_press(data, &chan_val);
850 			if (ret)
851 				return ret;
852 
853 			*val = chan_val;
854 			*val2 = 1000;
855 			return IIO_VAL_FRACTIONAL;
856 		case IIO_HUMIDITYRELATIVE:
857 			ret = bme680_read_humid(data, &chan_val);
858 			if (ret)
859 				return ret;
860 
861 			*val = chan_val;
862 			*val2 = 1000;
863 			return IIO_VAL_FRACTIONAL;
864 		case IIO_RESISTANCE:
865 			ret = bme680_read_gas(data, &chan_val);
866 			if (ret)
867 				return ret;
868 
869 			*val = chan_val;
870 			return IIO_VAL_INT;
871 		default:
872 			return -EINVAL;
873 		}
874 	case IIO_CHAN_INFO_RAW:
875 		switch (chan->type) {
876 		case IIO_TEMP:
877 			ret = bme680_read_temp(data, (s16 *)&chan_val);
878 			if (ret)
879 				return ret;
880 
881 			*val = chan_val;
882 			return IIO_VAL_INT;
883 		case IIO_PRESSURE:
884 			ret = bme680_read_press(data, &chan_val);
885 			if (ret)
886 				return ret;
887 
888 			*val = chan_val;
889 			return IIO_VAL_INT;
890 		case IIO_HUMIDITYRELATIVE:
891 			ret = bme680_read_humid(data, &chan_val);
892 			if (ret)
893 				return ret;
894 
895 			*val = chan_val;
896 			return IIO_VAL_INT;
897 		default:
898 			return -EINVAL;
899 		}
900 	case IIO_CHAN_INFO_SCALE:
901 		switch (chan->type) {
902 		case IIO_TEMP:
903 			*val = 10;
904 			return IIO_VAL_INT;
905 		case IIO_PRESSURE:
906 			*val = 1;
907 			*val2 = 1000;
908 			return IIO_VAL_FRACTIONAL;
909 		case IIO_HUMIDITYRELATIVE:
910 			*val = 1;
911 			*val2 = 1000;
912 			return IIO_VAL_FRACTIONAL;
913 		default:
914 			return -EINVAL;
915 		}
916 	case IIO_CHAN_INFO_OVERSAMPLING_RATIO:
917 		switch (chan->type) {
918 		case IIO_TEMP:
919 			*val = data->oversampling_temp;
920 			return IIO_VAL_INT;
921 		case IIO_PRESSURE:
922 			*val = data->oversampling_press;
923 			return IIO_VAL_INT;
924 		case IIO_HUMIDITYRELATIVE:
925 			*val = data->oversampling_humid;
926 			return IIO_VAL_INT;
927 		default:
928 			return -EINVAL;
929 		}
930 	default:
931 		return -EINVAL;
932 	}
933 }
934 
bme680_is_valid_oversampling(int rate)935 static bool bme680_is_valid_oversampling(int rate)
936 {
937 	return (rate > 0 && rate <= 16 && is_power_of_2(rate));
938 }
939 
bme680_write_raw(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,int val,int val2,long mask)940 static int bme680_write_raw(struct iio_dev *indio_dev,
941 			    struct iio_chan_spec const *chan,
942 			    int val, int val2, long mask)
943 {
944 	struct bme680_data *data = iio_priv(indio_dev);
945 
946 	guard(mutex)(&data->lock);
947 
948 	if (val2 != 0)
949 		return -EINVAL;
950 
951 	switch (mask) {
952 	case IIO_CHAN_INFO_OVERSAMPLING_RATIO:
953 	{
954 		if (!bme680_is_valid_oversampling(val))
955 			return -EINVAL;
956 
957 		switch (chan->type) {
958 		case IIO_TEMP:
959 			data->oversampling_temp = val;
960 			break;
961 		case IIO_PRESSURE:
962 			data->oversampling_press = val;
963 			break;
964 		case IIO_HUMIDITYRELATIVE:
965 			data->oversampling_humid = val;
966 			break;
967 		default:
968 			return -EINVAL;
969 		}
970 
971 		return bme680_chip_config(data);
972 	}
973 	case IIO_CHAN_INFO_PROCESSED:
974 	{
975 		switch (chan->type) {
976 		case IIO_CURRENT:
977 			return bme680_preheat_curr_config(data, (u8)val);
978 		default:
979 			return -EINVAL;
980 		}
981 	}
982 	default:
983 		return -EINVAL;
984 	}
985 }
986 
987 static const char bme680_oversampling_ratio_show[] = "1 2 4 8 16";
988 
989 static IIO_CONST_ATTR(oversampling_ratio_available,
990 		      bme680_oversampling_ratio_show);
991 
992 static struct attribute *bme680_attributes[] = {
993 	&iio_const_attr_oversampling_ratio_available.dev_attr.attr,
994 	NULL,
995 };
996 
997 static const struct attribute_group bme680_attribute_group = {
998 	.attrs = bme680_attributes,
999 };
1000 
1001 static const struct iio_info bme680_info = {
1002 	.read_raw = &bme680_read_raw,
1003 	.write_raw = &bme680_write_raw,
1004 	.attrs = &bme680_attribute_group,
1005 };
1006 
1007 static const unsigned long bme680_avail_scan_masks[] = {
1008 	BIT(BME680_GAS) | BIT(BME680_HUMID) | BIT(BME680_PRESS) | BIT(BME680_TEMP),
1009 	0
1010 };
1011 
bme680_trigger_handler(int irq,void * p)1012 static irqreturn_t bme680_trigger_handler(int irq, void *p)
1013 {
1014 	struct iio_poll_func *pf = p;
1015 	struct iio_dev *indio_dev = pf->indio_dev;
1016 	struct bme680_data *data = iio_priv(indio_dev);
1017 	struct device *dev = regmap_get_device(data->regmap);
1018 	u32 adc_temp, adc_press, adc_humid;
1019 	u16 adc_gas_res, gas_regs_val;
1020 	u8 gas_range;
1021 	s32 t_fine;
1022 	int ret;
1023 
1024 	guard(mutex)(&data->lock);
1025 
1026 	ret = bme680_set_mode(data, BME680_MODE_FORCED);
1027 	if (ret < 0)
1028 		goto out;
1029 
1030 	ret = bme680_wait_for_eoc(data);
1031 	if (ret)
1032 		goto out;
1033 
1034 	ret = regmap_bulk_read(data->regmap, BME680_REG_MEAS_STAT_0,
1035 			       data->buf, sizeof(data->buf));
1036 	if (ret) {
1037 		dev_err(dev, "failed to burst read sensor data\n");
1038 		goto out;
1039 	}
1040 	if (data->buf[0] & BME680_GAS_MEAS_BIT) {
1041 		dev_err(dev, "gas measurement incomplete\n");
1042 		goto out;
1043 	}
1044 
1045 	/* Temperature calculations */
1046 	adc_temp = FIELD_GET(BME680_MEAS_TRIM_MASK, get_unaligned_be24(&data->buf[5]));
1047 	if (adc_temp == BME680_MEAS_SKIPPED) {
1048 		dev_err(dev, "reading temperature skipped\n");
1049 		goto out;
1050 	}
1051 	data->scan.chan[0] = bme680_compensate_temp(data, adc_temp);
1052 	t_fine = bme680_calc_t_fine(data, adc_temp);
1053 
1054 	/* Pressure calculations */
1055 	adc_press = FIELD_GET(BME680_MEAS_TRIM_MASK, get_unaligned_be24(&data->buf[2]));
1056 	if (adc_press == BME680_MEAS_SKIPPED) {
1057 		dev_err(dev, "reading pressure skipped\n");
1058 		goto out;
1059 	}
1060 	data->scan.chan[1] = bme680_compensate_press(data, adc_press, t_fine);
1061 
1062 	/* Humidity calculations */
1063 	adc_humid = get_unaligned_be16(&data->buf[8]);
1064 	if (adc_humid == BME680_MEAS_SKIPPED) {
1065 		dev_err(dev, "reading humidity skipped\n");
1066 		goto out;
1067 	}
1068 	data->scan.chan[2] = bme680_compensate_humid(data, adc_humid, t_fine);
1069 
1070 	/* Gas calculations */
1071 	gas_regs_val = get_unaligned_be16(&data->buf[13]);
1072 	adc_gas_res = FIELD_GET(BME680_ADC_GAS_RES, gas_regs_val);
1073 	if ((gas_regs_val & BME680_GAS_STAB_BIT) == 0) {
1074 		dev_err(dev, "heater failed to reach the target temperature\n");
1075 		goto out;
1076 	}
1077 	gas_range = FIELD_GET(BME680_GAS_RANGE_MASK, gas_regs_val);
1078 	data->scan.chan[3] = bme680_compensate_gas(data, adc_gas_res, gas_range);
1079 
1080 	iio_push_to_buffers_with_timestamp(indio_dev, &data->scan,
1081 					   iio_get_time_ns(indio_dev));
1082 out:
1083 	iio_trigger_notify_done(indio_dev->trig);
1084 	return IRQ_HANDLED;
1085 }
1086 
bme680_core_probe(struct device * dev,struct regmap * regmap,const char * name)1087 int bme680_core_probe(struct device *dev, struct regmap *regmap,
1088 		      const char *name)
1089 {
1090 	struct iio_dev *indio_dev;
1091 	struct bme680_data *data;
1092 	int ret;
1093 
1094 	indio_dev = devm_iio_device_alloc(dev, sizeof(*data));
1095 	if (!indio_dev)
1096 		return -ENOMEM;
1097 
1098 	data = iio_priv(indio_dev);
1099 	mutex_init(&data->lock);
1100 	dev_set_drvdata(dev, indio_dev);
1101 	data->regmap = regmap;
1102 	indio_dev->name = name;
1103 	indio_dev->channels = bme680_channels;
1104 	indio_dev->num_channels = ARRAY_SIZE(bme680_channels);
1105 	indio_dev->available_scan_masks = bme680_avail_scan_masks;
1106 	indio_dev->info = &bme680_info;
1107 	indio_dev->modes = INDIO_DIRECT_MODE;
1108 
1109 	/* default values for the sensor */
1110 	data->oversampling_humid = 2; /* 2X oversampling rate */
1111 	data->oversampling_press = 4; /* 4X oversampling rate */
1112 	data->oversampling_temp = 8;  /* 8X oversampling rate */
1113 	data->heater_temp = 320; /* degree Celsius */
1114 	data->heater_dur = 150;  /* milliseconds */
1115 	data->preheat_curr_mA = 0;
1116 
1117 	ret = regmap_write(regmap, BME680_REG_SOFT_RESET, BME680_CMD_SOFTRESET);
1118 	if (ret < 0)
1119 		return dev_err_probe(dev, ret, "Failed to reset chip\n");
1120 
1121 	fsleep(BME680_STARTUP_TIME_US);
1122 
1123 	ret = regmap_read(regmap, BME680_REG_CHIP_ID, &data->check);
1124 	if (ret < 0)
1125 		return dev_err_probe(dev, ret, "Error reading chip ID\n");
1126 
1127 	if (data->check != BME680_CHIP_ID_VAL) {
1128 		dev_err(dev, "Wrong chip ID, got %x expected %x\n",
1129 			data->check, BME680_CHIP_ID_VAL);
1130 		return -ENODEV;
1131 	}
1132 
1133 	ret = bme680_read_calib(data, &data->bme680);
1134 	if (ret < 0) {
1135 		return dev_err_probe(dev, ret,
1136 			"failed to read calibration coefficients at probe\n");
1137 	}
1138 
1139 	ret = bme680_chip_config(data);
1140 	if (ret < 0)
1141 		return dev_err_probe(dev, ret,
1142 				     "failed to set chip_config data\n");
1143 
1144 	ret = bme680_gas_config(data);
1145 	if (ret < 0)
1146 		return dev_err_probe(dev, ret,
1147 				     "failed to set gas config data\n");
1148 
1149 	ret = devm_iio_triggered_buffer_setup(dev, indio_dev,
1150 					      iio_pollfunc_store_time,
1151 					      bme680_trigger_handler,
1152 					      NULL);
1153 	if (ret)
1154 		return dev_err_probe(dev, ret,
1155 				     "iio triggered buffer setup failed\n");
1156 
1157 	return devm_iio_device_register(dev, indio_dev);
1158 }
1159 EXPORT_SYMBOL_NS_GPL(bme680_core_probe, "IIO_BME680");
1160 
1161 MODULE_AUTHOR("Himanshu Jha <himanshujha199640@gmail.com>");
1162 MODULE_DESCRIPTION("Bosch BME680 Driver");
1163 MODULE_LICENSE("GPL v2");
1164