Imported Upstream version 3.2.2
[debian/gnuradio] / usrp2 / firmware / lib / eeprom.c
1 /*
2  * Copyright 2007 Free Software Foundation, Inc.
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 3 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,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17
18 #include "i2c.h"
19 #include "mdelay.h"
20
21 static const int EEPROM_PAGESIZE = 16;
22
23 bool
24 eeprom_write (int i2c_addr, int eeprom_offset, const void *buf, int len)
25 {
26   unsigned char cmd[2];
27   const unsigned char *p = (unsigned char *) buf;
28   
29   // The simplest thing that could possibly work:
30   //   all writes are single byte writes.
31   //
32   // We could speed this up using the page write feature,
33   // but we write so infrequently, why bother...
34
35   while (len-- > 0){
36     cmd[0] = eeprom_offset++;
37     cmd[1] = *p++;
38     bool r = i2c_write (i2c_addr, cmd, sizeof (cmd));
39     mdelay (10);        // delay 10ms worst case write time
40     if (!r)
41       return false;
42   }
43   return true;
44 }
45
46 bool
47 eeprom_read (int i2c_addr, int eeprom_offset, void *buf, int len)
48 {
49   unsigned char *p = (unsigned char *) buf;
50
51   // We setup a random read by first doing a "zero byte write".
52   // Writes carry an address.  Reads use an implicit address.
53
54   unsigned char cmd[1];
55   cmd[0] = eeprom_offset;
56   if (!i2c_write (i2c_addr, cmd, sizeof (cmd)))
57     return false;
58
59   while (len > 0){
60     // int n = std::min (len, MAX_EP0_PKTSIZE);
61     int n = len;
62     if (!i2c_read (i2c_addr, p, n))
63       return false;
64     len -= n;
65     p += n;
66   }
67   return true;
68 }
69