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 
adc_rpi_channel_setup(const struct device * dev,const struct adc_channel_cfg * channel_cfg)98 static int adc_rpi_channel_setup(const struct device *dev,
99 				 const struct adc_channel_cfg *channel_cfg)
100 {
101 	const struct adc_rpi_config *config = dev->config;
102 
103 	if (channel_cfg->channel_id >= config->num_channels) {
104 		LOG_ERR("unsupported channel id '%d'", channel_cfg->channel_id);
105 		return -ENOTSUP;
106 	}
107 
108 	if (channel_cfg->acquisition_time != ADC_ACQ_TIME_DEFAULT) {
109 		LOG_ERR("Acquisition time is not valid");
110 		return -EINVAL;
111 	}
112 
113 	if (channel_cfg->differential) {
114 		LOG_ERR("unsupported differential mode");
115 		return -ENOTSUP;
116 	}
117 
118 	if (channel_cfg->gain != ADC_GAIN_1) {
119 		LOG_ERR("Gain is not valid");
120 		return -EINVAL;
121 	}
122 
123 	return 0;
124 }
125 
126 /**
127  * @brief Check if buffer in @p sequence is big enough to hold all ADC samples
128  *
129  * @param dev RaspberryPi Pico ADC device
130  * @param sequence ADC sequence description
131  *
132  * @return 0 on success
133  * @return -ENOMEM if buffer is not big enough
134  */
adc_rpi_check_buffer_size(const struct device * dev,const struct adc_sequence * sequence)135 static int adc_rpi_check_buffer_size(const struct device *dev,
136 				     const struct adc_sequence *sequence)
137 {
138 	const struct adc_rpi_config *config = dev->config;
139 	uint8_t channels = 0;
140 	size_t needed;
141 	uint32_t mask;
142 
143 	for (mask = BIT(config->num_channels - 1); mask != 0; mask >>= 1) {
144 		if (mask & sequence->channels) {
145 			channels++;
146 		}
147 	}
148 
149 	needed = channels * sizeof(uint16_t);
150 	if (sequence->options) {
151 		needed *= (1 + sequence->options->extra_samplings);
152 	}
153 
154 	if (sequence->buffer_size < needed) {
155 		return -ENOMEM;
156 	}
157 
158 	return 0;
159 }
160 
161 /**
162  * @brief Start processing read request
163  *
164  * @param dev RaspberryPi Pico ADC device
165  * @param sequence ADC sequence description
166  *
167  * @return 0 on success
168  * @return -ENOTSUP if requested resolution or channel is out side of supported
169  *         range
170  * @return -ENOMEM if buffer is not big enough
171  *         (see @ref adc_rpi_check_buffer_size)
172  * @return other error code returned by adc_context_wait_for_completion
173  */
adc_rpi_start_read(const struct device * dev,const struct adc_sequence * sequence)174 static int adc_rpi_start_read(const struct device *dev,
175 			      const struct adc_sequence *sequence)
176 {
177 	const struct adc_rpi_config *config = dev->config;
178 	struct adc_rpi_data *data = dev->data;
179 	int err;
180 
181 	if (sequence->resolution > ADC_RPI_MAX_RESOLUTION ||
182 	    sequence->resolution == 0) {
183 		LOG_ERR("unsupported resolution %d", sequence->resolution);
184 		return -ENOTSUP;
185 	}
186 
187 	if (find_msb_set(sequence->channels) > config->num_channels) {
188 		LOG_ERR("unsupported channels in mask: 0x%08x",
189 			sequence->channels);
190 		return -ENOTSUP;
191 	}
192 
193 	err = adc_rpi_check_buffer_size(dev, sequence);
194 	if (err) {
195 		LOG_ERR("buffer size too small");
196 		return err;
197 	}
198 
199 	data->buf = sequence->buffer;
200 	adc_context_start_read(&data->ctx, sequence);
201 
202 	return adc_context_wait_for_completion(&data->ctx);
203 }
204 
205 /**
206  * Interrupt handler
207  */
adc_rpi_isr(const struct device * dev)208 static void adc_rpi_isr(const struct device *dev)
209 {
210 	struct adc_rpi_data *data = dev->data;
211 	uint16_t result;
212 	uint8_t ainsel;
213 
214 	/* Fetch result */
215 	result = adc_get_result();
216 	ainsel = adc_get_selected_input();
217 
218 	/* Drain FIFO */
219 	while (!adc_fifo_is_empty()) {
220 		(void)adc_fifo_get();
221 	}
222 
223 	/* Abort converting if error detected. */
224 	if (adc_get_err()) {
225 		adc_context_complete(&data->ctx, -EIO);
226 		return;
227 	}
228 
229 	/* Copy to buffer and mark this channel as completed to channels bitmap. */
230 	*data->buf++ = result;
231 	data->channels &= ~(BIT(ainsel));
232 
233 	/* Notify result if all data gathered. */
234 	if (data->channels == 0) {
235 		adc_context_on_sampling_done(&data->ctx, dev);
236 		return;
237 	}
238 
239 	/* Kick next channel conversion */
240 	ainsel = (uint8_t)(find_lsb_set(data->channels) - 1);
241 	adc_select_input(ainsel);
242 	adc_start_once();
243 }
244 
adc_rpi_read_async(const struct device * dev,const struct adc_sequence * sequence,struct k_poll_signal * async)245 static int adc_rpi_read_async(const struct device *dev,
246 			      const struct adc_sequence *sequence,
247 			      struct k_poll_signal *async)
248 {
249 	struct adc_rpi_data *data = dev->data;
250 	int err;
251 
252 	adc_context_lock(&data->ctx, async ? true : false, async);
253 	err = adc_rpi_start_read(dev, sequence);
254 	adc_context_release(&data->ctx, err);
255 
256 	return err;
257 }
258 
adc_rpi_read(const struct device * dev,const struct adc_sequence * sequence)259 static int adc_rpi_read(const struct device *dev,
260 			const struct adc_sequence *sequence)
261 {
262 	return adc_rpi_read_async(dev, sequence, NULL);
263 }
264 
adc_context_start_sampling(struct adc_context * ctx)265 static void adc_context_start_sampling(struct adc_context *ctx)
266 {
267 	struct adc_rpi_data *data = CONTAINER_OF(ctx, struct adc_rpi_data,
268 						 ctx);
269 
270 	data->channels = ctx->sequence.channels;
271 	data->repeat_buf = data->buf;
272 
273 	adc_clear_errors();
274 
275 	/* Find next channel and start conversion */
276 	adc_select_input(find_lsb_set(data->channels) - 1);
277 	adc_start_once();
278 }
279 
adc_context_update_buffer_pointer(struct adc_context * ctx,bool repeat_sampling)280 static void adc_context_update_buffer_pointer(struct adc_context *ctx,
281 					      bool repeat_sampling)
282 {
283 	struct adc_rpi_data *data = CONTAINER_OF(ctx, struct adc_rpi_data,
284 						 ctx);
285 
286 	if (repeat_sampling) {
287 		data->buf = data->repeat_buf;
288 	}
289 }
290 
291 /**
292  * @brief Function called on init for each RaspberryPi Pico ADC device. It setups all
293  *        channels to return constant 0 mV and create acquisition thread.
294  *
295  * @param dev RaspberryPi Pico ADC device
296  *
297  * @return 0 on success
298  */
adc_rpi_init(const struct device * dev)299 static int adc_rpi_init(const struct device *dev)
300 {
301 	const struct adc_rpi_config *config = dev->config;
302 	struct adc_rpi_data *data = dev->data;
303 	int ret;
304 
305 	ret = pinctrl_apply_state(config->pcfg, PINCTRL_STATE_DEFAULT);
306 	if (ret < 0) {
307 		return ret;
308 	}
309 
310 	ret = clock_control_on(config->clk_dev, config->clk_id);
311 	if (ret < 0) {
312 		return ret;
313 	}
314 
315 	ret = reset_line_toggle_dt(&config->reset);
316 	if (ret < 0) {
317 		return ret;
318 	}
319 
320 	config->irq_configure();
321 
322 	/*
323 	 * Configure the FIFO control register.
324 	 * Set the threshold as 1 for getting notification immediately
325 	 * on converting completed.
326 	 */
327 	adc_fifo_setup(true, false, 1, true, true);
328 
329 	/* Set max speed to conversion */
330 	adc_set_clkdiv(0.f);
331 
332 	/* Enable ADC and wait becoming READY */
333 	adc_enable();
334 
335 	/* Enable FIFO interrupt */
336 	adc_irq_set_enabled(true);
337 
338 	adc_context_unlock_unconditionally(&data->ctx);
339 
340 	return 0;
341 }
342 
343 #define IRQ_CONFIGURE_FUNC(idx)						   \
344 	static void adc_rpi_configure_func_##idx(void)			   \
345 	{								   \
346 		IRQ_CONNECT(DT_INST_IRQN(idx), DT_INST_IRQ(idx, priority), \
347 			    adc_rpi_isr, DEVICE_DT_INST_GET(idx), 0);	   \
348 		irq_enable(DT_INST_IRQN(idx));				   \
349 	}
350 
351 #define IRQ_CONFIGURE_DEFINE(idx) .irq_configure = adc_rpi_configure_func_##idx
352 
353 #define ADC_RPI_INIT(idx)                                                                          \
354 	IRQ_CONFIGURE_FUNC(idx)                                                                    \
355 	PINCTRL_DT_INST_DEFINE(idx);                                                               \
356 	static struct adc_driver_api adc_rpi_api_##idx = {                                         \
357 		.channel_setup = adc_rpi_channel_setup,                                            \
358 		.read = adc_rpi_read,                                                              \
359 		.ref_internal = DT_INST_PROP(idx, vref_mv),                                        \
360 		IF_ENABLED(CONFIG_ADC_ASYNC, (.read_async = adc_rpi_read_async,))                  \
361 	};                                                                                         \
362 	static const struct adc_rpi_config adc_rpi_config_##idx = {                                \
363 		.num_channels = ADC_RPI_CHANNEL_NUM,                                               \
364 		.pcfg = PINCTRL_DT_INST_DEV_CONFIG_GET(idx),                                       \
365 		.clk_dev = DEVICE_DT_GET(DT_INST_CLOCKS_CTLR(idx)),                                \
366 		.clk_id = (clock_control_subsys_t)DT_INST_PHA_BY_IDX(idx, clocks, 0, clk_id),      \
367 		.reset = RESET_DT_SPEC_INST_GET(idx),                                              \
368 		IRQ_CONFIGURE_DEFINE(idx),                                                         \
369 	};                                                                                         \
370 	static struct adc_rpi_data adc_rpi_data_##idx = {                                          \
371 		ADC_CONTEXT_INIT_TIMER(adc_rpi_data_##idx, ctx),                                   \
372 		ADC_CONTEXT_INIT_LOCK(adc_rpi_data_##idx, ctx),                                    \
373 		ADC_CONTEXT_INIT_SYNC(adc_rpi_data_##idx, ctx),                                    \
374 		.dev = DEVICE_DT_INST_GET(idx),                                                    \
375 	};                                                                                         \
376                                                                                                    \
377 	DEVICE_DT_INST_DEFINE(idx, adc_rpi_init, NULL,                                             \
378 			      &adc_rpi_data_##idx,                                                 \
379 			      &adc_rpi_config_##idx, POST_KERNEL,                                  \
380 			      CONFIG_ADC_INIT_PRIORITY,                                            \
381 			      &adc_rpi_api_##idx)
382 
383 DT_INST_FOREACH_STATUS_OKAY(ADC_RPI_INIT);
384