adc.c
2.03 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
/*
* Copyright (C) 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_lpc11u34
* @{
*
* @file
* @brief Low-level ADC driver implementation
*
* @author Paul Rathgeb <paul.rathgeb@skynet.be>
* @author Hauke Petersen <hauke.petersen@fu-berlin.de>
*
* @}
*/
#include <stdint.h>
#include "cpu.h"
#include "mutex.h"
#include "periph/adc.h"
/**
* @brief Mutex to synchronize ADC access from different threads
*/
static mutex_t lock = MUTEX_INIT;
static inline uint32_t *pincfg_reg(adc_t line)
{
int offset = (line < 6) ? (11 + line) : (16 + line);
return ((uint32_t *)(LPC_IOCON) + offset);
}
static inline void prep(void)
{
mutex_lock(&lock);
LPC_SYSCON->PDRUNCFG &= ~(1 << 4);
LPC_SYSCON->SYSAHBCLKCTRL |= (1 << 13);
}
static inline void done(void)
{
LPC_SYSCON->SYSAHBCLKCTRL &= ~(1 << 13);
LPC_SYSCON->PDRUNCFG |= (1 << 4);
mutex_unlock(&lock);
}
int adc_init(adc_t line)
{
uint32_t *pincfg;
prep();
/* ADC frequency : 3MHz */
LPC_ADC->CR = (15 << 8);
/* configure the connected pin */
pincfg = pincfg_reg(line);
/* Put the pin in its ADC alternate function */
if (line < 5) {
*pincfg |= 2;
}
else {
*pincfg |= 1;
}
/* Configure ADMODE in analog input */
*pincfg &= ~(1 << 7);
done();
return 0;
}
int adc_sample(adc_t line, adc_res_t res)
{
int sample;
/* check if resolution is valid */
if (res < 0xff) {
return -1;
}
/* prepare the device */
prep();
/* set resolution */
LPC_ADC->CR &= ~(0x7 << 17);
LPC_ADC->CR |= res;
/* Start a conversion */
LPC_ADC->CR |= (1 << line) | (1 << 24);
/* Wait for the end of the conversion */
while (!(LPC_ADC->DR[line] & (1 << 31))) {}
/* Read and return result */
sample = (LPC_ADC->DR[line] >> 6);
done();
return sample;
}