altos/attiny: Add ADC implementation
[fw/altos] / src / attiny / ao_adc_attiny.c
1 /*
2  * Copyright © 2017 Keith Packard <keithp@keithp.com>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  */
14
15 #include <ao.h>
16
17 /*
18  * ATtiny ADC interface
19  */
20
21 uint16_t
22 ao_adc_read(uint8_t mux)
23 {
24         uint8_t low, high;
25
26         /* Set the mux */
27         ADMUX = mux;
28
29         /* Start conversion */
30         ADCSRA = ((1 << ADEN) |
31                   (1 << ADSC) |
32                   (0 << ADATE) |
33                   (0 << ADIF) |
34                   (0 << ADIE) |
35                   (0 << ADPS2) |
36                   (0 << ADPS1) |
37                   (0 << ADPS0));
38
39         /* Await conversion complete */
40         while ((ADCSRA & (1 << ADSC)) != 0)
41                 ;
42
43         /* Read low first */
44         low = ADCL;
45         high = ADCH;
46
47         return (((uint16_t) high) << 8) | low;
48 }