1 /*
2  * Copyright (c) 2023 Intel Corporation
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/drivers/adc.h>
8 #include <zephyr/drivers/dac.h>
9 #include <zephyr/drivers/adc.h>
10 #include <zephyr/ztest.h>
11 
12 #define DIV 2
13 
14 #define DAC_DEVICE_NODE	DT_PROP(DT_PATH(zephyr_user), dac)
15 
16 extern const struct adc_dt_spec *get_adc_channel(void);
17 
18 static const struct dac_channel_cfg dac_ch_cfg = {
19 	.channel_id = DT_PROP(DT_PATH(zephyr_user), dac_channel_id),
20 	.resolution = DT_PROP(DT_PATH(zephyr_user), dac_resolution),
21 	.buffered = true
22 };
23 
init_dac(void)24 static const struct device *init_dac(void)
25 {
26 	int ret;
27 	const struct device *const dac_dev = DEVICE_DT_GET(DAC_DEVICE_NODE);
28 
29 	zassert_true(device_is_ready(dac_dev), "DAC device is not ready");
30 
31 	ret = dac_channel_setup(dac_dev, &dac_ch_cfg);
32 	zassert_equal(ret, 0,
33 		      "Setting up of the first channel failed with code %d", ret);
34 
35 	return dac_dev;
36 }
37 
test_dac_to_adc(void)38 static int test_dac_to_adc(void)
39 {
40 	int ret, write_val;
41 	int32_t sample_buffer = 0;
42 
43 	struct adc_sequence sequence = {
44 		.buffer      = &sample_buffer,
45 		.buffer_size = sizeof(sample_buffer),
46 	};
47 
48 	const struct device *dac_dev = init_dac();
49 	const struct adc_dt_spec *adc_channel = get_adc_channel();
50 
51 	write_val = (1U << dac_ch_cfg.resolution) / DIV;
52 
53 	ret = dac_write_value(dac_dev, DT_PROP(DT_PATH(zephyr_user), dac_channel_id), write_val);
54 
55 	zassert_equal(ret, 0, "dac_write_value() failed with code %d", ret);
56 
57 	k_sleep(K_MSEC(10));
58 
59 	adc_sequence_init_dt(adc_channel, &sequence);
60 	ret = adc_read_dt(adc_channel, &sequence);
61 
62 	zassert_equal(ret, 0, "adc_read_dt() failed with code %d", ret);
63 	zassert_within(sample_buffer,
64 			(1U << adc_channel->resolution) / DIV, 32,
65 			"Value %d read from ADC does not match expected range.",
66 			sample_buffer);
67 
68 	return TC_PASS;
69 }
70 
ZTEST(adc_accuracy_test,test_dac_to_adc)71 ZTEST(adc_accuracy_test, test_dac_to_adc)
72 {
73 	int i;
74 
75 	for (i = 0; i < CONFIG_NUMBER_OF_PASSES; i++) {
76 		zassert_true(test_dac_to_adc() == TC_PASS);
77 	}
78 }
79