1 /*
2 * Copyright (c) 2006-2022, Synwit Technology Co.,Ltd.
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 *
6 * Change Logs:
7 * Date Author Notes
8 * 2022-02-10 lik first version
9 */
10
11 #include "drv_dac.h"
12
13 #ifdef BSP_USING_DAC
14
15 //#define DRV_DEBUG
16 #define LOG_TAG "drv.dac"
17 #include <drv_log.h>
18
19 static struct rt_dac_device swm_dac_device;
20
swm_dac_enabled(struct rt_dac_device * device,rt_uint32_t channel)21 static rt_err_t swm_dac_enabled(struct rt_dac_device *device, rt_uint32_t channel)
22 {
23 RT_ASSERT(device != RT_NULL);
24
25 if (channel != 0)
26 {
27 LOG_E("dac channel must be 0.");
28 return -RT_ERROR;
29 }
30 DAC_Open(DAC);
31
32 return RT_EOK;
33 }
34
swm_dac_disabled(struct rt_dac_device * device,rt_uint32_t channel)35 static rt_err_t swm_dac_disabled(struct rt_dac_device *device, rt_uint32_t channel)
36 {
37 RT_ASSERT(device != RT_NULL);
38
39 if (channel != 0)
40 {
41 LOG_E("dac channel must be 0.");
42 return -RT_ERROR;
43 }
44 DAC_Close(DAC);
45
46 return RT_EOK;
47 }
48
swm_dac_convert(struct rt_dac_device * device,rt_uint32_t channel,rt_uint32_t * value)49 static rt_err_t swm_dac_convert(struct rt_dac_device *device, rt_uint32_t channel, rt_uint32_t *value)
50 {
51 RT_ASSERT(device != RT_NULL);
52 RT_ASSERT(value != RT_NULL);
53
54 if (channel != 0)
55 {
56 LOG_E("dac channel must be 0.");
57 return -RT_ERROR;
58 }
59
60 DAC->DHR = *value;
61 while(DAC->SR & DAC_SR_DHRFULL_Msk) __NOP();
62
63 return RT_EOK;
64 }
65
66 static const struct rt_dac_ops swm_dac_ops =
67 {
68 .disabled = swm_dac_disabled,
69 .enabled = swm_dac_enabled,
70 .convert = swm_dac_convert,
71 };
72
swm_dac_init(void)73 int swm_dac_init(void)
74 {
75 int result = RT_EOK;
76
77 PORT_Init(PORTD, PIN2, PORTD_PIN2_DAC_OUT, 0);
78
79 DAC_Init(DAC, DAC_FORMAT_LSB12B);
80
81 SYS->DACCR &= ~SYS_DACCR_VRADJ_Msk;
82 SYS->DACCR |= (17 << SYS_DACCR_VRADJ_Pos);
83
84 /* register dac device */
85 result = rt_hw_dac_register(&swm_dac_device, "dac", &swm_dac_ops, RT_NULL);
86 if(result != RT_EOK)
87 {
88 LOG_E("dac register fail.");
89 }
90 else
91 {
92 LOG_D("dac register success.");
93 }
94
95 return result;
96 }
97 INIT_DEVICE_EXPORT(swm_dac_init);
98
99 #endif /* BSP_USING_DAC */
100