1 /*
2  * Copyright 2022-2024 NXP
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #define DT_DRV_COMPAT nxp_gau_adc
8 
9 #include <zephyr/drivers/adc.h>
10 #include <zephyr/irq.h>
11 #include <errno.h>
12 #include <zephyr/logging/log.h>
13 
14 LOG_MODULE_REGISTER(adc_mcux_gau_adc, CONFIG_ADC_LOG_LEVEL);
15 
16 #define ADC_CONTEXT_USES_KERNEL_TIMER
17 #include "adc_context.h"
18 
19 #include <fsl_adc.h>
20 
21 #define NUM_ADC_CHANNELS 16
22 
23 struct mcux_gau_adc_config {
24 	ADC_Type *base;
25 	void (*irq_config_func)(const struct device *dev);
26 	adc_clock_divider_t clock_div;
27 	adc_analog_portion_power_mode_t power_mode;
28 	bool input_gain_buffer;
29 	adc_calibration_ref_t cal_volt;
30 };
31 
32 struct mcux_gau_adc_data {
33 	const struct device *dev;
34 	struct adc_context ctx;
35 	adc_channel_source_t channel_sources[NUM_ADC_CHANNELS];
36 	uint8_t scan_length;
37 	uint16_t *results;
38 	size_t results_length;
39 	uint16_t *repeat;
40 	struct k_work read_samples_work;
41 };
42 
mcux_gau_adc_channel_setup(const struct device * dev,const struct adc_channel_cfg * channel_cfg)43 static int mcux_gau_adc_channel_setup(const struct device *dev,
44 				      const struct adc_channel_cfg *channel_cfg)
45 {
46 	const struct mcux_gau_adc_config *config = dev->config;
47 	struct mcux_gau_adc_data *data = dev->data;
48 	ADC_Type *base = config->base;
49 	uint8_t channel_id = channel_cfg->channel_id;
50 	uint8_t source_channel = channel_cfg->input_positive;
51 	uint32_t tmp_reg;
52 
53 	if (channel_cfg->differential) {
54 		LOG_ERR("Differential channels not yet supported");
55 		return -ENOTSUP;
56 	}
57 
58 	if (channel_id >= NUM_ADC_CHANNELS) {
59 		LOG_ERR("ADC does not support more than %d channels", NUM_ADC_CHANNELS);
60 		return -ENOTSUP;
61 	}
62 
63 	if (source_channel > 12 && source_channel != 15) {
64 		LOG_ERR("Invalid source channel");
65 		return -EINVAL;
66 	}
67 
68 	/* Set Acquisition/Warmup time */
69 	tmp_reg = base->ADC_REG_INTERVAL;
70 	base->ADC_REG_INTERVAL &= ~ADC_ADC_REG_INTERVAL_WARMUP_TIME_MASK;
71 	base->ADC_REG_INTERVAL &= ~ADC_ADC_REG_INTERVAL_BYPASS_WARMUP_MASK;
72 	if (channel_cfg->acquisition_time == 0) {
73 		base->ADC_REG_INTERVAL |= ADC_ADC_REG_INTERVAL_BYPASS_WARMUP_MASK;
74 	} else if (channel_cfg->acquisition_time <= 32) {
75 		base->ADC_REG_INTERVAL |=
76 			ADC_ADC_REG_INTERVAL_WARMUP_TIME(channel_cfg->acquisition_time - 1);
77 	} else {
78 		LOG_ERR("Invalid acquisition time requested of ADC");
79 		return -EINVAL;
80 	}
81 	/* If user changed the warmup time, warn  */
82 	if (base->ADC_REG_INTERVAL != tmp_reg) {
83 		LOG_WRN("Acquisition/Warmup time is global to entire ADC peripheral, "
84 		"i.e. channel_setup will override this property for all previous channels.");
85 	}
86 
87 	/* Set Input Gain */
88 	tmp_reg = base->ADC_REG_ANA;
89 	base->ADC_REG_ANA &= ~ADC_ADC_REG_ANA_INBUF_GAIN_MASK;
90 	if (channel_cfg->gain == ADC_GAIN_1) {
91 		base->ADC_REG_ANA |= ADC_ADC_REG_ANA_INBUF_GAIN(kADC_InputGain1);
92 	} else if (channel_cfg->gain == ADC_GAIN_1_2) {
93 		base->ADC_REG_ANA |= ADC_ADC_REG_ANA_INBUF_GAIN(kADC_InputGain0P5);
94 	} else if (channel_cfg->gain == ADC_GAIN_2) {
95 		base->ADC_REG_ANA |= ADC_ADC_REG_ANA_INBUF_GAIN(kADC_InputGain2);
96 	} else {
97 		LOG_ERR("Invalid gain");
98 		return -EINVAL;
99 	}
100 	/* If user changed the gain, warn */
101 	if (base->ADC_REG_ANA != tmp_reg) {
102 		LOG_WRN("Input gain is global to entire ADC peripheral, "
103 		"i.e. channel_setup will override this property for all previous channels.");
104 	}
105 
106 	/* Set Reference voltage of ADC */
107 	tmp_reg = base->ADC_REG_ANA;
108 	base->ADC_REG_ANA &= ~ADC_ADC_REG_ANA_VREF_SEL_MASK;
109 	if (channel_cfg->reference == ADC_REF_INTERNAL) {
110 		base->ADC_REG_ANA |= ADC_ADC_REG_ANA_VREF_SEL(kADC_Vref1P2V);
111 	} else if (channel_cfg->reference == ADC_REF_EXTERNAL0) {
112 		base->ADC_REG_ANA |= ADC_ADC_REG_ANA_VREF_SEL(kADC_VrefExternal);
113 	} else if (channel_cfg->reference == ADC_REF_VDD_1) {
114 		base->ADC_REG_ANA |= ADC_ADC_REG_ANA_VREF_SEL(kADC_Vref1P8V);
115 	} else {
116 		LOG_ERR("Vref not supported");
117 		return -ENOTSUP;
118 	}
119 	/* if user changed the reference voltage, warn */
120 	if (base->ADC_REG_ANA != tmp_reg) {
121 		LOG_WRN("Reference voltage is global to entire ADC peripheral, "
122 		"i.e. channel_setup will override this property for all previous channels.");
123 	}
124 
125 	data->channel_sources[channel_id] = source_channel;
126 
127 	return 0;
128 }
129 
mcux_gau_adc_read_samples(struct k_work * work)130 static void mcux_gau_adc_read_samples(struct k_work *work)
131 {
132 	struct mcux_gau_adc_data *data =
133 				CONTAINER_OF(work, struct mcux_gau_adc_data,
134 						read_samples_work);
135 	const struct device *dev = data->dev;
136 	const struct mcux_gau_adc_config *config = dev->config;
137 	ADC_Type *base = config->base;
138 
139 	/* using this variable to prevent buffer overflow */
140 	size_t length = data->results_length;
141 
142 	while ((ADC_GetFifoDataCount(base) > 0) && (--length > 0)) {
143 		*(data->results++) = (uint16_t)ADC_GetConversionResult(base);
144 	}
145 
146 	adc_context_on_sampling_done(&data->ctx, dev);
147 }
148 
149 
mcux_gau_adc_isr(const struct device * dev)150 static void mcux_gau_adc_isr(const struct device *dev)
151 {
152 	const struct mcux_gau_adc_config *config = dev->config;
153 	struct mcux_gau_adc_data *data = dev->data;
154 	ADC_Type *base = config->base;
155 
156 	if (ADC_GetStatusFlags(base) & kADC_DataReadyInterruptFlag) {
157 		/* Clear flag to avoid infinite interrupt */
158 		ADC_ClearStatusFlags(base, kADC_DataReadyInterruptFlag);
159 
160 		/* offload and do not block during irq */
161 		k_work_submit(&data->read_samples_work);
162 	} else {
163 		LOG_ERR("ADC received unimplemented interrupt");
164 	}
165 }
166 
adc_context_start_sampling(struct adc_context * ctx)167 static void adc_context_start_sampling(struct adc_context *ctx)
168 {
169 	struct mcux_gau_adc_data *data =
170 		CONTAINER_OF(ctx, struct mcux_gau_adc_data, ctx);
171 	const struct mcux_gau_adc_config *config = data->dev->config;
172 	ADC_Type *base = config->base;
173 
174 	ADC_StopConversion(base);
175 	ADC_DoSoftwareTrigger(base);
176 }
177 
adc_context_update_buffer_pointer(struct adc_context * ctx,bool repeat_sampling)178 static void adc_context_update_buffer_pointer(struct adc_context *ctx,
179 					      bool repeat_sampling)
180 {
181 	struct mcux_gau_adc_data *data =
182 		CONTAINER_OF(ctx, struct mcux_gau_adc_data, ctx);
183 
184 	if (repeat_sampling) {
185 		data->results = data->repeat;
186 	}
187 }
188 
mcux_gau_adc_do_read(const struct device * dev,const struct adc_sequence * sequence)189 static int mcux_gau_adc_do_read(const struct device *dev,
190 		   const struct adc_sequence *sequence)
191 {
192 	const struct mcux_gau_adc_config *config = dev->config;
193 	ADC_Type *base = config->base;
194 	struct mcux_gau_adc_data *data = dev->data;
195 	uint8_t num_channels = 0;
196 
197 	/* if user selected channel >= NUM_ADC_CHANNELS that is invalid */
198 	if (sequence->channels & (0xFFFF << NUM_ADC_CHANNELS)) {
199 		LOG_ERR("Invalid channels selected for sequence");
200 		return -EINVAL;
201 	}
202 
203 	/* Count channels */
204 	for (int i = 0; i < NUM_ADC_CHANNELS; i++) {
205 		num_channels += ((sequence->channels & (0x1 << i)) ? 1 : 0);
206 	}
207 
208 	/* Buffer must hold (number of samples per channel) * (number of channels) samples */
209 	if ((sequence->options != NULL && sequence->buffer_size <
210 	    ((1 + sequence->options->extra_samplings) * num_channels)) ||
211 	    (sequence->options == NULL && sequence->buffer_size < num_channels)) {
212 		LOG_ERR("Buffer size too small");
213 		return -ENOMEM;
214 	}
215 
216 	/* Set scan length in data struct for isr to understand & set scan length register */
217 	base->ADC_REG_CONFIG &= ~ADC_ADC_REG_CONFIG_SCAN_LENGTH_MASK;
218 	data->scan_length = num_channels;
219 	/* Register Value is 1 less than what it represents */
220 	base->ADC_REG_CONFIG |= ADC_ADC_REG_CONFIG_SCAN_LENGTH(data->scan_length - 1);
221 
222 	/* Set up scan channels */
223 	for (int channel = 0; channel < NUM_ADC_CHANNELS; channel++) {
224 		if (sequence->channels & (0x1 << channel)) {
225 			ADC_SetScanChannel(base,
226 				data->scan_length - num_channels--,
227 				data->channel_sources[channel]);
228 		}
229 	}
230 
231 	/* Set resolution of ADC */
232 	base->ADC_REG_ANA &= ~ADC_ADC_REG_ANA_RES_SEL_MASK;
233 	/* odd numbers are for differential channels */
234 	if (sequence->resolution == 12 || sequence->resolution == 11) {
235 		base->ADC_REG_ANA |= ADC_ADC_REG_ANA_RES_SEL(kADC_Resolution12Bit);
236 	} else if (sequence->resolution == 14 || sequence->resolution == 13) {
237 		base->ADC_REG_ANA |= ADC_ADC_REG_ANA_RES_SEL(kADC_Resolution14Bit);
238 	} else if (sequence->resolution == 16 || sequence->resolution == 15) {
239 		base->ADC_REG_ANA |= ADC_ADC_REG_ANA_RES_SEL(kADC_Resolution16Bit);
240 	} else {
241 		LOG_ERR("Invalid resolution");
242 		return -EINVAL;
243 	}
244 
245 	/* Set oversampling */
246 	base->ADC_REG_CONFIG &= ~ADC_ADC_REG_CONFIG_AVG_SEL_MASK;
247 	if (sequence->oversampling == 0) {
248 		base->ADC_REG_CONFIG |= ADC_ADC_REG_CONFIG_AVG_SEL(kADC_AverageNone);
249 	} else if (sequence->oversampling == 1) {
250 		base->ADC_REG_CONFIG |= ADC_ADC_REG_CONFIG_AVG_SEL(kADC_Average2);
251 	} else if (sequence->oversampling == 2) {
252 		base->ADC_REG_CONFIG |= ADC_ADC_REG_CONFIG_AVG_SEL(kADC_Average4);
253 	} else if (sequence->oversampling == 3) {
254 		base->ADC_REG_CONFIG |= ADC_ADC_REG_CONFIG_AVG_SEL(kADC_Average8);
255 	} else if (sequence->oversampling == 4) {
256 		base->ADC_REG_CONFIG |= ADC_ADC_REG_CONFIG_AVG_SEL(kADC_Average16);
257 	} else {
258 		LOG_ERR("Invalid oversampling setting");
259 		return -EINVAL;
260 	}
261 
262 	/* Calibrate if requested */
263 	if (sequence->calibrate) {
264 		if (ADC_DoAutoCalibration(base, config->cal_volt)) {
265 			LOG_WRN("Calibration of ADC failed!");
266 		}
267 	}
268 
269 	data->results = sequence->buffer;
270 	data->results_length = sequence->buffer_size;
271 	data->repeat = sequence->buffer;
272 
273 	adc_context_start_read(&data->ctx, sequence);
274 
275 	return adc_context_wait_for_completion(&data->ctx);
276 }
277 
mcux_gau_adc_read(const struct device * dev,const struct adc_sequence * sequence)278 static int mcux_gau_adc_read(const struct device *dev,
279 			   const struct adc_sequence *sequence)
280 {
281 	struct mcux_gau_adc_data *data = dev->data;
282 	int error;
283 
284 	adc_context_lock(&data->ctx, false, NULL);
285 	error = mcux_gau_adc_do_read(dev, sequence);
286 	adc_context_release(&data->ctx, error);
287 	return error;
288 }
289 
290 #ifdef CONFIG_ADC_ASYNC
mcux_gau_adc_read_async(const struct device * dev,const struct adc_sequence * sequence,struct k_poll_signal * async)291 static int mcux_gau_adc_read_async(const struct device *dev,
292 				   const struct adc_sequence *sequence,
293 				   struct k_poll_signal *async)
294 {
295 	struct mcux_gau_adc_data *data = dev->data;
296 	int error;
297 
298 	adc_context_lock(&data->ctx, true, async);
299 	error = mcux_gau_adc_do_read(dev, sequence);
300 	adc_context_release(&data->ctx, error);
301 	return error;
302 }
303 #endif
304 
305 
mcux_gau_adc_init(const struct device * dev)306 static int mcux_gau_adc_init(const struct device *dev)
307 {
308 	const struct mcux_gau_adc_config *config = dev->config;
309 	struct mcux_gau_adc_data *data = dev->data;
310 	ADC_Type *base = config->base;
311 	adc_config_t adc_config;
312 
313 	data->dev = dev;
314 
315 	LOG_DBG("Initializing ADC");
316 
317 	ADC_GetDefaultConfig(&adc_config);
318 
319 	/* DT configs */
320 	adc_config.clockDivider = config->clock_div;
321 	adc_config.powerMode = config->power_mode;
322 	adc_config.enableInputGainBuffer = config->input_gain_buffer;
323 	adc_config.triggerSource = kADC_TriggerSourceSoftware;
324 
325 	adc_config.inputMode = kADC_InputSingleEnded;
326 	/* One shot meets the needs of the current zephyr adc context/api */
327 	adc_config.conversionMode = kADC_ConversionOneShot;
328 	/* since using one shot mode, just interrupt on one sample (agnostic to # channels) */
329 	adc_config.fifoThreshold = kADC_FifoThresholdData1;
330 	/* 32 bit width not supported in this driver; zephyr seems to use 16 bit */
331 	adc_config.resultWidth = kADC_ResultWidth16;
332 	adc_config.enableDMA = false;
333 	adc_config.enableADC = true;
334 
335 	ADC_Init(base, &adc_config);
336 
337 	if (ADC_DoAutoCalibration(base, config->cal_volt)) {
338 		LOG_WRN("Calibration of ADC failed!");
339 	}
340 
341 	ADC_ClearStatusFlags(base, kADC_DataReadyInterruptFlag);
342 
343 	config->irq_config_func(dev);
344 	ADC_EnableInterrupts(base, kADC_DataReadyInterruptEnable);
345 
346 	k_work_init(&data->read_samples_work, &mcux_gau_adc_read_samples);
347 
348 	adc_context_init(&data->ctx);
349 	adc_context_unlock_unconditionally(&data->ctx);
350 
351 	return 0;
352 }
353 
354 static DEVICE_API(adc, mcux_gau_adc_driver_api) = {
355 	.channel_setup = mcux_gau_adc_channel_setup,
356 	.read = mcux_gau_adc_read,
357 #ifdef CONFIG_ADC_ASYNC
358 	.read_async = mcux_gau_adc_read_async,
359 #endif
360 	.ref_internal = 1200,
361 };
362 
363 
364 #define GAU_ADC_MCUX_INIT(n)							\
365 										\
366 	static void mcux_gau_adc_config_func_##n(const struct device *dev);     \
367 										\
368 	static const struct mcux_gau_adc_config mcux_gau_adc_config_##n = {	\
369 		.base = (ADC_Type *)DT_INST_REG_ADDR(n),			\
370 		.irq_config_func = mcux_gau_adc_config_func_##n,		\
371 		/* Minus one because DT starts at 1, HAL enum starts at 0 */	\
372 		.clock_div = DT_INST_PROP(n, nxp_clock_divider) - 1,		\
373 		.power_mode = DT_INST_ENUM_IDX(n, nxp_power_mode),		\
374 		.input_gain_buffer = DT_INST_PROP(n, nxp_input_buffer),		\
375 		.cal_volt = DT_INST_ENUM_IDX(n, nxp_calibration_voltage),	\
376 	};									\
377 										\
378 	static struct mcux_gau_adc_data mcux_gau_adc_data_##n = {0};		\
379 										\
380 	DEVICE_DT_INST_DEFINE(n, &mcux_gau_adc_init, NULL,			\
381 			      &mcux_gau_adc_data_##n, &mcux_gau_adc_config_##n,	\
382 			      POST_KERNEL, CONFIG_ADC_INIT_PRIORITY,		\
383 			      &mcux_gau_adc_driver_api);			\
384 										\
385 	static void mcux_gau_adc_config_func_##n(const struct device *dev)	\
386 	{									\
387 		IRQ_CONNECT(DT_INST_IRQN(n), DT_INST_IRQ(n, priority),		\
388 				mcux_gau_adc_isr, DEVICE_DT_INST_GET(n), 0);	\
389 		irq_enable(DT_INST_IRQN(n));					\
390 	}
391 
392 DT_INST_FOREACH_STATUS_OKAY(GAU_ADC_MCUX_INIT)
393