1 /*
2  * Copyright 2021 Google LLC
3  * Copyright 2022 TOKITA Hiroshi <tokita.hiroshi@fujitsu.com>
4  *
5  * SPDX-License-Identifier: Apache-2.0
6  */
7 
8 #define DT_DRV_COMPAT raspberrypi_pico_adc
9 
10 #include <zephyr/drivers/adc.h>
11 #include <zephyr/drivers/clock_control.h>
12 #include <zephyr/drivers/pinctrl.h>
13 #include <zephyr/drivers/reset.h>
14 #include <zephyr/logging/log.h>
15 
16 #include <hardware/adc.h>
17 #include <zephyr/irq.h>
18 
19 LOG_MODULE_REGISTER(adc_rpi, CONFIG_ADC_LOG_LEVEL);
20 
21 #define ADC_CONTEXT_USES_KERNEL_TIMER
22 #include "adc_context.h"
23 
24 #define ADC_RPI_MAX_RESOLUTION 12
25 
26 /** Bits numbers of rrobin register mean an available number of channels. */
27 #define ADC_RPI_CHANNEL_NUM (ADC_CS_RROBIN_MSB - ADC_CS_RROBIN_LSB + 1)
28 
29 /**
30  * @brief RaspberryPi Pico ADC config
31  *
32  * This structure contains constant data for given instance of RaspberryPi Pico ADC.
33  */
34 struct adc_rpi_config {
35 	/** Number of supported channels */
36 	uint8_t num_channels;
37 	/** pinctrl configs */
38 	const struct pinctrl_dev_config *pcfg;
39 	/** function pointer to irq setup */
40 	void (*irq_configure)(void);
41 	/** Pointer to clock controller device */
42 	const struct device *clk_dev;
43 	/** Clock id of ADC clock */
44 	clock_control_subsys_t clk_id;
45 	/** Reset controller config */
46 	const struct reset_dt_spec reset;
47 };
48 
49 /**
50  * @brief RaspberryPi Pico ADC data
51  *
52  * This structure contains data structures used by a RaspberryPi Pico ADC.
53  */
54 struct adc_rpi_data {
55 	/** Structure that handle state of ongoing read operation */
56 	struct adc_context ctx;
57 	/** Pointer to RaspberryPi Pico ADC own device structure */
58 	const struct device *dev;
59 	/** Pointer to memory where next sample will be written */
60 	uint16_t *buf;
61 	/** Pointer to where will be data stored in case of repeated sampling */
62 	uint16_t *repeat_buf;
63 	/** Mask with channels that will be sampled */
64 	uint32_t channels;
65 };
66 
adc_start_once(void)67 static inline void adc_start_once(void)
68 {
69 	hw_set_bits(&adc_hw->cs, ADC_CS_START_ONCE_BITS);
70 }
71 
adc_get_result(void)72 static inline uint16_t adc_get_result(void)
73 {
74 	return (uint16_t)adc_hw->result;
75 }
76 
adc_get_err(void)77 static inline bool adc_get_err(void)
78 {
79 	return (adc_hw->cs & ADC_CS_ERR_BITS) ? true : false;
80 }
81 
adc_clear_errors(void)82 static inline void adc_clear_errors(void)
83 {
84 	/* write 1 to clear */
85 	hw_set_bits(&adc_hw->fcs, ADC_FCS_OVER_BITS);
86 	hw_set_bits(&adc_hw->fcs, ADC_FCS_UNDER_BITS);
87 	hw_set_bits(&adc_hw->fcs, ADC_FCS_ERR_BITS);
88 	hw_set_bits(&adc_hw->cs, ADC_CS_ERR_STICKY_BITS);
89 }
90 
adc_enable(void)91 static inline void adc_enable(void)
92 {
93 	adc_hw->cs = ADC_CS_EN_BITS;
94 	while (!(adc_hw->cs & ADC_CS_READY_BITS)) {
95 		;
96 	}
97 }
98 
adc_rpi_channel_setup(const struct device * dev,const struct adc_channel_cfg * channel_cfg)99 static int adc_rpi_channel_setup(const struct device *dev,
100 				 const struct adc_channel_cfg *channel_cfg)
101 {
102 	const struct adc_rpi_config *config = dev->config;
103 
104 	if (channel_cfg->channel_id >= config->num_channels) {
105 		LOG_ERR("unsupported channel id '%d'", channel_cfg->channel_id);
106 		return -ENOTSUP;
107 	}
108 
109 	if (channel_cfg->acquisition_time != ADC_ACQ_TIME_DEFAULT) {
110 		LOG_ERR("Acquisition time is not valid");
111 		return -EINVAL;
112 	}
113 
114 	if (channel_cfg->differential) {
115 		LOG_ERR("unsupported differential mode");
116 		return -ENOTSUP;
117 	}
118 
119 	if (channel_cfg->gain != ADC_GAIN_1) {
120 		LOG_ERR("Gain is not valid");
121 		return -EINVAL;
122 	}
123 
124 	return 0;
125 }
126 
127 /**
128  * @brief Check if buffer in @p sequence is big enough to hold all ADC samples
129  *
130  * @param dev RaspberryPi Pico ADC device
131  * @param sequence ADC sequence description
132  *
133  * @return 0 on success
134  * @return -ENOMEM if buffer is not big enough
135  */
adc_rpi_check_buffer_size(const struct device * dev,const struct adc_sequence * sequence)136 static int adc_rpi_check_buffer_size(const struct device *dev,
137 				     const struct adc_sequence *sequence)
138 {
139 	const struct adc_rpi_config *config = dev->config;
140 	uint8_t channels = 0;
141 	size_t needed;
142 	uint32_t mask;
143 
144 	for (mask = BIT(config->num_channels - 1); mask != 0; mask >>= 1) {
145 		if (mask & sequence->channels) {
146 			channels++;
147 		}
148 	}
149 
150 	needed = channels * sizeof(uint16_t);
151 	if (sequence->options) {
152 		needed *= (1 + sequence->options->extra_samplings);
153 	}
154 
155 	if (sequence->buffer_size < needed) {
156 		return -ENOMEM;
157 	}
158 
159 	return 0;
160 }
161 
162 /**
163  * @brief Start processing read request
164  *
165  * @param dev RaspberryPi Pico ADC device
166  * @param sequence ADC sequence description
167  *
168  * @return 0 on success
169  * @return -ENOTSUP if requested resolution or channel is out side of supported
170  *         range
171  * @return -ENOMEM if buffer is not big enough
172  *         (see @ref adc_rpi_check_buffer_size)
173  * @return other error code returned by adc_context_wait_for_completion
174  */
adc_rpi_start_read(const struct device * dev,const struct adc_sequence * sequence)175 static int adc_rpi_start_read(const struct device *dev,
176 			      const struct adc_sequence *sequence)
177 {
178 	const struct adc_rpi_config *config = dev->config;
179 	struct adc_rpi_data *data = dev->data;
180 	int err;
181 
182 	if (sequence->resolution > ADC_RPI_MAX_RESOLUTION ||
183 	    sequence->resolution == 0) {
184 		LOG_ERR("unsupported resolution %d", sequence->resolution);
185 		return -ENOTSUP;
186 	}
187 
188 	if (find_msb_set(sequence->channels) > config->num_channels) {
189 		LOG_ERR("unsupported channels in mask: 0x%08x",
190 			sequence->channels);
191 		return -ENOTSUP;
192 	}
193 
194 	err = adc_rpi_check_buffer_size(dev, sequence);
195 	if (err) {
196 		LOG_ERR("buffer size too small");
197 		return err;
198 	}
199 
200 	data->buf = sequence->buffer;
201 	adc_context_start_read(&data->ctx, sequence);
202 
203 	return adc_context_wait_for_completion(&data->ctx);
204 }
205 
206 /**
207  * Interrupt handler
208  */
adc_rpi_isr(const struct device * dev)209 static void adc_rpi_isr(const struct device *dev)
210 {
211 	struct adc_rpi_data *data = dev->data;
212 	uint16_t result;
213 	uint8_t ainsel;
214 
215 	/* Fetch result */
216 	result = adc_get_result();
217 	ainsel = adc_get_selected_input();
218 
219 	/* Drain FIFO */
220 	while (!adc_fifo_is_empty()) {
221 		(void)adc_fifo_get();
222 	}
223 
224 	/* Abort converting if error detected. */
225 	if (adc_get_err()) {
226 		adc_context_complete(&data->ctx, -EIO);
227 		return;
228 	}
229 
230 	/* Copy to buffer and mark this channel as completed to channels bitmap. */
231 	*data->buf++ = result;
232 	data->channels &= ~(BIT(ainsel));
233 
234 	/* Notify result if all data gathered. */
235 	if (data->channels == 0) {
236 		adc_context_on_sampling_done(&data->ctx, dev);
237 		return;
238 	}
239 
240 	/* Kick next channel conversion */
241 	ainsel = (uint8_t)(find_lsb_set(data->channels) - 1);
242 	adc_select_input(ainsel);
243 	adc_start_once();
244 }
245 
adc_rpi_read_async(const struct device * dev,const struct adc_sequence * sequence,struct k_poll_signal * async)246 static int adc_rpi_read_async(const struct device *dev,
247 			      const struct adc_sequence *sequence,
248 			      struct k_poll_signal *async)
249 {
250 	struct adc_rpi_data *data = dev->data;
251 	int err;
252 
253 	adc_context_lock(&data->ctx, async ? true : false, async);
254 	err = adc_rpi_start_read(dev, sequence);
255 	adc_context_release(&data->ctx, err);
256 
257 	return err;
258 }
259 
adc_rpi_read(const struct device * dev,const struct adc_sequence * sequence)260 static int adc_rpi_read(const struct device *dev,
261 			const struct adc_sequence *sequence)
262 {
263 	return adc_rpi_read_async(dev, sequence, NULL);
264 }
265 
adc_context_start_sampling(struct adc_context * ctx)266 static void adc_context_start_sampling(struct adc_context *ctx)
267 {
268 	struct adc_rpi_data *data = CONTAINER_OF(ctx, struct adc_rpi_data,
269 						 ctx);
270 
271 	data->channels = ctx->sequence.channels;
272 	data->repeat_buf = data->buf;
273 
274 	adc_clear_errors();
275 
276 	/* Find next channel and start conversion */
277 	adc_select_input(find_lsb_set(data->channels) - 1);
278 	adc_start_once();
279 }
280 
adc_context_update_buffer_pointer(struct adc_context * ctx,bool repeat_sampling)281 static void adc_context_update_buffer_pointer(struct adc_context *ctx,
282 					      bool repeat_sampling)
283 {
284 	struct adc_rpi_data *data = CONTAINER_OF(ctx, struct adc_rpi_data,
285 						 ctx);
286 
287 	if (repeat_sampling) {
288 		data->buf = data->repeat_buf;
289 	}
290 }
291 
292 /**
293  * @brief Function called on init for each RaspberryPi Pico ADC device. It setups all
294  *        channels to return constant 0 mV and create acquisition thread.
295  *
296  * @param dev RaspberryPi Pico ADC device
297  *
298  * @return 0 on success
299  */
adc_rpi_init(const struct device * dev)300 static int adc_rpi_init(const struct device *dev)
301 {
302 	const struct adc_rpi_config *config = dev->config;
303 	struct adc_rpi_data *data = dev->data;
304 	int ret;
305 
306 	ret = pinctrl_apply_state(config->pcfg, PINCTRL_STATE_DEFAULT);
307 	if (ret < 0) {
308 		return ret;
309 	}
310 
311 	ret = clock_control_on(config->clk_dev, config->clk_id);
312 	if (ret < 0) {
313 		return ret;
314 	}
315 
316 	ret = reset_line_toggle_dt(&config->reset);
317 	if (ret < 0) {
318 		return ret;
319 	}
320 
321 	config->irq_configure();
322 
323 	/*
324 	 * Configure the FIFO control register.
325 	 * Set the threshold as 1 for getting notification immediately
326 	 * on converting completed.
327 	 */
328 	adc_fifo_setup(true, false, 1, true, true);
329 
330 	/* Set max speed to conversion */
331 	adc_set_clkdiv(0.f);
332 
333 	/* Enable ADC and wait becoming READY */
334 	adc_enable();
335 
336 	/* Enable FIFO interrupt */
337 	adc_irq_set_enabled(true);
338 
339 	adc_context_unlock_unconditionally(&data->ctx);
340 
341 	return 0;
342 }
343 
344 #define IRQ_CONFIGURE_FUNC(idx)						   \
345 	static void adc_rpi_configure_func_##idx(void)			   \
346 	{								   \
347 		IRQ_CONNECT(DT_INST_IRQN(idx), DT_INST_IRQ(idx, priority), \
348 			    adc_rpi_isr, DEVICE_DT_INST_GET(idx), 0);	   \
349 		irq_enable(DT_INST_IRQN(idx));				   \
350 	}
351 
352 #define IRQ_CONFIGURE_DEFINE(idx) .irq_configure = adc_rpi_configure_func_##idx
353 
354 #define ADC_RPI_INIT(idx)                                                                          \
355 	IRQ_CONFIGURE_FUNC(idx)                                                                    \
356 	PINCTRL_DT_INST_DEFINE(idx);                                                               \
357 	static DEVICE_API(adc, adc_rpi_api_##idx) = {                                              \
358 		.channel_setup = adc_rpi_channel_setup,                                            \
359 		.read = adc_rpi_read,                                                              \
360 		.ref_internal = DT_INST_PROP(idx, vref_mv),                                        \
361 		IF_ENABLED(CONFIG_ADC_ASYNC, (.read_async = adc_rpi_read_async,))                  \
362 	};                                                                                         \
363 	static const struct adc_rpi_config adc_rpi_config_##idx = {                                \
364 		.num_channels = ADC_RPI_CHANNEL_NUM,                                               \
365 		.pcfg = PINCTRL_DT_INST_DEV_CONFIG_GET(idx),                                       \
366 		.clk_dev = DEVICE_DT_GET(DT_INST_CLOCKS_CTLR(idx)),                                \
367 		.clk_id = (clock_control_subsys_t)DT_INST_PHA_BY_IDX(idx, clocks, 0, clk_id),      \
368 		.reset = RESET_DT_SPEC_INST_GET(idx),                                              \
369 		IRQ_CONFIGURE_DEFINE(idx),                                                         \
370 	};                                                                                         \
371 	static struct adc_rpi_data adc_rpi_data_##idx = {                                          \
372 		ADC_CONTEXT_INIT_TIMER(adc_rpi_data_##idx, ctx),                                   \
373 		ADC_CONTEXT_INIT_LOCK(adc_rpi_data_##idx, ctx),                                    \
374 		ADC_CONTEXT_INIT_SYNC(adc_rpi_data_##idx, ctx),                                    \
375 		.dev = DEVICE_DT_INST_GET(idx),                                                    \
376 	};                                                                                         \
377                                                                                                    \
378 	DEVICE_DT_INST_DEFINE(idx, adc_rpi_init, NULL,                                             \
379 			      &adc_rpi_data_##idx,                                                 \
380 			      &adc_rpi_config_##idx, POST_KERNEL,                                  \
381 			      CONFIG_ADC_INIT_PRIORITY,                                            \
382 			      &adc_rpi_api_##idx)
383 
384 DT_INST_FOREACH_STATUS_OKAY(ADC_RPI_INIT);
385