1 /*
2  * Copyright (c) 2020 Libre Solar Technologies GmbH
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/kernel.h>
8 #include <zephyr/sys/printk.h>
9 #include <zephyr/drivers/dac.h>
10 
11 #define ZEPHYR_USER_NODE DT_PATH(zephyr_user)
12 
13 #if (DT_NODE_HAS_PROP(ZEPHYR_USER_NODE, dac) && \
14 	DT_NODE_HAS_PROP(ZEPHYR_USER_NODE, dac_channel_id) && \
15 	DT_NODE_HAS_PROP(ZEPHYR_USER_NODE, dac_resolution))
16 #define DAC_NODE DT_PHANDLE(ZEPHYR_USER_NODE, dac)
17 #define DAC_CHANNEL_ID DT_PROP(ZEPHYR_USER_NODE, dac_channel_id)
18 #define DAC_RESOLUTION DT_PROP(ZEPHYR_USER_NODE, dac_resolution)
19 #else
20 #error "Unsupported board: see README and check /zephyr,user node"
21 #define DAC_NODE DT_INVALID_NODE
22 #define DAC_CHANNEL_ID 0
23 #define DAC_RESOLUTION 0
24 #endif
25 
26 static const struct device *const dac_dev = DEVICE_DT_GET(DAC_NODE);
27 
28 static const struct dac_channel_cfg dac_ch_cfg = {
29 	.channel_id  = DAC_CHANNEL_ID,
30 	.resolution  = DAC_RESOLUTION,
31 	.buffered = true
32 };
33 
main(void)34 int main(void)
35 {
36 	if (!device_is_ready(dac_dev)) {
37 		printk("DAC device %s is not ready\n", dac_dev->name);
38 		return 0;
39 	}
40 
41 	int ret = dac_channel_setup(dac_dev, &dac_ch_cfg);
42 
43 	if (ret != 0) {
44 		printk("Setting up of DAC channel failed with code %d\n", ret);
45 		return 0;
46 	}
47 
48 	printk("Generating sawtooth signal at DAC channel %d.\n",
49 		DAC_CHANNEL_ID);
50 	while (1) {
51 		/* Number of valid DAC values, e.g. 4096 for 12-bit DAC */
52 		const int dac_values = 1U << DAC_RESOLUTION;
53 
54 		/*
55 		 * 1 msec sleep leads to about 4 sec signal period for 12-bit
56 		 * DACs. For DACs with lower resolution, sleep time needs to
57 		 * be increased.
58 		 * Make sure to sleep at least 1 msec even for future 16-bit
59 		 * DACs (lowering signal frequency).
60 		 */
61 		const int sleep_time = 4096 / dac_values > 0 ?
62 			4096 / dac_values : 1;
63 
64 		for (int i = 0; i < dac_values; i++) {
65 			ret = dac_write_value(dac_dev, DAC_CHANNEL_ID, i);
66 			if (ret != 0) {
67 				printk("dac_write_value() failed with code %d\n", ret);
68 				return 0;
69 			}
70 			k_sleep(K_MSEC(sleep_time));
71 		}
72 	}
73 	return 0;
74 }
75