I'm working on an i2c system using processing and the raspberry PI.
I built it in javascript with node.js on the raspberry pi first, and it's working great. But since processing is Java, I had to port it over and it's not functioning properly.
I can verify that i2c is working in processing as I'm able to write to registers and read the correct values back. But it seems when I attempt to write values over 127 things start to get confusing. When I send a value of 0x80 over i2c to a register, and then read the value back from the register I receive -128. I realise this is 2's complement but is the register getting the intended binary sequence 10000000 (0x80)?
Here is my code, I left out the setup methods for starting up the LIS3DH accelerometer as they are functioning fine. So this just shows one write/read cycle which results in -128 being received from the register:
import java.util.*;
import processing.core.*;
import processing.io.*;
I2C i2c;
private static final byte LIS3DH_DEFAULT_ADDRESS = (byte)0x18;
private static final byte LIS3DH_REG_TEMPCFG = (byte)0x1F;
boolean debug = true;
void setup() {
size(500, 500);
println("Available I2C interfaces:");
printArray(I2C.list());
i2c = new I2C(I2C.list()[0]);
background(0);
colorMode(RGB, 255, 255, 255, 255);
// enable adcs
if(debug) println("Write ", (byte) 0x80, "to LIS3DH_REG_TEMPCFG");
writeByte(i2c_address, LIS3DH_REG_TEMPCFG, (byte) 0x80);
if(debug) println("Read LIS3DH_REG_TEMPCFG", readByte(LIS3DH_DEFAULT_ADDRESS, LIS3DH_REG_TEMPCFG));
}
void draw() {
background(255,0,0);
}
byte readByte(byte deviceAddress, byte regAddress){
i2c.beginTransmission(deviceAddress);
i2c.write(regAddress);
return (i2c.read(1)[0]);
}
void writeByte(byte deviceAddress, byte regAddress, byte val){
i2c.beginTransmission(deviceAddress);
i2c.write(regAddress);
i2c.write(val);
i2c.endTransmission();
}
Bytes are signed in Java with a value range from -128 to 127, that's why you see -128. The bit pattern is actually exactly the same as (byte)0x80
. The register is getting the intended value.