xref: /linux/drivers/iio/adc/hx711.c (revision 3a39d672e7f48b8d6b91a09afa4b55352773b4b5)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * HX711: analog to digital converter for weight sensor module
4  *
5  * Copyright (c) 2016 Andreas Klinger <ak@it-klinger.de>
6  */
7 #include <linux/err.h>
8 #include <linux/kernel.h>
9 #include <linux/module.h>
10 #include <linux/mod_devicetable.h>
11 #include <linux/platform_device.h>
12 #include <linux/property.h>
13 #include <linux/slab.h>
14 #include <linux/sched.h>
15 #include <linux/delay.h>
16 #include <linux/iio/iio.h>
17 #include <linux/iio/sysfs.h>
18 #include <linux/iio/buffer.h>
19 #include <linux/iio/trigger_consumer.h>
20 #include <linux/iio/triggered_buffer.h>
21 #include <linux/gpio/consumer.h>
22 #include <linux/regulator/consumer.h>
23 
24 /* gain to pulse and scale conversion */
25 #define HX711_GAIN_MAX		3
26 #define HX711_RESET_GAIN	128
27 
28 struct hx711_gain_to_scale {
29 	int			gain;
30 	int			gain_pulse;
31 	int			scale;
32 	int			channel;
33 };
34 
35 /*
36  * .scale depends on AVDD which in turn is known as soon as the regulator
37  * is available
38  * therefore we set .scale in hx711_probe()
39  *
40  * channel A in documentation is channel 0 in source code
41  * channel B in documentation is channel 1 in source code
42  */
43 static struct hx711_gain_to_scale hx711_gain_to_scale[HX711_GAIN_MAX] = {
44 	{ 128, 1, 0, 0 },
45 	{  32, 2, 0, 1 },
46 	{  64, 3, 0, 0 }
47 };
48 
hx711_get_gain_to_pulse(int gain)49 static int hx711_get_gain_to_pulse(int gain)
50 {
51 	int i;
52 
53 	for (i = 0; i < HX711_GAIN_MAX; i++)
54 		if (hx711_gain_to_scale[i].gain == gain)
55 			return hx711_gain_to_scale[i].gain_pulse;
56 	return 1;
57 }
58 
hx711_get_gain_to_scale(int gain)59 static int hx711_get_gain_to_scale(int gain)
60 {
61 	int i;
62 
63 	for (i = 0; i < HX711_GAIN_MAX; i++)
64 		if (hx711_gain_to_scale[i].gain == gain)
65 			return hx711_gain_to_scale[i].scale;
66 	return 0;
67 }
68 
hx711_get_scale_to_gain(int scale)69 static int hx711_get_scale_to_gain(int scale)
70 {
71 	int i;
72 
73 	for (i = 0; i < HX711_GAIN_MAX; i++)
74 		if (hx711_gain_to_scale[i].scale == scale)
75 			return hx711_gain_to_scale[i].gain;
76 	return -EINVAL;
77 }
78 
79 struct hx711_data {
80 	struct device		*dev;
81 	struct gpio_desc	*gpiod_pd_sck;
82 	struct gpio_desc	*gpiod_dout;
83 	int			gain_set;	/* gain set on device */
84 	int			gain_chan_a;	/* gain for channel A */
85 	struct mutex		lock;
86 	/*
87 	 * triggered buffer
88 	 * 2x32-bit channel + 64-bit naturally aligned timestamp
89 	 */
90 	u32			buffer[4] __aligned(8);
91 	/*
92 	 * delay after a rising edge on SCK until the data is ready DOUT
93 	 * this is dependent on the hx711 where the datasheet tells a
94 	 * maximum value of 100 ns
95 	 * but also on potential parasitic capacities on the wiring
96 	 */
97 	u32			data_ready_delay_ns;
98 	u32			clock_frequency;
99 };
100 
hx711_cycle(struct hx711_data * hx711_data)101 static int hx711_cycle(struct hx711_data *hx711_data)
102 {
103 	unsigned long flags;
104 
105 	/*
106 	 * if preempted for more then 60us while PD_SCK is high:
107 	 * hx711 is going in reset
108 	 * ==> measuring is false
109 	 */
110 	local_irq_save(flags);
111 	gpiod_set_value(hx711_data->gpiod_pd_sck, 1);
112 
113 	/*
114 	 * wait until DOUT is ready
115 	 * it turned out that parasitic capacities are extending the time
116 	 * until DOUT has reached it's value
117 	 */
118 	ndelay(hx711_data->data_ready_delay_ns);
119 
120 	/*
121 	 * here we are not waiting for 0.2 us as suggested by the datasheet,
122 	 * because the oscilloscope showed in a test scenario
123 	 * at least 1.15 us for PD_SCK high (T3 in datasheet)
124 	 * and 0.56 us for PD_SCK low on TI Sitara with 800 MHz
125 	 */
126 	gpiod_set_value(hx711_data->gpiod_pd_sck, 0);
127 	local_irq_restore(flags);
128 
129 	/*
130 	 * make it a square wave for addressing cases with capacitance on
131 	 * PC_SCK
132 	 */
133 	ndelay(hx711_data->data_ready_delay_ns);
134 
135 	/* sample as late as possible */
136 	return gpiod_get_value(hx711_data->gpiod_dout);
137 }
138 
hx711_read(struct hx711_data * hx711_data)139 static int hx711_read(struct hx711_data *hx711_data)
140 {
141 	int i, ret;
142 	int value = 0;
143 	int val = gpiod_get_value(hx711_data->gpiod_dout);
144 
145 	/* we double check if it's really down */
146 	if (val)
147 		return -EIO;
148 
149 	for (i = 0; i < 24; i++) {
150 		value <<= 1;
151 		ret = hx711_cycle(hx711_data);
152 		if (ret)
153 			value++;
154 	}
155 
156 	value ^= 0x800000;
157 
158 	for (i = 0; i < hx711_get_gain_to_pulse(hx711_data->gain_set); i++)
159 		hx711_cycle(hx711_data);
160 
161 	return value;
162 }
163 
hx711_wait_for_ready(struct hx711_data * hx711_data)164 static int hx711_wait_for_ready(struct hx711_data *hx711_data)
165 {
166 	int i, val;
167 
168 	/*
169 	 * in some rare cases the reset takes quite a long time
170 	 * especially when the channel is changed.
171 	 * Allow up to one second for it
172 	 */
173 	for (i = 0; i < 100; i++) {
174 		val = gpiod_get_value(hx711_data->gpiod_dout);
175 		if (!val)
176 			break;
177 		/* sleep at least 10 ms */
178 		msleep(10);
179 	}
180 	if (val)
181 		return -EIO;
182 
183 	return 0;
184 }
185 
hx711_reset(struct hx711_data * hx711_data)186 static int hx711_reset(struct hx711_data *hx711_data)
187 {
188 	int val = hx711_wait_for_ready(hx711_data);
189 
190 	if (val) {
191 		/*
192 		 * an examination with the oszilloscope indicated
193 		 * that the first value read after the reset is not stable
194 		 * if we reset too short;
195 		 * the shorter the reset cycle
196 		 * the less reliable the first value after reset is;
197 		 * there were no problems encountered with a value
198 		 * of 10 ms or higher
199 		 */
200 		gpiod_set_value(hx711_data->gpiod_pd_sck, 1);
201 		msleep(10);
202 		gpiod_set_value(hx711_data->gpiod_pd_sck, 0);
203 
204 		val = hx711_wait_for_ready(hx711_data);
205 
206 		/* after a reset the gain is 128 */
207 		hx711_data->gain_set = HX711_RESET_GAIN;
208 	}
209 
210 	return val;
211 }
212 
hx711_set_gain_for_channel(struct hx711_data * hx711_data,int chan)213 static int hx711_set_gain_for_channel(struct hx711_data *hx711_data, int chan)
214 {
215 	int ret;
216 
217 	if (chan == 0) {
218 		if (hx711_data->gain_set == 32) {
219 			hx711_data->gain_set = hx711_data->gain_chan_a;
220 
221 			ret = hx711_read(hx711_data);
222 			if (ret < 0)
223 				return ret;
224 
225 			ret = hx711_wait_for_ready(hx711_data);
226 			if (ret)
227 				return ret;
228 		}
229 	} else {
230 		if (hx711_data->gain_set != 32) {
231 			hx711_data->gain_set = 32;
232 
233 			ret = hx711_read(hx711_data);
234 			if (ret < 0)
235 				return ret;
236 
237 			ret = hx711_wait_for_ready(hx711_data);
238 			if (ret)
239 				return ret;
240 		}
241 	}
242 
243 	return 0;
244 }
245 
hx711_reset_read(struct hx711_data * hx711_data,int chan)246 static int hx711_reset_read(struct hx711_data *hx711_data, int chan)
247 {
248 	int ret;
249 	int val;
250 
251 	/*
252 	 * hx711_reset() must be called from here
253 	 * because it could be calling hx711_read() by itself
254 	 */
255 	if (hx711_reset(hx711_data)) {
256 		dev_err(hx711_data->dev, "reset failed!");
257 		return -EIO;
258 	}
259 
260 	ret = hx711_set_gain_for_channel(hx711_data, chan);
261 	if (ret < 0)
262 		return ret;
263 
264 	val = hx711_read(hx711_data);
265 
266 	return val;
267 }
268 
hx711_read_raw(struct iio_dev * indio_dev,const struct iio_chan_spec * chan,int * val,int * val2,long mask)269 static int hx711_read_raw(struct iio_dev *indio_dev,
270 				const struct iio_chan_spec *chan,
271 				int *val, int *val2, long mask)
272 {
273 	struct hx711_data *hx711_data = iio_priv(indio_dev);
274 
275 	switch (mask) {
276 	case IIO_CHAN_INFO_RAW:
277 		mutex_lock(&hx711_data->lock);
278 
279 		*val = hx711_reset_read(hx711_data, chan->channel);
280 
281 		mutex_unlock(&hx711_data->lock);
282 
283 		if (*val < 0)
284 			return *val;
285 		return IIO_VAL_INT;
286 	case IIO_CHAN_INFO_SCALE:
287 		*val = 0;
288 		mutex_lock(&hx711_data->lock);
289 
290 		*val2 = hx711_get_gain_to_scale(hx711_data->gain_set);
291 
292 		mutex_unlock(&hx711_data->lock);
293 
294 		return IIO_VAL_INT_PLUS_NANO;
295 	default:
296 		return -EINVAL;
297 	}
298 }
299 
hx711_write_raw(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,int val,int val2,long mask)300 static int hx711_write_raw(struct iio_dev *indio_dev,
301 				struct iio_chan_spec const *chan,
302 				int val,
303 				int val2,
304 				long mask)
305 {
306 	struct hx711_data *hx711_data = iio_priv(indio_dev);
307 	int ret;
308 	int gain;
309 
310 	switch (mask) {
311 	case IIO_CHAN_INFO_SCALE:
312 		/*
313 		 * a scale greater than 1 mV per LSB is not possible
314 		 * with the HX711, therefore val must be 0
315 		 */
316 		if (val != 0)
317 			return -EINVAL;
318 
319 		mutex_lock(&hx711_data->lock);
320 
321 		gain = hx711_get_scale_to_gain(val2);
322 		if (gain < 0) {
323 			mutex_unlock(&hx711_data->lock);
324 			return gain;
325 		}
326 
327 		if (gain != hx711_data->gain_set) {
328 			hx711_data->gain_set = gain;
329 			if (gain != 32)
330 				hx711_data->gain_chan_a = gain;
331 
332 			ret = hx711_read(hx711_data);
333 			if (ret < 0) {
334 				mutex_unlock(&hx711_data->lock);
335 				return ret;
336 			}
337 		}
338 
339 		mutex_unlock(&hx711_data->lock);
340 		return 0;
341 	default:
342 		return -EINVAL;
343 	}
344 
345 	return 0;
346 }
347 
hx711_write_raw_get_fmt(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,long mask)348 static int hx711_write_raw_get_fmt(struct iio_dev *indio_dev,
349 		struct iio_chan_spec const *chan,
350 		long mask)
351 {
352 	return IIO_VAL_INT_PLUS_NANO;
353 }
354 
hx711_trigger(int irq,void * p)355 static irqreturn_t hx711_trigger(int irq, void *p)
356 {
357 	struct iio_poll_func *pf = p;
358 	struct iio_dev *indio_dev = pf->indio_dev;
359 	struct hx711_data *hx711_data = iio_priv(indio_dev);
360 	int i, j = 0;
361 
362 	mutex_lock(&hx711_data->lock);
363 
364 	memset(hx711_data->buffer, 0, sizeof(hx711_data->buffer));
365 
366 	iio_for_each_active_channel(indio_dev, i) {
367 		hx711_data->buffer[j] = hx711_reset_read(hx711_data,
368 					indio_dev->channels[i].channel);
369 		j++;
370 	}
371 
372 	iio_push_to_buffers_with_timestamp(indio_dev, hx711_data->buffer,
373 							pf->timestamp);
374 
375 	mutex_unlock(&hx711_data->lock);
376 
377 	iio_trigger_notify_done(indio_dev->trig);
378 
379 	return IRQ_HANDLED;
380 }
381 
hx711_scale_available_show(struct device * dev,struct device_attribute * attr,char * buf)382 static ssize_t hx711_scale_available_show(struct device *dev,
383 				struct device_attribute *attr,
384 				char *buf)
385 {
386 	struct iio_dev_attr *iio_attr = to_iio_dev_attr(attr);
387 	int channel = iio_attr->address;
388 	int i, len = 0;
389 
390 	for (i = 0; i < HX711_GAIN_MAX; i++)
391 		if (hx711_gain_to_scale[i].channel == channel)
392 			len += sprintf(buf + len, "0.%09d ",
393 					hx711_gain_to_scale[i].scale);
394 
395 	len += sprintf(buf + len, "\n");
396 
397 	return len;
398 }
399 
400 static IIO_DEVICE_ATTR(in_voltage0_scale_available, S_IRUGO,
401 	hx711_scale_available_show, NULL, 0);
402 
403 static IIO_DEVICE_ATTR(in_voltage1_scale_available, S_IRUGO,
404 	hx711_scale_available_show, NULL, 1);
405 
406 static struct attribute *hx711_attributes[] = {
407 	&iio_dev_attr_in_voltage0_scale_available.dev_attr.attr,
408 	&iio_dev_attr_in_voltage1_scale_available.dev_attr.attr,
409 	NULL,
410 };
411 
412 static const struct attribute_group hx711_attribute_group = {
413 	.attrs = hx711_attributes,
414 };
415 
416 static const struct iio_info hx711_iio_info = {
417 	.read_raw		= hx711_read_raw,
418 	.write_raw		= hx711_write_raw,
419 	.write_raw_get_fmt	= hx711_write_raw_get_fmt,
420 	.attrs			= &hx711_attribute_group,
421 };
422 
423 static const struct iio_chan_spec hx711_chan_spec[] = {
424 	{
425 		.type = IIO_VOLTAGE,
426 		.channel = 0,
427 		.indexed = 1,
428 		.info_mask_separate = BIT(IIO_CHAN_INFO_RAW),
429 		.info_mask_shared_by_type = BIT(IIO_CHAN_INFO_SCALE),
430 		.scan_index = 0,
431 		.scan_type = {
432 			.sign = 'u',
433 			.realbits = 24,
434 			.storagebits = 32,
435 			.endianness = IIO_CPU,
436 		},
437 	},
438 	{
439 		.type = IIO_VOLTAGE,
440 		.channel = 1,
441 		.indexed = 1,
442 		.info_mask_separate = BIT(IIO_CHAN_INFO_RAW),
443 		.info_mask_shared_by_type = BIT(IIO_CHAN_INFO_SCALE),
444 		.scan_index = 1,
445 		.scan_type = {
446 			.sign = 'u',
447 			.realbits = 24,
448 			.storagebits = 32,
449 			.endianness = IIO_CPU,
450 		},
451 	},
452 	IIO_CHAN_SOFT_TIMESTAMP(2),
453 };
454 
hx711_probe(struct platform_device * pdev)455 static int hx711_probe(struct platform_device *pdev)
456 {
457 	struct device *dev = &pdev->dev;
458 	struct hx711_data *hx711_data;
459 	struct iio_dev *indio_dev;
460 	int ret;
461 	int i;
462 
463 	indio_dev = devm_iio_device_alloc(dev, sizeof(struct hx711_data));
464 	if (!indio_dev)
465 		return dev_err_probe(dev, -ENOMEM, "failed to allocate IIO device\n");
466 
467 	hx711_data = iio_priv(indio_dev);
468 	hx711_data->dev = dev;
469 
470 	mutex_init(&hx711_data->lock);
471 
472 	/*
473 	 * PD_SCK stands for power down and serial clock input of HX711
474 	 * in the driver it is an output
475 	 */
476 	hx711_data->gpiod_pd_sck = devm_gpiod_get(dev, "sck", GPIOD_OUT_LOW);
477 	if (IS_ERR(hx711_data->gpiod_pd_sck))
478 		return dev_err_probe(dev, PTR_ERR(hx711_data->gpiod_pd_sck),
479 				     "failed to get sck-gpiod\n");
480 
481 	/*
482 	 * DOUT stands for serial data output of HX711
483 	 * for the driver it is an input
484 	 */
485 	hx711_data->gpiod_dout = devm_gpiod_get(dev, "dout", GPIOD_IN);
486 	if (IS_ERR(hx711_data->gpiod_dout))
487 		return dev_err_probe(dev, PTR_ERR(hx711_data->gpiod_dout),
488 				     "failed to get dout-gpiod\n");
489 
490 	ret = devm_regulator_get_enable_read_voltage(dev, "avdd");
491 	if (ret < 0)
492 		return ret;
493 
494 	/*
495 	 * with
496 	 * full scale differential input range: AVDD / GAIN
497 	 * full scale output data: 2^24
498 	 * we can say:
499 	 *     AVDD / GAIN = 2^24
500 	 * therefore:
501 	 *     1 LSB = AVDD / GAIN / 2^24
502 	 * AVDD is in uV, but we need 10^-9 mV
503 	 * approximately to fit into a 32 bit number:
504 	 * 1 LSB = (AVDD * 100) / GAIN / 1678 [10^-9 mV]
505 	 */
506 
507 	/* we need 10^-9 mV */
508 	ret *= 100;
509 
510 	for (i = 0; i < HX711_GAIN_MAX; i++)
511 		hx711_gain_to_scale[i].scale =
512 			ret / hx711_gain_to_scale[i].gain / 1678;
513 
514 	hx711_data->gain_set = 128;
515 	hx711_data->gain_chan_a = 128;
516 
517 	hx711_data->clock_frequency = 400000;
518 	ret = device_property_read_u32(&pdev->dev, "clock-frequency",
519 					&hx711_data->clock_frequency);
520 
521 	/*
522 	 * datasheet says the high level of PD_SCK has a maximum duration
523 	 * of 50 microseconds
524 	 */
525 	if (hx711_data->clock_frequency < 20000) {
526 		dev_warn(dev, "clock-frequency too low - assuming 400 kHz\n");
527 		hx711_data->clock_frequency = 400000;
528 	}
529 
530 	hx711_data->data_ready_delay_ns =
531 				1000000000 / hx711_data->clock_frequency;
532 
533 	indio_dev->name = "hx711";
534 	indio_dev->info = &hx711_iio_info;
535 	indio_dev->modes = INDIO_DIRECT_MODE;
536 	indio_dev->channels = hx711_chan_spec;
537 	indio_dev->num_channels = ARRAY_SIZE(hx711_chan_spec);
538 
539 	ret = devm_iio_triggered_buffer_setup(dev, indio_dev,
540 					      iio_pollfunc_store_time,
541 					      hx711_trigger, NULL);
542 	if (ret < 0)
543 		return dev_err_probe(dev, ret,
544 				     "setup of iio triggered buffer failed\n");
545 
546 	ret = devm_iio_device_register(dev, indio_dev);
547 	if (ret < 0)
548 		return dev_err_probe(dev, ret, "Couldn't register the device\n");
549 
550 	return 0;
551 }
552 
553 static const struct of_device_id of_hx711_match[] = {
554 	{ .compatible = "avia,hx711", },
555 	{ }
556 };
557 
558 MODULE_DEVICE_TABLE(of, of_hx711_match);
559 
560 static struct platform_driver hx711_driver = {
561 	.probe		= hx711_probe,
562 	.driver		= {
563 		.name		= "hx711-gpio",
564 		.of_match_table	= of_hx711_match,
565 	},
566 };
567 
568 module_platform_driver(hx711_driver);
569 
570 MODULE_AUTHOR("Andreas Klinger <ak@it-klinger.de>");
571 MODULE_DESCRIPTION("HX711 bitbanging driver - ADC for weight cells");
572 MODULE_LICENSE("GPL");
573 MODULE_ALIAS("platform:hx711-gpio");
574 
575