xref: /linux/drivers/iio/imu/inv_icm42600/inv_icm42600_temp.c (revision e7e2296b0ecf9b6e934f7a1118cee91d4d486a84)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (C) 2020 Invensense, Inc.
4  */
5 
6 #include <linux/kernel.h>
7 #include <linux/device.h>
8 #include <linux/mutex.h>
9 #include <linux/pm_runtime.h>
10 #include <linux/regmap.h>
11 #include <linux/iio/iio.h>
12 
13 #include "inv_icm42600.h"
14 #include "inv_icm42600_temp.h"
15 
16 static int inv_icm42600_temp_read(struct inv_icm42600_state *st, s16 *temp)
17 {
18 	struct device *dev = regmap_get_device(st->map);
19 	__be16 *raw;
20 	int ret;
21 
22 	pm_runtime_get_sync(dev);
23 	mutex_lock(&st->lock);
24 
25 	ret = inv_icm42600_set_temp_conf(st, true, NULL);
26 	if (ret)
27 		goto exit;
28 
29 	raw = (__be16 *)&st->buffer[0];
30 	ret = regmap_bulk_read(st->map, INV_ICM42600_REG_TEMP_DATA, raw, sizeof(*raw));
31 	if (ret)
32 		goto exit;
33 
34 	*temp = (s16)be16_to_cpup(raw);
35 	/*
36 	 * Temperature data is invalid if both accel and gyro are off.
37 	 * Return -EBUSY in this case.
38 	 */
39 	if (*temp == INV_ICM42600_DATA_INVALID)
40 		ret = -EBUSY;
41 
42 exit:
43 	mutex_unlock(&st->lock);
44 	pm_runtime_put_autosuspend(dev);
45 
46 	return ret;
47 }
48 
49 int inv_icm42600_temp_read_raw(struct iio_dev *indio_dev,
50 			       struct iio_chan_spec const *chan,
51 			       int *val, int *val2, long mask)
52 {
53 	struct inv_icm42600_state *st = iio_device_get_drvdata(indio_dev);
54 	s16 temp;
55 	int ret;
56 
57 	if (chan->type != IIO_TEMP)
58 		return -EINVAL;
59 
60 	switch (mask) {
61 	case IIO_CHAN_INFO_RAW:
62 		if (!iio_device_claim_direct(indio_dev))
63 			return -EBUSY;
64 		ret = inv_icm42600_temp_read(st, &temp);
65 		iio_device_release_direct(indio_dev);
66 		if (ret)
67 			return ret;
68 		*val = temp;
69 		return IIO_VAL_INT;
70 	/*
71 	 * T°C = (temp / 132.48) + 25
72 	 * Tm°C = 1000 * ((temp / 132.48) + 25)
73 	 * Tm°C = 7.548309 * temp + 25000
74 	 * Tm°C = (temp + 3312) * 7.548309
75 	 * scale: 100000 / 13248 ~= 7.548309
76 	 * offset: 3312
77 	 */
78 	case IIO_CHAN_INFO_SCALE:
79 		*val = 7;
80 		*val2 = 548309;
81 		return IIO_VAL_INT_PLUS_MICRO;
82 	case IIO_CHAN_INFO_OFFSET:
83 		*val = 3312;
84 		return IIO_VAL_INT;
85 	default:
86 		return -EINVAL;
87 	}
88 }
89