Hi the community,
I’m trying to use Java language with GrovePI. My development is based on the Software/Java8 directory.
All sensors from the GrovePi+ Starter kit are working in Java excepted the button sensor. I obtain always the same value even if I press the button.
I know the button sensor is working because I tested it with a Python program.
Here is a snippet which uses GrovePi API (Software/Java8).
public class Button {
public static void main(String[] args) throws InterruptedException, IOException {
GrovePi grovePi = new GrovePi4J();
GroveDigitalIn led = grovePi.getDigitalIn(6);
while (true) {
try {
System.out.println(led.get());
Thread.sleep(500);
} catch (IOException ex) {
}
}
}
}
Here is a snippet where I’ve isolated the problem (pure PI4J).
public class ButtonIssue {
private static final int dRead_cmd = 1;
private static final int unused = 0;
private static final int GROVEPI_ADDRESS = 4;
private static final byte PIN_MODE_COMMAND = 5;
private static final byte PIN_MODE_INPUT = 0;
private static final int PIN = 6;
private I2CDevice device;
public ButtonIssue() throws IOException, InterruptedException, UnsupportedBusNumberException {
I2CBus bus = I2CFactory.getInstance(I2CBus.BUS_1);
device = bus.getDevice(GROVEPI_ADDRESS);
writeI2c(PIN_MODE_COMMAND, PIN, PIN_MODE_INPUT, unused);
while (true) {
writeI2c(dRead_cmd, PIN, unused, unused);
System.out.println(device.read() & 0xff);
Thread.sleep(300);
}
}
public void writeI2c(int... bytes) throws IOException {
// Convert array: int[] to byte[]
final ByteBuffer byteBuffer = ByteBuffer.allocate(bytes.length);
for (int i = 0; i < bytes.length; i++) {
byteBuffer.put((byte) bytes[i]);
}
device.write(1, byteBuffer.array(), 0, byteBuffer.limit());
}
public static void main(String[] args) throws IOException, InterruptedException, UnsupportedBusNumberException {
new ButtonIssue();
}
}
I supposed that writeI2c with read command has a problem. Maybe, someone can test these snippets to confirm this issue?
Thx