Die Methode read()

Die read-Methode soll vier Parameter erhalten: Ein byte-Array, in das die gelesenen Daten kopiert werden, die Variablen startindex und length zur Angabe der Startposition und Länge für den Kopiervorgang in das Array und wordaddr, die Leseadresse. Damit ergibt sich der folgende Quelltext, wobei sich der eigentliche I2C-Zugriff auf drei Zeilen beschränkt:

44    /** Reads out the serial EEPROM to the destination byte array.
45     * @param data the byte array to fill with data
46     * @param startindex the index in data to start filling
47     * @param length number of bytes to read
48     * @param wordaddr the word address of the EEprom to start reading
49     * @return the number of bytes read (could be less than array
50     *         stop-startindex)
51     * @throws IOException on communication error (maybe data is partially
52     *         filled)
53     */
54    public int read(byte[] data,
55                    int startindex,
56                    int length,
57                    int wordaddr) throws IOException {
58      int read = 0,stopindex=startindex+length;
59      byte[] sendaddr = new byte[1];
60      int i = size-wordaddr+startindex;
61    
62      // check stopindex is inside param boundaries
63      if (stopindex > i) stopindex = i;
64    
65      // read bytes from EEPROM using I2C
66      while (startindex < stopindex) {
67        sendaddr[0] = (byte)(wordaddr&255);
68        int count = stopindex-startindex; // transfer length
69        int devaddr = address+((wordaddr>>7)&14); // read address
70        i = 256-(wordaddr&255);
71        if (count>i) count=i; // page boundry
72    
73        // I2C access
74        I2C i2c = new I2C(devaddr);
75        i2c.write(sendaddr, 0, 1);
76        i2c.read(data, startindex, startindex+count);
77    
78        // update variables
79        startindex += count;
80        wordaddr += count;
81        read += count;
82      }
83      // return number of bytes read
84      return read;
85    }
Listing 2: Auszug aus SerialEEPROM.java

Die Variable sendaddr wird auf die Leseadresse initialisiert und per I2C.write()-Kommando an das EEPROM gesendet. Danach wird die I2C.read()-Methode mit dem byte-Array als Parameter aufgerufen, um eine Anzahl Bytes aus dem EEPROM über I2C einzulesen. Diese Operationen werden in einer while-Schleife so lange durchgeführt, bis die gewünschte Anzahl Bytes übertragen wurde. Dies ist notwendig, wenn die Anzahl der zu lesenden Bytes die Seitengröße des seriellen EEPROMs übersteigt und daher die Leseadresse inkrementiert werden muss.