Skip to content

Commit 5a61832

Browse files
committed
IO: Add a byte-variant of I2C.write and SPI.write
1 parent 2a8d62b commit 5a61832

File tree

2 files changed

+29
-6
lines changed

2 files changed

+29
-6
lines changed

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

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -211,18 +211,30 @@ public void write(String out) {
211211

212212
/**
213213
* Adds a byte to be written to the attached device
214-
* @param out single byte to be written (0-255)
214+
* @param out single byte to be written, e.g. numeric literal (0 to 255, or -128 to 127)
215215
* @see beginTransmission
216216
* @see read
217217
* @see endTransmission
218218
*/
219219
public void write(int out) {
220-
if (out < 0 || 255 < out) {
221-
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.");
220+
if (out < -128 || 255 < out) {
221+
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, or -128 to 127.");
222222
throw new RuntimeException("Argument does not fit into a single byte");
223223
}
224224
byte[] tmp = new byte[1];
225225
tmp[0] = (byte)out;
226226
write(tmp);
227227
}
228+
229+
/**
230+
* Adds a byte to be written to the attached device
231+
* @param out single byte to be written
232+
* @see beginTransmission
233+
* @see read
234+
* @see endTransmission
235+
*/
236+
public void write(byte out) {
237+
// cast to (unsigned) int
238+
write(out & 0xff);
239+
}
228240
}

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

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -182,16 +182,27 @@ public byte[] transfer(String out) {
182182

183183
/**
184184
* Transfers data over the SPI bus
185-
* @param out single byte to send
185+
* @param out single byte to send, e.g. numeric literal (0 to 255, or -128 to 127)
186186
* @return bytes read in (array is the same length as out)
187187
*/
188188
public byte[] transfer(int out) {
189-
if (out < 0 || 255 < out) {
190-
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.");
189+
if (out < -128 || 255 < out) {
190+
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, or -128 to 127.");
191191
throw new RuntimeException("Argument does not fit into a single byte");
192192
}
193193
byte[] tmp = new byte[1];
194194
tmp[0] = (byte)out;
195195
return transfer(tmp);
196196
}
197+
198+
199+
/**
200+
* Transfers data over the SPI bus
201+
* @param out single byte to send
202+
* @return bytes read in (array is the same length as out)
203+
*/
204+
public byte[] transfer(byte out) {
205+
// cast to (unsigned) int
206+
return transfer(out & 0xff);
207+
}
197208
}

0 commit comments

Comments
 (0)