]> rtime.felk.cvut.cz Git - pes-rpp/rpp-lib.git/blob - rpp/src/drv/dac.c
Merge branches 'master' and 'rm48/master'
[pes-rpp/rpp-lib.git] / rpp / src / drv / dac.c
1 /* Copyright (C) 2012-2013 Czech Technical University in Prague
2  *
3  * Authors:
4  *     - Michal Horn
5  *     - Carlos Jenkins <carlos@jenkins.co.cr>
6  *
7  * This document contains proprietary information belonging to Czech
8  * Technical University in Prague. Passing on and copying of this
9  * document, and communication of its contents is not permitted
10  * without prior written authorization.
11  *
12  * File : dac.c
13  * Abstract:
14  *     RPP driver implementation for DAC.
15  *
16  * References:
17  *     None
18  */
19
20
21 #include "drv/dac.h"
22
23 #define DAC_PIN_NUM     4
24
25 // See mcp4922.pdf p. 24
26 // Options:
27 //   Bit 13: Output Gain Selection bit set = 1x (VOUT = VREF * D/4096)
28 //   Bit 15: DACA (0) or DACB (1) Selection bit.
29 #define DAC1_INIT_VAL   (_BV(13)          )
30 #define DAC2_INIT_VAL   (_BV(13) | _BV(15))
31 #define DAC3_INIT_VAL   (_BV(13)          )
32 #define DAC4_INIT_VAL   (_BV(13) | _BV(15))
33
34 /**
35  * Pin status for each DAC pin, the structure of each field is defined
36  * as spi command structure.
37  */
38 uint16_t dac_pin_stat[DAC_PIN_NUM] = {
39         DAC1_INIT_VAL,
40         DAC2_INIT_VAL,
41         DAC3_INIT_VAL,
42         DAC4_INIT_VAL
43 };
44
45 /**
46  * Port names for each DAC port, to be easily accessible by indexing
47  */
48 const char *dac_port_names[DAC_PIN_NUM] = {
49         PORT_NAME_DAC1_2,
50         PORT_NAME_DAC1_2,
51         PORT_NAME_DAC3_4,
52         PORT_NAME_DAC3_4
53 };
54
55 /**
56  * Command for SPI
57  */
58 static uint32_t dac_spi_cmd;
59 /**
60  * Shadow variable of SPI command
61  */
62 static uint32_t dac_spi_cmd_sh;
63
64 int drv_dac_spi_transfer(uint8_t pin, boolean_t enabled, uint16_t value)
65 {
66         // Check pin range
67         if (pin >= DAC_PIN_NUM)
68                 return -1;
69
70         // Check value range
71         if (value > 4095)
72                 return -2;
73
74         // Prepare command
75         if (enabled)
76                 bit_set(dac_pin_stat[pin], 12);
77         else
78                 bit_clear(dac_pin_stat[pin], 12);
79
80         dac_pin_stat[pin] = dac_pin_stat[pin] & 0xF000;
81         dac_pin_stat[pin] |= (value & 0xFFF);
82
83         uint32_t commands[2];
84
85         // Warning!!! Can be "optimized" by compiler
86         dac_spi_cmd = dac_pin_stat[pin];
87         dac_spi_cmd_sh = dac_spi_cmd;
88         //--
89         port_desc_t *desc;
90         desc = hal_port_get_dsc(dac_port_names[pin], -1);
91         commands[0] = (dac_spi_cmd_sh & 0xFF00) >> 8;
92         commands[1] = (dac_spi_cmd_sh & 0xFF);
93
94         return desc->port_setfnc_ptr(desc->config, desc->numValues, commands);
95 }