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