From edf411e566eb8855e5c558923c1eb2b725cf960c Mon Sep 17 00:00:00 2001 From: gohai Date: Mon, 12 Oct 2015 16:56:01 +0200 Subject: [PATCH] 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. --- java/libraries/io/src/processing/io/I2C.java | 12 ++++++++---- java/libraries/io/src/processing/io/SPI.java | 8 ++++++-- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/java/libraries/io/src/processing/io/I2C.java b/java/libraries/io/src/processing/io/I2C.java index a981d1492..936ae4259 100644 --- a/java/libraries/io/src/processing/io/I2C.java +++ b/java/libraries/io/src/processing/io/I2C.java @@ -221,19 +221,23 @@ public class I2C { /** - * Adds bytes to be written to the device + * Adds a byte to be written to the device * * You must call beginTransmission() before calling this function. * The actual writing takes part when read() or endTransmission() is being * called. - * @param out single byte to be written + * @param out single byte to be written (0-255) * @see beginTransmission * @see read * @see endTransmission */ - public void write(byte out) { + public void write(int out) { + if (out < 0 || 255 < out) { + 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."); + throw new RuntimeException("Argument does not fit into a single byte"); + } byte[] tmp = new byte[1]; - tmp[0] = out; + tmp[0] = (byte)out; write(tmp); } } diff --git a/java/libraries/io/src/processing/io/SPI.java b/java/libraries/io/src/processing/io/SPI.java index f3f6f8cd7..4a4b08352 100644 --- a/java/libraries/io/src/processing/io/SPI.java +++ b/java/libraries/io/src/processing/io/SPI.java @@ -171,9 +171,13 @@ public class SPI { * @param out single byte to send * @return bytes read in (array is the same length as out) */ - public byte[] transfer(byte out) { + public byte[] transfer(int out) { + if (out < 0 || 255 < out) { + 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."); + throw new RuntimeException("Argument does not fit into a single byte"); + } byte[] tmp = new byte[1]; - tmp[0] = out; + tmp[0] = (byte)out; return transfer(tmp); } }