1 /*
2  * Copyright 2025 NXP
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/drivers/opamp.h>
8 #include <zephyr/devicetree.h>
9 #include <zephyr/kernel.h>
10 #include <zephyr/ztest.h>
11 
12 #define OPAMP_SUPPORT_PROGRAMMABLE_GAIN					\
13 	DT_NODE_HAS_PROP(DT_PHANDLE(DT_PATH(zephyr_user), opamp),	\
14 			programmable_gain)
15 
16 #if OPAMP_SUPPORT_PROGRAMMABLE_GAIN
17 static const enum opamp_gain gain[] = {
18 	DT_FOREACH_PROP_ELEM_SEP(DT_PHANDLE(DT_PATH(zephyr_user), opamp),
19 				programmable_gain, DT_ENUM_IDX_BY_IDX, (,))
20 };
21 #endif
22 
get_opamp_device(void)23 const struct device *get_opamp_device(void)
24 {
25 	return DEVICE_DT_GET(DT_PHANDLE(DT_PATH(zephyr_user), opamp));
26 }
27 
init_opamp(void)28 static const struct device *init_opamp(void)
29 {
30 	int ret;
31 
32 	const struct device *const opamp_dev =
33 				DEVICE_DT_GET(DT_PHANDLE(DT_PATH(zephyr_user), opamp));
34 
35 	ret = device_is_ready(opamp_dev);
36 
37 	zassert_true(ret, "OPAMP device %s is not ready", opamp_dev->name);
38 
39 	return opamp_dev;
40 }
41 
42 #if OPAMP_SUPPORT_PROGRAMMABLE_GAIN
43 /* Test OPAMP opamp_set_gain API, Only OPAMPs
44  * that support PGA need to test this API.
45  */
ZTEST(opamp,test_gain_set)46 ZTEST(opamp, test_gain_set)
47 {
48 	int ret;
49 
50 	const struct device *opamp_dev = init_opamp();
51 
52 	for (uint8_t index = 0; index < ARRAY_SIZE(gain); ++index) {
53 		ret = opamp_set_gain(opamp_dev, gain[index]);
54 		zassert_ok(ret, "opamp_set_gain() failed with code %d", ret);
55 	}
56 }
57 #endif
58 
ZTEST(opamp,test_init_opamp)59 ZTEST(opamp, test_init_opamp)
60 {
61 	const struct device *opamp_dev = init_opamp();
62 
63 	ARG_UNUSED(opamp_dev);
64 }
65 
opamp_setup(void)66 static void *opamp_setup(void)
67 {
68 	k_object_access_grant(get_opamp_device(), k_current_get());
69 
70 	return NULL;
71 }
72 
73 ZTEST_SUITE(opamp, NULL, opamp_setup, NULL, NULL, NULL);
74