Merge branch 'master' into mm-ms5611
[fw/altos] / src / attiny / ao_eeprom_tiny.c
1 /*
2  * Copyright © 2012 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; version 2 of the License.
7  *
8  * This program is distributed in the hope that it will be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License along
14  * with this program; if not, write to the Free Software Foundation, Inc.,
15  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
16  */
17
18 #include <ao.h>
19
20 static void
21 ao_eeprom_wait(void)
22 {
23         /* Wait for previous write to complete */
24         while (EECR & (1 << EEPE))
25                 ;
26 }
27
28 static uint8_t
29 ao_eeprom_read_byte(uint16_t addr)
30 {
31         uint8_t v;
32
33         ao_eeprom_wait();
34         EEAR = addr;
35         cli();
36         EECR |= (1 << EERE);
37         v = EEDR;
38         sei();
39         return v;
40 }
41
42 static void
43 ao_eeprom_write_byte(uint16_t addr, uint8_t v)
44 {
45         ao_eeprom_wait();
46         EECR = (0 << EEPM1) | (0 << EEPM0);
47         EEAR = addr;
48         EEDR = v;
49         cli();
50         EECR |= (1 << EEMPE);
51         EECR |= (1 << EEPE);
52         sei();
53 }
54
55 void
56 ao_eeprom_read(uint16_t addr, void *buf, uint16_t len)
57 {
58         uint8_t *b = buf;
59
60         while (len--)
61                 *b++ = ao_eeprom_read_byte(addr++);
62 }
63
64 void
65 ao_eeprom_write(uint16_t addr, void *buf, uint16_t len)
66 {
67         uint8_t *b = buf;
68
69         while (len--)
70                 ao_eeprom_write_byte(addr++, *b++);
71 }