dac.c
2.71 KB
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
/*
* Copyright (C) 2014 Simon Brummer
* 2015-2016 Freie Universität Berlin
*
* This file is subject to the terms and conditions of the GNU Lesser
* General Public License v2.1. See the file LICENSE in the top level
* directory for more details.
*/
/**
* @ingroup cpu_stm32_common
* @ingroup drivers_periph_dac
* @{
*
* @file
* @brief Low-level DAC driver implementation
*
* @author Simon Brummer <simon.brummer@haw-hamburg.de>
* @author Hauke Petersen <hauke.petersen@fu-berlin.de>
*
* @}
*/
#include "cpu.h"
#include "assert.h"
#include "periph/dac.h"
/* only compile this, if the CPU has a DAC */
#ifdef DAC_NUMOF
/* DAC channel enable bits */
#ifdef DAC_CR_EN2
#define EN_MASK (DAC_CR_EN1 | DAC_CR_EN2)
#else
#define EN_MASK (DAC_CR_EN1)
#endif
/* get RCC bit */
#ifdef RCC_APB1ENR_DAC1EN
#define RCC_BIT (RCC_APB1ENR_DAC1EN)
#else
#define RCC_BIT (RCC_APB1ENR_DACEN)
#endif
/* deduct DAC device from given line channel */
static inline DAC_TypeDef *dev(dac_t line)
{
#if defined(DAC2)
return (dac_config[line].chan > 1) ? DAC2 : DAC1;
#elif defined (DAC1)
return DAC1;
#else
return DAC;
#endif
}
int8_t dac_init(dac_t line)
{
if (line >= DAC_NUMOF) {
return DAC_NOLINE;
}
/* configure pin */
gpio_init_analog(dac_config[line].pin);
/* reset output and enable the line's channel */
dac_poweron(line);
dac_set(line, 0);
return DAC_OK;
}
void dac_set(dac_t line, uint16_t value)
{
assert(line < DAC_NUMOF);
/* scale set value to 12-bit */
value = (value >> 4);
#ifdef DAC_DHR12R2_DACC2DHR
if (dac_config[line].chan & 0x01) {
dev(line)->DHR12R2 = value;
}
else {
dev(line)->DHR12R1 = value;
}
#else
dev(line)->DHR12R1 = value;
#endif
}
void dac_poweron(dac_t line)
{
assert(line < DAC_NUMOF);
/* enable the DAC's clock */
#if defined(DAC2)
periph_clk_en(APB1, (dac_config[line].chan > 1) ?
RCC_APB1ENR_DAC2EN : RCC_APB1ENR_DAC1EN);
#else
periph_clk_en(APB1, RCC_BIT);
#endif
/* enable corresponding DAC channel */
dev(line)->CR |= (1 << (16 * (dac_config[line].chan & 0x01)));
}
void dac_poweroff(dac_t line)
{
assert(line < DAC_NUMOF);
/* disable corresponding channel */
dev(line)->CR &= ~(1 << (16 * (dac_config[line].chan & 0x01)));
/* disable the DAC's clock in case no channel is active anymore */
if (!(dev(line)->CR & EN_MASK)) {
#if defined(DAC2)
periph_clk_dis(APB1, (dac_config[line].chan > 1) ?
RCC_APB1ENR_DAC2EN : RCC_APB1ENR_DAC1EN);
#else
periph_clk_dis(APB1, RCC_BIT);
#endif
}
}
#else
typedef int dont_be_pedantic;
#endif /* DAC */