1 /* Copyright (C) 2013, 2015 Czech Technical University in Prague
4 * - Carlos Jenkins <carlos@jenkins.co.cr>
6 * This document contains proprietary information belonging to Czech
7 * Technical University in Prague. Passing on and copying of this
8 * document, and communication of its contents is not permitted
9 * without prior written authorization.
13 * Analog Output RPP API implementation file.
17 * RPP API documentation.
22 #include "rpp/mutex.h"
24 #ifndef FREERTOS_POSIX
29 RPP_MUTEX_DEFINE(mutex_dac);
31 static boolean_t initialized = FALSE;
37 if (!RPP_MUTEX_INIT(mutex_dac))
40 #ifndef FREERTOS_POSIX
44 // FIXME find out why board has default output of ~3.8V
45 //rpp_dac_setup(1, FALSE);
46 //rpp_dac_setup(2, FALSE);
47 //rpp_dac_setup(3, FALSE);
48 //rpp_dac_setup(4, FALSE);
54 static boolean_t changed_st[4] = {
55 FALSE, FALSE, FALSE, FALSE
57 static boolean_t enabled_cache[4] = {
58 FALSE, FALSE, FALSE, FALSE
60 static uint16_t out_cache[4] = {
64 int8_t rpp_dac_setup(uint8_t pin, boolean_t enabled)
67 if ((pin < 1) || (pin > 4))
70 uint8_t index = pin - 1;
72 RPP_MUTEX_LOCK(mutex_dac);
74 enabled_cache[index] = enabled;
77 changed_st[index] = TRUE;
78 RPP_MUTEX_UNLOCK(mutex_dac);
83 // Value that tops the DAC output
84 const static uint16_t dac_top =
85 (uint16_t)(4095.0 * (12000.0 / 1000.0) / (RPP_DAC_OA * RPP_DAC_VREF));
87 // Simple mapping function
88 static int32_t map(int32_t x,
89 int32_t in_min, int32_t in_max,
90 int32_t out_min, int32_t out_max)
92 return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
95 int8_t rpp_dac_set(uint8_t pin, uint16_t val)
98 if ((pin < 1) || (pin > 4))
102 val = map(val, 0, 4095, 0, dac_top);
108 uint8_t index = pin - 1;
110 RPP_MUTEX_LOCK(mutex_dac);
111 // Set value to output cache
112 out_cache[index] = val;
115 changed_st[index] = TRUE;
116 RPP_MUTEX_UNLOCK(mutex_dac);
122 int8_t rpp_dac_set_voltage(uint8_t pin, uint16_t mv)
125 if ((pin < 1) || (pin > 4))
128 // Check millivolts range
132 // Calculate millivolts -> value
133 int val = (int)(4095.0 * ((float)mv / 1000.0) / (RPP_DAC_OA*RPP_DAC_VREF));
137 uint8_t index = pin - 1;
139 RPP_MUTEX_LOCK(mutex_dac);
140 // Set value to output cache
141 out_cache[index] = val;
144 changed_st[index] = TRUE;
145 RPP_MUTEX_UNLOCK(mutex_dac);
151 int8_t rpp_dac_update()
155 for (i = 0; i < 4; i++) {
156 RPP_MUTEX_LOCK(mutex_dac);
157 // If changed commit changes to hardware
160 #ifndef FREERTOS_POSIX
161 // TODO: Confirm via returned SPI code that transfer was successful
162 drv_dac_spi_transfer(i, enabled_cache[i], out_cache[i]);
164 UNUSED(enabled_cache);
168 changed_st[i] = FALSE;
170 RPP_MUTEX_UNLOCK(mutex_dac);