1 /*
2  * Copyright (c) 2023 Mustafa Abdullah Kus, Sparse Technology
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <stdbool.h>
8 #include <zephyr/device.h>
9 #include <zephyr/devicetree.h>
10 #include <zephyr/drivers/adc.h>
11 #include <zephyr/logging/log.h>
12 #include <zephyr/drivers/spi.h>
13 #include <zephyr/kernel.h>
14 #include <zephyr/sys/byteorder.h>
15 #include <zephyr/sys/util.h>
16 
17 #define ADC_CONTEXT_USES_KERNEL_TIMER
18 #include "adc_context.h"
19 
20 LOG_MODULE_REGISTER(ADC_MAX1125X, CONFIG_ADC_LOG_LEVEL);
21 
22 #define MAX1125X_CONFIG_PGA(x)     BIT(x)
23 #define MAX1125X_CONFIG_CHANNEL(x) ((x) << 5)
24 #define MAX1125X_CONFIG_CHMAP(x)   ((x << 2) | BIT(1))
25 #define MAX1125X_REG_DATA(x)       (MAX1125X_REG_DATA0 + (x << 1))
26 
27 #define MAX1125X_CMD_READ        0xC1
28 #define MAX1125X_CMD_WRITE       0xC0
29 #define MAX1125X_CMD_CONV        0x80
30 #define MAX1125X_CMD_CALIBRATION 0x20
31 #define MAX1125X_CMD_SEQUENCER   0x30
32 
33 enum max1125x_mode {
34 	MAX1125X_MODE_POWERDOWN = 0x01,
35 	MAX1125X_MODE_CALIBRATION = 0x02,
36 	MAX1125X_MODE_SEQUENCER = 0x03,
37 };
38 
39 enum {
40 	MAX1125X_CONFIG_RATE_1_9 = 0x00,
41 	MAX1125X_CONFIG_RATE_3_9 = 0x01,
42 	MAX1125X_CONFIG_RATE_7_8 = 0x02,
43 	MAX1125X_CONFIG_RATE_15_6 = 0x03,
44 	MAX1125X_CONFIG_RATE_31_2 = 0x04,
45 	MAX1125X_CONFIG_RATE_62_5 = 0x05,
46 	MAX1125X_CONFIG_RATE_125 = 0x06,
47 	MAX1125X_CONFIG_RATE_250 = 0x07,
48 	MAX1125X_CONFIG_RATE_500 = 0x08,
49 	MAX1125X_CONFIG_RATE_1000 = 0x09,
50 	MAX1125X_CONFIG_RATE_2000 = 0x0A,
51 	MAX1125X_CONFIG_RATE_4000 = 0x0B,
52 	MAX1125X_CONFIG_RATE_8000 = 0x0C,
53 	MAX1125X_CONFIG_RATE_16000 = 0x0D,
54 	MAX1125X_CONFIG_RATE_32000 = 0x0E,
55 	MAX1125X_CONFIG_RATE_64000 = 0x0F,
56 };
57 
58 enum max1125x_reg {
59 	MAX1125X_REG_STAT = 0x00,
60 	MAX1125X_REG_CTRL1 = 0x02,
61 	MAX1125X_REG_CTRL2 = 0x04,
62 	MAX1125X_REG_CTRL3 = 0x06,
63 	MAX1125X_REG_GPIO_CTRL = 0x08,
64 	MAX1125X_REG_DELAY = 0x0A,
65 	MAX1125X_REG_CHMAP1 = 0x0C,
66 	MAX1125X_REG_CHMAP0 = 0x0E,
67 	MAX1125X_REG_SEQ = 0x10,
68 	MAX1125X_REG_GPO_DIR = 0x12,
69 	MAX1125X_REG_SOC = 0x14,
70 	MAX1125X_REG_SGC = 0x16,
71 	MAX1125X_REG_SCOC = 0x18,
72 	MAX1125X_REG_SCGC = 0x1A,
73 	MAX1125X_REG_DATA0 = 0x1C,
74 	MAX1125X_REG_DATA1 = 0x1E,
75 	MAX1125X_REG_DATA2 = 0x20,
76 	MAX1125X_REG_DATA3 = 0x22,
77 	MAX1125X_REG_DATA4 = 0x24,
78 	MAX1125X_REG_DATA5 = 0x26,
79 };
80 
81 enum {
82 	MAX1125X_REG_STAT_LEN = 3,
83 	MAX1125X_REG_CTRL1_LEN = 1,
84 	MAX1125X_REG_CTRL2_LEN = 1,
85 	MAX1125X_REG_CTRL3_LEN = 1,
86 	MAX1125X_REG_GPIO_CTRL_LEN = 1,
87 	MAX1125X_REG_DELAY_LEN = 2,
88 	MAX1125X_REG_CHMAP1_LEN = 3,
89 	MAX1125X_REG_CHMAP0_LEN = 3,
90 	MAX1125X_REG_SEQ_LEN = 1,
91 	MAX1125X_REG_GPO_DIR_LEN = 1,
92 	MAX1125X_REG_SOC_LEN = 3,
93 	MAX1125X_REG_SGC_LEN = 3,
94 	MAX1125X_REG_SCOC_LEN = 3,
95 	MAX1125X_REG_SCGC_LEN = 3,
96 };
97 
98 enum {
99 	MAX1125X_CTRL1_CAL_SELF = 0,
100 	MAX1125X_CTRL1_CAL_OFFSET = 1,
101 	MAX1125X_CTRL1_CAL_FULLSCALE = 2,
102 };
103 
104 enum {
105 	MAX1125X_CTRL1_PD_NOP = 0,
106 	MAX1125X_CTRL1_DP_SLEEP = 1,
107 	MAX1125X_CTRL1_DP_STANDBY = 2,
108 	MAX1125X_CTRL1_DP_RESET = 3,
109 };
110 
111 enum {
112 	MAX1125X_CTRL1_CONTSC = 0,
113 	MAX1125X_CTRL1_SCYCLE = 1,
114 	MAX1125X_CTRL1_FORMAT = 2,
115 	MAX1125X_CTRL1_UBPOLAR = 3,
116 };
117 
118 enum {
119 	MAX1125X_CTRL2_PGA_GAIN_1 = 0,
120 	MAX1125X_CTRL2_PGA_GAIN_2 = 1,
121 	MAX1125X_CTRL2_PGA_GAIN_4 = 2,
122 	MAX1125X_CTRL2_PGA_GAIN_8 = 3,
123 	MAX1125X_CTRL2_PGA_GAIN_16 = 4,
124 	MAX1125X_CTRL2_PGA_GAIN_32 = 5,
125 	MAX1125X_CTRL2_PGA_GAIN_64 = 6,
126 	MAX1125X_CTRL2_PGA_GAIN_128 = 7,
127 };
128 
129 enum {
130 	MAX1125X_CTRL2_PGAEN = 3,
131 	MAX1125X_CTRL2_LPMODE = 4,
132 	MAX1125X_CTRL2_LDOEN = 5,
133 	MAX1125X_CTRL2_CSSEN = 6,
134 	MAX1125X_CTRL2_EXTCLK = 7,
135 };
136 
137 enum {
138 	MAX1125X_CTRL3_NOSCO = 0,
139 	MAX1125X_CTRL3_NOSCG = 1,
140 	MAX1125X_CTRL3_NOSYSO = 2,
141 	MAX1125X_CTRL3_NOSYSG = 3,
142 	MAX1125X_CTRL3_CALREGSEL = 4,
143 	MAX1125X_CTRL3_SYNC_MODE = 5,
144 	MAX1125X_CTRL3_GPO_MODE = 6,
145 };
146 
147 enum {
148 	MAX1125X_GPIO_CTRL_DIO0 = 0,
149 	MAX1125X_GPIO_CTRL_DIO1 = 1,
150 	MAX1125X_GPIO_CTRL_DIRO = 3,
151 	MAX1125X_GPIO_CTRL_DIR1 = 4,
152 	MAX1125X_GPIO_CTRL_GPIO0_EN = 6,
153 	MAX1125X_GPIO_CTRL_GPIO1_EN = 7,
154 };
155 
156 enum {
157 	MAX1125X_SEQ_RDYBEN = 0,
158 	MAX1125X_SEQ_MDREN = 1,
159 	MAX1125X_SEQ_GPODREN = 2,
160 	MAX1125X_SEQ_MODE0 = 3,
161 	MAX1125X_SEQ_MODE1 = 4,
162 	MAX1125X_SEQ_MUX0 = 5,
163 	MAX1125X_SEQ_MUX1 = 6,
164 	MAX1125X_SEQ_MUX2 = 7,
165 };
166 
167 enum {
168 	MAX1125X_GPO_DIR_GPO0 = 0,
169 	MAX1125X_GPO_DIR_GPO1 = 1,
170 };
171 
172 enum {
173 	MAX1125X_CMD_RATE0 = 0,
174 	MAX1125X_CMD_RATE1 = 1,
175 	MAX1125X_CMD_RATE2 = 2,
176 	MAX1125X_CMD_RATE3 = 3,
177 };
178 
179 enum {
180 	MAX1125X_CHANNEL_0 = 0x0,
181 	MAX1125X_CHANNEL_1 = 0x1,
182 	MAX1125X_CHANNEL_2 = 0x2,
183 	MAX1125X_CHANNEL_3 = 0x3,
184 	MAX1125X_CHANNEL_4 = 0x4,
185 	MAX1125X_CHANNEL_5 = 0x5,
186 };
187 
188 enum {
189 	MAX1125X_CMD_MODE0 = 4,
190 	MAX1125X_CMD_MODE1 = 5,
191 };
192 
193 struct max1125x_gpio_ctrl {
194 	bool gpio0_enable;
195 	bool gpio1_enable;
196 	bool gpio0_direction;
197 	bool gpio1_direction;
198 };
199 
200 struct max1125x_gpo_ctrl {
201 	bool gpo0_enable;
202 	bool gpo1_enable;
203 };
204 
205 struct max1125x_config {
206 	struct spi_dt_spec bus;
207 	struct gpio_dt_spec drdy_gpio;
208 	const uint32_t odr_delay[16];
209 	uint8_t resolution;
210 	bool multiplexer;
211 	bool pga;
212 	bool self_calibration;
213 	struct max1125x_gpio_ctrl gpio;
214 	struct max1125x_gpo_ctrl gpo;
215 };
216 
217 struct max1125x_data {
218 	const struct device *dev;
219 	struct adc_context ctx;
220 	uint8_t rate;
221 	struct gpio_callback callback_data_ready;
222 	struct k_sem acq_sem;
223 	struct k_sem data_ready_signal;
224 	int32_t *buffer;
225 	int32_t *repeat_buffer;
226 	struct k_thread thread;
227 	bool differential;
228 
229 	K_KERNEL_STACK_MEMBER(stack, CONFIG_ADC_MAX1125X_ACQUISITION_THREAD_STACK_SIZE);
230 };
231 
max1125x_data_ready_handler(const struct device * dev,struct gpio_callback * gpio_cb,uint32_t pins)232 static void max1125x_data_ready_handler(const struct device *dev, struct gpio_callback *gpio_cb,
233 					uint32_t pins)
234 {
235 	ARG_UNUSED(dev);
236 	ARG_UNUSED(pins);
237 
238 	struct max1125x_data *data =
239 		CONTAINER_OF(gpio_cb, struct max1125x_data, callback_data_ready);
240 
241 	k_sem_give(&data->data_ready_signal);
242 }
243 
max1125x_read_reg(const struct device * dev,enum max1125x_reg reg_addr,uint8_t * buffer,size_t reg_size)244 static int max1125x_read_reg(const struct device *dev, enum max1125x_reg reg_addr, uint8_t *buffer,
245 			     size_t reg_size)
246 {
247 	int ret;
248 	const struct max1125x_config *config = dev->config;
249 	uint8_t buffer_tx[3];
250 	uint8_t buffer_rx[ARRAY_SIZE(buffer_tx)];
251 	const struct spi_buf tx_buf[] = {{
252 		.buf = buffer_tx,
253 		.len = ARRAY_SIZE(buffer_tx),
254 	}};
255 	const struct spi_buf rx_buf[] = {{
256 		.buf = buffer_rx,
257 		.len = ARRAY_SIZE(buffer_rx),
258 	}};
259 	const struct spi_buf_set tx = {
260 		.buffers = tx_buf,
261 		.count = ARRAY_SIZE(tx_buf),
262 	};
263 	const struct spi_buf_set rx = {
264 		.buffers = rx_buf,
265 		.count = ARRAY_SIZE(rx_buf),
266 	};
267 	buffer_tx[0] = MAX1125X_CMD_READ | reg_addr;
268 	/* read one register */
269 	buffer_tx[1] = 0x00;
270 
271 	ret = spi_transceive_dt(&config->bus, &tx, &rx);
272 	if (ret != 0) {
273 		LOG_ERR("MAX1125X: error writing register 0x%X (%d)", reg_addr, ret);
274 		return ret;
275 	}
276 	*buffer = buffer_rx[1];
277 	LOG_DBG("read from register 0x%02X value 0x%02X", reg_addr, *buffer);
278 
279 	return 0;
280 }
281 
max1125x_write_reg(const struct device * dev,enum max1125x_reg reg_addr,uint8_t * reg_val,size_t reg_size)282 static int max1125x_write_reg(const struct device *dev, enum max1125x_reg reg_addr,
283 			      uint8_t *reg_val, size_t reg_size)
284 {
285 	int ret;
286 	const struct max1125x_config *config = dev->config;
287 	uint8_t command = MAX1125X_CMD_WRITE | reg_addr;
288 
289 	const struct spi_buf spi_buf[2] = {{.buf = &command, .len = sizeof(command)},
290 					   {.buf = reg_val, .len = reg_size}};
291 	const struct spi_buf_set tx = {.buffers = spi_buf, .count = ARRAY_SIZE(spi_buf)};
292 
293 	ret = spi_write_dt(&config->bus, &tx);
294 	if (ret != 0) {
295 		LOG_ERR("MAX1125X: error writing register 0x%X (%d)", reg_addr, ret);
296 		return ret;
297 	}
298 
299 	return 0;
300 }
301 
max1125x_send_command(const struct device * dev,enum max1125x_mode mode,uint8_t rate)302 static int max1125x_send_command(const struct device *dev, enum max1125x_mode mode, uint8_t rate)
303 {
304 	int ret;
305 	const struct max1125x_config *config = dev->config;
306 	uint8_t command = MAX1125X_CMD_CONV | mode | rate;
307 	const struct spi_buf spi_buf = {.buf = &command, .len = sizeof(command)};
308 	const struct spi_buf_set tx = {.buffers = &spi_buf, .count = 1};
309 
310 	ret = spi_write_dt(&config->bus, &tx);
311 	if (ret != 0) {
312 		LOG_ERR("MAX1125X: error writing register 0x%X (%d)", rate, ret);
313 		return ret;
314 	}
315 
316 	return 0;
317 }
318 
max1125x_start_conversion(const struct device * dev)319 static int max1125x_start_conversion(const struct device *dev)
320 {
321 	const struct max1125x_data *data = dev->data;
322 
323 	return max1125x_send_command(dev, MAX1125X_CMD_SEQUENCER, data->rate);
324 }
325 
max1125x_acq_time_to_dr(const struct device * dev,uint16_t acq_time)326 static inline int max1125x_acq_time_to_dr(const struct device *dev, uint16_t acq_time)
327 {
328 	struct max1125x_data *data = dev->data;
329 	const struct max1125x_config *config = dev->config;
330 	const uint32_t *odr_delay = config->odr_delay;
331 	uint32_t odr_delay_us = 0;
332 	uint16_t acq_value = ADC_ACQ_TIME_VALUE(acq_time);
333 	int odr = -EINVAL;
334 
335 	if (acq_time != ADC_ACQ_TIME_DEFAULT && ADC_ACQ_TIME_UNIT(acq_time) != ADC_ACQ_TIME_TICKS) {
336 		LOG_ERR("MAX1125X: invalid acq time value (%d)", acq_time);
337 		return -EINVAL;
338 	}
339 
340 	if (acq_value < MAX1125X_CONFIG_RATE_1_9 || acq_value > MAX1125X_CONFIG_RATE_64000) {
341 		LOG_ERR("MAX1125X: invalid acq value (%d)", acq_value);
342 		return -EINVAL;
343 	}
344 
345 	odr = acq_value;
346 	odr_delay_us = odr_delay[acq_value];
347 
348 	data->rate = odr;
349 
350 	return odr;
351 }
352 
max1125x_wait_data_ready(const struct device * dev)353 static int max1125x_wait_data_ready(const struct device *dev)
354 {
355 	struct max1125x_data *data = dev->data;
356 
357 	return k_sem_take(&data->data_ready_signal, ADC_CONTEXT_WAIT_FOR_COMPLETION_TIMEOUT);
358 }
359 
max1125x_read_sample(const struct device * dev)360 static int max1125x_read_sample(const struct device *dev)
361 {
362 	const struct max1125x_config *config = dev->config;
363 	struct max1125x_data *data = dev->data;
364 	bool is_positive;
365 	uint8_t buffer_tx[(config->resolution / 8) + 1];
366 	uint8_t buffer_rx[ARRAY_SIZE(buffer_tx)];
367 	uint8_t current_channel = find_msb_set(data->ctx.sequence.channels) - 1;
368 	int rc;
369 
370 	const struct spi_buf tx_buf[] = {{
371 		.buf = buffer_tx,
372 		.len = ARRAY_SIZE(buffer_tx),
373 	}};
374 	const struct spi_buf rx_buf[] = {{
375 		.buf = buffer_rx,
376 		.len = ARRAY_SIZE(buffer_rx),
377 	}};
378 	const struct spi_buf_set tx = {
379 		.buffers = tx_buf,
380 		.count = ARRAY_SIZE(tx_buf),
381 	};
382 	const struct spi_buf_set rx = {
383 		.buffers = rx_buf,
384 		.count = ARRAY_SIZE(rx_buf),
385 	};
386 
387 	buffer_tx[0] = MAX1125X_CMD_READ | MAX1125X_REG_DATA(current_channel);
388 
389 	rc = spi_transceive_dt(&config->bus, &tx, &rx);
390 	if (rc != 0) {
391 		LOG_ERR("spi_transceive failed with error %i", rc);
392 		return rc;
393 	}
394 
395 	/* The data format while in unipolar mode is always offset binary.
396 	 * In offset binary format the most negative value is 0x000000,
397 	 * the midscale value is 0x800000 and the most positive value is
398 	 * 0xFFFFFF. In bipolar mode if the FORMAT bit = ‘1’ then the
399 	 * data format is offset binary. If the FORMAT bit = ‘0’, then
400 	 * the data format is two’s complement. In two’s complement the
401 	 * negative full-scale value is 0x800000, the midscale is 0x000000
402 	 * and the positive full scale is 0x7FFFFF. Any input exceeding
403 	 * the available input range is limited to the minimum or maximum
404 	 * data value.
405 	 */
406 	is_positive = buffer_rx[(config->resolution / 8)] >> 7;
407 	if (is_positive) {
408 		*data->buffer++ = sys_get_be24(buffer_rx) - (1 << (config->resolution - 1));
409 	} else {
410 		*data->buffer++ = sys_get_be24(buffer_rx + 1);
411 	}
412 
413 	adc_context_on_sampling_done(&data->ctx, dev);
414 
415 	return rc;
416 }
417 
max1125x_configure_chmap(const struct device * dev,const uint8_t channel_id)418 static int max1125x_configure_chmap(const struct device *dev, const uint8_t channel_id)
419 {
420 	uint8_t last_order = 0;
421 	uint8_t chmap1_register[3] = {0};
422 	uint8_t chmap0_register[3] = {0};
423 
424 	if (channel_id > 6) {
425 		LOG_ERR("MAX1125X: invalid channel (%u)", channel_id);
426 		return -EINVAL;
427 	}
428 
429 	max1125x_read_reg(dev, MAX1125X_REG_CHMAP1, chmap1_register, MAX1125X_REG_CHMAP1_LEN);
430 	for (int index = 0; index < 3; index++) {
431 		if ((chmap1_register[index] >> 2) >= last_order) {
432 			last_order = chmap1_register[index] >> 2;
433 		} else {
434 			continue;
435 		}
436 	}
437 
438 	max1125x_read_reg(dev, MAX1125X_REG_CHMAP0, chmap0_register, MAX1125X_REG_CHMAP0_LEN);
439 	for (int index = 0; index < 3; index++) {
440 		if ((chmap0_register[index] >> 2) >= last_order) {
441 			last_order = chmap0_register[index] >> 2;
442 		} else {
443 			continue;
444 		}
445 	}
446 
447 	last_order++;
448 
449 	switch (channel_id) {
450 	case MAX1125X_CHANNEL_0:
451 		chmap0_register[2] = MAX1125X_CONFIG_CHMAP(last_order);
452 		break;
453 	case MAX1125X_CHANNEL_1:
454 		chmap0_register[1] = MAX1125X_CONFIG_CHMAP(last_order);
455 		break;
456 	case MAX1125X_CHANNEL_2:
457 		chmap0_register[0] = MAX1125X_CONFIG_CHMAP(last_order);
458 		break;
459 	case MAX1125X_CHANNEL_3:
460 		chmap1_register[2] = MAX1125X_CONFIG_CHMAP(last_order);
461 		break;
462 	case MAX1125X_CHANNEL_4:
463 		chmap1_register[1] = MAX1125X_CONFIG_CHMAP(last_order);
464 		break;
465 	case MAX1125X_CHANNEL_5:
466 		chmap1_register[0] = MAX1125X_CONFIG_CHMAP(last_order);
467 		break;
468 	default:
469 		break;
470 	}
471 
472 	if (channel_id > 3) {
473 		/* CHMAP 1 register configuration */
474 		max1125x_write_reg(dev, MAX1125X_REG_CHMAP1, chmap1_register,
475 				   MAX1125X_REG_CHMAP1_LEN);
476 	} else {
477 		/* CHMAP 0 register configuration */
478 		max1125x_write_reg(dev, MAX1125X_REG_CHMAP0, chmap0_register,
479 				   MAX1125X_REG_CHMAP0_LEN);
480 	}
481 
482 	return 0;
483 }
484 
max1125x_self_calibration(const struct device * dev)485 static int max1125x_self_calibration(const struct device *dev)
486 {
487 	uint8_t seq_register = 0;
488 	uint8_t ctrl1_register = BIT(MAX1125X_CTRL1_SCYCLE);
489 
490 	max1125x_write_reg(dev, MAX1125X_REG_SEQ, &seq_register, MAX1125X_REG_SEQ_LEN);
491 	max1125x_write_reg(dev, MAX1125X_REG_CTRL1, &ctrl1_register, MAX1125X_REG_CTRL1_LEN);
492 	max1125x_send_command(dev, MAX1125X_CMD_CALIBRATION, 0x00);
493 
494 	k_sleep(K_MSEC(200));
495 	return 0;
496 }
497 
max1125x_channel_setup(const struct device * dev,const struct adc_channel_cfg * channel_cfg)498 static int max1125x_channel_setup(const struct device *dev,
499 				  const struct adc_channel_cfg *channel_cfg)
500 {
501 	const struct max1125x_config *max_config = dev->config;
502 	uint8_t seq_register = 0;
503 	uint8_t ctrl2_register = 0;
504 	uint8_t gpio_reg = 0;
505 	uint8_t gpo_reg = 0;
506 
507 	/* sequencer register configuration */
508 	max1125x_read_reg(dev, MAX1125X_REG_SEQ, &seq_register, MAX1125X_REG_SEQ_LEN);
509 	seq_register |= BIT(MAX1125X_SEQ_MDREN);
510 	seq_register |= BIT(MAX1125X_SEQ_MODE0);
511 	max1125x_write_reg(dev, MAX1125X_REG_SEQ, &seq_register, MAX1125X_REG_SEQ_LEN);
512 
513 	/* configuration multiplexer */
514 	if (max_config->multiplexer) {
515 		if (!channel_cfg->differential) {
516 			LOG_ERR("6 channel fully supported only supported differential "
517 				"differemtial option %i",
518 				channel_cfg->differential);
519 			return -ENOTSUP;
520 		}
521 	}
522 
523 	max1125x_acq_time_to_dr(dev, channel_cfg->acquisition_time);
524 
525 	/* ctrl2 register configuration */
526 	if (max_config->pga) {
527 		/* programmable gain amplifier support */
528 		ctrl2_register |= MAX1125X_CONFIG_PGA(MAX1125X_CTRL2_PGAEN);
529 		switch (channel_cfg->gain) {
530 		case ADC_GAIN_1:
531 			ctrl2_register |= MAX1125X_CTRL2_PGA_GAIN_1;
532 			break;
533 		case ADC_GAIN_2:
534 			ctrl2_register |= MAX1125X_CTRL2_PGA_GAIN_2;
535 			break;
536 		case ADC_GAIN_4:
537 			ctrl2_register |= MAX1125X_CTRL2_PGA_GAIN_4;
538 			break;
539 		case ADC_GAIN_8:
540 			ctrl2_register |= MAX1125X_CTRL2_PGA_GAIN_8;
541 			break;
542 		case ADC_GAIN_16:
543 			ctrl2_register |= MAX1125X_CTRL2_PGA_GAIN_16;
544 			break;
545 		case ADC_GAIN_32:
546 			ctrl2_register |= MAX1125X_CTRL2_PGA_GAIN_32;
547 			break;
548 		case ADC_GAIN_64:
549 			ctrl2_register |= MAX1125X_CTRL2_PGA_GAIN_64;
550 			break;
551 		case ADC_GAIN_128:
552 			ctrl2_register |= MAX1125X_CTRL2_PGA_GAIN_128;
553 			break;
554 		default:
555 			LOG_ERR("MAX1125X: unsupported channel gain '%d'", channel_cfg->gain);
556 			return -ENOTSUP;
557 		}
558 	}
559 
560 	if (channel_cfg->reference == ADC_REF_INTERNAL) {
561 		ctrl2_register |= BIT(MAX1125X_CTRL2_LDOEN);
562 
563 	} else if (channel_cfg->reference == ADC_REF_EXTERNAL1) {
564 		ctrl2_register &= ~BIT(MAX1125X_CTRL2_LDOEN);
565 	} else {
566 		LOG_ERR("MAX1125X: unsupported channel reference type '%d'",
567 			channel_cfg->reference);
568 		return -ENOTSUP;
569 	}
570 	max1125x_write_reg(dev, MAX1125X_REG_CTRL2, &ctrl2_register, MAX1125X_REG_CTRL2_LEN);
571 
572 	/* GPIO_CTRL register configuration */
573 	gpio_reg |= max_config->gpio.gpio0_enable << MAX1125X_GPIO_CTRL_GPIO0_EN;
574 	gpio_reg |= max_config->gpio.gpio1_enable << MAX1125X_GPIO_CTRL_GPIO1_EN;
575 	gpio_reg |= max_config->gpio.gpio0_direction << MAX1125X_GPIO_CTRL_DIRO;
576 	gpio_reg |= max_config->gpio.gpio1_direction << MAX1125X_GPIO_CTRL_DIR1;
577 	max1125x_write_reg(dev, MAX1125X_REG_GPIO_CTRL, &gpio_reg, MAX1125X_REG_GPIO_CTRL_LEN);
578 
579 	/* GPO_DIR register configuration */
580 	gpo_reg |= max_config->gpo.gpo0_enable << MAX1125X_GPO_DIR_GPO0;
581 	gpo_reg |= max_config->gpo.gpo1_enable << MAX1125X_GPO_DIR_GPO1;
582 	max1125x_write_reg(dev, MAX1125X_REG_GPO_DIR, &gpo_reg, MAX1125X_REG_GPO_DIR_LEN);
583 
584 	/* configuration of channel order */
585 	max1125x_configure_chmap(dev, channel_cfg->channel_id);
586 
587 	return 0;
588 }
589 
max1125x_validate_buffer_size(const struct adc_sequence * sequence)590 static int max1125x_validate_buffer_size(const struct adc_sequence *sequence)
591 {
592 	size_t needed = sizeof(uint8_t) * (sequence->resolution / 8);
593 
594 	if (sequence->options) {
595 		needed *= (1 + sequence->options->extra_samplings);
596 	}
597 
598 	if (sequence->buffer_size < needed) {
599 		return -ENOMEM;
600 	}
601 
602 	return 0;
603 }
604 
max1125x_validate_sequence(const struct device * dev,const struct adc_sequence * sequence)605 static int max1125x_validate_sequence(const struct device *dev, const struct adc_sequence *sequence)
606 {
607 	int err;
608 
609 	if (sequence->oversampling) {
610 		LOG_ERR("MAX1125X: oversampling not supported");
611 		return -ENOTSUP;
612 	}
613 
614 	err = max1125x_validate_buffer_size(sequence);
615 	if (err) {
616 		LOG_ERR("MAX1125X: buffer size too small");
617 		return -ENOTSUP;
618 	}
619 
620 	return 0;
621 }
622 
adc_context_update_buffer_pointer(struct adc_context * ctx,bool repeat_sampling)623 static void adc_context_update_buffer_pointer(struct adc_context *ctx, bool repeat_sampling)
624 {
625 	struct max1125x_data *data = CONTAINER_OF(ctx, struct max1125x_data, ctx);
626 
627 	if (repeat_sampling) {
628 		data->buffer = data->repeat_buffer;
629 	}
630 }
631 
adc_context_start_sampling(struct adc_context * ctx)632 static void adc_context_start_sampling(struct adc_context *ctx)
633 {
634 	struct max1125x_data *data = CONTAINER_OF(ctx, struct max1125x_data, ctx);
635 
636 	data->repeat_buffer = data->buffer;
637 
638 	max1125x_start_conversion(data->dev);
639 
640 	k_sem_give(&data->acq_sem);
641 }
642 
max1125x_adc_start_read(const struct device * dev,const struct adc_sequence * sequence)643 static int max1125x_adc_start_read(const struct device *dev, const struct adc_sequence *sequence)
644 {
645 	int rc;
646 	struct max1125x_data *data = dev->data;
647 
648 	rc = max1125x_validate_sequence(dev, sequence);
649 	if (rc != 0) {
650 		return rc;
651 	}
652 
653 	data->buffer = sequence->buffer;
654 
655 	adc_context_start_read(&data->ctx, sequence);
656 
657 	return adc_context_wait_for_completion(&data->ctx);
658 }
659 
max1125x_adc_read_async(const struct device * dev,const struct adc_sequence * sequence,struct k_poll_signal * async)660 static int max1125x_adc_read_async(const struct device *dev, const struct adc_sequence *sequence,
661 				   struct k_poll_signal *async)
662 {
663 	int rc;
664 	struct max1125x_data *data = dev->data;
665 
666 	adc_context_lock(&data->ctx, async ? true : false, async);
667 	rc = max1125x_adc_start_read(dev, sequence);
668 	adc_context_release(&data->ctx, rc);
669 
670 	return rc;
671 }
672 
max1125x_adc_perform_read(const struct device * dev)673 static int max1125x_adc_perform_read(const struct device *dev)
674 {
675 	struct max1125x_data *data = dev->data;
676 	int rc;
677 
678 	rc = max1125x_read_sample(dev);
679 	if (rc != 0) {
680 		LOG_ERR("reading sample failed (err %d)", rc);
681 		adc_context_complete(&data->ctx, rc);
682 		return rc;
683 	}
684 
685 	return rc;
686 }
687 
max1125x_read(const struct device * dev,const struct adc_sequence * sequence)688 static int max1125x_read(const struct device *dev, const struct adc_sequence *sequence)
689 {
690 	return max1125x_adc_read_async(dev, sequence, NULL);
691 }
692 
max1125x_acquisition_thread(void * p1,void * p2,void * p3)693 static void max1125x_acquisition_thread(void *p1, void *p2, void *p3)
694 {
695 	ARG_UNUSED(p2);
696 	ARG_UNUSED(p3);
697 
698 	const struct device *dev = p1;
699 	struct max1125x_data *data = dev->data;
700 	int rc;
701 
702 	while (true) {
703 		k_sem_take(&data->acq_sem, K_FOREVER);
704 
705 		rc = max1125x_wait_data_ready(dev);
706 		if (rc != 0) {
707 			LOG_ERR("MAX1125X: failed to get ready status (err %d)", rc);
708 			adc_context_complete(&data->ctx, rc);
709 			break;
710 		}
711 
712 		max1125x_adc_perform_read(dev);
713 	}
714 }
715 
max1125x_init(const struct device * dev)716 static int max1125x_init(const struct device *dev)
717 {
718 	int err;
719 	const struct max1125x_config *config = dev->config;
720 	struct max1125x_data *data = dev->data;
721 
722 	data->dev = dev;
723 
724 	k_sem_init(&data->acq_sem, 0, 1);
725 	k_sem_init(&data->data_ready_signal, 0, 1);
726 
727 	if (!spi_is_ready_dt(&config->bus)) {
728 		LOG_ERR("spi bus %s not ready", config->bus.bus->name);
729 		return -ENODEV;
730 	}
731 
732 	if (config->self_calibration) {
733 		LOG_INF("performing self calibration process");
734 		max1125x_self_calibration(dev);
735 	}
736 
737 	err = gpio_pin_configure_dt(&config->drdy_gpio, GPIO_INPUT);
738 	if (err != 0) {
739 		LOG_ERR("failed to initialize GPIO for data ready (err %d)", err);
740 		return err;
741 	}
742 
743 	err = gpio_pin_interrupt_configure_dt(&config->drdy_gpio, GPIO_INT_EDGE_TO_ACTIVE);
744 	if (err != 0) {
745 		LOG_ERR("failed to configure data ready interrupt (err %d)", err);
746 		return -EIO;
747 	}
748 
749 	gpio_init_callback(&data->callback_data_ready, max1125x_data_ready_handler,
750 			   BIT(config->drdy_gpio.pin));
751 	err = gpio_add_callback(config->drdy_gpio.port, &data->callback_data_ready);
752 	if (err != 0) {
753 		LOG_ERR("failed to add data ready callback (err %d)", err);
754 		return -EIO;
755 	}
756 
757 	k_tid_t tid = k_thread_create(
758 		&data->thread, data->stack, K_KERNEL_STACK_SIZEOF(data->stack),
759 		max1125x_acquisition_thread, (void *)dev, NULL, NULL,
760 		CONFIG_ADC_MAX1125X_ACQUISITION_THREAD_PRIORITY, 0, K_NO_WAIT);
761 	k_thread_name_set(tid, "adc_max1125x");
762 
763 	adc_context_unlock_unconditionally(&data->ctx);
764 
765 	return 0;
766 }
767 
768 static const struct adc_driver_api max1125x_api = {
769 	.channel_setup = max1125x_channel_setup,
770 	.read = max1125x_read,
771 	.ref_internal = 2048,
772 #ifdef CONFIG_ADC_ASYNC
773 	.read_async = max1125x_adc_read_async,
774 #endif
775 };
776 
777 #define DT_INST_MAX1125X(inst, t) DT_INST(inst, maxim_max##t)
778 
779 #define MAX1125X_INIT(t, n, odr_delay_us, res, mux, pgab)                                          \
780 	static const struct max1125x_config max##t##_cfg_##n = {                                   \
781 		.bus = SPI_DT_SPEC_GET(DT_INST_MAX1125X(n, t),                                     \
782 				       SPI_OP_MODE_MASTER | SPI_WORD_SET(8) | SPI_TRANSFER_MSB,    \
783 				       1),                                                         \
784 		.odr_delay = odr_delay_us,                                                         \
785 		.resolution = res,                                                                 \
786 		.multiplexer = mux,                                                                \
787 		.pga = pgab,                                                                       \
788 		.drdy_gpio = GPIO_DT_SPEC_GET_OR(DT_INST_MAX1125X(n, t), drdy_gpios, {0}),         \
789 		.self_calibration = DT_PROP_OR(DT_INST_MAX1125X(n, t), self_calibration, 0),       \
790 		.gpio.gpio0_enable = DT_PROP_OR(DT_INST_MAX1125X(n, t), gpio0_enable, 1),          \
791 		.gpio.gpio1_enable = DT_PROP_OR(DT_INST_MAX1125X(n, t), gpio1_enable, 0),          \
792 		.gpio.gpio0_direction = DT_PROP_OR(DT_INST_MAX1125X(n, t), gpio0_direction, 0),    \
793 		.gpio.gpio1_direction = DT_PROP_OR(DT_INST_MAX1125X(n, t), gpio1_direction, 0),    \
794 		.gpo.gpo0_enable = DT_PROP_OR(DT_INST_MAX1125X(n, t), gpo1_enable, 0),             \
795 		.gpo.gpo1_enable = DT_PROP_OR(DT_INST_MAX1125X(n, t), gpo1_enable, 0),             \
796 	};                                                                                         \
797 	static struct max1125x_data max##t##_data_##n = {                                          \
798 		ADC_CONTEXT_INIT_LOCK(max##t##_data_##n, ctx),                                     \
799 		ADC_CONTEXT_INIT_TIMER(max##t##_data_##n, ctx),                                    \
800 		ADC_CONTEXT_INIT_SYNC(max##t##_data_##n, ctx),                                     \
801 	};                                                                                         \
802 	DEVICE_DT_DEFINE(DT_INST_MAX1125X(n, t), max1125x_init, NULL, &max##t##_data_##n,          \
803 			 &max##t##_cfg_##n, POST_KERNEL, CONFIG_ADC_MAX1125X_INIT_PRIORITY,        \
804 			 &max1125x_api);
805 
806 /* Each data register is a 16-bit read-only register. Any attempt to write
807  * data to this location will have no effect. The data read from these
808  * registers is clocked out MSB first. The result is stored in a format
809  * according to the FORMAT bit in the CTRL1 register. The data format
810  * while in unipolar mode is always offset binary. In offset binary
811  * format the most negative value is 0x0000, the midscale value is 0x8000 and
812  *  the most positive value is 0xFFFF. In bipolar mode if the FORMAT
813  * bit = ‘1’ then the data format is offset binary. If the FORMAT
814  * bit= ‘0’, then the data format is two’s complement. In two’s
815  * complement the negative full-scale value is 0x8000, the midscale is 0x0000
816  * and the positive full scale is 0x7FFF. Any input exceeding the available
817  * input range is limited to the minimum or maximum data value.
818  */
819 
820 #define MAX11253_RESOLUTION 16
821 
822 /* Each data register is a 24-bit read-only register. Any attempt to write
823  * data to this location will have no effect. The data read from these
824  * registers is clocked out MSB first. The result is stored in a format
825  * according to the FORMAT bit in the CTRL1 register. The data format
826  * while in unipolar mode is always offset binary. In offset binary format
827  * the most negative value is 0x000000, the midscale value is 0x800000 and
828  * the most positive value is 0xFFFFFF. In bipolar mode if the FORMAT
829  * bit = ‘1’ then the data format is offset binary. If the FORMAT bit = ‘0’,
830  * then the data format is two’s complement. In two’s complement the negative
831  * full-scale value is 0x800000, the midscale is 0x000000 and the positive
832  * full scale is 0x7FFFFF. Any input exceeding the available input range is
833  * limited to the minimum or maximum data value.
834  */
835 
836 #define MAX11254_RESOLUTION 24
837 
838 /*
839  * Approximated MAX1125X acquisition times in microseconds. These are
840  * used for the initial delay when polling for data ready.
841  *
842  * {1.9 SPS, 3.9 SPS, 7.8 SPS, 15.6 SPS, 31.2 SPS, 62.5 SPS, 125 SPS, 250 SPS, 500 SPS,
843  * 1000 SPS, 2000 SPS, 4000 SPS, 8000 SPS, 16000 SPS, 32000 SPS, 64000 SPS}
844  */
845 #define MAX1125X_ODR_DELAY_US                                                                      \
846 	{                                                                                          \
847 		526315, 256410, 128205, 64102, 32051, 16000, 8000, 4000, 2000, 1000, 500, 250,     \
848 			125, 62, 31, 15                                                            \
849 	}
850 
851 /*
852  * MAX11253: 16 bit, 6-channel, programmable gain amplifier, delta-sigma
853  */
854 #define MAX11253_INIT(n)                                                                           \
855 	MAX1125X_INIT(11253, n, MAX1125X_ODR_DELAY_US, MAX11253_RESOLUTION, false, true)
856 #undef DT_DRV_COMPAT
857 #define DT_DRV_COMPAT maxim_max11253
858 DT_INST_FOREACH_STATUS_OKAY(MAX11253_INIT)
859 
860 /*
861  * MAX1125X: 24 bit, 6-channel, programmable gain amplifier, delta-sigma
862  */
863 
864 #define MAX11254_INIT(n)                                                                           \
865 	MAX1125X_INIT(11254, n, MAX1125X_ODR_DELAY_US, MAX11254_RESOLUTION, false, true)
866 #undef DT_DRV_COMPAT
867 #define DT_DRV_COMPAT maxim_max11254
868 DT_INST_FOREACH_STATUS_OKAY(MAX11254_INIT)
869