]> git.donarmstrong.com Git - qmk_firmware.git/blob - tool/mbed/mbed-sdk/libraries/mbed/targets/hal/TARGET_Freescale/TARGET_KPSDK_MCUS/analogout_api.c
Squashed 'tmk_core/' changes from 7967731..b9e0ea0
[qmk_firmware.git] / tool / mbed / mbed-sdk / libraries / mbed / targets / hal / TARGET_Freescale / TARGET_KPSDK_MCUS / analogout_api.c
1 /* mbed Microcontroller Library
2  * Copyright (c) 2006-2013 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 #include "analogout_api.h"
17
18 #if DEVICE_ANALOGOUT
19
20 #include "cmsis.h"
21 #include "pinmap.h"
22 #include "mbed_error.h"
23 #include "PeripheralPins.h"
24 #include "fsl_clock_manager.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     if (obj->dac == (DACName)NC) {
31         error("DAC pin mapping failed");
32     }
33
34     SIM_HAL_EnableDacClock(SIM_BASE, 0);
35
36     DAC0->DAT[obj->dac].DATH = 0;
37     DAC0->DAT[obj->dac].DATL = 0;
38
39     DAC0->C1 = DAC_C1_DACBFMD(2);     // One-Time Scan Mode
40
41     DAC0->C0 = DAC_C0_DACEN_MASK      // Enable
42              | DAC_C0_DACSWTRG_MASK   // Software Trigger
43              | DAC_C0_DACRFS_MASK;    // VDDA selected
44
45     analogout_write_u16(obj, 0);
46 }
47
48 void analogout_free(dac_t *obj) {}
49
50 static inline void dac_write(dac_t *obj, int value) {
51     DAC0->DAT[obj->dac].DATL = (uint8_t)( value       & 0xFF);
52     DAC0->DAT[obj->dac].DATH = (uint8_t)((value >> 8) & 0xFF);
53 }
54
55 static inline int dac_read(dac_t *obj) {
56     return ((DAC0->DAT[obj->dac].DATH << 8) | DAC0->DAT[obj->dac].DATL);
57 }
58
59 void analogout_write(dac_t *obj, float value) {
60     if (value < 0.0f) {
61         dac_write(obj, 0);
62     } else if (value > 1.0f) {
63         dac_write(obj, RANGE_12BIT);
64     } else {
65         dac_write(obj, value * (float)RANGE_12BIT);
66     }
67 }
68
69 void analogout_write_u16(dac_t *obj, uint16_t value) {
70     dac_write(obj, value >> 4); // 12-bit
71 }
72
73 float analogout_read(dac_t *obj) {
74     uint32_t value = dac_read(obj);
75     return (float)value * (1.0f / (float)RANGE_12BIT);
76 }
77
78 uint16_t analogout_read_u16(dac_t *obj) {
79     uint32_t value = dac_read(obj); // 12-bit
80     return (value << 4) | ((value >> 8) & 0x003F);
81 }
82
83 #endif