]> git.donarmstrong.com Git - qmk_firmware.git/blob - tool/mbed/mbed-sdk/libraries/mbed/targets/hal/TARGET_Freescale/TARGET_K20XX/analogout_api.c
Squashed 'tmk_core/' changes from 7967731..b9e0ea0
[qmk_firmware.git] / tool / mbed / mbed-sdk / libraries / mbed / targets / hal / TARGET_Freescale / TARGET_K20XX / analogout_api.c
1 /* mbed Microcontroller Library
2  * Copyright (c) 2006-2015 ARM Limited
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16  
17 #include "mbed_assert.h"
18 #include "analogout_api.h"
19
20 #if DEVICE_ANALOGOUT
21
22 #include "cmsis.h"
23 #include "pinmap.h"
24 #include "PeripheralPins.h"
25
26 #define RANGE_12BIT     0xFFF
27
28 void analogout_init(dac_t *obj, PinName pin) {
29     obj->dac = (DACName)pinmap_peripheral(pin, PinMap_DAC);
30     MBED_ASSERT(obj->dac != (DACName)NC);
31
32     SIM->SCGC2 |= SIM_SCGC2_DAC0_MASK;
33
34     uint32_t port = (uint32_t)pin >> PORT_SHIFT;
35     SIM->SCGC5 |= 1 << (SIM_SCGC5_PORTA_SHIFT + port);
36
37     DAC0->DAT[obj->dac].DATH = 0;
38     DAC0->DAT[obj->dac].DATL = 0;
39
40     DAC0->C1 = DAC_C1_DACBFMD_MASK;     // One-Time Scan Mode
41
42     DAC0->C0 = DAC_C0_DACEN_MASK      // Enable
43              | DAC_C0_DACSWTRG_MASK   // Software Trigger
44              | DAC_C0_DACRFS_MASK;    // VDDA selected
45
46     analogout_write_u16(obj, 0);
47 }
48
49 void analogout_free(dac_t *obj) {}
50
51 static inline void dac_write(dac_t *obj, int value) {
52     DAC0->DAT[obj->dac].DATL = (uint8_t)( value       & 0xFF);
53     DAC0->DAT[obj->dac].DATH = (uint8_t)((value >> 8) & 0xFF);
54 }
55
56 static inline int dac_read(dac_t *obj) {
57     return ((DAC0->DAT[obj->dac].DATH << 8) | DAC0->DAT[obj->dac].DATL);
58 }
59
60 void analogout_write(dac_t *obj, float value) {
61     if (value < 0.0) {
62         dac_write(obj, 0);
63     } else if (value > 1.0) {
64         dac_write(obj, RANGE_12BIT);
65     } else {
66         dac_write(obj, value * (float)RANGE_12BIT);
67     }
68 }
69
70 void analogout_write_u16(dac_t *obj, uint16_t value) {
71     dac_write(obj, value >> 4); // 12-bit
72 }
73
74 float analogout_read(dac_t *obj) {
75     uint32_t value = dac_read(obj);
76     return (float)value * (1.0f / (float)RANGE_12BIT);
77 }
78
79 uint16_t analogout_read_u16(dac_t *obj) {
80     uint32_t value = dac_read(obj); // 12-bit
81     return (value << 4) | ((value >> 8) & 0x003F);
82 }
83
84 #endif