Skip to content

Commit 807833f

Browse files
committed
I/O: Make I2C & SPI accept ints for write()
This makes everyone's sketches a bit lighter, since it is not longer necessary to explicitly cast to byte or call byte(). Instead, we throw an exception if the value does not fit into the byte.
1 parent 377616f commit 807833f

File tree

2 files changed

+14
-6
lines changed

2 files changed

+14
-6
lines changed

java/libraries/io/src/processing/io/I2C.java

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -221,19 +221,23 @@ public void write(String out) {
221221

222222

223223
/**
224-
* Adds bytes to be written to the device
224+
* Adds a byte to be written to the device
225225
*
226226
* You must call beginTransmission() before calling this function.
227227
* The actual writing takes part when read() or endTransmission() is being
228228
* called.
229-
* @param out single byte to be written
229+
* @param out single byte to be written (0-255)
230230
* @see beginTransmission
231231
* @see read
232232
* @see endTransmission
233233
*/
234-
public void write(byte out) {
234+
public void write(int out) {
235+
if (out < 0 || 255 < out) {
236+
System.err.println("The write function can only operate on a single byte at a time. Call it with a value from 0 to 255.");
237+
throw new RuntimeException("Argument does not fit into a single byte");
238+
}
235239
byte[] tmp = new byte[1];
236-
tmp[0] = out;
240+
tmp[0] = (byte)out;
237241
write(tmp);
238242
}
239243
}

java/libraries/io/src/processing/io/SPI.java

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -171,9 +171,13 @@ public byte[] transfer(String out) {
171171
* @param out single byte to send
172172
* @return bytes read in (array is the same length as out)
173173
*/
174-
public byte[] transfer(byte out) {
174+
public byte[] transfer(int out) {
175+
if (out < 0 || 255 < out) {
176+
System.err.println("The transfer function can only operate on a single byte at a time. Call it with a value from 0 to 255.");
177+
throw new RuntimeException("Argument does not fit into a single byte");
178+
}
175179
byte[] tmp = new byte[1];
176-
tmp[0] = out;
180+
tmp[0] = (byte)out;
177181
return transfer(tmp);
178182
}
179183
}

0 commit comments

Comments
 (0)