• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * SRF04: ultrasonic sensor for distance measuring by using GPIOs
3  *
4  * Copyright (c) 2017 Andreas Klinger <ak@it-klinger.de>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  * GNU General Public License for more details.
15  *
16  * For details about the device see:
17  * http://www.robot-electronics.co.uk/htm/srf04tech.htm
18  *
19  * the measurement cycle as timing diagram looks like:
20  *
21  *          +---+
22  * GPIO     |   |
23  * trig:  --+   +------------------------------------------------------
24  *          ^   ^
25  *          |<->|
26  *         udelay(10)
27  *
28  * ultra           +-+ +-+ +-+
29  * sonic           | | | | | |
30  * burst: ---------+ +-+ +-+ +-----------------------------------------
31  *                           .
32  * ultra                     .              +-+ +-+ +-+
33  * sonic                     .              | | | | | |
34  * echo:  ----------------------------------+ +-+ +-+ +----------------
35  *                           .                        .
36  *                           +------------------------+
37  * GPIO                      |                        |
38  * echo:  -------------------+                        +---------------
39  *                           ^                        ^
40  *                           interrupt                interrupt
41  *                           (ts_rising)              (ts_falling)
42  *                           |<---------------------->|
43  *                              pulse time measured
44  *                              --> one round trip of ultra sonic waves
45  */
46 #include <linux/err.h>
47 #include <linux/gpio/consumer.h>
48 #include <linux/kernel.h>
49 #include <linux/module.h>
50 #include <linux/of.h>
51 #include <linux/platform_device.h>
52 #include <linux/property.h>
53 #include <linux/sched.h>
54 #include <linux/interrupt.h>
55 #include <linux/delay.h>
56 #include <linux/iio/iio.h>
57 #include <linux/iio/sysfs.h>
58 
59 struct srf04_data {
60 	struct device		*dev;
61 	struct gpio_desc	*gpiod_trig;
62 	struct gpio_desc	*gpiod_echo;
63 	struct mutex		lock;
64 	int			irqnr;
65 	ktime_t			ts_rising;
66 	ktime_t			ts_falling;
67 	struct completion	rising;
68 	struct completion	falling;
69 };
70 
srf04_handle_irq(int irq,void * dev_id)71 static irqreturn_t srf04_handle_irq(int irq, void *dev_id)
72 {
73 	struct iio_dev *indio_dev = dev_id;
74 	struct srf04_data *data = iio_priv(indio_dev);
75 	ktime_t now = ktime_get();
76 
77 	if (gpiod_get_value(data->gpiod_echo)) {
78 		data->ts_rising = now;
79 		complete(&data->rising);
80 	} else {
81 		data->ts_falling = now;
82 		complete(&data->falling);
83 	}
84 
85 	return IRQ_HANDLED;
86 }
87 
srf04_read(struct srf04_data * data)88 static int srf04_read(struct srf04_data *data)
89 {
90 	int ret;
91 	ktime_t ktime_dt;
92 	u64 dt_ns;
93 	u32 time_ns, distance_mm;
94 
95 	/*
96 	 * just one read-echo-cycle can take place at a time
97 	 * ==> lock against concurrent reading calls
98 	 */
99 	mutex_lock(&data->lock);
100 
101 	reinit_completion(&data->rising);
102 	reinit_completion(&data->falling);
103 
104 	gpiod_set_value(data->gpiod_trig, 1);
105 	udelay(10);
106 	gpiod_set_value(data->gpiod_trig, 0);
107 
108 	/* it should not take more than 20 ms until echo is rising */
109 	ret = wait_for_completion_killable_timeout(&data->rising, HZ/50);
110 	if (ret < 0) {
111 		mutex_unlock(&data->lock);
112 		return ret;
113 	} else if (ret == 0) {
114 		mutex_unlock(&data->lock);
115 		return -ETIMEDOUT;
116 	}
117 
118 	/* it cannot take more than 50 ms until echo is falling */
119 	ret = wait_for_completion_killable_timeout(&data->falling, HZ/20);
120 	if (ret < 0) {
121 		mutex_unlock(&data->lock);
122 		return ret;
123 	} else if (ret == 0) {
124 		mutex_unlock(&data->lock);
125 		return -ETIMEDOUT;
126 	}
127 
128 	ktime_dt = ktime_sub(data->ts_falling, data->ts_rising);
129 
130 	mutex_unlock(&data->lock);
131 
132 	dt_ns = ktime_to_ns(ktime_dt);
133 	/*
134 	 * measuring more than 6,45 meters is beyond the capabilities of
135 	 * the supported sensors
136 	 * ==> filter out invalid results for not measuring echos of
137 	 *     another us sensor
138 	 *
139 	 * formula:
140 	 *         distance     6,45 * 2 m
141 	 * time = ---------- = ------------ = 40438871 ns
142 	 *          speed         319 m/s
143 	 *
144 	 * using a minimum speed at -20 °C of 319 m/s
145 	 */
146 	if (dt_ns > 40438871)
147 		return -EIO;
148 
149 	time_ns = dt_ns;
150 
151 	/*
152 	 * the speed as function of the temperature is approximately:
153 	 *
154 	 * speed = 331,5 + 0,6 * Temp
155 	 *   with Temp in °C
156 	 *   and speed in m/s
157 	 *
158 	 * use 343,5 m/s as ultrasonic speed at 20 °C here in absence of the
159 	 * temperature
160 	 *
161 	 * therefore:
162 	 *             time     343,5     time * 106
163 	 * distance = ------ * ------- = ------------
164 	 *             10^6         2         617176
165 	 *   with time in ns
166 	 *   and distance in mm (one way)
167 	 *
168 	 * because we limit to 6,45 meters the multiplication with 106 just
169 	 * fits into 32 bit
170 	 */
171 	distance_mm = time_ns * 106 / 617176;
172 
173 	return distance_mm;
174 }
175 
srf04_read_raw(struct iio_dev * indio_dev,struct iio_chan_spec const * channel,int * val,int * val2,long info)176 static int srf04_read_raw(struct iio_dev *indio_dev,
177 			    struct iio_chan_spec const *channel, int *val,
178 			    int *val2, long info)
179 {
180 	struct srf04_data *data = iio_priv(indio_dev);
181 	int ret;
182 
183 	if (channel->type != IIO_DISTANCE)
184 		return -EINVAL;
185 
186 	switch (info) {
187 	case IIO_CHAN_INFO_RAW:
188 		ret = srf04_read(data);
189 		if (ret < 0)
190 			return ret;
191 		*val = ret;
192 		return IIO_VAL_INT;
193 	case IIO_CHAN_INFO_SCALE:
194 		/*
195 		 * theoretical maximum resolution is 3 mm
196 		 * 1 LSB is 1 mm
197 		 */
198 		*val = 0;
199 		*val2 = 1000;
200 		return IIO_VAL_INT_PLUS_MICRO;
201 	default:
202 		return -EINVAL;
203 	}
204 }
205 
206 static const struct iio_info srf04_iio_info = {
207 	.read_raw		= srf04_read_raw,
208 };
209 
210 static const struct iio_chan_spec srf04_chan_spec[] = {
211 	{
212 		.type = IIO_DISTANCE,
213 		.info_mask_separate =
214 				BIT(IIO_CHAN_INFO_RAW) |
215 				BIT(IIO_CHAN_INFO_SCALE),
216 	},
217 };
218 
srf04_probe(struct platform_device * pdev)219 static int srf04_probe(struct platform_device *pdev)
220 {
221 	struct device *dev = &pdev->dev;
222 	struct srf04_data *data;
223 	struct iio_dev *indio_dev;
224 	int ret;
225 
226 	indio_dev = devm_iio_device_alloc(dev, sizeof(struct srf04_data));
227 	if (!indio_dev) {
228 		dev_err(dev, "failed to allocate IIO device\n");
229 		return -ENOMEM;
230 	}
231 
232 	data = iio_priv(indio_dev);
233 	data->dev = dev;
234 
235 	mutex_init(&data->lock);
236 	init_completion(&data->rising);
237 	init_completion(&data->falling);
238 
239 	data->gpiod_trig = devm_gpiod_get(dev, "trig", GPIOD_OUT_LOW);
240 	if (IS_ERR(data->gpiod_trig)) {
241 		dev_err(dev, "failed to get trig-gpios: err=%ld\n",
242 					PTR_ERR(data->gpiod_trig));
243 		return PTR_ERR(data->gpiod_trig);
244 	}
245 
246 	data->gpiod_echo = devm_gpiod_get(dev, "echo", GPIOD_IN);
247 	if (IS_ERR(data->gpiod_echo)) {
248 		dev_err(dev, "failed to get echo-gpios: err=%ld\n",
249 					PTR_ERR(data->gpiod_echo));
250 		return PTR_ERR(data->gpiod_echo);
251 	}
252 
253 	if (gpiod_cansleep(data->gpiod_echo)) {
254 		dev_err(data->dev, "cansleep-GPIOs not supported\n");
255 		return -ENODEV;
256 	}
257 
258 	data->irqnr = gpiod_to_irq(data->gpiod_echo);
259 	if (data->irqnr < 0) {
260 		dev_err(data->dev, "gpiod_to_irq: %d\n", data->irqnr);
261 		return data->irqnr;
262 	}
263 
264 	ret = devm_request_irq(dev, data->irqnr, srf04_handle_irq,
265 			IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING,
266 			pdev->name, indio_dev);
267 	if (ret < 0) {
268 		dev_err(data->dev, "request_irq: %d\n", ret);
269 		return ret;
270 	}
271 
272 	platform_set_drvdata(pdev, indio_dev);
273 
274 	indio_dev->name = "srf04";
275 	indio_dev->dev.parent = &pdev->dev;
276 	indio_dev->info = &srf04_iio_info;
277 	indio_dev->modes = INDIO_DIRECT_MODE;
278 	indio_dev->channels = srf04_chan_spec;
279 	indio_dev->num_channels = ARRAY_SIZE(srf04_chan_spec);
280 
281 	return devm_iio_device_register(dev, indio_dev);
282 }
283 
284 static const struct of_device_id of_srf04_match[] = {
285 	{ .compatible = "devantech,srf04", },
286 	{},
287 };
288 
289 MODULE_DEVICE_TABLE(of, of_srf04_match);
290 
291 static struct platform_driver srf04_driver = {
292 	.probe		= srf04_probe,
293 	.driver		= {
294 		.name		= "srf04-gpio",
295 		.of_match_table	= of_srf04_match,
296 	},
297 };
298 
299 module_platform_driver(srf04_driver);
300 
301 MODULE_AUTHOR("Andreas Klinger <ak@it-klinger.de>");
302 MODULE_DESCRIPTION("SRF04 ultrasonic sensor for distance measuring using GPIOs");
303 MODULE_LICENSE("GPL");
304 MODULE_ALIAS("platform:srf04");
305