Die Methode write()
Die Implementierung der write
-Methode gestaltet sich ähnlich zu jener von read
. Im Wesentlichen muss der I2C
-Lese- in einen Schreibzugriff umgeschrieben werden. Außerdem kommt nun der im Konstruktor berechnete Parameter maxburst
zum Einsatz, der die Anzahl der pro Seite beschreibbaren Bytes bestimmt.
83 | /** Writes a byte array to the serial EEPROM. |
84 | * @param data the byte array to write |
85 | * @param startindex the index in data to start transmitting |
86 | * @param length number of bytes to read |
87 | * @param wordaddr the word address of the EEprom to start writing |
88 | * @return the number of bytes written (could be less than array |
89 | * stop-startindex) |
90 | * @throws IOException on communication error (maybe data is partially |
91 | * transmitted) |
92 | */ |
93 | public int write(byte[] data, |
94 | int startindex, |
95 | int length, |
96 | int wordaddr) throws IOException { |
97 | int written=0,stopindex=startindex+length; |
98 | int i = size-wordaddr+startindex; |
99 | |
100 | // check stopindex is inside param boundaries |
101 | if (stopindex > i) stopindex = i; |
102 | while (startindex < stopindex) { |
103 | int count = stopindex-startindex; // transfer length |
104 | int devaddr = address+((wordaddr>>7)&14); // write address |
105 | i = 256-(wordaddr&255); |
106 | if (count > i) count=i; // page boundry |
107 | if (count > maxburst) count = maxburst; // maximum burst transfer |
108 | |
109 | // create write buffer |
110 | byte[] buf = new byte[count+1]; |
111 | buf[0] = (byte)(wordaddr&255); |
112 | for (i = 0; i < count; i++) // copy data to write buffer |
113 | buf[i+1] = data[i+startindex]; |
114 | |
115 | // I2C access |
116 | I2C i2c = new I2C(devaddr); |
117 | i2c.write(buf, 0, count+1); |
118 | |
119 | // update variables |
120 | startindex += count; |
121 | wordaddr += count; |
122 | written += count; |
123 | } |
124 | // return number of bytes written |
125 | return written; |
126 | } |
Listing 3: Auszug aus SerialEEPROM.java