-
Notifications
You must be signed in to change notification settings - Fork 2
/
dac.c
95 lines (76 loc) · 2.15 KB
/
dac.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/** @file dac.c
* @brief DAC driver
* @author Dennis Law
* @date April 2016
*/
#include "dac.h"
/** @brief Initializes a DAC channel.
* @param chn Channel to initialize.
* @returns Returns 0 if successful and -1 if otherwise.
*
* Initializes either channel 1 or 2 of the DAC. The channel is configured to
* use timer as the triggering source. The assignment of the timer to the
* channel is done with reference to Table 31 of the Reference Manual. Also,
* DMA is enabled.
*/
int dac_init(enum dac_channel chn)
{
/* Check if channel index is correct */
if ((chn != DAC_CHN_1) && (chn != DAC_CHN_2))
return -1;
/* Enable clock for DAC peripheral */
RCC->APB1ENR |= RCC_APB1ENR_DACEN;
if (chn == DAC_CHN_1) {
/* Configure Timer 6 as trigger */
DAC->CR &= ~(DAC_CR_TSEL1);
DAC->CR |= DAC_CR_TEN1;
/* Configure DMA */
DAC->CR |= DAC_CR_DMAEN1;
/* Congigure GPIO */
GPIOA->MODER |= GPIO_MODER_MODER4; /* Set pin as AIN */
GPIOA->PUPDR &= ~(GPIO_PUPDR_PUPDR4); /* Disable pull resistor */
/* Enable output buffer */
DAC->CR |= DAC_CR_BOFF1;
} else if (chn == DAC_CHN_2) {
/* Configure Timer 7 as trigger */
DAC->CR &= ~(DAC_CR_TSEL2);
DAC->CR |= DAC_CR_TSEL2_1;
DAC->CR |= DAC_CR_TEN2;
/* Configure DMA */
DAC->CR |= DAC_CR_DMAEN2;
/* Congigure GPIO */
GPIOA->MODER |= GPIO_MODER_MODER5; /* Set pin as AIN */
GPIOA->PUPDR &= ~(GPIO_PUPDR_PUPDR5); /* Disable pull resistor */
/* Enable output buffer */
DAC->CR |= DAC_CR_BOFF2;
}
return 0;
}
/** @brief Disables the selected channel.
* @param chn The channe to disable.
* @returns 0 if successful and -1 if otherwise.
*/
int dac_disable(enum dac_channel chn)
{
if ((chn != DAC_CHN_1) && (chn != DAC_CHN_2))
return -1;
if (chn == DAC_CHN_1)
DAC->CR &= ~(DAC_CR_EN1);
else
DAC->CR &= ~(DAC_CR_EN2);
return 0;
}
/** @brief Enables the selected channel.
* @param chn The channel to enable.
* @returns Returns 0 if successful and -1 if otherwise.
*/
int dac_enable(enum dac_channel chn)
{
if ((chn != DAC_CHN_1) && (chn != DAC_CHN_2))
return -1;
if (chn == DAC_CHN_1)
DAC->CR |= DAC_CR_EN1;
else
DAC->CR |= DAC_CR_EN2;
return 0;
}